I’m as much of a geek as Pavan about this kind of stuff, so I thought I’d try to integrate a Physics engine with WPF. After way too much googling and prototyping, I finally settled on using the Newton Game Dynamics engine. It’s written in C++, but the demos and flexibility of the thing just blew me away. I found a pretty good .NET wrapper for it by a guy called flylio (I’ve found & fixed a couple of bugs in it that I’ll need to tell him about).

So far I’ve got some randomly generated static platforms, with random shapes dropped from the top of the screen. It’s really cool and disturbingly addictive to watch them bounce and roll about.

Some notes:

Newton is a 3D physics engine but I needed to get it to work well in 2D (I tried 2D engines but none of them came close to Newton for accuracy, speed or stability). After some disappointing tests (involving an ‘invisible wall’ behind and in front of the scene) I settled instead on attaching a handler to Newton’s ‘body matrix changed’ event. In it I just cleared the Z values and crossed my fingers. It worked!

Newton can work with primitive objects like cylinders, cones, boxes etc. as well as arbitrary convex hulls (nicely represented as "vertex clouds"). This is great combined with WPF, because it means ‘real’ shapes can be used to represent round primitives (better to have a single-sided ellipse than a 30+ sided polygon).

WPF data binding rocks. The whole scene is just an <ItemsControl> with a <Canvas> inside it (using <ItemsPanelTemplate>) bound to an ObservableCollection. The actual bodies are defined as <DataTemplate> elements.

The shapes all look awesome thanks to WPF’s anti-aliasing!

Next I’ll try to add a block car with lumpy wheels, just like the video!

Obviously this is only half what I want to achieve. Getting a designer for this stuff working in WPF should be an interesting ride!

UPDATE: Removed dependency on XNA Framework. Now has a car! Click the image above for demo.

[…] That was a fantastic lecture by the way, and it’s awesome to see the code up. It’s all here There’s also, on the WPF front, is a very cool little WPF/C# 2d physics engine here at Chris Cavanaghs blog that replicates the SMART board sample up on youtube that has a guy drawing a picture of a car and sending it off on his way, google for it since I can’t be bothered to find the link right now. It does however turn pictures in gravitationally accurate (somewhat at least) objects in physical space. Go WPF. […]

[…] WPF and Physics Chris Cavanagh has posted some great code on using a physics engine with WPF. It’s an interesting and elegant example demonstrating a few things: A series of objects making use the wrapped physics engine Chris has chosen. The use of data templates and binding to represent the objects on screen and the use of matrix transforms for rendering based on updates from the the physics code. The interception of the CompositionTarget.Rendering event to perform the physics updates (which results in UI updates owing to the binding) Take a look at a screen shot: Extremely smart, and the first example I’ve seen of such stuff. So who’s building the ‘Asteroids’ clone? Technorati Tags: WPF – Physics Filed under: WPF […]

Hey Jon that sounds cool! Let me know when you’ve got it working in .NET (or if you need some help with it); I’d love to try it out :o)

Did you see my other post on ‘XBAP 2D Physics’? Basically using a simple 2D engine (called Flade); might be useful to you. I’ll get the source posted soon. Flade is written in Actionscript, so it’s quite tempting to port it to Javascript and drive a WPF/E demo with it… ;o)

i was wondering if you or anyone else who reads this and knows more of what’s going on could explain the ‘body matrix changed’ event? specifically, i’m looking to do 2d physics as well, with the additional excercise of having some objects with a specifically set rotational component, and leaving the position to the physics engine. would you mind sharing your insight with this event callback method?

well, i’m still a bit unsure about whether or not i can even do what i’m looking towards doing using newton.

i need to be able to use the collision event, keep the positional offsets from newton, and disregard any rotational changes it does.

i’m also using a c# wrapper, which also makes it that much more tricky to see where exactly i put the callback.. from a ‘Body’ object, i can set up events to be triggered at Transformed, AutoActivated, or ForceCallback. only Transformed has any positional or quaternion rotation associated with it, and from resetting these, i see no effect.. from the documentation, this is an event to be used for updating other objects after collision.. i need to be able to pretty much intercept the collision right as it’s being written.

is the callback you mention even inside the Body, or is it somewhere else entirely?

I just replaced the matrix with a new one and it did the trick. The OnPropertyChanged call just marks the DisplayMatrix DependencyPropertyas changed (you’ll need to do something similar if you’re using WPF databinding).

Chris – Don’t be afraid to rip apart my code :) It could definitely use some refactoring; there’s some functionality in the demo that really should be in its own assembly. The only bit that shouldn’t need any change is the NewtonWrapper (apart from bugs or just bits of Newton functionality it’s not exposing). Let me know how it works out :)

Hi Chris – This is a very cool project (the one where you drop the cars). I saw Mark Miller playing with it at the MVP Summit in Seattle and thought it rocked. I see in the comments that others have asked for the source code for this, but don’t see a link for it. Could you e-mail me a link of where to get the code for this? Thanks…

[…] A very funny WPF 2D application by Chris Cavanagh that itegrates the Newtown Dynamics Physics Engine. The app is very simple but really addictive. It presents a physical environment to you with a couple of obstacles. The only thing you can do is drop stuff into the screen and watch gravity fool around. Nice! WPF 2D Physics […]

Leslie – Your WPF extensions look extremely cool :) The lunar lander demo confirms I’d make a lousy astronaut (something I’ve long suspected). Any plans to make a Silverlight version? :) (BulletX is an ok engine to use, but it has a couple annoying bugs… Howabout a soft-body lander using Wallaber’s JelloPhysics library?).

What I’d like to do is use a Soft and Rigid body combination.
My plan was to make the physics library generic enough to have separate implementations of different physics engines. One day I’m sure. I chose Newton because it is a mature, solid, many featured engine. (Which helped naught for my lander skills as well. *sigh* it too far to long for me to stop breaking the legs off. And I wrote the stoopid thing. In fact I had to make it easier…..hehehe)

Failed object initialization (ISupportInitialize.EndInit). Exception has been thrown by the target of an invocation. Error at object ‘bodies’ in markup file ‘WPFPhysics1;component/window1.xaml’ Line 16 Position 5.

Rohit – I’d love you see the enhancements you’ve made! I’d happily post something about it. I’d recommend setting up a quick project for it on CodePlex, then use TortoiseSVN to get it up there (let me know if you need any help).

You’ll probably also enjoy using Walaber’s “soft body physics” engine I’ve used a few times:

Guys,
It may be cool to look at, but have you ever taken a look at the amount of CPU this small demo chews up? I have a Core 2 Duo machine where I am running this demo on. I noticed that if I keep on dropping rectangles, after some time, the whole animation becomes sluggish. The task manager shows the demo taking 66% CPU even when it was not the main window. That’s too much CPU for a small animation demo like this.