Add Fog to your Mod

(The "Coding Fog" tutorial originally posted on TWHL by Highlander formed the basis of this tutorial, but as originally posted it contained several errors that prevented it from working. The TWHL Admins kindly agreed to allow me to revise his tutorial. Needless to say, without his original tutorial as a starting point, I would never have gotten this code to work as it now does. Additional credit (as originally extended by Highlander) goes to Confused, Sysop, and Cause of Death. Furthermore, it is highly possible that some of this code originally came from Spirit of Half-Life, which also has an env_fog entity which functions similarly; however, I have been unable to locate a copy of the SoHL source to confirm or negate this suspicion... I decided to re-post this tutorial here because the BBCODE in use at TWHL did not allow me to present this information in the format I preferred...)

If you want to add fog to one or more maps in your Half-Life mod, this tutorial will show you how to do it.

This fog is a visual effect, controlled by a point entity (an env_fog) which you can insert into your level. It can be toggled on or off as required. It can be any colour you choose, and its apparent density is controlled by setting the start and end distances over which the effect is applied. Additionally, if you set a non-zero fade_on and/or fade_off time, it will appear or disappear gradually when triggered.

Sadly, the code also has its limitations:

So, if you want to go ahead and add support for this client-based point-entity fog to your mod, read on.

General Comments

The following tutorial is quite code-intensive, but it does work. All the code presented herein is pulled directly from my CVS repository; only the formatting has been changed for presentation purposes!

I have scattered additional //explanatory comments in green throughout the code. These form part of the tutorial, but are (obviously) not necessary to the compiler; however, I hope they will assist in explaining what is going on. (Or, I guess, make it quite clear that I do not know what is going on...)

Existing code (shown for reference and/or context) is in dark red. In many cases I have given approximate line numbers; these are only approximate, because my files contain other code changes not relevant to this tutorial... If the line number does not help you locate the piece of code I am changing, your [ins]Find...[/ins] tool is your friend!

New (added or modified) code is in bold blue.

Files to be edited are shown in bold red.

Server-side: The ClientFog Class

First we need to create support for the env_fog entity. This is done server-side (in the dlls directory, and the associated Project/Workspace.)

Open the dlls/effects.cpp file in your favourite editor and add the following code at the end of the file:

//=======================
// ClientFog
//=======================
extern int gmsgSetFog;

// This is the flag defined by the env_fog entity
#define SF_FOG_STARTOFF        0x0001
#define SF_FOG_FADE_GRANULARITY    20  // How often to recalc fog intensity (100ths of a second)
#define SF_FOG_OFF    0
#define SF_FOG_ON    32767

LINK_ENTITY_TO_CLASS( env_fog, CClientFog );

