TeamLRN sPeCiAL 3D Game Engine Architecture Engineering Real-Time Applications with Wild Magic TeamLRN sPeCiAL THE MORGAN KAUF M AN N SERI ES I N I NTERACT IVE D T ECH N O LO GY SERIES EDITOR: DAVID H EBERLY, MAGIC SOFTWARE, INC The game industry is a powerful and driving force in the evolution of computer technology As the capabilities of personal computers, peripheral hardware, and game consoles have grown, so has the demand for quality information about the algorithms, tools, and descriptions needed to take advantage of this new technology To satisfy this demand and establish a new level of professional reference for the game developer, we created the Morgan Kaufmann Series in Interactive 3D Technology Books in the series are written for developers by leading industry professionals and academic researchers, and cover the state of the art in real-time 3D The series emphasizes practical, working solutions and solid software-engineering principles The goal is for the developer to be able to implement real systems from the fundamental ideas, whether it be for games or other applications 3D Game Engine Architecture: Engineering Real-Time Applications with Wild Magic David H Eberly Real-Time Collision Detection Christer Ericson Physically Based Rendering: From Theory to Implementation Matt Pharr and Gregg Humphreys Essential Mathematics for Game and Interactive Applications: A Programmer’s Guide James M Van Verth and Lars M Bishop Game Physics David H Eberly Collision Detection in Interactive 3D Environments Gino van den Bergen 3D Game Engine Design: A Practical Approach to Real-Time Computer Graphics David H Eberly Forthcoming Artificial Intelligence for Computer Games Ian Millington Visualizing Quaternions Andrew J Hanson TeamLRN sPeCiAL 3D Game Engine Architecture Engineering Real-Time Applications with Wild Magic David H Eberly Magic Software, Inc AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Morgan Kaufmann is an imprint of Elsevier TeamLRN sPeCiAL Senior Editor Tim Cox Publishing Services Manager Simon Crump Project Editor Justin Palmeiro Project Management Elisabeth Beller Assistant Editor Rick Camp Cover Design Chen Design Associates, San Francisco Text Design Rebecca Evans Composition Windfall Software, using ZzTEX Technical Illustration Dartmouth Publishing Copyeditor Ken DellaPenta Proofreader Jennifer McClain Indexer Steve Rath Interior Printer The Maple-Vail Book Manufacturing Group Cover Printer Phoenix Color Corporation Morgan Kaufmann Publishers is an imprint of Elsevier 500 Sansome Street, Suite 400, San Francisco, CA 94111 This book is printed on acid-free paper © 2005 by Elsevier Inc All rights reserved Designations used by companies to distinguish their products are often claimed as trademarks or registered trademarks In all instances in which Morgan Kaufmann Publishers is aware of a claim, the product names appear in initial capital or all capital letters Readers, however, should contact the appropriate companies for more complete information regarding trademarks and registration No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means—electronic, mechanical, photocopying, scanning, or otherwise—without prior written permission of the publisher Permissions may be sought directly from Elsevier’s Science & Technology Rights Department in Oxford, UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333, e-mail: permissions@elsevier.com.uk You may also complete your request online via the Elsevier homepage (http://elsevier.com) by selecting “Customer Support” and then “Obtaining Permissions.” Library of Congress Cataloguing-in-Publication: applied for ISBN: 0-12-229064-X For information on all Morgan Kaufmann publications, visit our Web site at www.mkp.com Printed in the United States of America 08 07 06 05 04 TeamLRN sPeCiAL Abo ut t he Aut ho r Dave Eberly is the president of Magic Software, Inc (www.magic-software.com), a company that specializes in software development for computer graphics, image analysis, and numerical methods Previously, he was the director of engineering at Numerical Design Ltd., the company responsible for the real-time 3D game engine, NetImmerse His background includes a BA degree in mathematics from Bloomsburg University, MS and PhD degrees in mathematics from the University of Colorado at Boulder, and MS and PhD degrees in computer science from the University of North Carolina at Chapel Hill He is the author of Game Physics (2004) and 3D Game Engine Design (2001) and coauthor with Philip Schneider of Geometric Tools for Computer Graphics (2003), all published by Morgan Kaufmann As a mathematician, Dave did research in the mathematics of combustion, signal and image processing, and length-biased distributions in statistics He was an associate professor at the University of Texas at San Antonio with an adjunct appointment in radiology at the U.T Health Science Center at San Antonio In 1991 he gave up his tenured position to re-train in computer science at the University of North Carolina After graduating in 1994, he remained for one year as a research associate professor in computer science with a joint appointment in the Department of Neurosurgery, working in medical image analysis His next stop was the SAS Institute, working for a year on SAS/Insight, a statistical graphics package Finally, deciding that computer graphics and geometry were his real calling, Dave went to work for Numerical Design Ltd., then later to Magic Software, Inc Dave’s participation in the newsgroup comp.graphics.algorithms and his desire to make 3D graphics technology available to all are what has led to the creation of his company’s Web site and this book v TeamLRN sPeCiAL This page intentionally left blank TeamLRN sPeCiAL Co nt ent s About the Author Preface v xiii Chapter Introduction 1.1 1.2 1.3 1.4 Drawing a Triangle Drawing a Triangle Mesh Drawing a Complicated Scene Abstraction of Systems 17 27 27 Chapter Core Systems 31 2.1 The Low-Level System 31 33 45 46 47 48 49 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 Basic Data Structures Encapsulating Platform-Specific Concepts Endianness System Time File Handling Memory Allocation and Deallocation 2.2 The Mathematics System 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.2.6 2.2.7 Basic Mathematics Functions Fast Functions Vectors Matrices Quaternions Lines and Planes Colors 2.3 The Object System 2.3.1 2.3.2 2.3.3 2.3.4 Run-Time Type Information Names and Unique Identifiers Sharing and Smart Pointers Controllers 53 53 57 61 75 90 102 103 105 105 112 114 121 vii TeamLRN sPeCiAL viii Contents 2.3.5 2.3.6 2.3.7 2.3.8 Streaming Cloning String Trees Initialization and Termination 122 133 138 139 Chapter Scene Graphs and Renderers 149 3.1 The Core Classes 152 153 160 163 3.1.1 3.1.2 3.1.3 Motivation for the Classes Spatial Hierarchy Design Instancing 3.2 Geometric State 3.2.1 3.2.2 3.2.3 Transformations Bounding Volumes The Core Classes and Geometric Updates 3.3 Geometric Types 3.3.1 3.3.2 3.3.3 3.3.4 Points Line Segments Triangle Meshes Particles 3.4 Render State 3.4.1 3.4.2 3.4.3 3.4.4 3.4.5 3.4.6 Global State Lights Textures Multitexturing Effects The Core Classes and Render State Updates 3.5 Renderers and Cameras 166 167 177 184 196 197 198 200 202 203 203 223 230 242 248 251 Camera Models Basic Architecture for Rendering Single-Pass Drawing The DrawPrimitive Function Cached Textures and Vertex Attributes Global Effects and Multipass Support 259 259 276 281 285 292 295 Advanced Scene Graph Topics 299 4.1 Level of Detail 299 3.5.1 3.5.2 3.5.3 3.5.4 3.5.5 3.5.6 Chapter TeamLRN sPeCiAL 722 Index quaternions (continued) multiplication, 92 multiplicative inverse, 94 physics, 101–102 products, 92 rotations, 93–95 scalar multiplication, 91–92, 102 standard constructors, 90 symbolic representation, 91 typecasting, 90 unit-length, 93, 94 utility, 93 queries collision detection, 487, 540, 542 collision group intersection, 539–540 containment, 347 find-intersection, 488, 506–507, 511–513, 516–517 group intersection, 538 intersection, 184, 501–503 object state change during, 539 patch, 361 renderer, 280 RTTI, 107, 108 test-intersection, 487–488, 501, 505–506, 511, 515 triangle-triangle intersection, 550–551 which-side-of-plane, 178, 180 QueryPerformanceCounter function, 47 QueryPerformanceFrequency function, 47 quick rejection test, 540 R radians to degrees, 56 TeamLRN sPeCiAL range checking, 34 ray-OBB intersection, 522–524 illustrated, 522 projections, 523 separation tests, 522 test-intersection query, 523–524 rays intersection with triangles, 504 pick, 527–530 ray-sphere intersection, 510–513 find-intersection query, 511–513 graph configurations, 510 quadratic equation, 511 test-intersection query, 511 reals, 605 rectangle patches, 361 rectangles axis-aligned, 560 in denoting grouping nodes, 161 intersecting, 560 overlapping, 560 vertices, reentrancy, 295 reference counters, 114 increment/decrement, 114 manipulating, 115 reflections × homogeneous transformation for, 90 matrix, 460 planar, 249, 295, 457–462 planes, 89 reflection vector, 447 RegisterFactory function, 126 Register function, 126 registers, 469 reindexing, 326 ReleaseShader function, 481 ReleaseTexture function, 294, 295 RemoveAllLights function, 230 RemoveAll method, 34 Remove method, 34, 43 Renderer class, 152, 153 deferred drawing interface, 356 defined, 276 enable/disable functions, 481 interface, 277–278, 464, 481 interrelationships, 153 motivation for, 157–158 renderers building, 149 cameras and, 259–298 defined, 149 derived-class, 278 notifying, 294 querying, 280 requirements, 158 vertices and, 157 virtual functions, 278 renderer state, 203–259, 248–251 effects, 248–251 global state, 203–223 at leaf node, 252 lights, 223–230 multitexturing, 242–248 restoration, 457 textures, 230–242 updates, 251–259, 307 rendering advanced topics, 431–486 architecture, 276–280 cameras for, 263 particles, 304 portable layer, 277 reflected object, 461 scene graph management vs., 150–151 tiled, 267, 268 Reorder function, 332 Index reordering vertices, 326 RequestTermination method, 617 ResetColors function, 654 Response function, 654 RestoreScreenTransformation function, 291 rigid bodies, 592–600 angular momentum, 593 angular velocity, 593 class, 595–600 defined, 592 immovable, 597 inertia tensor, 593 initializing, 600 linear momentum, 592, 593–594 motion calculations, 592 motion equation, 593 standard representation, 592 unconstrained motion, 592, 594 RigidBody class, 595–600 applications using, 599–600 constructor, 597 defined, 595 Function function, 597 interface, 595–596 Update function, 597–599 ROAM algorithm, 378–379 description, 379 variants, 378–379 roll, 87 root finding with bisection, 496–497 hybrid, 497 with Newton’s method, 496 numerical, 494 RotateTrackBall function, 630, 631–634 rotation matrices, 4, 5, 171 counterclockwise, 76 interpolation, 87 local, 264 TeamLRN sPeCiAL particles, 303 quaternion, 93 representation, 76 rotational slerp, 87–88 rotation definition, 88 unit length quaternions and, 94 update, 14 x-axis, 77 y-axis, 78 z-axis, 78 rotation(s) about right axis, 15–16 about right vector, 623 about up vector, 622 about view direction, 16 angle of, 100, 418, 622 axis, 100 camera, 15 composition of, 90 counterclockwise, 77, 622 incremental, 625–626 inverse transformation, 175 joint, 417, 418 object, 621–622 quaternion, 94 trackball, 630, 634 triangle, 3, twist, 101 round-off errors, 56, 356 Run function, 609, 610 Runge-Kutta methods, 102 defined, 569 fourth-order method, 571–572 midpoint method, 569–570 numerical solver, 582 solver, 577, 580 run-time type information (RTTI), 105–111, 531 caller object, 106, 107 defined, 105 input object, 106, 107 name, 108, 128 723 queries, 107, 108 single-inheritance class trees, 105–109 static and dynamic typecasting, 110–111 strings, 130 S sample applications, 637–672 TestBillboardNode, 642, 643 TestBspNode, 642–645 TestCachedArray, 645–646 TestCastle, 646–648 TestClodMesh, 648 TestCollision, 648–654 TestInverseKinematics, 654–656 TestPortals, 656–662 TestScreenPolygon, 662– 668 TestSkinnedBiped, 668–669 TestSoftFaces, 669–670 TestTerrain, 670–672 sample tools, 673–675 Save class, 128 scalar multiplication, 91–92, 102 scale inverse transformation, 175 nonuniform, 177 uniform, 177 ScaleByMax method, 104, 105 scene graph management, 28 changes and, 151 core, 29 core classes, 28, 152–166 defined, 150 rendering system vs., 150–151 shader program support, 463–479 sharing, 294 visibility determination, 150 724 Index scene graphs advanced topics, 299–429 defined, 150 deleting, 293 geometric update of, 189 illustrated, 164, 166 loading, 129–133 memory footprint, 123 reconstruction, 129 roots of, 122 saving, 126–129 string trees applied to, 138 written to disk, 129 scene hierarchies leaf nodes, 213 updating need, 195 ScenePrinter tool, 138, 674 scenes defined, 150 organization, 213 root node, 129 writing memory blocks to, 133 SceneTree tool, 138, 674, 675 SceneViewer tool, 674 ScreenPolygon class, 292 screen space height, 388 polygons, 291, 292 segment-OBB intersection, 524–527 illustrated, 525 Minkowski difference, 524 projections, 525 separation tests, 525 test-intersection query, 526–527 segments array, 367 curve, 361 defined, 361 of intersections, 494 intersection with triangles, 504 TeamLRN sPeCiAL line, 196, 198–200 quantity, 367 storage during subdivision, 370 tessellated by single line, 366 segment-sphere intersection, 513–517 configuration descriptions, 514 find-intersection query, 516–517 graph configurations, 513 test-intersection query, 515 SelectLevelOfDetail function, 309, 333 self-intersections, preventing, 591 separating axes defined, 518 line-OBB, 521 potential, 518 ray-OBB, 522 segment-OBB, 525 SetActiveQuality function, 198 SetAlphaState function, 286 SetChild function, 163 SetConstantCameraPosition function, 485 SetConstantFogParams function, 485 SetConstantLightDiffuse function, 485–486 SetConstantTransform function, 486 SetDirection function, 229 SetElement method, 34 SetFrustum method, 266, 267 SetGeometryType function, 199 SetGlobalState function, 286 SetLevel function, 374, 376 SetLight function, 230 SetLocal function, 185 SetMaxQuantity method, 35 SetName function, 112 SetObject function, 400 sets, 41–43 assert-and-repair paradigm, 42 elements insertion, 43 elements modification, 42 elements quantity, 42 elements removal, 43 initial maximum quantity, 42 memory overhead, 41 searching, 43 STL, 41 SetScale function, 171 SetScreenTransformation function, 291 SetTranslate function, 171 SetViewPort function, 528 Shader class, 472–474 architecture, 465 binding mechanism, 479 defined, 464 interface, 472–473, 474 shader program encapsulation, 472 ShaderConstant class, 467–470 constructor inputs, 476 interface, 468–469 objects, 467, 470, 472 variables, 484 shader constants defined, 467 vertex shader, 470 ShaderEffect class, 477–478 defined, 477 interface, 477–478 objects, 478, 481 shader programs benefits, 462 defined, 462 drawing function support, 481–482 DrawShader function and, 482 encapsulation, 472 Index executable, 474 as functions, 463 global effects, 478 inputs, 469, 474 low-level, 486 paper texture, 479 pixel shader, 462 renderer support, 479–486 scene graph support, 463–479 support, implementing, 463 text string representation, 474 vertex shader, 462 shaders defined, 30, 149 pixel, 149, 150 vertex, 149–150 writing, 150 ShadeState class, 222–223 shading, 222–223 flat, 222 Gouraud, 222 models, 222 modes, 223 See also global states shadows caster, 456 colors, 456 planar, 454–457 sharing, 114–120 signed distance defined, 492 flat spot, 494, 495 function, 494, 495 measure, 494 Sign functions, 57 simplification algorithms, 396 block, 382–388 terrain, 671 terrain pages, 395–398 vertex, 379–382 Simplify function, 398 TeamLRN sPeCiAL sine function, 55, 57, 58 fast approximations to, 58 inverse, 59 single-inheritance systems class trees, 105–109 defined, 105 hierarchy illustration, 106 single-pass drawing, 281–284 behavior, 284 with DrawPrimitive function, 285 traversal, 283–284 single textures, 434–435 singular value decomposition, 168, 169 skeleton application code, 637–641 header file, 637–638 OnInitialize callback, 640–641 source file, 638–640 See also applications skew-symmetric matrix, 76 skin-and-bones See skinning SkinController class, 411–413, 592 defined, 411 interface, 411–412 Update function, 413 skinning, 404, 410–414 bones, 410–414 data, 414 defined, 410 hardware-based, 414 sample application, 414 skin, 410, 413 software-based, 411 support, 411 update routine, 414 skins defined, 410 world transformation, 413 Slerp function, 88, 96 725 smart pointers, 114–120 alias, 116 array, 259 assignment to self, 117 comparison, 118 defined, 114 eliminating, 255 as function parameters, 119 implementation warning, 117 to lights, 230 NULL assignment, 119 to texture images, 232 typecast, 118 use guidelines, 119 soft addition, 211 defined, 437 light map using, 438 SortByTexture function, 359 SortedCube class, 669 sorting, 29, 335–360 with BSP trees, 336–343 by texture state, 359 children of nodes, 354–356 coarse-level, 336 deferred drawing and, 356–360 for faces, 355 geometric, 335 portals, 343–354 spatial regions, 336 vertices, 331 source support continuous LOD, 331–334 Spatial class, 152, 153, 158, 160 bounding volumes in, 184 design goal, 160 encapsulation, 184 geometric updates and, 184–196 hierarchical picking, 530 interrelationships, 153 lights support, 229–230 motivation for, 154–155 726 Index Spatial class (continued) render state updates and, 251–259 spatial hierarchy design, 160–163 special effects bump maps, 440–446 dark maps, 436 environment maps, 446–450 with fixed-function pipeline, 431–462 gloss maps, 437–440 light maps, 437 planar reflection, 457–462 planar shadows, 454–457 projected textures, 451–454 renderer support, 479–486 scene graph support, 463–479 single textures, 434–436 with vertex and pixel shaders, 462–486 vertex coloring, 433–434 specular highlights, 223 specular light, 223 SphereBV class, 182, 542 bounding volume, 546 defined, 542 objects, 545 use of, 542 SphereBVTree class defined, 542 pre-main initialization macros, 545 spheres, 178 bounding, 180 intersection with line, 508–509 intersection with linear components, 508–517 intersection with ray, 510–513 intersection with segment, 513–517 TeamLRN sPeCiAL testing, 178 See also bounding volumes sphere trees, 542 spherical environment mapping, 447 spherical linear interpolation, 95 acronym, 96 equation, 96 spherical quadrangle interpolation, 96–97 defined, 96–97 of four quaternions, 97 SplitTriangles function, 546 spot lights angle, 227 defined, 224 direction change, 224 direction vector, 227 light vector, 445 modulator, 227 position, 227 unit-length vector, 227 See also lights Sqr function, 54 square-distance function, 489, 493, 494 stacks, 43–44 full, 44 iterating over, 44 operations, 44 Standard Template Library (STL), 31, 698 applications using, 68 functionality, 33 maps, 32 state, 28 state constants, 467, 469, 470 static typecast, 110–111 in C-style, 110, 111 safety, 110 using, 110 stencil buffers, 279 stitching terrain pages, 389–391 code, 390–391 visual anomaly, 399 See also terrain; terrain pages Stream class, 49, 122, 129, 133 streaming, 122–133 deep copy side effect, 133 defined, 122 disk, 124 memory, 124–125 to memory block, 133 object registration, 126–127 support, 125 to/from disks, 123 typical usage, 124 stream loader, 128 strings, 44–45, 605 names, 134 reading, 44, 45 RTTI, 130 type, 45 Strings class, 44, 45 StringTree class, 138–139 string trees, 138–139 applied to scene graphs, 138 control code, 138 creation, 139 nodes, 139 saving, 139 tools using, 138 Subdivide function, 371, 376 subdivision adaptive schemes, 372 Boolean results and, 491 curve segment storage, 370 curve tessellation by, 366–373 default level, 368 level, varying, 371 polyline produced by, 368 surfaces, 334 surface tessellation by, 373–377 uniform scheme, 372 Index vertex attributes after, 374 subdivision functions, 371, 376 surface masses, 583–586 deformable, 584, 586 illustrated, 583 implementation class, 584–585 representation, 583 sample application, 586 surface mesh code, 376 defined, 361 SurfaceMesh class, 591 defined, 373 interface, 374 sample application, 377 SurfacePatch class, 364–365 surfaces dynamic changes, 375, 376 locking mechanism, 376 NURBS, 362 parametric, 361, 364–366 subdivision, 334 tessellation by subdivision, 373–377 vertices, 373 SwapBuffers function, 12, 13 swaps, 314, 321 heap arrays after, 314, 315, 316, 317 repeating, 317 sweep algorithm defined, 555 phase, 556 pseudocode, 556–557 update phase, 559 switching, 308, 309 SwitchNode class, 531 switch nodes active child support, 308 defined, 300, 306 SymmetricRandom function, 57 System functions, 46–47 system headers, 31, 45–46 TeamLRN sPeCiAL system timers, 619 T tangents function, 60 unit-length, 364 vectors, 97, 99, 363, 364 target records, 333 targets, 406 defined, 404 display in viewport, 534 goals, 415 weighted combination of, 404 TArray class, 42 templates, 53–54 member functions, 52 vector, 67–68 TerminateFactory function, 126 termination, 139–147 function additions, 143 function call, 143 function registration, 142 post-main, 142 terrain, 377–399 algorithm design, 377 camera movement about, 398 clamp-to-edge mechanism, 399 close assumption, 382 data representations, 377–378 distant assumption, 381–382 fold over, 377 as height field, 377 level of detail, 378–388 objects, 29 simplification, 671 tiled, handling, 388 uses, 377 vertex simplification, 379–382 727 terrain pages, 384 as child nodes, 395 collection, as active set, 395 dependencies, 389 design, 399 invisible, 398 level of detail, 389 management, 391–395 memory management and, 388–399 memory use, 388 numbering, 389 ordering, 389 replacing, 395, 398–399 simplification, 395–398 stitching, 389–391 stitching code, 390–391 subset, 398 texturing issues, 399 toroidal topology, 394 vertex dependences (sharing column edge), 391 vertex dependences (sharing row edge), 390 world origin, 388 TestBillboardNode sample, 642–643 defined, 642 scene graph, 642 screen shots, 643 TestBspNode sample, 642–645 defined, 642 illustrated, 645 scene graph, 642–643 TestCachedArray sample, 645–646 TestCastle sample, 646–648 defined, 646 picking system, 646 screen shots (inside), 649 screen shots (outside), 647 TestCharcoalEffect sample, 480, 486 TestClodMesh sample, 648 728 Index TestCollision sample, 648–654 callback, 653 defined, 648 OnKeyDown function, 650–651 Response function, 650 scene graph structure, 648 Transform function, 651 TestIntersection function, 183, 551, 552, 552–553 test-intersection queries, 487–488 collision records, 548–549 dynamic, 550 line-sphere intersection, 508–509 line-triangle intersection, 505–506 picking, 531, 533 ray-OBB intersection, 523–524 ray-sphere intersection, 511 segment-OBB intersection, 52–67 segment-sphere intersection, 515 separating axes method, 518 static, 550 triangle-triangle pairs, 550 for two ellipsoids, 501 TestInverseKinematics sample, 654–656 defined, 654 IK system encapsulation, 655 implementation, 655 scene graph, 654–655 screen shot, 656 Test method, 502 TestPortals sample, 656–662 environment cross section, 657 indoor environment bounding planes, 658–659 screen shots, 663, 665 TeamLRN sPeCiAL vertex and index assignments, 661–662 wireline views, 664, 666 TestScreenPolygon sample, 662–668 defined, 662 OnIdle loop, 667–668 screen shot, 667 TestSkinnedBiped sample, 668–669 TestSortFaces sample, 669–670 defined, 669 scene graph, 669 screen shot, 670 TestTerrain sample, 670–672 defined, 670 OnIdle callback, 671 screen shots, 672 terrain simplification, 671 texels defined, 234 interpolation at, 238 size, 235 Texture class, 210 blending equation information, 249 defined, 230–231 interface, 231, 235–236, 240– 241, 242–243, 249–250, 292–293 texture coordinates, 22, 231, 479 arrays, 24, 231 automatic generation of, 240–242 computation, 447 cylinders, 654 at image boundaries, 238 interpolated, 232 out-of-range, 238–240 with sphere mapping, 447 TextureEffect class, 434–435 defined, 434 interface, 434–435 sample use, 435 texture images, 231, 393, 440 affine drawing, 232 draw control, 232 filtering with, 232–237 magnification, 234 numbering scheme, 394 particle, 410 perspective-correct drawing, 232 projection type, 232 samples, 234 smart pointer to, 232 textures, 17, 230–242 alpha channel, 439 apply mode, 242 artifacts, 234 binding, 295 blending, 242 bound to graphics card, 292 bump maps, 440–446 cached, 292–295 checkerboard, 233 color, 245 dark maps, 436 decal, 215 deleting, 293 environment maps, 446–450 global effect, 448, 449 gloss maps, 437–440 information, 24 light maps, 437 loading, 21 objects, 435 primary, 26, 242 projected, 240, 242, 248, 249, 451–454 secondary, 25, 242, 248 single, 434–435 soft addition, 211 state, sorting by, 359 sunfire, 454 toggle, 20 unbinding, 294 Index See also renderer state TextureState class, 248, 249 texture units, 24 configuring, 248 different numbers of, 290–291 disabling, 26, 289–290 enabling, 289–290 THashSet class, 38 THashTable class, 35 three-dimensional arrays, 51–53 allocation/deallocation, 51–53 storage, 51 3D Game Engine Design (3DGED), 3D picking, 180 3DsToWmof importer, 673 tiled rendering, 267, 268 tiled terrain, 388 TimesTranspose function, 81 time-varying distance function, 492 TList class, 39, 40 ToAngle method, 83 ToAxisAngle method, 86 ToEulerAnglesUVW method, 86 tools, sample, 673–675 BmpToWmif converter, 673 Maya exporter, 673 ScenePrinter, 674 SceneTree, 674, 675 SceneViewer, 674 3DsToWmof importer, 673 WmifToBmp converter, 674 trackballs coordinate system, 629 motion, 631 projection, 630 rotation, 630, 634 virtual, 629, 630 Transformation class, 339 TeamLRN sPeCiAL transformations × homogeneous, 89 affine, 167 algebraic operations for, 173 bounds relationship, 157 homogeneous, 174–175 identity, 173 inverse, 13, 169, 175, 176–177, 339 joint, 417 local, 155, 156, 157, 168, 422 model bounding sphere, 172–173 model-to-world, 13, 183, 338 of planes, 175 propagation, 156 restoring, 291 setting, 291 similarity, 631 support, 167 world, 155, 156, 164, 169–170, 186 translation inverse transformation, 175 in right direction, 622 in up direction, 622 in view direction, 622 Transpose function, 81 TransposeTimes function, 81 trees bounding volume, 540, 542, 546 BSP, 336–343 directed, 105, 107 OBB, 542 single-inheritance, 105–109 sphere, 542 string, 138–139 tree structure, 163 triangle meshes, 196, 200–202 application screen shots, 18 bilinear interpolation, 24 class, 201 729 collision detection for, 180 in collision queries, 540 decimation, 309, 326, 328 defined, 201 destroying, 22 drawing, 17–26 generation, 360 nearest-neighbor interpolation, 25 shrinking, avoiding, 327 in terrain design, 378 textures, 17, 20 with vertex normals, 201–202 without normals, 202 See also geometric types triangle patches, 361 triangles back-facing, 220 center point, 3, centroids, 544 configurations, 380 double-sided, 220 drawing, 2–17 drawing application screen shots, 17 front-facing, 219, 220 insertion, 330 intersection, 501 intersection with linear components, 503–507 intersection with rays, 504 intersection with segments, 504 partitioning, 544 point representation, 503 removal, 330 rotating, unit-length normals, 202 vertex normal and, 202 vertices, 2, 4, 11, 12, 200 triangle soup, 200, 201 defined, 200 730 Index triangle soup (continued) sent to renderer, 201 triangle-triangle intersection queries, 550–551 dynamic, 550–551 implementation, 550 static, 550 trigonometric functions, 57–61 cosine, 59–60 fast, 58 inverse, 58 sine, 55, 57, 58, 59 tangent, 60 See also mathematics functions trilinear interpolation, 236, 237, 452 defined, 236 illustrated, 237 TriMesh class, 201, 203, 332, 374, 531 TSet class, 41, 42 TStack class, 43 TurnLeft function, 624 TurnRight function, 624, 625 two-dimensional arrays, 49–51 typecast dynamic, 110–111 smart pointers, 118 static, 110–111 U umbilic point, 366 uniform scaling, 167, 170 unique identifiers, 113–114 UnitCross function, 74 UnitRandom function, 57 UpdateBS function, 187, 194 Update function, 400, 403, 406, 412, 413, 562 UpdateGS function, 187, 190, 192, 194, 195–196, 229 UpdateLocal function, 419 TeamLRN sPeCiAL UpdateLocalR function, 422, 425–427 UpdateLocalT function, 420–422, 429 UpdateModelNormals function, 188, 201 UpdateMS function, 188, 192 UpdatePointMotion function, 408, 409 UpdateRS method, 252, 255, 256, 258 updates geometric, 184–196 geometric state, 307 heap, 330 local transformations, 422 render state, 251–259, 307 UpdateState function, 252, 254, 258 UpdateSystemMotion function, 408, 409 UpdateWorldBound function, 188, 192, 229, 264 UpdateWorldData function, 187, 188, 191–192, 258, 301 UpdateWorldSRT function, 418 updating the render state, 251–259 common situation for, 253 defined, 251 initiation, 253 interfaces, 251–252 semantics, 254 user-defined constants, 467, 469 UVBias function, 388 V variables, 688–689 vectors, 61–75 algebraic operations, 70 basic operations, 67–68 basis, 68 binormal, 363, 443 camera direction, 260 camera right, 260 camera up, 260 classes, 61, 67–68 comparison operators, 69 constant, 68 with float components, 67 geometric operations, 70–75 homogeneous, 174 input, 73, 176 light, 440–442, 445 member access, 68–69 memory layout, 61–67 normal, 363, 364 normalized, 71 output, 176 perpendicular, 71 reflection, 447 returned, 73 tangent, 97, 99, 363, 364 templates, 67–68 unit-length, 71, 100 zero, 68 See also mathematics system velocities angular, 594 changes, 538 constant linear, 537–538 linear, 593–594 object, 500 vertex arrays, 23 vertex collapses for 16-sided polygon, 325 computing, 322 illustrated, 324 table, 326, 327 VertexColorEffect class, 433–434 defined, 433 interface, 433 sample use, 433–434 vertex coloring, 433–434 vertex controllers, 158–159 Index VertexShader class, 464, 473–474 GetShaderType function implementation, 473 instantiation, 474 interface, 473 object, 483 vertex shaders Cg, 465–466 defined, 149–150 enabling in OpenGL, 482–483 inputs, 466–467, 486 prototypical, 462 shader constants, 470 support implementation, 463 writing, 462 See also shader programs vertex simplification, 379–382 vertex weights adjacent, 320 calculation of, 310 defined, 309 definitions for, 310 vertices batch-transforming, 326 colors, 288 disabled, 382 far plane, 260 index, 312 keep, 326, 327 model, 154 near plane, 260 normals, 288 offset, 411 order of application, 156 polygon, 345 polyline of, 580 reduced polyline, 310 renderer and, 157 reordering, 326, 331 sorting, 331 surface, 373 TeamLRN sPeCiAL throw, 326, 327 vertices (triangle), 2, 4, 200 colors, 12 connecting, 22 locations, 12 normals, 201, 202 transformed to world coordinates, 11 view frustum, 179 camera model and, 261 defined, 259 parameters, 265–268 specifying, symmetric, 267 viewport parameters, 268–270 defined, 268 offset window, 269 orientation, 269–270 position, 269–270 viewports current, 276 normalized coordinates, 528 on near plane, 529 settings, 275, 534 target display in, 534 view volume, 259 virtual function tables base class, 64 derivation support, 62 derived class, 64 results, 65 virtual function pointers, 62 virtual trackballs, 629, 630 volume masses, 586–589 deformable, 587 illustrated, 586 implementation class, 587–588 representation, 586 sample application, 589 See also masses VRAM, 335–336 discard operations, 336 limited, 335 731 W weighted squared distances, 420, 424 WglRenderer class, 277 WhichSide function, 103, 183, 342 which-side-of-plane query, 178, 180 white space, 681–685 blank lines, 682 conditionals, 684–685 function calls, 684 function declarators, 682–683 indentation, 681–682 See also coding conventions Wild Magic, 17 abstract system layer, 45 architecture, 28 classes, 67 class hierarchy, 30 collision detection support, 30 defined, 1, 28 renderers, 149 Win32, 3, WindowApplication3 class, 620–636 defined, 620 interface, 620–621 LookDown function, 625 LookUp function, 625 MoveBackward function, 624 MoveDown function, 624 MoveForward function, 623 MoveObject function, 628–629 MoveUp function, 624 OnKeyDown function, 629 OnMotion callback, 635 OnMouseClick callback, 624–625 TurnLeft function, 624 TurnRight function, 624, 625 732 Index WindowApplication class, 612–620 constructor, 614–615 defined, 612 event callbacks, 615–616 font handling support, 619 interface, 612 Main function, 614 windowing systems event handling, 615–620 main function structure, 616 windows creation step, dimensions, title, width/height, WinMain function, 601, 602 WinProc function, 10, 13 wireframes, 221 as application members, 221 TeamLRN sPeCiAL defined, 221 enabling/disabling, 221 See also global states WireframeState class, 221 Wm3System file, 31 WmifToBmp converter, 674 WndProc function, 601, 602 world bound, 155 children, 157 defined, 155 parent, 157 world bounding volumes, 186 calculation, 187 propagation, 190, 191, 194 recomputation, 189 updating, 193 world coordinates camera, 398 inertia tensor in, 593 triangle vertices transformation to, 11 world transformations, 155, 156, 164 as compositions, 186 computation, 169–170, 186 directly setting, 186 in public scope, 186 See also transformations X–Z yaw, 87 z-buffers defined, 206 state, 253 state members, 215 state pointer, 254 Abou t t he C D-R OM Elsevier CD-ROM License Agreement PLEASE READ THE FOLLOWING AGREEMENT CAREFULLY BEFORE USING THIS CD-ROM PRODUCT This CD-ROM Product is licensed under the terms contained in this CD-ROM license agreement (“Agreement”) By using this CD-ROM Product, You, an individual or entity including employees, agents and representatives (“You” or “Your”), acknowledge that You have read this agreement, that You understand it, and that You agree to be bound by the terms and conditions of this agreement Elsevier Inc (“Elsevier”) expressly does not agree to license this CD-ROM Product to You unless You assent to this agreement If You not agree with any of the following terms, You may, within thirty (30) days after Your receipt of this CD-ROM Product, return the unused CD-ROM Product and all accompanying documentation to Elsevier for a full refund Limited Warranty and Limitation of Liability Neither Elsevier nor its licensors represent or warrant that the CD-ROM Product will meet Your requirements or that its operation will be uninterrupted or errorfree We exclude and expressly disclaim all express and implied warranties not stated herein, including the implied warranties of merchantability and fitness for a particular purpose In addition, neither Elsevier nor its licensors make any representations or warranties, either express or implied, regarding the performance of Your network or computer system when used in conjunction with the CD-ROM Product We shall not be liable for any damage or loss of any kind arising out of or resulting from Your possession or use of the software product caused by errors or omissions, data loss or corruption, errors or omissions in the proprietary material, regardless of whether such liability is based in tort, contract or otherwise and including, but not limited to, actual, special, indirect, incidental or consequential damages If the foregoing limitation is held to be unenforceable, our maximum liability to You shall not exceed the amount of the purchase price paid by You for the software product The remedies available to You against us and the licensors of materials included in the software product are exclusive If this CD-ROM Product is defective, Elsevier will replace it at no charge if the defective CD-ROM Product is returned to Elsevier within sixty (60) days (or the greatest period allowable by applicable law) from the date of shipment 733 TeamLRN sPeCiAL 734 About the CD-ROM YOU UNDERSTAND THAT, EXCEPT FOR THE 60-DAY LIMITED WARRANTY RECITED ABOVE, ELSEVIER, ITS AFFILIATES, LICENSORS, SUPPLIERS AND AGENTS, MAKE NO WARRANTIES, EXPRESSED OR IMPLIED, WITH RESPECT TO THE CD-ROM PRODUCT, INCLUDING, WITHOUT LIMITATION THE PROPRIETARY MATERIAL, AND SPECIFICALLY DISCLAIM ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE IN NO EVENT WILL ELSEVIER, ITS AFFILIATES, LICENSORS, SUPPLIERS OR AGENTS, BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, WITHOUT LIMITATION, ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF YOUR USE OR INABILITY TO USE THE CD-ROM PRODUCT REGARDLESS OF WHETHER SUCH DAMAGES ARE FORESEEABLE OR WHETHER SUCH DAMAGES ARE DEEMED TO RESULT FROM THE FAILURE OR INADEQUACY OF ANY EXCLUSIVE OR OTHER REMEDY Software License Agreement This Software License Agreement is a legal agreement between Magic Software, Inc., a North Carolina corporation, and any person or legal entity using or accepting any Software governed by this Agreement The Software is available on the CD-ROM in The Book, 3D Game Engine Architecture, which is published by Morgan Kaufmann Publishers The Software includes computer source code, the associated media, any printed materials, and any online or electronic documentation The Software and any updates are available online from the Web site www.wild-magic.com By installing, copying, or otherwise using The Software, you agree to be bound by the terms of this Agreement If you not agree to the terms of this Agreement, you may not use The Software, and you should remove The Software from your computer The Software is protected by copyright laws and international copyright treaties, as well as other intellectual property laws and treaties The Software is licensed, not sold This Agreement shall be effective on the first day you use or accept The Software governed by this Agreement, whichever is earlier The parties agree as follows: Grant of License We grant you a nonexclusive license to use The Software subject to the terms and conditions of the Agreement: (a) Book Ownership You must own a copy of The Book to use The Software Ownership of The Book by two or more people does not satisfy the intent of this constraint (b) Transferability If you sell your copy of The Book to another person or legal entity, you must also transfer The Book’s CD-ROM to the purchaser You must destroy all copies of The Software on your computer(s), and you must destroy any backup copies that you have made of The Software TeamLRN sPeCiAL About the CD-ROM 735 (c) No Source Code Redistribution You may not redistribute any of the source code files of The Software, whether the original files or modified versions of the files In this sense, The Software does not conform to the Open Source Definition as stated by the Open Source Initiative at the Web site www.opensource.org We encourage you to report bugs and make suggestions for improvement In this way The Software can evolve (and has evolved) in a controlled and disciplined manner that benefits all its users (d) Binary Distribution The Software may be used by you for noncommercial or commercial products When distributed to end users, your products are a redistribution of The Software, but in a binary format obtained by compiling the source code to object code using a C++ compiler Redistribution of The Software in binary format, either as part of an executable program or as part of a dynamic link library, is allowed subject to the following conditions: The intent of this Agreement is that any product, whether noncommercial or commercial, is not built solely to wrap The Software for the purposes of redistributing it or selling it as if it were your own product The intent of this clause is that you use The Software, in part or in whole, to assist you in building your own original products An example of acceptable use is to incorporate The Software in a game to be sold to an end user An example that violates this clause is to compile a library from only The Software, bundle it with the headers files as a Software Development Kit (SDK), then sell that SDK to others Disclaimer of Warranty We make no warranties at all The Software is transferred to you on an “as is” basis You use The Software at your own peril You assume all risk of loss for all claims or controversies, now existing or hereafter, arising out of use of The Software We shall have no liability based on a claim that your use or combination of The Software with products or data not supplied by us infringes any patent, copyright, or proprietary right All other warranties, expressed or implied, including, without limitation, any warranty of merchantability or fitness for a particular purpose are hereby excluded Limitation of Liability We will have no liability for special, incidental or consequential damages even if advised of the possibility of such damages We will not be liable for any other damages or loss in any way connected with The Software Entire Agreement, Amendments This Agreement represents the complete and exclusive statement of the Agreements between the parties relating to the licensing of The Software and maintenance of The Software and supersedes all prior Agreements and representations between them relating to such licensing Modifications to this Agreement shall not be effective unless in writing and signed by the party against whom enforcement is sought The terms of this Agreement shall not be amended or changed by any purchase order or acknowledgment even if we have signed such documents TeamLRN sPeCiAL 736 About the CD-ROM North Carolina Law, Severability This Agreement will be governed by North Carolina law If any provision of this Agreement shall be unlawful, void, or for any reason unenforceable, it shall be deemed severable from and shall in no way affect the validity or enforceability of the remaining provisions of this Agreement Installing and Compiling the Source Code The Wild Magic engine is portable and runs on PCs with Microsoft Windows 2000/XP operating systems or Linux operating systems The engine also runs on Apple computers with the Macintosh OS X operating system (version 10.2.3 or higher) OpenGL renderers are provided for all the platforms Project files are provided for Microsoft Visual Studio NET 2003 on Microsoft Windows Make files are provided for Linux Xcode project files are provided for the Macintosh For convenience of copying, the platforms are stored in separate directories on the root of the CD-ROM The root of the CD-ROM contains three directories and one PDF file: Windows Linux Macintosh ReleaseNotes3p0.pdf Copy the files from the directory of your choice The directions for installing and compiling are found in the PDF file Please read the release notes carefully before attempting to compile Various modifications must be made to your development environment and some tools must be installed in order to have full access to all the features of Wild Magic Updates and Bug Fixes The Web site for version of the Wild Magic engine is www.wild-magic.com Updates and bug fixes will be posted, and a history of changes is maintained at the site TeamLRN sPeCiAL ... systems from the fundamental ideas, whether it be for games or other applications 3D Game Engine Architecture: Engineering Real- Time Applications with Wild Magic David H Eberly Real- Time Collision... sPeCiAL 3D Game Engine Architecture Engineering Real- Time Applications with Wild Magic TeamLRN sPeCiAL THE MORGAN KAUF M AN N SERI ES I N I NTERACT IVE D T ECH N O LO GY SERIES EDITOR: DAVID H EBERLY,... shipped with a CD-ROM that contained the source code for version 0.1 of the Wild Magic engine Although the algorithms have not changed over the years, the engine has evolved significantly The original