Monday 2 August 2010

How to Connect 3D Points With Each Other in WPF?

 

Imagine you have some 3D spheres that you want them to be connected to each other such as:

image

Assuming you know a point in each of these spheres, the following Code uses a 3D cube to connect 2 3D Points with each other:

private void ConnectPoints(Point3D firstPoint, Point3D secondPoint, DiffuseMaterial diffuseMaterial, double thickness)
{
MeshGeometry3D linkCube = GetCube(firstPoint, secondPoint, thickness);

GeometryModel3D mGeometryLink = new GeometryModel3D(linkCube, diffuseMaterial);
mGeometryLink.Transform = new Transform3DGroup();

ModelVisual3D modelVisual3D = new ModelVisual3D();
modelVisual3D.Content = mGeometryLink;

_models.Add(modelVisual3D);
}

private MeshGeometry3D GetCube(Point3D firstPoint, Point3D secondPoint, double thickness)
{
MeshGeometry3D mesh = new MeshGeometry3D();
mesh.Positions.Add(new Point3D(firstPoint.X, firstPoint.Y, firstPoint.Z));
mesh.Positions.Add(new Point3D(firstPoint.X + thickness, firstPoint.Y, firstPoint.Z));
mesh.Positions.Add(new Point3D(firstPoint.X + thickness, firstPoint.Y - thickness, firstPoint.Z));
mesh.Positions.Add(new Point3D(firstPoint.X, firstPoint.Y - thickness, firstPoint.Z));

mesh.Positions.Add(new Point3D(secondPoint.X, secondPoint.Y, secondPoint.Z));
mesh.Positions.Add(new Point3D(secondPoint.X + thickness, secondPoint.Y, secondPoint.Z));
mesh.Positions.Add(new Point3D(secondPoint.X + thickness, secondPoint.Y - thickness, secondPoint.Z));
mesh.Positions.Add(new Point3D(secondPoint.X, secondPoint.Y - thickness, secondPoint.Z));

int k = mesh.Positions.Count - 8;
// Front face
mesh.TriangleIndices.Add(0 + k);
mesh.TriangleIndices.Add(1 + k);
mesh.TriangleIndices.Add(2 + k);
mesh.TriangleIndices.Add(2 + k);
mesh.TriangleIndices.Add(3 + k);
mesh.TriangleIndices.Add(0 + k);

// Back face
mesh.TriangleIndices.Add(6 + k);
mesh.TriangleIndices.Add(5 + k);
mesh.TriangleIndices.Add(4 + k);
mesh.TriangleIndices.Add(4 + k);
mesh.TriangleIndices.Add(7 + k);
mesh.TriangleIndices.Add(6 + k);

// Right face
mesh.TriangleIndices.Add(1 + k);
mesh.TriangleIndices.Add(5 + k);
mesh.TriangleIndices.Add(2 + k);
mesh.TriangleIndices.Add(5 + k);
mesh.TriangleIndices.Add(6 + k);
mesh.TriangleIndices.Add(2 + k);

// Top face
mesh.TriangleIndices.Add(2 + k);
mesh.TriangleIndices.Add(6 + k);
mesh.TriangleIndices.Add(3 + k);
mesh.TriangleIndices.Add(3 + k);
mesh.TriangleIndices.Add(6 + k);
mesh.TriangleIndices.Add(7 + k);

// Bottom face
mesh.TriangleIndices.Add(5 + k);
mesh.TriangleIndices.Add(1 + k);
mesh.TriangleIndices.Add(0 + k);
mesh.TriangleIndices.Add(0 + k);
mesh.TriangleIndices.Add(4 + k);
mesh.TriangleIndices.Add(5 + k);

// Right face
mesh.TriangleIndices.Add(4 + k);
mesh.TriangleIndices.Add(0 + k);
mesh.TriangleIndices.Add(3 + k);
mesh.TriangleIndices.Add(3 + k);
mesh.TriangleIndices.Add(7 + k);
mesh.TriangleIndices.Add(4 + k);
return mesh;
}

No comments: