racer home

Onyx Tutorial - Shared Variables

 

Home A simple start.


Dolphinity Organiser - free planning, project management and organizing software for all your action lists

Introduction

Often you will want to share certain state across all scripts. For this purpose, shared variables exist that can be created. They can optionally be synchronized over the network to get network-wide global variables (start from Racer v0.9.0RC9).

This is useful to create simple state replication. For example, suppose you have a flashing light that you've implemented in a script, which turns on or off based on a certain criterium. The game server (multiplayer server) can be authorative over this state and the non-server client machines just listen to the state which determines whether the light flashes or not. This way, all PC's will have the same visuals.

This may sound a bit complex, so let's walk through some implementation notes.

Use cases

Shared variables are assumed to not vary too much. They may change as much as every frame, but the infrastructure was not designed for this. Slowly changing states, like high-level game states or scores are candidates to be implemented using shared variables.

Defining shared variables

Shared variables must be defined at some point in the script code, before they can be read (this requirement may be loosened in the future to automatically create shared variables as they are passed around the network).

Here is an example of how to create a shared floating point named value:

void TrackState()
{
  int t;
  while(1)
  {
     yield;
     t=GetServerTime();
     // Toggle state every half a second
     if((t%1000)<500)
       SetSharedFloat("lights_state",0);
     else
       SetSharedFloat("lights_state",1);
   }
}

void DetectState()
// Clients just read the variable
{
  float f;

  while(1)
  {
     yield;
     f=GetSharedFloat("lights_state");
     echo(f);
  }
}

void main()
{
  DefineSharedFloatNetwork("lights_state");
  // Only the multiplayer (game) server should 'set' the shared variable - clients just receive the value
  if(IsMultiplayerServer())
    TrackState();
  else
    DetectState();
}

Notice that by default, the value of the shared floating point variable is 0.

Implementation notes

The contents of shared variables are checked for change at every frame render. This means you can set the value multiple times per frame, but only the last change will be detected.

The changed contents will be sent across the network to other connected PC's. When nothing changes, nothing is sent. This means continually changing variables take more bandwidth than slowly changing variables (those change only now & then).

 


Dolphinity Organiser - free planning, project management and organizing software for all your action lists

(last updated January 13, 2014 )