51
1 Game Physics Game Physics

1 Game Physics. 2 Introduction to Game Physics Traditional game physics Traditional game physics Particle system Particle system Rigid body dynamics Rigid

Embed Size (px)

Citation preview

1

Game PhysicsGame Physics

22

Introduction to Game PhysicsIntroduction to Game Physics Traditional game physicsTraditional game physics

Particle systemParticle system Rigid body dynamicsRigid body dynamics Flexible body dynamicsFlexible body dynamics

Some state-of-art topicsSome state-of-art topics Car physicsCar physics Fluid dynamicsFluid dynamics Rag-doll physicsRag-doll physics

PhysicsPhysics Rigid body kinematicsRigid body kinematics Newton’s LawsNewton’s Laws ForcesForces MomentumMomentum EnergyEnergy

33

Game Physics Applications in Games (1/2)Game Physics Applications in Games (1/2) In generalIn general

Particle system for combat effectsParticle system for combat effects First-person shootingFirst-person shooting

Rag-doll systemRag-doll system Physical character motion simulationPhysical character motion simulation

Rigid-body dynamicsRigid-body dynamics Fracture mechanicsFracture mechanics

SportsSports Rag-doll systemRag-doll system

Physical character motion simulation Physical character motion simulation Fluid dynamicsFluid dynamics

Car racingCar racing Car physicsCar physics Rigid-body dynamicsRigid-body dynamics Fracture mechanicsFracture mechanics

44

Game Physics Applications in Games (2/2)Game Physics Applications in Games (2/2) FightingFighting

Flexible-body dynamicsFlexible-body dynamics Cloth simulationCloth simulation

Rag-dollRag-doll EtcEtc

55

Introduction to Particle SystemIntroduction to Particle System Point massPoint mass

Mass centerMass center Newton’s LawsNewton’s Laws

ForcesForces AccelerationAcceleration VelocityVelocity PositionPosition

Easy to implementEasy to implement Good for game FXsGood for game FXs

Attach a billboard on each particleAttach a billboard on each particle A basic feature of a game engineA basic feature of a game engine

Fundamentals of Game PhysicsFundamentals of Game Physics

66

Introduction to Rigid Body DynamicsIntroduction to Rigid Body Dynamics Mass of a bodyMass of a body

Mass centerMass center ForceForce

Linear momentumLinear momentum TorqueTorque

Angular momentumAngular momentum Inertia tensorInertia tensor

ReferenceReference www-2.cs.cmu.edu/afs/cs/user/baraff/www/pbmwww-2.cs.cmu.edu/afs/cs/user/baraff/www/pbm

77

Introduction to Flexible Body Dynamics (1/2)Introduction to Flexible Body Dynamics (1/2) Particle-spring modelParticle-spring model

F = k xF = k x Spring forceSpring force

Not a stress-strain modelNot a stress-strain model Lack of Elasticity, Plasticity, & Viscous-ElasticityLack of Elasticity, Plasticity, & Viscous-Elasticity Can be unstableCan be unstable

8

Introduction to Flexible Body Dynamics (2/2) Finite element method

有限元素法– Solver for ODE/PDE– Boundary conditions– Energy equation– Stress-strain model– Very complicated computing process

Conservation of energy

99

Advanced Topics in Game PhysicsAdvanced Topics in Game Physics Fracture mechanics (Fracture mechanics ( 破壞力學模擬破壞力學模擬 )) Fluid dynamics (Fluid dynamics ( 流體力學流體力學 )) Car dynamics (Car dynamics ( 車輛動力學車輛動力學 )) Rag-doll physics (Rag-doll physics ( 人體物理模擬人體物理模擬 ))

1010

Game Physics Middleware (Physics Engine)Game Physics Middleware (Physics Engine) FreewareFreeware

ODEODE Open Dynamics Engine (ODE)Open Dynamics Engine (ODE) http://www.ode.org/

BulletBullet Commercial ones (now almost free)Commercial ones (now almost free)

