WPF 3D Programming

By | February 17, 2011

WPF uses DirectX as its rendering engine. The framework allows much more than only 2D programming. Before we start with a simple 3D example, you should know some basics:

3D model A 3D model is an object that will be presented in your application. A model is defined by triangles. The triangles together build up a mesh. For each point, the coordinates X,Y and Z have to be defined.
Camera A camera specifies how you look at the model/scene.
Light As in normal life, we need light to see something. 🙂 There are multiple types of light.

Example:
You can create the models in XAML or C#. There are some tools, which are able to export the model (created in a designer) into XAML. For this example, I used only XAML.
First we define the points (attribute Positions) and then the “connection” between them (attribute TriangleIndicies). There are two ways for defining a point:
-1, 1, 0 or -1 1 0. The order is following: X, Y and then Z.

        
        
            
            
                
            
            
                
                    
                        
                        
                    
                
                
                    
                        
                            
                                
                                 
                            
                            
                                
                                    
                                        
                                    
                                
                            
                            
                                
                                    
                                    
                                        
                                    
                                
                            
                        
                    
                
            
            
                
                
                    
                        
                            
                            
                        
                    
                
            
        

The result is a cube. A cube contains 12 triangles. This picture shows how they are placed and in which direction the cube is rotating.
3D cube
In the code I used a “Viewport3D”. A viewport renders the 3D content to 2D. Because a screen shows the 3D content only flat (2D).
The rotation is done with “DoubleAnimation”. DoubleAnimation can be used in 2D programming too.