Create a 3D surface really quickly with WPF, XAML, and C#

Create a 3D surface really quickly

The example Draw a smooth 3D surface with WPF, XAML, and C# draws a smooth surface but take about 16 seconds on my computer. The example Create a 3D surface more quickly with WPF, XAML, and C# searches for duplicate points from the rear of its points collection so it’s much faster, taking only about 2 seconds.

This example stores its points in a Dictionary (as well as in the collection that the WPF drawing code needs), so it can locate points even more quickly. This example uses the following AddPoints method to create new points for the surface.

// A dictionary to hold points for fast lookup.
private Dictionary<Point3D, int> PointDictionary =
    new Dictionary<Point3D, int>();

// If the point already exists, return its index.
// Otherwise create the point and return its new index.
private int AddPoint(Point3DCollection points, Point3D point)
    // If the point is in the point dictionary,
    // return its saved index.
    if (PointDictionary.ContainsKey(point))
        return PointDictionary[point];

    // We didn't find the point. Create it.
    PointDictionary.Add(point, points.Count - 1);
    return points.Count - 1;

This code creates a Dictionary to hold the points’ indices in the points collection. The AddPoint method first uses the Dictionary object’s ContainsKey method to see if the point is already in the collection. If ContainsKey returns true, the code gets the point’s index from the Dictionary and returns it. If this is a new point, the method adds it to the points collection and returns its index.

The previous example builds its surface in under 2 seconds. This example builds its data model almost instantly.

The ultimate solution would be to do some (relatively) simple math to figure out where each triangle’s index is stored. Then you could calculate each point’s index instead of needing to look it up. For a scene where calculating indices would be hard, this example shows that a Dictionary can give you pretty good performance even when that kind of calculation is impossible.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in algorithms, geometry, graphics, mathematics, wpf, XAML and tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Create a 3D surface really quickly with WPF, XAML, and C#

  1. Pingback: Draw smooth spheres using WPF and C# - C# HelperC# Helper

Leave a Reply

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