/*
// While a CClientFog constructor is not actually necessary for
// this code, you might find use for one down the track, 
// in which case it may look like this:
CClientFog *CClientFog::FogCreate( void )
{
    CClientFog *pFog = GetClassPtr( (CClientFog *)NULL );
    pFog->pev->classname = MAKE_STRING("env_fog");
    pFog->Spawn();
    return pFog;
}
/*

// Spawns our env_fog entity and sets the initial amount.
void CClientFog :: Spawn ( void )
{
    pev->solid            = SOLID_NOT;
    pev->movetype        = MOVETYPE_NONE;
    pev->effects        = 0;
    if ( pev->spawnflags & SF_FOG_STARTOFF ) {
        m_iAmount = SF_FOG_OFF;
        m_iTarget = SF_FOG_OFF;
    }
    else 
    {
        m_iAmount = SF_FOG_ON;
        m_iTarget = SF_FOG_ON;
    }
    SetThink( FogThink );
    pev->nextthink = gpGlobals->time + 0.01;
}

// Reads salient values from the env_fog entity
void CClientFog :: KeyValue( KeyValueData *pkvd )
{
    if (FStrEq(pkvd->szKeyName, "startdist"))
    {
        m_iStartDist = min(atoi(pkvd->szValue),(int)CVAR_GET_FLOAT("sv_zmax"));
        pkvd->fHandled = TRUE;
    }
    else if (FStrEq(pkvd->szKeyName, "enddist"))
    {
        m_iEndDist = min(atoi(pkvd->szValue),(int)CVAR_GET_FLOAT("sv_zmax"));
        pkvd->fHandled = TRUE;
    }
    else if (FStrEq(pkvd->szKeyName, "fadeon"))
    {
        m_iFadeOn = atoi(pkvd->szValue);
        pkvd->fHandled = TRUE;
    }
    else if (FStrEq(pkvd->szKeyName, "fadeoff"))
    {
        m_iFadeOff = atoi(pkvd->szValue);
        pkvd->fHandled = TRUE;
    }
    else
        CBaseEntity::KeyValue( pkvd );
}

// Essentially turns our fog effect on/off by sending a message to the client.
// Anything which changes m_active should force a FogThink.
void CClientFog :: FogThink ( void )
{
    float fStepSize;
    float fStepTime = SF_FOG_FADE_GRANULARITY/100.0;

    if ( m_iTarget > m_iAmount ) {
        if (m_iFadeOn == 0)
            m_iAmount = m_iTarget;
        else
        {
            fStepSize = max( 1.0,32768.0 / (m_iFadeOn / fStepTime) );
            m_iAmount += (int)fStepSize;
            if (m_iAmount > m_iTarget)
                m_iAmount = m_iTarget;
        }
    }
    else if ( m_iTarget < m_iAmount ) {
        if (m_iFadeOff == 0)
            m_iAmount = m_iTarget;
        else 
        {
            fStepSize = max( 1.0,32768.0 / (m_iFadeOff / fStepTime) );
            m_iAmount -= (int)fStepSize;
            if (m_iAmount < m_iTarget)
                m_iAmount = m_iTarget;
        }
    }

    MESSAGE_BEGIN( MSG_ALL, gmsgSetFog, NULL );
    WRITE_SHORT ( pev->rendercolor.x );
    WRITE_SHORT ( pev->rendercolor.y );
    WRITE_SHORT ( pev->rendercolor.z );
    WRITE_SHORT ( m_iStartDist );
    WRITE_SHORT ( m_iEndDist );
    WRITE_SHORT ( m_iAmount );
    MESSAGE_END();

    if ( m_iTarget != m_iAmount )
        pev->nextthink = gpGlobals->time + fStepTime;
}

// Called when the entity is triggered.
void CClientFog::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
    int m_active = (m_iTarget == SF_FOG_ON );
    if ( ShouldToggle( useType, m_active ) )
    {
        if (m_iTarget == SF_FOG_ON)
            m_iTarget = SF_FOG_OFF;
        else
            m_iTarget = SF_FOG_ON;
    }
    SetThink( FogThink );
    pev->nextthink = gpGlobals->time + 0.01;
}

// These macros set up the save/restore code for the CClientFog object
TYPEDESCRIPTION CClientFog::m_SaveData[] =
{
    DEFINE_FIELD( CClientFog, m_iStartDist, FIELD_INTEGER ),
    DEFINE_FIELD( CClientFog, m_iEndDist, FIELD_INTEGER ),
    DEFINE_FIELD( CClientFog, m_iFadeOn, FIELD_INTEGER ),
    DEFINE_FIELD( CClientFog, m_iFadeOff, FIELD_INTEGER ),
    DEFINE_FIELD( CClientFog, m_iAmount, FIELD_INTEGER ),
    DEFINE_FIELD( CClientFog, m_iTarget, FIELD_INTEGER ),
};

IMPLEMENT_SAVERESTORE(CClientFog,CBaseEntity);

The declarations for the above code need to be added to effects.h (you'll note some of the classes defined in effects.cpp have their declarations in the .cpp file, but we need to make our fog visible to other files!) Place the following code at the bottom of the dlls/effects.h file, just above the final #endif line:

//=======================
// ClientFog
//=======================
class CClientFog : public CBaseEntity
{
    public:
/*
// As stated above, this constructor is not needed; add if required!
        static CClientFog *FogCreate( void );
*/
        void Spawn( void );
        void KeyValue( KeyValueData *pkvd );
        void EXPORT FogThink( void );
        void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
        int m_iStartDist;
        int m_iEndDist;
        int m_iFadeOn;
        int m_iFadeOff;
        int m_iAmount;
        int m_iTarget;
        virtual int Save( CSave &save );
        virtual int Restore( CRestore &restore );
        static TYPEDESCRIPTION m_SaveData[];
};

