Make a three-dimensional cube that displays different pictures on each side with WPF, XAML, and C#


The example Make a 3D cube and rotate it using WPF, XAML, and C# explains how to use XAML to display a three-dimensional cube in a WPF program. As I mention in that post, the GeometryModel3D object that defines the cube can display only a single material. There are two basic approaches for displaying a different image on each side of the cube. First, you can make one big image that contains all of the others. Then when you define each side's triangles, you set their texture coordinates so they each display the appropriate part of the big image. The second approach is to make a separate GeometryModel3D object for each side. The first approach is particularly common for game and other high-performance 3D programming because it is more efficient for the graphics hardware to display many triangles that use the same texture than to display many separate objects that use different textures. However, this program was supposed to make it easy to display cubes with different pictures so, to make changing the pictures as easy as possible, I decided to use a separate texture and GeometryModel3D for each side. The following code shows how the program defines the cube's top face.
<!-- Top -->The difference between this code and the code in the previous example is that this object's material uses an image file to define its brush. The cube's other faces are similar. (This example has two other useful features: the ability to respond to menu commands and the ability to save the cube's image into a file. I'll explain them in my next post.)
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions = "-1,1,1 1,1,1 1,1,-1 -1,1,-1"
TriangleIndices = "0 1 2 2,3,0"
TextureCoordinates="0,1 1,1 1,0 0,0"
/>
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<ImageBrush ImageSource="Top.png"/>
</DiffuseMaterial.Brush>
</DiffuseMaterial>
</GeometryModel3D.Material>
</GeometryModel3D>


Comments