Custom Meshes

As I already mentioned, typing mesh positions by hand is not scalable, even for the simplest things like a cube. Meshes must be generated either by a tool or by code. Ideally, I would like to write something like this:

<GeometryModel3D>
<GeometryModel3D.Geometry>
<my:Sphere Center=”1 2 -1″ Radius=”0.9″>
</GeometryModel3D.Geometry>
</GeometryModel3D>

Unfortunately, this is not possible. Geometry property expects MeshGeometry3D, which is a sealed class. So, deriving a Sphere from MeshGeometry3D is not an option. Surprisingly, very little on the subject can be found on the net. It appears that there are two practical ways to refer to a generated mesh (as Charles Petzold describes in this post):

There are basically two ways to create classes that generate MeshGeometry3D objects and which can be used in XAML:

Method 1: Write a class that exposes a public property (named Geometry, for example) of type MeshGeometry3D. In XAML, reference that class in a Resource section. In your markup, create a GeometryModel3D as usual, and define a binding between the Geometry property of that GeometryModel3D and the Geometry property of the resource.

Method 2: Write a class that derives from ModelVisual3D. This is the only class in the Systems.Windows.Media.Media3D namespace that is neither sealed nor abstract! This class creates its own MeshGeometry3D and GeometryModel3D objects. The class must also define its own public Material and BackMaterial properties, and transfer the values of those properties to its internal GeometryModel3D. It’s messy, but you can then instantiate this class directly in XAML as a child of a Viewport3D.

This seems a little surprising. After all, if WPF does not provide its own primitives, it should have made creating custom primitives easy, no?

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *