Building a Physics Engine with C++ and Simulating Machines

AngeTheGreat
31 Jan 202211:22

Summary

TLDRIn this video, the creator unveils a physics engine developed over weeks, initially part of a larger project but now a standalone codebase for future reuse. The engine simulates physical principles using a system state object, force generators, time discretization, and a differential equation solver. It employs Euler's method and the more advanced Runge-Kutta method for stability. The creator demonstrates basic mass-spring systems, cloth simulation, and repulsion forces in a game environment. The video also covers constraint-based physics, showcasing complex systems like double and triple pendulums, and the importance of spring stiffness. The creator's homemade screen capture program is highlighted, emphasizing the video's focus on physics simulation for game development.

Takeaways

  • 🛠️ The video introduces a custom physics engine developed by the creator for use in game projects.
  • 🔧 Initially, the physics engine was a small part of a larger project but was later developed into a standalone codebase for future reuse.
  • 🎮 The physics engine is essential for simulating physical reality in games, as showcased with a sentient cereal box affected by gravity and reaction forces.
  • 📐 The engine uses a system state object to track object properties like position, velocity, and orientation.
  • 💨 Force generators are employed to apply forces such as gravity or springs to objects within the scene.
  • ⏱️ Time discretization is crucial for simulating continuous time values in a digital environment, with smaller time steps leading to more accurate results.
  • 🔢 The differential equation solver, such as Euler's method, is used to update an object's position and velocity, simulating acceleration.
  • 🚀 An improved solver, the Runge-Kutta method (RK4), offers greater accuracy and stability over Euler's method, requiring fewer iterations for the same simulation quality.
  • 📹 The creator also developed a custom screen capture program integrated into the demo for high-quality video encoding without lag.
  • 🔗 Constraints are used to simulate more complex physical interactions, such as maintaining a circle's position or simulating a rolling object.
  • 🔍 The physics engine's constraint solver uses a matrix equation to find the forces needed to satisfy multiple constraints simultaneously.
  • 🤖 The video includes demos of the physics engine simulating various systems, including mass-spring systems, pendulums, and complex mechanical assemblies.

Q & A

  • What was the original purpose of the physics engine mentioned in the video?

    -The physics engine was initially intended to be a small part of a larger project, but the creator found it useful enough to be developed into its own code base for future reuse in similar physics simulations.

  • Why is simulating physics important in game development?

    -Simulating physics is crucial in game development because it allows games to approximate some form of physical reality, making the gameplay more realistic and engaging for players.

  • What is a 'system state object' in the context of a physics engine?

    -A system state object is a simple structure that tracks various properties of objects in the simulation, such as position, velocity, and orientation.

  • What is the role of a 'force generator' in a physics engine?

    -A force generator is responsible for applying forces to objects in the scene, such as gravity or spring forces, and is essential for simulating realistic interactions between objects.

  • Why is time discretization necessary in computer simulations?

    -Time discretization is necessary because computers cannot handle continuous values of time. By breaking the simulation into discrete time steps, it becomes computationally manageable.

  • What is Euler's method, and how is it used in physics simulations?

    -Euler's method is a numerical approach for solving differential equations. It is used to update an object's position and velocity in a simulation by adding the product of velocity and time step to the position, and the product of acceleration and time step to the velocity.

  • What are the limitations of Euler's method in sensitive systems?

    -Euler's method can introduce significant errors in sensitive systems, causing the simulation to become unstable or 'explode'. It requires very small time steps to maintain accuracy, which can be computationally expensive.

  • What is the Runge-Kutta method (RK4), and how does it improve upon Euler's method?

    -The Runge-Kutta method, specifically RK4, is a more advanced numerical technique that takes a weighted average of four points instead of a single point like Euler's method. This results in a more stable and accurate simulation with fewer iterations required.

  • What is a 'constraint' in the context of a physics engine, and how is it used?

    -A constraint in a physics engine is a function that evaluates to zero only when a physical constraint is satisfied. The goal is to apply forces in such a way that all constraint functions are zero, ensuring realistic behavior under the constraints.

  • What is the purpose of the 'differential equation solver' in a physics engine?

    -The differential equation solver is responsible for updating the state of the system over time by solving differential equations that describe the motion of objects under the influence of applied forces.

  • How does the video creator handle the complexity of simulating more advanced systems like a double pendulum?

    -The creator uses a constraint solver system, which involves setting up and solving matrix equations to find the forces required to satisfy all constraints simultaneously, allowing for the simulation of more complex and realistic systems.

