3-D Graphics Overview
This topic provides an overview of 3-D functionality in the Windows Presentation Foundation (WPF) graphics system. The WPF 3-D implementation allows developers to draw, transform, and animate 3-D graphics in both markup and procedural code, using the same capabilities afforded by the platform to 2-D graphics. Developers can combine 2-D and 3-D graphics to create rich controls, provide complex illustrations of data, or enhance the user experience of an application's interface. 3-D support in WPF is not designed to provide a full-featured game-development platform.
This topic contains the following sections.
3-D graphics content in WPF is encapsulated in an element, Viewport3D, that can participate in the two-dimensional element structure. The graphics system treats Viewport3D as a two-dimensional visual element like many others in WPF. Viewport3D functions as a window—a viewport—into a three-dimensional scene. More accurately, it is a surface on which a 3-D scene is projected.
In a conventional 2-D application, use Viewport3D as you would another container element like Grid or Canvas. Although you can use Viewport3D with other 2-D drawing objects in the same scene graph, you cannot interpenetrate 2-D and 3-D objects within a Viewport3D. This topic will focus on how to draw 3-D graphics inside the Viewport3D.
The WPF coordinate system for 2-D graphics locates the origin in the upper left of the rendering area (typically the screen). In the 2-D system, positive x-axis values proceed to the right and positive y-axis values proceed downward. In the 3-D coordinate system, however, the origin is located in the center of the rendering area, with positive x-axis values proceeding to the right but positive y-axis values proceeding upward instead, and positive z-axis values proceeding outward from the origin, toward the viewer.
The space defined by these axes is the stationary frame of reference for 3-D objects in WPF. As you build models in this space and create lights and cameras to view them, it's helpful to distinguish this stationary frame of reference, or "world space," from the local frame of reference you create for each model when you apply transformations to it. Remember also that objects in world space might look entirely different, or not be visible at all, depending on light and camera settings, but the position of the camera does not change the location of objects in world space.
Developers who work in 2-D are accustomed to positioning drawing primitives on a two-dimensional screen. When you create a 3-D scene, it's important to remember that you are really creating a 2-D representation of 3-D objects. Because a 3-D scene looks different depending on the onlooker's point of view, you must specify that point of view. The Camera class allows you to specify this point of view for a 3-D scene.
Another way to understand how a 3-D scene is represented on a 2-D surface is by describing the scene as a projection onto the viewing surface. The ProjectionCamera allows you to specify different projections and their properties to change how the onlooker sees 3-D models. A PerspectiveCamera specifies a projection that foreshortens the scene. In other words, the PerspectiveCamera provides vanishing-point perspective. You can specify the position of the camera in the coordinate space of the scene, the direction and field of view for the camera, and a vector that defines the direction of "up" in the scene. The following diagram illustrates the PerspectiveCamera's projection.
The NearPlaneDistance and FarPlaneDistance properties of ProjectionCamera limit the range of the camera's projection. Because cameras can be located anywhere in the scene, it's possible for the camera to be actually positioned inside a model or very near a model, making it hard to distinguish objects properly. NearPlaneDistance allows you to specify a minimum distance from the camera beyond which objects will not be drawn. Conversely, FarPlaneDistance lets you specify a distance from the camera beyond which objects will not be drawn, which ensures that objects too far away to be recognizable won't be included in the scene.
OrthographicCamera specifies an orthogonal projection of a 3-D model to a 2-D visual surface. Like other cameras, it specifies a position, viewing direction, and "upward" direction. Unlike PerspectiveCamera, however, OrthographicCamera describes a projection that does not include perspective foreshortening. In other words, OrthographicCamera describes a viewing box whose sides are parallel, instead of one whose sides meet in a point at the camera. The following image shows the same model as viewed using PerspectiveCamera and OrthographicCamera.
The following code shows some typical camera settings.
// Defines the camera used to view the 3D object. In order to view the 3D object, // the camera must be positioned and pointed such that the object is within view // of the camera. PerspectiveCamera myPCamera = new PerspectiveCamera(); // Specify where in the 3D scene the camera is. myPCamera.Position = new Point3D(0, 0, 2); // Specify the direction that the camera is pointing. myPCamera.LookDirection = new Vector3D(0, 0, -1); // Define camera's horizontal field of view in degrees. myPCamera.FieldOfView = 60; // Asign the camera to the viewport myViewport3D.Camera = myPCamera;
Model3D is the abstract base class that represents a generic 3-D object. To build a 3-D scene, you need some objects to view, and the objects that make up the scene graph derive from Model3D. Currently, the WPF supports modeling geometries with GeometryModel3D. The Geometry property of this model takes a mesh primitive.
To build a model, begin by building a primitive, or mesh. A 3-D primitive is a collection of vertices that form a single 3-D entity. Most 3-D systems provide primitives modeled on the simplest closed figure: a triangle defined by three vertices. Because the three points of a triangle are coplanar, you can continue adding triangles in order to model more complex shapes, called meshes.
The WPF 3-D system currently provides the MeshGeometry3D class, which allows you to specify any geometry; it does not currently support predefined 3-D primitives like spheres and cubic forms. Begin creating a MeshGeometry3D by specifying a list of triangle vertices as its Positions property. Each vertex is specified as a Point3D. (In Extensible Application Markup Language (XAML), specify this property as a list of numbers grouped in threes that represent the coordinates of each vertex.) Depending on its geometry, your mesh might be composed of many triangles, some of which share the same corners (vertices). To draw the mesh correctly, the WPF needs information about which vertices are shared by which triangles. You provide this information by specifying a list of triangle indices with the TriangleIndices property. This list specifies the order in which the points specified in the Positions list will determine a triangle.
<GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D Positions="-1 -1 0 1 -1 0 -1 1 0 1 1 0" Normals="0 0 1 0 0 1 0 0 1 0 0 1" TextureCoordinates="0 1 1 1 0 0 1 0 " TriangleIndices="0 1 2 1 3 2" /> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial> <DiffuseMaterial.Brush> <SolidColorBrush Color="Cyan" Opacity="0.3"/> </DiffuseMaterial.Brush> </DiffuseMaterial> </GeometryModel3D.Material> <!-- Translate the plane. --> <GeometryModel3D.Transform> <TranslateTransform3D OffsetX="2" OffsetY="0" OffsetZ="-1" > </TranslateTransform3D> </GeometryModel3D.Transform> </GeometryModel3D>
In the preceding example, the Positions list specifies eight vertices to define a cube-shaped mesh. The TriangleIndices property specifies a list of twelve groups of three indices. Each number in the list refers to an offset into the Positions list. For example, the first three vertices specified by the Positions list are (1,1,0), (0,1,0), and (0,0,0). The first three indices specified by the TriangleIndices list are 0, 2, and 1, which correspond to the first, third, and second points in the Positions list. As a result, the first triangle that makes up the cube model will be composed from (1,1,0) to (0,1,0) to (0,0,0), and the remaining eleven triangles will be determined similarly.
You can continue defining the model by specifying values for the Normals and TextureCoordinates properties. To render the surface of the model, the graphics system needs information about which direction the surface is facing at any given triangle. It uses this information to make lighting calculations for the model: surfaces that face directly towards a light source appear brighter than those angled away from the light. Though the WPF can determine default normal vectors by using the position coordinates, you can also specify different normal vectors to approximate the appearance of curved surfaces.
The TextureCoordinates property specifies a collection of Points that tell the graphics system how to map the coordinates that determine how a texture is drawn to the vertices of the mesh. TextureCoordinates are specified as a value between zero and 1, inclusive. As with the Normals property, the graphics system can calculate default texture coordinates, but you might choose to set different texture coordinates to control the mapping of a texture that includes part of a repeating pattern, for example. More information about texture coordinates can be found in subsequent topics or in the Managed Direct3D SDK.
The following example shows how to create one face of the cube model in procedural code. Note that you can draw the entire cube as a single GeometryModel3D; this example draws the cube's face as a distinct model in order to apply separate textures to each face later.
side1Plane.Positions.Add(new Point3D(-0.5, -0.5, -0.5)); side1Plane.Positions.Add(new Point3D(-0.5, 0.5, -0.5)); side1Plane.Positions.Add(new Point3D(0.5, 0.5, -0.5)); side1Plane.Positions.Add(new Point3D(0.5, 0.5, -0.5)); side1Plane.Positions.Add(new Point3D(0.5, -0.5, -0.5)); side1Plane.Positions.Add(new Point3D(-0.5, -0.5, -0.5)); side1Plane.TriangleIndices.Add(0); side1Plane.TriangleIndices.Add(1); side1Plane.TriangleIndices.Add(2); side1Plane.TriangleIndices.Add(3); side1Plane.TriangleIndices.Add(4); side1Plane.TriangleIndices.Add(5); side1Plane.Normals.Add(new Vector3D(0, 0, -1)); side1Plane.Normals.Add(new Vector3D(0, 0, -1)); side1Plane.Normals.Add(new Vector3D(0, 0, -1)); side1Plane.Normals.Add(new Vector3D(0, 0, -1)); side1Plane.Normals.Add(new Vector3D(0, 0, -1)); side1Plane.Normals.Add(new Vector3D(0, 0, -1)); side1Plane.TextureCoordinates.Add(new Point(1, 0)); side1Plane.TextureCoordinates.Add(new Point(1, 1)); side1Plane.TextureCoordinates.Add(new Point(0, 1)); side1Plane.TextureCoordinates.Add(new Point(0, 1)); side1Plane.TextureCoordinates.Add(new Point(0, 0)); side1Plane.TextureCoordinates.Add(new Point(1, 0));
For a mesh to look like a three-dimensional object, it must have an applied texture to cover the surface defined by its vertices and triangles so it can be lit and projected by the camera. In 2-D, you use the Brush class to apply colors, patterns, gradients, or other visual content to areas of the screen. The appearance of 3-D objects, however, is a function of the lighting model, not just of the color or pattern applied to them. Real-world objects reflect light differently depending on the quality of their surfaces: glossy and shiny surfaces don't look the same as rough or matte surfaces, and some objects seem to absorb light while others glow. You can apply all the same brushes to 3-D objects that you can apply to 2-D objects, but you can't apply them directly.
To define the characteristics of a model's surface, WPF uses the Material abstract class. The concrete subclasses of Material determine some of the appearance characteristics of the model's surface, and each also provides a Brush property to which you can pass a SolidColorBrush, TileBrush, or VisualBrush.
DiffuseMaterial specifies that the brush will be applied to the model as though that model were lit diffusely. Using DiffuseMaterial most resembles using brushes directly on 2-D models; model surfaces do not reflect light as though shiny.
SpecularMaterial specifies that the brush will be applied to the model as though the model's surface were hard or shiny, capable of reflecting highlights. You can set the degree to which the texture will suggest this reflective quality, or "shine," by specifying a value for the SpecularPower property.
EmissiveMaterial allows you to specify that the texture will be applied as though the model were emitting light equal to the color of the brush. This does not make the model a light; however, it will participate differently in shadowing than it would if textured with DiffuseMaterial or SpecularMaterial.
For better performance, the backfaces of a GeometryModel3D (those faces that are out of view because they are on the opposite side of the model from the camera) are culled from the scene. To specify a Material to apply to the backface of a model like a plane, set the model's BackMaterial property.
To achieve some surface qualities, like glowing or reflective effects, you might want to apply several different brushes to a model in succession. You can apply and reuse multiple Materials by using the MaterialGroup class. The children of the MaterialGroup are applied first to last in multiple rendering passes.
The following code examples show how to apply a solid color and a drawing as brushes to 3-D models.
<DrawingBrush x:Key="patternBrush" Viewport="0,0,0.1,0.1" TileMode="Tile"> <DrawingBrush.Drawing> <DrawingGroup> <DrawingGroup.Children> <GeometryDrawing Geometry="M0,0.1 L0.1,0 1,0.9, 0.9,1z" Brush="Gray" /> <GeometryDrawing Geometry="M0.9,0 L1,0.1 0.1,1 0,0.9z" Brush="Gray" /> <GeometryDrawing Geometry="M0.25,0.25 L0.5,0.125 0.75,0.25 0.5,0.5z" Brush="#FFFF00" /> <GeometryDrawing Geometry="M0.25,0.75 L0.5,0.875 0.75,0.75 0.5,0.5z" Brush="Black" /> <GeometryDrawing Geometry="M0.25,0.75 L0.125,0.5 0.25,0.25 0.5,0.5z" Brush="#FF0000" /> <GeometryDrawing Geometry="M0.75,0.25 L0.875,0.5 0.75,0.75 0.5,0.5z" Brush="MediumBlue" /> </DrawingGroup.Children> </DrawingGroup> </DrawingBrush.Drawing> </DrawingBrush>
Lights in 3-D graphics do what lights do in the real world: they make surfaces visible. More to the point, lights determine what part of a scene will be included in the projection. Light objects in WPF create a variety of light and shadow effects and are modeled after the behavior of various real-world lights. You must include at least one light in your scene, or no models will be visible.
The following lights derive from the base class Light:
AmbientLight: Provides ambient lighting that illuminates all objects uniformly regardless of their location or orientation.
PointLightIlluminates like a nearby light source. PointLights have a position and cast light from that position. Objects in the scene are illuminated depending on their position and distance with respect to the light. PointLightBase exposes a Range property, which determines a distance beyond which models will not be illuminated by the light. PointLight also exposes attenuation properties which determine how the light's intensity diminishes over distance. You can specify constant, linear, or quadratic interpolations for the light's attenuation.
SpotLightInherits from PointLight. Spotlights illuminate like PointLight and have both position and direction. They project light in a cone-shaped area set by InnerConeAngle and OuterConeAngle properties, specified in degrees.
Lights are Model3D objects, so you can transform and animate light properties, including position, color, direction, and range.
When you create models, they have a particular location in the scene. To move those models around in the scene, to rotate them, or to change their size, it's not practical to change the vertices that define the models themselves. Instead, just as in 2-D, you apply transformations to models.
Each model object has a Transform property with which you can move, re-orient, or resize the model. When you apply a transform, you effectively offset all the points of the model by whatever vector or value specified by the transform. In other words, you've transformed the coordinate space in which the model is defined ("model space"), but you haven't changed the values that make up the model's geometry in the coordinate system of the entire scene ("world space").
For more information about transforming models, see 3-D Transformations Overview.
The WPF 3-D implementation participates in the same timing and animation system as 2-D graphics. In other words, to animate a 3-D scene, animate the properties of its models. It's possible to animate properties of primitives directly, but it's typically easier to animate transformations that change the position or appearance of models. Because transformations can be applied to Model3DGroup objects as well as individual models, it's possible to apply one set of animations to a child of a Model3DGroup and another set of animations to a group of child objects. You can also achieve a variety of visual effects by animating the properties of your scene's lighting. Finally, you might choose to animate the projection itself by animating the camera position or field of view. For background information on the WPF timing and animation system, see the Animation Overview, Storyboards Overview, and Freezable Objects Overview topics.
To animate an object in WPF, you create a timeline, define an animation (which is really a change in some property value over time), and specify the property to which to apply the animation. Because all the objects in a 3-D scene are children of Viewport3D, the properties targeted by any animation you want to apply to the scene are properties of properties of Viewport3D.
Suppose you want to make a model appear to wobble in place. You might choose to apply a RotateTransform3D to the model, and animate the axis of its rotation from one vector to another. The following code example demonstrates applying a Vector3DAnimation to the Axis property of the transformation's Rotation3D, assuming the RotateTransform3D to be one of several transforms applied to the model with a TransformGroup.
To render the scene, add models and lights to a Model3DGroup, then set the Model3DGroup as the Content of a ModelVisual3D. Add the ModelVisual3D to the Children collection of the Viewport3D. Add cameras to the Viewport3D by setting its Camera property.
Finally, add the Viewport3D to the window. When the Viewport3D is included as the content of a layout element like Canvas, specify the size of the Viewport3D by setting its Height and Width properties (inherited from FrameworkElement).
<UserControl x:Class="HostingWpfUserControlInWf.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Grid> <!-- Place a Label control at the top of the view. --> <Label HorizontalAlignment="Center" TextBlock.TextAlignment="Center" FontSize="20" Foreground="Red" Content="Model: Cone"/> <!-- Viewport3D is the rendering surface. --> <Viewport3D Name="myViewport" > <!-- Add a camera. --> <Viewport3D.Camera> <PerspectiveCamera FarPlaneDistance="20" LookDirection="0,0,1" UpDirection="0,1,0" NearPlaneDistance="1" Position="0,0,-3" FieldOfView="45" /> </Viewport3D.Camera> <!-- Add models. --> <Viewport3D.Children> <ModelVisual3D> <ModelVisual3D.Content> <Model3DGroup > <Model3DGroup.Children> <!-- Lights, MeshGeometry3D and DiffuseMaterial objects are added to the ModelVisual3D. --> <DirectionalLight Color="#FFFFFFFF" Direction="3,-4,5" /> <!-- Define a red cone. --> <GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D Positions="0.293893 -0.5 0.404509 0.475528 -0.5 0.154509 0 0.5 0 0.475528 -0.5 0.154509 0 0.5 0 0 0.5 0 0.475528 -0.5 0.154509 0.475528 -0.5 -0.154509 0 0.5 0 0.475528 -0.5 -0.154509 0 0.5 0 0 0.5 0 0.475528 -0.5 -0.154509 0.293893 -0.5 -0.404509 0 0.5 0 0.293893 -0.5 -0.404509 0 0.5 0 0 0.5 0 0.293893 -0.5 -0.404509 0 -0.5 -0.5 0 0.5 0 0 -0.5 -0.5 0 0.5 0 0 0.5 0 0 -0.5 -0.5 -0.293893 -0.5 -0.404509 0 0.5 0 -0.293893 -0.5 -0.404509 0 0.5 0 0 0.5 0 -0.293893 -0.5 -0.404509 -0.475528 -0.5 -0.154509 0 0.5 0 -0.475528 -0.5 -0.154509 0 0.5 0 0 0.5 0 -0.475528 -0.5 -0.154509 -0.475528 -0.5 0.154509 0 0.5 0 -0.475528 -0.5 0.154509 0 0.5 0 0 0.5 0 -0.475528 -0.5 0.154509 -0.293892 -0.5 0.404509 0 0.5 0 -0.293892 -0.5 0.404509 0 0.5 0 0 0.5 0 -0.293892 -0.5 0.404509 0 -0.5 0.5 0 0.5 0 0 -0.5 0.5 0 0.5 0 0 0.5 0 0 -0.5 0.5 0.293893 -0.5 0.404509 0 0.5 0 0.293893 -0.5 0.404509 0 0.5 0 0 0.5 0 " Normals="0.7236065,0.4472139,0.5257313 0.2763934,0.4472138,0.8506507 0.5308242,0.4294462,0.7306172 0.2763934,0.4472138,0.8506507 0,0.4294458,0.9030925 0.5308242,0.4294462,0.7306172 0.2763934,0.4472138,0.8506507 -0.2763934,0.4472138,0.8506507 0,0.4294458,0.9030925 -0.2763934,0.4472138,0.8506507 -0.5308242,0.4294462,0.7306172 0,0.4294458,0.9030925 -0.2763934,0.4472138,0.8506507 -0.7236065,0.4472139,0.5257313 -0.5308242,0.4294462,0.7306172 -0.7236065,0.4472139,0.5257313 -0.858892,0.429446,0.279071 -0.5308242,0.4294462,0.7306172 -0.7236065,0.4472139,0.5257313 -0.8944269,0.4472139,0 -0.858892,0.429446,0.279071 -0.8944269,0.4472139,0 -0.858892,0.429446,-0.279071 -0.858892,0.429446,0.279071 -0.8944269,0.4472139,0 -0.7236065,0.4472139,-0.5257313 -0.858892,0.429446,-0.279071 -0.7236065,0.4472139,-0.5257313 -0.5308242,0.4294462,-0.7306172 -0.858892,0.429446,-0.279071 -0.7236065,0.4472139,-0.5257313 -0.2763934,0.4472138,-0.8506507 -0.5308242,0.4294462,-0.7306172 -0.2763934,0.4472138,-0.8506507 0,0.4294458,-0.9030925 -0.5308242,0.4294462,-0.7306172 -0.2763934,0.4472138,-0.8506507 0.2763934,0.4472138,-0.8506507 0,0.4294458,-0.9030925 0.2763934,0.4472138,-0.8506507 0.5308249,0.4294459,-0.7306169 0,0.4294458,-0.9030925 0.2763934,0.4472138,-0.8506507 0.7236068,0.4472141,-0.5257306 0.5308249,0.4294459,-0.7306169 0.7236068,0.4472141,-0.5257306 0.8588922,0.4294461,-0.27907 0.5308249,0.4294459,-0.7306169 0.7236068,0.4472141,-0.5257306 0.8944269,0.4472139,0 0.8588922,0.4294461,-0.27907 0.8944269,0.4472139,0 0.858892,0.429446,0.279071 0.8588922,0.4294461,-0.27907 0.8944269,0.4472139,0 0.7236065,0.4472139,0.5257313 0.858892,0.429446,0.279071 0.7236065,0.4472139,0.5257313 0.5308242,0.4294462,0.7306172 0.858892,0.429446,0.279071 " TriangleIndices="0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 " /> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial> <DiffuseMaterial.Brush> <SolidColorBrush Color="Red" Opacity="1.0"/> </DiffuseMaterial.Brush> </DiffuseMaterial> </GeometryModel3D.Material> </GeometryModel3D> </Model3DGroup.Children> </Model3DGroup> </ModelVisual3D.Content> </ModelVisual3D> </Viewport3D.Children> </Viewport3D> </Grid> </UserControl>