45
University of Texas at Austin CS 378 – Game Technology Don Fussell CS 378: Computer Game Technology Game Engine Architecture Spring 2012

CS 378: Computer Game Technology

  • Upload
    kyrene

  • View
    55

  • Download
    0

Embed Size (px)

DESCRIPTION

CS 378: Computer Game Technology. Game Engine Architecture Spring 2012. What is a Game Engine?. Runtime system Low-level architecture 3-d system Physics system GUI system Sound system Networking system High-level architecture Game objects Attributes Behaviors Game mechanics - PowerPoint PPT Presentation

Citation preview

Page 1: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

CS 378: Computer Game Technology

Game Engine ArchitectureSpring 2012

Page 2: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

What is a Game Engine?Runtime system

Low-level architecture3-d systemPhysics systemGUI systemSound systemNetworking system

High-level architectureGame objects

AttributesBehaviors

Game mechanics

World editorTool(s) for defining world chunks (e.g. levels) and static and dynamic game objects

Page 3: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Game Engine Subsystems

Runtime object modelRealtime object model updatingMessaging and event handlingScriptingLevel management and streamingObjectives and game flow management

Page 4: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

What are Game Objects?

Anything that has a representation in the game worldCharacters, props, vehicles, missiles, cameras, trigger volumes, lights, etc.

Created/modified by world editor toolsManaged at runtime in the runtime engineNeed to present an object model to designers in the editorNeed to implement this object model at runtime efficiently

Page 5: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Runtime Object Model Architectures

Object-centricObjects implemented as class instancesObject’s attributes and behaviors encapsulated within the class(es)Game world is a collection of game object class instances

Property-centricObject attributes are implemented as data tables, one per attribute Game objects are just IDs of some kindProperties of an object are distributed across the tables, keyed by the object’s idObject behaviors implicitly defined by the collection of properties of the objectProperties may be implemented as hard-coded class instancesLike a relational database system in some ways

Page 6: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Object-centric Architectures

Natural taxonomy of game object typesCommon, generic functionality at rootSpecific game object types at the leaves

GameObject

MovableObject

DrawableObject

PacMan Ghost Pellet

PowerPellet

Hypothetical PacMan Class Hierarchy

Page 7: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Monolithic Class Hierarchies

Very intuitive for small simple casesTend to grow ever wider and deeperVirtually all classes in the game inherit from a common base class

Actor

Brush

Controller

Info

Pawn

Vehicle

UnrealPawn

RedeemerWarhead

Scout

AIController

PlayerController

GameInfo

Light

Inventory

HUD

Pickup

Ammo

ArmorPickup

WeaponPickup

Ammunition

Powerups

Weapon

……

…Part of object class hierarchy from Unreal Tournament 2004

Page 8: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Vehicle

Hard to understand, maintain, and modify classesNeed to understand a lot of parent classes

Hard to describe multidimensional taxonomiesWhat if you want to classify objects along more than one axis?E.g. how would you include an amphibious vehicle in the class hierarchy below?

Problems with Monolithic Hierarchies

LandVehicle

Car Motorcycle Truck

WaterVehicle

Yacht Sailboat Cruiser

Page 9: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Tempted to use Multiple Inheritance?

NOOOO!!!!!There’s a reason languages like Java don’t have itDerived classes often end up with multiple copies of base class members

Better to use composition or aggregation than inheritanceMix-in classes (stand alone classes with no base class) are particularly useful here (even with multiple inheritance)

Vehicle

LandVehicle

AmphibiousVehicle

WaterVehicle

Page 10: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Mix-ins Perhaps?

Drawable(renderable model)

Simulated(rigid body model)

Trigger(volume)

GameObject(transform, refcount)

AnimatedMixin(animation controller)

Animated

AnimatedWithPhysics

Page 11: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Observations

Not every set of relationships can be described in a directed acyclic graphClass hierarchies are hard to changeFunctionality drifts upwardsSpecializations pay the memory cost of the functionality in siblings and cousins

Page 12: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Components vs. Inheritance

A simple generic GameObject specialized to add properties up to full blown physical simulationWhat if (as in your current games) you want to use physical simulation on objects that don’t use skeletal animation?

GameObject

MovableObject

