
1ee0a2e2026fd3d552469d1e3e8d1203.ppt
- Количество слайдов: 69
CSCE 590 E Spring 2007 Game Programming By Jijun Tang
Announcements n n n We will meet in 2 A 21 on Wednesday Please bring laptops (with mouse) on Wednesday Please install 3 D Canvas Pro Flash Game due this Wednesday Small game due Friday, March 9 th, 5: 00 pm
Game Design Presentation n n Two presentations, on March 5 th and March 7 th. March 5 th: group A, Cheeze Puffs!, Team Swampus March 7 th: Group D, Group E, Psychosoft Each has 20 minutes to present, 5 minutes to answer questions
Contents for the Presentation n n Description, specification, goals, game play System requirement, audience, rating Interface, input/output, interactions, cameras Premise/limitations/choices/resources Content designs, audio Level designs, flexibility Use case/UML (rough) Engines to use Version control/testing strategy Brief timeline (demo date is May 2 nd-9 th)
Logos-so-far
3 D Canvas Pro n n n http: //www. amabilis. com/ Requires XP/2000, Direct. X 9 Requires license code Installation package is available for download After installation, enter the code under the help menu
Programming Teams n n In the 1980 s programmers developed the whole game (and did the art and sounds too!) Now programmers write code to support designers and artists (content creators)
Different Programs n Game code ¡ Anything n related directly to the game Game engine ¡ Any code that can be reused between different games n Tools ¡ In house tools ¡ Plug-ins for off-the-shelf tools
Methodologies n n Code and Fix Waterfall Iterative Agile
Make Coding Easier n n n Version control Coding standards Automated build Code review Unit testing and acceptance testing
Languages n n n C/C++ Java Script: Flash, Python, LISP, etc. C# XNA for PC and Xbox
Programming Fundamentals
Data Structures: Array n Elements are adjacent in memory (great cache consistency) ¡ n They never grow or get reallocated ¡ ¡ n Use dynamic incremental array concept GCC has a remalloc function In C++ there's no check for going out of bounds ¡ ¡ n Requires continuous memory space Use vector if possible Keep in mind of checking boundaries Inserting and deleting elements in the middle is expensive
List n n n Very cheap to add/remove elements. Available in the STL (std: : list) Every element is allocated separately, not placed contiguously in memory ¡ Lots of little allocations ¡ Bad cache awareness, but can use arrays to hold pre-allocated items n Single/Double linked list
Lists
Dictionaries n n n Maps a set of keys to some data. std: : map, std: : hash, etc Very fast access to data Perfect for mapping IDs to pointers, or resource handles to objects May waste space, need to design comparison operators
Hash Table
Others n Stacks ¡ First in, last out ¡ std: : stack adaptor in STL n Queues ¡ First in, first out ¡ std: : deque ¡ Priority queue is useful in game to schedule events
Stack/Queue/Priority Queue
Bit packing n n n Fold all necessary data into a smaller number of bits Bool in C++ may use up to 4 bytes, thus is very expensive Very useful for storing boolean flags: pack 32 in an integer Possible to apply to numerical values if we can give up range or accuracy Very low level trick ¡ ¡ Use shifts to handle the operation or use assembly Only use when absolutely necessary
Bits
OO Design and Patterns
Object Oriented Design n Concepts ¡ Class n Abstract specification of a data type ¡ Instance n. A region of memory with associated semantics to store all the data members of a class ¡ Object n Another name for an instance of a class
Inheritance n n Models “is-a” relationship Extends behavior of existing classes by making minor changes Do not overuse, if possible, use component systerm UML diagram representing inheritance
Polymorphism n n n The ability to refer to an object through a reference (or pointer) of the type of a parent class Key concept of object oriented design C++ implements it using virtual functions
Multiple Inheritance n n n Allows a class to have more than one base class Derived class adopts characteristics of all parent classes Huge potential for problems (clashes, casting, dreaded diamond, etc) Multiple inheritance of abstract interfaces is much less error prone (virtual inheritance) Java has no multiple inheritance
The Dreaded Diamond
Limitations of inheritance n n n Tight coupling Unclear flow of control Not flexible enough ¡ ¡ n A person is an employee, and a father What if the person is also an employer Static hierarchy ¡ ¡ The inheritance hierarchy is fixed at instantiation The object's type does not change with time.
Component Systems n n Use aggregation (composition) instead of inheritance A game entity can “own” multiple components that determine its behaviour Each component can execute whenever the entity is updated Messages can be passed between components and to other entities
Component Systems n Component system organization
Benefits of Component Systems n Data-Driven Composition ¡ The structure of the game entities can be specified in data ¡ Components are created and loaded at runtime ¡ Very easy to change (which is very important in game development)
Analysis of Component System n n Very hard to debug Performance can be a bottleneck Keeping code and data synchronized can be a challenge Extremely flexible ¡ n Great for experimentation and varied gameplay Not very useful if problem/game is very well known ahead of time
Design Patterns n n n Design pattern is a general repeatable solution to a commonly occurring problem in software design Design patterns can speed up the development process by providing tested, proven development paradigms Algorithm (for computation problem) is not pattern (for design)
Object Factory n n n Creates objects by name Pluggable factory allows for new object types to be registered at runtime Extremely useful in game development for passing messages, creating new objects, loading games, or instantiating new content after game ships
UML for Factory
Singleton n Implements a single instance of a class with global point of creation and access For example, GUI Don't overuse it!!!
Observer n n Allows objects to be notified of specific events with minimal coupling to the source of the event Two parts ¡ subject and observer
UML for Observer
Composite n n Allow a group of objects to be treated as a single object Very useful for GUI elements, hierarchical objects, inventory systems, etc
UML for Composite
Debugging
The Five Step Debugging Process 1. Reproduce the problem consistently 2. Collect clues 3. Pinpoint the error 4. Repair the problem 5. Test the solution
Step 1: Reproduce the Problem Consistently Sample reproduce steps: 1. Start a single player game 2. Choose Skirmish on map 44 3. Find the enemy camp 4. From a distance, use projectile weapons to attack the enemies at the camp 5. Result: 90 percent of the time the game crashes
Step 2: Collect Clues n n n Each clue a chance to rule out a cause Each clue a chance to narrow down the list of suspects Realize that some clues can be misleading and should be ignored
Step 3: Pinpoint the Error Two main methods: 1. Propose a Hypothesis n n You have an idea what is causing the bug Design tests to prove or disprove your hypothesis 2. Divide and Conquer n Narrow down what could be causing the bug ¡ ¡ Eliminate possibilities from the top down or Backtrack from the point of failure upward
Step 4: Repair the Problem n n Propose solution Consider implications at point in project Programmer who wrote the code should ideally fix the problem (or at least be consulted) Explore other ways the bug could occur ¡ ¡ Ensure underlying problem fixed and not just a symptom of the problem Bug trace database
Step 5: Test the Solution n n Verify the bug was fixed Check original repro steps Ideally have someone else independently verify the fix Make sure no new bugs were introduced At the very end of the project, have other programmers review the fix
Expert Debugging Tips n n n Question assumptions Minimize interactions and interference Minimize randomness Break complex calculations into steps Check boundary conditions, use assertions Disrupt parallel computations Exploit tools in the debugger (VC is good) Check code that has recently changed Explain the bug to someone else Debug with a partner (A second pair of eyes) Take a break from the problem Get outside help (call people)
Tough Debugging Scenarios n Bug exists in Release but not Debug ¡ n Bug exists on final hardware, not dev-kit ¡ n Retry, Rebuild, Reboot, Reinstall Internal compiler errors ¡ n Record as much info when it does happen Unexplainable behavior ¡ n Timing or memory overwrite problem Intermittent problems ¡ n Find out how they differ – usually memory size or disc emulation Bug disappears when changing something innocuous (e. g. , add a print) ¡ n Uninitialized data or optimization issue Full rebuild, divide and conquer, try other machines Suspect it’s not your code ¡ ¡ Check for patches, updates, or reported bugs Contact console maker, library maker, or compiler maker
Understanding the Underlying System n Knowing C or C++ not enough ¡ ¡ Know how the compiler implements code, and optimize code Know the details of your hardware n ¡ Especially important for console development Know some assembly and be able to read it n n Read memories will help Helps with optimization bugs or compiler issues
Adding Infrastructure to Assist in Debugging n n n n Alter game variables during gameplay Visual AI diagnostics Logging capability Recording and playback capability Track memory allocation Print as much information as possible on a crash Educate your entire team ¡ testers, artists, designers, producers
Prevention of Bugs n n n Set compiler to highest warning level Set compiler warnings to be errors Compiler on multiple compilers Write your own memory manager Use asserts to verify assumptions Initialize variables when they are declared Bracket loops and if statements Use cognitively different variable names Avoid identical code in multiple places Avoid magic (hardcoded) numbers Verify code coverage when testing
Game Architecture
Overall Architecture n n The code for modern games is highly complex With code bases exceeding a million lines of code, a well-defined architecture is essential
Overall Architecture n Main structure ¡ ¡ ¡ n Game-specific code Game-engine code Both types of code are often split into modules, which can be static libraries, DLLs, or just subdirectories Architecture types ¡ ¡ Ad-hoc (everything accesses everything) Modular DAG (directed acyclic graph) Layered
Overall Architecture n Options for integrating tools into the architecture ¡ Separate code bases (if there's no need to share functionality) ¡ Partial use of game-engine functionality ¡ Full integration
Overview: Initialization/Shutdown n n The initialization step prepares everything that is necessary to start a part of the game The shutdown step undoes everything the initialization step did, but in reverse order
Overview: Initialization/Shutdown n Resource Acquisition Is Initialization ¡ ¡ n A useful rule to minimalize mismatch errors in the initialization and shutdown steps Means that creating an object acquires and initializes all the necessary resources, and destroying it destroys and shuts down all those resources Optimizations ¡ ¡ Fast shutdown Warm reboot
Overview: Main Game Loop n n n Games are driven by a game loop that performs a series of tasks every frame Some games have separate loops for the front and the game itself Other games have a unified main loop
Overview: Main Game Loop n Tasks ¡ ¡ ¡ ¡ Handling time Gathering player input Networking Simulation Collision detection and response Object updates Rendering Other miscellaneous tasks
Overview: Main Game Loop n Structure ¡ Hard-coded loops ¡ Multiple game loops n For each major game state ¡ Consider through steps as tasks to be iterated
Overview: Main Game Loop n Coupling ¡ Can decouple the rendering step from simulation and update steps ¡ Results in higher frame rate, smoother animation, and greater responsiveness ¡ Implementation is tricky and can be errorprone
Overview: Main Game Loop n Execution order ¡ Most of the time it doesn't matter ¡ In some situations, execution order is important ¡ Can help keep player interaction seamless ¡ Can maximize parallelism ¡ Exact ordering depends on hardware
Game Entities n What are game entities? ¡ ¡ ¡ n Basically anything in a game world that can be interacted with More precisely, a self-contained piece of logical interactive content Only things we will interact with should become game entities Organization ¡ ¡ Simple list Multiple databases Logical tree Spatial database
Game Entities n Updating ¡ Updating each entity once per frame can be too expensive ¡ Can use a tree structure to impose a hierarchy for updating ¡ Can use a priority queue to decide which entities to update every frame
Game Entities n Object creation ¡ Basic object factories ¡ Extensible object factories ¡ Using automatic registration ¡ Using explicit registration
Game Entities n Level instantiation ¡ Loading a level involves loading both assets and the game state ¡ It is necessary to create the game entities and set the correct state for them ¡ Using instance data vs. template data
Game Entities n Identification ¡ Strings ¡ Pointers ¡ Unique IDs or handles
Game Entities n Communication ¡ Simplest method is function calls ¡ Many games use a full messaging system ¡ Need to be careful about passing and allocating messages
1ee0a2e2026fd3d552469d1e3e8d1203.ppt