Adding an Ocean Effect

Adding an ocean or water surface to a Torque X game is not as complicated as it might initially sound. The solution I took was to add a new shader effect and supporting texture files to the game project. Then, create a new material class that associates a material definition with the ocean shader effect. Next add another class that creates a simple 3D plane and uses the new ocean custom material. All that remains is to instantiate that new water plane and then add it to the game scene.

The Custom Material

The WaterMaterial class is a custom material that descends from the GenericMaterial class. Its constructor points to the Ocean shader effect file and sets the shader values in the _LoadParameters() method. And there are a lot of parameters that can be set to customize the look of the water surface. This material definition also passes instances of a cubemap for the reflective water surface and the normal map for the wave definition into the shader.

The Water Object

The WaterPlane object is a basic TorqueObject descendant that creates a renderable T3DBox and places it within the game scene. It also associates the WaterMaterial with this object in order to render the water effect. It exposes a dozen or so properties that let you easily set the values on the water shader, such as width, height, wave amplitude, flow speed, etc.

Using the Water Plane

You can use the water plane like any other TorqueObject, by creating an instance of it, setting some properties, and then registering it with the TorqueObjectDatabase.

 The Source Code

[Use this link to download the source code. ]

The package contains:

  • WaterMaterial.cs – the custom water material effect wrapper class
  • WaterPlane.cs – the class which creates the physics 3D plane
  • Ocean.fx – the shader used to render the ocean effect
  • cubeMap.dds – the environment cube map for the water reflection
  • waves2.dds – the normal map for the waves

To use the water effects in your Torque X game, add the following code to your game’s BeginRun() method.

WaterPlane water = new WaterPlane();
water.WaterLength = 1024;
water.WaterWidth = 1024;
water.NormalMapFilename = @"data\images\waves2";
water.EnvironmentMapFilename = @"data\images\cubeMap";
T3DSceneComponent componentScene = new T3DSceneComponent();
componentScene.Position = new Vector3(512, 512, 255);
water.Components.AddComponent(componentScene);
TorqueObjectDatabase.Instance.Register(water);

The results are pretty basic, but good enough for many games. The biggest issue is that without change to the engine code, the ocean will vanish when the center of the ocean is not in the viewport. To fix this, the Torque X rendering engine will need to be updated.