 All right on that note. We have another session of crisp talk starting up. We wonder what's gonna happen now That's not really dramatic. I'm sorry Give it up for Nilesh Trivedi guys. That's Nilesh over there So Nilesh has been programming for about 14 years 14 years now Started with C and did Java and Ruby JavaScript and occasionally some scheme and Erlang like all over the place For the last four years He's been working with Gapshup in Mumbai and he's quit to work independently And he also wants to spend more time on his personal projects and doing more science like yay science mostly aerospace stuff He likes hacking with the guitar audio electronics and making more music He's been spending some time figuring out how to do physics simulations in the browser and he'd like to talk to you About that today Nilesh floors yours Hello everyone So I'm going to talk about interactive physics simulation in the browser So first of all, what do we know about our universe? Well, one of the theories that the string theory right the universe is made of tiny vibrating strings Unfortunately, we don't have string dot vibrate. So we need to go back to Newton Newton after all So why start from scratch well, the most important reason was I was just wanted to do it for fun But at the same time most of the existing physics engines They are more tuned for performance rather than accuracy. They are meant for games where energy conservation is not a strict requirement They don't give you very very low level access to the state as the simulation is happening So and I wanted to make an learning environment for people's Studying mechanics problem or physics problems, you know, so there were those reasons So again that f equal to m is the basic fundamental equation that we are going to solve and it's actually a second-order differential equation So you have x position and you differentiate it twice with respect time That is supposed to be equal to your force divided by mass now the first tip that I can give you don't solve don't integrate twice during the same step You don't need to what you can do is you can keep track of velocity And you make you turn it into a first-order differential equation So you are using the last time steps velocity to calculate the position for the new time step and you calculate the forces to Calculate acceleration and new velocities Now this is a very simple case. There's just one particle one dimension when you extend it to rigid bodies and multiple dimensions What will happen is that instead of x you will have x y and theta if it's a two-dimensional physics problem that that's the one I have solved and velocities will be your vx vy and omega which is the angular velocity and In case of forces Rotations are influenced by torques and instead of m you will have moment of inertia So this is a key bit. This is a second tip that I can give you you will have to maintain two representations of the world because it's interactive as well as Solving a differential equation. One is your normal data structure, whatever you have you have basically arrays of bodies You can define arrays of you can define n number of forces like gravitation or electromagnetic attraction or springs Or you can have motors which could be linear or as well as circular and you can define certain joints to connect those bodies now those joints could be Revolute joints which allow rotation, but they do not allow any movement. You could have hinges. You could have axles you could have ropes and pulleys those those things and On the other hand for solution for the solver part you will have to actually maintain a state vector in which all of those variables Those x and v they get translated to Something like this. So if you have n bodies, you're basically having a six n Size of state vector and that's the size of your system of questions that you're solving So one way of looking at this thing is either you look off the universe as n bodies n bodies moving in three dimensions Or you could think of it as one body Moving in a six n dimensional space. That's just one way to look at it because from the mathematical point of view all those values are comparable Now how do we integrate? There are a bunch of methods well known methods first is the most simple and The first one that everybody tries, you know, I know the derivative I just multiply it with delta t and you know, I add it to the old value and I get a new value Well, it's simple. It's fast. It's also horribly wrong so what happens is because you're calculating the derivative at t1 and t2 and you have you know the derivative at t1 and you use it to extrapolate the value of x at t2 You are getting you're using a really bad estimate of the derivative You're only considering the value at the start of the time step so if you use that solution and simulate let's say earth rotating around Sun, what happens is that those errors which are of second order? They start getting accumulated and Earth starts spilling outwards. So this is clearly not what you want. Don't use Euler's method There are much better methods and they are not really that complicated second one is Ranje Kutta method, which is the fourth order method So you measure the you estimate the derivative at multiple points of the interval and so you get a better estimate or errors are of Fourth order and it's a really really simple really popular. So what happens? When we use Ranje Kutta method now we have a satisfactory Orbit if you zoom in to this there is still some errors But this is fine in this case. I'm using a time step of one day. So one degree is what every time step is now We come to joints joints are basically constraints on the movement of bodies Customs are used to simulate things like clothes. So the the one on the right is our clothes or Human bodies which are basically limbs that are that allow rotation up to a limit You can also use it for collision detection as well as contact so and friction So how do we go about solving constraints? So first of all What all types of concern I have already discussed this there are anchors which Disallow any movement at all of anybody. There are pins which are basically revolute joints they allow revolution but no movement they are sticks which Constraint a distance between two bodies to be a fixed length There are ropes which can Support tension, but no compression. They are police. They are gears and things like that. So, how do we? Go about solving constraints. So first of all what what are constraints doing? They are applying some forces which reject the in illegal movement, right? so we write down the construct equations if you have a If you have a body moving on a given path that curve equation of that that path is the construct equation So those are your position variables and we represent them will let us see now second step is we Calculate corrective forces which will cancel out all those illegal velocities or acceleration. So, there are two approaches One is we can apply corrective forces and second is we can apply corrective impulses so forces is the more Intuitively simpler one because that's what they are doing actually in the in real life But it turns out that if you actually use a force-based constraint solver your errors are start getting higher because Force will correct the velocity in next time step and velocities will correct the position in the time step after that So in the meantime the position has become wrong After this even even after correcting constraint forces They are still numerical errors. So your body may have shifted to a wrong position. So you need to include drift correction So you just include extra term which will bring it back to the Correct position and then you apply those forces to bodies to correct the velocities So the second thing was that the second point said that You need to calculate the forces using Jacobians and Lagrange multipliers. I'll just talk about that So first of all what is Jacobian? What is it's a derivative of this constraint equation with respect to x y and theta? So of course, it will involve partial derivatives. It will Look something like this So the first row is for the first constraint the second row is for the second constraint and by this constraint I don't mean one joint a joint can have multiple constraints, right? For example a pin Pin has two constraints. It removes two degrees of freedom. It allows angular movement, but no x movement and no So you list down all the constraint equations you Differentiate them with respect to all the position variables. There are no velocities here It's just x y and thetas So the size of this matrix will be rows will be number of constraints and Columns will be number of bodies into three if every body is a rigid body in case of particles. We don't have angles, right? now So that's how that's how we got j right we differentiated c and we got j into v Now because We are saying that constraint equation have always to be satisfied That means the derivative of c has to be 0 If c was initially 0 and c dot 2 is always 0 the constraints will be satisfied What that means is that j is actually perpendicular to v if j v is 0 your j is actually perpendicular to velocity so j is basically a representation of some force that this constraint is applying to the body to keep it on the path So if when you think of constant forces Intuitively you it makes sense that forces are also applied perpendicular to the velocity And that means that we can write the corrective force or impulse as simply a constant multiplied by the Jacobian, right? So this is one. This is something called a principle of virtual work This basically says that force corrective forces do no work. They don't add any energy So So this is the tip number 3 Avoid force based constraint solver. They will lead to errors even though it looks like they shouldn't Impulse based constraint solver are better. They you can also include collisions in them. So it's even simpler So how do we solve for constraints actually? So first of all we got the initial velocity Then we need to find out pc which is the corrective impulse Which will give the corrected velocity which is vc We know that c dot has to be 0 and we know that Impulse is proportional perpendicular to velocity. So it's jt lambda So the solution of this three is basically a simple linear equation which is of the format ax equal to b, right? You can use any iterative linear solver most popular is gauss-seidel solver And once you get lambda You get the pc which is the corrective impulse and then you get you use the pc to get the corrected velocities So How do we handle collision detection and response? Well, there are multiple approaches again When it comes to game game engines, they tend to be you know more focused towards performance. They want to do it fast so they make a lot of assumptions or like instead of a The body shape of mario the character you just assume it as a rectangle and Find out whether this rectangle is overlapping another rectangle. So that is that is the axis aligned bounding box approach You can have oriented bounding box approach Mainly you use separating axis theorem which says that two objects are not colliding if you can find a straight line which separates them It's a very simple intuitive thing The one that I have been personally using because I wanted to be more accurate than more Fast is the gjk algorithm. It's a very formal algorithm. It works for convex bodies. It does not work for concave or It it works for including polygons and everything Second problem will be Do you use a discrete collision detection or do you use continuous? So the what do I mean by that? Discrete is when you at every time step you check whether there are any collisions or not When you check at t1 you check at t2, right? But there's a problem with that if you have a bullet and a wall You check at t1 the bullet was here and t2 it has crossed. So you miss the collision, right? So what you need to do is continuous collision detection. You need to extrapolate The movement of the bullet and the movement of the other body and whether they are going to collide or not So if you want to be really accurate and you have If you if your speeds are faster more higher than let's say dimensions of the bodies you should switch to continuous collision detection So I want to show you what I have been able to achieve So first of all, this is the sun and earth model. I have already created this because their values are really elaborate so Let's first solve this using Ranje Kutta method So the time step is again one day and if you see the orbit It is sort of okay but If you switch to let's say Euler's method You will start seeing those Errors So Euler's method is simple, but please don't use it. It's really It's really horrible Uh the second demo I have is Now this is a okay, let me just remove this where I can create the simulation from scratch So I add a box I Change its angle I change its dimension Then I Add a pin I attach the pin to one end of the box There is already Oh, I deleted the box So if you see there is already the earth gravity is already on so there is Gravity pulling it down, but the constant is will reject the movement downward movement So there is it will create a torque of its own. So what happens when I click play So you start seeing those velocities in acceleration and it starts oscillating normally Right now as I said uh use First of all, let me show what what if we don't use drift correction So energy will be conserved, but gradually the body will start drifting in the vertical direction because gravity is always acting And we are only uh solving uh numerically So let let it run for a few while You see those drift happening Right What if I again Enable drift correction it will immediately pull back to the position because the there will be extra force Pulling it back to the so this is required to keep it in valid position Now what if I was not using velocity model for constant solver I'm using a force based constant solver now. So what happens is Every time the position is getting uh wrong by some amount which means increasing potential energy So the amplitude is increasing and the simulation is unstable See that this is not realistic. So so again, I have I have been I have added particles just boxes You can define forces like constant force weight force. You can even define Custom forces by writing a javascript function You can have springs linear motors circular motors In the earth and sun model you saw that A trajectory was being plotted So that was a tracer that you can attach to any point on anybody and it will trace the path of that point Uh, you can display values and these are the joints anchor will reject every every movement Pins will allow only rotation and stick will Enforce the distance to be constant you can add more constants like ropes and pulleys and gears and but that's to do So Yeah, basically that's it. Thank you All right That's pretty cool. Uh, we have time for one question Uh, are you using any uh library for uh doing all the physics and maths calculation here? Are you using a library? Uh, well, I'm using numeric.js just for the linear system solver Everything else the all the differential like question integration and everything is from scratch Because I wanted to first learn and second. I wanted to be accurate rather than fast Okay, and what about all the rendering? Is it all css? No, it's just canvas canvas. Okay, and just normal canvas There's no library. Okay Okay, guys big round of applause for nilesh. Thank you everybody