nVIDIA PhysX (Ageia PhysX)nVIDIA PhysX (Ageia PhysX) http://www.nvidia.com.tw/object/physx_new_tw.html Powered by CUDAPowered by CUDA

Harvok (Intel)Harvok (Intel) http://www.havok.com/http://www.havok.com/

1111

Initial value problemsInitial value problems Ordinary differential equationOrdinary differential equation

NNumerical solutionsumerical solutions EEuler’s methoduler’s method TThe midpoint methodhe midpoint method Runge-Kutta methodRunge-Kutta method

Differential Equation BasicsDifferential Equation Basics

1212

An ODEAn ODE

xx = = f f ((xx, t), t)

wherewhere ff is a known function is a known functionxx is the is the statestate of the system, of the system, xx is the is the xx’s ’s timetime derivative derivative

xx & & xx are vectors are vectorsxx(t(t00) = ) = xx00, initial condition, initial condition

..

Start hereStart here Follow the vectors …Follow the vectors …

Initial Value ProblemsInitial Value Problems

..

..

Vector fieldVector field SolutionsSolutions

Symbolic solutionSymbolic solution Numerical solutionNumerical solution

13

A numerical solution A simplification from Tayler’s series

Discrete time steps starting with initial value Simple but not accurate

Bigger steps, bigger errors O(t2) errorserrors

Can be unstableCan be unstable Not even efficientNot even efficient

x(t + t) = x(t) + t f(x, t)

Euler’s MethodEuler’s Method

1414

Runge-KuttaRunge-Kutta method of order 4 method of order 4 OO(h(h55))

kk11 = h f(x = h f(x00, t, t00))kk22 = h f(x = h f(x00 + k + k11/2, t/2, t00 + h/2) + h/2)kk33 = h f(x = h f(x00 + k + k22/2, t/2, t00 + h/2) + h/2)kk44 = h f(x = h f(x00 + k + k33, t, t00 + h) + h)

xx(t(t00+h) = +h) = xx00 + 1/6 k + 1/6 k11 + 1/3 k + 1/3 k22 + 1/3 k + 1/3 k33 + 1/6 k + 1/6 k44

The The Runge-KuttaRunge-Kutta Method Method

1515

The tendency of an object at rest to remain at rest.The tendency of an object at rest to remain at rest. The mass is a measure of the inertia of the object.The mass is a measure of the inertia of the object. The force is the general mechanism for changing the mechanical state of an The force is the general mechanism for changing the mechanical state of an

object.object. A force is a vector quantity.A force is a vector quantity. An external force is one where source is outside the system of interest.An external force is one where source is outside the system of interest. The standard unit of measurement for the magnitude of a force is a The standard unit of measurement for the magnitude of a force is a newtonnewton.. A newton is the required force magnitude to give 1kg mass 1m/secA newton is the required force magnitude to give 1kg mass 1m/sec22

acceleration.acceleration.

InertiaInertia

1616

First LawFirst Law In the absence of external forces, an object at rest will remain at rest.In the absence of external forces, an object at rest will remain at rest. If the object is in motion and no external forces acting on it, the object If the object is in motion and no external forces acting on it, the object

remains in motion with constant velocity.remains in motion with constant velocity. Only forces can change an object’s motion.Only forces can change an object’s motion.

Newton’s Laws (1/3)Newton’s Laws (1/3)

17

Second LawSecond Law For an object with constant mass over time, its acceleration For an object with constant mass over time, its acceleration aa is is

proportional to the force proportional to the force FF and inversely proportional to the mass and inversely proportional to the mass mm of the of the object : object : aa = = FF//mm..

If the mass changes over time, the more general statement of the law isIf the mass changes over time, the more general statement of the law is

Newton’s Laws (2/3)Newton’s Laws (2/3)

F F = (= (mmvv) = ) = mama + + vvdddtdt dtdt

ddmm

linear momentumlinear momentum

An object’s path of motion is determined from applied forces.An object’s path of motion is determined from applied forces.

1818

