1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control.

Slides:



Advertisements
Similar presentations
7.2. AI E NGINE AND S TEERING B EHAVIOUR I Design of an AI Engine and introduction to steering in game AI.
Advertisements

Finite State Machines in Games
Chapter 4.2 Collision Detection and Resolution. 2 Collision Detection Complicated for two reasons 1. Geometry is typically very complex, potentially requiring.
Flocking and more.  NPC groups can move in cohesive groups not just independently ◦ Meadow of sheep grazing? ◦ Hunting flock of birds? ◦ Ants? Bees?
LOCOMOTION IN INTERACTIVE ENVIRONMENTS Navjot Garg.
Steering Behaviors GAM 376 Robin Burke Winter 2008.
Artificial Intelligence in Game Design Representing NPCs as Finite State Machines.
The Bioloid Robot Project Presenters: Michael Gouzenfeld Alexey Serafimov Supervisor: Ido Cohen Winter Department of Electrical Engineering.
1 CO Games Development 2 Week 22 Flocking Gareth Bellaby.
Optimizing Flocking Controllers using Gradient Descent
Kristen Gardner. Outline Swarm Intelligence Flocking Basic Steering Swarms Applications Animals Vehicles People.
Artificial Intelligence in Game Design Intelligent Decision Making and Decision Trees.
Artificial Intelligence in Game Design Hierarchical Finite State Machines.
On the Impact of Delay on Real-Time Multiplayer Games Authors: Lothar Pantel, Lars C. Wolf Presented by: Bryan Wong.
1Notes. 2 Building implicit surfaces  Simplest examples: a plane, a sphere  Can do unions and intersections with min and max  This works great for.
Chapter 4.2 Collision Detection and Resolution. 2 Collision Detection Complicated for two reasons 1. Geometry is typically very complex, potentially requiring.
Game Design and Programming. Objectives Classify the games How games are design How games are implemented What are the main components of a game engine.
1 Geometry A line in 3D space is represented by  S is a point on the line, and V is the direction along which the line runs  Any point P on the line.
CS274 Spring 01 Lecture 5 Copyright © Mark Meyer Lecture V Higher Level Motion Control CS274: Computer Animation and Simulation.
Introduction What is this ? What is this ? This project is a part of a scientific research in machine learning, whose objective is to develop a system,
Crowd Simulation Seminar ”Steering Behaviors For Autonomous Characters” By Craig W. Reynolds Rudi Bonfiglioli ( )
Steering Behaviors For Autonomous Characters
1 Advanced Scene Management System. 2 A tree-based or graph-based representation is good for 3D data management A tree-based or graph-based representation.
Tactical AI in Real Time Supervisor: Aleks Jakulin Crew: Damir Arh, Matija Jekovec, Mitja Luštrek Gregor Leban, Martin Žnidaršič, Uroš Čibej Translation:
University of Texas at Austin CS 378 – Game Technology Don Fussell CS 378: Computer Game Technology Beyond Meshes Spring 2012.
SE320: Introduction to Computer Games Week 8: Game Programming Gazihan Alankus.
Crowd Simulations Guest Instructor - Stephen J. Guy.
Artificial Intelligence in Game Design Camera Control.
Modeling and Animation with 3DS MAX R 3.1 Graphics Lab. Korea Univ. Reference URL :
CSE 381 – Advanced Game Programming 3D Game Architecture.
Artificial Intelligence in Game Design Event and Sense Management.
Chapter 11-Multimedia Authoring Tools. Overview Introduction to multimedia authoring tools. Types of authoring tools. Cross-platform authoring notes.
Creative Commons Attribution 3.0 creativecommons.org/licenses/by/3.0 Key Abstractions in Game Maker Foundations of Interactive Game Design Prof. Jim Whitehead.
Collision and Animation Systems in Games Jani Kajala Lead Programmer / Chief Technology Officer, Pixelgene Ltd (0)
DEVSView: A DEVS Visualization Tool Wilson Venhola.
1 Animation & Java3D ©Anthony Steed Overview n Introduction to Animation Kinematics Dynamics Boids n Java3D Scene graph Animation Vehicles.
Flow Fields Hao Li and Howard Hamilton. Motivation for Flow Fields Multiple AI algorithms in a computer game can produce conflicting results. The AI must.
An Introduction to Programming and Algorithms. Course Objectives A basic understanding of engineering problem solving process. A basic understanding of.
Steering Autonomous Characters Spring 2005 Ref: Craig Reynolds.
CHAPTER TEN AUTHORING.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 7 The Game Loop and Animation Starting Out with Games & Graphics.
Review IMGD Engine Architecture Types Broadly, what are the two architecture types discussed for game engines? What are the differences?
Math / Physics 101 GAM 376 Robin Burke Fall 2006.
Web Games Programming An Introduction to Unity 3D.
1 Game AI Finite State Machine. Finite State Machine (FSM) is the most commonly used Game AI technology Finite State Machine (FSM) is the most commonly.
Developing An Educational Rigid Body Dynamics Physics Engine By Neal Milstein.
Introduction to Flash Animation CS 318. Topics Introduction to Flash and animation The Flash development environment Creating Flash animations  Layers.
Game Maker Terminology
1 Game AI Steering Behavior & Group Movement ( 轉向行為 及 群體運動 )
Artificial Intelligence in Game Design Complex Steering Behaviors and Combining Behaviors.
Games Development Game Architecture: Entities CO2301 Games Development 1 Week 22.
1 Contents  Audio  Sprite  Input devices  Game production milestones  Course summary.
Games Development 2 Entity Update & Rendering CO3301 Week 2, Part 1.
Artificial Intelligence for Games Finite State Machines
11 General Game Programming Approach. The program is event-driven The program is event-driven –Messages = events –So as all windows system (for example.
Microsoft Visual Basic 2010 CHAPTER TWO Program and Graphical User Interface Design.
1 Game Control. 2 Camera Control Types Types First-personal view First-personal view Third-personal view but following the playable character Third-personal.
Kalpaware presents. Demo.
Artificial Intelligence in Game Design Lecture 8: Complex Steering Behaviors and Combining Behaviors.
CSCI 4310 Lecture 5: Steering Behaviors in Raven.
1 Game AI Finite State Machine. 2 Finite State Machine (FSM) is the Most Commonly used Game AI Technology Today Finite State Machine (FSM) is the Most.
Introduction to Game Programming & Design III Lecture III.
Finite State Machines Logical and Artificial Intelligence in Games Lecture 3a.
Computer Graphics Imaging Ying Zhu Georgia State University Lecture 29 Soft Bodies and Rigid Bodies.
UNIT 11: 3D AutoCAD Objectives: How to print or plot a drawing How to setup a layout using title blocks and viewports Create and manage new layouts Be.
Game Maker Tutorials Introduction Clickball IntroductionClickball Where is it? Shooting Where is it?Shooting.
Review IMGD Engine Architecture Types Broadly, what are the two architecture types discussed for game engines? What are the differences?
© University of Wisconsin, CS559 Fall 2004
CIS 488/588 Bruce R. Maxim UM-Dearborn
Games Development Game Architecture: Entities
Presentation transcript:

1 Game System

2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control Camera control View angle View angle View range View range Interaction with player Interaction with player A “walk through” system A “walk through” system Combat system Combat system Controls Controls Motion management and blending Motion management and blending NPC AI NPC AI FX FX Visual Visual Audio Audio Simplify Your Thinking into Modula (1/2)

3 Reward system Reward system Number system Number system Levels Levels Damage Damage User Interface User Interface Menu Menu Mini-map Mini-map Messages Messages Blood bar Blood bar Caption Caption The main program The main program Main loop Main loop Level management Level management Configuration Configuration Save/Load Save/Load Simplify Your Thinking into Modula (2/2)

4

5 Game AI Steering Behavior

6 Action selection Action selection Steering Steering Locomotion Locomotion Motion Behavior A Hierarchy of Motion Behavior

7 Game AI engine Game AI engine State machine State machine Discussed in “Finite State Machine” section Discussed in “Finite State Machine” section Goals Goals Planning Planning Strategy Strategy Scripting Scripting Assigned by players Assigned by players Players’ input Players’ input Action Selection

8 Path determination Path determination Path finding or path planning Path finding or path planning Discussed in “Path Finding” Discussed in “Path Finding” Behaviors Behaviors Seek & flee Seek & flee Pursuit & evasion Pursuit & evasion Obstacle avoidance Obstacle avoidance Wander Wander Path following Path following Unaligned collision avoidance Unaligned collision avoidance Group steering Group steeringSteering

9 Character physically-based models Character physically-based models Movement Movement Turn right, move forward, … Turn right, move forward, … Animation Animation By artists By artists Implemented / managed by game engine Implemented / managed by game engineLocomotion

10 A point mass A point mass Linear momentum Linear momentum No rotational momentum No rotational momentum Parameters Parameters Mass Mass Position Position Velocity Velocity Modified by applied forces Modified by applied forces Max speed Max speed Top speed of a vehicle Top speed of a vehicle Max steering force Max steering force Self-applied Self-applied Orientation Orientation Car Car Aircraft Aircraft A Simple Vehicle Model (1/2)

11 Local space Local space Origin Origin Forward Forward Up Up Side Side Steering forces Steering forces Asymmetrical Asymmetrical Thrust Thrust Braking Braking Steering Steering Velocity alignment Velocity alignment No slide, spin, … No slide, spin, … Turn Turn A Simple Vehicle Model (2/2)

12 The approach : The approach : Steer_force = Truncate(streer_direction, Max_force) Steer_force = Truncate(streer_direction, Max_force) Acceleration = Steer_force / mass Acceleration = Steer_force / mass Velocity = Truncate(Velocity + Acceleration, Max_speed) Velocity = Truncate(Velocity + Acceleration, Max_speed) Position = Position + Velocity Position = Position + Velocity Euler Integration

13 Pursuit to a static target Pursuit to a static target Steer a character toward to a target position Steer a character toward to a target position “A moth buzzing a light bulb” “A moth buzzing a light bulb” Flee Flee Inverse of seek Inverse of seek Variants Variants Arrival Arrival Pursuit to a moving target Pursuit to a moving target Seek & Flee Behaviors Seek Steering force Seek Steering force desired_velocity = normalize(target - position)*max_speed desired_velocity = normalize(target - position)*max_speed steering = desired_velocity – velocity steering = desired_velocity – velocity

14 One of the idea : a stopping radius One of the idea : a stopping radius Outside the radius, arrival is identical to seek Outside the radius, arrival is identical to seek Inside the radius, the speed is ramped down to zero Inside the radius, the speed is ramped down to zero target_offset = target – position target_offset = target – position distance = length(target_offset) distance = length(target_offset) ramped_speed = max_speed*(distance/slowing_distance) ramped_speed = max_speed*(distance/slowing_distance) clipped_speed = minimum(ramped_speed, max_speed) clipped_speed = minimum(ramped_speed, max_speed) desired_velocity = (clipped_speed/distance)*target_offset desired_velocity = (clipped_speed/distance)*target_offset steering = desired_velocity – velocity steering = desired_velocity – velocity Arrival Behavior

15 Target is moving Target is moving Apply seek or flee to the target’s predicted position Apply seek or flee to the target’s predicted position Pursuit & Evasion Behaviors Estimate the prediction interval T Estimate the prediction interval T T = Dc T = Dc D = distance(pursur, quarry) D = distance(pursur, quarry) c = turning parameter c = turning parameter Variants Variants Offset pursuit Offset pursuit “Fly by” “Fly by”

16 Use bounding sphere Use bounding sphere Not collision detection Not collision detection Obstacle Avoidance Behavior steering force Probe Probe A cylinder lying along forward axis A cylinder lying along forward axis Diameter = character’s bounding sphere Diameter = character’s bounding sphere Length = speed (means Alert range) Length = speed (means Alert range) Find the most threaten obstacle Find the most threaten obstacle Nearest intersected obstacle Nearest intersected obstacle Steering Steering

17 Random steering Random steering One solution : One solution : Retain steering direction state Retain steering direction state Constrain steering force to the sphere surface located slightly ahead of the character Constrain steering force to the sphere surface located slightly ahead of the character Make small random displacements to it each frame Make small random displacements to it each frame A small sphere on sphere surface to indicate and constrain the displacement A small sphere on sphere surface to indicate and constrain the displacement Wander Behavior Another one : Another one : Perlin noise Perlin noise Variants Variants Explore Explore

18 The path The path Spine Spine A spline or poly-line to define the path A spline or poly-line to define the path Pipe Pipe The tube or generated cylinder by a defined “radius” The tube or generated cylinder by a defined “radius” Path Following Behavior Variants Variants Wall following Wall following Containment Containment Following Following A velocity-based prediction position A velocity-based prediction position Inside the tube Inside the tube Do nothing about steering Do nothing about steering Outside the tube Outside the tube “Seek” to the on-path projection “Seek” to the on-path projection

19 A flow field environment is defined. A flow field environment is defined. Virtual reality Virtual reality Not common in games Not common in games Flow Field Following Behavior

20 Turn away from possible collision Turn away from possible collision Predict the potential collision Predict the potential collision Use bounding spheres Use bounding spheres Unaligned Collision Avoidance Behavior If possibly collide, If possibly collide, Apply the steering on both characters Apply the steering on both characters Steering direction is possible collision result Steering direction is possible collision result Use “future” possible position Use “future” possible position The connected line between two sphere centers The connected line between two sphere centers

21 Steering behaviors determining how the character reacts to the other characters within his/her local neighborhood Steering behaviors determining how the character reacts to the other characters within his/her local neighborhood The behaviors including : The behaviors including : Separation Separation Cohesion Cohesion Alignment Alignment Steering Behaviors for Groups of Characters

22 The local neighborhood is defined as : The local neighborhood is defined as : A distance A distance The field-of-view The field-of-view Angle Angle The Local Neighborhood of a Character The Neighborhood

23 Make a character to maintain a distance from others nearby. Make a character to maintain a distance from others nearby. Compute the repulsive forces within local neighborhood Compute the repulsive forces within local neighborhood Calculate the position vector for each nearby Calculate the position vector for each nearby Normalize it Normalize it Weight the magnitude with distance Weight the magnitude with distance 1/distance 1/distance Sum the result forces Sum the result forces Negate it Negate it Separation Behavior

24 Make a character to cohere with the others nearby Make a character to cohere with the others nearby Compute the cohesive forces within local neighborhood Compute the cohesive forces within local neighborhood Compute the average position of the others nearby Compute the average position of the others nearby Gravity center Gravity center Apply “Seek” to the position Apply “Seek” to the position Cohesion Behavior

25 Make a character to align with the others nearby Make a character to align with the others nearby Compute the steering force Compute the steering force Average the together velocity of all other characters nearby Average the together velocity of all other characters nearby The result is the desired velocity The result is the desired velocity Correct the current velocity to the desired one with the steering force Correct the current velocity to the desired one with the steering force Alignment Behavior

26 “Boids Model of Flocks” “Boids Model of Flocks” [Reynolds 87] [Reynolds 87] Combination of : Combination of : Separation steering Separation steering Cohesion steering Cohesion steering Alignment steering Alignment steering For each combination including : For each combination including : A weight for combing A weight for combing A distance A distance An Angle An Angle Flocking Behavior

27 Follow a leader Follow a leader Stay with the leader Stay with the leader “Pursuit” behavior (Arrival style) “Pursuit” behavior (Arrival style) Stay out of the leader’s way Stay out of the leader’s way Defined as “next position” with an extension Defined as “next position” with an extension “Evasion” behavior when inside the above area “Evasion” behavior when inside the above area “Separation” behavior for the followers “Separation” behavior for the followers Leader Following Behavior

28 A simple vehicle model with local neighborhood A simple vehicle model with local neighborhood Common steering behaviors including : Common steering behaviors including : Seek Seek Flee Flee Pursuit Pursuit Evasion Evasion Offset pursuit Offset pursuit Arrival Arrival Obstacle avoidance Obstacle avoidance Wander Wander Path following Path following Behavior Conclusion Wall following Wall following Containment Containment Flow field following Flow field following Unaligned collision avoidance Unaligned collision avoidance Separation Separation Cohesion Cohesion Alignment Alignment Flocking Flocking Leader following Leader following Combining the above behaviors in your application Combining the above behaviors in your application

29 Game AI Finite State Machine

30 Finite State Machine (FSM) is the most commonly used game AI technology today. Finite State Machine (FSM) is the most commonly used game AI technology today. Simple Simple Efficient Efficient Easily extensible Easily extensible Powerful enough to handle a wide variety of situations Powerful enough to handle a wide variety of situations Theory (simplified) Theory (simplified) A set states, S A set states, S An input vocabulary, I An input vocabulary, I Transition function, T(s, i) Transition function, T(s, i) Map a state and an input to another state Map a state and an input to another state Introduction (1/2)

31 Practical use Practical use State State Behavior Behavior Transition Transition Across states Across states Conditions Conditions It’s all about driving behavior It’s all about driving behavior Flow-chart diagram Flow-chart diagram UML State chart UML State chart Arrow Arrow Transition Transition Rectangle Rectangle State State Introduction (2/2)

32 An Example of FSM As a Diagram Gather Treasure Flee Fight Monster in sight No monster Monster dead Cornered

33 Character AI Character AI “Decision-Action” model “Decision-Action” model Behavior Behavior Mental state Mental state Transition Transition Players’ action Players’ action The other characters’ actions The other characters’ actions Some features in the game world Some features in the game world FSM for Games

34 Code-based FSM Code-based FSM Simple Code One Up Simple Code One Up Straightforward Straightforward Most common Most common Macro-assisted FSM Language Macro-assisted FSM Language Data-Driven FSM Data-Driven FSM FSM Script Language FSM Script Language Implement FSM

35 Coding an FSM – Code Example 1 void RunLogic(int *state) { switch(*state) switch(*state) { case 0: // Wander case 0: // Wander Wander(); Wander(); if (SeeEnemy()) *state = 1; if (SeeEnemy()) *state = 1; if (Dead()) *state = 2; if (Dead()) *state = 2; break; break; case 1: // Attack case 1: // Attack Attack(); Attack(); *state = 0; *state = 0; if (Dead()) *state = 2; if (Dead()) *state = 2; break; break; case 2: // Dead case 2: // Dead SlowlyRot(); SlowlyRot(); break; break; }}

36 Coding an FSM – Code Example 2 void RunLogic(FSM *fsm) { // Do action based on the state and determine next input // Do action based on the state and determine next input input = 0; input = 0; switch(fsm->GetStateID()) switch(fsm->GetStateID()) { case 0: // Wander case 0: // Wander Wander(); Wander(); if (SeeEnemy()) input = SEE_ENEMY; if (SeeEnemy()) input = SEE_ENEMY; if (Dead()) input = DEAD; if (Dead()) input = DEAD; break; break; case 1: // Attack case 1: // Attack Attack(); Attack(); input = WANDER; input = WANDER; if (Dead()) input = DEAD; if (Dead()) input = DEAD; break; break; case 2: // Dead case 2: // Dead SlowlyRot(); SlowlyRot(); break; break; } // DO state transition based on computed input // DO state transition based on computed input fsm->StateTransition(input); fsm->StateTransition(input);}

37 Mealy & Moore Machines Mealy machine Mealy machine A Mealy machine is an FSM whose actions are performed on transitions A Mealy machine is an FSM whose actions are performed on transitions Moore machine Moore machine A Moore machine’s actions reside in states A Moore machine’s actions reside in states More intuitive for game developers More intuitive for game developers

38 FSM Language Use Macros Coding a state machine directly causes lack of structure Coding a state machine directly causes lack of structure Going complex when FSM at their largest Going complex when FSM at their largest Use macros Use macros Beneficial properties Beneficial properties Structure Structure Readability Readability Debugging Debugging Simplicity Simplicity

39 FSM Language Use Macros – An Example #define BeginStateMachine … #define State(a) … … bool MyStateMachine::States(StateMachineEvent event, int state) int state){ BeginStateMachine BeginStateMachine State(0) State(0) OnUpdate OnUpdate Wander(); Wander(); if (SeeEnemy()) SetState(1); if (SeeEnemy()) SetState(1); if (Dead()) SetState(2); if (Dead()) SetState(2); State(1) State(1) OnUpdate OnUpdate Attack(); Attack(); SetState(0); SetState(0); if (Dead()) SetState(2); if (Dead()) SetState(2); State(2); State(2); OnUpdate OnUpdate RotSlowly(); RotSlowly(); EndStateMachine EndStateMachine}

40 Data-Driven FSM Scripting language Scripting language Text-based script file Text-based script file Transformed into Transformed into C++ C++ Integrated into source code Integrated into source code Bytecode Bytecode Interpreted by the game Interpreted by the game Authoring Authoring Compiler Compiler AI editing tool AI editing tool Game Game FSM script engine FSM script engine FSM interface FSM interface

41 Data-Driven FSM Diagram Authoring FSMs bytecode Compiler AI Editing Tool Condition & Action Vocabulary Games FSM Script Engine FSM Interface Condition & Action Code Game Engine Artist, Designers, & Developers

42 AI Editing Tool for FSM Pure text Pure text Syntax ? Syntax ? Visual graph with text Visual graph with text Used by Designers, Artists, or Developers Used by Designers, Artists, or Developers Non-programmers Non-programmers Conditions & action vocabulary Conditions & action vocabulary SeeEnemy SeeEnemy CloseToEnemy CloseToEnemy Attack Attack …

43 FSM Interface Facilitating the binding between vocabulary and game world Facilitating the binding between vocabulary and game world Glue layer that implements the condition & action vocabulary in the game world Glue layer that implements the condition & action vocabulary in the game world Native conditions Native conditions SeeEnemy(), CloseToEnemy() SeeEnemy(), CloseToEnemy() Action library Action library Attack(…) Attack(…)

44 FSM Script Language Benefits Accelerated productivity Accelerated productivity Contributions from artists & designers Contributions from artists & designers Ease of use Ease of use Extensibility Extensibility

45 Processing Models for FSMs Processing the FSMs Processing the FSMs Evaluate the transition conditions for current state Evaluate the transition conditions for current state Perform any associated actions Perform any associated actions When and how ? When and how ? Depend on the exact need of games Depend on the exact need of games Three common FSM processing models Three common FSM processing models Polling Polling Event-driven Event-driven Multithread Multithread

46 Polling Processing Model Processing each FSM at regular time intervals Processing each FSM at regular time intervals Tied to game frame rate Tied to game frame rate Or some desired FSM update frequency Or some desired FSM update frequency Limit one state transition in a cycle Limit one state transition in a cycle Give a FSM a time-bound Give a FSM a time-bound Pros Pros Straightforward Straightforward Easy to implement Easy to implement Easy to debug Easy to debug Cons Cons Inefficiency Inefficiency Some transition are not necessary to check every frame Some transition are not necessary to check every frame Careful design to your FSM Careful design to your FSM

47 Event-driven Processing Model Designed to prevent from wasted FSM processing Designed to prevent from wasted FSM processing An FSM is only processed when it’s relevant An FSM is only processed when it’s relevant Implementation Implementation A Publish-subscribe messaging system (Observer pattern) A Publish-subscribe messaging system (Observer pattern) Allows the engine to send events to individual FSMs Allows the engine to send events to individual FSMs An FSM subscribes only to the events that have the potential to change the current state An FSM subscribes only to the events that have the potential to change the current state When an event is generated, the FSMs subscribed to that events are all processed When an event is generated, the FSMs subscribed to that events are all processed “As-needed” approach “As-needed” approach Should be much more efficient than polling ? Should be much more efficient than polling ? Tricky balance for fine-grained or coarse-grained events Tricky balance for fine-grained or coarse-grained events

48 Multithread Processing Model Both polling & event-driven are serially processed Both polling & event-driven are serially processed Multithread processing model Multithread processing model Each FSM is assigned to its own thread for processing Each FSM is assigned to its own thread for processing Game engine is running in another separate thread Game engine is running in another separate thread All FSM processing is effectively concurrent and continuous All FSM processing is effectively concurrent and continuous Communication between threads must be thread-safe Communication between threads must be thread-safe Using standard locking & synchronization mechanisms Using standard locking & synchronization mechanisms Pros Pros FSM as an autonomous agent who can constantly and independently examine and react to his environment FSM as an autonomous agent who can constantly and independently examine and react to his environment Cons Cons Overhead when many simultaneous characters active Overhead when many simultaneous characters active Multithreaded programming is difficult Multithreaded programming is difficult

49 Interfacing with Game Engine (1/2) FSMs encapsulate complex behavior logic FSMs encapsulate complex behavior logic Decision, condition, action, … Decision, condition, action, … Game engine does corresponding Game engine does corresponding Character animation, movements, sounds, … Character animation, movements, sounds, … The interface : The interface : Code each action as a function Code each action as a function Need recompile if any code is changed Need recompile if any code is changed ie., FleeWolf() ie., FleeWolf() Callbacks Callbacks Function pointers Function pointers ie., actionFunction[fleeWolf]() ie., actionFunction[fleeWolf]() Container method Container method actionFunctions->FleeWolf(); actionFunctions->FleeWolf(); DLL DLL

50 Interfacing with Game Engine (2/2) Take TheFly3D as example: Take TheFly3D as example: class AArmyUnit : public FnCharacter { … void DoAttack(…); } AArmyUnit *army; army->Object(…); army->MoveForward(dist, …); … army->DoAttack(…);

51 FSM Efficiency & Optimization Two categories : Two categories : Time spent Time spent Computational cost Computational cost Scheduled processing Scheduled processing Priority for each FSM Priority for each FSM Different update frequency Different update frequency Load balancing scheme Load balancing scheme Collecting statistics of past performance & extrapolating Collecting statistics of past performance & extrapolating Time-bound for each FSM Time-bound for each FSM Do careful design Do careful design At the design level At the design level Level-of-detail FSMs Level-of-detail FSMs

52 Level-Of-Detail FSMs Simplify the FSM when the player won’t notice the differences Simplify the FSM when the player won’t notice the differences Outside the player’s perceptual range Outside the player’s perceptual range Just like the LOD technique used in 3D game engine Just like the LOD technique used in 3D game engine Three design keys : Three design keys : Decide how many LOD levels Decide how many LOD levels How much development time available ? How much development time available ? The approximation extent The approximation extent LOD selection policy LOD selection policy The distance between the NPC with the player ? The distance between the NPC with the player ? If the NPC can “see” the player ? If the NPC can “see” the player ? Be careful the problem of “visible discontinuous behavior” Be careful the problem of “visible discontinuous behavior” What kind of approximations What kind of approximations Cheaper and less accurate solution Cheaper and less accurate solution

53 Extending the Basic FSM Extending states Extending states Begin-end block Begin-end block BeginDoAction(); DoActions(); EndDoAction(); Stacks & FSMs Stacks & FSMs Stack-based “history” of FSMs Stack-based “history” of FSMs “Remember” the sequence of states passed through “Remember” the sequence of states passed through “Retrace” its steps at will “Retrace” its steps at will Hierarchical FSM Hierarchical FSM Polymorphic FSMs Polymorphic FSMs Fuzzy State Machine Fuzzy State Machine Combined with fuzzy logic Combined with fuzzy logic

54 A Hierarchical FSM Example Gather Treasure Flee Fight Monster in sight No monster Monster dead Cornered Find Treasure Go To Treasure Take Treasure Find Treasure Gather Treasure Live Active FSM Stack

55 Another Hierarchical FSM Example Patrol Investigate Attack Done Noise Saw Enemy Done Go to A Look for Intruders Go to B Look for Intruders Patrol Report Noise Go Over To Noise Look for Intruders False Alarm! Investigate noise

56 More Topics in Game AI Scripting Scripting Goal-based planning Goal-based planning Rule-based inference engine Rule-based inference engine Neural network Neural network References References Game Gems Game Gems AI Game Programming Wisdom AI Game Programming Wisdom

57 Shadows (brief version)

58Contents Fake shadow Fake shadow Traditional projected shadow Traditional projected shadow Two-pass shadow rendering Two-pass shadow rendering Projective texture mapping Projective texture mapping Shadow mapping (shader) Shadow mapping (shader) Shadow volume Shadow volume

59Shadows light source occluder receiver shadow penumbra umbra

60 Traditional Projected Shadow By Jim Blinn By Jim Blinn Me and My (Fake) Shadow Me and My (Fake) Shadow IEEE Computer Graphics and Applications, January, 1988 IEEE Computer Graphics and Applications, January, 1988 Project the geometry on the “ground” plane. Project the geometry on the “ground” plane. Scale the height to zero. Scale the height to zero. Make the shadow material to black. Make the shadow material to black. Polygon solution Polygon solution “Flat” shadow on the ground. “Flat” shadow on the ground.

61 Two-pass Shadow Rendering First pass : First pass : Treat the light source as the camera. Treat the light source as the camera. Assign the material color of the object (to be shadowed) Assign the material color of the object (to be shadowed) 1 – shadow_color 1 – shadow_color “Render” the object on a texture (shadow map). “Render” the object on a texture (shadow map). Second pass : Second pass : Texture map the shadow map on the terrain with Texture map the shadow map on the terrain with Source_blend = zero Source_blend = zero Destination_blend = 1 – source_color Destination_blend = 1 – source_color Pros Pros Easy to implement Easy to implement Cons Cons Texture resolution Texture resolution Z fighting Z fighting Aliasing Aliasing

62 Game Control System

63 Introduction (1/2) Game control is the interface between the game and the user. Game control is the interface between the game and the user. Game control is not only input device control but also camera control Game control is not only input device control but also camera control Input device control Input device control On PC On PC Mouse Mouse Keyboard Keyboard Gamepad Gamepad On game console On game console Gamepad Gamepad 0 or or 255 Joystick Joystick

64 Introduction (2/2) Camera control Camera control First-personal view First-personal view Third-personal view Third-personal view God view God view Pre-set camera view Pre-set camera view

65 Mouse Control (1/3) Mouse is a 2D device. Mouse is a 2D device. 2-axis moving 2-axis moving Related movement Related movement 2 or 3 buttons 2 or 3 buttons Mouse can Mouse can Move Move Drag Drag Double-click Double-click Behaviors Behaviors Hit test Hit test Selection Selection Pilot Pilot Position & orientation Position & orientation

66 Mouse Control (2/3) Typical game types using mouse control Typical game types using mouse control Real-time strategy games Real-time strategy games Role Playing Game Role Playing Game Typical game play examples : Typical game play examples : Path finding for playable character Path finding for playable character Hitting the enemy Hitting the enemy Selecting a group of units Selecting a group of units Orientating the camera in FPS games Orientating the camera in FPS games Menu selection Menu selection … Features Features Always coupling with god-view camera control Always coupling with god-view camera control Viewing from the top of game world Viewing from the top of game world

67 Mouse Control (3/3) Easy to hand on Easy to hand on 一鼠到底 一鼠到底 Slow action Slow action Compared with joystick Compared with joystick Value range from Value range from

68 Keyboard Control (1/3) Standard PC input device Standard PC input device Simulating the gamepads usually Simulating the gamepads usually Not every PC game player having gamepad Not every PC game player having gamepad Using keyboard as the alternative device Using keyboard as the alternative device Hotkey system Hotkey system Each key has two states. Each key has two states. Pressed Pressed Released Released 256 keys 256 keys Behaviors Behaviors Key presses/released Key presses/released ASCII code ASCII code One hotkey can represent a command One hotkey can represent a command

69 Keyboard Control (2/3) Communication tool Communication tool Typing messages Typing messages Typical game types using keyboard Typical game types using keyboard MMORPG MMORPG Needs chatting with friends Needs chatting with friends Real-time strategy games Real-time strategy games Hotkey system Hotkey system First-person shooting games First-person shooting games Fighting games Fighting games Typical game play examples : Typical game play examples : Chatting Chatting Character controls Character controls Move forward Move forward Turning Turning

70 Keyboard Control (3/3) Features Features Shortcut for a sequence of actions Shortcut for a sequence of actions Commands Commands Menu selection Menu selection But a little bit complicated for players But a little bit complicated for players 256 keys 256 keys

71 Gamepad Control (1/3) A small “keyboard” designed for game playing A small “keyboard” designed for game playing Gamepad can map to the hotkey system Gamepad can map to the hotkey system Same behaviors Same behaviors Less than 20 keys Less than 20 keys Majors keys : Majors keys :

72 Gamepad Control (2/3) Recent gamepad capable of two extra digital joysticks Recent gamepad capable of two extra digital joysticks For keys For keys Value range : 0 or 255 Value range : 0 or 255 For joystick For joystick Value range : 0 to 255 Value range : 0 to 255 Typical game types using gamepad Typical game types using gamepad Almost all types of games except Almost all types of games except Need typing Need typing Need large-range selection for game units Need large-range selection for game units Typical game play examples : Typical game play examples : Character controls Character controls Move forward Move forward Turn Turn

73 Gamepad Control (3/3) Combat system in a fighting game Combat system in a fighting game Move forward Move forward Turn Turn … Features Features Designed for game playing Designed for game playing Look and feel Look and feel Easy to hand-on Easy to hand-on If you not to challenge the players’ usual practice If you not to challenge the players’ usual practice

74 Camera Control Types Types First-personal view First-personal view Third-personal view but following the playable character Third-personal view but following the playable character God view God view Fixed Fixed Following the playable character Following the playable character Fixed view Fixed view Pre-rendered background Pre-rendered background Pre-set view Pre-set view … Very sensitive to game play design & game control Very sensitive to game play design & game control Camera control is not an independent system Camera control is not an independent system

75 God-view Camera Example Age of Empire 3

76 Game Control Case Study – Third-personal View (1/6) Use arrow keys on keyboard or gamepad Use arrow keys on keyboard or gamepad Basic key assignments : Basic key assignments : Up key to move the playable character forward Up key to move the playable character forward Down key to turn character facing to the camera and move forward Down key to turn character facing to the camera and move forward Left & right keys to turn the character to left or right Left & right keys to turn the character to left or right

77 Game Control Case Study – Third-personal View (2/6) The camera following the character to move The camera following the character to move And keeping a range of distance, a reasonable height and look-down angle with the character. And keeping a range of distance, a reasonable height and look-down angle with the character.  Distance PC Camera Height

78 Game Control Case Study – Third-personal View (3/6) Detailed key assignments : Detailed key assignments : Up key Up key Turn the character facing back to the camera Turn the character facing back to the camera Move the character forward Move the character forward If the distance between the character and the camera is larger a pre-set range, move the camera forward to keep the distance. If the distance between the character and the camera is larger a pre-set range, move the camera forward to keep the distance. At the same time, the height to the ground will be changed to synchronize with the character. At the same time, the height to the ground will be changed to synchronize with the character. Down key Down key Turn the character facing to the camera Turn the character facing to the camera Move the character forward Move the character forward The camera will move backward to keep a distance with the character. The camera will move backward to keep a distance with the character. The height to the ground will be changed to synchronize with the character. The height to the ground will be changed to synchronize with the character.

79 Game Control Case Study – Third-personal View (4/6) If the camera is blocked by obstacle to move backward, raise the height of the camera but keep the eyes on the character. If the camera is blocked by obstacle to move backward, raise the height of the camera but keep the eyes on the character. PC Camera

80 Game Control Case Study – Third-personal View (5/6) Right key Right key Turn the character facing to the right of the camera. Turn the character facing to the right of the camera. Take the camera’s position as a circle center and the distance between the camera and the character as the radius. Take the camera’s position as a circle center and the distance between the camera and the character as the radius. Set the circle as the movement orbit. Set the circle as the movement orbit. Let the character move on the orbit. Let the character move on the orbit. When the character moving, turn the camera to right to keep eyes on the character. When the character moving, turn the camera to right to keep eyes on the character.

81 Game Control Case Study – Third-personal View (6/6) When the character hitting the obstacle, let the character keep on turning and moving, use the same approach in “Down key” step to raise the camera. When the character hitting the obstacle, let the character keep on turning and moving, use the same approach in “Down key” step to raise the camera. Left key Left key As same as “Right key” step except the left direction. As same as “Right key” step except the left direction. Reference game examples: Reference game examples: Sprinter cell 3 Sprinter cell 3 PSO PSO Prince of Persia( 波斯王子 ) Prince of Persia( 波斯王子 ) The Legend of Zelda ( 薩爾達傳說 ) The Legend of Zelda ( 薩爾達傳說 ) … Demo : DCI students’ work : iRobot Demo : DCI students’ work : iRobot