010复习详细
Data structures 1_23
Array
- simple, never grows and don’t fragment the memory
- the elements lie continuously in the memory, make traversal very cache friendly
- is good when: have limited memory or if dynamic memory is impossible, and we know how many elements we want to strore
weakness: fixed size
- if increase the size, we need create a new and copy the origin
- also insert or delete
- in C++, it will access elements out of bounds
Linked Lists
- common in game programming
- fast to add or remove elements, since no copying of other elements is required
- drawbacks
- require more memory(pointers)
- not stored consecutively, worse cache consistency
- single linked or double linked
- double linked lists require more memory, but faster if traverse the list backwards
Queue
- need elements are always sorted, priority queue is good
- update the high priority, and lower the priority if can’t update in a single frame
- priority queues are useful for pathfinding
Scriping 1_42
- game engine and game specific code is often written in a compiled language, C++. C#, Java
- compiling and building can take much time
- game designers can write some high level code for the game, be addressed using scripting
Scriping Languages
- more simple to use than fully-featured, compiled languages
- interpreted at runtime and therefore does not require any compilation
- Therefore the behavior of for example a character can be changed without having to recompile the whole game
- can often update existing scripts or write new scripts
- players can mod(ify) the game after release(无敌?)
- most important reason: the time between when we make a code change and when the results are
seen in the game - fast and easy to update scripts and see the effects
- depend on how the scripting engine works, sometimes need modify and reload while playing
Drawbacks of scripting languages
- Performance
- usually not compiled
- interpreted at runtime in the scripting engine
- lower performance than in compiled, game specific code
- Tool support
- complied language(非脚本语言) supported by development tools(Eclipse…)
- the tools are simple
- *Error handling
- since interpreted at runtime, no compiler tell you about errors in the code
- tools(开发工具) are not as rigid(精确的) as a compiler
- limited support for exception handling
- most are dynamically typed(variables don’t have type), difficult to track down bugs
- *Communicating with the game engine
- must do if want to be useful
- extensive interface to the compiled game code
- if action not in interface, can’t do it
Game system overview 2_3
Architecture
module: a group of classes that handle a specific task in the game.
Architecture types 2_5
Ad-Hoc Architecture
no organization
classes are simply added when they are needed without looking at the big picture
classes are not separated in different subsystems, tight coupling
Modular Architecture
subsystems are identified and separated into modules or libraries
modules communicate with more or less coupled ways:
tightest coupling is use direct calls; lowest coupling is use interface
drawback: dependencies between modules are not controlled, over time modules tend to be more and more dependent on each other, leading to a very tightly coupled system
Direct Acyclic Graph(DAG) Architecture
dependencies between modules are controlled, avoid getting a tightly coupled system
want to be wide and shallow
Layered Architecture
organizes modules into separate layers, and a module is only allowed to access modules in the layer directly below.
are useful in cases where we have a number of serial operations to perform
Initialization and shutdown steps 2_17
initialization purpose: load all resources needed for a part of the game
shutdown purpose: unload all resources used in a part of the game to free up memory
-
to minimize dependency problems, we can unload in reverse order
-
make sure the steps are quickly
-
good idea: Resources Acquisition Is Initialization(RAII)
When we create a game object, it is itself responsible for loading all resources (textures, collision boxes, …) it needs
When we destroy a game object, it is responsible for shutting down the resources it is using
Fast Shutdown
dedicate a large block of memory to the game world, just wipe whole the whole memory block which is an extremely fast operation
Main game loop 2_25
a running game is driven by a game loop that performs a series of tasks to keep the game world updated and alive
- gather player input
- run AI
- run physics simulation
- update game entities
- render graphics
each iteration of this game loop is called a frame
tasks take long time will cause lag, we should break it down into many frames, or use multithreading
Simulation
The game world is a simulation of a real (or fictive), living world.
->things happen in the world even without player input!
The simulation task includes a lot of subtasks:
- run AI code so entities decide what to di
- run scripts that update states or trigger events
- run physics simulation to make sure game objects move correctly in the game world
- …
the simulation is time consuming.
only run simulation for the part of the game that is visible for the player
another optimization is to keep the entities that needs updating in a priority queue
the simulation engine starts updating the entity with the highest priority, and continues until the frame time runs out.
an entity that was updated gets a lower priority and is moved back in the queue
the entities that were not updated, will be updated in the future frames
consider avoid starvation: that an entity has so low priority that it is never updated
Collision
two separate phases:
collision detection
check if it is colliding with another entity
the more complex an object is, the more expensive the collision check is
to speed up, use simplified collision
collision response
when detected, need calculate how it affects each of the entities involved
follow the laws of physics and is affected by
- the speed and direction of movement
- gravity
- friction of the ground(地面摩擦)
- material the entities are made of
If involved entities are destructible, we must also handle damage.
Rendering 6_1
rendering a three-dimensional scene onto a flat two-dimensional screen
performed by the graphics hardware
Graphics Fundamentals: Buffers
Frame Buffer and Back Buffer
the frame buffer is the location where what is shown on the actual screen is stored
- in many computer applications the GUI contents are drawn directly on the frame buffer
- but in 3D games is not feasible, user can see the frame being constructed
->Instead we construct the frame on a nonvisible area called the back buffer
- when the frame construction is finished, the back buffer is copied to the frame buffer
when compressing an image of high resolution to a lower resolution,visible distortion artifacts(aliasing) occur.
->use antialiasing techniques to minimize these artifacts
Depth Buffer
a second invisible buffer called the depth buffer(or Z-buffer, since the z-axis often represents the depth in a 3D scene)
for each pixel that is written to the back buffer, a depth value for that pixel is written to the depth buffer
The values in the depth buffer indicate how far away pixels are, and when attempting to render a new object at the same position the depth of the new object is compared with the depth stored in the depth buffer.
A major benefit with this approach is that we don’t have to render objects in a specific order based on depth.
Stencil Buffer
this buffer is often interleaved with the depth buffer: 24 of 32 bits are used for the depth buffer and the remainong 8 for the stencil buffer
the meaning is not as clearly defined, just the “really useful” buffer
common application:
- windows: value 1 inside the window, 0 otherwise
- rendering objects with reflections like a mirror
Graphics Fundamentals: Coordinate Spaces 6_17
World and Object space
the game world is located in the world space, and uses the global coordinate system
game objects are often defined in their own object space, using a local coordinate system
- before rendering an object, its location and rotation must be transformed to the world space
- other wise the renderer does not know where an object is relative to other objects
Camera Space
the camera has a space in front, called a frustum
objects are only visible if they are fully or partially inside the frustum
when the camera move or rotate, the frustum also moves and a new part of the scene will be visible
Camera Frustum
The frustum is a volume defined by six planes:
Graphics Fundamentals: Textures and Materials 6_26
总结 Meshes & Materials
a mesh is a collection of triangles forming an object
each triangle also have a material which is used to render the triangle
a material is a description of how to render the triangle:
- which texture to use, and texture coordinates
- which shader to use
Textures
is mapped onto a mesh
a textures is a surface that holds data called texels(texture pixel)
a texels holds a color(RGB) and often an alpha transparency channel
Textures are 2D arrays representing a picture that is mapped onto an object. 3D arrays, Cube map…
The texture is used by a shader to calculate how the object looks like in the current lighting conditions
Texture mapping
Shaders
it determine the shape (vertex shader) and color (pixel shader) of a mesh.
this is necessary since meshes are deformed(due to perspective) when placed on the screen, and we also have different lighting in a scene
Materials
a material is a destription of how to render a triangle
usually consists of associated textures, reflectivity…, and which shader(s) to use
Meshes
An object can have multiple meshes, which allows it to represent objects with multiple materials.
The atomic operation of the hardware is to draw a set of triangles with a single material.
Graphics Fundamentals: more about Textures 6_56
Texture formats
- No alpha required: DXT1
- Low precision alpha is enough: DXT3
- High precision alpha is required: DXT5
Mipmap chains
It is a sequence of the same picture, but each is half the size in each dimension as the previous one.
shrinking an image to a smaller size can lead to aliasing artifacts which makes the texture look bad.
Mipmapping is a very effective approach for reducing aliasing artifacts.
Texture Filtering
When mapping a square texture onto a non-square mesh surface, or when rotating or shrinking a texture artifacts can appear.
point sampling
we simply use the texel color at the coordinate we have calculated.
bilinear filtering
It uses the nearest four texels to construct the color for a pixel.
trilinear filtering
an extension of bilinear filtering
This is done by doing bilinear filtering on two mipmap entries and then interpolate between the two results.
It does two bilinear filtering operations plus an interpolation
anisotropic filtering
It uses the mipmap version in the least filtered direction (horizontally), and uses a filter to reduce aliasing when reducing the size vertically.
Graphics Fundamentals: Lighting 6_85
the position and direction of a light source determines which surfaces it is shining on
the material or the surface determines how the light is reflected
we typically have:
- bright directional lights: processed in high detail
- ambient light: a small constant lighting is added to surfaces, simulating background lighting
- It is based on the assumption that there is always some light bouncing around in random directions in a scene illuminating every surface.
- This models how lighting can be scattered or reflected many times producing a uniform effect.
Animation 7_2
Bone-based animation
In a bone-based system, we have bones arranged in a tree hierarchy.
Each bone hangs from a single parent bone, and each bone may have multiple child bones.
Two bones are connected with a joint.
-
forward Kinematics
We can determine the position of the last bone depending on the translation and orientation of the previous bones.
-
Inverse Kinematics
Now the position of the end bone is fixed, and the bones higher up in the hierarchy is moved to keep it there
Animations 7_13
Storage, Keyframes
store an animation by certain keyframes, and interpolate between them
Interpolation
Interpolation between translation and scale is simple.
For rotation this is however not as simple
Rotation 7_23
Rotation means how the bone is rotated in the joint relative to its parent bone.
Euler Angles
x, y, z控制
先x后y和先y后x不同
problem:
there is no efficient interpolation method that always produce
good results.
solution:
- 3x3 Rotation Matrix
- Quaternions
Gimbal lock
To save space, we store character animations in keyframes and interpolate between the orientations of two frames.
Storing every possible orientation between two frames would take up too much memory.
*3x3 Rotation Matrix
Quaternions
Quaternions does not suffer from the polar problem of Euler angles and requires less memory than 3x3 rotation matrices.
A quaternion is a vector composed of the four components x, y, z and w.
The (x, y, z) values are chosen so that the length of the vector defines the sine value of half the rotation angle.
The w value defines the cosine value of half the rotation angle.
Both rotations have the same half-angle sine values, but different half-angle cosine values.
Interpolating between two quaternions is fast and gives reasonably good results.
总结
- Don’t suffer from the Gimbal lock problem.
- Require less memory than 3x3 rotation matrices.
- Are easy to interpolate.
Complex Motions 7_48
Cubic Bezier curve
to interpolate between two keyframes F1 and F2, we also need to define two control points T1 and T2
memory consuming
however can make memory optimizations
接起来,但是也有不可以接起来的情况,C1(方向相反),C0(位置不对)
Motion Extraction 7_77
走路的动作要和position的位置一致
Linear Motion Extraction
- take the root bone position at the last animation frame
- subtract by the root bone position at the first animation frame
- now we know the travel distance for the animation
- linearly interpolate when playing the animation
drawback:
it does not capture rotational movement
Composite Motion Extraction
instead of interpolating between the last and first frame, we interpolate between each keyframe in the animation
Variable Delta Extraction
deal with non-linear interpolation between keyframes
we need to sample the animation each frame, and calculate the translational change of the root bone between the current and previous frame(delta).
the delta is then used to move the instance
the instance then always follows the root bone
Game Agents 8_10
non-player characters(NPCs)
game AI=game agents
agent: an autonomous entity that can sense its environment and act intelligently upon it
Game agents usually follow a three step sense-think-act cycle
sense
know about the current state of the game world
the AI has perfect information about the game world
usually be given similar limitations as humans have
One such (human) limitation is vision. In a realistic setting agents cannot see everything.
距离、角度、有没有被挡住
Step 3 is unfortunately a very costly operation requiring rays to be cast from the agent towards the other game object, and test the rays for collisions.
解决3的方法
using simplified bounding boxes instead of the complex mesh of game objects
it is easier to see moving objects than stationary objects.
hearing
noise attract
communicate
reaction times
adding some reaction time to agents can enhance the realism.
think
- rule-based system
- state machines
act
remember that this is what the player sees
flee action(逃跑)
Finite-State Machines 8_28
A FSM is one way to implement the behavior of an agent
An FSM consists of states, transitions between states, and conditions for a transition
an agent can only be one state at a time
each state has its own logic
When an agent is in a specific state, the logic for that state is executed.
After executing the state logic, rules are checked for transition to a new state.
- Moore machine: code is executed within states
- Mealy machine: code is executed at transitions between states
Pathfinding 8_58
Grid
Characters can move from the center of one square to the center of an adjacent square.
Smaller squares give better paths, but pathfinding takes longer time to complete.
Waypoint Graph
Characters can only move on links that connect two waypoints.
Does not cover the whole game world => It is an incomplete representation.
More waypoints give better paths, but pathfinding takes longer time to complete.
Navigation Mesh
The game world is divided into convex polygons.
Characters can move freely within a polygon, and edges can connect a polygon to another polygon.
Covers the whole game world (complete epresentation).
Depth-First Search
complete, not-optimal
New nodes are added first in the open list (LIFO).
Greedy Search(Best-First Search)
an informed search algorithm
pick the most promising node in the open list.
A node is more promising the closer it is to the goal node
We cannot know exactly which node is the closest (the problem would already be solved then), but we can make an educated guess.
to make a guess we use a heuristic function. it gives a numerical value for how promising each node is
the most common heuristic function in pathfinding is Euclidean distance
The open list is sorted on Euclidean distance, lowest
value first.
complete, non-optimal
A-star(A*)
complete, optimal
The only difference from Greedy Search is that A-star uses a slightly more complex heuristic function:
Object-oriented design in games
Component systems 1_64
- relies on the composition principle
- create one base class and attach components, not create separate classes
- component has some logic or functionality
- component is simply to be added or replaced to change functionality
- add or remove don’t need recompilation(can change during running)
Data-Driven Composition
- game entities are defined in separate data files
- change without recompile
- loose coupling
Development processes 1_90
Waterfall model
Numerial Quantities: Matrix 4_15
rows and columns
square matrix
the main diagonal entries
a diagonal matrix
MT, exchanging the rows and columns
a symmetric matrix
an n-dimensional vector V
a column vector
Matrix multiplication
Identity matrix, 和它相乘等于自己
Inverse M − 1 M^{-1} M−1和它相乘是单位矩阵
The Dot Product 4_27
点乘
x和x乘…
v w cosα
- 点乘为0,垂直orthogonal
- 大于0,锐角
- 小于0,钝角
Collision Detection and Response 4_63
Overlap Testing
Optimizing Collision Detection
two ways to optimize collision detection
- using simplified collision volumes
- organizing entities in for example grids or BSP trees to reduce the number of entity pairs we need to calculate collisions for
The Five-Step Debugging Process
1 Reproduce the Problem Consistently
create a set of “repro steps” that show how to reproduce the bug every time
- provide valuable clues
- a systematic way
- can be used in regression testing
2 Collect Clues
clues suggest where problem might be
be aware that some clues are false
don’t spend too long- get in and observe
3 Pinpoint the Error
focus your search and pinpoint the error
- propose a hypothesis
- use the divide-and-conquer method
4 Repair the Problem
Propose solution. Exact solution depends upon stage of problem
Ideally, want original coder of fix
Consider other similar cases, even if not ye reported
5 Test the Solution
So, test that solution repairs bug
Best by independent tester
set of “repro steps” that show how to reproduce the bug every time
- provide valuable clues
- a systematic way
- can be used in regression testing