Outlines

00:00

🛠️ Physics Engine Development

The creator introduces a physics engine they've developed over several weeks, initially intended as a small part of a larger project but later realized to be useful on its own. The engine simulates basic physical principles like gravity and reaction forces, as demonstrated by a sentient cereal box in a game. The physics are not sophisticated but serve as a foundation. The video explains the necessity of physics in games to approximate physical reality and the creator's journey to build a more accurate physics engine, starting with a system state object to track object properties and a force generator for applying forces like gravity or springs. The importance of time discretization in simulations for computer applications is discussed, and Euler's method is introduced as a basic numerical approach for solving differential equations, though it's acknowledged to be error-prone and computationally expensive.

05:01

🔍 Advanced Simulation Techniques

The video delves into the use of the Runge-Kutta 4th order method (RK4) for improving simulation accuracy and performance, allowing for a more stable simulation with fewer iterations per second. The creator shares a basic interface with demos using springs and masses to illustrate the engine's capabilities. They also discuss the creation of a custom screen capture program due to issues with OBS, which integrates directly with the demo for smooth video encoding. The creator demonstrates the mass-spring system's energy conservation and its application in simulating cloth, as well as the use of force generators for simple game physics, like repulsion forces and AI movement. However, the limitations of the spring-based approach are acknowledged, leading to the introduction of constraints for more complex simulations.

10:01

🔧 Implementing Constraints in Physics Simulations

The video explains the concept of constraints in physics simulations, which are functions that evaluate to zero when a physical constraint is satisfied. The creator discusses the process of finding reaction forces to satisfy multiple constraints simultaneously, which can be formulated as a matrix equation. Gaussian elimination is used to solve this equation, though more advanced algorithms may be necessary for future projects. The implementation of constraints as classes with their own calculation methods is described, along with the creation of a master Jacobian matrix for solving the constraints. The video showcases demos using the constraint solver system, including a double pendulum and a triple pendulum, highlighting the importance of numerical stability and accuracy in simulations. The creator also discusses the challenges of implementing rolling constraints and the importance of matching spring stiffness to specific applications. The video concludes with a demo of a complex system with many moving parts, emphasizing the use of triangles to create rigid structural members, similar to real-world machine design.

Mindmap

Keywords

💡Physics Engine

A physics engine is a software framework that simulates the physical world, allowing developers to create more realistic and interactive experiences in games and simulations. In the video, the creator discusses building a physics engine from scratch, which was initially a part of a larger project but was found to be useful on its own, demonstrating its application in simulating a sentient cereal box affected by gravity and reaction forces.

💡System State Object

A system state object in the context of physics engines is a data structure that tracks the properties of objects within the simulation, such as their position, velocity, and orientation. It is fundamental to the engine as it provides the current state of the system which is then updated based on the applied forces and motion equations, as mentioned in the script when discussing the basic elements needed for the physics engine.

💡Force Generator

A force generator is a component within a physics engine that applies forces to objects in the simulation. Examples include gravity and springs. The script explains that force generators are essential for simulating the interaction of objects with their environment, such as a sentient cereal box standing on furniture and being affected by these forces.

💡Discretization

Discretization in the context of simulations refers to the process of converting continuous values into discrete steps, which is necessary because computers cannot handle infinite subdivisions of time. In the video, the creator discusses how time is discretized into time steps for the simulation, which is crucial for updating the system state in a game's physics engine.

💡Differential Equation Solver