DrawableObject

CollisionObject

AnimatedObject

PhysicalObject

Page 13: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Components vs. Inheritance

One “hub” object that contains pointers to instances of various service class instances as needed.

GameObject

Transform

AnimationController

MeshInstance

RigidBody

Page 14: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Component-based exampleclass GameObject {protected: // My transform (position, rotation, scale) Transform m_transform; // Standard components MeshInstance* m_pMeshInst; AnimationController* m_pAnimController; RigidBody* mpRigidBodypublic: GameObject() { // Assume no components by default. Derived classes will override m_pMeshInst = NULL; m_pAnimController = NULL; m_pRigidBody = NULL; } ~GameObject() { // Automatically delete any components created by derived classes delete m_pMeshInst; delete m_pAnimController; delete m_pRigidBody; // …};

Page 15: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Component-based exampleclass Vehicle : public GameObject {protected: // Add some more components specific to vehicles Chassis* m_pChassis; Engine* m_pEngine; // …public: Vehicle() { // Construct standard GameObject components m_pMeshInst = new MeshInstance; m_pRigidBody = new RigidBody; m_pAnimController = new AnimationController(*m_pMeshInst); // Construct vehicle-specific components m_pChassis = new Chassis(*this, *m_pAnimController); m_pEngine = new Engine(*this); } ~Vehicle() { // Only need to destroy vehicle-specific components delete m_pChassis; delete m_pEngine; }};

Page 16: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Example properties

“Hub” class owns its components (it manages their lifetimes, i.e. creates and destroys them)How does it know which components to create?In this simple case, the GameObject class has pointers to all possible components, initialized to NULLOnly creates needed components for a given derived classDestructor cleans up all possible components for convenienceAll optional add-on features for derived classes are in component classes

Page 17: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

More flexible (and complex) alternative

Root GameObject contains a linked list of generic componentsDerive specific components from the component base classAllows arbitrary number of instances and types of components

GameObject

TransformRigidBod

yAnimationController

MeshInstance

Component+GetType()+isType()+ReceiveEvent()+Update()

Page 18: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Why not get rid of GameObject?

If a GameObject instance becomes just an empty container of pointers to components with an object ID, why not just get rid of the class entirely?Create a component for a game object by giving the component class instance for that object the object’s unique ID.Components logically grouped by an ID form a “game object”Need fast component lookup by IDUse factory classes to create components for each game object typeOr, preferably use a “data driven” model to read a text file that defines object typesHow about inter-object communication? How do you send a message to an “object” and get the proper response?

Know a priori which component gets a given messageMulticast to all of the components of an object

Page 19: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Property-centric Architectures

Think in terms of properties (attributes) of objects rather than in terms of objectsFor each property, build a table containing that property’s values keyed by object IDNow you get something like a relational database

Each property is like a column in a database table whose primary key is the object ID

Where are the object’s behaviors defined?Each type of property can be implemented as a property classDo it with scripts, have one of an object’s properties by ScriptIDScripts can also be the target of messages

Page 20: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Pros and consPros

More memory-efficientOnly store properties in use, no unused data members in objects

Easier to construct in a data-driven wayDefine new attributes with scripts, less recoding of class definitions

Can be more cache-friendlyData tables loaded into contiguous locations in cacheStruct of arrays (rather than array of structs) principle

ConsHard to enforce relationships among propertiesHarder to implement large-scale behaviors if they’re composed of scattered little pieces of fine-grained behaviorHarder to debug, can’t just put a game object into a watch window in the debugger and see what happens to it.

Page 21: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Component-Based Approach

Related to, but not the same as aspect-oriented programmingOne class, a container for:

attributes (data)behavior (logic)

Attributes := list of key-value pairsBehavior := object with OnUpdate() and OnMessage()

Page 22: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Components vs Hierarchies

Prop

GameObject

GameObject

Attribute<T> Behaviour

* *

Page 23: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Hulk:Ultimate Destruction Object Model

CCharacter+Renderable+Simulation+Intention+Motion+Locomotion+Sequencer+Charge+Effects+Targetting+Throwing+Attachment*+AI+Health+Scenario+Cloud+Variables+11 diffferent updates()

CSPHulkPropInstance+Renderable+Simulation+State machine+Targetting+Throwing+Attachment+AI+Health+Collectable+Update()

0..1

CCow+Animation+State machine+AI+Update()

1

CCivilian+Renderable+Animation+State machine+Simulation+AI+Health+Throwing+Update()

AmbientManager+Civilians+Vehicles+Cows+Update()

*

*

Page 24: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Prototype Game Objects

AlexPhysicsBehaviourTouchBehaviourCharacterIntentionBehaviourMotionTreeBehaviourCollisionActionBehaviourPuppetBehaviourCharacterMotionBehaviourMotionStateBehaviourRagdollBehaviourCharacterSolverBehaviourHealthBehaviourRenderBehaviourSensesInfoBehaviourHitReactionBehaviourGrabSelectionBehaviourGrabbableBehaviour

TargetableBehaviourAudioEmitterBehaviourFightVariablesBehaviour

ThreatReceiverBehaviour

HelicopterPhysicsBehaviourTouchBehaviourCharacterIntentionBehaviourMotionTreeBehaviourCollisionActionBehaviourPuppetBehaviour

CharacterSolverBehaviourHealthBehaviourRenderBehaviour

HitReactionBehaviour

GrabbableBehaviourGrabBehaviorTargetableBehaviourAudioEmitterBehaviourFightVariablesBehaviourEmotionalStateBehaviourThreatReceiverBehaviourFEDisplayBehaviour

Pedestrian(HLOD)PhysicsBehaviour

CharacterIntentionBehaviourMotionTreeBehaviour

PuppetBehaviour

HealthBehaviourRenderBehaviour

GrabbableBehaviourGrabBehaviourTargetableBehaviourAudioEmitterBehaviour

EmotionalStateBehaviour

FEDisplayBehaviourCharacterPedBehaviour

Pedestrian(LLOD)

SensesInfoBehaviour

TargetableBehaviour

PedBehaviour

Page 25: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Data-Driven Creation

Text or binaryLoaded from pipelineLoad and goDelayed instancingDedicated toolsData-driven inheritance

Page 26: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Data-Driven Advantages

Endowing with new properties is easyCreating new types of entities is easyBehaviours are portable and reusableCode that talks to game objects is type-agnosticEverything is packaged and designed to talk to each otherIn short: you can write generic code

Page 27: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Data-Driven Disadvantages

In short: you have to write generic codeGame objects are typeless and opaqueCan’t ask, e.g.

if object has AttachableBehaviourthen attach to it

Code has to treat all objects identicallyThis is wrong!

Page 28: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Messaging

AttachMessage msg(this);object->OnMessage(&msg);

Dispatched immediately to all interested behaviours (synchronous operation)Fast, but not as fast as a function callUse for irregular (unscheduled) processing

Collisions, state transitions, event handling

Can be used for returning values

Page 29: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Attribute Access

The game object must be notified if you modify an attributeConst accessor

Read-only accessCacheable

Non-const accessorPermits writingNot cacheableSends a notification message to the game object

Free access from object’s own behaviours

Page 30: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

An attribute or not an attribute?

Attribute ifaccessed by more than one behaviour, oraccessed by external code

Otherwise a private member of the behaviourIf not sure, make it an attribute

Page 31: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Game Object Update

GameObject::OnUpdate(pass, delta)for b in behaviours

b.OnUpdate(pass, delta)OnUpdate() and OnMessage() are the only two entry points to a behaviour.

Page 32: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Health Behavior Examplevoid HealthBehaviour::OnMessage(Message* m) { switch (m.type) { case APPLY_DAMAGE: Attribute<float>* healthAttr = GetAttribute(HEALTH_KEY); healthAttr->value -= m.damage; if (healthAttr->value < 0.f) mGameObject->SetLogicState(DEAD); break;

case ATTR_UPDATED: if (m.key == HEALTH_KEY){ Attribute<float>* healthAttr = GetAttribute(HEALTH_KEY); if (healthAttr->value < 0.f) mGameObject->SetLogicState(DEAD); } break; }}

Page 33: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Components in Practice

Behaviours and Attributesin [PROTOTYPE]

Page 34: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Adoption

Some coders were resistant:Too complicated

Don’t know what’s going onToo cumbersome

Calling a function is easier than sending a messageReading a data member is easier than retrieving an attribute

Don’t like typeless objects

Ongoing education

Page 35: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Post-Mortem Survey

0

2

4

6

8

10

12

14

Adoption Coding Debugging Maintenance Reuse Performance Overall

Much worse A little worse About the Same A little better Much better

Page 36: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Post-Mortem Comments

Data-driven creation was the biggest winPrototyping is the biggest win once you have a library of behaviorsModularity of behaviors was the biggest winData inheritance was the biggest winComponents are nothing new - no modern game could be built without them

Page 37: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Performance

GameObject::OnUpdate and OnMessage are easy targets

For the criticFor the optimiser

Existing optimisations:Message masksUpdate masksLogic state masksTime-slicingAttribute cachingLeaving the back door open

Page 38: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Performance LessonsBest optimizations are algorithmic:

Avoid unnecessary messages, e.g.

object->OnMessage(&message1);if (message1.x)object->OnMessage(&message2);

Prefer attributes over messagesAvoid unnecessary updates

Better instrumentationLegalize the back door entrance

Page 39: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Future Improvements

Stateless behavioursSubmit batches of objects to stateless behaviours

Better suited for parallel architectures

Message queuing

Page 40: CS  378:  Computer Game Technology

Prototype’s Data Types

1544 game object definitions145 unique behaviours335 unique data types

156 unique prop types alone

0

5

10

15

20

25

30

1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47

Number of behaviours

Num

ber

of u

niqu

e ty

pes

Page 41: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Behavior Usage

0.00%

10.00%

20.00%

30.00%

40.00%

50.00%

60.00%

70.00%

80.00%

Ren

derB

ehav

iour

prot

o::H

itRea

ctio

nBeh

avio

ur

Gra

bbab

leB

ehav

iour

prot

o::H

ealth

Beh

avio

ur

Cha

ract

erIn

tent

ionB

ehav

iour

Targ

etS

elec

tionB

ehav

iour

prot

o::T

hrea

tRec

eive

rBeh

avio

ur

Cha

ract

erS

olve

rBeh

avio

ur

prot

o::S

houl

derC

onFi

xupB

ehav

iour

prot

o::S

cary

Mon

ster

Beh

avio

ur

Wal

king

Beh

avio

ur

prot

o::H

ealth

Sha

derB

ehav

iour

LOD

Ren

derB

ehav

iour

engi

ne::T

rigge

rBeh

avio

ur

prot

o::A

IFly

ingP

atro

lBeh

avio

ur

prot

o::H

elic

opte

rMov

emen

tBeh

avio

ur

prot

o::T

ankI

nten

tionB

ehav

iour

Tank

Aim

Beh

avio

ur

prot

o::P

oiso

nRea

ctio

nBeh

avio

ur

prot

o::V

ehic

leB

ehav

iour

Am

bien

t

prot

o::A

utoT

arge

tingB

ehav

iour

TagB

ehav

iour

engi

ne::R

agdo

llLO

DB

ehav

iour

prot

o::D

ecal

Beh

avio

ur

engi

ne::A

dver

tisem

entB

ehav

iour

engi

ne::N

ISP

laye

rBeh

avio

ur

prot

o::L

ight

Dec

alB

ehav

iour

prot

o::M

issi

leJB

ehav

iour

Thre

atB

allB

ehav

iour

prot

o::Z

oneB

ehav

iour

prot

o::B

lobS

hado

wB

ehav

iour

prot

o::G

roun

dSpi

keB

ehav

iour

engi

ne::L

ight

Beh

avio

ur

prot

o::T

rans

form

atio

nBeh

avio

ur

prot

o::In

fect

edP

edB

ehav

iour

prot

o::D

istr

ictB

ehav

iour

prot

o::S

tayO

nNav

mes

hBeh

avio

ur

Page 42: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Implicit “Class Hierarchy”

Page 43: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Implicit “Class Hierarchy”

Page 44: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Prop Hierarchy

Page 45: CS  378:  Computer Game Technology

University of Texas at Austin CS 378 – Game Technology Don Fussell

Summary

Designs changeClass hierarchies don’t like changeComponents do, but not without some sacrifices