Cosmo 3D™ Programmer’s Guide Document Number 007-3445-002
CONTRIBUTORS Written by George Eckel Illustrated by Dany Galgani and Martha Levine Production by Carlos Miqueo Engineering contributions by Brian Cabral, John Rohlf, Brad Grantham, Chris Tanner, Rich Silba, Tonia Spyridi, Michael Jones, Trina Roy, Chris Walker St. Peter’s Basilica image courtesy of ENEL SpA and InfoByte SpA. Disk Thrower image courtesy of Xavier Berenguer, Animatica. © 1998, Silicon Graphics, Inc.
Contents at a Glance List of Figures xxi List of Tables xxiii About This Guide xxv What This Guide Contains xxv Related Reading xxvii Who Should Read This Guide xxvii What You Should Know Before Reading This Guide Suggestions for Further Reading xxvii Style Conventions xxviii 1. 2.
Contents at a Glance 3. Specifying the Appearance of Geometries csContext Overview 35 Changing the Context 39 Using csAppearance 40 Applying Textures to Geometries 42 Material Settings 51 Shade Model Settings 53 Transparency Settings 53 4. Scene Graph Nodes 55 What Is a Node 56 Leaf Nodes 57 Group Nodes 58 Setting the Values in Scene Graph Nodes 5. 6. 7. 8.
Contents at a Glance 9. Viewing the Scene 97 Setting the Screen Display of the Scene csCamera 99 csOrthoCamera 101 csPerspCamera 101 csFrustumCamera 105 10. Scene Graph Engines 107 Engines 107 Engines that Interpolate Values 110 Engines That Change Shapes 117 11. Sensors 121 csTimeSensor 122 csSphereSensor 126 csPlaneSensor 130 csTouchSensor 134 12. User Interface Mechanisms 137 Creating a csWindow 137 Handling User Input 139 Selecting Screen Objects 140 Creating Your Own Window 143 13.
Contents at a Glance 15. Adding Sounds To Virtual Worlds 167 Overview 168 How to Play a Sound File 173 Specifying Audio Files 174 Playing Sound in Immediate Mode 177 A. Cosmo Basic Types 179 Array Storage Class Types Vector Classes 183 Bounding Volumes 187 Field Classes 188 Other Math Classes 191 B. Cosmo 3D Sample Application Cube.cxx Explained 195 Scene Graph for Cube.cxx 203 C.
Contents List of Figures xix List of Tables xxi About This Guide xxiii What This Guide Contains xxiii Related Reading xxv Who Should Read This Guide xxv What You Should Know Before Reading This Guide Suggestions for Further Reading xxv Style Conventions xxvi 1.
Contents Classes That Determine How Things Are Drawn 12 csContext 12 The csEnvironment Classes 12 Classes defining Geometric Objects 13 Steps for Creating and Displaying a Simple Scene Graph 2.
Contents 3.
Contents x 4. Scene Graph Nodes 55 What Is a Node 56 Node Types 56 Leaf Nodes 57 csShape 57 Group Nodes 58 Group Node Types 58 Using csSwitch to Switch Between Nodes 59 Using csBillboard 60 Setting the Values in Scene Graph Nodes 61 Using set() and get() Methods to Set and Get Single-Value Fields 61 Using Tokens to Set and Get Single-Value Fields 62 Using set() and get() Methods to Set and Get Multiple-Value Fields 62 Using Tokens to Set and Get Multiple-Value Fields 63 5.
Contents Transforming Shapes to New Locations, Sizes, and Orientations Placing Transform Nodes 79 Setting the Transformation 80 Ordering Transformations 81 Placing Geometries in World Space 82 Cosmo 3D Matrices 82 7. 8. 9.
Contents csOrthoCamera 101 csPerspCamera 101 Setting the Frustum 102 Setting the Clip Planes 103 Setting the Fields of View 103 Offsetting the Fields of View 103 csFrustumCamera 105 10.
Contents 11.
Contents csTouchSensor 134 Associating csTouchSensor and Geometry Scope of csTouchSensor 135 csTouchSensor Output 135 isOver Event 135 Hit Events 136 touchTime Events 136 xiv 12. User Interface Mechanisms 137 Creating a csWindow 137 Manipulating the Window Stack 138 Handling User Input 139 Using Callback Functions 139 Querying Devices 140 Selecting Screen Objects 140 Using csIsectAction 140 Using Pick() 141 Storing Selected Screen Objects 142 Creating Your Own Window 143 Sample Window Code 143 13.
Contents Back Patch Culling 152 Back Patch Culling Advantage 153 When to Use Back Patch Culling 154 Method of Calculation 154 Updating the View Vector 155 Normals 155 Choosing the Type of Normal 156 Using Back Patch Culling 157 Enabling Back Patch Culling 157 Building Back Patch Culling Data for a csGeoSet Updating Back Patch Culling Data 158 Back Patch Culling Code 159 Culling the View Frustum 160 Level of Detail Reduced for Performance 160 Choosing a Child Node Based on Range 161 Transitioning Between Le
Contents Specifying Audio Files 174 Manipulating the Audio Samples Directly 176 Example Setting a csAudioSamples Node 176 Playing Sound in Immediate Mode 177 csSoundPlayer Methods 177 A.
Contents B. C. Cosmo 3D Sample Application 193 Cube.cxx Explained 195 Understanding the Different Parts of Cube.cxx Scene Graph for Cube.
List of Figures Figure 1-1 Figure 1-2 Figure 2-1 Figure 2-2 Figure 2-3 Figure 2-4 Figure 2-5 Figure 2-6 Figure 2-7 Figure 3-1 Figure 3-2 Figure 3-3 Figure 3-4 Figure 3-5 Figure 3-6 Figure 4-1 Figure 4-2 Figure 5-1 Figure 5-2 Figure 5-3 Figure 5-4 Figure 5-5 Figure 5-6 Figure 6-1 Figure 6-2 Figure 6-3 Figure 7-1 Cube Scene Graph 8 Two Transformations into World Space 10 Primitives in a csGeoSet 18 Sequential Specification of Attributes Per Primitive 23 Indexed Attributes 24 Deciding Whether to Index Attrib
List of Figures Figure 9-1 Figure 9-2 Figure 9-3 Figure 9-4 Figure 9-5 Figure 10-1 Figure 10-2 Figure 10-3 Figure 11-1 Figure 11-2 Figure 11-3 Figure 11-4 Figure 12-1 Figure 12-2 Figure 13-1 Figure 13-2 Figure 14-1 Figure 14-2 Figure 14-3 Figure 14-4 Figure 14-5 Figure 14-6 Figure 15-1 Figure 15-2 Figure 15-3 Figure A-1 Figure B-1 Figure B-2 Figure B-3 xx Viewport 98 Aspect Ratio 99 Changing the Window Without Changing the Image’s Aspect Perspective Explained 102 Horizontal and Vertical Fields of View Of
List of Tables Table 2-1 Table 2-2 Table 2-3 Table 4-1 Table 8-1 Table 15-1 Table 15-2 Geometry Terminology 16 Fields in a csGeoSet 19 Attribute Bindings 21 Examples of Fields in Nodes 56 Fields in csFog 94 csAudioClip Fields 173 Fields of csSoundSamples 175 xxi
About This Guide Cosmo 3D is a new toolkit that brings 3D graphics programming to desktop applications. Cosmo 3D is a scene graph API; its concepts are new, but similar to concepts developed in Open Inventor, Performer, and OpenGL. This guide shows you how to develop Cosmo 3D applications. Included are descriptions of Cosmo 3D applications that you can run on your workstation, as well as code examples that you can use as a guide when developing your Cosmo 3D applications.
About This Guide • Chapter 3, “Specifying the Appearance of Geometries,” describes the appearance fields in csContext and csAppearance. • Chapter 4, “Scene Graph Nodes,” describes nodes and node types. • Chapter 5, “Building a Scene Graph,” describes how to build and edit a scene graph. • Chapter 6, “Placing Shapes in a Scene,” describes how to place shapes in scenes.
About This Guide Related Reading Reference pages for Cosmo 3D are obtained by pointing your web browser at: • For IRIX: /usr/share/Optimizer/doc/developer • For Windows: /doc/developer Where inst_dir is the directory where Optimizer was installed. The default installation location is :/Progral Files/Silicon Graphics/Optimizer. Who Should Read This Guide This guide is written for developers of OpenGL Optimizer applications.
About This Guide Style Conventions These style conventions are used in this guide: • Bold—Functions, class names, node names, data members, and data types • Italics—Variables, filenames, spatial dimensions, and commands • Regular—Program names and enumerated types Code examples are set off from the text in a fixed-space font.
Chapter 1 1. Getting Started with Cosmo 3D Cosmo 3D is a scene graph API that brings 3D graphics programming to desktop applications. Cosmo 3D speeds up and facilitates the process of creating complex graphics applications. It allows applications to use a higher-level interface than the lower-level OpenGL language that it is based on. Developers interact with C++ objects that are arranged in an object hierarchy.
Chapter 1: Getting Started with Cosmo 3D Understanding a Cosmo 3D Scene Graph A scene graph is a directed acyclical graph of nodes that embodies the semantics of what is to be drawn, but not how it is to be drawn. Developers interacting with a scene graph are interested in achieving a result, usually seeing a model on screen and manipulating it. They leave it up to Cosmo 3D to achieve this result in the most efficient way.
Scene Graph Base Classes The csObject Class The csObject class is the base class for all objects in a scene; where an object is an entity that you can place in the scene graph. A csObject provides reference counting and runtime typing for all its children. Reference Counting Many kinds of data objects in Cosmo 3D can be placed in a hierarchical scene graph. Using instancing, an object can be referenced multiple times. Scene graphs can become quite complex, which can cause problems if you’re not careful.
Chapter 1: Getting Started with Cosmo 3D Example 1-1 demonstrates how reference counts are incremented and decremented. Example 1-1 Objects and Reference Counts csAppearance *appearanceA, *appearanceC; csGeoSet *gset; csShape *shape; shape->setGeometry(0, gset); /* Attach appearanceC to gset. Reference count of appearanceC * is incremented. */ shape->setAppearance(appearanceC); /* Attach appearanceA to gset, replacing appearanceC.
Scene Graph Base Classes The csContainer Class csContainer objects contain data associated with scene graphs. The data in csContainer objects is grouped into fields (csField). Fields are not accessible directly to applications. Instead, set() and get() methods are provided to set and return field values. Each field contains either a single value of a simple data type, such as a float, or a group of values, all of simple data types.
Chapter 1: Getting Started with Cosmo 3D Single-Item and Multi-Item Fields Each field contains either a single value of a simple data type, such as a float, or a group of values, all of simple data types. • Single Item Fields—Single-valued field types, including SFDouble, SFEnum, SFRef, SFString, SFInt, SFFloat, SFVec2f, SFVec3f, SFVec4f, SFBitMask, SFName, SFMatrix4f, SFRotation.
Scene Graph Construction Classes Scene Graph Construction Classes This section discusses several essential elements of a scene graph.These elements are part of most scene graphs and make it possible for the geometry elements of a model to be drawn and to relate to one another. Figure 1-1 shows a basic scene graph similar to the example program discussed in Appendix B, “Cosmo 3D Sample Application.” Black lines indicate parent-child relationships; gray lines indicate class-field links.
Chapter 1: Getting Started with Cosmo 3D Group Transform lxf Transform xf Shape Pointlight Shape Appearance Geometry Appearance Figure 1-1 Cube Scene Graph The csGroup Class The csGroup class allows applications to group a list of csNodes. When the application then applies actions to the csGroup, the actions traverse the scene graph starting at the group-type node. The group-type node passes the action to some or all of its children.
Scene Graph Construction Classes The csTransform Class A csTransform is a csGroup that allows applications to apply a transformation to all of its children. A csTransformAction pushes down an action’s matrix stack, applies the transform to the top of the stack, visits the children, and then pop the action’s matrix stack. See “Transforming Shapes to New Locations, Sizes, and Orientations” on page 79 for more information.
Chapter 1: Getting Started with Cosmo 3D Group node Transform node Group node Transform node Leaf node Figure 1-2 10 Two Transformations into World Space
Scene Graph Construction Classes The csShape Class csShape nodes, derived from csNode, define a textured geometry by associating a csAppearance, which describes the look of a shape (such as its color), with a csGeometry, which defines the dimensions of the geometry (such as whether the geometry is a cube or sphere). The csAppearance Class A csAppearance contains fields to specify the material properties of a surface, including transparency, color, and texture.
Chapter 1: Getting Started with Cosmo 3D Classes That Determine How Things Are Drawn The set of nodes discussed in this section determines how things are drawn. • “csContext”—Maintains the OpenGL state, for example, • “The csEnvironment Classes”—Determines how lights and fog are applied to its children. csContext csContext defines the default, global graphics state of shapes in the scene graph. Shapes inherit some or all of the csContext values according to the values set in a mask.
Classes defining Geometric Objects Classes defining Geometric Objects The actual geometric objects in a Cosmo 3D scene graph are derived as follows: • As a direct subclass of csGeometry. These subclasses include csCone, csSphere, and so on. • A csGeoSet is a collection of primitives, such as points, lines, triangles, and triangle strips, that, when arranged, create a geometry. For more information, see Chapter 2, “Creating Geometries.
Chapter 1: Getting Started with Cosmo 3D 5. Add the csTransform node as a child of a csGroup-type node. For more information about adding nodes to scene graphs, see Chapter 6, “Placing Shapes in a Scene.” 6. Create a window, csWindow, in which to view the application and interact with it. 7. Set the current graphical context, csContext. 8. Draw all of the shapes in world space by applying a csDrawAction to the root of the scene graph. The root node is the csGroup-type node at the “top” of the scene graph.
Chapter 2 2. Creating Geometries csGeometry is an abstract class. All derivations of the class represent one or more geometric objects, either concrete (such as a sphere or cube) or abstract (such as geoSet). The appearance of a shape—whether a sphere is dotted or striped— is characterized by a csAppearance object, csContext object, or both. Combining a geometry with an appearance completely describes the graphic content of a rendered object.
Chapter 2: Creating Geometries Geometry Terminology Table 2-1 briefly summarizes the geometry terminology used in this manual. Understanding the key terms will help you understand the discussions of the different elements. Table 2-1 Geometry Terminology Term Description Encapsulated in Geometry An object of any form; the surface of which is uniform and non-descript. csGeometry objects or objects derived from this class. Appearance Contains all the parameters that specify csAppearance object.
Creating csGeoSet Objects Each class has methods that allow you to set and retrieve the values necessary to define the geometry, including (where appropriate) • coordinates of the center • length of the radius • height • width The names of the methods that set and retrieve these values are intuitively obvious, for example, to set and retrieve the coordinates of the center of a geometry, you use methods similar to the following: void setCenter(const csVec3f& center); void getCenter(csVec3f& center);
Chapter 2: Creating Geometries csGeoSet StripLengths PrimCoords ColorBind MormalBind TexCoordBind le1 le2 le3 . . . CoordSet ColorSet NormalSet TexCoordSet CoordIndexSet ColorIndexSet NormalIndexSet TextCoordIndexSet Figure 2-1 < x, y, z > . . . < r, g, b > . . . Primitives in a csGeoSet These attributes are captured in csGeoSet fields. 18 < nx, ny, nz > . . . < x, y, z > . . .
Creating csGeoSet Objects csGeoSet Fields The fields in a csGeoSet object can be grouped in the following manner: Table 2-2 Fields in a csGeoSet Field Default General settings short cullFace int primCount BACK 0 Attribute specifications Color colors Normal normals TexCoord texCoords Coord coords NULL NULL NULL NULL Attribute index specifications Index colorIndices Index normalIndices Index texCoordIndices Index coordIndices NULL NULL NULL NULL Attribute binding specifications char colorBind ch
Chapter 2: Creating Geometries csGeoSet Attributes csGeoSet is a virtual class from which all geometric primitives are derived. Cosmo 3D-supplied csGeoSet-derived classes include, for example: • csPointSet—A collection of equally-sized points. • csLineStripSet—A collection of linestrips, also known as polylines, of equal width. • csTriStripSet—A collection of triangle strips. • csPolySet—A collection of convex, coplanar polygons. All of the primitives within a given set are equal in size.
csGeoSet Attributes For example, a single color can be specified for the entire collection of primitives, for individual primitives, or per vertex. One set of coordinates, on the other hand, cannot be specified for the entire collection of primitives, cannot be specified for individual primitives, but must be specified per vertex.
Chapter 2: Creating Geometries The enumerated binding values that are valid for each of the attributes coincide with the entries in Table 2-3.
Setting Attributes This pattern continues, as shown in Figure 2-2. Array of csGeoSet primitives primitives primitives primitives primitives primitives . . . Figure 2-2 Array of attributes Array of color values attribute 1 color attribute 1 normal attribute 1 coord attribute 1 tex coord color value1 color value2 color value3 color value4 attribute 2 color attribute 2 normal attribute 2 coord attribute 2 tex coord . . . color value5 color value6 color value7 color value8 . . .
Chapter 2: Creating Geometries csGeoSet StripLengths PrimCoords ColorBind MormalBind TexCoordBind le1 le2 le3 . . . CoordSet ColorSet NormalSet TexCoordSet CoordIndexSet ColorIndexSet NormalIndexSet TextCoordIndexSet < x, y, z > . . . i1 i2 i3 . . . Figure 2-3 < r, g, b > . . . i1 i2 i3 . . . < nx, ny, nz > . . . i1 i2 i3 . . . < x, y, z > . . . i1 i2 i3 . . .
Setting Attributes 0 Figure 2-4 2 4 1 3 5 Deciding Whether to Index Attributes In the triangle strip, each vertex is shared by two adjoining triangles. In the square, the same vertex is shared by eight triangles. Consider the task that is required to move these vertices when, for example, morphing the object. If the vertices were not indexed, in the square, the application would have to look up and alter eight triangles to change one vertex.
Chapter 2: Creating Geometries Specifying Attributes Whether you index your attributes or not, you must use the following set...() methods in csGeoSet to specify the attributes in a specific csGeoSet object: void void void void setCoordsSet(csCoordSet* coords); setNormalsSet(csNormalSet* normals); setColorsSet(csColorSet* colors); setTexCoordsSet(csTexCoordSet* texCoords); There is a corresponding set of get...
Setting Attributes The first constructor allows you to specify the number of array primitives, n. The second constructor allows you to reference an array, *array, of attribute values, specify the offset, offset, if any, and the stride, stride. The stride mechanism that lets an application choose to keep all data staggered in a single array (or use two arrays). For example, you could combine color, vertex, and coordinate data and access each type as needed using the stride number.
Chapter 2: Creating Geometries Indexing Attributes An indexed csGeoSet object uses a list of unsigned short integers to index an attribute array. Four set...() methods in csGeoSet specify these indices: void void void void setCoordIndices(csIndexSet* coordIndices); setNormalIndices(csIndexSet* normalIndices); setColorIndices(csIndexSet* colorIndices); setTexCoordIndices(csIndexSet* texCoordIndices); There is a corresponding set of get...
Setting Attributes // Set the attribute bindings gset->setNormalBind(csGeoSet::PER_VERTEX_NORMS); gset->setColorBind(csGeoSet::PER_PRIM_COLORS); // Prepare to fill the Attribute and Indices arrays csVec3f *coords = vset->coords()->edit(); csVec3f *norms = nset->normals()->edit(); int *indices = iset->indices()->edit(); Editing Attribute Arrays Cosmo 3D allows you to modify the values in arrays using the csNormalSet3f::edit() and csNormalSet3f::editDone() methods.
Chapter 2: Creating Geometries Cosmo 3D-Derived csGeoSet Objects Cosmo 3D provides the following csGeoSet collections. Each is a derivative of csGeoSet. • csPointSet—A collection of equally-sized points. • csLineSet—A collection of lines of equal length. • csIndexedLineSet—A set of indexed line strips. • csLineStripSet—A collection of linestrips, also known as polylines. • csTriSet—A collection of triangles. • csTriFanStrip—A collection of triangles that share a common vertex.
Cosmo 3D-Derived csGeoSet Objects Using csLineSet A csLineSet object contains a collection of lines of equal length. The fields allow you to set and return the width of the lines used for drawing. void csFloat setWidth(csFloat width); getWidth(); Using csIndexedLineSet A csIndexedLineSet object contains an indexed collection of lines of equal length. The fields allow you to set and return the colors of the lines in the collection.
Chapter 2: Creating Geometries Using csTriFanSet A csTriFanSet is a set of triangles all of which share one common vertex, as shown in Figure 2-6. 3 2 4 1 5 0 Figure 2-6 TriFanSet You use the following method to retrieve or set the number of triangles in the csTriFanSet. csMFInt* fanLength() const; Using csTriStripSet A csTriStripSet object contains a collection of triangle strips. A triangle strip is a series of adjacent triangles that form a strip, as shown in Figure 2-7.
Cosmo 3D-Derived csGeoSet Objects csTriStripSet contains the following field: csMFInt* stripLength() const; This field allows you to specify and find out how long each triangle strip is in a csTriStripSet object. The length is expressed in the number of vertices per strip, for example, three tristrips with individual lengths of 4, 6, and 8, would be represented by an array of three integers: csMFInt* length = [4, 6, 8]; Using csPolySet A csPolySet object contains a collection of polygons.
Chapter 2: Creating Geometries void void void setCreaseAngle(csFloat creaseAngle); setColorPerVertex(csBool colorPerVertex); setNormalPerVertex(csBool normalPerVertex); There is a corresponding get...() method for every set...() statement. The first four fields contain arrays for storing the color. setCCW() is true if the vertices of these faces wind counter-clockwise when viewed from the front.
Chapter 3 3. Specifying the Appearance of Geometries The geometry and appearance of a shape are independent of one another. The appearance of a shape is the two-dimensional texture, such as the rind of an orange, that is mapped onto a geometry. This chapter describes how to specify the appearance of a geometry in the following sections:: • “csContext Overview” on page 35. • “Changing the Context” on page 39. • “Using csAppearance” on page 40. • “Applying Textures to Geometries” on page 42.
Chapter 3: Specifying the Appearance of Geometries There is an inheritance mask in each csAppearance that specifies which appearance values are inherited by csAppearance from csContext. csAppearance values automatically override csContext default values on a per-shape basis, regardless of the bit values in the inheritance mask. State Machine csContext maintains and manages OpenGL graphics state for the purpose of efficient graphics pipeline state control.
csContext Overview . . csAppearance *app = new csAppearance; app->setMaterial(mtl); shape->setAppearance(app); 0 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 1 0 0 0 csContext elements (Default state) Figure 3-1 CullFace Material Light enable csAppearance fields csContext elements (Current state) Inheritance Mask All 0 bits indicate that the default value is used. When you set a csAppearance value, its corresponding bit in the inheritance mask is set.
Chapter 3: Specifying the Appearance of Geometries Warning: It is critical that such a callback not alter the OpenGL state. You can avoid altering the OpenGL state either by using csContext::set() calls or by saving and restoring OpenGL state explicitly upon entry and exit of the callback. What Modifies the Graphics State? As a csDrawAction traverses the scene graph, the current state is modified when: • Appearances a their draw methods are invoked.
Changing the Context Overriding Appearances and Geometry Properties with csContext In general, csAppearance settings override csContext default values. You can, however, override csAppearance settings using csContext::pushOverrideAppearance(). Only one override appearance per context can be in place at a time. You can override some properties that are not in csAppearance and are geometry-specific through the use of pushOverrideGeoProp().
Chapter 3: Specifying the Appearance of Geometries In this example, the second context replaces the first. • display is a pointer to the X window display. • window is the GLXDrawable in which the scene is displayed. getCurrent() returns the context object on top of the context stack. csWindow has a context and calls makeCurrent() automatically. Using csAppearance csAppearance fields define the appearance of a csGeometry object, for example, its texture, material, or color.
Using csAppearance The csAppearance class includes a series of set...() methods to define the appearance characteristics of a geometry. A series of corresponding get...() methods provide access to those values. The following set...
Chapter 3: Specifying the Appearance of Geometries Applying Textures to Geometries One way to affect the appearance of a geometry is to apply a texture to it. A texture is a rectangular 2D image, for example, a 2D map of the world. This rectangular texture is scaled or repeated to fit on the surface of a 3D object, such as a sphere. The clamping and repetition of a texture over a surface is programmatically controllable.
Applying Textures to Geometries 1.0 t 0.0 Figure 3-3 s 1.0 Texture Coordinates Texture coordinates are assigned to each vertex of a geometry either by you or by Cosmo 3D. Applying a Texture To apply a texture to a geometry, set the argument of the csAppearance::setTexEnable() method to ON. If you do not want to apply a texture to a geometry, set the argument of setTexEnable() to OFF. Texture rendering uses the texture values specified in csContext by default.
Chapter 3: Specifying the Appearance of Geometries Specifying a Texture Image To apply a texture to a geometry, supply a csTexture object in the argument of setTexture(). csTexture is a class consisting of the following fields and default values: csSFString filename “noName” csMFRef imageLevel[] csSFEnum format 0 csSFEnum repeat_S REPEAT csSFEnum repeat_T REPEAT csSFEnum minFilter FAST csSFEnum magFilter FAST csSFEnum source 0 imageLevel is an array of MIPmap levels for this texture of type csImages.
Applying Textures to Geometries When you choose the NON_PERSP_TEX mode, Cosmo 3D applies the texture to a geometry without proper perspective. For example, if you apply a texture to a plane extending into the Z dimension, the pattern should not distort but just appear to recede into the distance. In NON_PERSP_TEX mode, however, the pattern is distorted, as shown in Figure 3-4.
Chapter 3: Specifying the Appearance of Geometries Texture Environment Settings Texture environment variables specify how texture colors are blended with the colors of a geometry; the texture color can replace, blend with, or subtract from the colors already on the geometry.
Applying Textures to Geometries Color Components A texture image can have up to four components per texture element: • A one-component image consists of a luminance value, Lt. One-component textures are often referred to as intensity maps. For example, an image of a statue could use polygons of different intensities to shade and provide detail. • A two-component image consists of luminance, Lt, and transparency, At.
Chapter 3: Specifying the Appearance of Geometries Specifying Texture Coordinates There are two ways to specify how a texture is applied to a geometry: • Use the default. Cosmo 3D applies textures to geometries according to the geometry. • Use the texture coordinate function, setTexGen(). Using the Default Cosmo 3D applies textures to geometries according to the geometry. For all geometries subclassed from csGeometry, Cosmo 3D • Computes the bounding box.
Applying Textures to Geometries The setTexGen() method specifies • Whether or not the texture plane is repeated across the geometry. • Whether the texture plane is stationary or moves in concert with the motion of the geometry. The setTexGen() method takes a csTexGen object for an argument. In a csTexGen object, you set the • Repetition of the texture image in three dimensions, s, t, and r. • Mode of the texture in each of the dimensions. For example, csTexGen::setPlaneS(2.
Chapter 3: Specifying the Appearance of Geometries Setting the csTexGen Mode If you think of the texture plane as being projected onto the surface of a geometry rather than being on the surface of a geometry, it is easy to understand how the mode settings in csTexGen work. Either the plane is stationary and the geometry moves “under” it or the plane moves in concert with the geometry.
Material Settings Material Settings The material field in csAppearance defines the surface qualities of a geometry, such as how well it reflects light, what color it reflects, and what color it emits. The material field is of type csMaterial, which has the following set...
Chapter 3: Specifying the Appearance of Geometries Shininess describes how much of the surroundings are reflected by an object, for example, a mirror would have a large shininess value so that surrounding objects would be seen in it. Values range from 0.0, for a very dull surface, to 1.0, for a highly polished surface. The default value is 0.2. Transparency describes how opaque or clear an object is, for example, water might be more clear than opaque. Values range from 0.0, for opaque, to 1.
Shade Model Settings Shade Model Settings You set the shading model using the setShadeModel() method with one of the following csContext::ShadeModelEnum values as its argument: FLAT_SHADE Each primitive, geometric polygon that comprises a geometry has the same shade value. This option has the effect of making the primitive geometric polygons visible. SMOOTH_SHADE Shade values are interpolated across primitive geometric polygons. This option makes the primitive polygons look more like a curved surface.
Chapter 3: Specifying the Appearance of Geometries To use the setAlphaFunc() method, you first set the reference value against which you measure the alpha value of the pixel to be drawn using setAlphaRef(), for example setAlphaRef(10); Then you supply, as an argument to setAlphaFunc(), one of the values of csContext::AlphaFuncEnum: • NEVER_AFUNC • LESS_AFUNC • EQUAL_AFUNC • LEQUAL_AFUNC • GREATER_AFUNC • NOTEQUAL_AFUNC • GEQUAL_AFUNC • ALWAYS_AFUNC For example, the following code setAlphaR
Chapter 4 4. Scene Graph Nodes A node is an object that can be part of or entirely comprise a scene graph. Typically, a node is a collection of one or more fields and methods that together perform a specific function, for example, a csShape node encapsulates all information about the shape and appearance of a geometry. Cosmo 3D nodes are divided into two types: • group—associate other nodes. • leaf— contain rendering information. This chapter describes nodes and node types.
Chapter 4: Scene Graph Nodes What Is a Node A node is a collection of one or more fields and methods. Each field is a C++ class with data members and methods that get and set those member values. The fields set a variety of parameters. For example, some of the fields in the csGeoSet are summarized in Table 4-1. Table 4-1 Examples of Fields in Nodes Field Type Fields Description SFRef COORDS Is a csCoordSet containing vertex coordinates.
Leaf Nodes Leaf Nodes Leaf nodes are responsible for defining the visual and aural elements portrayed in a scene. Leaf nodes cannot have child nodes. The following list shows all of the different types of Cosmo 3D leaf nodes; all are derivatives of csLeaf. • csShape—associates a csGeometry object with a csAppearance object. • csLight—is an abstract base class for light sources. • csDirectionalLight—is a directional light source whose origin is at infinity.
Chapter 4: Scene Graph Nodes Group Nodes Group nodes associate other nodes into a hierarchy known as a scene graph. Only group nodes can have children. A group node, for example, might associate two csShape nodes, as shown in Figure 4-1. Group node csShape node csShape node Figure 4-1 A Simple Grouping Actions, such as a draw action, applied to a group node may be applied in no particular order to some or all of its children. A group node, then, defines the scope of an action.
Group Nodes • csLOD—(level-of-detail) is a switch that selects one of its children based on the distance between the camera and the shape encapsulated by the csLOD; the closer the shape, the greater the detail used when rendering the shape, the farther away the shape, the less detailed the shape. For more information, see Chapter 14, “Optimizing Rendering.” • csTransform—positions and orients a shape in the coordinate system of the parent node to csTransform.
Chapter 4: Scene Graph Nodes Using csBillboard csBillboard is a subclass of csGroup. It is used to rotate its children to face the viewer at all times. csBillboard has the following fields: csMFRef children (inherited from csGroup) csEnum mode csMFVec3f position csVec3f axis The mode field specifies one of three billboard modes: AXIAL, POINT_SCREEN, and POINT_OBJECT. The mode defines how the billboard’s children should be rotated to face the viewer.
Setting the Values in Scene Graph Nodes Setting the Values in Scene Graph Nodes Cosmo 3D allows you to set the values for nodes in two ways: either using the set() method in each of the node’s fields, or by using tokens. Setting the fields is different depending on whether or not the variable has a single or multiple value. If the variable has a single value, the variable can be set directly; if it has multiple values, the particular value in the set of values must be specified, as shown in Figure 4-2.
Chapter 4: Scene Graph Nodes Using Tokens to Set and Get Single-Value Fields To use tokens to set or get single-value fields, you 1. Get a handle to the field specified by the token. 2. Use the handle to set or get the field. For example: F = mtl->getField(SHININESS); F->set(ShininessValue); ShininessValue = F->get(); F->get(c); ShininessValue is a float. The first line of code returns a handle, F, to the shininess field. The second line then sets the value of that field.
Setting the Values in Scene Graph Nodes Using Tokens to Set and Get Multiple-Value Fields To use tokens to set or get multiple-value fields, you 1. Get a handle to the field specified by the token. 2. Use the handle to set or get values from a specific variable in the field.
Chapter 5 5. Building a Scene Graph A scene graph can be a single node or a hierarchy of nodes, as shown in Figure 5-1. Root myFog myShape myLight Figure 5-1 Scene Graph The hierarchy specifies the order in which the nodes are acted upon when an action is applied to the scene graph. The hierarchy is established by the order in which the group nodes are added to the branches in a scene graph branch. This chapter describes how to build and edit a scene graph.
Chapter 5: Building a Scene Graph This chapter includes the following sections: • “Creating Scene Graphs” on page 66. • “Diagramming Scene Graphs” on page 69. • “Altering Scene Graphs” on page 73. • “Loading a VRML Scene Graph” on page 74. • “Saving Scene Graphs” on page 75. • “Troubleshooting Scene Graph Construction” on page 75. Creating Scene Graphs The top node in a scene graph is called the root node; it must be a group-type node.
Creating Scene Graphs Figure 5-2 Multiple Root Nodes Applying Actions to Multiple Root Nodes If a scene graph has multiple root nodes, an action applied to one of the roots would only traverse the descendants of the specific root node. While this hierarchy of nodes is legal, if your application is going to draw both scene graphs anyway, you should create a single root node common to both scene graphs.
Chapter 5: Building a Scene Graph Creating A Sample Scene Graph Example 5-1 is a simple scene graph.
Diagramming Scene Graphs Diagramming Scene Graphs Diagramming a scene graph is helpful in visualizing the structure of a Cosmo 3D application. Figure 5-3 shows a diagram representing the scene graph coded in Example 5-1. Root myFog myShape myLight Figure 5-3 Simple Scene Graph In diagrams of scene graphs, circles represent nodes and lines represent the node hierarchy.
Chapter 5: Building a Scene Graph For more information about the order in which nodes are acted upon, see “The Order In Which Actions Are Passed Between Nodes” on page 86. There are no rules for constructing a scene graph, however, it is customary to organize it in the following way: • Reading the nodes left to right shows you the different geometries rendered in a scene graph. • Reading the nodes from top to bottom shows you the different parts that are combined to form a larger geometry.
Diagramming Scene Graphs In the subgraph shown in Figure 5-5, you can see that the foot, leg, and torso nodes are parts which, when rendered together, display the lower half of a body. Torso node Leg node Leg node Foot node Foot node Figure 5-5 Torso Subgraph Because the left leg looks different from the right leg, you need two different shape nodes.
Chapter 5: Building a Scene Graph Root node transforn location 2 transforn location 1 Cube Figure 5-6 Showing the Same Geometry in Two Locations In this example, the scene graph makes it easy to see that a cube is rendered in two locations by two csTransform nodes.
Altering Scene Graphs Altering Scene Graphs After using csGroup::addChild() to create a scene graph, you can use the following methods to edit it: void int int void removeChild(int i); removeChild(csNode *node); replaceChild(csNode *old, csNode *node); insertChild(int i, csNode *node); These methods allow you to remove, replace, or insert a child node, respectively.
Chapter 5: Building a Scene Graph Loading a VRML Scene Graph Example 5-2 shows a portion of vrml.cxx. The example illustrates how to load a VRML scene graph using vlDB::readFile(). Example 5-2 csGroup Loading a VRML Scene Graph *vrml = new csGroup; for (int i=1; i
Saving Scene Graphs Saving Scene Graphs The data in the scene graph database is not necessarily static. You might, therefore, need to save scene graph data into a file. To do so, you use the following method: csGlobal::storeFile(NameOfFile, *dataStructure); where NameOfFile is the name of the file where you want to store the data and dataStructure is the Cosmo 3D in-memory data structure to store. The method returns TRUE if the file is stored successfully, FALSE otherwise.
Chapter 6 6. Placing Shapes in a Scene When you create a geometry, it has a specified size, location, and orientation, as defined in its own space. You place such a geometry • In relationship to other shapes in the same scene. • Into the coordinate system of the root node, known as world space. This chapter describes how to perform each of those tasks. The final transformation that affects the view of the user is that created with the camera.
Chapter 6: Placing Shapes in a Scene Overriding the Default Order of Layering Shapes To override this layering effect, you can use the csContext::setcsDepthFunc() method; it determines the layering order of geometries in a scene according to values in the Z dimension. To specify a layering method, use one of the tokens in csContext::DepthFuncEnum.
Transforming Shapes to New Locations, Sizes, and Orientations Transforming Shapes to New Locations, Sizes, and Orientations The csTransform node • Allows you to specify vertex coordinates of a shape in local space, using (0, 0, 0) as the origin. • Translates the local coordinates into the coordinates of its parent node.
Chapter 6: Placing Shapes in a Scene Setting the Transformation The csTransform node allows you to set the location (translation), rotation, and scale of its children using the following methods: void setTranslation(const csVec3f& translation); void setTranslation(csFloat v0, csFloat v1, csFloat v2); void setRotation(const csRotation& rotation); void setRotation(csFloat v0, csFloat v1, csFloat v2, csFloat v3); void setScale(const csVec3f& scale); void setScale(csFloat v0, csFloat v1, csFloat v2); void setS
Transforming Shapes to New Locations, Sizes, and Orientations z z Figure 6-2 y y x x Scaling in Different Orientations All of these methods invisibly set a transformation matrix to carry out their actions. If you want to set the matrix directly, you can use the setMatrix() method. Ordering Transformations The order in which you perform transformations can effect the final result. Take, for example, translating and rotating a model.
Chapter 6: Placing Shapes in a Scene When you reverse the order of the transformations, the end result is different. Since the center of rotation is the origin, the rotation transformation lifts the object above the X axis. Placing Geometries in World Space Multiple transformation nodes can orient and size all shapes in a scene graph into the space of the root node. The space of the root node is called world space.
Chapter 7 7. Traversing the Scene Graph Once you create a scene graph, you apply an action to the root node to trigger the events prescribed in the scene graph nodes. Most nodes include an overwritten apply() method that triggers an appropriate response when a specific action is applied to the node. Actions include rendering the scene (draw action) and playing sound files (sound action). This chapter describes how an action traverses a scene graph and the actions available in Cosmo 3D.
Chapter 7: Traversing the Scene Graph The action-specific responses taken by a node are implemented in the following node functions: • draw()—for csDrawAction • isect()—for csIsectAction • compile()—for csCompileAction • sound()—for csSoundAction When an action operates on one node after another, the action is said to be traversing the scene graph. Action Types In Cosmo 3D, there are four kinds of actions: • csDrawAction—Renders a scene graph. • csIsectAction—Selects objects intersecting a ray.
Scene Graph Actions You invoke an action by creating an instance of an action class and applying it to a node (commonly the root node), for example: csGroup* rootNode = new csGroup; ... csDrawAction* renderAction = new csDrawAction; renderAction->apply(rootNode); In this example, a draw action, renderAction, is applied to the root node, rootNode, of a scene graph. When an action is applied to a node, each kind of node responds in its own way.
Chapter 7: Traversing the Scene Graph Playing Sound Files csSoundAction plays sound files. The csSound node indirectly specifies—through csAudioClip and csAudioSamples nodes—the sound file to play. The csSoundAction places the listener (referred to as the microphone in Cosmo 3D) relative to the sound source for spatial effects, such as volume based on the proximity of the listener to the sound source.
The Order In Which Actions Are Passed Between Nodes Root node 1 10 9 7 6 8 2 4 3 5 Figure 7-1 The Flow of an Action Through A Scene Graph A top-down traversal means that a node can never affect a node “above” it. For example, node 3 in Figure 7-1 cannot affect nodes 4 and 5, however, node 4 can affect node 5. So, that branch of the scene graph is traversed in the following way when an action is applied to the root node: 1. The action traverses from node 1 to any of its children. 2.
Chapter 8 8. Lighting and Fog This chapter discusses two features implemented by subclasses of csEnvironment, lighting and fog. • Lights illuminate shapes in a scene. Without lights, shapes are not visible. To limit the range of a light, such as limiting the rays of a light to the room it is in, you include the lights in the light array in csEnvironment. • Fog makes an image appear more natural by fading objects in the distance. You include fog in csEnvironment.
Chapter 8: Lighting and Fog csLight csLight is an abstract base class for light sources. It provides the following methods for setting light values: void void void void void setOn(csBool on); setIntensity(csFloat intensity); setAmbientIntensity(csFloat ambientIntensity); setColor(const csVec3f& color); setColor(csFloat v0, csFloat v1, csFloat v2); There is a corresponding set of get...() methods that return each of the light settings. setOn() turns on the csLight object.
Using Lights in Scenes csSpotLight csSpotLight is a directional light source. Because csSpotLight is subclassed from csPointLight, csSpotLight can be positioned.
Chapter 8: Lighting and Fog Limiting the Scope of Lights csEnvironment defines the scope of environmental effects, such as how far light from a csLight object can travel. When you create a virtual room, the goal is to make a lamp in the room shine in the room only—not leak through walls into the hallway. When you make a csLight part of the light array in csEnvironment, the lamp light stops at the walls of the room. Another application of csEnvironment is rendering headlights on a car.
Using Fog in Scenes // add the lights to the environment light array park->light()->append(3, spot); park->light()->append(4, flood); Using Fog in Scenes Fog is generated by setting up a csFog node and adding it to the csEnvironment. This fog description will affect all children of the csEnvironment. Subsequent csFog nodes will override the current fog description. Fog should also be globally enabled via csContext::setFogEnable() and can be overridden with csAppearance::setFogEnable().
Chapter 8: Lighting and Fog All types of geometric primitives can be fogged, including points and lines. Using the fog effect on points and lines is also called depth-cuing and is popular in molecular modeling and other applications. How to Use Fog in Cosmo 3D Applications Fog is generated by setting up a csFog node and adding it to the csEnvironment.
Using Fog in Scenes In general whoever is OFF has precedence. • If csContext::fogEnable is OFF, no fog is drawn unless there is a csAppearance that has fogEnable ON. In this case, fog is enabled for that shape only if it is within the scope of a fog node that is turned on (that is, under a csEnvironment that has fog enabled). • If the csFog node is OFF, there will be no fog drawn in any circumstances, even if the fogEnable in the csAppearance or csContext is TRUE.
Chapter 9 9. Viewing the Scene To view a scene, you must define: • The size of the viewport. • The position and the orientation of the camera. This chapter describes how to set up the viewport and how to use cameras to view a scene. This chapter has the following sections: • “Setting the Screen Display of the Scene” on page 97. • “Using a Camera to View a Scene” on page 98. Setting the Screen Display of the Scene The viewport is the rectangular portal through which you view a scene.
Chapter 9: Viewing the Scene Monitor screen Window Viewport Scene Figure 9-1 Viewport You set the size of the viewport using the following csContext method: static void setViewport(csInt x, csInt y, csInt w, csInt h); x and y are the coordinates of the lower, left corner of the viewport (where the lower, left corner of the csWindow is (0. 0)). w and h are the width and height of the viewport.
csCamera csCamera csCamera is an abstract base class from which all other cameras are derived. csCamera defines the viewing volume. The viewing volume is bounded by the camera’s origin and orientation, the far clip plane, and an aspect ratio. The aspect ratio is defined as the image’s width divided by its height, as shown in Figure 9-2.
Chapter 9: Viewing the Scene Figure 9-3 Changing the Window Without Changing the Image’s Aspect It is important, therefore, to change the aspect of the image if the window is revised. To do that, you use csWindow, as explained in Chapter 12, “User Interface Mechanisms.” The aspect ratio can be set through methods of csOrthoCamera and csPerspCamera. The following methods set the position and orientation of a camera.
csOrthoCamera csOrthoCamera csOrthoCamera defines an orthographic projection. An orthographic projection uses a parallelepiped (box) frustum. Unlike the frustum in Figure 9-2, the size of the frustum does not change from one end to the other. For this reason, the distance from the camera to an object in the frustum does not affect the size of the object. You use this type of camera when you do not want to view objects in perspective.
Chapter 9: Viewing the Scene Figure 9-4 Perspective Explained If you compare the height of an object in the near clipping plane to the height of the near clipping plane, you see that the ratio is larger than the ratio of the height of the same object in the far clipping plane to the height of the far clipping plane. Hobject -------Hnear Hobject > -------Hfar Consequently, when you compare the size of the object to its surroundings, it appears smaller in the distance.
csPerspCamera Setting the Clip Planes You use the following fields to set the distance to the near and far clip planes: void setNearClip(csFloat nearClip); void setFarClip(csFloat farClip); There is a corresponding get...() field for each set...() field. Setting the Fields of View You use the following fields to set the horizontal and vertical fields of view (FOV) of the frustum. The arguments are the angles, in degrees, of the fields of view.
Chapter 9: Viewing the Scene Far clip plane Near clip plane y y Horizontal FOV Vertical FOV -z -x -z -x Vertical FOV offset Horizontal FOV offset x z -y Figure 9-5 z x -y Horizontal and Vertical Fields of View Offsets The offset angles are measured starting at the -z axis, following the right-hand rule. For example, the horizontal FOV offset angle shown in Figure 9-5 is positive.
csFrustumCamera csFrustumCamera csFrustumCamera allows you to work directly with a frustum without worrying about the specifics of a camera. You define the frustum using the csFrustumCamera’s only method: setFrustum(csFrustum * frustum) For a definition of csFrustum, see csGeoMath.h.
Chapter 10 10. Scene Graph Engines There are classes that work with scene graphs, but are not nodes; they cannot be part of the scene graph, but they serve the vital function of enabling animation. csEngine is such a class. This chapter describes csEngine and the multiple subclasses derived from it. These are the sections in this chapter: • “Engines” on page 107. • “Engines that Interpolate Values” on page 110. • “Engines That Change Shapes” on page 117.
Chapter 10: Scene Graph Engines Input and Output Fields csEngine has input and output fields. csEngine updates its output fields according to the function carried out by the csEngine. For example, a simple engine might take two inputs and output the average of the two. csEngine updates its output fields only under the following conditions: • Output fields are read. • Input fields have changed since the output fields were last read.
Engines Engine Types Many engines interpolate between two values at specified increments. For example, a rotation interpolator might take the beginning and ending rotation coordinates and the incremental changes between the two. Its output might be a series of transformations that move an object through a series of coordinates that rotate it from the beginning to the ending coordinates. Another example for using an engine is color cycling.
Chapter 10: Scene Graph Engines csInterpolator is the base class for the following engines: • csColorInterpolator • csCoordinateInterpolator • csNormalInterpolator • csOrientationInterpolator • csPositionInterpolator • csScalarInterpolator The following csEngines can be used to change the features of a shape: • csMorphVec—produces a weighted sum of attribute sets. Derived classes include csMorphVec3f and csMorphVec4f.
Engines that Interpolate Values Interpolator nodes are designed for linear, keyframed animation, that is, an interpolator node defines a piecewise linear function, f(k), on the interval [-∞, ∞]. The piecewise linear function is defined by n keys and n corresponding key values, f(k). The keys must be monotonic and non-decreasing. An interpolator node evaluates f(k) given any value of k.
Chapter 10: Scene Graph Engines csInterpolator Fields The fields in csInterpolator include: void float setFraction(float fraction); getFraction(); csMFFloat* key(); For an explanation of key() and setFraction(), see, “Interpolator Engine Terminology” on page 111. csSpline A csSpline takes an array of keys as its input and outputs a set of weights. A key is one or more pieces of data; a weight is a fractional scaling factor. How the output is weighted depends on the order of the spline.
Engines that Interpolate Values Keys and Key Values In Figure 10-3, the X axis represents keys, such as time, and the Y axis represents any attribute or set of attributes, such as location, color, or transparency. Y axis values are called key values. Notice that the interval between the key values is nonuniform. After setting the key values, csSpline fills in the values between the key values. The difference between the piecewise linear and cubic splines is created by the different weight factors.
Chapter 10: Scene Graph Engines csColorInterpolator This node interpolates among a set of key values in a csMFColor to produce a csSFColor (RGB) color. csColorInterpolator contains the following fields: csMFVec3f* csSFVec3f keyValue() const; value keyValue() is the set of RGB color values over which you want to interpolate. The number of colors in the keyValue() field must be equal to the number of keyframes in the key field.
Engines that Interpolate Values When P and Q are pointed in opposite directions, they are on opposite sides of the unit sphere, and therefore all arcs connecting them on the unit sphere are the same length, so an infinite number of arcs describe the shortest path between the two points. The interpolation can be along any one of these arcs. csNormalInterpolator contains the following fields: csMFVec3f* csMFVec3f keyValue() const; value keyValue() contains the vectors used for the normal interpolation.
Chapter 10: Scene Graph Engines csPositionInterpolator csPositionInterpolator linearly interpolates between sets of values in a SFVec3f. This is appropriate for interpolating a translation. The vectors are interpreted as absolute positions in local space. The keyValue field must contain exactly as many values as in the key field.
Engines That Change Shapes csSelectorEng3F and csSelectorEng4F csSelectorEng3F and csSelectorEng4F sets the output value to the nth item in the input array where n is the value of selector.
Chapter 10: Scene Graph Engines csMorphEng Fields csMorphEng contains the following fields: csMFInt* csMFInt* csMFFloat* count() const; index() const; weight() const; count() is an array of integer values. Each value represents the number of input values which will be morphed based on the corresponding weight value. If the value of count() is positive, the next coordinate is chosen by dereferencing and incrementing the input array pointer.
Engines That Change Shapes Example 10-1 Building a Morph Engine: the Worm // Build morph engine MorphCoords = new csMorphEng3f; // “Neutral” is non-indexed and always has weight of 1 MorphCoords->input()->setRange(0, NumRings*RingVerts, coords); MorphCoords->count()->set(0, NumRings*RingVerts); MorphCoords->weight()->set(0, 1.0f); // build the coordinate vectors for the rings on the worm for (k=0,i=0; i
Chapter 10: Scene Graph Engines csTransformEng Fields csTransformEng has the following fields: void TransformTypeEnum setTransformType(TransformTypeEnum transformType); getTransformType(); csMFInt* csMFInt* csMFMatrix4f* count() const; index() const; matrix() const; transformType() specifies the input data type. If the transformType() value is • POINT—the input is interpreted as points with a homogeneous value of 1.0. • VECTOR—the input is interpreted as vectors with a homogeneous value of 0.
Chapter 11 11. Sensors Sensors are used to detect one of the following: • Time passing. • Pointer device events. Sensors are often implemented to perform one of the following tasks: • Trigger an engine at a specified interval (csTimeSensor). This task is most commonly used to animate geometries. • Generate rotations based on pointer device events (csSphereSensor). • Generate translations based on pointer device events (csPlaneSensor).
Chapter 11: Sensors csTimeSensor csTimeSensor generates timer events either once or repeatedly for a specified interval. A csTimeSensor is typically used to drive animations or periodic events.
csTimeSensor Updating csTimeSensor csTimeSensors are not automatically evaluated. The following method triggers the evaluation of all instantiated csTimeSensors: csTimeSensor::updateSensors(); This method should be called at regular intervals, usually once per frame, for csTimeSensors to function as expected. Updating with csWindow By default, if there are instantiated csTimeSensors, csWindow calls csTimeSensor::updateSensors() at regular intervals; the default interval is 16 milliseconds.
Chapter 11: Sensors You can, for example, trigger events based on the time of day using csTime::getTimeOfDay(), which returns the current time of day. Your application can then determine whether or not that time falls between startTime and stopTime.
csTimeSensor Continuing Timer Events csTimeSensor::loop() takes a boolean value. If it is TRUE, the csTimeSensor continues to generate events after the completion of one cycle. If the boolean value is FALSE, csTimeSensor only generates events for a single cycle. The following two methods are used to get and set the value of loop(): csTimeSensor::getLoop(); csTimeSensor::setLoop(); Cycle Time Event A csTimeSensor generates a cycleTime event whenever the csTimeSensor begins a new cycle.
Chapter 11: Sensors csSphereSensor csSphereSensor maps the drag motion of a pointer device into a spherical rotation about a virtual sphere. The rotation gives the impression that the geometry is attached to the surface of a spinning sphere. Virtual Sphere The center of the virtual sphere is located at the center of either the local or world coordinate system, based on whether the argument of csSphereSensor::coordFrame() is LOCAL or WORLD, respectively.
csSphereSensor csSphereSensor Events A csSphereSensor begins generating events when both of the following conditions are met: • The pointer device cursor is depressed over geometry associated with a csSphereSensor. • csSphereSensors are updated to determine whether the pointer device cursor is depressed while over a geometry associated with a csSphereSensor. While the csSphereSensor is active, it generates rotation and trackPoint events.
Chapter 11: Sensors Updating csSphereSensor csSphereSensor is not updated automatically. You customarily update it explicitly when pointer device events are detected, using one of the following methods: csSphereSensor::updateSensors(); csWindow::updateSensors(); The difference between the methods is that the arguments to the csSphereSensor version includes pointer device coordinates. Note: csSphereSensor inherits updateSensors() from its abstract, base class, csPickSensor.
csSphereSensor csGroup csTransform csSphereSensor csShape csShape Figure 11-2 Placing csSphereSensor in a Scene Graph A csSphereSensor is activated when the pointer device is depressed over its associated geometry. However, its output events, rotation and trackPoint, can be connected to any field in a scene graph. The effects of csSphereSensor, therefore, are not limited to its associated geometry.
Chapter 11: Sensors csPlaneSensor A csPlaneSensor maps the drag motion of a pointer device’s events into a translation in the XY plane of the local or world coordinate space, depending on the value specified by csPlaneSensor::coordFrame(). Setting Up csPlaneSensor A typical use of csPlaneSensor is to connect its output event, translation, to a transformation node.
csPlaneSensor csGroup csTransform csPlaneSensor csShape csShape Figure 11-3 Placing csPlaneSensor in a Scene Graph Scope of csPlaneSensor A csPlaneSensor translates all geometries in the scene graph “below” the parent node of the csPlaneSensor. A csPlaneSensor is activated when the pointer device is depressed over its associated geometry. However, its output events, translation and trackPoint, can be connected to any field in a scene graph.
Chapter 11: Sensors Updating csPlaneSensor csPlaneSensor is not updated automatically. You customarily update it explicitly when pointer device events are detected, using one of the following methods: csPlaneSensor::updateSensors(); csWindow::updateSensors(); The difference between the methods is that the csPlaneSensor version includes pointer device coordinates. Note: csPlaneSensor inherits updateSensors() from the abstract, base class, csPickSensor.
csPlaneSensor TrackPoint events represent unclamped drag positions of the geometry in the XY plane of local or world space, depending on the value set in csPlaneSensor::setCoordFrame().
Chapter 11: Sensors csTouchSensor csTouchSensor tracks the location of the pointer device cursor and generates up to five outputs when the cursor is over the geometry associated with csTouchSensor. If the pointer device cursor passes over multiple geometry, events are generated based on the geometry nearest the camera. Associating csTouchSensor and Geometry A geometry is associated with a csTouchSensor when the geometry and csTouchSensor nodes are descendants of the same node, as shown in Figure 11-4.
csTouchSensor Scope of csTouchSensor A csTouchSensor monitors all geometries in the scene graph “below” the parent node of the csTouchSensor. Not only does it monitor the children of csTouchSensor’s parent node, it also monitors all the descendants of the children.
Chapter 11: Sensors Hit Events csTouchSensor generates the following three hit events whenever the pointing device is over a geometry associated with a csTouchSensor: • hitPoint—represents the coordinates where the pointer device cursor intersects the geometry. • hitNormal—represents the surface normal vector where the pointer device cursor intersects the geometry. • hitTexCoord—represents the surface texture coordinates where the pointer device cursor intersects the geometry.
Chapter 12 12. User Interface Mechanisms Cosmo 3D applications either appear within a csWindow object or a window object that you create using X window code. The window provides an interface for users to interact with the Cosmo 3D application. Cosmo 3D also supports user interaction by enabling the selection of screen objects. This chapter discusses how to implement user interaction using X window code, csWindow, and selection mechanisms.
Chapter 12: User Interface Mechanisms To reposition or reshape the window after its initial display, use the following methods: static void static void positionWindow(int x, int y); reshapeWindow(int width, int height); To specify the title of the window or its icon, use the following methods: static void static void setWindowTitle(const char *title); setIconTitle(const char *title); Note: If the title is NULL, the window has no borders, except on the PC.
Handling User Input Handling User Input Events, such as mouse motion, key presses, and window resize, are converted to csEvent objects and queued on their associated csWindow. When the application is ready to process these events the getEvents() method of each csWindow can be called to get the array of queued csEvent’s. After processing the events, the event array should be discarded by calling the window’s resetEvents() method.
Chapter 12: User Interface Mechanisms When csWindow::setFreeRun() is TRUE, callbacks are invoked only when the main loop goes idle, similar to the CONTINUE mode. Otherwise, callbacks occur with every event but nothing happens when the main loop is idle. With the either of these event callback mechanisms, the event information, returned by getEvents(), is extracted from the csEvent objects. The application, however, does not need to call resetEvents(); it is called automatically.
Selecting Screen Objects S Figure 12-1 csPickPoints Ray Pick Action The shape closest to the origin of the csSeg and intersected by the line segment is recorded in a csHit object. For information about csHit, see “Storing Selected Screen Objects” on page 142. Using Pick() csCamera::pick() uses window and viewport coordinates to select the screen object closest to the ray connecting the camera to the point.
Chapter 12: User Interface Mechanisms Storing Selected Screen Objects csHit objects hold pointers to objects selected using a variety of mechanisms. The methods in csHit allow you to access the information held by csHit, including: 142 • The index number, geomPartNumber, of the triangle, quadrilateral, or polygon inside a csGeoSet. • The csGeometry that was intersected. • The csShape that was intersected. • The normal in local space at the intersection point.
Creating Your Own Window Creating Your Own Window Instead of using the window provided by Cosmo 3D, csWindow, you can create your own window using X11 or WIN32 window code. In this case your application controls the csContext, events, and window, as shown in Figure 12-2. Application X Windows csEvent Window csContext GLXContext Figure 12-2 Creating Your Own Window Sample Window Code For sample code that shows you how to create your own window, see the demonstration programs, cubex.cxx and cubew32.
Chapter 13 13. Multiprocessing If you would like to display two views of the same scene graph, you need to use the multiprocessing capabilities of Cosmo 3D. You might, for example, like to display a ground-view and an over-head view of the same scene at the same time. You can accomplish this by creating a thread for each view and connecting each to their own csWindow and csContext, as shown in Figure 13-1.
Chapter 13: Multiprocessing Implementing Multiprocessing One rule that you must follow when implementing multiprocessing is the scene graph cannot be modified during rendering. Cosmo 3D does not provide a mechanism for concurrent scene graph modification and drawing. The consequence of this rule is that you must implement semaphores to block the action of the application or draw threads. Note: OpenGL Optimizer provides the semaphore class, opBarrier.
Implementing Multiprocessing To create a thread and bind it appropriately, use the following procedure: 1. Create a thread, as follows: csThread* drawThread = new csThread(drawThreadEntry, NULL); 2.
Chapter 13: Multiprocessing Thread Parameters Thread-related parameters include the following csThread methods: • numProcessors()—returns the number of usable processors on the system. • setStackSize()—sets the stack size to be used for this thread when it starts. Exiting Threads A thread only terminates execution when it calls csThread::exit() on itself. Cosmo 3D does not support termination of threads by other threads.
Thread Blocking Application Draw threads thread sce Mo ne dify gra ph imaDraw ge Draw barrier Swap barrier Figure 13-2 sce Mo ne dify gra ph imaDraw ge Ti me Blocking Action of Multiple Threads The general order of events displayed in Figure 13-2 is as follows: 1. The application and draw threads are created and initialized. 2. The draw threads try to render but are stopped. 3. The application thread modifies the scene graph. 4. The scene graph is cleaned using csField::cleanFields(). 5.
Chapter 13: Multiprocessing Cleaning the csContext Fields Before rendering, the application thread must call csField::cleanFields() to clean the csContext fields. This method forces the evaluation of all fields that have been dirty, thereby circumventing the normal lazy evaluation of field values. Generally, in Cosmo 3D, fields are updated only when queried. To use this method, tracking of dirty fields must be enabled.
Chapter 14 14. Optimizing Rendering One of the greatest challenges developers face is optimizing application performance. This chapter describes the Cosmo 3D nodes and programming techniques that can help optimize your application’s performance. The more vertices calculated and rendered, the slower the application’s performance. If you can reduce calculations and rendering, you can improve application performance.
Chapter 14: Optimizing Rendering Face Culling When solid, three-dimensional geometry is rendered, the side of it facing away from the camera is normally hidden by the side that faces the camera. For example, when a sphere is rendered, you normally only see its front side.
Back Patch Culling Figure 14-1 shows the same geometry before and after back patch culling. Figure 14-1 Before and After Back Patch Culling Back Patch Culling Advantage Back patch culling occurs before the primitives are processed by the graphics pipeline. As a result, back patch culling off-loads some of the graphics pipeline work to the CPU, yielding an added degree of parallelism between the two processors.
Chapter 14: Optimizing Rendering Back patch culling usually reduces the work done by the graphics hardware but it does increase the workload of the host. Performance is enhanced when the time spent performing back patch culling is roughly equal to the time spent processing culled triangles in the graphics hardware. When to Use Back Patch Culling Back patch culling is most effective when: • The primitives are composed of many elements.
Back Patch Culling Updating the View Vector As long as you use csDrawAction::apply() to initiate the back patch culling, you never need to calculate the view vector. If you need greater control over the Draw process and use csDrawAction::draw(), you need to update the view vector using csDrawAction::updateViewVector(). csDrawAction::getViewVector() returns the view vector. Normals Two types of normals can be used to calculate the viewing angle: • Face normal—the normal to the surface of an element.
Chapter 14: Optimizing Rendering 2 1 0 0 2 Normal goes into page Figure 14-4 1 Normal comes out of page Direction of Normals Choosing the Type of Normal The csGeoSet method, setBPCullVertNormModeEnable(), sets the type of normal used to calculate the viewing angle: if the argument to the method evaluates TRUE, primitive normals are used, if the argument evaluates FALSE, face normals are used.
Back Patch Culling Face normals are used by default with the following primitive types: • csPolySet • csQuadSet • csTriFanSet • csTriSet • csTriStripSet If normals are not provided for a csGeoSet and the primitive normal mode is enabled, the csGeoSet is never back patch culled. Using Back Patch Culling There are two steps you take to implement back patch culling: • Enable back patch culling. • Build back patch culling data.
Chapter 14: Optimizing Rendering Building Back Patch Culling Data for a csGeoSet Before calling a csDrawAction, which triggers back patch culling, you must first build back patch culling data for the csGeoSets of the scene. You only need to call csGeoSet::buildBPCullData() once; afterwards, the data can be automatically recomputed. If back patch data does not exist for a csGeoSet, nothing is culled by back patch culling.
Back Patch Culling Back Patch Culling Code Now that you understand all the facets of back patch culling, Example 14-1 presents the series of calls your application must make to implement back patch culling. Example 14-1 Implementing Back Face Culling // Create a draw action. csDrawAction *drawAction = new csDrawAction; ... // Set the back patch culling mode. drawAction->setBPCullMode(csDrawAction::DRAW_FRONT_FACING); // Build scene graph. csNode *scene = new csNode; ...
Chapter 14: Optimizing Rendering Culling the View Frustum View frustum culling eliminates from the rendering list all of those shapes not in the viewing frustum. View frustum culling works best if the objects in a csGroup node are close together, for example, all of the nodes representing a body are linearly hierarchical. When this is the case, the CULL process only needs to visit the top of the body subgraph.
Level of Detail Reduced for Performance csLOD allows you to reach a compromise between performance and the level of detail rendered. For high quality images, a shape close to the camera should be rendered in high detail. When a shape recedes from the camera, the same level of detail is not necessary. Reducing the level of image detail reduces the number of vertices required to render a shape, which results in improved performance. OpenGL Optimizer can create the csLOD child nodes.
Chapter 14: Optimizing Rendering The camera may disregard range values and • Display an already-fetched level of detail while a higher level of detail is downloaded from disk. • Adjust the level of detail displayed to maintain a constant frame rate; this is always the case if you leave the range() field empty. • Disregard the range values for any other implementation-dependent reason.
Performance Programming Techniques Performance Programming Techniques The following sections provide programming tips for improving the performance of your application: • “Minimize Use of csAppearance Fields” on page 163. • “Minimize Use of csAppearance Modes” on page 163. • “Indexing csGeoSet Attributes” on page 164. • “Setting the Transformation Matrix Directly” on page 164. • “Compiling Part of a Scene Graph” on page 164.
Chapter 14: Optimizing Rendering Indexing csGeoSet Attributes You can specify the appearance of all the csGeoSet elements making up a geometry either individually or collectively. You have the option of specifying the attribute values sequentially, so that the first element is described by the first csAttribute values or you can use an index system. Choosing to index the attribute values (or not) can dramatically affect application performance.
Performance Programming Techniques Torso node Leg node Leg node Foot node Foot node Figure 14-6 Arranging Scene Graph Nodes When an action traverses a scene graph, the more nodes it visits, the longer it takes to execute the action. If scene graph branches are deep, the traversal can become expensive. To correct this problem, if you find that the elements in a branch do not change often, you can precompile that branch using csCompileAction.
Chapter 15 15. Adding Sounds To Virtual Worlds You can incorporate sound into your virtual worlds by including at least one csSound node in a scene graph and by invoking a csSoundAction. The csSoundAction plays the sound file specified in the csSound node. This node also includes parameters, such as volume, for playing the sound. This chapter describes how to set and play sound using Cosmo 3D. These are the sections in this chapter: • “Overview” on page 168. • “How to Play a Sound File” on page 173.
Chapter 15: Adding Sounds To Virtual Worlds Overview A csSound node contains the location of a sound file and the parameters used for playing it. To play a sound file in a virtual world, attach one or more csSound objects to a scene graph and apply a csSoundAction to it. To associate a specific sound to a specific shape, make the csSound object and shape nodes children of the same group nodes.
Overview csSound Fields The fields in csSound specify the sound source to play by specifying a csAudioClip object. csSound can optionally specify the location, the direction of the sound, and the spatial characteristics of the sound.
Chapter 15: Adding Sounds To Virtual Worlds To choose a starting location in a sound file, pass the starting frame to the setCurrentFrame() field. A frame is equal to (1/SampleRate) of a second. The sample rate might be, for example, 44KHz, or 44,000 Hz. If, for example, you pass 44000.0 into the setCurrentFrame() field, the sound would begin playing one second (44000 × 1/44000 = 1) into the sound file. Sound Priority Your application can play only a limited number of sounds at the same time.
So un d di re ct io n Overview Minimum forward sound intensity perimeter Sound source Maximum forward sound intensity perimeter Figure 15-2 Sound Direction In this figure, (1.0, 1.0, 0.0) is passed as the direction vector to setDirection(). The ellipse tips, accordingly, at a 45 degree angle. Note: A transformation node can reorient the sound’s location and direction.
Chapter 15: Adding Sounds To Virtual Worlds Outside of the maximum intensity perimeter, the intensity of the sound attenuates over distance until it reaches the minimum intensity perimeter. Beyond the minimum intensity perimeter, the volume of the sound source is constant, defined by the setCullIntensity() field.
How to Play a Sound File How to Play a Sound File You use csAudioClip to specify how to play the sound files referenced in the csAudioSamples node.
Chapter 15: Adding Sounds To Virtual Worlds Table 15-1 (continued) csAudioClip Fields Field Description getDuration Returns the duration of the playing of the sound source; subtracts setStartTime from setStopTime. getIsActive Returns whether or not the sound should be played. Example 15-1 sets all of the fields in a csAudioSamples node.
Specifying Audio Files csAudioSamples has the following fields: void void void void void void void void LoadStatusEnum csMFByte* setFileName(const csString& fileName); setNumFrames(csInt numFrames); setSampleRate(csFloat sampleRate); setSampleSize(csInt sampleSize); setSampleType(SampleTypeEnum sampleType); setNumChannels(csInt numChannels); setSampleScale(csFloat scale); setLoadStatus(LoadStatusEnum loadStatus); getLoadStatus(); samples() const; These set() fields have corresponding get() fields.
Chapter 15: Adding Sounds To Virtual Worlds Manipulating the Audio Samples Directly csAudioSample::samples() returns the multivalued array field that contains the actual audio samples. This handle allows you to directly manipulate the array field.
Playing Sound in Immediate Mode Playing Sound in Immediate Mode When a csSoundAction is invoked on a scene graph, the action traverses the scene graph and gathers a list of active csSound nodes. The action notifies csContext internally of this list of nodes. When the context is applied to the rendering pipeline, the sounds specified in the associated csAudioSamples nodes are played. You can also play a sound file immediately.
Chapter 15 15. Adding Sounds To Virtual Worlds You can incorporate sound into your virtual worlds by including at least one csSound node in a scene graph and by invoking a csSoundAction. The csSoundAction plays the sound file specified in the csSound node. This node also includes parameters, such as volume, for playing the sound. This chapter describes how to set and play sound using Cosmo 3D. These are the sections in this chapter: • “Overview” on page 168. • “How to Play a Sound File” on page 173.
Chapter 15: Adding Sounds To Virtual Worlds Overview A csSound node contains the location of a sound file and the parameters used for playing it. To play a sound file in a virtual world, attach one or more csSound objects to a scene graph and apply a csSoundAction to it. To associate a specific sound to a specific shape, make the csSound object and shape nodes children of the same group nodes.
Overview csSound Fields The fields in csSound specify the sound source to play by specifying a csAudioClip object. csSound can optionally specify the location, the direction of the sound, and the spatial characteristics of the sound.
Chapter 15: Adding Sounds To Virtual Worlds To choose a starting location in a sound file, pass the starting frame to the setCurrentFrame() field. A frame is equal to (1/SampleRate) of a second. The sample rate might be, for example, 44KHz, or 44,000 Hz. If, for example, you pass 44000.0 into the setCurrentFrame() field, the sound would begin playing one second (44000 × 1/44000 = 1) into the sound file. Sound Priority Your application can play only a limited number of sounds at the same time.
So un d di re ct io n Overview Minimum forward sound intensity perimeter Sound source Maximum forward sound intensity perimeter Figure 15-2 Sound Direction In this figure, (1.0, 1.0, 0.0) is passed as the direction vector to setDirection(). The ellipse tips, accordingly, at a 45 degree angle. Note: A transformation node can reorient the sound’s location and direction.
Chapter 15: Adding Sounds To Virtual Worlds Outside of the maximum intensity perimeter, the intensity of the sound attenuates over distance until it reaches the minimum intensity perimeter. Beyond the minimum intensity perimeter, the volume of the sound source is constant, defined by the setCullIntensity() field.
How to Play a Sound File How to Play a Sound File You use csAudioClip to specify how to play the sound files referenced in the csAudioSamples node.
Chapter 15: Adding Sounds To Virtual Worlds Table 15-1 (continued) csAudioClip Fields Field Description getDuration Returns the duration of the playing of the sound source; subtracts setStartTime from setStopTime. getIsActive Returns whether or not the sound should be played. Example 15-1 sets all of the fields in a csAudioSamples node.
Specifying Audio Files csAudioSamples has the following fields: void void void void void void void void LoadStatusEnum csMFByte* setFileName(const csString& fileName); setNumFrames(csInt numFrames); setSampleRate(csFloat sampleRate); setSampleSize(csInt sampleSize); setSampleType(SampleTypeEnum sampleType); setNumChannels(csInt numChannels); setSampleScale(csFloat scale); setLoadStatus(LoadStatusEnum loadStatus); getLoadStatus(); samples() const; These set() fields have corresponding get() fields.
Chapter 15: Adding Sounds To Virtual Worlds Manipulating the Audio Samples Directly csAudioSample::samples() returns the multivalued array field that contains the actual audio samples. This handle allows you to directly manipulate the array field.
Playing Sound in Immediate Mode Playing Sound in Immediate Mode When a csSoundAction is invoked on a scene graph, the action traverses the scene graph and gathers a list of active csSound nodes. The action notifies csContext internally of this list of nodes. When the context is applied to the rendering pipeline, the sounds specified in the associated csAudioSamples nodes are played. You can also play a sound file immediately.
Appendix A A. Cosmo Basic Types This chapter discusses all of the basic types that are used in other Cosmo 3D classes. The basic class types fall into the following categories: • Array storage—stores data. • Vector classes—stores vectors. • Bounding shapes—creates a volume around a specified shape. • Field classes—specifies the classes for the node fields: single value. • Other math classes—miscellaneous math classes. This chapter examines each of these class categories.
Appendix A: Cosmo Basic Types Array Storage Class Types The array classes store data. • csData—stores raw data. • csArray—is a virtual array class. • Array-derived classes—are derivations of csArray. The following sections describe each of these array classes. Data Class The csData class is similar to malloc: it stores raw data. You can use the csData class directly, such as in storing data in arrays, but it is more common to derive your own class from it.
Array Storage Class Types Array Classes csArray is a virtual array class from which all other array classes are derived. Arrays are used as storage vehicles for a variety of types. Cosmo 3D provides a wealth of csArray-derived array classes for different types, including: • csPtrArray—An array of pointers often used to point to values in other arrays. • csFieldArray—An array of fields. • csByteArray—An array of bytes. • csIntArray—An array of integers. • csFloatArray—An array of floats.
Appendix A: Cosmo Basic Types To fill an array, or to retrieve values from an array, use one of the set() or get() methods in the class, respectively, replacing with the base type of the array. void set(int i, csInt t); void get(int i, csInt& t) const; get(int i) const; void set(const csIntArray &l); • i is the position of the value in the array. • tis the value of that element in the array. The second version of the set() method allows you to copy the contents of one array to another.
Vector Classes • Use the append() method to add a value after the last value in an array. • Use the insert() method to insert a value at a specified index location. • Use the replace() method to replace one value with another. • Use the remove() method to remove the first value it finds that matches its argument. • Use the removeIndex() method to remove a specific value or a value located at a specific index.
Appendix A: Cosmo Basic Types Vector Math Vectors are used in a variety of ways in Cosmo 3D. Commonly, they are used to define orientation, rotation, and transformations. Cosmo 3D provides the following multi-dimensional vectors. • csVec2f— represents a two-element floating point vector. • csVec3f— represents a three-element floating point vector. • csVec3s— represents a three-element short-integer vector.
Vector Classes The classes contain the following methods: csBool csBool void float void void void void void float float float float void void equal(const csVec4f& v) const; almostEqual(const csVec4f& v, float tol) const; negate(const csVec4f& v); dot(const csVec4f& v) const; add(const csVec4f& v1, const csVec4f& v2); sub(const csVec4f& v1, const csVec4f& v2); scale(float s, const csVec4f& v); addScaled(const csVec4f& v1, float s, const csVec4f& v2); combine(float a, const csVec4f& v1, float b, const, csVe
Appendix A: Cosmo Basic Types The classes also provide the following write and operator methods: void write(csOutput *out); csVec4f& csVec4f& float& float csBool csBool operator=(const csVec4f &v); operator=(float v); operator[](int i); operator[](int i) const; operator==(const csVec4f &v) const; operator!=(const csVec4f &v) const; The write() method prints the vector to the device or file defined by out. The operator() method defines an operation that can be performed on two vectors.
Bounding Volumes • A csVec3f::xformPt(const csVec3f& v, const csMatrix4f& m) transform vector sets a csVec3f vector, v, to be the first three components of (v,1) * m where v is treated as a row vector. • A csVec3f::xformVec(const csVec3f& v, const csMatrix4f& m) transform point sets this vector to be v, thought of as a row vector, times the 3X3 submatrix formed by the first 3 rows and first three columns of m. This is most useful for non-projective transformations.
Appendix A: Cosmo Basic Types Cosmo 3D provides two bounding shapes as well as an abstract class from which you can derive your own bounding shapes. • csBound— is the abstract base class from which bounding objects are derived. • csBoxBound—prescribes the minimum-sized box that can enclose an object. • csSphereBound—prescribes the minimum-sized sphere that can enclose an object.
Field Classes csField csField is the abstract class from which all of the other field classes are derived. Because it does not have a constructor, you cannot use it directly. See “The csField Class” on page 5 for additional information on csField.
Appendix A: Cosmo Basic Types The editDone() method allows you to signal when you have finished manipulating the csMField object so that, for example, you can allow its values to take effect. short short getOffset() const; getStride() const; void int setCount(int n); getCount(); void int void setSize(int n); getSize(); editDone(); csAtomField csAtomField is a single-valued composite field type. A single value field can be something as simple as an integer or a csVec4f.
Other Math Classes You can fill an array by setting groups of values using the following methods: void void void setRange(int i, int count, csInt vals[]); getRange(int i, int count, csInt vals[]); fillRange(int i, int count, csInt vals[]); • i is the position in the array where you want to begin setting values. • count is the number of array elements you want to set. • vals[] is an array of values that you want to enter into the array.
Appendix A: Cosmo Basic Types csPlane csPlane represents a half space with a normal and an offset, which together form the parameters of the traditional Ax + By + Cz = D plane equation. The methods in the class allow you to • Determine the closest point on the plane to a point in space. • Determine whether or not it intersects with a csSeg. • Construct a plane from three points. • Construct a plane from a point and the plane normal at a point. • Transform the orientation of the plane.
Appendix B B. Cosmo 3D Sample Application This appendix discusses a simple Cosmo 3D application, called cube.cxx. The files are in the following locations: Source Executable UNIX /usr/share/Optimizer/src/apps/Cosmo3D directory /usr/sbin NT C:\Program Files...\Optimizer\bind C:\Program Files\Silicon Graphics\Optimizer\src\apps\cosmo3D In cube.cxx, two cubes, one red the other green, slowly revolve, as shown (statically) in Figure B-1.
Appendix B: Cosmo 3D Sample Application These are the sections in this chapter: • “Cube.cxx Explained” on page 195. • “Understanding the Different Parts of Cube.cxx” on page 202. • “Scene Graph for Cube.cxx” on page 203.
Cube.cxx Explained Cube.cxx Explained Example B-1 shows the cube.cxx application. It also includes embedded comments (not found in the cube.cxx file) that explain the functionality of each section of cube.cxx. The sections that follow Example B-1 explain the structure and functionality of the code in more generic terms, so that you can understand the principles of programming Cosmo 3D applications.
Appendix B: Cosmo 3D Sample Application //Start the application here int main(int argc, char *argv[]) { int doOrthoCam = 0, doFullScreen = 0; if(argc > 1) { argv++; argc--; while(argc > 0) { if(argv[0][0] == '-') switch(argv[0][1]) { case 'f': doFlash = 1; break; case 'F': doFullScreen = 1; doBorders = 0; break; case 'o': doOrthoCam = 1; break; } argv++; argc--; } } // Initialize Cosmo3D csObject::initClasses(); // define scene root = makeCube(); 196
Cube.
Appendix B: Cosmo 3D Sample Application int frame(void*) { static int frame = 0; const csEventArray &elist = csWindow::getCurrent()->getEvents(); for (int i=0; i
Cube.cxx Explained // swap buffers csWindow::swapBuffers(); frame++; return csWindow::CONTINUE; } //Create a cube; the cube will be rendered twice. static csGroup* makeCube() { // int i; static float cubeCoords[24][3] = { {-1.0f, -1.0f, 1.0f}, { 1.0f, -1.0f, { 1.0f, 1.0f, 1.0f}, {-1.0f, 1.0f, {-1.0f, -1.0f, -1.0f}, {-1.0f, 1.0f, { 1.0f, 1.0f, -1.0f}, { 1.0f, -1.0f, { 1.0f, -1.0f, 1.0f}, { 1.0f, -1.0f, { 1.0f, 1.0f, -1.0f}, { 1.0f, 1.0f, {-1.0f, -1.0f, 1.0f}, {-1.0f, 1.0f, {-1.0f, 1.0f, -1.0f}, {-1.0f, -1.
Appendix B: Cosmo 3D Sample Application csQuadSet *gset = new csQuadSet; // cube vertices csCoordSet3f *cset = new csCoordSet3f(numCubeCoords); cset->point()->edit(); #if 0 for (i=0; ipoint()->set(i, csVec3f(cubeCoords[i][0], cubeCoords[i][1], cubeCoords[i][2])); #else cset->point()->setRange(0, numCubeCoords, (csVec3f *)cubeCoords); #endif cset->point()->editDone(); gset->setCoordSet(cset); // cube normals csNormalSet3f *nset = new csNormalSet3f(numCubeNorms); nset->vector()->ed
Cube.cxx Explained highlight = new csAppearance; highlight->setMaterial(hlMaterial); highlight->setLightEnable(1); // red cube csMaterial *redMaterial = new csMaterial; redMaterial->setSpecularColor(1.0f, 1.0f, 1.0f); redMaterial->setDiffuseColor(0.8f, 0.1f, 0.1f); redMaterial->setShininess(.0078125 *16.0f); redMaterial->setTransparency(0.
Appendix B: Cosmo 3D Sample Application // environment csPointLight *lt = new csPointLight; csEnvironment *environment = new csEnvironment; environment->light()->append(lt); environment->addChild(fgTransform); environment->addChild(bgTransform); return environment; } Understanding the Different Parts of Cube.cxx The embedded comments in Example B-1 call out the different functional parts of cube.cxx, which include: 202 • Include statements and global method declarations.
Scene Graph for Cube.cxx Scene Graph for Cube.cxx Scene graphs provide the structure for Cosmo 3D applications. Cosmo 3D applications use scene graphs to specify the objects rendered. Figure B-2 shows the scene graph used for cube.cxx.
Appendix B: Cosmo 3D Sample Application In cube.cxx, csGeometry defines a cube and the csAppearance nodes specify the green and red colors of the cubes. Note: Neither csGeometry nor csAppearance are nodes; they are classes associated by a csShape node. Relating Local Space to World Space Once you define the orientation of a shape, you use csTransform nodes to place and orient the shape in a different coordinate system. World space is the coordinate system of the root node.
Scene Graph for Cube.cxx Group node Transform node Group node Transform node Leaf node Figure B-3 Two Transformations Into World Space In Figure B-3, after the leaf node is transformed twice, it is placed in world space. In cube.cxx, two transformation nodes transform the shapes into world space.
Appendix B: Cosmo 3D Sample Application Creating the User Interface csWindow encapsulates the user interface: it includes the methods you use to construct a window in which a Cosmo 3D application runs. csWindow manages a csContext object to control the graphics context as well as a csEvent object that handles user actions, like mouse events. csWindow is replete with default values that satisfy most application needs. cube.
Scene Graph for Cube.cxx Summary The following procedure summarizes the steps you take to create and render a very simple scene graph. 1. Create csAppearance and csGeometry containers to define the appearance and the geometry of an object. For more information on setting csAppearance values, see Chapter 3, “Specifying the Appearance of Geometries.” For more information on setting csGeometry values, see Chapter 2, “Creating Geometries.” 2. Relate the csAppearance and csGeometry nodes in a csShape node.
Appendix C C. Cosmo 3D Class Hierarchy The following list shows the class hierarcy in Cosmo 3D.
Appendix C: Cosmo 3D Class Hierarchy csField csMField csMFByte csMFFloat csMFInt csMFMatrix4f csMFRef csMFRotation csMFString csMFVec2f csMFVec3f csMFVec3s csMFVec4f csSFBitMask csSFBoxBound csSFDouble csSFEnum csSFFloat csSFInt csSFMatrix4f csSFName csSFRef csSFRotation csSFShort csSFSphereBound csSFString csSFTime csSFUByte csSFUInt csSFVec2f csSFVec3f csSFVec3s csSFVec4f csSFVec4ub 210
csFieldInfo csMFByteInfo csMFFloatInfo csMFIntInfo csMFMatrix4fInfo csMFRefInfo csMFRotationInfo csMFStringInfo csMFVec2fInfo csMFVec3fInfo csMFVec3sInfo csMFVec4fInfo csSFBitMaskInfo csSFBoxBoundInfo csSFDoubleInfo csSFEnumInfo csSFFloatInfo csSFIntInfo csSFMatrix4fInfo csSFNameInfo csSFRefInfo csSFRotationInfo csSFShortInfo csSFSphereBoundInfo csSFStringInfo csSFTimeInfo csSFUByteInfo csSFUIntInfo csSFVec2fInfo csSFVec3fInfo csSFVec3sInfo csSFVec4fInfo csSFVec4ubInfo csFrustum csGlobal csMatStack4f csMatr
Appendix C: Cosmo 3D Class Hierarchy csObject csAction csCompileAction csTransformAction csIsectAction csSoundAction csVFCullAction csDrawAction csContainer csAppearance csAudio csAudioClip csAudioSamples csCamera csFrustumCamera csOrthoCamera csPerspCamera csColorSet csColorSet3f csColorSet4f csCoordSet csCoordSet3f csGeometry csBox csCone csCylinder csGeoSet csLineSet csLineStripSet csIndexedLineSet csPointSet csPolySet csIndexedFaceSet csQuadSet csTriFanSet csTriSet csTriStripSet csScreenAlignedText csS
csNode csEngine csInterpolator csColorInterpolator csCoordinateInterpolator csNormalInterpolator csOrientationInterpolator csPositionInterpolator csScalarInterpolator csMorphEng csMorphEng3f csMorphEng4f csSelectorEng csSelectorEng3f csSelectorEng4f csSpline csTransformEng csTransformEng3f csFog csGroup csBillboard csCollision csEnvironment csSwitch csSwitch csInline csSwitch csLOD csTransform csLight csDirectionalLight csPointLight csSpotLight csPickSensor csPlaneSensor csSphereSensor csTouchSensor csShape
Appendix C: Cosmo 3D Class Hierarchy csTexCoordSet csTexCoordSet2f csTexGen csTexture csImageTexture csContext csData csDispatch csEvent csHit csOverrideGeoProp csWindow csOgl csOutput csPrivate csPtrArray2D csRotation csSeg csString csStringDict csStringDictEntry csThread csTime csType csVec2f csVec3f csVec4f csVec4ub csdFile_csb vlDB vlDebugError vlGeom vlInput vlReadError 214
Index A actions, 67, 83 addChild(), 66 ambient color, 51 animate, 121 animation, creating, 124 application, simple, 193 aspect ratio, 99 atmospheric effects, See fog attribute, 17, 20 indexing, 23 setting, 21 specifying, 26 B base classes, 2 binding, 21 BLEND, 53 BLEND_TENV, 46 bounding shape, 187 C camera, 99 ortho, 101 perspective, 101 cleanFields(), 150 clip plane, 103 compile, scene graph, 164 coordIndices, 28 Cosmo 3D, 1 csAction, 84 csAppearance, 11, 15, 163, 203 csArray, 181 csArrayField, 190 csA
Index csEnvironment, 12, 59, 92 csFog, 94 csField, 5, 189 csFieldInfo, 189 csFog, 94 fields, 94 csFrustum, 105, 192 csFrustumCamera, 105 csGeoMath.
Index csThread, 146 csTimeSensor, 122 csTimeSensor, active or not, 124 csTimeSensors, updating, 123 csTouchSensor, 134 csTouchSensor, scope of, 135 csTransform, 9, 59, 79 csTransformEng, 109, 110, 119 csTriSet, 31 csTriStripSet, 20, 31, 32 csVec2f, 184 csVec3f, 184 csVec3s, 184, 186 csVec4f, 184 csVec4ub, 186 csWindow, 137, 145, 206 using a portion of, 97 csWindow, updating sensors, 123 cube.
Index flight simulation fog, use of, 93 fog, 93-??, 94 example program, 95 FOV, 104 fractionChanged, 125 frustum, 160, 192 frustum culling, 160 G geometry, 35 placing in a scene, 77 ready-made, 16 graphics state, 36 group node, 58 H haze, See fog hitNormal event, 135 hitPoint event, 135 hitTexCoord event, 135 I insertChild(), 73 interface, 137 isOver event, 135 K key, 111, 113 key value, 111, 113 218 L layering shapes, 78 level of detail, 160 light, setting boundaries for, 92 LINE_PMODE, 52 line segm
Index OBJECT_LINEAR, 50 offset, rotation, 126 opBarrier, 146 OpenGL, 37 OpenGL Optimizer, 1 optimize, 151 optimize,setCullFace(), 152 optimizing performance, 151 orthographic projection, 101 REPLACE_TENV, 46 resolution, 160 root node, 66, 67 rotate, 80 rotation, using sensors, 126 rotation event, 127 routines pfGetRef(), 4 pfRef(), 4 pfUnref(), 4 runtime type, 4 P S parts of a Cosmo application, 202 performance tips, 163 fog, 93 performance tools, 151 PERSP_TEX, 44 perspective, 45 pick(), 141 playing s
Index setMatrix(), 81 setNearClip(), 103 setPolyMode(), 52 setPosition(), 100 setScaleOrientation(), 80 setTexGen(), 50 setting fields, 61 setTranslation(), 80 setVertFOV(), 103 shading model, 53 shininess, 52 single-value field, 62 sleep(), 148 smoke, See fog SMOOTH_TEX, 53 sound, 167 locating and directing, 170 playing, 170 priority, 170 reverse direction, 172 spatialized, 170 sound file specifying, 169 specular, 51 SPHERE_MAP, 50 start(), 147 state, accessing, 37 state, changing, 38 state, current, 37 s
Index V view using camera, 98 viewport, 97 virtual sphere, 126 visual simulation fog, use of, 93 VRML, 74 W wait(), 148 window, creating your own, 143 world space, 9, 79, 82, 133, 204 X X window, 143 221
Tell Us About This Manual As a user of Silicon Graphics products, you can help us to better understand your needs and to improve the quality of our documentation. Any information that you provide will be useful.