Third LawThird Law If the force exerted on one object, there is a force with equal magnitude but If the force exerted on one object, there is a force with equal magnitude but

opposite direction on some other that interacts with it.opposite direction on some other that interacts with it. Action and reaction always occur between interacting objects.Action and reaction always occur between interacting objects.

Newton’s Laws (3/3)Newton’s Laws (3/3)

1919

Gravitational forcesGravitational forces Spring forcesSpring forces Friction and other dissipative forcesFriction and other dissipative forces

ForcesForces

2020

Given two point masses Given two point masses mm and and MM that have gravitational interaction, they that have gravitational interaction, they attract each other with forces of equal magnitude but opposite direction, as attract each other with forces of equal magnitude but opposite direction, as indicated by Newton’s third law.indicated by Newton’s third law.

Gravitational Forces (1/2)Gravitational Forces (1/2)

FFgravitygravity = =GmMGmM

rr22

G = 6.67 x 10G = 6.67 x 10-11-11 newton-meter newton-meter22 per kg per kg22

(universal gravitational constant)(universal gravitational constant)

2121

Gravitational Forces (2/2)Gravitational Forces (2/2) Assume the earth’s surface is flat and the direction of gravitation force is Assume the earth’s surface is flat and the direction of gravitation force is

normal to the plane, the gravitational force exerted on the object by the earth normal to the plane, the gravitational force exerted on the object by the earth is :is :

F F = -= -mgUmgU gg = 9.81 meters per sec = 9.81 meters per sec22

UU as unit-length upward direction as unit-length upward direction

UU

22

Spring ForcesSpring Forces Hooke’s LawHooke’s Law

FF = -c = -c UU c > 0, spring constantc > 0, spring constantUU, , displacementdisplacement

pullpull

FF

UU > 0 > 0

pushpush

FF

UU < 0 < 0

2323

Dissipative ForcesDissipative Forces A dissipative force is one for which energy of the system decreases when A dissipative force is one for which energy of the system decreases when

motion takes place.motion takes place. A simple model for a dissipative force :A simple model for a dissipative force :

FF = -c | = -c |vv||nn

Two common cases :Two common cases : FrictionFriction ViscosityViscosity

2424

Friction (1/2)Friction (1/2) A frictional force between two objects in contact opposes the sliding of one A frictional force between two objects in contact opposes the sliding of one

(moving) object over the surface of adjacent object (nonmoving).(moving) object over the surface of adjacent object (nonmoving). The friction force is tangent to the contact surface and opposite in direction to The friction force is tangent to the contact surface and opposite in direction to

the velocity of the moving object.the velocity of the moving object. The magnitude of the frictional force is assumed to be proportional to the The magnitude of the frictional force is assumed to be proportional to the

magnitude of the normal force between surfaces.magnitude of the normal force between surfaces.

F = - cF = - ckk v / |v|, if v is not zero v / |v|, if v is not zero = 0, if v is zero= 0, if v is zero

cckk is referred to as the coefficient of kinetic friction is referred to as the coefficient of kinetic friction

The kinetic friction force is modeled asThe kinetic friction force is modeled as

cckk = F = Ffrictionfriction / F / Fnormalnormal

2525

Friction (2/2)Friction (2/2) Static frictionStatic friction

ccss, coefficient of static friction, coefficient of static friction

1122 > > 11

static casestatic case kinetic casekinetic case

ccss = max(F = max(Ffrictionfriction)/ F)/ Fnormalnormal

2626

ViscosityViscosity A typical occurrence of this type of force is when an object is dragged through a A typical occurrence of this type of force is when an object is dragged through a

thick fluidthick fluid.. The force is modeled to have the direction opposite to that of the moving The force is modeled to have the direction opposite to that of the moving

object.object.

FF = - = -FFdissipativedissipative vv/|/|vv| = -(c|| = -(c|vv|) |) vv/|/|vv| = -c| = -cvv

c > 0c > 0

27

TorqueTorque Moment of forceMoment of force