This gives us the code we need to initialise our fog to the values set in the env_fog entity. However there are still a couple of minor problems to tackle...

Server-side: Fog Status Messages

Whenever a new player joins the server, it needs to send a fog status message to the client. There are three possible situations in which the client needs to be updated, and we need to cover them all:

Our first problem is that we cannot directly detect a change of map. Let's change that by hooking into code which is called at every level change.

First we shall add our variable declaration to the bottom of dlls/globals.cpp:

DLL_GLOBAL int          gLevelLoaded;

Now we set it at the appropriate moment; let's edit dlls/world.cpp:

Somewhere around line #43, you will find:

extern DLL_GLOBAL    int            gDisplayTitle;

Add the following line below that:

extern DLL_GLOBAL    int            gLevelLoaded;

Now, down around line #479 you should find the CWorld :: Precache function, to which you need to add the following line:

void CWorld :: Precache( void )
{
    g_pLastSpawn = NULL;
    gLevelLoaded = TRUE;    // Handles "level loaded" case

With that out of the way, let's handle the player spawning cases. First we'll declare our variable in dlls/player.h (somewhere around line #90):

class CBasePlayer : public CBaseMonster
{
public:
    BOOL                m_bRespawned; // True when fog update msg needs to be sent

Now we can modify our player code to pull all of this together. Be brave; there are many small changes scattered through this next file. Open dlls/player.cpp -- and here we go!

First we need to find the following line (at around line #45):

extern DLL_GLOBAL int        g_iSkillLevel, gDisplayTitle;

and change it to look like this:

extern DLL_GLOBAL int        g_iSkillLevel, gDisplayTitle, gLevelLoaded;

A little further down you will find a whole list of int initialisation lines; look for:

int gmsgTeamNames = 0;

and add the following on the next line:

int gmsgSetFog = 0;

Just below that you will find LinkUserMessages function; add gmsgSetFog somewhere near the top, like so:

void LinkUserMessages( void )
{
    // Already taken care of?
    if ( gmsgSelAmmo )
    {
        return;
    }
    // This basically registers "SetFog" as a known message to be sent to the server
    gmsgSetFog = REG_USER_MSG("SetFog", -1 );
    gmsgSelAmmo = REG_USER_MSG("SelAmmo", sizeof(SelAmmo));

Now you want to jump down to the CBasePlayer::PlayerDeathThink function; this will be somewhere around line #1150 to #1200. Right at the bottom of the function, just before the respawn call, you want to add the following:

    //ALERT(at_console, "Respawn\n");
    m_bRespawned = TRUE;    // Handles "player respawned" case
    respawn(pev, !(m_afPhysicsFlags & PFLAG_OBSERVER) );// don't copy a corpse if we're in deathcam.

Down around line #2700 to #2800 is CBasePlayer::Spawn; add the following line right near the bottom of the function:

    m_flNextChatTime = gpGlobals->time;
    m_bRespawned = TRUE;    // Handles "new player" case
    g_pGameRules->PlayerSpawn( this );

We're almost done. Now that we have detected all of the cases for which we need to send our fog status message, all we need to do is actually process that information. The best place to do that is in the CBasePlayer::UpdateClientData function, down around line #3800. You can probably insert the following snippet of code at any convenient point in this function; I slotted mine between the if ( m_iFOV != m_iClientFOV ) and the if (gDisplayTitle):


    if ( m_iFOV != m_iClientFOV )
    {
    :
    :
    }
    
    if ( m_bRespawned || gLevelLoaded )
    {
        CBaseEntity *pEntity = NULL;
        pEntity = UTIL_FindEntityByClassname( pEntity, "env_fog" );
        if ( pEntity )
        {
            CClientFog *pFog = (CClientFog *)pEntity;
            // CClientFog::FogThink handles the actual message sending, so let's force a think
            pFog->pev->nextthink = gpGlobals->time + 0.01;
        }
        m_bRespawned = gLevelLoaded = FALSE;
    }

    // HACKHACK -- send the message to display the game title
    if (gDisplayTitle)
    {
    :
    :
    }

That's it for the server-side code. Before we leave the dlls directory, we can probably compile the server dll -- or leave it till we're fully finished; whatever works best for you!

Client-side: Incoming Messages

At this point, the server has initialised the fog, detected everything it needs to detect, and sent a fog status message hurtling through the void (sorry, bad pun!) towards the client(s). Now we just need to convince the client to catch them! To do that, we'll leave the safety of dlls and move over to the cl_dll directory (and associated Project/Workspace!)

First we'll ask the HUD to catch the incoming message. Open cl_dll/hud.cpp and look for __MsgFunc_GameMode at around line #130. Add the following:

int __MsgFunc_GameMode(const char *pszName, int iSize, void *pbuf )
{
    return gHUD.MsgFunc_GameMode( pszName, iSize, pbuf );
}

int __MsgFunc_SetFog(const char *pszName, int iSize, void *pbuf )
{
    return gHUD.MsgFunc_SetFog( pszName, iSize, pbuf );
}

Further down, around line #300, you will find a whole list of HOOK_MESSAGE macros in no particular order. Add:

    HOOK_MESSAGE( SetFog );

to the list. (I added it between HOOK_MESSAGE(TeamInfo); and HOOK_MESSAGE(Spectator);, but I don't suppose its placement is critical. It might almost be nice if the list was sorted alphabetically, but that's up to you -- and more to the point, it may break everything, so let's leave that for another time! :-))

To follow through on our changes to the .cpp file, open the cl_dll/hud.h file; look for

    int  _cdecl MsgFunc_Concuss( const char *pszName, int iSize, void *pbuf );

somewhere near line #640, and after it add:

    int  _cdecl MsgFunc_SetFog(const char *pszName, int iSize, void *pbuf );

Now that we've caught the message from the server, let's process it. To do this we need cl_dll/hud_msg.cpp. Before we do anything else, let's declare the variables we're going to use. After the initial #includes and #defines, add the following:

float g_fFogColor[3];
float g_fStartDist;
float g_fEndDist;
int   g_iFogLevel;

A couple of lines down from there, we shall reset our fog distance values when we reset the HUD:

int CHud :: MsgFunc_ResetHUD(const char *pszName, int iSize, void *pbuf )
{
    ASSERT( iSize == 0 );
    g_fStartDist = 0.0;
    g_fEndDist = 0.0;
    g_iFogLevel = 0;

Right at the bottom of the file, we'll add our SetFog function which actually interprets the received message:

int CHud :: MsgFunc_SetFog( const char *pszName, int iSize, void *pbuf )
{
    BEGIN_READ( pbuf, iSize );
    g_fFogColor[0] = (float)READ_SHORT(); // R
    g_fFogColor[1] = (float)READ_SHORT(); // G
    g_fFogColor[2] = (float)READ_SHORT(); // B
    g_fStartDist = (float)READ_SHORT();
    g_fEndDist = (float)READ_SHORT();
    g_iFogLevel = READ_SHORT();

    float fPercent = g_iFogLevel / 32767.0;
    float sv_zmax = CVAR_GET_FLOAT("sv_zmax") * 1.1; 
    float fStart = sv_zmax - fPercent*(sv_zmax - g_fStartDist);
    float fEnd = sv_zmax - fPercent*(sv_zmax - g_fEndDist);
    g_fStartDist = fStart;
    g_fEndDist = fEnd;

    return 1;
}

Where The Magic Happens

We're on the home straight now. We've done everything except actually display the fog. (Well, almost everything, but I'll get to that!) The file we want to edit now is tri.cpp. This is the file which confused me the most when I was originally trying the get the code to work -- but it was only once I started looking further afield that I solved the puzzle. Anyway, without further ado, let's open cl_dll/tri.cpp. Just after the initial #includes and #defines, we'll access the variables we set up previously:

extern float g_fFogColor[3];
extern float g_fStartDist;
extern float g_fEndDist;
extern int g_iFogLevel;

After the extern "C" { ... } declarations, we'll add the heart of the whole thing:

void RenderFog ( void )
{
    static float fColorBlack[3] = {0,0,0};
    if (g_iFogLevel > 0)
        gEngfuncs.pTriAPI->Fog ( g_fFogColor, g_fStartDist, g_fEndDist, 1 );
    else
        gEngfuncs.pTriAPI->Fog ( fColorBlack, 0, 0, 0 );
}

And now for the thing that really confused me. At the bottom of the file we have HUD_DrawNormalTriangles and HUD_DrawTransparentTriangles. Extensive testing led me to the inescapable conclusion that each apparently does the other's job: HUD_DrawNormalTriangles handles "transparent" faces and HUD_DrawTransparentTriangles handles -- well, everything. Of course, all you really need to know is to change the latter function as follows:

/*
=================
HUD_DrawTransparentTriangles

Despite the name, it appears that this actually controls 
non-transparent entities and world brushes
=================
*/
void DLLEXPORT HUD_DrawTransparentTriangles( void )
{
    RenderFog();
#if defined( TEST_IT )
//    Draw_Triangles();
#endif
}

That's it! Compile that, and if all goes according to plan you'll have working fog.

(Well, there's still that "almost" to take care of. I'll get there in a second. Just as an aside, though, while we're here: see that #if defined( TEST_IT ) ... #endif? While playing with this file I compiled in the Draw_Triangles() code. The whole thing (ie, Half-Life) fell over while trying to start a map, so I hastily got rid of it again. As soon as I'm done with this tutorial I shall probably clean all that code out to make the file a little neater...)

The Final Step

So what remains to be done? Adding the env_fog entity to your map, of course. If you use Valve Hammer Editor, you can add the following to whichever FGD file you are mapping with:

@PointClass base(Targetname) size(-16 -16 -16, 16 16 16) = env_fog : "Client Fog"
[
    startdist(integer) : "Start Distance" : 1
    enddist(integer) : "End Distance" : 1500
    rendercolor(color255) : "Fog Color (R G B)" : "0 0 0"
    fadeon(integer) : "Time to Fade On (sec)" : 0
    fadeoff(integer) : "Time to Fade Off (sec)" : 0
    spawnflags(Flags) = 
    [
        1 : "Start Off"     : 0
    ]
]

Since VHE does no sorting of its own, it probably makes sense to add this between env_explosion and env_global -- ie, alphabetically! You will now be able to add env_fogs to your maps -- although be warned, I'm not sure what will happen if you have more than one per level. I'd imagine if you had several with different colours, you could trigger them off and on to change the colour of your fog -- but I have not tested that!

Unfortunately I am not familiar with any other editors used to make HL maps. No doubt they have a way of adding new entities, similar to the FGD file in Hammer -- but you'll need to figure that out for yourself! Sorry...

Wrap Up

What I have done is produce a small (and exceedingly ugly) test map for you to check out. I guess you could play with that to add multiple env_fog entities, or whatever else you wanted to try. In the map you will find several transparent objects ("texture"-rendered and "solid"-rendered) because that was what I was having the most difficulty with initially. You will also find a large target which, if shot, will toggle the fog on and off.

It is quite a bit of coding to get to this point, but I hope my directions have been clear enough that we all arrived here with code which compiles and, y'know, actually works! If you have any problems let me know and I'll see if I can help out.

Have fun!