A differential equation solver is a method used to solve equations that describe the rate of change of a system's state over time. In the video, the creator explains that even simple game simulations often involve solving differential equations, such as updating an object's position based on its velocity and acceleration, which is an example of using Euler's method.

💡Euler's Method

Euler's method is a numerical technique for solving ordinary differential equations by approximating the solution at a series of points. The script mentions that this method is simple but not very accurate for sensitive systems, as it can lead to significant errors and unstable simulations, requiring a very small time step for better accuracy.

💡RK4 (Runge-Kutta 4th Order Method)

The Runge-Kutta 4th Order method, or RK4, is a more advanced numerical technique for solving differential equations, which provides a more accurate solution than Euler's method. The video script illustrates that by using RK4, the creator was able to run the simulation with fewer iterations per second, resulting in a more stable and performant physics engine.

💡Constraints

In physics engines, constraints are functions that define the limitations or conditions that objects must satisfy, such as two objects not passing through each other. The script describes how constraints are used to ensure that physical behaviors, like a circle staying at a fixed x position, are accurately represented in the simulation.

💡Jacobi Matrix

The Jacobi matrix, often simply called the Jacobian, is a matrix of all first-order partial derivatives of a vector-valued function. In the context of the video, it is used to calculate the constraints' impact on the system, helping to determine the necessary forces to satisfy all constraints simultaneously.

💡Gaussian Elimination

Gaussian elimination is a method for solving systems of linear equations, which is used in the video's physics engine to find the unknown forces that satisfy all constraints. The creator mentions that while it works well for their purposes, more complex scenes might require more advanced algorithms.

💡Optimization

Optimization in the context of programming refers to improving the efficiency of code, often by reducing computational complexity or resource usage. The script notes that while the current physics engine is not optimized for performance, it is written for clarity, indicating that there is room for optimization to increase efficiency and potentially improve the engine's performance.

Highlights

Introduction of a physics engine developed for a larger project but found to be useful by itself.

The physics engine is designed to be reusable for future projects requiring similar physics simulations.

Explanation of the necessity for physics simulation in games to approximate physical reality.

Demonstration of a sentient cereal box game affected by gravity and reaction forces.

The physics implemented are not sophisticated but functional, highlighting the need for a more advanced engine.

Introduction of a system state object to track object properties in a physics engine.

Description of a force generator for applying forces like gravity or springs to objects in the scene.

Time discretization in simulations to make continuous real-world time compatible with digital systems.

The use of time steps in simulations and their relation to video frame lengths.

Introduction of the differential equation solver, a fundamental component of a physics engine.

Explanation of Euler's method for solving differential equations with its limitations.

Introduction of the Runge-Kutta method (RK4) as an improvement over Euler's method.

Demonstration of a basic mass-spring system and its energy conservation properties.

Use of mass-spring systems to simulate cloth in games with its limitations.

Application of force generators to create simple game physics like repulsion forces.

Introduction of constraints in physics engines to simulate more complex and accurate physical interactions.

Explanation of how constraints are implemented and solved in a physics engine using matrix equations.

Description of the process of solving for constraint forces using Gaussian elimination.

Demonstration of various demos using the constraint solver system, including a double pendulum.

Discussion on the importance of matching spring stiffness to the application in simulations.

Showcasing complex system simulations using triangles to create rigid structural members.

Acknowledgment of the non-optimized code for clarity and ease of debugging.

Teaser for future projects using the physics engine and ongoing work on a serial adventure game.

Transcripts

play00:00

hey what's up guys and welcome back to

play00:02

another video

play00:03

what you see on the screen right now in

play00:05

front of you is a physics engine that

play00:07

i've been working on for the past few

play00:09

weeks and it was originally meant to be

play00:11

a small part of a bigger project

play00:14

but i realized that it was actually kind

play00:16

of useful by itself so i took all the

play00:17

physics code

play00:19

and i made it into its own code base and

play00:21

now anytime that i need similar physics

play00:23

in the future i can just reuse this