FF is the applied force. is the applied force. rr is the position of the applied force relative to the mass center. is the position of the applied force relative to the mass center. The torque is the quantity :The torque is the quantity :

= = rr x x FF

oo rr

FF

The torque will generate a local rotation with respect to the mass center.The torque will generate a local rotation with respect to the mass center. Two forces of equal magnitude, opposite direction, but different lines of action Two forces of equal magnitude, opposite direction, but different lines of action

are said to be a are said to be a couplecouple..

2828

EquilibriumEquilibrium Forces on an object are said to be Forces on an object are said to be concurrentconcurrent if the lines of action all pass if the lines of action all pass

through a common point.through a common point. Balanced forcesBalanced forces mean the sum of the forces is zero. mean the sum of the forces is zero.

concurrentconcurrentnot balancednot balanced

concurrentconcurrentbalancedbalanced

not concurrentnot concurrentnot balancednot balanced not concurrentnot concurrent

balancedbalanced

FF

FF

2F2F

2929

MomentumMomentum Linear momentumLinear momentum Angular momentumAngular momentum

30

Linear MomentumLinear Momentum The linear momentum is the product :The linear momentum is the product :

pp = = mm vv

mm is the mass is the massvv is the velocity is the velocity

For a system of For a system of pp particles of masses m particles of masses mii and velocity and velocity vvii for for ii is in the range of ( is in the range of (11, , pp), the linear momentum is), the linear momentum is

pp = = Σ Σ mmii vvii

pp

i = 1i = 1

If the object is a continuum of mass that occupies a region If the object is a continuum of mass that occupies a region RR, the linear , the linear momentum ismomentum is

pp = = ∫∫vv d dmm = = ∫∫vv d dRRR R

ddmm = = ddRRInfinite small measurement of massInfinite small measurement of mass

31

Angular MomentumAngular Momentum Angular momentum can be treated as a measure of inertia to continue rotating Angular momentum can be treated as a measure of inertia to continue rotating

about an axis.about an axis.

LL = = rr x x pp = = rr x x mm vv

Angular momentum for a set of particles,Angular momentum for a set of particles,

LL = = ΣΣrrii xx mmii vvii

pp

i = 1i = 1

If the object is a continuum of mass that occupies a region If the object is a continuum of mass that occupies a region RR, the angular , the angular momentum ismomentum is

LL = = ∫∫r r x x vv d dmm = = ∫∫rr xx vv d dRRRR RR

ddmm = = ddRRInfinite small measurement of massInfinite small measurement of mass

3232

Moment of InertiaMoment of Inertia The measure of the rotational inertia of a body about an axis is the The measure of the rotational inertia of a body about an axis is the moment of moment of

inertiainertia.. For a single particle, moment of inertia is For a single particle, moment of inertia is

II = = m rm r22 mm is the mass is the massrr is the distance to an axis is the distance to an axis

But for a rigid body object, the inertia will be integrated as a function of mass But for a rigid body object, the inertia will be integrated as a function of mass and the geometry shape.and the geometry shape. We will discuss it in the section of “Rigid-body Dynamics”We will discuss it in the section of “Rigid-body Dynamics”

Moment of inertia in one dimensionMoment of inertia in one dimension Moment of inertia in two dimensionMoment of inertia in two dimension Moment of inertia in three dimensionMoment of inertia in three dimension Mass and Inertia tensor of a solid polyhedronMass and Inertia tensor of a solid polyhedron

33

Particles are objects with Mass Position Velocity Respond to forces

But no spatial extent (no size!) Point mass

Based on Newton Laws f = ma x = f / m v = f / m, v = x

Particle Dynamics

... .

3434

Euler’s Method for Particle SystemEuler’s Method for Particle System

vv(t + (t + t) = t) = vv(t) + (t) + t t f’f’(v, t)(v, t)xx(t + (t + t) = t) = xx(t) + (t) + t t ff(x, t)(x, t)

Discrete time steps starting with initial valueDiscrete time steps starting with initial value t = tt = t00, t, t11, t, t22, …, … Fixed frame rate but adaptive sampling rateFixed frame rate but adaptive sampling rate

