gizmo3d programmers manual · c++ toolkit. it is similar to other scene graph engines such as...

106
Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 1(106) Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com , email mailto:[email protected] Programmers Manual for the Gizmo3D Toolkit

Upload: others

Post on 30-Sep-2020

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 1(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Programmers Manual for the Gizmo3D Toolkit

Page 2: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 2(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Contents

1 GENERAL....................................................................................................................................................4 1.1 History.....................................................................................................................................................4

2 GIZMO3D API OVERVIEW.......................................................................................................................5 2.1 Code structure & libraries .......................................................................................................................6

2.1.1 GizmoBase Library (1) ................................................................................................................7 2.1.2 System Library (2) .......................................................................................................................8 2.1.3 Scene Graph Library (3) ..............................................................................................................8 2.1.4 Image Format Library (4) ..........................................................................................................10 2.1.5 Graph Format Library (5) (Database (DB)) ...............................................................................10

3 GIZMO3D API DETAILS .........................................................................................................................11 3.1 Graph.....................................................................................................................................................11

3.1.1 Rendering...................................................................................................................................11 3.1.1.1 The device Context (gzDeviceContext) ...............................................................................12 3.1.1.2 The window Context (gzWindowContext)...........................................................................12 3.1.1.3 The rendering context (gzRenderContext) ...........................................................................12 3.1.1.4 The Graphics Context (gzContext).......................................................................................13

3.1.2 Coordinate systems ....................................................................................................................14 3.1.3 The camera.................................................................................................................................18

3.1.3.1 Using the camera ..................................................................................................................19 3.1.4 What is a Scene Graph? .............................................................................................................23 3.1.5 The basic node ...........................................................................................................................25

3.1.5.1 Node cloning ........................................................................................................................26 3.1.5.2 Node RTTI ...........................................................................................................................26

3.1.6 Geometry node...........................................................................................................................28 3.1.6.1 Description of primitives......................................................................................................31 3.1.6.2 Built-in geometry utilities ....................................................................................................33 3.1.6.3 Parametric Geometry............................................................................................................36 3.1.6.4 Geometry features ................................................................................................................36

3.1.7 The group node ..........................................................................................................................37 3.1.7.1 Built in group node types .....................................................................................................38

3.1.8 States..........................................................................................................................................55 3.1.8.1 Textures................................................................................................................................56 3.1.8.2 Materials...............................................................................................................................59

3.1.9 Shaders.......................................................................................................................................60 3.1.9.1 Pre defined shaders...............................................................................................................61

3.1.10 Skinning and vertex weights ......................................................................................................61 3.1.11 Custom nodes.............................................................................................................................61 3.1.12 Boundary update ........................................................................................................................62 3.1.13 Added node behaviors................................................................................................................62 3.1.14 Serializing ..................................................................................................................................62 3.1.15 Intersection.................................................................................................................................62 3.1.16 IRMA.........................................................................................................................................63 3.1.17 Debugging the scene ..................................................................................................................66 3.1.18 Traversals...................................................................................................................................68

3.2 System...................................................................................................................................................71 3.2.1 Application.................................................................................................................................71 3.2.2 Windows ....................................................................................................................................71 3.2.3 gzImageRender ..........................................................................................................................72 3.2.4 Input ...........................................................................................................................................73 3.2.5 Output ........................................................................................................................................74

3.3 Image.....................................................................................................................................................74 3.3.1 Supported formats......................................................................................................................76 3.3.2 Adding an image format ............................................................................................................76

3.4 Database (Db) .......................................................................................................................................78

Page 3: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 3(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.4.1 Supported DB formats ...............................................................................................................81 3.4.2 Adding a new DB format ...........................................................................................................82 3.4.3 Node name encodings ................................................................................................................82 3.4.4 Adding node types to the .gzd format ........................................................................................82

4 TUTORIALS ..............................................................................................................................................83 4.1 Working with gzWindow and gzApplication........................................................................................83 4.2 Working with the Gizmo3D scene graph ..............................................................................................85

4.2.1 Creating an environment............................................................................................................90 4.2.2 Adding a billboard .....................................................................................................................93 4.2.3 Adding a lod node......................................................................................................................94 4.2.4 Loading a model ........................................................................................................................95 4.2.5 Debugging the scene ..................................................................................................................96

4.3 Working with shaders ...........................................................................................................................99

5 FAQ ..........................................................................................................................................................103 5.1 Scene graph .........................................................................................................................................103 5.2 Compiling............................................................................................................................................103

5.2.1 Linux Issues .............................................................................................................................103 5.2.2 Win32 Issues............................................................................................................................104

6 LINKS.......................................................................................................................................................105

APPENDIX A NODE SYMBOLS.............................................................................................................106

Page 4: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 4(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

1 GENERAL

1.1 History

During the past 5 years, 3D graphics has moved from advanced and expensive 3D simulators to desktop computers and games. Today it is necessary for your game or your graphical application to have advanced 3D graphics if you want your application to sell. Another breakthrough is the Linux Operating system that is getting better and more popular amongst professional software developers. Unfortunately the APIs available today are either platform dependent just like Micro$oft DirectX or SGIs Cosmo3D, or they target large companies that are willing to pay a lot of money for customized APIs. With these aspects in mind, the Gizmo3D API project was started in mid 1997. The following statements are the fundamental principles in the Gizmo3D project.

• A platform independent API that runs on at least Linux, Irix, Mac OS X and Win32

• Possible to run on BeOS, Xbox and PS2

• High performance 3D functionality equal or better than Vega, Performer or other today existing scene graph APIs.

• Fully featured to give game or simulator programmers what they need to make a great 3D application

• Free for non-commercial use. Use it for free in education. A small symbolic license fee for commercial-use

• A platform with capabilities to add features and algorithms for future usage

Now Gizmo3D is a full time project, part of the Saab Training System’s product suite GizmoSDK since 2003. It is used in a number of large Vis-Sim software applications in both the military and the gaming industry. It is used by customers like Saab, CAE, Pixxim, SPARTA etc. so the project has grown since the start 1997 from a one man project to a full time project for many programmers.

Page 5: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 5(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

2 GIZMO3D API OVERVIEW

During the past years we at Saab Training Systems AB have developed applications for military combat simulation and training. We have numerous times reinvented the wheel in our applications and we have found out that we needed a general architecture to solve our problems, which was repeated in almost all our projects. We created a number of component libraries that are described below and put them together in a SDK that we call GizmoSDK (Gizmo Software Development Kit) We always found out that we needed a platform abstraction API that isolated the different HW platform code solutions from our code so we could write once and run everywhere. We also found out that standard template library (STL) didn’t work well in situations when we used shared libraries (.dlls), memory management was slow on Win32, exception management on PocketPC was not implemented, different programmers used different solutions on various plattforms etc. so we tried to solve all these issues by a common layer API that forced many programmers in a group to write compatible code. The solution was a library that we call GizmoBase. The library is a C++ layer that implements most needed features for memory management, error management, templates, reference pointers, file io etc. GizmoBase is a stand alone library but it is included in the Gizmo3D distribution. We also needed a fast and powerful API for 3D graphics so we could present large 2D and 3D maps, indoor and outdoor realistic environment with effects for snow, rain and daylight sun effects. There were lots of 3D APIs that could do this but none were flexible enough to be integrated in windowed applications with error management and progress information etc. We also wanted to use the latest graphics HW possibilities and the final solution was to write our own API. Our API , Gizmo3D is a high performance 3D Scene Graph and effect visualization C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM/Inventor/VisKit/VTree TM but is a multi platform compatible API with very high performance. It also adds some state of the art functionality for effect presentations and graph interaction. So this document defines the Gizmo3D API that also includes the GizmoBase API…

Page 6: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 6(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

2.1 Code structure & libraries

The Gizmo3D API (toolkit) is divided into 5 main sections. They are...

Gizmo3D Application

Gizmo3D System Library (gzsystem)

Gizmo3D Scene Graph Library (gzgraph)

Gizmo3D Scene Graph

Format Library (gzdb)

Gizmo3D Image Format

Library (gzimage)

Gizmo3D Base Library (gzbase)

Application Layer

Window and UI Layer

Graph Management Layer

Persist Storage Layer

Platform utility layer

Dependancy

1

2

3

45

Figure 1. Dependancy Graph

Each section is implemented as a set of header files and a library. The libraries are available as statically linked (.lib) libraries or dynamically (.dll, .so) linked libraries. The Application layer is intended to show where the customer application code is located in the dependency graph. The libraries are designed according to OOAD, Object Oriented Analysis and Design, criterions but with speed and easy to use criterions as well. The libraries are implemented in C++ and can be use in combination with COM (Win32) to interface other development languages such as basic, C# or java.

Page 7: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 7(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

2.1.1 GizmoBase Library (1)

We always found out that we needed a platform abstraction API that isolated the different HW platform code solutions from our code so we could write once and run everywhere. We also found out that standard template library (STL) didn’t work well in situations when we used shared libraries (.dlls), memory management was slow on Win32, exception management on PocketPC was not implemented, different programmers used different solutions on various plattforms etc. so we tried to solve all these issues by a common layer API that forced many programmers in a group to write compatible code. The solution was a library that we call GizmoBase. The library is a C++ layer that implements most needed features for memory management, error management, templates, reference pointers, file io etc. The GizmoBase library provides a platform abstraction layer in combination with a set of utilities for C++ programmers. The GizmoBase library is fully platform independent allowing you to write advanced C++ code that runs on all supported platforms Irix, Linux, Win32 and Mac OS X. It covers utilities and design patterns like…

• exception management

Classification of exceptions as notice, warnings or fatal exceptions with report mechanisms

• observer/notifier pattern

Load balanced notification with priority queues and timeouts. Templates to add your own subscription management.

• templates

For dictionaries, lists, queues and dynamic arrays etc. in combination with smart pointers (shared reference management)

• shared cloning

Recursive shared cloning of factories to build trees with selected shared node types

• message and debug notifications

Report mechanisms and subscriptions

• serialization

Persist storage etc. with serializing patterns

• threads and mutexes

Multiprocess management

• RTTI

Selected RunTimeTypeInformation with support for hierarcical/non hierarcical structures

Page 8: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 8(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

• Networking

Interfaces to tcp/ip,udp using Ethernet or IRDA etc.

• Utilites

Strings, File management, Environment settings, fast memory allocation, memory debugging etc.

2.1.2 System Library (2)

This part provides the platform independent implementation of Windows, User Interfaces and application management.

Gizmo3D System Library

GZ Bind QT Bind

X11 WIN32

MacOSBeOS

Figure 2. Binding between Gizmo3D Window system and other available

implementations

The basic idea behind Gizmo3D is that it should be easy to implement a fully featured 3D visualizer integrated into some window management system. This is something most professional 3D APIs has forgotten. Gizmo3D provides windows, input management, sound control, file system control, etc. The toolkit interfaces WIN32 HWND windows, Unix Xt Widgets, wxWindows and QT QWidgets on WIN32, Linux and Irix. Future releases will interface Mac and Be Window widgets. The library also manages other input devices that can interact with the Scene Graph and provides a platform independent interface to devices such as HUDs, JoySticks…

2.1.3 Scene Graph Library (3)

The scene graph library provides the basic 3D API for the engine. The basic criterion is to provide functionality similar to professional scene graphs like Performer/Inventor/VEGA/Optimizer/Fahrenheit/VTree/DirectX etc. This gives us...

• Scene management and presentation The presentation of 3D graphics, images, effects etc takes place in a "scene". The

Page 9: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 9(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

software provides means to interact with the scene. Cameras can be positioned in the virtual scene to represent a viewer. The camera can then be connected to a window that shows the contents the camera is viewing in the scene.

• 3D Graphical nodes The 3D graphics is represented by a hierarchical database structure that makes it easy to build, control and interact with the 3D geometry. Most nodes found in Performer/Cosmo3D can be found in Gizmo3D.

• Multipass rendering and effects The 3D Engine uses multipass rendering to provide advanced features for recursive mirrors, magnifiers, portals, refractors, projective textures, texture sorting, transparency etc. This area will be an important feature if you write modern games or simulations.

• Parametric Surfaces, CAT and APARS To present 3D advanced surfaces you need to use some kind of parametric definition. Traditional parametric surfaces like NURBS etc are often slow and not so easy to work with. Tomorrow's hardware will probably implement NURBS directly in the hardware but apart from that there are other techniques that minimize the amount of drawn data and that speeds up the rendering process. CAT stands for Continuous Adaptive Terrain and is a set of terrain data that automatically is reduced when possible (often based on distance from viewer). APARS stands for Adaptive Parametric Surfaces and works just like ordinary parametric surfaces but with automatic LOD (Level Of Detail). The Gizmo3D toolkit uses an algorithm called IRMA (Improved ROAM Algorithm) for the continuous LOD and gluing of patches.

• Selection and collision detection To provide precise input to kinematics and behaviors.

• Script control with an implemented Java interpreter or LUA interpreter to control behaviors (brains) and motion with scripts.

• Animation control to provide animation built into the scene graph

The API is divided into two sub layers. The top layer provides the API for the Scene Graph management. The bottom layer provides an immediate mode API which is compatible with OpenGL 1.4 and OpenGL extensions. It is used to realize the rendering in the scene graph. This makes the scene graph independent of underlying rendering architecture. The underlying rendering architecture is selected in runtime.

Page 10: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 10(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Gizmo3D Scene Graph Library

Retaned Node Mode API

Immediate Mode API

OpenGL DirectX

CustomDebug

Figure 3. The two sub layers of the API.

The immediate mode API can be used by the programmer to make his own rendering effects run on different target platforms. The user can also use debug output or even his own hardware API.

2.1.4 Image Format Library (4)

This part provides APIs for management of Image data readers and writers. The API provides functionality for the programmer to add his own image manager or his best friends JPEG converter etc. There will be support built in for BMP, PNG, RGB, INT, TIFF and JPEG etc. (Future release will continuously add more formats)

2.1.5 Graph Format Library (5) (Database (DB))

This part works just like the Image library but it is used to manage 3D database formats. Typically you want to read 3DS files or Multigen flight files if you are working in the military business. There will be support built in for Multigen OpenFlight (.flt), Performer (.pfb), VRML 97 (.wrl), 3D Studio (.3ds) and a Gizmo3D specialized format to allow all features in Gizmo3D to be stored in a database.

Page 11: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 11(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3 GIZMO3D API DETAILS

3.1 Graph

The Graph library contains functionality to do retained graphics (Gizmo3D renders the graphics when needed) or immediate graphics (directly graphical commands sent to the GPU). The retained mode graphics are implemented by a scene graph (a hierarchical structure for graphical or other relational data) that helps Gizmo3D to render the graphics as efficiently as possible. The retained mode handles selection of graphical states, sorting of textures, optimizations of geometry etc. to perform faster and in some cases more predictable (load balancing, constant refresh rate etc.) The retained mode graphics uses the immediate mode graphics to do the actual drawing. In the Gizmo3D engine the immediate mode is abstracted through a Graphical Abstraction Layer (GAL), to be able to interface different kind of hardware/software implementations like DirectX or OpenGL. You can even add your own GAL to do your special kind of render or debugging. If you want to use the classes in the graph library you need to link your project against gzgraph.lib.

3.1.1 Rendering

The rendering is performed by the HW, that interprets the GAL commands. To feed the HW with the correct GAL commands to do rendering in a window, Gizmo3D need to handle a number of contexts (handles) that is used to identify what HW is used and where the rendering occurs. The Graphics Abstraction Layer (GAL) is a platform independent layer between Gizmo3D immediate mode commands and the HW/SW platform dependant 3D immediate mode commands. The GAL is syntax compatible with OpenGL. This makes it easy to port any 3D OpenGL code to Gizmo3D. You select the implementation of GAL by using gzGraphicsEngine::useEngine(imp). This way you can select OpenGL, DirectX, Glide or software as you HW implementation layer. The default is to use OpenGL. The application software must set the GAL engine before any graphics commands are used. Therefore you normally must issue the command…

gzGraphicsEngine::useEngine(GZ_ENGINE_OPENGL)

Application

Retained

Immediate (GAL)

Page 12: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 12(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

in your code. Otherwise it will crash when GAL commands are used. Currently only OpenGL is implemented. When you write custom nodes you can use GAL commands instead of OpenGL or DirectX. Just translate your code from OpenGL

glBegin(GL_TRIANGLES)

glVertex3f(a,b,c)

..

glEnd();

to

gzBegin(GZ_TRIANGLES)

gzVertex3f(a,b,c)

..

gzEnd();

Note that Gizmo3D can use either float or double precision for the gzReal type. Use the gzReal type with extension (r) instead of (f) or (d) like gzVertex3r(r1, r2, r3);

3.1.1.1 The device Context (gzDeviceContext)

The device context identifies the actual HW that shall render the GAL commands. On a normal PC desktop machine, you will probably only use one HW (device context) connected to your monitor, but on more advanced systems you can use multiple monitors connected to several HW Graphics Cards. A gzDeviceContext then identifies what HW to be used. On Unix X11 you can compare a gzDeviceContext with the “display” and on Win32 platforms you can compare it with a “HDC” handle.

3.1.1.2 The window Context (gzWindowContext)

The window context is used to identify what window shall be used in the rendering process so the HW can clip the output to fit in a rectangle on the display. Each gzWindow has an associated gzWindowContext. On Win32 you can compare it with a “HWND” handle and on Unix with a “window”. On Unix you can also use the gzWindowHandle which is associated with the X11 Motif “widget”. However each “widget” has an associated “window” as well.

3.1.1.3 The rendering context (gzRenderContext)

The rendering context gzRenderContext is used to get a GAL pipeline to the HW. It is associated with the gzDeviceContext and the gzWindowContext so this is the actual handle to identify where the GAL commands shall be sent. If you are familiar with OpenGL, you know that you should create a rendering context, activate it and execute your OpenGL commands.

Page 13: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 13(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Note that there can be only one rendering context for each thread and that context can only be used from the thread that created it.

3.1.1.4 The Graphics Context (gzContext)

A context (gzContext) is a handle to a unique memory area that is unique for each thread and each gzRenderContext. This allows multiple instances of renders render the same scene asynchronous as well as recursive. A user shall keep in mind that there is a default gzContext associated with his window and that some calls operate on that context. You should not as a beginner try to change or alter this context, but when you get deeper into Gizmo3D you will find a lot of info in your gzContext.

Page 14: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 14(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.2 Coordinate systems

The coordinate system used in Gizmo3D is a Cartesian right handed coordinate system. There is one global world coordinate system where objects are placed. Every object has its local coordinate system. This can be illustrated with a room. The room is a global coordinate system. In the room stand a chair and a table. The positions of the objects are given in global coordinates and each object has its own local coordinate system. On the table a book is placed. The position of the book is related to the table and given in the local coordinate system for the table. Since the position in the local coordinate system is known it has to be transformed to global coordinates to be compared to the position of other objects. One advantage of using global and local coordinate systems becomes clear when the table is moved. If the table is moved we want the book to still be placed on the table instead of hanging free in the air with no connection to other objects. A movement of the table is a translation of the local coordinate system which means relationship within the coordinate system is maintained. The scene graph transformation is the first stage of the viewing pipeline. During this transformation each object is moved from its local coordinate system to the global world coordinate system. As each object has its own coordinate system, each object must be processed individually. By using a local coordinate system the object becomes independent from any other object in the scene.

Figure 4. The figure shows two local coordinates systems and the global

coordinate system. To translate each coordinate from local to global a

matrix multiplication with the modeling transform is made.

z1

x y

x

y

z

z2 x

y

Scene graph

Local coordinate

Global coordinate

Page 15: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 15(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

To create an image the 3D information in world space is projected onto a 2D image plane. This is done by using matrix multiplication. The pipeline is shown in Figure 5 below.

Figure 5. To create a 2D image on the screen each point has to be translated

from local coordinates to display coordinates. The scene graph

transformation is used to transform a point in local coordinates to world

coordinates. Then the camera view transform transforms the coordinates to

eye space and finally the camera frustum transformation performs the

transformation to clip space coordinates.

The translation from local coordinates to world coordinates is described earlier. The next step is to translate the objects in the world coordinate system to clip space coordinates. The clip space coordinate system represents what is visible to the camera. Everything within the world which is visible to the camera has coordinates ranging between -1 and 1. The x and y values represents the location at the image plane while z represents the distance from the point to the camera. To translate the world coordinates xw, yw, zw to clip space coordinates X, Y and Z the following matrix multiplication is used.

=

1

w

w

w

camprojz

y

x

MM

w

Z

Y

X

Camera frustum transformation, Mproj

Camera view transformation, Mcam

World coordinates - light position - camera position - object position

Local coordinates - unique for each object

Clip space coordinates -culling

Scene graph transformation, Mscene

Eye space coordinates - Viewer looks down the negative z-axis

Display coordinates

Viewport transformation

11

11

11

≤≤−

≤≤−

≤≤−

z

y

x

Page 16: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 16(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

The first step is to use the camera view transform to translate the coordinates from world space to view space. The transform is the following:

=

1000

100

010

001

1000

0

0

0

z

y

x

zyx

zyx

zyx

camC

C

C

NNN

VVV

UUU

M

In the matrix N is the viewing direction of the camera. U and V is the other two axes in the view coordinate system. C is the camera position. To transform every object within the scene graph from its local coordinates to eye space coordinates the modelview Mv matrix is used.

Mv= Mcam* Mscene.

The modelview matrix is a compound matrix and is stored in the GZ_MODELVIEW matrix. All transforms used in the scene graph affects the scene graph matrix and consequently even the model view matrix. All objects transformed through gzTransforms etc. will be multiplied with the actual current modelview transform. The eye space coordinate system is a coordinate system located in (0,0,0) looking in the negative Z direction with X positive to the right and Y positive up. The near plane is located at z = -near_distance and far plane located at z = - far_distance From eye space the camera projection matrix is used to perform the transformation to clip space. The camera transformation is different for different types of cameras since different types of projection transform are used. The perspective camera uses a perspective transform and the orthogonal uses the orthogonal transform. The matrix is called the frustum matrix and is stored in the GZ_PROJECTION matrix.

+−

+

+

==

0100

2)(00

02

0

002

nf

fn

nf

nfbt

bt

bt

nlr

lr

lr

n

MM eperspectivproj

Page 17: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 17(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

+−

+−

+−

==

1000

200

02

0

002

nf

nf

nf

bt

bt

bt

lr

lr

lr

MM orthogonalproj

where n = the distance from the camera to near plane

f = the distance from the camera to far plane r = the right coordinate for near plane l = the left coordinate for near plane t = the top coordinate for near plane b =the bottom coordinate for near plane

Page 18: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 18(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.3 The camera

When the scene graph shall be rendered you can imagine a camera that can move around in a 3D world and look at the scene graph data. The camera projects the 3D scene onto a plane and forms a 2D image. The camera is connected to the scene. One scene may have many different cameras with different views depending on the camera position and viewing direction. Every camera has a near clip plane and a far clip plane which both in most cases are orthogonal to the cameras viewing direction. When using a camera and looking on the scene, the scene is projected onto the view plane. The scene projected is the part of the scene which is placed between the near plane and the far plane. Everything in front of the near plane and behind the far plane is ignored. The field of view is also important, everything outside the field of view are ignored. The distance to the clipping planes are measured from the camera position along the viewing direction. When a window is connected to the camera the scene graph data is projected onto a screen that is represented by the window output. The viewing frustum is a rectangular pyramid with the camera position as the apex, propagating along the viewing direction. The near clip plane truncates this volume at the top and the far clipping plane at the bottom. The viewing frustum defines the region of 3D space visible to the camera. The user can define camera properties like camera position and the viewing direction. Position, viewing direction and the view up vector together defines the camera orientation. There are different types of projection. The projection determines how the scene is projected onto the image plane. Each projection method has its own camera. The defined cameras are described below. The perspective camera, gzPerspCamera, is one of the two main types of cameras. The other one is the orthogonal camera. In Figure 6 below the viewing frustum is shown using a perspective camera. With a perspective camera objects seems to be smaller when placed far away. When you look at two trees of the same size placed at different distance from you, the tree placed furthest away seems to be smaller than the one near you. Using a perspective camera will give the same effect.

Near

plane

Far

plane

Camera

position

Figure 6. The view with perspective projection.

Page 19: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 19(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

When using this camera the field of view has to be specified. Field of view determines how wide the camera lens is. The gzOrthoCamera is the another main type of camera. It is an orthogonal camera and uses a parallel mapping process which skip the z-component in the position. This is called the orthographic or parallel projection. The advantage with this camera is the size of objects is constant independently of the distance to the camera. Lengths parallel to the projection plane is preserved. A disadvantage is that the look of e.g. a room is misunderstood since all objects in a room have the same size. The user has to specify width and height for the image.

Figure 7. The figure shows the parallel projection. There is no center of

projections since the projection lines are parallel.

Another type of camera is the gzStereoCamera which is a stereoscopic camera to be used with 3D glasses etc. The gzGenericCamera is a generic camera to which the user defines its own projection method. The gzDummyCamera is a dummy camera which does not generate anything. It observes everything that happens into the scene, not just everything inside the field of view. It is not just the visible things which is observed, it is anything like sound etc.

3.1.3.1 Using the camera

The scene is located in the world coordinate system which is a XYZ coordinate system where you can imagine an X coordinate axis positive to the right, an Y positive axis up and the Z positive axis towards you. In this 3D system you can position the camera at any point with any viewing direction.

Near plane

Far plane

Page 20: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 20(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 8. The figure shows a right handed coordinate system. The x-y plane

can be used for 2D projections of xy. If values in the x-y plane are changed it

will be visible in the image.

E.g. If you position the camera at (0,0,10) you can imagine that it is located 10 units toward you in the positive Z direction. By default the camera always look in the negative z direction so therefore it looks at point (0,0,0). There are a lot of functions available which sets the properties for the camera. You can place a camera at the position (x, y, z) with the function setPosition (gzReal x, gzReal y, gzReal z).

To make the camera look in another direction than along the negative z-axis there are several alternatives available. If you know what the camera is looking at you can specify the point to look at with command lookAt (gzReal x, gzReal y, gzReal z, gzReal) or lookAt(gzReal x,

gzReal y, gzReal z, gzReal roll, gzVec3 &up). Then the camera will look in the direction from the camera position to the lookat point, see Figure 9. By changing the up vector you can tilt the head.

Figure 9. The camera is placed at a position and look at the lookat point.

The user does not have to specify the viewing direction for the camera.

The second alternative is useful when you know the orientation of the camera. Then the heading, pitch and roll for the camera is specified. The heading is the direction which the camera is looking at in the world xz-plane. A positive heading rotates the camera clockwise in the y direction. The roll and pitch influences the up vector. The terms are explained with images in Figure 10.

x

y

z

Camera position

LookAt point

Direction

up

Page 21: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 21(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 10. The heading shows the direction in the xz-plane. The roll

describes the angle between the camera viewing direction and the xz-plane.

The pitch describes how the camera tilts sideways.

To set the HPR use the function setHPR (gzReal heading, gzReal pitch, gzReal roll).

More advanced users can set the camera transform directly with setTransform (const

gzMatrix4 &transform).

The camera uses a near and a far clip plane to determine if data shall be visible or not. Everything in front of the near clip plane and behind the far clip plane is ignored in the rendering. You can set the distances to these clip planes with setNearClipPlane (gzReal

distance) and setFarClipPlane (gzReal distance). The default value for the near plane is 1 and the default far distance is 500. Note that the perspective camera (gzPerspCamera) can use an infinite far plane with useInfiniteFarPlane (gzBool on). Since the camera is observing a scene you need to specify the scene. This is done with the function setScene (gzScene *scene). The functions flipVerticalView (gzBool on) and flipHorizontalView (gzBool on) flips the view vertical and horizontal. The following code shows how to create a camera at position (10, 10, 10) looking at point (0, 0, 0).

gzCamera cam = new gzPerspCamera();

roll

pitch

up

up

heading

x

z

Page 22: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 22(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

camera->setPosition(10,10,10)

camera->lookAt(0,0,0)

A gzCamera cannot be instantiated since it is an abstract class. A specialization is required, this is why a specific camera is initialized in the code above. The default camera is a perspective camera (gzPerspCamera) that is attached to a window. When you create a window (gzWindow) it will automatically have a camera. To get a pointer to this camera use:

window->getCamera()

With the camera placed the 2D image can be generated. When rays travelling in the 3D scene pass trough the camera lens a 2D image is produced. The position and other properties for the camera determines which rays of light get captured. This is the rays which intersect the camera position and are within the viewing frustum. The camera defines a number of transforms. First it creates the mapping of the world coordinate space to the eye space with the camera view transformation Mcam. To get this matrix camera->getTransform() is called. To transform from eye space to clip space the camera frustum matrix Mproj is used. This matrix is returned when camera->getProjectionTransform() is called. The camera also contains a handle to the current scene. Multiple cameras can be used to render a scene from different positions and with different viewing directions. The gzWindow is the default rendering output. It is connected to a camera and shows everything visible to the camera. This image is drawn in a window on the computer screen. You can read about windows in 3.2.2 Windows.

Page 23: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 23(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.4 What is a Scene Graph?

If you are familiar with OpenGL or any other low level graphics API, you know that when you use the immediate commands, you need to do a lot of thinking and optimizations to render exactly what you need. If you send a lot of graphics commands to render object outside your view, you will use a lot of unnecessary processor power. You may also end up with complex sorting of objects to optimize the rendering for minimal texture changes etc. If you are not familiar with such problems, you can try to understand that it is really a complex task to do efficient rendering. A scene graph is a tree structure which means data is ordered in a hierarchical manner. The basic building blocks in the scene graph are the node, the group and the geometry. Both the group and the geometry are actual special types of a node. The group node groups several nodes and therefore can be used to create the actual tree structure with children-parent relationship. The geometry node contains the geometry information for the actual rendering. The third basic component of the scene graph is the state which is used to apply properties on the nodes, such as texture, materials etc. A node holds information about an object such as shape description or geometric transformation. The tree consists of group nodes which contain one or several children. A child node can also be a group node so the hierarchy can extend deeper and deeper. There are many kinds of nodes. The most common node you use is the transform node which is a group node with children that are translated/rotated/scaled. The other most common node type is the geometry node which contains the geometry. To every node the user can attach properties such as material, lighting model or textures. To understand how a scene graph works we model a kitchen. The kitchen is a room. In the room stands a chair. The chair has a certain shape and is made of metal. In the kitchen there are additional two identical chairs. The only difference between the chairs is that they are placed at different positions in the room. In the kitchen there is also a table. The table is made of wood. It consists of a tabletop and legs. A scene graph gives an overview of the kitchen which is easy to understand. The shape of the chair is described by a geometry node. This node contains all information about the geometry. Since all chairs looks the same it is enough to use one geometry node. Every chair is transformed from the original position with a transform node. Three transform nodes are created and each transform is connected to the geometry node. Next to the chairs is a table placed. The table is described by one geometry node. They are grouped with one transform node because the translation for all components of the table is the same. The geometries are placed in the same room and are therefore grouped with a group node. To describe the material of an object a property are connected to the corresponding geometry. The figure below shows the scene graph we just created.

Page 24: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 24(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Table

Top

Room

(G)

Legs

(G)

Chair

(G)

Table

(T)

Chair

(T)

Chair

(T)Chair

(T)

Wood

(S)

Metal

(S)

Group node

Geometry node

Property

Figure 11. The scene graph describing a kitchen and its furniture.

The programmer creates an application by building rules for the scene graph’s structure. The API renders the scene and handles the interaction from the user. In the rendering process the scene graph is traversed and transforms the rules made by the programmer to the graphic image which is shown on the screen. The bottom nodes represent the actual geometry. The circular shapes represent groups. Now what is the benefit by using a scene graph? The trick is that if the viewer only sees one chair in the picture, the scene graph renderer can automatically discard the others. Other benefits can be e.g. to use transforms so the user by setting a rotation/position can adjust the position of the chairs without the need to duplicate the geometry. You can see that there is only one geometry for the chair but three transforms that puts the geometry in three different places. When a transform is applied to a group node all nodes at a lower level will be affected. The scene graph is an ordered collection of nodes. When the scene graph is created it is possible to apply operations or action to it, like rendering, searching, compute bounding box and reading or writing to a file. The relationship between nodes control how properties and transformations are applied to the nodes when they are rendered. A scene graph is used to control the rendering process. The user creates a scene and places objects into the scene. All objects in the scene have a bounding volume which completely contains the geometry. Since the position and size of every object is known it is possible to do a view volume culling, which means that only the objects the camera can see is rendered. The rest is ignored. This is a huge advantage since a world can be very complex and it is unnecessary to draw information that the user cannot see. By ignoring everything outside the viewing frustum the rendering becomes faster. By using a scene graph you will find lots of benefits in the hierarchical structure of data.

Page 25: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 25(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.5 The basic node

The basic node (gzNode) is the base class of all nodes in the system. You will not find any gzNodes in the graph, but you will see that all node classes are derived from the gzNode. A lot of features used by the scene graph are contained in the gzNode class.

The node class is derived from the gzNameInterface. This gives each node a unique name. You will be able to create nodes with unique names. These named nodes can later be found in the graph by a search for the name. The node also contains a boundary (gzBoundary). This is basically a sphere that surrounds the physical contents, see Figure 12. The scene graph uses this boundary to cull and occlude sibling children in the node traversal. If the bounding sphere for the group node is within the view frustum, the group and all its children are drawn. If the whole group node bounding sphere is outside, all children are culled. If the bounding sphere for the group is both inside and outside the view frustum the bounding sphere for all children is checked. If the bounding sphere is outside it is culled, otherwise it is drawn.

Figure 12. A group of two nodes. Each node has a bounding sphere. The

group has a bounding sphere which surrounds all its children.

If you want to set the boundary for a node you usually call the method updateBoundary(). This method is implemented for each node type and does a proper calculation of the boundary. If you still want to set the boundary manually you can set the center and radius manually in your own updateBoundary() method. In the case of non physical contents, you can use the boundary to force traversal (rendering) by setting setForceIncludeBoundary(TRUE). The basic node is referenced managed. It is derived from the gzReference class. This means that you shall follow two rules when using nodes.

N

Page 26: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 26(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

1. You shall always use reference functions when working with nodes. E.g. never store a pointer to a node in a class because it might be deleted by another function when used which will give you a dangling pointer.

2. When a function returns a pointer to a node it has in most cases a reference = 0 which means that you need to manage the ref() / unref().

The best way to work with nodes and avoid confusion is to use smart pointers

gzRefPointer<gzNode> pNode; // smart pointer

pNode = new gzTransform; // gzTransform is derived from gzNode

...

3.1.5.1 Node cloning

Because all graphics nodes are derived from the gzNode class, there are lots of situations when the scene graph engine need to copy contents. You must then assure that you have provided a clone method for your class. Typically this looks like this… virtual gzReference* MyClass::clone() const

{

return (gzReference *)new MyClass(*this);

}

This way the engine can just call pObject->clone() and get a correct copy constructed object for that class.

3.1.5.2 Node RTTI

The engine also uses RTTI information so it can decide what type the object has. You typically provide this MACRO in the header like this. class MyClass : public gzNode

{

public:

GZ_DECLARE_TYPE_INTERFACE;

......

};

and in the body..

GZ_DECLARE_TYPE_CHILD(MyClass,gzNode,"MyClassName");

These code snippets makes it possible to use methods like

Page 27: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 27(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

if(pNode->isOfType(MyClass::getClassType())

{

// Now we know the pointer is a MyClass or derived from a MyClass

}

if(pNode->isExactType(MyClass::getClassType())

{

// We know it is exact MyClass Type

}

GZTRACE(“Class name %s”,pNode->getTypeName());

Page 28: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 28(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.6 Geometry node

The most commonly used node is the gzGeometry class. This class contains the actual geometry. The geometry is defined by a primitive type which is the kind of geometry it represents. A single geometry instance can only be one primitive

type at a time. One single instance can represent a number of primitives of one single type. The following primitives are defined: GZ_PRIM_POINTS Points, each point is defined by a vertice

GZ_PRIM_LINES Lines, Each line uses two vertices

GZ_PRIM_LINESTRIPS A consecutive line. A line is drawn between each vertex

GZ_PRIM_FLAT_LINESTRIPS Non shaded version of above

GZ_PRIM_LINELOOPS Close loop lines

GZ_PRIM_TRIS Triangles, Each triangle is defined by 3 vertices

GZ_PRIM_QUADS Quads, Each Quad is defined by 4 vertices

GZ_PRIM_TRISTRIPS A strip built by triangles

GZ_PRIM_FLAT_TRISTRIPS Non shaded version of above

GZ_PRIM_TRIFANS A fan build by triangles

GZ_PRIM_FLAT_TRIFANS Non shaded version of above

GZ_PRIM_POLYS A convex polygon

GZ_PRIM_QUADSTRIPS A strip build by quads In the above list we can see that some prim types are bold. They represent the primitives that always use the same number of coordinates. When using these prim types it is possible to calculate the number of primitives to be rendered by dividing the coordinate array size with the number of vertices in each prim. The other primitives need a length array to define how many vertices are used. Each position of the array specifies the number of points used in one primitive. The size of the array is the number of primitives used. E.g. If you want to create a geometry of two primitives of type GZ_PRIM_TRIFANS with 4 vertices in the first and 5 vertices in the second you need to provide 9 vertices to be used as coordinates, you need to set the length array to size two (two primitives) and length[0]=4 and length[1]=5. This is illustrated in Figure 13.

Figure 13. Two trifans are created of 9 vertices

If one coordinate is used several times to build a geometry it is possible to use an index array. When using indices to specify coordinates there is a geometry array which contains information about all verices. The index array is used to point at the geometry array and

0

1

4

5

7

8

6 2

3

G

Page 29: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 29(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

specify the order in which vertices are used, see Figure 14. The index in the index array must not be larger than the size of the coordinate array.

Figure 14. Indices might be used to specify in which order the coordinates

are used.

You can apply textures, colors and normals to the geometry. Each feature can be provided overall, per primitive or per vertex. Use the setColorBind() method to define this for colors. The same function is available for textures and normals. The available binding methods are: GZ_BIND_OFF No binding is applied to the geometry GZ_BIND_OVERALL The first position in the texCoord/ color/ normal array is

applied to the complete geometry. GZ_BIND_PER_PRIM Each primitive has a texture coordinate/ color/ normal. GZ_BIND_ON The same as GZ_BIND_PER_VERTEX GZ_BIND_PER_VERTEX Each vertex has its own texture coordinate/ color/ normal. A texture can be used to add more detail to the geometry. The texture contains an image which is pasted to the surface of the geometry, see Figure 15. To add a texture a texture map, texture coordinates and texture mapping method are required. The texture map is added using a state, see part 3.1.8.1. Then texture coordinates and binding method needs to specify how the texture is connected to the geometry, otherwise the texture will not be applied to the geometry. One state can use several textures, to use all available textures you need to specify the number of texture units, texture coordinate array for each unit and texture binding method for each unit are defined. The number of texture units is specified with setTextureUnits

(gzULong size). By default there is one texture unit.

v1

v2

v3

v4

v5

v6

v7

v8

v9

v10

v11

1

2

3

1

3

5

4

2

7

1

3

Page 30: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 30(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Texture coordinates are given with an array of gzVec2 vectors. Each vector contains two values, u and v, between 0 and 1. If larger values are used, the result depends on which texture filtering method that is used, read more about this in 3.1.8.1.

Figure 15. The coordinates in the geometry are allotted corresponding

texture coordinates which shows how the texture is mapped onto the

geometry.

To specify a texture coordinate array the function setTexCoordinateArray (gzArray< gzVec2 > &array, gzULong unit) is used. Then a texture coordinate array is added to the specified unit. If no unit is specified the array is added to the texture unit zero. It is also possible to specify an array of coordinate arrays, instead of specifying one array for each unit. Then the function setTexCoordinateArrays (gzArray<

gzArray< gzVec2 > > &array) is used. Texture binding is specified for each unit or as an array for all units with the functions setTexBind (gzGeoAttribBinding binding, gzULong unit) and setTexBindArray (const

gzArray< gzGeoAttribBinding > &binding).

It is possible to change the point size and line width for the geometry with the functions geometry->setPointSize (gzFloat size) and geometry->setLineWidth (gzFloat size).

The following code creates a geometry with triangle fans as primitive. The geometry is assigned texture. At first a new geometry is created. The primitive type is set to trifans. Then the length array describes the distribution of the vertices. The size of the array determines the number of primitives and the value at each position describes how many points to be used in each primitive. The coordinates for the points is given as a gzVec3 array. Every point has a corresponding texture coordinate. The texture coordinates is stored in a gzVec2 array. When the information needed is added the boundary of the boundary is updated.

gzGeometry * geometry = new gzGeometry();

geometry -> setGeoPrimType(GZ_PRIM_TRIFANS);

geometry -> setPrimLengthArray(length);

u

v

Page 31: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 31(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

geometry -> setCoordinateArray(coords);

geometry -> setTexCoordinateArray(texCoords);

geometry -> updateBoundary();

The geometry has a bounding sphere which is the smallest possible sphere to enclose the geometry. This bounding sphere is important in the rendering process since to see the position and size of every object. Every time the geometry is changed the boundary also is changed. The boundary has to be updated when the geometry changes.

3.1.6.1 Description of primitives

Below follows figure and detailed description of each primitive type.

GZ_PRIM_POINTS GZ_PRIM_LINES

GZ_PRIM_LINESTRIPS GZ_PRIM_LINELOOPS

GZ_PRIM_TRIS GZ_PRIM_QUADS

v6

v4

v3

v2

v0

v1

v5

v7

v3

v4

v2 v0

v1

v5

v5

v4

v3

v1

v0

v2

v4

v3

v1

v0

v2

v7

v6 v5

v4 v3

v1

v0

v2

v7 v6

v5 v4

v3

v1 v0

v2

Page 32: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 32(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

GZ_PRIM_TRISTRIPS GZ_PRIM_TRIFANS

GZ_PRIM_POLYS GZ_PRIM_QUADSTRIPS

An array with vertices (v0, v1, v2, …, vn-1) is used to create the primitives. GZ_PRIM_POINTS at every vertex a point is dawn GZ_PRIM_LINES A series of unconnected lines are drawn. The first

line is between v0 and v1, the second between v2 and v3 and so on. If n is odd the last vertex is ignored.

GZ_PRIM_LINESTRIPS One long line strip consisting of a series of line

segments are created. The first line segment is drawn between v0 and v1, the next from v1 to v2 and so on. The total number of line segments is n-1. If n = 0 nothing is drawn.

GZ_PRIM_GLAT_LINESTRIPS As line strips but flat shaded. GZ_PRIM_LINELOOPS Works as GZ_PRIM_LINESTRIPS with the

difference that one last line segment is drawn between vn-1 and v0 which creates a loop.

GZ_PRIM_TRIS A series of triangles are drawn. First vertices v0, v1

and v2 are used, then v3, v4 and v5 and so on. N has to be an exact multiple of 3, otherwise the last one or two vertices are ignored.

v9

v8

v4

v2

v3 v5

v6

v7

v1

v0

v5

v4

v3

v2 v1

v0

v5

v4

v3

v2

v1

v0

v6

v7

v5

v4

v3

v2

v0

v1

Page 33: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 33(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

GZ_PRIM_QUADS A series of four-sided triangles or quadrilaterals are

drawn. First vertices v0, v1, v2 and v3, then v4, v5, v6 and v7 and so on. N has to be an exact multiple of 4, otherwise the last one, two or three vertices are ignored.

GZ_PRIM_TRISTRIPS Draws a series of connected triangles, using vertices

v0, v1, and v2 then v2, v1, and v3 The order is important since the orientation for the triangles has to be the same. To draw anything at all n has to be larger than 3.

GZ_PRIM_FLAT_TRISTRIPS As tri strips but flat shaded. GZ_PRIM_TRIFANS Draws a series of connected triangles. The order is

v0, v1, and v2 then v0, v2, and v3. GZ_PRIM_FLAT_TRIFANS As tri fans but flat shaded. GZ_PRIM_POLYS Draws a polygon using points v0, v1,… vn-1. If n is

smaller than 3 nothing is drawn. It is important the polygon is convex and not intersect itself. The result if it does is unpredictable.

GZ_PRIM_QUADSTRIPS A series of quadrilaterals is drawn using vertices v0,

v1, v3, v2 then v2, v3, v5, v4 and so on. The smallest value of n is 4 otherwise nothing is drawn. If n is odd the final vertex is ignored.

3.1.6.2 Built-in geometry utilities

There are a number of built-in geometry utilities available such as gzGeometryAxis, gzGeometrySphere, gzGeometryTube and gzTriGeometry. One of the built-in geometries is gzGeometryAxis which is coordinate axis that can be added to the scene with custom axis size, step size and color. Use the constructor gzGeometryAxis

(gzReal size, gzReal step, const gzVec4 &color) to create your axis. It is useful to add geometry axis to a group so you can display the local coordinate system and scaling for that group.

Page 34: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 34(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 16. The axis to the left have size 4 and step 1. The axis to the right

has size 4 and step 2.

It is possible to change the size with setSize (gzReal size). The step is changed with the function setStep (gzReal step). How these parameters affect the axis is visible in Figure 16. The default color for the geometry axis is black. Another pre defined geometry type is a sphere. To create a sphere it is enough to call the constructor gzGeometrySphere (gzReal radius, gzInt sections, const gzVec4 &color) which creates a sphere with your specified radius and sections. If you don’t specify a value for sections a sphere with 30 sections will be created. The default color is white, see Figure 17.

Figure 17. A gzGeometrySphere with default settings for sections and color.

Page 35: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 35(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

If you want a tube you create a gzGeometryTube with the constructor gzGeometryTube

(gzFloat length, gzFloat width, gzULong lengthSamples, gzULong widthSamples,). The default length for the tube is 10, the width is 1. Length and width samples is 10 as default and the default color is white. You can also provide callback functions for the tube that can vary the radius and offset from the center to create non linear tubes.

Figure 18. A gzGeometryTube with default settings

The gzTriGeometry is a geometry built of basic triangles. The size of the geometry is specified with setSize (gzULong size). This size defines the number of triangles the geometry consists of. Each triangle is created with the function setTri (gzULong index, const gzVec3

&a, const gzVec3 &b, const gzVec3 &c). Default color for the geometry is white, but the color can be specified for each triangle with the function setColor (gzULong index, const

gzVec4 &color), or for all triangles with setColor (const gzVec4 &color). You can also specify if the edge of each triangle is an edge in the total geometry with setEdge (gzULong

index, gzBool ab, gzBool bc, gzBool ca). It is also possible to add a texture to the triangle geometry with a state. To add texture coordinates to the model, use the function setTexCord (gzULong index, const gzVec2 &a,

const gzVec2 &b, const gzVec2 &c). The function calculateNormals () calculates the normals for the geometry.

Page 36: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 36(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.6.3 Parametric Geometry

In many situations you would like to render meshes. A mesh is a surface in 3D that can be defined by two parametric coordinates (s,t). For each (0<= s <= 1) (0<= t <= 1) a point in 3D is defined as V(x,y,z) = f(s,t). This math makes it easy

to provide a function in the gzParametric geometry and let Gizmo3D calculate the mesh. By deriving the parametric class and providing your own implementation of getColor, getCoordinate, getTexcoordinate etc. you will be able to just call createPatch(). There are also some other benefits to use a parametric surface. If you set up the size of the patch to have width and height as a power of 2 you can use a dynamic lod calculation called APARS (Adaptive Parametric Surface). The surface can be made to recalculate the drawing of the surface in real time so you can get better throughput even if you use very detailed surfaces. (Se the IRMA algorithm below 0)

In the image above, several patches are glued together. You can also see the APARS in action where the triangulation is higher in some visible parts where the geometry detail is higher and lower in other parts that does not require that high triangulation.

3.1.6.4 Geometry features

3.1.6.4.1 Edges

P

Page 37: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 37(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Edge array Can set if a vertex is an edge vertex or not. When is this useful?

3.1.6.4.2 Weights

generateWeights (const gzDouble &factor=1.0, gzUByte coordIndex=2, gzWeightMethod

method=GZ_WEIGHT_START_TRANS, gzULong baseID=1, gzFloat

baseWeight=GZ_FLOAT_ONE) The gzWeightMethod describes how the method generateWeights() creates the weighting coordinates. GZ_WEIGHT_START_TRANS Affects start coordinates (smaller values).

GZ_WEIGHT_END_TRANS Affects end coordinates. GZ_WEIGHT_MID_TRANS Affects mid coords. GZ_WEIGHT_START_END_TRANS Affects start and end coords.

GZ_WEIGHT_CONSTANT Affect all coordinates with constant value. setWeightArray (const gzDynamicArray< gzWeight > &array) The array may be a dynamic or static array. smoothAllWeightedNormals (gzBool on=FALSE)

usePerfectWeighedNormals (gzBool on=FALSE) updateWeightInfo (gzContext *context) gzWeightGeomInfo & getWeightInfo ()

3.1.7 The group node

The group Node (gzGroup) is the actual hierarchy creator in the scene graph. The group node contains a number of children. You add nodes by using addNode(node) and you remove them by using removeNode(node). Every property of the group node is inherited by its children. The properties may be states, transforms, etc. By

changing the properties for a child the inherited properties are overridden. There are two ways to traverse the group’s children. The first one is the traditional way which is easy to read but time consuming.

gzRefPointer<gzNode> pNode; // smart pointer

// pGroup is ponter to gzGroup

for(gzInt i=0;i<pGroup->getNumberOfNodes();I++)

{

pNode=pGroup->getNode(i);

G

Page 38: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 38(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

T

// do something with pNode..

}

The second high speed version

gzRefPointer<gzNode> pNode; // smart pointer

// pGroup is ponter to gzGroup

gzListIterator<gzNode> iterator(pGroup->getNodeList());

while(pNode=iterator())

{

// do something with pNode..

}

3.1.7.1 Built in group node types

Gizmo3D contains a number of pre defined node types that you can use to build your scene graph. They all provide high optimizations of code and make your code run faster or give you special effects like mirrors and shadow stuff.

3.1.7.1.1 The scene

The scene (gzScene) is the top node of the scene hierarchy. By setting up the scene and add it to the camera, you will be able to look at the scene graph contents. As soon as you add the scene to the camera, it will be active in the rendering process of the camera window.

You can switch between multiple scenes by setting different scene hierarchies in the camera.

3.1.7.1.2 Transform

The node gzTransform is a group node. The group nodes coordinates are transformed before they are rendered. If the transform defines a matrix M, then the result coordinate is defined as C’=M*C.

In 3D the points are represented by the vector (x, y, z). When doing transformations on a point homogeneous coordinates has to be used. Homogenous coordinates is represented by a four element vector (xh, yh, zh, wh). Using homogeneous coordinates makes it possible to define perspective transformation. To get the coordinates in 3D the first three terms are divided by the fourth term.

h

h

w

xx =

h

h

w

yy =

h

h

w

zz =

A transformation is done by multiplying the coordinates by a 4×4 transformation matrix. The transformations available are scaling, rotating and translating.

S

Page 39: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 39(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Each object has its own local coordinate system. Each transformation is acting on the local coordinate system. A coordinate system is translated by translating each of X, Y, and Z axes of the coordinate system. To make a translation of point (x, y, z,) by a vector (tx, ty, tz) the matrix looks like following:

=

1000

100

010

001

z

y

x

Tt

t

t

M

(x’, y’, z’, w’) is the resulting position of the point at (x, y, z) after the translation.

=

'

'

'

'

w

z

y

x

11000

100

010

001

z

y

x

t

t

t

z

y

x

After the multiplication the resulting coordinates are:

z

y

x

tzz

tyy

txx

+=

+=

+=

'

'

'

Figure 19. Translation of an object by a factor tx. Each point in the object

translates the same distance.

z z

y y

x (x, y, z)

(x’, y’, z’)

TR=(tx, 0, 0)

x

Page 40: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 40(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

A coordinate system is scaled by scale factors in each of X, Y, and Z axes of the coordinate system. When scaling a point the centre of scaling lies at the origin of the coordinate system. To scale a point with the factor sx along the x-axis, sy along the y-axis and sz along the z-axis the scaling matrix Ms is used.

=

1000

000

000

000

z

y

x

Ss

s

s

M

The resulting coordinates after scaling with factor s is:

z

y

x

sz

sy

sx

=

=

=

'

'

'

Page 41: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 41(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 20. Scaling the factor s. The object does not have to be scaled

uniformly. The scaling factor for each direction has to be specified.

A coordinate system can be rotated about an axis. The rotation axis is specified with a unit vector. The rotation axis passes the origin of the coordinate system and has the same direction as the specified unit vector. The rotation angle is specified in degrees. When the rotation axis is viewed in the negative direction from the positive side, clockwise angle is positive and counter clockwise angle is negative rotation angle.

y y y y

x x x

TS=(sx, 0, 0)

x

TS=(0, sy, 0) TS=(0, 0, sz)

Page 42: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 42(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 21. In the figure the axis about which the rotation is made is pointing

towards you. When looking at the object from this direction it is the

clockwise direction that is the positive rotation direction.

The rotation matrix is different depending on which axis to rotate about. When rotating about the x-axis the following matrix is used.

−=

1000

0cossin0

0sincos0

0001

θθ

θθ

xRM

Similarly the rotation is made about the y-axis and the z-axis.

−=

1000

0cos0sin

0010

0sin0cos

θθ

θθ

yRM

z z

Rotation

+35۫ around

the z-axis

y

x

y

x

Rotation

+35۫ around

the x-axis

z

y

x

y

z

x

Rotation

+35۫ around

the y-axis

Page 43: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 43(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

=

1000

0100

00cossin

00sincos

θθ

θθ

zRM

The order of the transformations is important. If you want to rotate an object 45 ۫ around the z-axis and then translate it (10, 0, 0) it is important the rotation is being performed first, see Figure 22.

Figure 22. The figure shows the result of a rotation and a translation.

Depending on the order they are being carried out the result is different. In

the upper figures the rotation is being applied first, then the translation

along the x-axis. In the bottom figure the translation is being applied first,

then the rotation.

The reason why the result is different is that the rotation is being carried out around the origin. If the object has its centre point in the origin it is rotating around its own centre point. If the object has been translated the rotation gives another result. It is still rotating the same angle but around the origin of the world coordinate system. By using the commands for translation , scaling and rotation the transform can be created in two ways. The first way is to use the absolute methods. They have a defined order of usage. First the object is scaled, then it is rotated and finally it is translated. The functions setTranslation(gzReal dx, gzReal dy, gzReal dz), setRotation(gzVec3 targetvector, gzReal

y

x

y

x

y

x

y

x

y

x

y

x

translate

translate

rotate

rotate

Page 44: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 44(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

rotation) and setScale(gzReal sx, gzReal sy, gzReal sz) creates the following matrix independently of their order. M=MT*MR*MS so the coordinate transform is C’= M*C = MT*MR*MS*C The other way are to use relative methods like translate(gzReal dx, gzReal dy, gzReal dz),

scale(gzReal sx, gzReal sy, gzReal sz) and rotate(gzVec3 vector, gzReal rotation) in the order you want the transformations to be done. These methods and are reset by the absolute methods. The absolute methods has to be used first and then the relative methods. Otherwise the relative methods will not contribute to the transform.

gzTransform *transform = new gzTransform;

transform -> setRotation(gzVec3(1.0f, 1.0f, 0.0f), 180.0);

transform -> setTranslation(0, 0, 10);

transform -> rotate(gzVec3(0.0f, 0.0f, 0.0f), 90.0);

transform -> translate(0, 20, 10);

The example code above results in the matrix: M = t*r* MT*MR. The composed matrix after all transformations is the scene graph matrix, Ms, which is used to translate an object from local to global coordinates, see 3.1.2

Page 45: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 45(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Coordinate systems. !!! XXX Add info about base !!!!

3.1.7.1.3 Origin

It is possible to create your own origin with gzOrigin. There can be several origins placed in the same scene. Each origin has an index which makes it possible to search for an origin with a specific index.

The gzOrigin is a transformation node and also a group node. Every child of the origin is placed in a local coordinate system around with this new origin. Transformations of the child nodes are made in this local coordinate system. If an origin is added as a child to a transform the position of the origin is determined by the transform. It is also possible to scale and/or rotate the coordinate system. Since the origin also is a transform node, transformations can be made for its children. These transformations are carried out in the new local coordinate system.

gzTransform trans = new gzTransform;

trans -> setTranslation(-2, 5, -5);

trans -> setRotation(gzVec3(1, 1, 0), 20);

origin = new gzOrigin(0);

origin -> addNode(child);

origin -> addOriginAxis(); // adds origin axis

trans -> addNode(origin);

Each origin can be scaled. First the origin scaling function needs to be activated. Then it is possible to scale the local coordinate system with a specified factor. // enables the possibility to scale the origin

origin -> useOriginScale(win -> getContext(), true);

// scales the local coordinate system with the factor 2

origin -> setOriginScale(win -> getContext(), 2);

It is possible to get the global position of the coordinate system when a gzOrigin is used. By adding the origin as a child to a transform node the position of the origin given in global coordinates can be found with the function myOrigin -> getGlobalOriginPosition().

O

Page 46: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 46(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.7.1.4 Environment

To be able to add environmental effects to a scene a gzEnvironment node is created. It is possible to add light or create fog to get a more realistic environment. It is possible to add and remove light with the functions addLight (gzLight *light)

and removeLight (gzLight *light). It is possible to have several light sources in a scene. The light consists of three parts, ambient, diffuse and specular. When a light is created each of these components is specified. Each kind of light is a combination of red, green, blue and alpha. It is hard to determine the direction of ambient light since it has been scattered so much by the environment. It seems like it comes from all directions and it is also reflected in all directions. Diffuse light comes from one direction but is reflected equally in all directions. It appears to be equally bright independent of the viewing directions. Specular light comes from a specific direction and is reflected in a specific direction. For a mirror the specular component is high. The following code snippet shows how to create a light and set its color.

gzLight *light = new gzLight;

// the ambient light is red

light -> setAmbientColor (1.0f, 0.0f, 0.0f, 1.0f);

// diffuse white light

light -> setDiffuseColor (1.0f, 1.0f, 1.0f, 1.0f);

// the specular light is white

light -> setSpecularColor (1.0f, 1.0f, 1.0f, 1.0f);

light -> setPosition (0, 0, 20);

The light is reflected by material, see section 3.1.8.2 Materials.

3.1.7.1.5 Billboards

A billboard is a group transform that calculates the transform as the scene graph is rendered. If you wish to make a tree that always is facing the viewer, the billboard class can rotate this tree for you.

The following billboard types are defined… GZ_BILLBOARD_AXIS Rotates the billboard around an axis

GZ_BILLBOARD_POINT_AXIS Rotates the billboard around a point

GZ_BILLBOARD_POINT_CAMERA_UP Same as above but with billboard facing camera up

GZ_BILLBOARD_POINT_CAMERA_ORTHO Same as above but with orthogonal projection

B

E

Page 47: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 47(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

The billboards always are defined in a projective view. That means that if you are moving close to billboards they will always face the center of your viewpoint. As you can see in the picture to the right, the top view frustum has billboard orthogonal to the eye center pos. This way you can move very close to billboards and they stay aligned towards you. This is very good for trees in a forest when you move through the forest. This is most of the time the correct behavior, but sometimes you want them to be aligned orthogonal to the viewer center z axis. You should set usePlanarBillboard(TRUE) so you avoid the rotate around you when you get near to them. In the lower image to the right you can see that the billboards are orthogonal to the eye z axis (parallel with the frustrum). As you move near billboard you will see that they do not rotate around you, but on the other hand they will always preserve the z distance between them and there for they do not flicker in some cases as non planar billboard does. E.g. if you want to create a particle simulation with billboards you want to use transparency and locations very near each other. With non planar billboard you will get flickering because of the variation between render order of close particles. With planar it looks good.

Page 48: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 48(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.7.1.6 Skybox

Gizmo3D provides a simple way to create a skybox. A skybox is a box which surrounds your scene and is a simple way to create a realistic visual environment to your scene. On each side an image can be applied. Imagine a camera which takes photographs in six directions. To capture the horizon four images are required. Two further images capture the sky and ground. You can see an example of these images in Figure 23. Together these six images can form a cube which corresponds to the view in all directions from the camera’s position.

Figure 23. The images in the first row are captured in the west, north, east

and south directions. In the second row the sky and ground is captured.

With a skybox it is easy to show a realistic sky in your application. If you want a blue sky, use a skybox with pictures from a day with nice weather, if you want a depressive look to your application just add images from a rainy day. The images is set to the skybox with the function setImageSide (gzSkyBoxLocation side,

gzImage *image). The available gzSkyBoxLocations are: GZ_SKYBOX_EAST

GZ_SKYBOX_WEST

GZ_SKYBOX_SOUTH

GZ_SKYBOX_NORTH

GZ_SKYBOX_GROUND

GZ_SKYBOX_SKY

You can also get the state for each of the sides with the function getState (gzSkyBoxLocation

side) so you can alter the state parameter yourself, eg shader.

The following additional functions are available:

Page 49: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 49(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

setOrientation (gzReal heading, gzReal pitch, gzReal roll) Sets the orientation of the skybox.

setStandardHeight (gzReal height) Sets the height of the skybox

setGroundPoint (gzReal x, gzReal y, gzReal z) Specifies the position of the center of the ground side.

setHorizonAngle (gzReal angle) Specifies the angular size for the horizon.

useFixedHeight (gzBool on=FALSE)

3.1.7.1.7 Lod

The gzLod class implements the Level Of Detail (LOD) functionality necessary for large and complex scenes. The lod class switches between high detailed polygon models near the viewer to simple polygon models far away. This way, the engine does not need to render geometry far away with details that would not be visible

and therefore it can render the scene faster. Gizmo3D can use the standard discreet distance values where the switch between one level of detail is at an exact distance and the geometry is immediately changes to another level. Gizmo3D can also use a smooth blending of levels to reduce or even eliminate the visible popping of geometry. This way you can have much less detail at geometry closer to you because you will not see the discreet popping at all, but on the other hand it requires a lot more computation and in some cases when you have multiple levels of details where some levels share geometry, it can be differences in transparencies that can be visible to the user. But in general it is much better to use fading between lod levels.

L

Page 50: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 50(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

In the image above, you can hardly see the fading of the trees. The lod node is a group node. Each child to the node contains a geometry with a certain level of detail. When to change geometry is determined by the function setLOD(gzULong index, gzBool enable, gzReal min, gzReal max, gzReal fade_min , gzReal

fade_max);

The child with index index is visible when the distance between the camera and object is larger than min and smaller than max. To fade between levels the fade distances need to be defined. The object is fading away between the distance max and max+fade_max. How this is working is shown in Figure 24 and Figure 25.

Figure 24. The red and blue fields represents the time the objects is visible.

No fading is used.

minred maxred = minblue maxblue

Page 51: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 51(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 25. Since Figure 24 a fading distance is added. The switch between

the two objects now becomes smooth.

A code snippet follows which creates a lod node and adds two child which is visible at different distances. gzLod * myLod = new Lod; //Creates a lod group node

//creates two nodes and loads models gzNode * lodNode1 = gzDbManager::loadDB(filename,GZ_EVALUATE_EXTENSION);

gzNode * lodNode2 = gzDbManager::loadDB(filename2,GZ_EVALUATE_EXTENSION);

//adds the nodes as children to the lod node

myLod -> addNode(lodNode1);

myLod -> addNode(lodNode2);

//sets the properties for the lod node. The first node is visible between 0

//and 20, and the second is visible between 20 and 40. The fading between

//levels is set to zero

myLod –> setLod(0, TRUE, 0, 20);

myLod –> setLod(1, TRUE, 20, 40);

minred maxred = minblue maxblue

Page 52: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 52(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.7.1.8 Shadows

Gizmo3D uses basically a technique called shadow volumes for generating shadows. There are other techniques like flat shadows, projected shadows and shadow maps but we have chosen to start with the robust and efficient shadow volume concept. Shadow volumes are a kind of virtual volumes not visible in the scene. Objects located “inside” a volume are shadowed or affected by other effects like dimming or shading. A shadow volume is the closed volume behind an object that “contains” the shadow. The front side of the volume is the objects geometry nearest the light source. The sides are the silhouette of the visible sides of the geometry seen from the light and the back of the volume is the closed volume capping. In the image to the right you can se the shadow volume rendered in black. The front side of the volume is defined by the helix shape seen from the light in the lower left corner of the picture. The silhouette defines the sides of the volume and the front side projected some distance away from the light defines the back of the volume. The shadow volume is a close volume. The volume can be generated from the geometry (gzShadowVolumeGeometry) itself, defined by a closed gzBasicGeometry, or by a shadow depth map (gzShadowVolumeDepthMap). The shadow depth map is generated by rendering the image into a gzImageRender image and then using the depth image component to generate the closed volume. All objects located within the volume can then have an added calculation pass to add shading, blur or even umbra/penumbra effects. In the picture to the right you can see that we have added a plain black color that shows where the object is located in the shadow. By using multiple volumes in parallel it is possible to generate umbra/penumbra effects. Each volume is generated from the light position with a slight radial offset. Multiple volumes gives a very good looking output but in the same time it consumes some more fillrate from the renderer. As fillrate is becoming less important as HW gets faster we would probably see more high definition shadows in the future. The shadow volumes only need to be recomputed as the light or shadowing object moves. For static objects you can have multiple high definition shadows without much performance loss.

Page 53: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 53(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 26. The picture shows the umbra/penumbra with 4 parallel shadow

volumes used.

3.1.7.1.8.1 ShadowRenderer

The gzShadowRender is responsible for the volume rendering. Every node which is a child to the shadow render will receive a shadow. The gzShadowGenerator adds shadow generators for the scene graph. For each shadow generator there is a shadow renderer which receives the generated shadow volume. The generators is added to the node tree with the function gzShadowGenerator::addShadowGenerators (gzNode *tree, gzShadowRender *render, gzLight *light, const gzDouble &lengthFactor=5.0). The length factor determines the length of the shadow, which means how many times the distance between the light and the occluding object the shadow should be. Each light creates its own shadow. If several lights are used then one shadow generator has to be used for each light.

// Add the shadow renderer.

gzShadowRender *vol = new gzShadowRender;

// All nodes under the shadow renderer receives the shadow

vol -> addNode(environment);

// and add the shadow render to the scene

scene -> addNode(vol);

Page 54: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 54(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

// add shadow generators to all geometries under the environment node

gzShadowGenerator::addShadowGenerators(environment, vol, light, 50);

3.1.7.1.8.2 ShadowVolumeGeometry

3.1.7.1.8.3 ShadowVolumeDepthMap

3.1.7.1.8.4 ShadowVolumeGenerator

3.1.7.1.9 Frame

3.1.7.1.10 FrameKey

3.1.7.1.11 FrameTransform

Page 55: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 55(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.8 States

A state is a bunch of properties that operates recursively on a scene graph. Typical properties are Texture, TexEnv, Transparency, Shaders etc. Stuff that affect the way things are drawn. A state can enable or disable data with the function setMode(gzStateMode mode, gzStateModeActivation activation).

The gzStateModeActivation changes the state in a gzState object. The available gzStateModeActivations are: GZ_STATE_ON Enable the mode GZ_STATE_OFF Disable the mode GZ_STATE_GLOBAL Use the parent global prop. (Default) The global state is the default state used when the top hierarchy is rendered. The available state modes (gzStateMode) are the following: GZ_STATE_EMPTY

GZ_STATE_LINE_STIPPLE Enable line stipples parameters.

GZ_STATE_POLYGON_MODE Enable polygon mode parameters.

GZ_STATE_BLENDING Enable blending parameters.

GZ_STATE_TEXTURE Enable textures.

GZ_STATE_MATERIAL Enable materials.

GZ_STATE_TEXENV Enable texture environment.

GZ_STATE_TEXGEN Enable texture coord generation.

GZ_STATE_POLYGON_OFFSET Enable polygon offset.

GZ_STATE_ACTION_STAGE Set active rendering stage.

GZ_STATE_GENERATE_DEBUG_INFO Generate debug info.

GZ_STATE_ALPHA_FUNC Enable alpha func.

GZ_STATE_GFX_PROGRAM Enable GFX Programs (shaders).

When polygon mode is enabled it is possible to change the type of polygon that shall be drawn. It can be done with setFrontPolygonMode (gzPolygonModeType mode) and

setBackPolygonMode (gzPolygonModeType mode). The available polygon types (gzPolygonModeType) are: GZ_POLYGON_MODE_FILL Enable filled polygons (Default) GZ_POLYGON_MODE_LINE The polygons are drawn using lines between vertices. GZ_POLYGON_MODE_POINT The polygons are drawn using points for each vertex. GZ_POLYGON_MODE_CULL The polygons are not drawn

In RGBA mode it is possible to draw or cull a fragment of a texture depending on its alpha value. This function is called with setAlphaFunc (gzAlphaFuncFactor func, gzClampf

refValue). The incoming alpha value is compared with a reference value. The reference value is a gzClampf which is a double that is clamped to a value between 0 and 1. There are several

S

Page 56: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 56(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

alphaFuncFactors, if the comparison of the function is true then the fragment is drawn otherwise it is culled. The available gzAlphaFuncFactors are the following: GZ_ALPHA_FUNC_NEVER the fragment is never accepted

GZ_ALPHA_FUNC_ALWAYS the fragment is always accepted

GZ_ALPHA_FUNC_LESS true if fragment alpha < reference alpha

GZ_ALPHA_FUNC_LEQUAL true if fragment alpha ≤ reference alpha

GZ_ALPHA_FUNC_EQUAL true if fragment alpha = reference alpha

GZ_ALPHA_FUNC_GEQUAL true if fragment alpha ≥ reference alpha

GZ_ALPHA_FUNC_GREATER true if fragment alpha > reference alpha

GZ_ALPHA_FUNC_NOTEQUAL true if fragment alpha ≠ reference alpha

A state can also override this behavior by forcing data to be valid for all children with the function setOverride (gzStateMode mode, gzStateModeActivation activation). This way it doesn’t matter if a sibling child changes the property. One typical example is to set the state to enable line drawings instead of filled polygons so you can see a wire frame rendering of the picture. Gizmo3D can set states on all nodes and thereby enable some special optimizations e.g. set a state on a parent hierarchy and only set child state changes for children with e.g. texture.

3.1.8.1 Textures

To enable textures GZ_STATE_TEXTURE must be activated in the state. Then it is possible to change properties for the textures. The texture uses an image and applies to the geometry. The image is specified with setImage(gzImage *image). The smallest part of the texture is called texel, texture element. This corresponds to the pixel in an image. When the camera is moving and zooming in and out the size of the geometry is changed. When the object changes size the texture has to be filtered to appropriate size which can be mapped onto the object. The filter has to be specified for a texture, this is done with: gzTexture::setMagFilter( filter ) gzTexture::setMinFilter( filter ) The available filters are Magnification: GZ_TEXTURE_MAG_NEAREST

GZ_TEXTURE_MAG_LINEAR

Minification: GZ_TEXTURE_MIN_NEAREST

GZ_TEXTURE_MIN_LINEAR

GZ_TEXTURE_MIN_NEAREST_MIPMAP_NEAREST

GZ_TEXTURE_MIN_NEAREST_MIPMAP_LINEAR

GZ_TEXTURE_MIN_LINEAR_MIPMAP_NEAREST

GZ_TEXTURE_MIN_LINEAR_MIPMAP_LINEAR

Page 57: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 57(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

When using GZ_TEXTURE_MAG_NEAREST the texel with coordinates nearest the center of the pixel is used. This is the simplest and also fastest filter. With GZ_ TEXTURE_MAG_LINEAR a weighted average is used to smooth the colors. These filters are available for both magnification and minification. There are four extra filters available when minifying using mipmaps. Mipmaps are a series of pre-filtered textures with decreasing resolution. Which texture to be used is automatically decided by Gizmo3D. Only one texture has to be loaded, the smaller versions are computed by Gizmo3D. The filter GZ_ TEXTURE_MIN_NEAREST_MIPMAP_NEAREST chooses the nearest value within one individual mipmap. By using the GZ_ TEXTURE_MIN_NEAREST_MIPMAP_LINEAR filter the value within one mipmap is interpolated. GZ_ TEXTURE_MIN_LINEAR_MIPMAP_NEAREST linearly interpolate texel values between two mipmaps which are the best choices. This avoids sudden transitions. Another filter which also gives smooth transitions is GZ_TEXTURE_MIN_LINEAR_MIPMAP_LINEAR. This filter linearly interpolate values within two mipmaps and then also between these mipmaps. This method gives the best result but is also the slowest since it require heavy computations. When texture coordinates with values outside the range [0, 1] is applied there are several options of how to apply the texture to the geometry. This need to be specified in both directions for the texture, with setWrapS (gzTextureWrapMode wrap) and setWrapT

(gzTextureWrapMode wrap). The available gzTextureWrapModes are: GZ_TEXTURE_WRAP_CLAMP Texture coordinates larger than 1.0 is clamped

to 1.0 and texture coordinates smaller than 0.0 is clamped to 0.0. If the filtering method GZ_LINEAR is used the texel from the border is used in the interpolation.

GZ_TEXTURE_WRAP_REPEAT Repeats the texture over the geometry. If the

texture coordinate are between 0.0 and 3.0 the texture is repeated 3 times in each direction. If the filtering method GZ_LINEAR is used the border is ignored. The linear interpolation for the right edge is made with the texels in the left edge, and the top edge is interpolated with the bottom edge.

GZ_TEXTURE_WRAP_CLAMP_TO_EDGE If the filtering method GZ_LINEAR is used the

border is ignored.

Page 58: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 58(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

GZ_TEXTURE_WRAP_CLAMP_TO_BORDER If the filtering method GZ_NEAREST is applied, the nearest border texel is chosen for texture coordinates outside the range [0,1]. If GZ_LINEAR is used then only border texels are used for texture application. Near the edge both texels from border and texture are used.

GZ_TEXTURE_WRAP_MIRRORED_REPEAT The original and reversed texture are applied

alternately. The part of geometry with texture coordinates between [0, 1] has the original texture applied. The part with [1, 2] has a reverse texture and [2, 3] has the original texture again.

3.1.8.1.1 Texture environment

If you want the environment to affect the appearance of your geometry you can create a texture environment. The state need to have GZ_STATE_TEXENV activated if the texture environment shall be used. The Gizmo3D class for texture environment is named gzTexEnv. This class derives the final color. The method used to computing the final color is specified with setMode (gzTexEnvMode mode). The available modes are the following: GZ_TEXENV_MODE_DECAL An alpha-blending is performed between the fragment

color and RGBA texture. If a RGB texture is used the fragment color is replaced.

GZ_TEXENV_MODE_REPLACE The original fragment color is replaced with the color from the texture.

GZ_TEXENV_MODE_MODULATE The original fragment color is multiplied or modulated with the the texel color.

GZ_TEXENV_MODE_BLEND The texture value controls the mix of the incoming fragment color and a constant texture environment color.

GZ_TEXENV_MODE_ADD

GZ_TEXENV_MODE_COMBINE

When using mode GZ_TEXENV_MODE_BLEND a color is used. This color is specified with the function setBlendColor (gzFloat red, gzFloat green, gzFloat blue, gzFloat alpha).

3.1.8.1.2 3D texture

There is also a 3D texture image format available.

3.1.8.1.3 Cube map texture

Page 59: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 59(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

A special cube map format for Gizmo3D is available. A world view renderer is used to generate 6 views around an observer and store these images in a cube map texture.

3.1.8.2 Materials

To be able to use materials the GZ_STATE_MATERIAL has to be activated in the state. The material reflects light and act together with the gzLight which means that there has to be a light in the scene. To do this a gzEnvironment is required. The material state must be added to a child to the environment node. There are several kinds of light and the material specifies how the light is reflected. A green object reflects all green light and absorbs all red and blue light. If the light that falls on the ball consists of some amount green the object appears to be green since the green light is reflected. If the light is pure red and/or blue the object appears black since all red and blue is absorbed. The colors specified for the material determines the reflection of the colors. The ambient color reflects ambient light, diffuse color reflects diffuse light and specular color reflects specular light. The ambient and diffuse reflectance defines the color of the material and is normally identical or similar. The diffuse is most important when determining the color of the object. The reflection is depending on the incident diffuse light and the angle between the incoming light and the normal direction for the object. The ambient light is clearest when the object not have direct illumination. Neither diffuse nor ambient reflection is affected by the position of the viewpoint. To get highlights on the object specular reflectance is used. This effect is brightest along the direct angle of reflection which means it is dependant of the viewing position. A mirror is an example of perfect specular reflectance. The specular reflection is often white or gray which means that the specular reflection has the same color as the specular intensity of the light source. This is because white light consists of equally amounts red, green and blue light.

Figure 27. The ball in the images uses materials with different specular

reflection. The light is white. To the left the all specular light is reflected, in

the middle only the blue and to the right only red light is reflected.

The function setShininess (gzFloat shininess) specifies the size and brightness for the specular reflection. The value has to be assigned a value between [0, 128]. A higher value gives a smaller, lighter and more focused highlight. Emission color is a color that comes from the material itself. The material is has luminous paint and looks like it is glowing.

Page 60: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 60(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

How to specify the material components is shown below.

myMat -> setAmbient(1.0, 1.0, 0.0, 1.0) // 0 ≤ value ≤ 1

myMat -> setDiffuse(1.0, 1.0, 0.0, 1.0)

myMat -> setSpecular(0.0, 1.0, 0.0, 1.0)

myMat -> setEmission(0.0, 1.0, 0.0, 1.0)

myMat -> setShininess(10.0) // 0 ≤ shininess ≤ 128

When the light is acting on the material the ambient component of the light is combined with the ambient component of the material. The diffuse, specular and emission components is combined in the same way. This gives the final appearance of the object.

3.1.9 Shaders

Shaders can be used to programmatically set up the rendering pipeline. A shader is compiled into GPU assembler and executed on the GPU. A shader can be written directly in assembler or in a high level C-language. The vertex pipeline, fragment pipeline or both pipelines can be exchanged. In the future the fixed function pipeline will be replaced by predefined shaders. The class which manages shaders is called gzGFXProgram. The shader uses a program script which is specified with the function loadProgramScript (const gzString &url) to load from an URL or setProgramScript(const gzString &script) when you want to set it directly. In the case the program script fails a fallback program can be specified. The function setFallbackProgram (gzGFXProgram *program) is used. These fallbacks can be recursively specified so a chain of scripts can be defined as fallbacks. Bind attribute to vertex with the function bindVertexAttribute (const gzString &name,

gzUInt index) that is defined by a vertex attribute list in a gzGeometry. gzNode *createModel()

{

gzGeometry *geom=new gzGeometry;

gzArray<gzVec3> ircolors;

// Create a test ir color as a "heat" sample for each vertex

// as vertex attribute list number 4

ircolors.setSize(size); // Set size of ir data

gzVertexAttributeListTemplate<gzVec3> *vaList=

new gzVertexAttributeListTemplate<gzVec3>(ircolors,4);

geom->addVertexAttributeList(vaList);

Page 61: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 61(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

return geom;

}

Now the list can be bound as index 4 to a variable in the above example with bindVertexAttribute(“ircolor”,4). Set a variable which is valid only for the shader with setLocalParameter (gzUInt index, const

gzFloat &val) for indexed variables like in ARB FP/VP or setLocalParameter( const

gzString &name, const gzFloat &val) for high level shaders (GLSL or HLSL) To be able to use the shaders the mode GZ_STATE_GFX_PROGRAM has to be enabled in the state. The specific program is set with the function

state->setGFXProgram (gzGFXProgramType type, gzGFXProgram *program)

The available types are: GZ_GFX_VERTEX_PROGRAM GZ_GFX_FRAGMENT_PROGRAM

GZ_GFX_SOFTWARE_PROGRAM

GZ_GFX_GLOBAL

The code snippet below describes how to use gzGFXProgram-functions and how to set the state.

gzString vertexProgram = "glsl_PFLight.vsh";

gzString alt_vertexProgram = "PFLight.vsh";

gzGFXProgram *program_vp = new gzGFXProgram;

program_vp -> loadProgramScript(vertexProgram);

program_vp -> bindVertexAttribute("ircolor",4);

gzGFXProgram *program_vp_alt = new gzGFXProgram;

program_vp_alt -> loadProgramScript(alt_vertexProgram);

program_vp -> setFallbackProgram(program_vp_alt);

state -> setGFXProgram(GZ_GFX_VERTEX_PROGRAM,program_vp);

state -> setMode(GZ_STATE_GFX_PROGRAM,GZ_STATE_ON);

3.1.9.1 Pre defined shaders

There are a number of predefined shaders available in the API. These are shaders for phong lighting, normal maps, bump maps, gloss maps, transparency maps and specular cube maps.

3.1.10 Skinning and vertex weights

3.1.11 Custom nodes

Page 62: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 62(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.12 Boundary update

As described in 3.1.5, each node has a bounding sphere which surrounds the node and its

subtree. When you derive a node you must also make sure the boundary is updated ok. Therefore you must provide the following code snippet. virtual gzVoid updateBoundary() // Note new code since Gizmo3D 1.1 Beta 24

{

gzVec3 center(0.5,0.5,0); // Here is your own code to calculate //

the boundary sphere. E.g. in this //

case center at (0.5,0.5,0)

gzReal radius=2; // And a radius of 2

resetBoundary(); // And set it

includeBoundary(center,radius);

adjustBoundary(); // We must apply to this rule

}

3.1.13 Added node behaviors

3.1.14 Serializing

3.1.15 Intersection

It is possible to get information about the scene graph with the gzIntersector. The intersector is a ray which has a start position and a direction and seek for nodes along the ray. It is possible to get information about the first hit or all hits. The intersector search for a specific node which is specified with the function intersect

(gzNode *node, gzIntersectQuery queryType). It is possible to use several queryTypes at the same time. The following queryTypes is defined: GZ_INTERSECTOR_NEAREST_POINT Returns the first hit between the intersector and the node

GZ_INTERSECTOR_NORMAL Returns the normal of the intersected objects.

GZ_INTERSECTOR_NODE Returns the node the intersector hits.

GZ_INTERSECTOR_HISTORY The current scene graph branch history is included in the

result.

GZ_INTERSECTOR_ABC_TRI Returns the points A, B and C which builds up the intersected

triangle.

GZ_INTERSECTOR_ALL_HITS All hits along the intersector is found.

GZ_INTERSECTOR_USE_BASE_INVERSE The coordinates will be given in world coordinates when this

query type is used. Otherwise they are given in camera

coordinates. A base transform has to be specified.

Page 63: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 63(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

The start position is set with the function setStartPosition (const gzVec3 &position, gzBool

useBaseTransform) and the direction with the function setDirection (const gzVec3

&direction, gzBool useBaseTransform) The base transform is used to transform all coordinates on the screen to world coordinates. The transform is set with the function setBaseTransform (const gzMatrix4 &baseTransform) The result of the intersection is returned in an array with gzIntersectorResult. The result consists of the coordinate for the point of interaction, the coordinates for the triangle corners A, B and C, the normal of the intersected point, the intersected node and an array of scene graph branch history nodes. Which attributes in the intersector result that is assigned a value depends on the specified intersection query type. You can get the array by using the function getResult (). The following code snippet illustrates how to create an intersector, how to intersect the scene and how to get the result. gzIntersector isector;

isector.setBaseTransform(mainTransform);

isector.setStartPosition(startPosition,TRUE);

isector.setDirection(direction,TRUE);

if(isector.intersect(scene, GZ_INTERSECTOR_NODE |

GZ_INTERSECTOR_USE_BASE_INVERSE |

GZ_INTERSECTOR_NEAREST_POINT |

GZ_INTERSECTOR_HISTORY ))

{

gzVec3 vec = isector.getResult()[0].coordinate;

gzNode *isect_node = isector.getResult()[0].node;

}

3.1.16 IRMA

The Gizmo3D engine implements a special algorithm for parametric surface data to do auto Level of detail calculations. This technique provides fast rendering of smooth curved surfaces with near “infinite polygon machine” capabilities. The Algorithm is based on the ROAM approach to split and merge vertices in a patch that are aligned in a split/merge pair. Pairs that make a visible change according to some specified metrics in screen space error is split and pairs with an error smaller than some metrics are merged.

Page 64: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 64(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Irma uses a perspective metric calculation that calculates the screen space for the vertex at vc (the split position). The split error is calculated in all 3 dimensions (represented by a 3D vector). This makes the error small when looking from the top and makes it larger when looking from the side. The data is organized into two memory chunks. One tree represents the relationship between parent/children and between split pairs with indices for coordinates etc. The other tree represents the actual data with coordinate values and error metrics for the 3D split error as well as a transaction counter. More about this counter later… The idea behind a fast ROAM algorithm is to incrementally calculate the data that needs split and merges in one or more queues and then sort these queues to do a minimal update of the mesh rendering.

Left Child Right Child

L R

RL

Split

This sorting is eliminated in IRMA by using a special traversal method. The first pass traverses the tree using the transaction counter that contains information about the previous rendering pass. This information makes it possible to do “change” calculations starting from the point where it was previously rendered (the last child in the tree rendered). This special traversal makes an average calculation of screen space error for split that is linearly dependant on the number of triangles rendered in the previous pass. This pass also updates the transaction counter.

v0v1

va

vc

Original

Split

Page 65: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 65(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

The next pass checks the possible split pairs changed in the previous pass and makes an update of the transaction counter for each split child that forces its parent to be split recursively until it encounters a valid transaction counter in a higher tree location. This makes the update of the tree that is necessary to correct for the split/merge change. This operation is also linearly dependant on the number of triangles that was forced to be rendered in the previous pass. The last pass makes a uniform split/merge calculation for all triangles that shares an edge of the squared patch. This pass makes two aligned patches stitched together without cracks.

1

29

13103 6

14 1511 127 84 5

Example. Lets say that node 3,6,10,14,15 was rendered in the previous pass. The first pass starts at 3 and makes the check that 4 or 5 will not be rendered, 6 makes the check that 7 needs rendering wich implies the rendering of 8. etc. The second pass uses this information to split 11 and 12 but stops at 10 because of the updated transaction counter. The last pass checks boundary nodes 2 and 9 but both are already updated with transaction counter. Then the nodes are rendered by using the indices in the tree where the lowest child with a correct transaction counter that is valid in the tree. These produced indices are put into a buffer used in index drawing graphics. The algorithm is used by Gizmo3D for all 3D graphics that can be expressed by f(x,y,z)=g(s,t) e.g. bezier surfaces, nurbs, terrain etc. The idea is to have all future graphics represented by this feature and in combination with discrete LOD and dynamic loading make an infinite polygon machine

Page 66: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 66(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.1.17 Debugging the scene

Sometimes it is useful to view information about the scene graph such as bounding spheres or normals. To make this information visible you have to activate this function in the state. Do this with state->setMode (GZ_STATE_GENERATE_DEBUG_INFO,

GZ_STATE_ON ). Now debug information is generated. You also need to specify a debug mode using state->setDebugMode (gzStateDebugMode mode). The available debug modes are the following: GZ_STATE_DEBUG_OFF Disable debug information. GZ_STATE_DEBUG_SHOW_NORMALS Normals are visible.

GZ_STATE_DEBUG_SHOW_BSPHERE Bounding spheres is visible. GZ_STATE_DEBUG_COLLECT_STATS Collect the number of drawn primitives during the

rendering. If normals shall be shown a line is visible which shows the direction of the normal for each vertex. When bounding spheres are visible each node is surrounded by a sphere. The local coordinate system is also visible. The transform nodes are distinguished with a diamond shape in the bounding sphere. It is also possible to collect information about the scene when rendered, like number of drawn primitives. Then you can get this information from the window during the rendering. The following code snippet shows how put debug information in a string and add this string as text to the window. gzString outputString = (gzGraphicsStats(m_win->getContext()));

//m_text is of type gzText and is a child to the scene.

m_text->setText(outputString);

The following output will then be printed in the window:

----- Statistics -----

TOTAL Tri: X

Exec APP :X% (X%) LOCK :X% (X%) BNDRY :X% (X%) CULL :X% (X%) DRAW :X% (X%)

Page 67: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 67(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

TRI : X QUAD : X QUADSTRIP : X TRIFAN : X TRISTRIP : X POLY : X

POINT : X LINE : X LINESTRIP : X LINELOOP : X

TEX ACT : X SIZE : X TRANS : X

The values given in the output have the following purpose: TOTAL Tri: Defines the total number of triangles inside the viewing frustrum. APP Defines the part of the total execution time that is consumed for

application. LOCK BNDRY CULL DRAW Defines the part of the total execution time that is consumed for

drawing. TRI Specifies the number of GZ_PRIM_TRIS available in the model. QUAD Specifies the number of GZ_PRIM_QUADS in the model. QUADSTRIP Specifies the number of GZ_PRIM_QUADSTRIPS in the model. TRIFAN Specifies the number of GZ_PRIM_TRIFANS in the model. TRISTRIP Specifies the number of GZ_PRIM_TRISTRIPS in the model. POLY Specifies the number of GZ_PRIM_POLYS in the model. POINT Specifies the number of GZ_PRIM_POINTS in the model. LINE Specifies the number of GZ_PRIM_LINES in the model. LINESTRIP Specifies the number of GZ_PRIM_LINESTRIPS in the model. LINELOOP Specifies the number of GZ_PRIM_LINELOOPS in the model. TEX ACT Specifies the number of active textures SIZE The size of the used texture memory TRANS Newly transferred texture object during one pass Se part 3.1.6.1 for descriptions of the primitive types. There are methods available for performance measuring your code. See Programmers Manual for GizmoBase. A more visual way to debug the geometry is to add the gzSceneGraphDebugger to your application. The debugger Create an instace of the debugger and connect it to the scene you want to debug. To refresh the information for the debugger the command refresh() is used. There are five different views available. The hierarcy view which shows the hierarchy of the scene graph makes it possible to drag and drop nodes to new positions. The resource view shows all common resources like textures, materials etc. The property view shows the properties for a selected node and makes it possible to change coordinates, bindings, point

Page 68: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 68(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

size, line size etc. The info view prints all messages sent by the system and saves the information in a log file. When the application is terminated the log information is printed to the file “sgpv_log.txt” which is placed in the working directory. It is also possible to open the debug viewer which draws the scene graph with the debugger’s rendering context. The following code snippet shows how to use the debugger:

gzSceneGraphDebugger debugger;

debugger.setScene(m_scene);

debugger.showHierarchy();

debugger.showResource();

debugger.showProperty();

debugger.showInfo();

debugger.showViewer();

//in the onIdle method

debugger.refresh();

For more information about the views, see the SGPV programmer’s manual

3.1.18 Traversals

The node class contains the definition of virtual action methods. These methods are used in the traversal and rendering of the scene graph. If you shall make your own node it is important that you provide these methods correctly. The actual traversal methods…

virtual gzVoid preTraverseAction( gzTraverseAction *actionclass , gzContext *context) {}; virtual gzVoid postTraverseAction( gzTraverseAction *actionclass , gzContext *context){};

are called during the traversal of the scene graph. If you derive from the gzNode class you will be called in the traversal stage. If you derive from gzBaseGeometry, you will be called in a rendering stage. You can control the actual stage that you wish to use with

virtual gzActionStage useActionStage( gzTraverseAction *actionclass , gzContext *context)

The following action stages can be used… GZ_ACTION_STAGE_TRAVERSE =-1, //!< Special Traverse stage, no

rendering

Page 69: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 69(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

GZ_ACTION_STAGE_DEFAULT =3, //!< Defines the default rendering stage

GZ_ACTION_STAGE_UNDERLAY =0, //!< First stage, Scene Graph Order

GZ_ACTION_STAGE_FRONT_TO_BACK =1, //!< Sorts in depth

GZ_ACTION_STAGE_USER_1 =2, //!< User available

GZ_ACTION_STAGE_SORTED_TEXTURE =3, //!< sorts in textures

GZ_ACTION_STAGE_SORTED_NOFLIP_TEXTURE =4, //!< sorts in textures but without flip

texture order

GZ_ACTION_STAGE_MULTIPASS_TEXTURE =5, //!< additive multitexture pass

GZ_ACTION_STAGE_SCENE_GRAPH_ORDER =6, //!< renders according to scene graph order

GZ_ACTION_STAGE_USER_2 =7, //!< User avail

GZ_ACTION_STAGE_BACK_TO_FRONT =8, //!< sorts in depth with Z buffer

GZ_ACTION_STAGE_USER_3 =9, //!< User avail

GZ_ACTION_STAGE_ALPHA_SORTED_TRANSPARENCY =10, //!< sorted transparency using alpha as sort

GZ_ACTION_STAGE_SEPARATE_ALPHA_HIGHQ =11, //!< four pass, non sorted sorted transparency

using separate 4 pass alpha

GZ_ACTION_STAGE_SEPARATE_ALPHA =12, //!< two pass, non sorted sorted transparency

using separate 2 pass alpha

GZ_ACTION_STAGE_HALF_ALPHA =13, //!< three pass, non sorted sorted transparency

using 3 pass alpha

GZ_ACTION_STAGE_USER_4 =14, //!< User avail

GZ_ACTION_STAGE_SHADOWED_TRANSPARENCY =15, //!< sorted transparency in depth back to front,

shadowed

GZ_ACTION_STAGE_NO_DEPTH_UPDATE =16, //!< non sorted transparency without depth

update

GZ_ACTION_STAGE_SHADOW =17, //!< late rendering, after all normal passes

GZ_ACTION_STAGE_TRANSPARENCY =18, //!< sorted transparency in depth back to front

GZ_ACTION_STAGE_USER_5 =19, //!< User avail

GZ_ACTION_STAGE_OVERLAY =20, //!< overlay, no depth cull, Scene graph order

GZ_ACTION_STAGE_COUNT =21, //!< How many stages... dont use..

GZ_ACTION_STAGE_PRE_RENDER =22, //!< Stage in preRender

GZ_ACTION_STAGE_POST_RENDER =23, //!< Stage in postRender

If you derive from a gzGroup you will also use the traversal method

virtual gzBool isTraversable( gzTraverseAction *action , gzNode *node , gzULong index , gzContext *context )

Page 70: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 70(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

By answer a TRUE value you will acknowledge a traversal of your child with index index and node value node. By answer FALSE the traversal of that child is discarded. Most traversal nodes are derived from the gzGroup node. This way they do not need to provide the useActionStage because it is default to the traversal stage. Most rendering nodes are derived from the gzBaseGeometry. This way they will default to the sorted texture rendering stage.

Page 71: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 71(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.2 System

If you want to use the classes in the system library you need to link your project against gzsystem.lib.

3.2.1 Application

XXX gzStartUpGizmo gzShutDownGizmo

3.2.2 Windows

The gzWindow is the default rendering output. The size and position for the window on the screen can be determined with setSize(width, height) and setPosition(x, y). The window shows the image captured by the camera. The camera is set with setCamera(gzCamera

*camera). To update the contents in the window with the current camera view the method refreshWindow() is used. You can create a window as a child to an already existing window and use the existing window manager to do all the application management stuff. E.g. You can create a normal window application and just add a gzWindow as a child to the window. The only thing you must do then is to call window->refreshWindow() to get the window contents updated. You can also create a stand alone application (gzApplication, manages the window stuff in a stand alone app) and add a gzWindow to the app. This is the easiest way when you just want to create a stand-alone app without any fancy GUI. The gzApplication takes care of the messages and ticking of your application. If you have your own function for ticking the application you should not use the gzApplication. On UNIX X11 you can not create a window without a parent widget (see a X11 manual for widgets) or a gzApplication. The application will terminate without a valid parent or an application. The window contains the default camera so just call window->getCamera() to get the pointer to the camera. It also contains valid values for WindowContext, RenderContext, and DeviceContext. These values are rarely changed by the user. The window also contains a gzContext. This is a handle to the GraphicsContext where you can find a lot of interesting stuff. Advanced users can get access to all internal rendering parameters through this context.

3.2.2.1.1 Window interaction

It is easy to add some standard camera movement to a window. The arrows are used to move the viewing direction, and the keys a, z, s, x, q, and w to change the camera position.

Page 72: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 72(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 28. The keys are used to change the camera position. The viewing

direction is changed with the arrows.

A camera has to be added to the window before the input interface can be enabled. The following code snippet connects movement to the camera.

gzSimpleMouseViewControl * input = new gzSimpleMouseViewControl( theCam );

theWin -> addInputInterface( input );

If an application is used, the onIdle() method is available which is run as fast as possible. The window is updated every time the onIdle method is run. To get a smooth movement the following line is added in the onIdle method to check if any keys are pressed.

theWin -> triggerKeyEvaluation();

You can create your own movement control by subclassing the gzInputInterface and connect it as a receiver to a gzWindow (see the material example in the example dist ).

3.2.3 gzImageRender

It is possible to render the camera view to an image. Then the gzImageRender is used. Like the window it is connected to a camera and renders the camera view. The size of the image render are specified in the constructor gzImageRender (const gzWindow *contextWindow,

gzInt maxWidth=1024, gzInt maxHeight=1024). The maximum size is 1024*1024. The renderer is dependant of the camera parameters since it observes everything within the view of the camera. To the imageRenderer an image is connected with setImage(gzImage *image). The size of this image needs to be equal to or less than the size of the renderer it is connected to. The renderer is updated when the method refreshImage() is used which means it captures an image. Then the corresponding image is updated. If a Field Of View not is specified Gizmo3D sets a default view for the imageRender which is related to the screen size. If no

q w

x

s

z

a

Page 73: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 73(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

FOV is specified the resulting image will not be exactly the same as the one the corresponding window shows. gzWindow *win = new gzWindow;

gzImageRender *imageRenderer=new gzImageRender(win, 1024, 1024);

gzImage *textureImage=gzImage::createImage(GZ_IMAGE_TYPE_RGBA_8);

textureImage -> setSize(1024, 1024);

imageRenderer -> setImage(textureImage);

gzPerspCamera *cam = new gzPerspCamera();

cam -> setPosition(0, 0, 40);

cam -> setVerticalFOV(45.0f);

cam -> setHorizontalFOV(45.0f);

imageRenderer -> setCamera(cam);

win -> setCamera(cam);

.

.

.

imageRenderer -> refreshImage();

win -> refreshWindow();

3.2.4 Input

Gizmo3D makes it possible to receive input information from the mouse and keyboard. You can take care of key input by adding gzInputInterface as a base class to your class and register your interface to e.g. a gzWindow. When the key input occurs, the function onKey in your class is called. The method onKey (gzKeyValue key, gzKeyState keystate, const gzLongXY &mousePos,

const gzLongXY &centerMousePos) must be implemented if gzInputInterface is a base class to your class. The following code shows how to check if a specific key is pressed or released. gzBool myClass::onKey(gzKeyValue key, gzKeyState keystate, const gzLongXY

&mousePos, const gzLongXY

&centerMousePos)

{

switch(key)

{

Page 74: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 74(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

case “ “ :

{

//Space button is pressed

}

break;

case GZ_KEY_LBUTTON :

{

if((keystate == GZ_KEY_STATE_PRESSED))

{

//left mouse button is pressed

}

else if((keystate == GZ_KEY_STATE_RELEASED))

{

m_win->setHideMouse(FALSE);

m_win->setCaptureMouse(FALSE);

}

}

break;

}

return FALSE;

}

If FALSE is returned the key event is routed forward and other functions can also take care of the key event. Return TRUE to indicate that the key event is handled and not shall be routed forward. Add it to a provider with: addInputInterface (gzInputInterface *iface). The interface is registered in the following way:

m_win->addInputInterface(myClass);

Call the function m_win->triggerKeyEvaluation() when you want to know if a key is pressed.

3.2.5 Output

3.3 Image

For image management Gizmo3D supports a number of built in formats. It is also possible to create your own image manager. To load an image the following line is used.

gzImageManager::saveImage(save_image, "savedImage.bmp",

GZ_EVALUATE_EXTENSION);

Page 75: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 75(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Now the image save_image is saved in the file savedImage.bmp.

gzImage *image=gzImageManager::loadImage("myImage.bmp");

The line above tries to find the file “myImage.bmp” in either the local path or a path pointed out by the “GIZMO_PATH” environment variable. If the file was found, it tries to locate a “.bmp” reader by evaluating the .bmp extension. If you want the loader to use a special registered loader you can add the extension tag to the loadImage command. To be able to save and load images the image manages needs to be initialized. This is done by adding one of the lines below to your program. // initialize image managers

gzInitializeImageManagers()

// initialize both image and db managers

gzInitializeDbManagers();

If you create your own image manager this must be initialized before you can use it. If you want to use the classes in the image library you need to link your project against gzimage.lib.

Page 76: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 76(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.3.1 Supported formats

Image Formats Image File Extension

Comments

Windows Bitmap bmp Does not yet support jpeg compression

Irix rgb rgb

Irix rgb with alpha rgba

Irix black and white int

Irix black & white &alpha inta

JPEG image jpg Not yet implemented,

TIFF tif Not yet implemented.

Gizmo3D image gzi Not yet implemented.

DirectX DDS dds

Portable Network png

Performer image pfi

Table 1. The table shows the supported image formats.

3.3.2 Adding an image format

When adding a custom image format some functions needs to be implemented. These are the following:

gzImageManager_xxx();

virtual gzImage *loadImage(gzSerializeAdapter *adapter);

virtual gzBool saveImage(gzImage *image, gzSerializeAdapter *adapter);

virtual gzVoid registerManager();

In the constructor the version and extension needs to be defined.

m_version=1;

m_extension="xxx";

To load and save images a serialize adapter is used. The order of serialization is specified in loadImage and saveImage.

Page 77: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 77(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

The registerManager prints a message when the image manager is registered.

gzVoid gzImageManager_xxx::registerManager()

{

GZMESSAGE(GZ_MESSAGE_DEBUG,"Registered '%s' Image Manager version

%ld.", (const char *)m_extension, m_version);

}

Page 78: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 78(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

3.4 Database (Db)

Gizmo3D supports a number of built in formats so you can load a model from file or from an http server etc. It also supports user defined loaders and new versions of old loaders etc that can be dynamically added to the Gizmo3d format manager. To load a database you normally issue the following code snippet.

gzNode *node=gzDbManager::loadDb(“test.flt”);

This line will try to find the file “test.flt” in either the local path or a path pointed out by the “GIZMO_PATH” environment variable. If the file was found, it tries to locate a “.flt” reader by evaluating the .flt extension. If you want the loader to use a special registered loader you can add the extension tag to the loadDb command.

gzNode *node=gzDbManager::loadDb(“test.fxx”,”flt”);

The above code line will try to load the file “test.fxx” with a loader registered with the “flt” tag. When loading a database you can control some properties of the loaded data with “loader flags”. By combining the loader flags you can get multiple properties activated for a load call.

gzNode *node=gzDbManager::loadDb( “test.flt”,

GZ_EVALUATE_EXTENSION, GZ_DB_FLAGS_USE_BUFFERED_GEOMETRY|

GZ_DB_FLAGS_DISPOSE_BUFFERED_GEOMETRY);

The above line will load a “test.flt” file. Evaluate the .flt file extension to a “flt” reader and load it with “disposed buffered geometry” properties. The following flags are defined: GZ_DB_FLAGS_FLIP_DDS_IMAGES This will flip .dds images referenced by

the dataset as the .dds format is ambigious from some vendors.

GZ_DB_FLAGS_NO_CACHED_IMAGE The image will not be cached for later on usage. Normally when an image is read by a loader the image is cached so consecutive loaders will use the same

Page 79: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 79(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

instance. Sometimes you want to change path with the GIZMO_PATH environment variable to change time of year etc. Then you want to use the same name of the image but a different file.

GZ_DB_FLAGS_NO_ALTERNATE_IMAGE_EXT Gizmo3D normally tries to load alternate images when an image is not understood by the loader. E.g. a database might reference a file “test.tiff” and there is no “tiff” reader registered. In that case Gizmo3D normally want to find a “test.dds” or a “test.bmp” file. This flag disables that search.

GZ_DB_FLAGS_USE_ANIMATION This flag will tell Gizmo3D to add keyframe transforms for animations instead of static transforms in the scene graph.

GZ_DB_FLAGS_USE_MIPMAPS This flag will tell Gizmo3D to automatically enable mip maps for all loaded textures.

GZ_DB_FLAGS_USE_DYNAMIC_LOADING This flag will tell Gizmo3D to use a dynamic loader in some cases. The loader will not wait for the loading to return, but a background process will load the database.

GZ_DB_FLAGS_USE_NAME_ENCODED_NODES This flag will tell Gizmo3D to use a name encoding schema. The node names e.g. in a .3ds file will be used to create billboards, switches etc. even if the format doesn’t support them. See node name encodings.

GZ_DB_FLAGS_GENERATE_LIGHT_MATERIAL This flag will tell Gizmo3D to generate light material properties and to smooth shade the geometry (generate normals) to models that doesn’t have light material properties. This way pure geometry will look shaded under a light

Page 80: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 80(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

lamp.

GZ_DB_FLAGS_SMOOTH_BINARY_ALPHA This flag will tell Gizmo3D to smooth binary alpha. Images with nearly two distinct alpha levels will be smoothed and sorted in the normal alpha sorting pipeline. Gives better images, but lower performance.

GZ_DB_FLAGS_FAST_BINARY_ALPHA This flag will tell Gizmo3D to not use alpha blending for binary alpha images. Gives better performance but the actual “edge” of the image is non transparent.

GZ_DB_FLAGS_NO_SORT_CONT_ALPHA This flag will tell Gizmo3D to treat all alpha images as binary alpha. No sorting is done for any alpha image. The fastest way to render alpha images, but you might get anomalies where some images might exclude others even if they are transparent.

GZ_DB_FLAGS_USE_INDEXED_GEOMETRY This flag will tell Gizmo3D to create indexed geometry. Geometry with many same coordinates referenced by many triangles etc. will be faster as indexed geometry.

GZ_DB_FLAGS_USE_DISPLAYLIST_GEOMETRY This flag will tell Gizmo3D to create display lists of the geometries. The geometries are compiled into displaylists the first time. Very fast on HW that supports displaylists good .e.g. SGI HW.

GZ_DB_FLAGS_USE_BUFFERED_GEOMETRY This flag will tell Gizmo3D to use VBO (Vertex Buffer Objects) for the geometry. A very fast way to render. However the memory consumption is doubled as the geometry is stored both in CPU mem and GFX mem.

Page 81: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 81(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

GZ_DB_FLAGS_DISPOSE_BUFFERED_GEOMETRY This flag will tell Gizmo3D to dispose memory on CPU. You will not be able to read the geometry again but you will get a very fast rendering of it. Must be combined with GZ_DB_FLAGS_USE_BUFFERED_GEOMETRY

GZ_DB_FLAGS_CONVERT_IMAGES_TO_GRAYSCALE This flag will tell Gizmo3D to convert read images to grayscale. Allows view usage of imagages on low memory apps.

GZ_DB_FLAGS_COMPRESS_ON_GPU This flag will tell Gizmo3D to compress images as they are read. Converts all images to compressed formats.

GZ_DB_FLAGS_DISPOSE_TEX_IMAGE This flag will tell Gizmo3D to drop the image from CPU mem. You can not read the image after this.

GZ_DB_FLAGS_CHECK_DDS_ALPHA Normally Gizmo3D treats DXT1 as opaque, DXT3 as binary alpha and DXT5 as continious alpha. However this is not always correct. The flag enables a calculation of the image during load.

GZ_DB_FLAGS_OPTIMIZE_DB This flag auto enables the gzNodeOptimizer to run the db before returning the node handle.

To be able to load and save db formats the database format manager needs to be initialized. This is done by adding a single line to your program, see below. By adding this line all image managers also are initialized.

gzInitializeDbManagers();

If you want to use the classes in the database library you need to link your project against gzdb.lib.

3.4.1 Supported DB formats

Gizmo3D supports the following database formats:

Page 82: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 82(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Database Format Db File

Extension Comments

Performer Binary pfb No support for clipmap textures

3D Studio 3ds Can only use textures in supported image formats

VRML 97 vrl Not yet implemented. Scheduled in version 2.0

Multigen OpenFlight flt

Gizmo3D database gzd Not yet implemented. Scheduled in version 2.00

Terrapage txp

Table 2. The table shows the supported file formats for the models.

If you have suggestions, please email [email protected]. We are open to new extensions and formats.

3.4.2 Adding a new DB format

3.4.3 Node name encodings

3.4.4 Adding node types to the .gzd format

Page 83: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 83(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

4 TUTORIALS

4.1 Working with gzWindow and gzApplication

After this tutorial you will be able to create a basic scene graph and use an application to be able to view the object. Start with creating an empty workspace. Then you need to setup the correct path. In windows this is done by right-clicking on this computer → properties → advanced → environment variables. The path must point to the directory where the Gizmo3D dll-files are located. Then the properties for the project need to be set. The Gizmo3D and GizmoBase include directories has to be specified as additional include directories. The lib-directories for both Gizmo3D and GizmoBase need to be specified as additional library directories. The last to be done is to specify gzbase.lib, gzgraph.lib, gzdb, gzimage.lib and gzsystem.lib as additional dependencies. Now you can start to build your application. To include the required Gizmo-files the file gzGizmo3DLibrary.h needs to be included in the beginning of your file.

#include "gzGizmo3DLibrary.h”

The first thing to do is creating a camera. This is required to be able to view the scene. There are several different camera types available. Each camera has its own projection method. You can read more about the camera in part 3.1.3 - Using the camera.. Now let’s create a gzPerspCamera at position (0, 0, 100) with near plane at distance 2.

gzCamera *myCam = new gzPerspCamera;

myCam -> setPosition(0.0, 0.0, 100.0);

myCam -> setNearClipPlane(2);

The next thing to do is to create a window to connect to the camera. The window shows everything visible to its camera. Part 3.2.2- Windows contains information about the window. Now create a gzWindow named “My test application” and connect your camera to this.

gzWindow *myWin = new gzWindow ("My test application");

myWin->setCamera(myCam);

Page 84: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 84(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Since we are creating a stand alone application a gzApplication is useful. This is the easiest way to create an application without any fancy GUI. It takes care of everything for the user. To create a gzApplication our class has to inherit from the gzApplication class. Instantiate and start your application in the main method. The code so far is shown below.

#include "gzGizmo3DLibrary.h”

class myTestApp: public gzApplication

{

public:

myTestApp(){};

~myTestApp(){};

void Create();

void onIdle();

private:

gzRefPointer <gzWindow> myWin;

};

void myTestApp::Create()

{

gzCamera *myCam = new gzPerspCamera;

myCam -> setPosition(0.0, 0.0, 100.0);

myCam -> setNearClipPlane(2);

myWin = new gzWindow ("My test application");

myWin->setCamera(myCam);

}

void myTestApp::onIdle()

{

}

int main(int argc, char *argv[])

{

gzStartUpGizmo();

try

{

myTestApp app;

app.Create();

app.run();

}

catch(gzBaseError &error)

{

error.reportError();

Page 85: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 85(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

}

gzShutDownGizmo();

}

In the Create() method we write the code which create the scene and window. Before any gizmo code is used a graphics engine has to be specified. Use the OpenGL engine.

gzGraphicsEngine::useEngine(GZ_ENGINE_OPENGL);

From now on we write the code in the Create() method if nothing else is mentioned.

4.2 Working with the Gizmo3D scene graph

Now we have a camera, a window and an application. We just need something to observe. Let us create a scene and add the scene to the camera. The gzScene is the top node of the scene graph. You can read more about what a scene graph is in part 3.1.4 - What is a Scene Graph.

gzScene *myScene = new gzScene;

myCam -> setScene(myScene);

The application so far is illustrated with the figure below.

Figure 29. The window myWin shows what is visible to myCam. The camera

is observing myScene.

Now let’s create a geometry, see 3.1.6 - Geometry, and add to the scene. There are several different primitive types available. We will use triangles in this tutorial. The geometry will be a square created of two triangles, see Figure 30. A gzArray with coordinates needs to be specified and set to the geometry. Finally the geometry is added as a child to the scene. The geometry with coordinates and texture coordinates is shown in the figure below.

myScene

MyCam myWin

Page 86: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 86(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 30. The geometry consists of two triangles. The coordinates is given

to the left and the texture coordinates to the right.

The code added to the project is the following:

gzGeometry *myGeometry = new gzGeometry;

myGeometry -> setGeoPrimType(GZ_PRIM_TRIS);

gzArray <gzVec3> geoArray;

geoArray += gzVec3(-10, -10, 0);

geoArray += gzVec3(-10, 10, 0);

geoArray += gzVec3(10, -10, 0);

geoArray += gzVec3(10, -10, 0);

geoArray += gzVec3(-10, 10, 0);

geoArray += gzVec3(10, 10, 0);

myGeometry -> setCoordinateArray(geoArray);

.

.

.

myScene -> addNode(myGeometry);

The structure of the application have been extended as shown below.

myScene

MyCam myWin

myGeometry

(-10, -10, 0)

(-10, 10, 0)

(10, -10, 0)

(10, 10, 0)

(0, 0)

(0, 1)

(1, 0)

(1, 1)

Page 87: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 87(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 31. The scene graph is extended with myGeometry which is a child to

myScene

It is possible to move, rotate and scale the geometry. This is done with a gzTransform node which is a group node. Every child to the transformation node will be transformed in the same way. If we want to rotate is 45° around the z-axis and translate the geometry 2 units to the left a gzTransform node has to be created and myGeometry added as a child to this node.

gzTransform *myTrans = new gzTransform;

//observe the order. When using absolute transformation the order is

//independent. The transformation matrix is always calculated the same way.

myTrans -> setTranslation(-2, 0, 0);

myTrans -> setRotation(gzVec3(0.0f, 0.0f, 1.0f), 45.0);

myTrans -> addNode(myGeometry);

.

.

.

// delete the row

// myScene -> addNode(myGeometry);

myScene -> addNode(myTrans);

The application structure is now:

Figure 32. A transformation node, myTrans, is added between myScene and

myGeometry. This makes it possible to translate, scale and rotate

myGeometry.

myScene

MyCam myWin

myTrans

myGeometry

Page 88: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 88(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

When running the program a window is opened and it is possible to see a geometry which is translated and rotated.

Figure 33. The result of the tutorial so far

To make it more interesting the next task is to put a texture on the geometry. When texturing a geometry texture coordinates is required. Begin with creating a gzArray with the texture coordinates and add them to the geometry. You also need to specify how to bind the texture to the geometry, which is per vertex in this case.

gzArray <gzVec2> texCoordArray;

texCoordArray += gzVec2(0, 0);

texCoordArray += gzVec2(0, 1);

texCoordArray += gzVec2(1, 0);

texCoordArray += gzVec2(1, 0);

texCoordArray += gzVec2(0, 1);

texCoordArray += gzVec2(1, 1);

myGeometry -> setTexCoordinateArray(texCoordArray);

myGeometry -> setTexBind(GZ_BIND_PER_VERTEX);

You also need to specify which texture to use. This is done by creating a gzState. A state is used to change properties like texture, material and transparency. The state is added to a node and the properties are inherited to all children to this node until they are overridden of a new state. Create a state with texture mode enabled. Create a texture and use this. A texture requires a gzImage. Load your image, save as a gzImage and use this. Add the state to the transform node. To be able to read images the method gzInitializeDbManagers() is required in the beginning of the program.

Page 89: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 89(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

gzImage *myImage = gzImageManager::loadImage("gizmo3d.bmp");

gzTexture *myTex = new gzTexture;

myTex -> setImage(myImage);

gzState *myState = new gzState;

myState -> setMode(GZ_STATE_TEXTURE, GZ_STATE_ON );

myState -> setTexture(myTex);

myTrans -> setState(myState);

.

.

.

//into the main method

gzInitializeDbManagers();

The final application is shown in the figure below.

Figure 34. myState is added to myGeometry. This changes the property and

makes it possible to use textures, materials, transparency etc.

myScene

MyCam myWin

myTrans

myGeometry

myState

Page 90: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 90(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 35. This window is the result of this tutorial.

To extend the scene graph let us create another instance of the geometry and add to the scene. You don’t have to create a new geometry since they should look the same. Just create a transform node and add the geometry as a child. First you create a new transform. Add it as a child to the other transform node, this means that the old transformations will affect this node as well. Observe that the total rotation is 45 – 60 = 15°. The geometry is added as a child to this new transformation.

gzTransform *myNewTrans = new gzTransform;

myNewTrans -> setTranslation(2, -15, 1);

myNewTrans -> setRotation(gzVec3(0.0f, 0.0f, 1.0f), -60.0);

myNewTrans -> setScale(gzVec3(0.3, 0.3, 0.3));

myTrans -> addNode(myNewTrans);

myNewTrans -> addNode(myGeometry);

4.2.1 Creating an environment

By adding an environment it is possible to add light sources and fog. Create an environment and add it as a child to the scene. Create a point light at the position (0, 0, 10). Add it to the environment.

gzEnvironment *myEnv = new gzEnvironment;

Page 91: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 91(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

myLight = new gzLight;

myLight -> setPosition(0.0, 0.0, 10.0);

myEnv -> addLight(myLight);

myEnv -> addNode(myTrans);

myScene -> addNode(myEnv);

Now we want to change the properties for this second geometry. Observe that it is just another instance of the same object! Create a red material which makes the texture glow in red. A light is required to make the material effect visible. Create another state which has the material mode enabled. Add the state to the second transform node.

gzMaterial *myMat = new gzMaterial;

myMat->setAmbient(0.16f , 0.16f, 0.16f , 0.5f);

myMat->setSpecular(1.0f, 1.0f, 1.0f,1.0f);

myMat->setDiffuse(0.8f, 0.1f, 0.1f, 0.5f);

myMat->setEmission(0 , 0, 0, 0.5f);

myMat->setShininess(16);

gzState *myRedState = new gzState:

myRedState -> setMode(GZ_STATE_MATERIAL, GZ_STATE_ON );

myRedState -> setMaterial(myMat);

myNewTrans -> setState(myRedState);

Try to comment the line which adds the light to the environment. Now you can see why a light source has to be added to see the material. The resulting window is shown below.

Page 92: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 92(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 36. The window when the geometry is drawn at two different

positions. They have the same texture state but the geometry down in the

right corner has a red material which gives it a different appearance.

The scene graph now is extended. See below.

myScene

MyCam myWin

myTrans myState

myNewTrans

myGeometry

myEnv myLight

myRedState

Page 93: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 93(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Figure 37. The complete application. The grey circles are nodes in the scene

graph.

4.2.2 Adding a billboard

Now let’s expand the scene graph with a billboard. A billboard is a transform nod which turns the image or geometry against the user. It rotates around a specified axis and always has the same side visible. To see the behaviour of a billboard we first add some camera movement to the scene. The standard camera movement which can be added to the scene uses the arrows to move the viewing direction, and the keys a, z, s, x, q, and w to change the camera position. You can also use the mouse to change viewing direction. Press the left mouse button and move the mouse in the direction you want to look.

Figure 38. The figure shows in which direction the keys change the camera

position.

When the camera has been added to the window the following code is added to enable basic camera movement.

gzSimpleMouseViewControl * input = new gzSimpleMouseViewControl( myCam );

myWin -> addInputInterface( input );

In the onIdle() method the following line is added. This makes the movement smoother.

myWin -> triggerKeyEvaluation();

Try to navigate in the scene and understand how the movement works. Now we can create a billboard and watch how it works. A billboard node is a child to the transform node. The methods of the transform node is inherited to the billboard. Change your transform node with texture state to a billboard node. Let it have the same children as the transform node. Choose the y-axis to rotate around.

q w

x

s

z

a

Page 94: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 94(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

// Delete the row:

// gzTransform *myTrans = new gzTransform;

// and add:

gzBillboard *myTrans = new gzBillboard;

myTrans -> setAxis(gzVec3(0.0, 1.0, 0.0));

Since the billboard rotates around the axis (0, 1, 0) this means that up is along that axis. The setRotation method will have no effect. Try to rotate around other axes. To get a clearer view of the coordinate system, axes can be added to the scene.

myScene->addNode(new gzGeometryAxis(10,1, gzVec4(1.0, 1.0, 0.0, 1.0)));

The size of the axis is 10, the step is 1 which means each axis have 10 marks. The vector specifies the color.

4.2.3 Adding a lod node

It is possible to add a switch node which activates or deactivates nodes. One type of switch is the lod node. This node activates and deactivates nodes depending on the distance to a center. The default center is the origin, but it is possible to add another origin. Create a lod node and add as a child to the billboard node. Let the nodes which were children to the billboard now be children to the lod node. Specify the distances for each child. This is the distances when the child and its children are visible.

// Remove the lines:

// myTrans -> addNode(myGeometry);

// myTrans -> addNode(myNewTrans);

// and write:

gzLod *myLod = new gzLod;

myTrans -> addNode(myLod);

myLod -> addNode(myGeometry);

myLod -> addNode(myNewTrans);

myLod -> setLOD(0, true, 0, 100);

myLod -> setLOD(1, true, 100, 150);

Now, change the position of the center to see how this influences the scene graph.

myLod -> setCenter(gzVec3(0.0, 10.0, 20.0));

Page 95: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 95(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

4.2.4 Loading a model

It is possible to load a complete model of 3D Studio Max, Open Flight or TerraPage format. An flt-model is a scene graph and by importing that model it preserves the scene graph structure. Choose a model to import. Since the size of the model is unknown it is desirable to be able to scale the model. Create a transform node and add the loaded model as a child to this transform. Add transform to the scene graph as a child to the lod node. If it not is possible to cast is to a transform the model itself is added as a child to the transform. Set lod distance for the node.

gzNode *myModel = gzDbManager::loadDB("lodmodel2.3ds");

gzTransform * myLodTrans = gzDynamic_Cast<gzTransform>(myModel);

if(myLodTrans)

{

myLodTrans -> unitScale();

// scale the size with the factor 10

myLodTrans -> scale((gzReal)(10),(gzReal)(10),(gzReal)(10));

}

.

.

.

if(myLodTrans)

myLod -> addNode(myLodTrans);

else

myLod -> addNode(myModel);

myLod -> setLOD(2, true, 150, 300);

Now run the program and see what happens. There are three lod modes and you can see how the lod mode is changing when the camera is moving. You can see the final structure in the scene graph below.

Page 96: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 96(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

4.2.5 Debugging the scene

It is possible to get information from the scene. A gzLogger collects information during execution of the program, see the GizmoBase Programmers Manual. Start by instantiating a gzLogger and then run the method debug() on the node you want to get information about. The information about the node and all its children is collected in a file named “gizmosdk.log”. It is important that the message level is set to GZ_MESSAGE_DEBUG.

gzMessage::setMessageLevel(GZ_MESSAGE_DEBUG);

gzLogger logger;

myScene -> debug();

The log file for the scene above gives information about each node, its children, the transformations and states. It is complete information about the scene. Note that the .3ds model consists of several nodes and transformations which are included in the file format. The

myScene

MyCam myWin

myBillboard myState

myNewTrans

myGeometry

myEnv myLight

myRedState

axis

myLod

myModel

Page 97: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 97(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

possibility to capture the information about the complete scene is a very powerful feature in Gizmo3D. Compare the output with the graph above.

+-(gzScene):

- Node Actions -

Children count:2

|

+-(gzEnvironment):

| - Node Actions -

| Children count:1

| |

| +-(gzBillboard): (S)

| - State:0xb1e1bb8 -

| [Attrib]:99

| - Node Actions -

| Children count:1

| [H ,P ,R ]: 0.0000, 0.0000, 45.0000

| [Tx,Ty,Tz]: -2.0000, 0.0000, 0.0000

| [Matrix]: 0.7071, -0.7071, 0.0000, -2.0000

| 0.7071, 0.7071, 0.0000, 0.0000

| 0.0000, 0.0000, 1.0000, 0.0000

| 0.0000, 0.0000, 0.0000, 1.0000

| |

| +-(gzLod):

| - Node Actions -

| Children count:3

| [gzLod:Center]:(0 0 0)

| [gzLod:child (0) distance]: near_dist: 0 , far_dist 100

| [gzLod:child (1) distance]: near_dist: 100 , far_dist 150

| [gzLod:child (2) distance]: near_dist: 150 , far_dist 300

| |

| +-(gzGeometry):

| | - Node Actions -

| | [PrimType] :Tris

| | [PrimCount] :2

| |

| +-(gzTransform): (S)

| | - State:0xb1e1d48 -

| | [Attrib]:99

| | - Node Actions -

| | Children count:1

| | [H ,P ,R ]: 0.0000, 0.0000, -60.0000

| | [Tx,Ty,Tz]: 2.0000, -15.0000, 1.0000

| | [Sx,Sy,Sz]: 0.3000, 0.3000, 0.3000

| | [Matrix]: 0.1500, 0.2598, 0.0000, 2.0000

| | -0.2598, 0.1500, 0.0000, -15.0000

| | 0.0000, 0.0000, 0.3000, 1.0000

| | 0.0000, 0.0000, 0.0000, 1.0000

| | |

| | +-(gzGeometry):

| | - Node Actions -

| | [PrimType] :Tris

| | [PrimCount] :2

| |

| +-(gzTransform):lodmodel2.3ds (U)

| - Userdata -

| [Name]:UserDataDbInfo [Type]:gzUserDataAttributeContainer

| | [Attrib]:DbI-Type [Type]:str [Val]:3ds

| - Node Actions -

| Children count:4

| [Tx,Ty,Tz]: 0.0693, -0.6219, -0.0022

| [Sx,Sy,Sz]: 0.0204, 0.0204, 0.0204

| [Matrix]: 0.2040, 0.0000, 0.0000, 0.6930

| 0.0000, 0.2040, 0.0000, -6.2199

| 0.0000, 0.0000, 0.2040, -0.0221

| 0.0000, 0.0000, 0.0000, 1.0000

| |

| +-(gzTransform):Group 0

| | - Node Actions -

Page 98: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 98(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

| | Children count:1

| | [Tx,Ty,Tz]: -0.0169, 0.0000, 0.1392

| | [Matrix]: 1.0000, 0.0000, 0.0000, -0.0169

| | 0.0000, 1.0000, 0.0000, 0.0000

| | 0.0000, 0.0000, 1.0000, 0.1392

| | 0.0000, 0.0000, 0.0000, 1.0000

| | |

| | +-(gzTransform):3dsGeo

| | - Node Actions -

| | Children count:1

| | |

| | +-(gzGeometry):Cone01 (S)

| | - State:0xb25ab78 -

| | [Attrib]:99

| | - Node Actions -

| | [PrimType] :TriStrips

| | [PrimCount] :1

| |

| +-(gzTransform):Group 1

| | - Node Actions -

| | Children count:1

| | [H ,P ,R ]: -90.0000, 90.0000, 0.0000

| | [Tx,Ty,Tz]: 39.9804, 33.5988, 0.0878

| | [Matrix]: 0.0000, -1.0000, -0.0000, 39.9804

| | 0.0000, 0.0000, -1.0000, 33.5988

| | 1.0000, 0.0000,1.4805e-16, 0.0878

| | 0.0000, 0.0000, 0.0000, 1.0000

| | |

| | +-(gzTransform):3dsGeo

| | - Node Actions -

| | Children count:1

| | |

| | +-(gzGeometry):Cylinder01 (S)

| | - State:0xb2ba6c8 -

| | [Attrib]:99

| | - Node Actions -

| | [PrimType] :TriStrips

| | [PrimCount] :1

| |

| +-(gzTransform):Group 2

| | - Node Actions -

| | Children count:1

| | [H ,P ,R ]: 0.0000, 90.0000, 0.0000

| | [Tx,Ty,Tz]: 0.2761, 60.0915, -0.0241

| | [Matrix]: 1.0000, 0.0000, 0.0000, 0.2761

| | 0.0000, 0.0000, -1.0000, 60.0915

| | 0.0000, 1.0000, 0.0000, -0.0241

| | 0.0000, 0.0000, 0.0000, 1.0000

| | |

| | +-(gzTransform):3dsGeo

| | - Node Actions -

| | Children count:1

| | |

| | +-(gzGeometry):Sphere01 (S)

| | - State:0xb25a008 -

| | [Attrib]:99

| | - Node Actions -

| | [PrimType] :TriStrips

| | [PrimCount] :1

| |

| +-(gzTransform):Group 3

| - Node Actions -

| Children count:1

| [H ,P ,R ]: -1.0001, 86.9999, -90.0000

| [Tx,Ty,Tz]: -34.6622, 28.7250, -0.1582

| [Matrix]: 0.0174, 0.9998, -0.0009, -34.6622

| -0.0523, -0.0000, -0.9986, 28.7250

| -0.9984, 0.0174, 0.0523, -0.1582

| 0.0000, 0.0000, 0.0000, 1.0000

| |

| +-(gzTransform):3dsGeo

| - Node Actions -

Page 99: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 99(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

| Children count:1

| |

| +-(gzGeometry):Torus01 (S)

| - State:0xb25a530 -

| [Attrib]:99

| - Node Actions -

| [PrimType] :TriStrips

| [PrimCount] :1

|

+-(gzGeometryAxis):

- Node Actions -

[PrimType] :Lines

[PrimCount] :0

4.3 Working with shaders

This tutorial will illustrate how to work with shaders and Gizmo3D. Start with creating a new application, window and camera as described in 4.1. Change the background color for the window by adding the line

myWin -> setBackground(0.5, 0.3, 0.8);

Let the window be updated in the onIdle method. This is done by adding the line

myWin -> refreshWindow();

Create a scene and add a geometry sphere with the radius 10 as a child to the node. Let the camera observe the scene.

gzGeometrySphere *mySphere = new gzGeometrySphere(10);

gzScene *myScene = new gzScene;

myScene -> addNode(mySphere);

myCam -> setScene(myScene);

Specify the graphics engine. Use the OpenGL engine. To be able to read the shader files the method gzInitializeDbManagers() is required in the beginning of the program.

gzGraphicsEngine::useEngine(GZ_ENGINE_OPENGL);

gzInitializeDbManagers();

Now you can run the application. A basic black sphere is visible.

Page 100: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 100(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

Now we will use a shader to change the appearance of the sphere. There are two main types of shaders that are used; vertex shaders and fragment shaders. The vertex shader act on each vertex and the fragment shader acts on each fragment (pixel). Varying variables can be written by the vertex shader and read by the fragment shader. The vertex shader accesses built-in attributes, such as gl_Vertex and gl_Normal. The shaders write to different built-in variables, the vertex shader writes to gl_Position and the fragment shader writes to the gl_FragColor etc. according to the OpenGL Shading Language specification. Below follows a vertex and a fragment program. There are several types of data that is used by the shader. An attribute is used for frequently changing information (per vertex), from the application to the vertex shader. A uniform is used for infrequently changing information for vertex and fragment shaders (per gzGeometry etc.). It is set only outside the shader and can be changed at most once per primitive. The varying variable is used for interpolated information passed from a vertex shader to a fragment shader. Each shader is defined by a gzString and can be read from file or from any gzSerializeAdapter. The following file is named vertexShader.vsh. The tangent of each vertex is sent to the vertex shader as an attribute. The value is stored in the variable test which is forwarded to the fragment shader.

varying vec3 test;

attribute vec3 tangent;

void main()

{

test = tangent;

gl_Position = ftransform();

}

The fragment shader is named fragmentShader.fsh and applies the color to the geometry. The color is determined by the variable test which comes from the vertex shader.

varying vec3 test;

void main()

{

gl_FragColor = vec4(test,1);

}

Page 101: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 101(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

The tangents are used to determine color for each fragment. These are stored in a gzVertexAttributeListTemplate as shown in the code below. gzArray<gzVec3> &normals = mySphere -> getNormalArray(FALSE);

gzArray<gzVec3> tangents(normals.getSize());

for(gzULong i=0;i<tangents.getSize();i++)

{

// create sample tangent

tangents[i] = gzVec3(normals[i].v3,0,-normals[i].v1);

}

gzVertexAttributeListTemplate<gzVec3> *vaList =

new gzVertexAttributeListTemplate<gzVec3>(tangents,10);

mySphere -> addVertexAttributeList(vaList);

Create a gzGFXProgram which uses the fragment program and another which uses the vertex program. If there are any uniform variables, they have to be specified with the function setLocalParameter (const gzString &name, const gzFloat &val). The tangent attribute in the shader needs to be bound.

gzGFXProgram *vp_program = new gzGFXProgram();

vp_program -> loadProgramScript("vertexShader.vsh");

vp_program -> bindVertexAttribute("tangent",10);

gzGFXProgram *fp_program = new gzGFXProgram();

fp_program -> loadProgramScript("fragmentShader.fsh");

To be able to use the gzGFXPrograms a state with GZ_STATE_GFX_PROGRAM enabled has to be applied to the node. The shader programs which are used have to be specified.

gzState *myState = new gzState;

myState -> setMode(GZ_STATE_GFX_PROGRAM, GZ_STATE_ON);

myState -> setGFXProgram(GZ_GFX_VERTEX_PROGRAM, vp_program);

myState -> setGFXProgram(GZ_GFX_FRAGMENT_PROGRAM, fp_program);

mySphere -> setState(myState);

Now you can add some camera movement to the scene. How to do this is described in 4.2.2. When the movement is implemented you can rotate around the sphere and see how the color is changing.

Page 102: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 102(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

The result of this tutorial shown in Figure 39.

Figure 39. A sphere with color specified by shaders.

Page 103: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 103(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

5 FAQ

5.1 Scene graph

• I have problems with 3D Studio Objects. It seems that lights have no effect on them. What should I do to correct this problem?

To get the effect of lighting a material is required. A material can be added in 3D Studio Max or in a state which is added to the object node. Observe that lights not are imported from 3D Studio Max to your Gizmo3D scene. The lights have to be created and added to an environment node. The environment node is often a child to the scene. The objects in the scene which are affected of light have to be added as children to the environment.

• I have problems when drawing two overlapping faces. When they refresh the first time it draws the first face and in the second refresh the second face is drawn. This results with a blinking effect. Because of this effect in some cases I get the whole scene blinking (in the places where the objects overlap). The far I am the more noticeable it gets. Is it possible to change the order of drawing the objects (I want gizmo to draw objects in the same order so the blinking effect to be avoided)?

The result is a phenomenia called z-fighting and is due to the fact that two overlapping faces have the same equation and as the rendering order switches each frame to get higher frame rates, the flicker occurs. There is a technique called layers or offset rendering, If you add polys to a gzLayer or set the offset in a state you will be able to remove this effect as the polys will be rendered with different equations. The 3ds format doesn't support this by default, but others like OpenFlight, ets does- Soon we will have a Gizmo3D format in 3d studio and then you can use this feature automatically. meanwhile you need to add the polys to a gzLayer yourself...

5.2 Compiling

5.2.1 Linux Issues

• NA:

Page 104: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 104(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

To compile Gizmo3D on a Linux distribution you need the GNU cpp compile version 3.1 or later. The binaries are compiled on Mandrake 10.1

5.2.2 Win32 Issues

• Compiling in Visual Studio 6.0 complains about wrong msvcrt library in linker

Gizmo3D is compiled with multithreaded DLL code model. This model uses the msvcrt C library. If you compile with any other code model you will use another C library. This is not always a problem since you can tell the compiler in the project settings to ignore the library it complains about. There are though certain situations that can arise when you must use the msvcrt (multithreaded DLL release) code model. Gizmo3D uses reference management so you can rely on Gizmo3D to clean up all your allocations. If you have made an allocation (new) of a class and you tell another package ( eg. a dll) to release it for you it will probably do delete but on another heap, and the memory gets corrupt!!! Gizmo3D is implemented to have its own memory management so when you do a allocation of a class in gizmo3D is is using the Gizmo3D heap. Therefor it is generally safe to do allocations and let Gizmo3D clean up, even if you prefer another code model than msvcrt.

• Can I use Gizmo3D with MFC and how do I do then ?

You can use Gizmo3D with MFC. You can create a sample MFC project in e.g. Visual Studio. Get the handle to any MFC component and retreive the Win32 HWND handle to it (e.g. a window in your framework) and create a gzWindow with the HWND handle as parent. e.g. gzWindow *window=new gzWindow("My Gizmo Window",HWND handle);

The MFC application will then automatically integrate the Gizmo3D window with its own window management.

Page 105: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 105(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

6 LINKS

Here are some recommended links that you can take a look at http://www.gizmosdk.com The link to the GizmoSDK Web Site http://www.flipcode.com The link to a very useful gaming site http://www.opengl.org The place for 3D programmers

Page 106: gizmo3d programmers manual · C++ toolkit. It is similar to other scene graph engines such as Cosmo3D TM /OpenGL Performer TM /Inventor/VisKit/VTree TM but is a multi platform compatible

Document: Date: Document version: Page: Gizmo3D Programmers Manual 2010-03-01 2.5 106(106)

Gizmo 3D Toolkit Copyright © 2003 –Saab Training Systems AB http://www.gizmosdk.com,

email mailto:[email protected]

APPENDIX A NODE SYMBOLS

The following symbols are used when representing a node. These symbols are found in this document as well as in the SGPV, see the SGPV programmer’s manual.

T N

gzNode

T G

gzGroup

T

gzTransform

B

gzBillboard

L

gzLod

BS

gzScene

E

gzEnvironment

O

gzOrigin

Sw

gzSwitch

G

gzGeometry

P

gzParametricGeometry