Printing to Multiple Locations

From Valve Developer Community
Jump to: navigation, search

Overview

When modding, the situation can frequently occur when you wish to display some text in the chat area, and also have it show in the console. Previously, two calls to UTIL_ClientPrint or UTIL_ClientPrintAll would be required, as shown:

UTIL_ClientPrintAll( HUD_PRINTTALK, "Message text" );
UTIL_ClientPrintAll( HUD_PRINTCONSOLE, "Message text" );

While this works, sending the same text from the server to the client twice is a highly inefficient solution. This tutorial will show you how to add two new text 'destinations,' HUD_PRINTTALKCONSOLE, which will cause the text to be displayed in both the talk area and on the console, and HUD_PRINTCENTERCONSOLE, which will display text in the centre of the screen, and log it in the console. Both of these will result in the text only being sent across the network once.

Procedure

First, open shareddefs.h and find where the current text destinations are defined (around line 103):

#define HUD_PRINTNOTIFY		1
#define HUD_PRINTCONSOLE	2
#define HUD_PRINTTALK		3
#define HUD_PRINTCENTER		4

Under these, add your own:

#define HUD_PRINTTALKCONSOLE 5
#define HUD_PRINTCENTERCONSOLE 6

Next up is the MsgFunc_TextMsg function of hl2mp_hud_chat.cpp (ep1) or hud_basechat.cpp (ob): To briefly summarise, this reads the message and its destination, and then does a switch, based upon the destination (msg_dest), which decides how to display it. We are going to cause it to loop over this switch statement twice if msg_dest has one of the "two destination" values.

Just before the loop, add two booleans, and the following checks (shown in bold):

	if ( !cl_showtextmsg.GetInt() )
		return;

	bool looping = true, runAgain = false;
	if ( msg_dest == HUD_PRINTTALKCONSOLE )
	{
		msg_dest = HUD_PRINTTALK;
		runAgain = true;
	}
	else if ( msg_dest == HUD_PRINTCENTERCONSOLE )
	{
		msg_dest = HUD_PRINTCENTER;
		runAgain = true;
	}

	int len;
	switch ( msg_dest )
	{

Now, surround the entire switch block in a while loop, and add a little bit on the end: (for neatness, I have increased the switch block's indentation)

	while ( looping )
	{
		int len;
		switch ( msg_dest )
		{
		case HUD_PRINTCENTER:
			blah blah
			break;

		case HUD_PRINTNOTIFY:
			blah blah
			break;

		case HUD_PRINTTALK:
			blah blah
			break;

		case HUD_PRINTCONSOLE:
			blah blah
			break;
		}

		if ( runAgain )
		{
			runAgain = false;
			msg_dest = HUD_PRINTCONSOLE;
		}
		else
			looping = false;
	}

Conclusion

That should do it. Now, to print a text block to both the chat area and the console, for all players, you need only:

UTIL_ClientPrintAll( HUD_PRINTTALKCONSOLE, "Message text");

Its the same procedure for the centre of the screen and the console, only using HUD_PRINTCENTERCONSOLE.