Simple but not accurateSimple but not accurate Bigger steps, bigger errorsBigger steps, bigger errors OO((tt22) errors) errors

Can be unstableCan be unstable Not even efficientNot even efficient

If the time step is very tinyIf the time step is very tiny Calculate the velocity firstCalculate the velocity first

Then the position Then the position

3535

Particle StatesParticle States PositionPosition VelocityVelocity MassMass LifeLife EtcEtc

BBounce rateounce rate OpacityOpacity ColorColor

IIn game application, we always put a billboard object with texture animation n game application, we always put a billboard object with texture animation on a particle to simulate the geometry shape of the particle.on a particle to simulate the geometry shape of the particle.

36

typedef struct {typedef struct { float m; /* mass */float m; /* mass */ float *x; /* position */float *x; /* position */ float *v; /* velocity */float *v; /* velocity */ float *f; /* force accumulator */float *f; /* force accumulator */} *Particle;} *Particle;

typedef struct {typedef struct { Particle *p /* array of pointers to particles */Particle *p /* array of pointers to particles */ int n; /* number of particles */int n; /* number of particles */ float t; /* simulation clock */float t; /* simulation clock */} *ParticleSystem;} *ParticleSystem;

xxvvff

mmstatesstates

xxvvff

mm

xxvvff

mm

xxvvff

mm

xxvvff

mm

xxvvff

mm

……Particle n timeParticle n time

Basic Particle System (1/5)Basic Particle System (1/5)

37

/* gather states from the particles *//* gather states from the particles */void ParticleGetState(ParticleSystem p, float *dst)void ParticleGetState(ParticleSystem p, float *dst){{ int i;int i; for (i = 0; i < p->n; i++) {for (i = 0; i < p->n; i++) { *(dst++) = p->p[i]->x[0];*(dst++) = p->p[i]->x[0]; *(dst++) = p->p[i]->x[1];*(dst++) = p->p[i]->x[1]; *(dst++) = p->p[i]->x[2];*(dst++) = p->p[i]->x[2]; *(dst++) = p->p[i]->v[0];*(dst++) = p->p[i]->v[0]; *(dst++) = p->p[i]->v[1];*(dst++) = p->p[i]->v[1]; *(dst++) = p->p[i]->v[2];*(dst++) = p->p[i]->v[2]; }}}}

Basic Particle System (2/5)Basic Particle System (2/5)

38

/* scatter states into the particles *//* scatter states into the particles */void ParticleSetState(ParticleSystem p, float *src)void ParticleSetState(ParticleSystem p, float *src){{ int i;int i; for (i = 0; i < p->n; i++) {for (i = 0; i < p->n; i++) { p->p[i]->x[0] = *(src++);p->p[i]->x[0] = *(src++); p->p[i]->x[1] = *(src++);p->p[i]->x[1] = *(src++); p->p[i]->x[2] = *(src++);p->p[i]->x[2] = *(src++); p->p[i]->v[0] = *(src++);p->p[i]->v[0] = *(src++); p->p[i]->v[1] = *(src++);p->p[i]->v[1] = *(src++); p->p[i]->v[2] = *(src++);p->p[i]->v[2] = *(src++); }}}}

Basic Particle System (3/5)Basic Particle System (3/5)

39

/* calculate derivative, place in dst *//* calculate derivative, place in dst */void ParticleDerivative(ParticleSystem p, float *dst)void ParticleDerivative(ParticleSystem p, float *dst){{ int i;int i;

ClearForce(p);ClearForce(p); ComputeForce(p);ComputeForce(p);

for (i = 0; i < p->n; i++) {for (i = 0; i < p->n; i++) { *(dst++) = p->p[i]->v[0];*(dst++) = p->p[i]->v[0]; *(dst++) = p->p[i]->v[1];*(dst++) = p->p[i]->v[1]; *(dst++) = p->p[i]->v[2];*(dst++) = p->p[i]->v[2]; *(dst++) = p->p[i]->f[0]/p->p[i]->m;*(dst++) = p->p[i]->f[0]/p->p[i]->m; *(dst++) = p->p[i]->f[1]/p->p[i]->m;*(dst++) = p->p[i]->f[1]/p->p[i]->m; *(dst++) = p->p[i]->f[2]/p->p[i]->m;*(dst++) = p->p[i]->f[2]/p->p[i]->m; }}}}

