My favorites | English | Sign in

O3D Best Practices and Tips

Introduction

This chapter presents a few useful tips for writing O3D applications.

Always initialize the perspective matrix from the width and height of the client area, not from magic numbers.

This method ensures that if the client area changes size, the perspective matrix changes accordingly.

If you are using a render target, make constants for the width and height of the render target such that it's clear how any perspective matrix used by the render target is set.

Don't use the DOM values clientWidth and clientHeight to initialize the perspective matrix; these values will give you the wrong answer in full-screen mode. Use client.width and client.height, which are correct in both full-screen and plug-in modes.

If your client area is resizeable, set the perspective matrix every frame in your render callback.

If you do not reset the perspective matrix for every frame, the browser will resize the client area with the wrong aspect ratio when the user resizes the window.

Always clear a render callback.

If you do not clear the callback in window.unload, the browser will attempt to render during cleanup after the JavaScript has been freed, which causes JavaScript errors in the callback.

Minimize the number of effects used in your application.

Since it's expensive to create and render effects, create objects that share effects when possible. For example, the Picking example creates seven different objects that all use the same effect.

Reuse geometry when possible.

It is much less expensive to create one cube and instance it 256 times than to create 256 identical cubes.

Adding transforms to the transform graph can simplify some tasks.

Often, adding a separate transform above a shape can help to isolate behavior to that shape.

Use the o3djs.debug library to debug your O3D application.

This library provides a debug helper object that can add axes, spheres, and boxes to your transforms as well as draw lines between two points in 3D space.

Use the camera utilities, o3djs.camera to create a simple camera that views your scene.

This library contains functions that provide an easy way to get your content in front of the camera.

A shader either handles textures or it doesn't. A trick that enables you to write only one shader, which handles textures and simulates color shading, is to create an error texture (with Client.setErrorTexture()) that is white.

With this solution, textures are applied to the objects as specified. The texture, when supplied, is multiplied by the COLOR value, as shown in the code sample below. If no texture is supplied, the white error texture is multiplied by the COLOR value, which produces an acceptable effect.

float4 color;
sampler texSampler;

float4 pixelShaderFunction(PixelShaderInput input): COLOR {
  float4 diffuseColor = tex2D(texSampler, input.texcoord) * color;
  return diffuseColor;
}