play00:25

whole thing all right so most games need

play00:27

a way of simulating physics because i

play00:30

mean most games tend to approximate some

play00:32

sort of physical reality and here in the

play00:34

real world we are obviously bound by

play00:37

certain physical principles

play00:39

so here's my own game which approximates

play00:41

the very real situation of a sentient

play00:44

cereal box

play00:45

and as you can see he is affected by

play00:47

forces like gravity and the reaction

play00:49

forces from the furniture that he's

play00:51

standing on

play00:52

the physics i implemented for this game

play00:54

is uh

play00:56

not particularly sophisticated though

play00:59

it works but it isn't suitable for

play01:01

simulating precise machines which is

play01:03

actually what i needed for this project

play01:06

so i set out building a real physics

play01:08

engine

play01:09

the first and most basic element that i

play01:11

needed is a system state object

play01:14

this is a simple structure which tracks

play01:16

various object properties like position

play01:18

velocity and orientation

play01:21

next we need a way to apply forces to

play01:23

the objects in the scene this is handled

play01:26

by something called a force generator

play01:28

and force generators can be things like

play01:30

gravity or springs and the math behind

play01:33

them is fairly straightforward

play01:36

next we need a way to discretize time

play01:39

and by discretization i mean that in the

play01:41

real world we usually regard time as

play01:44

being a continuous value so in other

play01:46

words you can subdivide it infinitely

play01:50

computers can't really do continuous

play01:52

values very well so we need to break our

play01:54

simulation down into time steps

play01:58

every time we run the simulation we

play01:59

advance time by the time step

play02:02

for games the time step is often just

play02:04

the length of each video frame but you

play02:05

can actually run the simulation multiple

play02:07

times per frame which further subdivides

play02:10

your time step

play02:11

and the usual rule is that the smaller

play02:13

the time step is the more accurate your

play02:16

simulation results will be

play02:18

the final component of a basic physics

play02:20

engine is called the differential

play02:22

equation solver now this sounds like a

play02:24

complex term but it actually isn't

play02:27

really that complicated if you've

play02:28

written a basic game before or some sort

play02:31

of simulation you've actually probably

play02:33

already written a differential equation

play02:34

solver you might be familiar with this

play02:37

sequence of events for an object that is

play02:39

accelerating

play02:40

so first you add velocity multiplied by

play02:43

the time step to the object's position

play02:46

and then you add acceleration multiplied

play02:48

by the time step to the object's

play02:49

velocity

play02:51

and in some sense this has the effect of

play02:52

basically updating the position every

play02:54

frame by moving it by the object's

play02:56

current velocity and you obviously have

play02:58

to update the velocity depending on how

play03:00

fast that object is

play03:02

accelerating the simple process is

play03:05

actually a numerical approach for

play03:07

solving a differential equation and this

play03:09

particular approach is called euler's

play03:11

method

play03:13

euler's method isn't really that great

play03:15

though

play03:15

for sensitive systems like what you see

play03:18

on the screen the error can actually be

play03:20

fairly significant and the simulation

play03:21

just explodes immediately

play03:24

you can improve the accuracy by reducing

play03:26

the time step since euler's method

play03:28

becomes more accurate as the time step

play03:30

becomes smaller but as you can see to

play03:33

get good results we need to run the

play03:34

simulation 600 000 times per second it's

play03:38

a fairly simple simulation so we can get

play03:40

away with it without taking a hit to our

play03:42

frame rate but for most scenes this

play03:45

isn't really going to work

play03:46

instead we can use a more clever

play03:48

technique called rk4 or the classic

play03:51

runga kuda method i have left a link in

play03:53

the description of this video if you

play03:55

want to learn more about it or you can

play03:57

check out my own implementation which is

play03:59

on the screen here

play04:00

essentially we take a weighted average

play04:03

of four points instead of just a single

play04:05

point like with euler's method

play04:07

this results in a much more stable

play04:09

simulation and ultimately better

play04:11

