* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Λ - Piazza
Elementary particle wikipedia , lookup
Monte Carlo methods for electron transport wikipedia , lookup
Center of mass wikipedia , lookup
Theoretical and experimental justification for the Schrödinger equation wikipedia , lookup
Laplace–Runge–Lenz vector wikipedia , lookup
Newton's theorem of revolving orbits wikipedia , lookup
Relativistic mechanics wikipedia , lookup
Velocity-addition formula wikipedia , lookup
Jerk (physics) wikipedia , lookup
Specific impulse wikipedia , lookup
Fictitious force wikipedia , lookup
Relativistic quantum mechanics wikipedia , lookup
Brownian motion wikipedia , lookup
Relativistic angular momentum wikipedia , lookup
Mass versus weight wikipedia , lookup
Fundamental interaction wikipedia , lookup
Classical mechanics wikipedia , lookup
Newton's laws of motion wikipedia , lookup
Centripetal force wikipedia , lookup
Classical central-force problem wikipedia , lookup
CS662 Computer Graphics & Game Technology Yotam Gingold (slide lineage: Jan Allbeck, …) Things You can do with a Physics System 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) • Allow characters to pick up rigid objects 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) • Allow characters to pick up rigid objects • Traps (such as avalanche of boulders) 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) • Allow characters to pick up rigid objects • Traps (such as avalanche of boulders) • Drivable vehicles with realistic suspensions 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) • Allow characters to pick up rigid objects • Traps (such as avalanche of boulders) • Drivable vehicles with realistic suspensions • Rag doll character deaths 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) • Allow characters to pick up rigid objects • Traps (such as avalanche of boulders) • Drivable vehicles with realistic suspensions • Rag doll character deaths • Powered rag doll: a realistic blend between traditional and rag doll physics 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) • Allow characters to pick up rigid objects • Traps (such as avalanche of boulders) • Drivable vehicles with realistic suspensions • Rag doll character deaths • Powered rag doll: a realistic blend between traditional and rag doll physics • Dangling props (canteens, necklaces, swords), semi-realistic hair, clothing movements 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) • Allow characters to pick up rigid objects • Traps (such as avalanche of boulders) • Drivable vehicles with realistic suspensions • Rag doll character deaths • Powered rag doll: a realistic blend between traditional and rag doll physics • Dangling props (canteens, necklaces, swords), semi-realistic hair, clothing movements • Cloth simulations 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) • Allow characters to pick up rigid objects • Traps (such as avalanche of boulders) • Drivable vehicles with realistic suspensions • Rag doll character deaths • Powered rag doll: a realistic blend between traditional and rag doll physics • Dangling props (canteens, necklaces, swords), semi-realistic hair, clothing movements • Cloth simulations • Water surface simulations and buoyancy 2 Things You can do with a Physics System • Detect collisions between dynamic objects and static world geometry • Simulate free rigid bodies under the influence of gravity and other forces • Spring-mass systems • Destructible buildings and structures • Ray and shape casts (to determine line of sight, bullet impacts, etc.) • Trigger volumes (determine when objects enter, leave, or are inside predefined regions) • Allow characters to pick up rigid objects • Traps (such as avalanche of boulders) • Drivable vehicles with realistic suspensions • Rag doll character deaths • Powered rag doll: a realistic blend between traditional and rag doll physics • Dangling props (canteens, necklaces, swords), semi-realistic hair, clothing movements • Cloth simulations • Water surface simulations and buoyancy • Audio propagation 2 Physics Impact on Games • Simulations: • Flight Simulator • Gran Turismo • NASCAR Racing • Physics Puzzle Games: • Bridge Builder • Angry Birds • Sandbox Games: • Grand Theft Auto • Spore 3 Increasing Importance • Physics deals with motions of objects in virtual scene • And object interactions during collisions • Physics increasingly important for games • Similar to advanced AI, advanced graphics • Enabled by more processing • Used to need it all for more core game play (graphics, I/O, AI) • Now have additional processing for more • Multi-core processors • Physics hardware (Ageia’s PhysX) and general GPU (instead of graphics) • Physics libraries (Havok FX) that are optimized 4 Newtonian Physics • Generally, object does not come to a stop naturally, but forces must bring it to stop • Force can be friction (i.e.- ground) • Force can be drag (i.e.- air or fluid) • Forces: gravitational, electromagnetic, weak nuclear, strong nuclear • But gravitational most common in games (and most well-known) • From dynamics: Force = mass x acceleration (F=ma) 5 Newtonian Physics • Generally, object does not come to a stop naturally, but forces must bring it to stop • Force can be friction (i.e.- ground) • Force can be drag (i.e.- air or fluid) • Forces: gravitational, electromagnetic, weak nuclear, strong nuclear • But gravitational most common in games (and most well-known) • From dynamics: Force = mass x acceleration (F=ma) • In games, forces often known, so need to calculate acceleration • a = F/m 5 Newtonian Physics • Generally, object does not come to a stop naturally, but forces must bring it to stop • Force can be friction (i.e.- ground) • Force can be drag (i.e.- air or fluid) • Forces: gravitational, electromagnetic, weak nuclear, strong nuclear • But gravitational most common in games (and most well-known) • From dynamics: Force = mass x acceleration (F=ma) • In games, forces often known, so need to calculate acceleration • a = F/m • Acceleration used to update velocity and velocity used to update objects position: • x = x + (v + a * dt) * dt (dt is the delta time) • Can do for (x, y, z) positions • (speed is just magnitude, or size, of velocity vector) 5 Newtonian Physics • Generally, object does not come to a stop naturally, but forces must bring it to stop • Force can be friction (i.e.- ground) • Force can be drag (i.e.- air or fluid) • Forces: gravitational, electromagnetic, weak nuclear, strong nuclear • But gravitational most common in games (and most well-known) • From dynamics: Force = mass x acceleration (F=ma) • In games, forces often known, so need to calculate acceleration • a = F/m • Acceleration used to update velocity and velocity used to update objects position: • x = x + (v + a * dt) * dt (dt is the delta time) • Can do for (x, y, z) positions • (speed is just magnitude, or size, of velocity vector) • So, if add up all forces on object and divide by mass to get acceleration 5 Newtonian Physics 6 Newtonian Physics • Motion of bodies and forces acting upon bodies 6 Newtonian Physics • Motion of bodies and forces acting upon bodies • Three bodies: • Point masses: no angles, so only linear motion (considered infinitely small) • Particle effects • Rigid bodies: shapes to not change, so deals with angular (orientation) and linear motion • Characters and dynamic game objects • Soft bodies: have position and orientation and can change shape (i.e.- cloth, liquids) • Starting to be possible in real-time 6 Point-Mass (Particle) Physics • What is a Particle? • A sphere of finite radius with a perfectly smooth, frictionless surface • Experiences no rotational motion • Particle Dynamics • Defines the basic properties of particle motion • Position, Velocity, Acceleration 7 More Definitions • State space representation: a mathematical model of a physical system as a set of input, output and state variables related by first-order differential equations 8 More Definitions • State space representation: a mathematical model of a physical system as a set of input, output and state variables related by first-order differential equations • Ordinary differential equations: a relation that contains functions of only one independent variable, and one or more of its derivatives with respect to that variable. (e.g. Newton’s second law) 8 More Definitions • State space representation: a mathematical model of a physical system as a set of input, output and state variables related by first-order differential equations • Ordinary differential equations: a relation that contains functions of only one independent variable, and one or more of its derivatives with respect to that variable. (e.g. Newton’s second law) • Euler integration: a first-order numerical procedure for solving ordinary differential equations (ODEs) with a given initial value 8 Particle Dynamics: Position • Location of Particle in World Space ! ! ! ! ! ! ! ! • Changes over time when object moves 9 Particle Dynamics: Velocity & Acceleration • Average velocity (units: meters/sec): • ( p(t+Δt) - p(t) ) / Δt • But velocity may change in time Δt • Instantaneous velocity is derivative of position: (Position is the integral of velocity over time) • Acceleration (units: m/s2) • First time derivative of velocity • Second time derivative of position 10 Particle Dynamics: Velocity & Acceleration • Average velocity (units: meters/sec): • ( p(t+Δt) - p(t) ) / Δt • But velocity may change in time Δt • Instantaneous velocity is derivative of position: (Position is the integral of velocity over time) • Acceleration (units: m/s2) • First time derivative of velocity • Second time derivative of position 10 Newton’s 2nd Law of Motion • Paraphrased: “An object’s change in velocity is proportional to an applied force” • The Classic Equation: • m = mass (units: kilograms, kg) • F(t) = force (units: Newtons) 11 What is Physics Simulation? 12 What is Physics Simulation? • The Cycle of Motion: • Force, F(t), causes acceleration • Acceleration, a(t), causes a change in velocity • Velocity, V(t) causes a change in position 12 What is Physics Simulation? • The Cycle of Motion: • Force, F(t), causes acceleration • Acceleration, a(t), causes a change in velocity • Velocity, V(t) causes a change in position • Physics Simulation: • Solving variations of the above equations over time • Use them to get positions of objects • Render objects on screen • Repeat to emulate the cycle of motion 12 Example: 3D Projectile Motion (1 of 3) • Basis for entire game! • Eagle eye: http:// www.teagames.com/ games/eagleeye/ play.php • Basic arrow projectile • Castle battle: http:// www.freeonlinegames.c om/game/castle-battles • 3d perspective, physics on blocks 13 Example: 3D Projectile Motion (2 of 3) • Constant Force (i.e. gravity) • Force is weight of the projectile, W = mg • g is constant acceleration due to gravity 2 • On earth, gravity (g) is 9.81 m/s • With constant force, acceleration is constant • Easy to integrate to get closed form • Closed-form “Projectile Equations of Motion”: ! ! ! ! • These closed-form equations are valid, and exact, for any time, t, in seconds, greater than or equal to tinit. (Note: requires constant force.) 14 Example: 3D Projectile Motion (3 of 3) 15 Example: 3D Projectile Motion (3 of 3) • For simulation: • Begins at time tinit • Initial velocity, Vinit and position, pinit, at time tinit, are known • Can find later values (at time t) based on initial values 15 Example: 3D Projectile Motion (3 of 3) • For simulation: • Begins at time tinit • Initial velocity, Vinit and position, pinit, at time tinit, are known • Can find later values (at time t) based on initial values • On Earth: • If we choose positive Z to be straight up (away from center of Earth), gEarth = 9.81 m/s2. 15 Pseudo-code for Simulating Projectile Motion void main() { // Initialize variables Vector v_init(10.0, 0.0, 10.0); Vector p_init(0.0, 0.0, 100.0), p = p_init; Vector g(0.0, 0.0, -9.81); // earth float t_init = 10.0; // launch at time 10 seconds ! // The game sim/rendering loop while (1) { float t = getCurrentGameTime(); // could use system clock if (t > t_init) { float t_delta = t - t_init; p = p_init + (v_init * t_delta); // velocity p = p + 0.5 * g * (t_delta * t_delta); // acceleration } renderParticle(p); // render particle at location p } } 16 Frictionless Collision Response (1 of 4) • Linear momentum: the mass times the velocity momentum = mV • (units are kilogram-meters per second) • Related to the force being applied • 1st time derivative of linear momentum is equal to net force applied to object d/dt (mV(t)) = F(t) 17 Frictionless Collision Response (1 of 4) • Linear momentum: the mass times the velocity momentum = mV • (units are kilogram-meters per second) • Related to the force being applied • 1st time derivative of linear momentum is equal to net force applied to object d/dt (mV(t)) = F(t) • Most objects have constant mass, so: d/dt (mV(t)) = m d/dt (V(t)) • Called the Newtonian Equation of Motion • When integrated over time it determines the motion of an object 17 Frictionless Collision Response (2 of 4) • Consider two colliding particles 18 Frictionless Collision Response (2 of 4) • Consider two colliding particles • For the duration of the collision, both particles exert force on each other • Normally, collision duration is very short, yet change in velocity is dramatic (example: pool balls) 18 Frictionless Collision Response (2 of 4) • Consider two colliding particles • For the duration of the collision, both particles exert force on each other • Normally, collision duration is very short, yet change in velocity is dramatic (example: pool balls) • Integrate previous equation over duration of collision m1V1+ = m1V1- + Λ (equation 1) 18 Frictionless Collision Response (2 of 4) • Consider two colliding particles • For the duration of the collision, both particles exert force on each other • Normally, collision duration is very short, yet change in velocity is dramatic (example: pool balls) • Integrate previous equation over duration of collision m1V1+ = m1V1- + Λ (equation 1) • m1V1- is linear momentum of particle 1 just before collision 18 Frictionless Collision Response (2 of 4) • Consider two colliding particles • For the duration of the collision, both particles exert force on each other • Normally, collision duration is very short, yet change in velocity is dramatic (example: pool balls) • Integrate previous equation over duration of collision m1V1+ = m1V1- + Λ (equation 1) • m1V1- is linear momentum of particle 1 just before collision • m1V1+ is the linear momentum just after collision 18 Frictionless Collision Response (2 of 4) • Consider two colliding particles • For the duration of the collision, both particles exert force on each other • Normally, collision duration is very short, yet change in velocity is dramatic (example: pool balls) • Integrate previous equation over duration of collision m1V1+ = m1V1- + Λ (equation 1) • m1V1- is linear momentum of particle 1 just before collision • m1V1+ is the linear momentum just after collision • Λ is the linear impulse • Integral of collision force over duration of collision 18 Frictionless Collision Response (3 of 4) • Newton’s third law of motion says for every action, there is an equal and opposite reaction: • Particle 2 is the same magnitude, but opposite in direction (so, -1*Λ) (equation 2) • Can solve these equations if we know Λ 19 Frictionless Collision Response (3 of 4) • Newton’s third law of motion says for every action, there is an equal and opposite reaction: • Particle 2 is the same magnitude, but opposite in direction (so, -1*Λ) (equation 2) • Can solve these equations if we know Λ • Without friction, impulse force acts completely along unit surface normal vector at point of contact Λ = Λs n • n is the unit surface normal vector (see collision detection for point of contact) • Λs is the scalar value of the impulse • (In physics, a scalar is a simple physical quantity that does not depend on direction.) 19 Frictionless Collision Response (3 of 4) • Newton’s third law of motion says for every action, there is an equal and opposite reaction: • Particle 2 is the same magnitude, but opposite in direction (so, -1*Λ) (equation 2) • Can solve these equations if we know Λ • Without friction, impulse force acts completely along unit surface normal vector at point of contact Λ = Λs n • n is the unit surface normal vector (see collision detection for point of contact) • Λs is the scalar value of the impulse • (In physics, a scalar is a simple physical quantity that does not depend on direction.) • So, we have 2 equations with three unknowns (V1+, V2+, Λs). • We need third equation to solve for all unknowns. 19 Frictionless Collision Response (4 of 4) Period of deformation Period of restitution • Third equation is approximation of material response to colliding objects (V1+ - V2+)·n = -ε (V1- - V2-)·n (equation 3) • Note, in general, can collide at angle • ε is coefficient of restitution • Related to conservation or loss of kinetic energy • ε is 1, totally elastic, so objects rebound fully • ε is 0, totally plastic, objects no restitution, maximum loss of energy • In real life, depends upon materials • Ex: tennis ball on racquet, ε is 0.85 and deflated basketball with court ε is 0) • (Next slides have details) 20 Coefficient of Restitution • A measure of the elasticity of the collision • How much of the kinetic energy of the colliding objects before collision remains as kinetic energy after collision • Links: • Basic Overview • Wiki • The Physics Factbook • Physics of Baseball and Softball Bats • Measurements of Sports Balls 21 Coefficient of Restitution • Defined as the ratio of the differences in velocities before and after collision ε = (V1+ - V2+)·n / (V1- - V2-)·n • For an object hitting an immovable object (i.e. the floor) ε = sqrt(h/H) • Where h is bounce height, H is drop height 22 Coefficient of Restitution • Drop ball from fixed height (92 cm) • Record bounce • Repeat 5 times and average) • Various balls 23 Coefficient of Restitution • Final notes… • Technically: • COR a property of a collision, not necessarily an object • 5 different types of objects à10 (5 choose 2 = 10) different CORs • May be energy lost to internal friction (baseball) • May depend upon speed • All that can get complicated! • But, for properties not available, can estimate • (i.e. rock off of helmet, dodge ball off wall) • Play test until looks “right” 24 Putting It All Together • Have 3 equations and 3 unknowns (V1+, V2+, Λs) • Compute the linear impulse ! ! ! • Apply Λs to equations 1 and 2 to get V1+ and V2+ … and divide by m1 (or m2) to get after-collision velocities 25 The Story So Far • Visited basic concepts in dynamics and Newtonian physics • Generalized for 3 dimensions • Ready to be used in some games! ! • Show Pseudo code next • Simulating N Spherical Particles under Gravity with no Friction 26 Psuedocode (1 of 5) void main() { // initialize variables vector v_init[N] = initial velocities; vector p_init[N] = initial positions; vector g(0.0, 0.0, -9.81); // earth float mass[N] = particle masses; float time_init[N] = start times; float eps = coefficient of restitution; 27 Psuedocode (2 of 5) // main game simulation loop while (1) { f loat t = getCurrentGameTime(); detect collisions (t_collide is time); for each colliding pair (i,j) { ! // calc position and velocity of i float telapsed = t_collide – t i m e _ i n i t [ i ] ; pi = p_init[i] + (V_init[i] * telapsed); // velocity pi = pi + 0.5*g*(telapsed*telapsed); // accel // calc position and velocity of j float telapsed = tcollide – t i m e _ i n i t [ j ] ; pj = p_init[j] + (V_init[j] * telapsed); // velocity pj = pj + 0.5*g*(telapsed*telapsed); // accel 28 Psuedocode (3 of 5) // for spherical particles, surface // normal is just vector joining middle normal = Normalize(pj – pi); ! // compute impulse (equation 4) impulse = normal; impulse *= -(1+eps)*mass[i]*mass[j]; impulse *=normal.DotProduct(vi-vj); // V i V j +V i V j +V i V j 1 1 2 2 3 3 impulse /= (mass[i] + mass[j]); 29 Psuedocode (4 of 5) ! // Restart particles i and j after collision (eq 1) // Since collision is instant, after-collisions // positions are the same as before V_init[i] += impulse/mass[i]; V_init[j] -= impulse/mass[j]; // equal and opposite p_init[i] = pi; p_init[j] = pj; // reset start time_init[i] = time_init[j] = } // end of for times since new init V t_collide; t_collide; each 30 Psuedocode (5 of 5) // Update and render particles for k = 0; k<N; k++){ float tm = t – time_init[k]; p = p_init[k] + V_init[k] * tm; // velocity p = p + 0.5*g*(tm*tm); // acceleration ! render particle k at location p; } 31 Rigid-Body Simulation Intro • If no rotation, only gravity and occasional frictionless collision, above is fine 32 Rigid-Body Simulation Intro • If no rotation, only gravity and occasional frictionless collision, above is fine • In many games (and life!), interesting motion involves nonconstant forces and collision impulse forces 32 Rigid-Body Simulation Intro • If no rotation, only gravity and occasional frictionless collision, above is fine • In many games (and life!), interesting motion involves nonconstant forces and collision impulse forces • Unfortunately, for the general case, often no closed-form solutions 32 Rigid-Body Simulation Intro • If no rotation, only gravity and occasional frictionless collision, above is fine • In many games (and life!), interesting motion involves nonconstant forces and collision impulse forces • Unfortunately, for the general case, often no closed-form solutions • Numerical simulation: • represents a series of techniques for incrementally solving the equations of motion when forces applied to an object are not constant, or when otherwise there is no closed-form solution 32 Numerical Integration of Newtonian Equation of Motion • Family of numerical simulation techniques called finite difference methods • The most common family of numerical techniques for rigid-body dynamics simulation • Incremental “solution” to equations of motion • Derived from Taylor series expansion of properties we are interested in • Taylor series expansion of a function f(x) about a point a: • Using the Taylor series expansion of a function S: S(t+Δt) = S(t) + Δt d/dt S(t) + (Δt) 2 /2! d 2 /dt S(t) + … • In general, hard to know higher order derivates. Truncate: 2 S(t+Δt) = S(t) + Δt d/dt S(t) + O(Δt ) • Can do beyond, but always higher terms 2 • O(Δt ) is called truncation error • Can use to update properties (position) • Called “simple” or “explicit” Euler integration 33 Explicit Euler Integration • A “one-point” method since solve using properties at exactly one point in time, t, prior to update time, t+Δt. • S(t+Δt) is the only unknown value so we can solve it without solving system of simultaneous equations • Important: every term on right side is evaluated at t, not at the new time t+Δt • View: S(t+Δt) = S(t) + Δt d/dt S(t) new state prior state derivative at prior state 34 Explicit Euler Integration • Can write numerical integrator to integrate arbitrary properties as change over time 35 Explicit Euler Integration • Can write numerical integrator to integrate arbitrary properties as change over time • Integrate state vector of length N 35 Explicit Euler Integration • Can write numerical integrator to integrate arbitrary properties as change over time • Integrate state vector of length N void ExplicitEuler(N, new_S, prior_S, s_deriv, delta_t) { 35 Explicit Euler Integration • Can write numerical integrator to integrate arbitrary properties as change over time • Integrate state vector of length N void ExplicitEuler(N, new_S, prior_S, s_deriv, delta_t) { f or (i=0; i<N; i++) { 35 Explicit Euler Integration • Can write numerical integrator to integrate arbitrary properties as change over time • Integrate state vector of length N void ExplicitEuler(N, new_S, prior_S, s_deriv, delta_t) { f or (i=0; i<N; i++) { new_S[i] = prior_S[i] + delta_t * S_deriv [i]; 35 Explicit Euler Integration • Can write numerical integrator to integrate arbitrary properties as change over time • Integrate state vector of length N void ExplicitEuler(N, new_S, prior_S, s_deriv, delta_t) { f or (i=0; i<N; i++) { new_S[i] = prior_S[i] + delta_t * S_deriv [i]; } 35 Explicit Euler Integration • Can write numerical integrator to integrate arbitrary properties as change over time • Integrate state vector of length N void ExplicitEuler(N, new_S, prior_S, s_deriv, delta_t) { f or (i=0; i<N; i++) { new_S[i] = prior_S[i] + delta_t * S_deriv [i]; } } 35 Explicit Euler Integration • Can write numerical integrator to integrate arbitrary properties as change over time • Integrate state vector of length N void ExplicitEuler(N, new_S, prior_S, s_deriv, delta_t) { f or (i=0; i<N; i++) { new_S[i] = prior_S[i] + delta_t * S_deriv [i]; } } • For single particle, S=(mV,p) and d/dt S = (F,V) 35 Explicit Euler Integration • Can write numerical integrator to integrate arbitrary properties as change over time • Integrate state vector of length N void ExplicitEuler(N, new_S, prior_S, s_deriv, delta_t) { f or (i=0; i<N; i++) { new_S[i] = prior_S[i] + delta_t * S_deriv [i]; } } • For single particle, S=(mV,p) and d/dt S = (F,V) • Note, in 3D, mV and p have 3 values each: • S(t) = (m 1 V 1 ,p 1 ,m 2 V 2 ,p 2 , …, m N V N ,p N ) • d/dt S(t) = (F 1 ,V 1 ,F 2 ,V 2 , …,F N ,V N ) 35 Pseudo Code for Numerical Integration (1 of 2) Vector cur_S[2*N]; Vector prior_S[2*N]; Vector S_deriv[2*N]; float mass[N]; float t; ! void main() { float delta_t; ! // // // // // S(t+Δt) S(t) d/dt S at time t mass of particles simulation time t // time step // set current state to initial conditions for (i=0; i<N; i++) { mass[i] = m a s s o f p a r t i c l e i ; cur_S[2*i] = p a r t i c l e i i n i t i a l m o m e n t u m ; cur_S[2*i+1] = p a r t i c l e i i n i t i a l p o s i t i o n ; } // Game simulation/rendering loop while (1) { doPhysicsSimulationStep(delta_t); for (i=0; i<N; i++) { render particle i at position cur_S[2*i+1]; } } 36 Pseudo Code for Numerical Integration (2 of 2) // update physics void doPhysicsSimulationStep(delta_t) { copy cur_S to prior_S; ! ! ! / / calcula te state derivative vector for (i=0; i<N; i++) { S_deriv[2*i] = CalcForce(i); // could be just gravity S_deriv[2*i+1] = prior_S[2*i]/mass[i]; / / s i n c e S [ 2 * i ] i s / / m V à d i v i d e b y m } / / integra te equations of motion E xplicitEu ler(2*N, cur_S, prior_S, S_deriv, d elta_t); // by integrating, effectively moved // simulation time forward by delta_t t = t + de lta_t; } 37 Explicit Euler Integration - Computing Solution Over Time • The solution proceeds step-by-step, each time integrating from the prior state 38 Truncation Error • Numerical solution can be different from exact, closed-form solution • Difference between exact solution and numerical solution is primarily truncation error • Equal and opposite to value of terms removed from Taylor Series expansion to produce finite difference equation • Truncation error, left unchecked, can accumulate to cause simulation to become unstable • Sometimes, truncation error can become zero • In other words, finite difference equation produces exact, correct result • For example, when zero force is applied 39 Truncation Error • Numerical solution can be different from exact, closed-form solution • Difference between exact solution and numerical solution is primarily truncation error • Equal and opposite to value of terms removed from Taylor Series expansion to produce finite difference equation • Truncation error, left unchecked, can accumulate to cause simulation to become unstable • Sometimes, truncation error can become zero • In other words, finite difference equation produces exact, correct result • For example, when zero force is applied • But, more often truncation error is nonzero. Control by: • Reduce time step, Δt (Next slide) • Select a different numerical integrator (Vertlet, Runge–Kutta, implicit Euler and others, not covered). Typically, more state kept. Stable within bounds. 39 Frame Rate Independence • Given numerical simulation sensitive to time step (Δt), important to create physics engine that is frame-rate independent • Results will be repeatable, every time run simulation with same inputs • Regardless of CPU/GPU performance • Maximum control over simulation • Pseudo code next 40 Pseudo Code for Frame Rate Independence void main() { float delta_t = 0.02; float game_time; float prev_game_time; float physics_lag_time=0.0; ! // // // // physics time game time game time at last step time since last update // simulation/render loop while(1) { update game_time; // could be take from system clock physics_lag_time += (game_time – prev_game_time); while (physics_lag_time > delta_t) { doPhysicsSimulation(delta_t); physics_lag_time -= delta_t; } prev_game_time = game_time; ! render scene; } } 41 Rigid Body Simulations 42 Rigid Body Simulation Object Properties Mass Position linear & angular velocity linear & angular momentum Calculate change in attributes Position linear & angular velocity linear & angular momentum Calculate forces Wind Gravity Viscosity Collisions Calculate accelerations Linear & angular using mass and inertia tensor 43 Impulse Response How to compute the collision response of two rotating rigid objects? 44 Impulse Response Given Separation velocity is to be negative of colliding velocity Compute Impulse force that produces sum of linear and angular velocities that produce desired separation velocity 45 Rigid Body Simulation 46 Update linear and angular velocities as a result of impulse force J = scalar impulse n = normal of the collision M = mass w = angular I = inertia tensor for rigid body rA - The vector from the center of mass of 47 rigid body A to the point of collision Velocities of Points of Contact 48 Rigid Body Simulation J = scalar impulse 49 Resting Contact Complex situations: need to solve for forces that prevent penetration, push objects apart, if the objects are separating, then the contact force is zero 50 Deformable Bodies 51 Deformable Bodies • Methods for moving control points and/or vertices 51 Collision Detection 52 Collision Detection • Determining when objects collide not as easy as it seems • Geometry can be complex (beyond spheres) • Objects can move fast • Can be many objects (say, n) • Naïve solution is O(n 2 ) time complexity, since every object can potentially collide with every other object 53 Collision Detection • Determining when objects collide not as easy as it seems • Geometry can be complex (beyond spheres) • Objects can move fast • Can be many objects (say, n) • Naïve solution is O(n 2 ) time complexity, since every object can potentially collide with every other object • Two basic techniques • Overlap testing • Detects whether a collision has already occurred • Intersection testing • Predicts whether a collision will occur in the future 53 Overlap Testing 54 Overlap Testing • Facts • Most common technique used in games • Exhibits more error than intersection testing 54 Overlap Testing • Facts • Most common technique used in games • Exhibits more error than intersection testing • Concept • For every simulation step, test every pair of objects to see if overlap • Easy for simple volumes like spheres, harder for polygonal models 54 Overlap Testing • Facts • Most common technique used in games • Exhibits more error than intersection testing • Concept • For every simulation step, test every pair of objects to see if overlap • Easy for simple volumes like spheres, harder for polygonal models • Useful results of detected collision • Collision normal vector (needed for physics actions, as seen earlier) • Time collision took place 54 Overlap Testing: Collision Time • Collision time calculated by moving object back in time until right before collision • Move forward or backward ½ step, called bisection ! ! ! ! ! ! ! ! ! • Get within a delta (close enough) • With distance moved in first step, can know “how close” • In practice, usually 5 iterations is pretty close 55 Overlap Testing: Limitations • Fails with objects that move too fast • Unlikely to catch time slice during overlap ! ! ! • Possible solutions • Design constraint on speed of objects (fastest object moves smaller distance than thinnest object) • May not be practical for all games • Reduce simulation step size • Adds overhead since more computation • Note, can try different step size for different objects 56 Intersection Testing • Predict future collisions 57 Intersection Testing • Predict future collisions • Extrude geometry in direction of movement • Ex: swept sphere turns into a “capsule” shape 57 Intersection Testing • Predict future collisions • Extrude geometry in direction of movement • Ex: swept sphere turns into a “capsule” shape • Then, see if overlap 57 Intersection Testing • Predict future collisions • Extrude geometry in direction of movement • Ex: swept sphere turns into a “capsule” shape • Then, see if overlap • When predicted: • Move simulation to time of collision • Resolve collision • Simulate remaining time step 57 Intersection Testing: Sphere-Sphere Collision Or, just check the discriminant: Collision if t is in [0..1] No collision if: See: http://www.gamasutra.com/view/feature/131790/simple_intersection_tests_for_games.php?page=2! More fun: http://www.realtimerendering.com/intersections.html 58 Dealing with Complexity • Complex geometry must be simplified • Complex object can have 100’s or 1000’s of polygons • Testing intersection of each costly • Reduce number of object pair tests • There can be 100’s or 1000’s of objects • If test all, O(n2) time complexity 59 Complex Geometry – Bounding Volume • Bounding volume is simple geometric shape that completely encapsulates object • Ex: approximate spiky object with ellipsoid • Note, does not need to encompass, but might mean some contact not detected • May be ok for some games 60 Complex Geometry – Bounding Volume • Testing cheaper • If no collision with bounding volume, no more testing is required • If there is a collision, then there could be a collision • More refined testing can be used • Commonly used bounding volumes • Sphere: if distance between centers < sum of radii, no collision • Box: axis-aligned (loose fit) or oriented (tighter fit) 61 Bounding Boxes/Volumes • Spheres 62 Bounding Boxes/Volumes • Spheres • Axis aligned bounding boxes (AABB) 62 Bounding Boxes/Volumes • Spheres • Axis aligned bounding boxes (AABB) • Object aligned bounding boxes (OABB) • In general, OABB fit tighter than AABB, which fit tighter than spheres. • Sphere have some nice properties when dealing with forces. 62 Bounding Boxes • Axis-aligned (AABB): use min/max in each dimension • Oriented (OBB): e.g., use AABB in object space and transform with object. 63 Complex Geometry – Bounding Volume • For complex object, can fit several bounding volumes around unique parts • Ex: For avatar, boxes around torso and limbs, sphere around head • Can use hierarchical bounding volume • Ex: large sphere around whole avatar • If collide, refine with more refined bounding boxes 64 Hierarchical Bounding Boxes (or Volumes) • Use hierarchical bounding boxes to avoid detailed edge by edge intersection tests. • Group objects any reasonable way: by complex areas, by natural parts, by proximity, by scene graph node, etc. 65 Recursive testing of bounding boxes • We can build up a recursive hierarchy of bounding boxes to determine quite accurate collision detection. ! ! ! ! ! ! ! • Here we use a sphere to test for course grain intersection. • If we detect intersection of the sphere, we test the two sub bounding boxes. • The lower bounding box is further reduced to two more bounding boxes to detect collision of the cylinders. 66 Tree structure used to model collision detection B A A D B C E C D E • A recursive algorithm can be used to parse the tree structure for detecting collisions. • If a collision is detected and leaf nodes are not null then traverse the leaf nodes. • If a collision is detected and the leaf nodes are null then collision has occurred at the current node in the structure. • If no collision is detected at all nodes where leaf nodes are null then no collision has occurred (in our diagram B, D or E must record collision). 67 Reduced Collision Tests – Plane Sweep • Objects tend to stay in same place • So, don’t need to test all pairs • Record bounds of objects along axes • Any objects with overlap on all axes should be tested further • Time consuming part is sorting bounds • Quicksort O(nlog(n)) • But, since objects don’t move, can do better with Bubblesort to repair – nearly O(n) 68 Reduced Collision Tests - Partitioning • Partition space so only test objects in same cell • If N objects, then sqrt(N) x sqrt(N) cells to get linear complexity • But what if objects don’t align nicely? • What if all objects in same cell? (same as no cells) 69 Data Structures for Scenes • Types of trees for holding scenes: • Scene Graphs • Organized by how the scene is constructed. • Nodes hold objects. • CSG Trees • Organized by how the scene is constructed. • Leaves hold 3-D primitives. Internal nodes hold set operations. • BSP Trees • Organized by spatial relationships in the scene. • Nodes hold facets (in 3-D, polygons). • Quadtrees & Octrees • Organized spatially. • Nodes represent regions in space. Leaves hold objects. 70 CSG Trees • In Constructive Solid Geometry (CSG), we construct a scene out of primitives representing solid 3-D shapes. Existing objects are combined using set operations (union, intersection, set difference). • We represent a scene as a binary tree. • Leaves hold primitives. • Internal nodes, which always have two children, hold set operations. U • Order of children matters! U U – ∩ cube cone sphere sphere sphere cube 71 BSP Trees: Introduction 72 BSP Trees: Introduction • A Binary Space Partition tree (BSP tree) is a very different way to represent a scene. • Nodes hold faces. • The structure of the tree encodes spatial information about the scene. • Useful for hidden surface removal and related applications. 72 BSP Trees: Definition 73 BSP Trees: Definition • A BSP tree is a binary tree. • Nodes can have 0, 1, or two children. • Order of child nodes matters, and if a node has just 1 child, it matters whether this is its left or right child. 73 BSP Trees: Definition • A BSP tree is a binary tree. • Nodes can have 0, 1, or two children. • Order of child nodes matters, and if a node has just 1 child, it matters whether this is its left or right child. • Each node holds a face. • This may be only part of a face from the original scene. • When constructing a BSP tree, we may need to split faces. 73 BSP Trees: Definition • A BSP tree is a binary tree. • Nodes can have 0, 1, or two children. • Order of child nodes matters, and if a node has just 1 child, it matters whether this is its left or right child. • Each node holds a face. • This may be only part of a face from the original scene. • When constructing a BSP tree, we may need to split faces. • Organization: • Each face lies in a unique plane. • In 2-D, a unique line. • For each face, we choose one side of its plane to be the “outside”. (The other direction is “inside”.) • This can be the side the normal vector points toward. • Rule: For each node, • Its left descendant subtree holds only faces “inside” it. • Its right descendant subtree holds only faces “outside” it. 73 BSP Trees: Construction 74 BSP Trees: Construction • To construct a BSP tree, we need: • A list of faces (with vertices). • An “outside” direction for each. 74 BSP Trees: Construction • To construct a BSP tree, we need: • A list of faces (with vertices). • An “outside” direction for each. • Procedure: • Begin with an empty tree. Iterate through the faces, adding a new node to the tree for each new face. • The first face goes in the root node. • For each subsequent face, descend through the tree, going left or right depending on whether the face lies inside or outside the face stored in the relevant node. • If a face lies partially inside & partially outside, split it along the plane [line] of the face. • The face becomes two “partial” faces. Each inherits its “outside” direction from the original face. • Continue descending through the tree with each partial face separately. • Finally, the (partial) face is added to the current tree as a leaf. 74 BSP Trees: Simple Example • Su pp ose we a re gi ve n th e follow ing ( 2-D ) faces and “o utside” di rec tion s: 2 ! ! • We it erat e t hrough the faces in nu me rica l o rde r. Face 1 b ecomes th e root. Fa ce 2 is inside of 1. Thus , after fa ce 2, w e h ave th e following BSP tree: ! 3 1 1 2 • Face t 3 is parti all y i ns ide face 1 and partially outside. ! 2 • We split face 3 along the line containing face 1. • The resulting faces are 3a and 3b. They inherit their “outside” directions from face 3. 1 • We p lace face s 3a a nd 3b separa te ly. • Face 3a is inside face 1 and outside face 2. • Face 3b is outside face 1. • The final BSP tree look s like th is: 3a 3b 1 2 3b 3a 75 BSP Trees: Traversing [1/2] • An important use of BSP trees is to provide a back-to-front (or front-toback) ordering of the faces in a scene, from the point of view of an observer. • When we say “back-to-front” ordering, we mean that no face comes before something that appears directly behind it. This still allows nearby faces to precede those farther away. • Key idea: All the descendants on one side of a face can come before the face, which can come before all descendants on the other side. • Procedure: • For each face, determine on which side of it the observer lies. • Back-to-front ordering: Do an in-order traversal of the tree in which the subtree opposite from the observer comes before the subtree on the same side as the observer. 2 1 3a 3b 76 BSP Trees: Traversing [2/2] • Procedure: • For each face, determine on which side of it the observer lies. • Back-to-front ordering: Do an in-order traversal of the tree in which the subtree opposite from the observer comes before the subtree on the same side as the observer. ! • Our observer is inside 1, outside 2, inside 3a, outside 3b. ! ! ! ! ! 1 2 1 3a 3b 2 3b 3a • Resulting back-to-front ordering: 3b, 1, 2, 3a. 77 BSP Trees: What Are They Good For? • BSP trees are primarily useful when a back-to-front or frontto-back ordering is desired: • For Hidden Surface Removal (HSR). • For translucency via blending. • Since it can take some time to construct a BSP tree, they are useful primarily for: • Static scenes. • Some dynamic objects are acceptable. • BSP-tree techniques are generally a waste of effort for small scenes. We use them on: • Large, complex scenes. 78 BSP Trees: Optimizing • The order in which we iterate through the faces can matter a great deal. • Consider our simple example again. If we change the ordering, we can obtain a simpler BSP tree. ! ! ! ! 1 ! ! numbers ! reversed ! ! 2 ! 1 2 2 3 1 3a 2 3b 3b 3a 1 1 3 2 3 • If a scene is not going to change, and the BSP tree will be used many times, then it may be worth a large amount of preprocessing time to find the best possible BSP tree. 79 BSP Trees: Finding Inside/Outside • When dealing with BSP trees, we need to determine inside or outside many times. What exactly does this mean? • A face lies entirely on one side of a plane if all of its vertices lie on that side. • Vertices are points. The position of the observer is also a point. • Thus, given a face and a point, we need to be able to determine on which side of the face’s plane the point lies. • We assume we know the normal vector of the face (and that it points toward the “outside”). • If not, compute the normal using a cross product. ! • If three non-colinear vertices of the face are stored in pos variables p1, p2, p3, then you can find the normal as follows. vec n = cross(p2-p1, p3-p1).normalized(); 80 BSP Trees: Finding Inside/Outside • To deter mine on which side of a face’s plane a point lies: • Let N be the normal vector of the face. • Let p be a point in the face’s plane. • Maybe p is a vertex of the face? • Let z be the point we want to check. • Compute (z – p) · N. • If this is positive, then z is on the outside. • Negative: inside. • Zero: on the plane. • Continuing from previous slide: ! pos z = …; ! // point to check if (dot(z-p1, n) >= 0.) // Outside or on plane else // Inside 81 Quadtrees & Octrees: Background • The idea of the binary space partition is one with good general applicability. Some variation of it is used in a number of different structures. • BSP trees (of course). • Split along planes containing faces. • Quadtrees & octrees (next). • Split along pre-defined planes. • kd-trees (not covered). • Split along planes parallel to coordinate axes, so as to split up the objects nicely. • Quadtrees are used to partition 2D space, while Octrees are for 3D. • The two concepts are nearly identical 82 Quadtrees & Octrees: Definition 83 Quadtrees & Octrees: Definition • In general: • A quadtree is a tree in which each node has at most 4 children. • An octree is a tree in which each node has at most 8 children. • Similarly, a binary tree is a tree in which each node has at most 2 children. 83 Quadtrees & Octrees: Definition • In general: • A quadtree is a tree in which each node has at most 4 children. • An octree is a tree in which each node has at most 8 children. • Similarly, a binary tree is a tree in which each node has at most 2 children. • In practice, however, we use “quadtree” and “octree” to mean something more specific: • Each node of the tree corresponds to a square (quadtree) or cubical (octree) region. • If a node has children, think of its region being chopped into 4 (quadtree) or 8 (octree) equal subregions. Child nodes correspond to these smaller subregions of their parent’s region. • Subdivide as little or as much as is necessary. • Each internal node has exactly 4 (quadtree) or 8 (octree) children. 83 Quadtrees & Octrees: Example • The root node of a quadtree corresponds to a square region in space. ! ! A • Generally, this encompasses the entire “region of interest”. • If desired, subdivide along lines parallel to the coordinate axes, forming four smaller identically sized square regions. The child nodes correspond to these. A A B B C D E A ! • Some or all of these children may be subdivided further. ! • Octrees work in a similar fashion, but in 3-D, with cubical regions subdivided into 8 parts. C D E B C A B C F D G E H I F G D H I A E 84 Quadtrees & Octrees: What Are They Good For? • Handling Observer-Object Interactions • Subdivide the quadtree/octree until each leaf’s region intersects only a small number of objects. • Each leaf holds a list of pointers to objects that intersect its region. • Find out which leaf the observer is in. We only need to test for interactions with the objects pointed to by that leaf. • Inside/Outside Tests for Odd Shapes • The root node represent a square containing the shape. • If a node’s region lies entirely inside or entirely outside the shape, do not subdivide it. • Otherwise, do subdivide (unless a predefined depth limit has been exceeded). • Then the quadtree or octree contains information allowing us to check quickly whether a given point is inside the shape. • Sparse Arrays of Spatially-Organized Data • Store array data in the quadtree or octree. • Only subdivide if that region of space contains interesting data. 85 Research in Physics & collision detection and response… Stephen Chenney and D.A.Forsyth, "Sampling Plausible Solutions to Multi-Body Constraint Problems". SIGGRAPH 2000 Conference Proceedings, pages 219-228, July 2000. 87 Stephen Chenney and D.A.Forsyth, "Sampling Plausible Solutions to Multi-Body Constraint Problems". SIGGRAPH 2000 Conference Proceedings, pages 219-228, July 2000. 87 Jovan Popovic, Steven M. Seitz, Michael Erdmann, Zoran Popovic, and Andrew Witkin. Interactive Manipulation of Rigid Body Simulations. In Computer Graphics (Proceedings of SIGGRAPH 2000), ACM SIGGRAPH, Annual Conference Series, 209-217. 88 Jovan Popovic, Steven M. Seitz, Michael Erdmann, Zoran Popovic, and Andrew Witkin. Interactive Manipulation of Rigid Body Simulations. In Computer Graphics (Proceedings of SIGGRAPH 2000), ACM SIGGRAPH, Annual Conference Series, 209-217. 88 Doug L. James and Dinesh K. Pai, BD-Tree: OutputSensitive Collision Detection for Reduced Deformable Models, ACM Transactions on Graphics (ACM SIGGRAPH 2004), 23(3), pp. 393-398, August 2004, pp. 393-398. 89 Doug L. James and Dinesh K. Pai, BD-Tree: OutputSensitive Collision Detection for Reduced Deformable Models, ACM Transactions on Graphics (ACM SIGGRAPH 2004), 23(3), pp. 393-398, August 2004, pp. 393-398. 89 Alec R. Rivers, Doug L. James: FastLSM: Fast Lattice Shape Matching for Robust Real-Time Deformation ACM Transactions on Graphics (SIGGRAPH 2007) 90 Alec R. Rivers, Doug L. James: FastLSM: Fast Lattice Shape Matching for Robust Real-Time Deformation ACM Transactions on Graphics (SIGGRAPH 2007) 90 Doug James: PSA 91 Doug James: PSA 91 Christopher D. Twigg and Doug L. James, Backward Steps in Rigid Body Simulation, ACM Transactions on Graphics (SIGGRAPH Conference Proceedings), 27(3), August 2008, pp. 25:1-25:10. 92 Christopher D. Twigg and Doug L. James, Backward Steps in Rigid Body Simulation, ACM Transactions on Graphics (SIGGRAPH Conference Proceedings), 27(3), August 2008, pp. 25:1-25:10. 92 Eric G. Parker and James F. O'Brien. "Real-Time Deformation and Fracture in a Game Environment". In Proceedings of the ACM SIGGRAPH/Eurographics Symposium on Computer Animation, pages 156–166, August 2009. 93 Eric G. Parker and James F. O'Brien. "Real-Time Deformation and Fracture in a Game Environment". In Proceedings of the ACM SIGGRAPH/Eurographics Symposium on Computer Animation, pages 156–166, August 2009. 93 94 94 94 UNC GAMMA http://www.youtube.com/view_play_list?p=B33BE6A376947BB1 95