From Valve Developer Community
Prediction is the notion of the client predicting the effects of the local player's actions without waiting for the server to confirm them. An entity's predicted state is tested against server commands as they arrive until either a match or a mis-match is detected.
In the vast majority of cases the client's prediction is confirmed by the server and it continues happily as if there was no latency. If there is a mis-match, which is rare if the prediction code is written correctly, then the client goes back and re-simulates all of the commands it ran with bad data. Depending on the severity of the error this can cause a noticeable hitch in the player's position and state, and possibly the state of the world too.
To predict an entity:
- It should be manipulable by the local player. Otherwise, what is the point in predicting it?
- The functions that are to be predicted must exist and be identical on both the client and server. This is achieved by making them shared code.
- The entity must make the call
SetPredictionEligible(true), preferably in its constructor.
- It must have a
bool ShouldPredict()function on the client. Check if the local player is holding this entity and so forth here.Note:Weapons must also implement
bool IsPredicted(), again on the client. It should return
trueall the time.
- Any variables that must be synchronised between the client and server must be both networked and present in the entity's prediction table.
All client-side variables modified by predicted player input must be added to a prediction table. There are three behaviours you can choose between:
- This is a networked variable. The client's predicted value will be tested against received server values, and if the two go out of synch a prediction error will be created.
- This is a predicted value that can go out of synch without generating a prediction error. It may or may not be networked.
- This isn't predicted or networked at all, but is still registered so that it can inspected with
cl_pdump.Note:This type of variable won't be saved/restored when the prediction system winds time back to test against a new server command. If a predicted function increments it, the increment will be applied over and over again on the client as each new command is tested.
These behaviours are implemented with the
DEFINE_PRED_FIELD_TOL() macros. The latter allows you to specify a tolerance within which an int or float is allowed to differ without generating prediction errors. This is mainly intended for use when a value has been rounded prior to transmission: floats are often trimmed to 1ms resolution, for instance (the #define
TD_MSECTOLERANCE exists especially for this situation - otherwise, you should pass a numeric value).
Be cautious when extrapolating from a rounded figure in these circumstances. Small differences in the transmitted value can lead to large changes in the results of your calculations!
#ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( CBaseCombatWeapon ) DEFINE_PRED_FIELD( m_nNextThinkTick, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_hOwner, FIELD_EHANDLE, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD_TOL( m_flNextPrimaryAttack, FIELD_FLOAT, FTYPEDESC_INSENDTABLE, TD_MSECTOLERANCE ), END_PREDICTION_DATA() #endif
Predicting entity creation
The standard prediction system can maintain an existing entity's state, but it does not help with creating new entities.
CreatePredictedEntityByName() does. It creates a new entity on the client and swaps it for the real one when it arrives from the server. Needless to say, you should call it from shared code.
CBaseEntity::CreatePredictedEntityByName( char* classname, char* class_file, int line, bool persist = false )
modulein the actual code, and its line number (
persistcauses the entity to be tested during reprediction.
If the predicted entity contains data that was not sent to the server, you should copy it into the real entity in
Tools and tricks
prediction->IsFirstTimePredicted() ensures that code is only executed when the client first predicts an action, and not when it checks against subsequent server updates. You must
#include "prediction.h" to access it.
Use this function for random numbers. The seed it uses is based on the usercmd number, making the result identical on client and server.
Suppressing network data
Non-critical events like weapon effects can be done entirely on the client. Suppressing that data is a good idea as it results in reduced bandwidth usage.
IPredictionSystem::SuppressHostEvents() is meant for this. When it is called, all network data to the given player is halted. Sending NULL again will turn transmission back on. For example:
if ( pPlayer->IsPredictingWeapons() ) IPredictionSystem::SuppressHostEvents( pPlayer ); pWeapon->CreateEffects(); IPredictionSystem::SuppressHostEvents( NULL );
Note that after doing the above you will need to write code somewhere else that makes the suppressed player's client generate the effects itself.
Here is a simple weapon that prints prediction information to the console. Use its rapid secondary fire with net_fakelag 200 (or above) to see how the engine handles multiple predicted shots.
If you add functionality to weapons and forget to follow the steps above, then an entity may jerk around or animate strangely. You can use
cl_pdump to debug this. Changing
cl_pred_optimize can also help sometimes.
Now let's say you see a variable that turns red in the
cl_pdump panel from time to time. Now you know that somehow the client is producing a different value for this variable than the server is. This can usually be traced down to one of the following problems:
- The client is not running some code that the server is running. This would be the case if you had an
#ifdef GAME_DLLor an
#ifndef CLIENT_DLLaround a piece of code that could affect the value of the variable that's turning red.
- Another variable that can wind up affecting the value of the red variable is not being transmitted via the data table. In this case, the client's value for that variable would always be wrong (since the server never transmitted it).
- It's also possible that you just forgot to add in the appropriate tolerance using the
DEFINE_PRED_FIELD_TOLmacro. For example, if you're transmitting a floating point variable with a value range of 0.0 - 255.0, and you only give it 4 bits of precision, then you're going to need a tolerance of about 17.0, or else the prediction system will think the variable's value is wrong when it is actually just different because the variable was compressed into 4 bits before sending it to the client.
Tracking down prediction problems is usually a matter of walking through any code that can affect the values that are turning red, and noticing which other variables affect their values. It can be tedious at first, but once you get the hang of it, you can track down prediction problems quickly.