performance as you can see i can run the

play04:13

same simulation with only 300 iterations

play04:16

per second as opposed to six hundred

play04:18

thousand

play04:19

this is actually all you need to

play04:21

simulate some basic systems and to show

play04:23

this i created this basic interface with

play04:26

my game engine and a few demos which

play04:28

only use springs and masses

play04:31

a side note

play04:32

and this is totally unrelated but obs

play04:34

which is the screen capture program that

play04:36

i usually use drove me absolutely insane

play04:39

while i was trying to make this video it

play04:42

kept lagging and missing frames even

play04:44

though my simulation was running

play04:45

smoothly

play04:46

so i just wrote my own version which is

play04:48

built directly into this demo

play04:50

every frame it takes what's on the

play04:52

screen and sends it to a video encoder

play04:54

that is running in a separate thread

play04:57

and i also made this into its own

play04:58

project as well and it's a simple

play05:00

interface with just a few functions and

play05:02

allows you to write high quality mp4

play05:04

files from a c plus application so check

play05:08

that out if you're interested one

play05:10

benefit of this is that regardless of

play05:12

the real time frame rate the video is

play05:14

always smooth with a stable frame rate

play05:17

of your choosing

play05:18

anyway

play05:19

this is a basic mass spring system

play05:21

suspended from a fixed point and one

play05:24

interesting thing to note is how the

play05:26

total energy of the system doesn't

play05:27

change which means that the simulation

play05:29

is at least somewhat stable

play05:32

if energy grows without putting any

play05:34

energy in then we know that something

play05:36

has to be broken

play05:38

we can use a mass spring system to

play05:40

simulate cloth as well and while it's

play05:42

not perfect it performs fairly well all

play05:45

things considered

play05:48

we can also use force generators to

play05:49

implement simple game physics so in this

play05:52

case i made a repulsion force that acts

play05:55

on these blobs and keeps them from

play05:57

moving too close together and i also

play05:59

added a simple ai that enables them to

play06:01

move around and explore

play06:03

it looks a bit bouncy but for some games

play06:06

that might actually be a good thing

play06:09

we can't actually use springs to

play06:10

simulate everything though

play06:12

even a simple double pendulum using

play06:14

stiff springs is pretty jittery and the

play06:16

more complex the system becomes the more

play06:19

unworkable this approach is

play06:21

instead we can use something called

play06:23

constraints

play06:25

a constraint in the mathematical sense

play06:27

is just a function that evaluates to

play06:29

zero only when a physical constraint is

play06:32

satisfied so for example let's say that

play06:34

we want to constrain this circle so that

play06:36

its x position is three

play06:38

and the constraint function is simply c

play06:41

equals x minus three and notice how when

play06:43

the circle is actually in the right

play06:45

place c is equal to zero and everywhere

play06:47

else c is non-zero

play06:50

the goal of the physics engine is to try

play06:53

to position and apply forces to objects

play06:56

such that every single constraint

play06:58

function is zero

play07:00

now most scenes are going to have a lot

play07:01

of constraints in them and we need to

play07:03

find reaction forces that will satisfy

play07:06

all of these constraints at the same

play07:07

time

play07:09

we can actually restate this problem as

play07:11

a matrix equation and the math is a

play07:13

little involved so i won't go into it

play07:15

too much in detail here but check the

play07:17

description for links to the full

play07:19

derivation

play07:21

essentially it all comes down to this

play07:23

sort of scary looking equation

play07:25

the right side is a vector with known

play07:27

values

play07:28

j times w times the transpose of j is a

play07:32

matrix with known values and lambda is a

play07:36

vector with unknown values

play07:38

a more standard way of writing this

play07:40

would be a times lambda equals b and by

play07:44

solving for lambda we can find all the

play07:46

forces required to satisfy all

play07:48

constraints at the same time

play07:51

there are a lot of different algorithms

play07:53

to solve this equation and some are more

play07:55

complex than others

play07:57

i just implemented gaussian elimination

play07:59

