UPDATES:
- ClickOnce demo available here! (.NET 3.5 SP1 required).
- VS2008 source on CodePlex.
Pavan Podila recently posted about a really cool video on YouTube. It shows a guy using a SMART Board (or similar) to draw a 2D scene and visualize it in a simulated physics environment.
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.

36 responses so far ↓
Pavan Podila // October 24, 2006 at 6:26 am |
Chris,
This is ridiculously cool. Would you mind sharing the code? I am interested in developing this further. Let me know.
Tim Sneath // October 30, 2006 at 5:37 pm |
A Sackful of WPF Tidbits
It’s been a busy month for me, primarily due to the arrival of our third child (and our first American!)
WPF Team Bloggers // October 30, 2006 at 7:02 pm |
A Sackful of WPF Tidbits
It’s been a busy month for me, primarily due to the arrival of our third child (and our first American!)
thefactoryfactory // October 31, 2006 at 9:35 am |
[...] 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. [...]
Hope is not an Architecture : WPF "whiteboard" demo // November 6, 2006 at 4:42 am |
[...] If you are running Windows Vista or .NET 3.0 then you can take a look here. [...]
Marc My Words : WPF and Physics // December 9, 2006 at 8:41 am |
[...] 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 [...]
luisdans WebLog : Diciembre 19, 2007. Productos mejor vendidos vs productos de nicho. Meshups. Multipoint. // December 19, 2006 at 9:56 am |
[...] Diciembre 19, 2007. Productos mejor vendidos vs productos de nicho. Meshups. Multipoint. En The Long Tail, Chris Anderson trata de demostrar que en la era de Internet hay 2 productos por su nivel ventas: los best-sellers y los de nicho; los primeros crean una curva estadística muy importante pero los segundos mayor a lo largo del tiempo – “la cola larga”. Recomienda como crear flexibilidad en precios, servicios y entrega utilizando mercadotecnia innovadora. Lee Gomes del WSJ quiere desbancar esa teoria, cita datos muy interesante de como los productos mejor vendidos continuan representando el 80% o más de las ventas o del acceso: El 10% de top videos de TouTube representa el 79% de las reproducciones totales. 50 titulos de los 60,000 de netflix o 1% del inventario generan el 30% de las rentas. Hay que seguir la conversación. Hablando de desarrollo de software, IBM tiene un artículo muy divertido sobre programación de Meshups y Borland anuncia de nuevos su línea Turbo recordando su conferencia de 1996. Aunque hay eventos que a uno lo hacen dudar mucho del rumbo real de todo esto: Google mata su interfaz programática de búsqueda. En lo referente a Innovación, todavia se puede hacer mucho en un programa de 640kb, ver esta demo de WPF 2D Physics. (También visite esta demo de WPF/E). El 23 de noviembre pasado comenté del Multipoint, vea ahora el video en Channel 9. Lea finalmente esta trágica historia. [...]
TheExpressionist // January 14, 2007 at 4:04 pm |
You should search for Shawn Van Ness’s Physics Illustrator, he’s a pm over on Tablet and he wrote something for Tablet a few years back that is amazing…
Chris Cavanagh // January 14, 2007 at 11:43 pm |
TheExpressionist – Yeah I saw that
) Pretty cool if I had a tablet PC! (could download source, compile and run on XP sans pen though). Should ask him to do a PocketPC version
)
What’d be really sweet is a simplified Javascript physics engine tied to WPF/E…
Jon Harrop // March 9, 2007 at 8:56 pm |
Excellent stuff!
I’ve just written a 2D rigid body simulator with OpenGL visualization in OCaml. I’m going to port it to .NET and F# for my book “F# for Scientists”. I’ll put the source up ASAP.
Chris Cavanagh // March 10, 2007 at 12:48 am |
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
)
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)
chris forrester // June 2, 2007 at 3:04 am |
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?
thanks,
chris.
Chris Cavanagh // June 2, 2007 at 6:56 am |
Chris – Which bit of the code are you looking at? Do you mean the SetTransform event?
chris forrester // June 3, 2007 at 3:26 am |
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?
Chris Cavanagh // June 3, 2007 at 8:17 am |
Chris – Not sure this is what you’re after, but here’s all I did:
///
/// Handle Matrix changed callback
///
/// Body
/// Event arguments
void Body_SetTransform( object sender, CSetTransformEventArgs e )
{
Matrix3D m = Matrix;
Matrix = new Matrix3D( (float)m.M11, (float)m.M12, 0, 0, (float)m.M21, (float)m.M22, 0, 0, 0, 0, 1, 0, (float)m.OffsetX, (float)m.OffsetY, 0, 0 );
OnPropertyChanged( “DisplayMatrix” );
}
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 forrester // June 3, 2007 at 7:53 pm |
awesome, that’s all i needed.. i was trying to figure out how to do it from the library as-is with some arcane callback, instead of going into the wrapper source directly and making the modifications.
that’s the thing with black boxes i’ve found.. i usually don’t even consider something inside the box being malleable. definitely something i have to change my perspective of.
thanks chris.
Chris Cavanagh // June 3, 2007 at 11:18 pm |
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
Mark Rosenberg // June 8, 2007 at 3:13 pm |
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…
Chris Cavanagh // June 8, 2007 at 4:57 pm |
Hi Mark! It’s great to know everyone’s getting a kick out of it
Actually the source code is available through these posts:
http://chriscavanagh.wordpress.com/2006/10/30/wpf-physics-source/
http://chriscavanagh.wordpress.com/2006/11/04/more-physics-source/
The first is the demo project, the second is the C# wrapper around the Newton Physics library. Hope this is what you’re looking for
Lary // June 7, 2008 at 2:09 pm |
download?
Chris Cavanagh // June 7, 2008 at 6:57 pm |
Lary – Try here:
http://chriscavanagh.wordpress.com/2006/10/30/wpf-physics-source/
Cool WPF Samples - Manuel Meyer's Blog // June 12, 2008 at 3:30 am |
[...] 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 Godwin // July 7, 2008 at 10:00 pm |
I’ve uploaded a beta of proper Newton Extensions for the WPF to “The Code Project”. Inspired by Chris’s really ingenious demo.
An example would be:
…
or
…
The extensions would pick up the visual model data and become, well, physical.
Link:
http://www.codeproject.com/KB/WPF/NetwonDynExtensionsWPF.aspx
Leslie Godwin // July 7, 2008 at 10:02 pm |
(Sorry code snippet’s didn’t come through.
I’ve uploaded a beta of proper Newton
Extensions for the WPF to “The Code Project”. Inspired by Chris’s really ingenious demo.
An example would be:
or
…
The extensions would pick up the visual model data and become, well, physical.
Link:
http://www.codeproject.com/KB/WPF/NetwonDynExtensionsWPF.aspx
Leslie Godwin // July 7, 2008 at 10:11 pm |
The examples again. *sigh*
I’m a knob.
<ModelVisual3D newton:World.Body=”ConvexBody3D”>
<ModelVisual3D.Content>
or
<ModelVisual3D>
<newton:World.Body>
<newton:ConvexBody3D x:Name=”_yellowCube” Mass=”0.1″ ApplyForce=”_yellowCube_ApplyForce”/>
</newton:World.Body>
Chris Cavanagh // July 7, 2008 at 11:11 pm |
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?).
Leslie Godwin // July 8, 2008 at 12:59 am |
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)
Anyhoo, I’m sure someone can implement the soft body model extension now that I’ve shown how it’s done.
Demos - ClickOnce deployment « Chris Cavanagh’s Blog // September 4, 2008 at 1:03 pm |
[...] WPF 2D Physics – One of my first demos (the NewtonDynamics-based one with the car) [blog post]. [...]
Tiago Andrade e Silva // January 21, 2009 at 9:24 am |
Hi!
Downloaded and tried to run but i’m getting:
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.
I converted both projects to VS2008.
Chris Cavanagh // January 21, 2009 at 10:17 am |
Tiago – I’ve added a more recent version of the source to CodePlex. Give it a try here: http://www.codeplex.com/WPF2DPhysics
Hope this helps!
Rohit Gupta // June 22, 2009 at 9:08 pm |
Chris,
This is a real great demo to kick start the WPF and NewtonDynamics learning process.
I have been making some enhancements to make the demo even more fun. The 2 that I have completed till now are:
1) Click to remove a body from the world
2) Click and “push” the body in any given direction
I can send you the code if you think others would be interested.
The main challenge for me (being new to C#, NewtonDynamics and WPF) was to get to the Newton Body object from the WPF Visual Object. Once I put that in place, it indeed was rather simple.
Chris Cavanagh // June 22, 2009 at 10:15 pm |
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:
http://chriscavanagh.wordpress.com/2008/06/24/silverlight-soft-body-physics/
Once you see jello rolling around your screen, you’ll be hooked
Rohit Gupta // June 23, 2009 at 7:51 pm |
Thanks. I just might need your help, but let me give it a try first.
Rohit Gupta // June 23, 2009 at 11:05 pm |
Almost there, but I am getting an authentication failure when I try to import my source code into CodePlex. Checked and double check passwords.
The CodePlex server was down for a little bit earlier today. I will try again tomorrow.
Rohit Gupta // June 24, 2009 at 9:20 pm |
Chris,
I have uploaded the project to codeplex.
http://wpf2dphysicsplus.codeplex.com/
There are 2 open issues that I am tracking. These are in the issues tracker.
Rohit
WPF 2D Physics Plus « Chris Cavanagh’s Blog // June 25, 2009 at 1:02 pm |
[...] 25, 2009 · Leave a Comment Rohit Gupta is working on some great enhancements to the WPF 2D Physics demo I posted. Features [...]