Basic Particle System (4/5)Basic Particle System (4/5)

40

/* Euler Solver *//* Euler Solver */void EulerStep(ParticleSystem p, float DeltaT)void EulerStep(ParticleSystem p, float DeltaT){{ ParticleDeriv(p, temp1);ParticleDeriv(p, temp1); ScaleVector(temp1, DeltaT);ScaleVector(temp1, DeltaT); ParticleGetState(p, temp2);ParticleGetState(p, temp2); AddVector(temp1, temp2, temp2);AddVector(temp1, temp2, temp2); ParticleSetState(p, temp2);ParticleSetState(p, temp2); p->t += DeltaT;p->t += DeltaT;}}

Basic Particle System (5/5)Basic Particle System (5/5)

4141

The Rigid BodyThe Rigid Body Non-deformable bodyNon-deformable body

Within the body, the distance between two points are constant.Within the body, the distance between two points are constant. Rigid body motionRigid body motion

KinematicsKinematics DynamicsDynamics

Degree of freedomDegree of freedom 3 3 rotationsrotations 3 3 translationstranslations

Mass of a bodyMass of a body Mass centerMass center

ForceForce Linear momentumLinear momentum

TorqueTorque Angular momentumAngular momentum

Inertia tensorInertia tensor

42

Inertia Tensor (1/2)Inertia Tensor (1/2)

4343

Inertia Tensor (2/2)Inertia Tensor (2/2) We always use bounding box to simplify the calculation of the inertia tensor.We always use bounding box to simplify the calculation of the inertia tensor.

Rectangle blockRectangle block CylinderCylinder SphereSphere

ProsPros SimpleSimple

ConsCons InaccurateInaccurate

44

Calculate Inertia Tensor for a Rectangle BlockCalculate Inertia Tensor for a Rectangle Block

4545

Body Space & World SpaceBody Space & World Space

p(t) = R(t)pp(t) = R(t)p00 + x(t) + x(t)

4646

Linear VelocityLinear Velocity We call We call x(t)x(t) and and R(t)R(t) the position and orientation of the body at time the position and orientation of the body at time tt..

* * R(t)R(t) is the rotation matrix. is the rotation matrix.

47

Angular Velocity (1/2)Angular Velocity (1/2) (t)(t) is the angular velocity of the body.is the angular velocity of the body.

(t)(t) is not is not R(t)R(t) (t) (t) is a vector. Butis a vector. But R(t) R(t) is a matrixis a matrix

.

4848

Angular Velocity (2/2)Angular Velocity (2/2)

4949

Rigid Body Equation of MotionRigid Body Equation of Motion

5050

Flexible Body Dynamics (1/2)Flexible Body Dynamics (1/2) Deformable bodyDeformable body

ClothCloth FFlaglag SSandand HHairair

SolversSolvers PParticle-spring modelarticle-spring model

PParticles simulate the mass and the inertia.articles simulate the mass and the inertia. SSprings simulate the material.prings simulate the material. PParticle has translation only.article has translation only.

External Forces

K K KKKSpring Constant, Hook's Constant

External Forces

Discretization the mass into particles

Deformable Solid Body

5151

Flexible Body Dynamics (2/2)Flexible Body Dynamics (2/2) SpringSpring

Hook’s LawHook’s Law Rigid-body-spring ModelRigid-body-spring Model

UUse rigid body objects or balls to replace the particles.se rigid body objects or balls to replace the particles. RRigid body has translation and rotation.igid body has translation and rotation. TTranslation springsranslation springs RRotation springsotation springs

FFinite element methodinite element method

SStresstress SStraintrain