which works well enough for my purposes

play08:01

but i might have to switch to using

play08:03

something a bit more advanced later on

play08:06

the actual constraints are implemented

play08:08

as classes

play08:10

and they each have their own calculate

play08:12

method which calculates j and the time

play08:14

derivative of j based on their own

play08:16

constraint functions

play08:18

and for those that are mathematically

play08:19

inclined j is the jacobian of the

play08:21

constraint function and it's basically a

play08:24

matrix of derivatives with respect to

play08:26

all of our system state parameters

play08:29

we then take all of these values and

play08:31

combine them all into a single master

play08:33

jacobian matrix

play08:35

then we pass the left and right side of

play08:37

this equation to the linear equation

play08:39

solver to find lambda

play08:41

then it's just a matter of applying

play08:43

these constraint forces to each rigid

play08:45

body and then our differential equation

play08:47

solver will take care of the rest by the

play08:49

way i know that this code is not

play08:51

particularly optimized it's mainly just

play08:54

written for clarity and there's a lot of

play08:56

room for optimization and unfortunately

play08:58

if i did optimize it it'd be a lot less

play09:00

readable and more difficult to debug i'm

play09:03

not an expert

play09:04

so i just wanted to keep things easy for

play09:06

me if i put anyone to sleep with that

play09:09

mathematical explanation i'm sorry i'm

play09:12

trying to find a compromise here

play09:14

but anyway here are some demos using

play09:16

this constraint solver system

play09:18

first we have the obligatory double

play09:21

pendulum system

play09:22

and just having this is going to get me

play09:24

millions of views on this video i'm sure

play09:26

we can also simulate a triple pendulum

play09:29

which is quite a bit more chaotic than a

play09:31

simple double pendulum you can see how

play09:34

the numerical error accumulates and

play09:36

starts to mysteriously increase the

play09:38

total energy of the system if we left

play09:41

this running for a very long time and i

play09:43

mean like a very long time like many

play09:45

hours maybe even days

play09:48

the simulation would eventually break

play09:49

down

play09:50

but that can be pretty easily prevented

play09:52

by just dampening the motion of

play09:53

everything slightly or just decreasing

play09:56

the time step to get a more accurate

play09:57

simulation

play09:59

now this demo

play10:01

is by far my favorite but also cause me

play10:03

the most headaches the mathematics

play10:05

behind things like this rolling

play10:07

constraint can be very tedious

play10:09

um as you can see and i spent many hours

play10:12

chasing down arithmetic errors in the

play10:14

code it's not difficult math per se

play10:17

it's just basic differentiation but

play10:19

small mistakes can be really hard to

play10:21

track down

play10:22

so that just added to the fun i guess

play10:27

here's another demo where we can see a

play10:29

vivid demonstration of why it's

play10:31

important to match spring stiffness to a

play10:34

particular application

play10:36

the spring is the same in both systems

play10:38

but its reaction to the system frequency

play10:40

is noticeably different

play10:43

we can also simulate more complex

play10:45

systems like this with a lot of moving

play10:47

parts in them

play10:48

and notice how you can make rigid

play10:51

structural members using triangles

play10:53

similar to how you design a real machine

play10:58

and that's pretty much all i wanted to

play11:00

show today i hope you guys got some

play11:02

value out of this video uh make sure to

play11:04

subscribe if you want to see what i end

play11:05

up using this physics engine for i'm

play11:07

pretty excited about that project and i

play11:09

think it'll be very interesting by the

play11:11

way i am still working on my serial

play11:13

adventure game so expect a devlog for

play11:15

that in the near future

play11:17

and alright thanks for watching everyone

play11:19

and i'll see you guys next time

Rate This

5.0 / 5 (0 votes)

Ähnliche Tags
Physics EngineGame DevelopmentSimulationEuler's MethodRK4 AlgorithmMass-SpringConstraintsGaussian EliminationNumerical MethodsSoftware Optimization
Benötigen Sie eine Zusammenfassung auf Englisch?