How to check for rotated objects translated points collisions? - c#

I've got two rectangles on WindowsForm and I would like to check if they collide. For simple non-rotated collision it looks like this:
Point newLocation; // upper-left corner of the object to check its collision
Size objectSize; // the object size
bool collision = false;
foreach (Object otherObject in otherObjects)
{
if (newLocation.X >= otherObject.location.X && newLocation.X <= otherObject.location.X + otherObject.size.width)
if (newLocation.Y >= otherObject.location.Y && newLocation.Y <= otherObject.location.Y + otherObject.size.height)
{
collision = true;
break;
}
}
But now I rotated both objects with:
Matrix matrix = new Matrix();
matrix.RotateAt(angle, newLocation);
graphics.Transform = matrix;
How can I check for the collisions at the rotated matrix? Can I somehow get the translated X, Y coordinates?

I have some code to transfer points from the standard coordinate system to a specific coordinate system (but in you case, Y increases downards in screen, so some adjusts were made and commented).
Here, the double[] represents a point, where index 0 is X coordinate and index 1 is Y.
Notice the angle of the new coordinate system is measurede counterclockwise and in radians. (Multiply by Pi/180 to transform degrees to radians).
/// <summary>
/// Implemented - Returns the point coordinates related to a new coordinate system
/// Does not change original point
/// </summary>
/// <param name="Point">Point to be returned in new coordinate system</param>
/// <param name="NewSystemCouterClockRotation">CounterClokWise Angle of rotation of the new coordinate system compared to the current, measured in radians</param>
/// <param name="NewSystemOrigin">Location of the new origin point in the current coordinate system</param>
/// <returns></returns>
public double[] ChangeCoordinateSystem(double[] Point, double NewSystemCouterClockRotation, double[] NewSystemOrigin)
{
//first adjust: fix that winform downwards increasing Y before applying the method
Point[1] = -Point[1];
NewSystemOrigin[1] = -NewSystemOrigin[1]
//end of first adjust
//original method
double[] Displacement = new double[2] { Point[0] - NewSystemOrigin[0], Point[1] - NewSystemOrigin[1] };
double[] Result = new double[2]
{
+ Displacement[0] * Math.Cos(NewSystemCouterClockRotation) + Displacement[1] * Math.Sin(NewSystemCouterClockRotation),
- Displacement[0] * Math.Sin(NewSystemCouterClockRotation) + Displacement[1] * Math.Cos(NewSystemCouterClockRotation)
};
//second adjust: reset Y of the result
Result[1] = - Result[1];
return Result;
}
But, if your two objects have different angles, you should be careful, the best way to do that is to check if all four corners of the first of the first rectangle are not inside the other object AND if the other object four corners are not inside the first as well.
Some algorythm to find out if a point is inside a polygon can be found here:
Point in polygon

Related

How System.Windows.Media.Media3D.Matrix3D work

It seems straight forward to define a function like this
/// <summary>
/// Build 3D transform matrix with image of unit vectors of axes, and the image of the origin
/// </summary>
/// <param name="xUnit">The image of x axis unit vector</param>
/// <param name="yUnit">The image of y axis unit vector</param>
/// <param name="zUnit">The image of z axis unit vector</param>
/// <param name="offset">The image of the origin</param>
/// <returns>The matrix</returns>
public static Matrix3D MatrixFromVectors(Vector3D xUnit, Vector3D yUnit, Vector3D zUnit, Vector3D offset)
{
var m = new Matrix3D(
xUnit.X, xUnit.Y, xUnit.Z, 0.0,
yUnit.X, yUnit.Y, yUnit.Z, 0.0,
zUnit.X, zUnit.Y, zUnit.Z, 0.0,
0, 0, 0, 1);
m.Translate(offset);
return m;
}
However the test code
...
var m = Geo.MatrixFromVectors(vx,vy,vz,new Vector3D(1,2,3));
var result = m.transform(new Vector3D(1,0,0)) //result: equal to vx
...
shows it does not use the offset at all. How to make it work?
The structures in the Media3D Namespace make a distinction between Vectors and Points. Vector3D is used to specify a position independent value in space (such as an Axis, Surface normal, Acceleration etc.), while Point3D is used to specify position.
Because Vectors are not suppsed to carry position Information Matrix3D.Transform(Vector3D) does not apply the offset. It only transforms the direction of the Vector.
If you pass a Point3D instead of a Vector3D to Matrix3D.Transform(Point3D) it works as expected:
...
var m = Geo.MatrixFromVectors(vx,vy,vz,new Vector3D(1,2,3));
var result = m.transform(new Point3D(0,0,0)) // result is 1,2,3
...

Get normal of a Point3D

I have set of points. I created strip triangles using these points.
I am using HelixToolkit to draw these rectangles. Function requires list of pointes (triangles will be made using triangle strip) and set of normal vectors. Now I need to calculate normal. What I thought that for each triangle there should be a normal. But function says that for every point there will be a normal. I used three points to calculate normal of a triangle, but how can I calculate normal of a point.
So if am using the example shown in the figure what will be normal of All points (A, B, C, D, E, F).
Here is the method which I am calling.
/// <summary>
/// Adds a triangle strip to the mesh.
/// </summary>
/// <param name="stripPositions">
/// The points of the triangle strip.
/// </param>
/// <param name="stripNormals">
/// The normal vectors of the triangle strip.
/// </param>
/// <param name="stripTextureCoordinates">
/// The texture coordinates of the triangle strip.
/// </param>
/// <remarks>
/// See http://en.wikipedia.org/wiki/Triangle_strip.
/// </remarks>
public void AddTriangleStrip(
IList<Point3D> stripPositions,
IList<Vector3D> stripNormals = null,
IList<Point> stripTextureCoordinates = null)
Here is what I have.
var points = new List<Point3D>();
// populate points.
// TODO: populate Normal for each point.
AddTriangleStrip(points, normal);
I used this method to calculate normal of a surface.
private static Vector3D CalculateNormal(Point3D firstPoint, Point3D secondPoint, Point3D thirdPoint)
{
var u = new Point3D(firstPoint.X - secondPoint.X,
firstPoint.Y - secondPoint.Y,
firstPoint.Z - secondPoint.Z);
var v = new Point3D(secondPoint.X - thirdPoint.X,
secondPoint.Y - thirdPoint.Y,
secondPoint.Z - thirdPoint.Z);
return new Vector3D(u.Y * v.Z - u.Z * v.Y, u.Z * v.X - u.X * v.Z, u.X * v.Y - u.Y * v.X);
}
There is no such concept like a normal of Point. Normal refers to a surface and not to a point, so I presume that we are talking here about average normal of all neighbour faces of a given point .
For this, you should know somehow from given point all connected to it faces.
For every face calculate its normal and make an average of them
Hope this helps.

Collision detection in XNA 3.1

I'm currently making a 3D car game using XNA 3.1. It is a taxi game. So my main vehicle encounters traffic vehicles during the game. I'm having problems with coding the collision detection among traffic vehicles and the main vehicle. I used the bounding box method instead of bounding sphere method because bounding spheres don't cover the vehicles properly.
Below is the code i used to achieve collision. Problem with it is when the vehicle turns left or right bounding box doesn't change according to that.
I wrote this code in the update method.
carWorld = Matrix.CreateScale(1f) * Matrix.CreateTranslation(vehicalClassObs[0].Position);
trafficWorld = Matrix.CreateScale(1f) * Matrix.CreateTranslation(carObject.Position);
BoundingBox b=CalculateBoundingBox(carO);
BoundingBox c=CalculateBoundingBox(car);
Vector3[] obb = new Vector3[8];
b.GetCorners(obb);
Vector3.Transform(obb, ref carWorld, obb);
BoundingBox worldAABB = BoundingBox.CreateFromPoints(obb);
Vector3[] occ=new Vector3[8];
c.GetCorners(occ);
Vector3.Transform(occ, ref trafficWorld, occ);
BoundingBox worldAACC = BoundingBox.CreateFromPoints(occ);
if (worldAABB.Intersects(worldAACC))
col = true;
else col = false;
Below is the CalculateBoundingBox method
public BoundingBox CalculateBoundingBox(Model m_model)
{
// Create variables to hold min and max xyz values for the model. Initialise them to extremes
Vector3 modelMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Vector3 modelMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
foreach (ModelMesh mesh in m_model.Meshes)
{
Matrix[] m_transforms = new Matrix[m_model.Bones.Count];
m_model.CopyAbsoluteBoneTransformsTo(m_transforms);
//Create variables to hold min and max xyz values for the mesh. Initialise them to extremes
Vector3 meshMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Vector3 meshMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
// There may be multiple parts in a mesh (different materials etc.) so loop through each
foreach (ModelMeshPart part in mesh.MeshParts)
{
// The stride is how big, in bytes, one vertex is in the vertex buffer
// We have to use this as we do not know the make up of the vertex
int stride = part.VertexDeclaration.GetVertexStrideSize(0);
byte[] vertexData = new byte[stride * part.NumVertices];
mesh.VertexBuffer.GetData(part.BaseVertex * stride, vertexData, 0, part.NumVertices, 1); // fixed 13/4/11
// Find minimum and maximum xyz values for this mesh part
// We know the position will always be the first 3 float values of the vertex data
Vector3 vertPosition=new Vector3();
for (int ndx = 0; ndx < vertexData.Length; ndx += stride)
{
vertPosition.X= BitConverter.ToSingle(vertexData, ndx);
vertPosition.Y = BitConverter.ToSingle(vertexData, ndx + sizeof(float));
vertPosition.Z= BitConverter.ToSingle(vertexData, ndx + sizeof(float)*2);
// update our running values from this vertex
meshMin = Vector3.Min(meshMin, vertPosition);
meshMax = Vector3.Max(meshMax, vertPosition);
}
}
// transform by mesh bone transforms
meshMin = Vector3.Transform(meshMin, m_transforms[mesh.ParentBone.Index]);
meshMax = Vector3.Transform(meshMax, m_transforms[mesh.ParentBone.Index]);
// Expand model extents by the ones from this mesh
modelMin = Vector3.Min(modelMin, meshMin);
modelMax = Vector3.Max(modelMax, meshMax);
}
// Create and return the model bounding box
return new BoundingBox(modelMin, modelMax);
}
If someone can help me to solve this problem it wil be very helpful. If there is a better way to achieve collision other than the way i used please let me know about that method.
You have a couple of options here. The easiest is to transform the vehicle's bounding box according to the vehicle's world transforms (no projection or view required here since you're not concerned about camera position when checking for collisions.)
Assuming you already have the vehicle's original bounding box,
/// <summary>
/// Transforms a bounding box for collision detection
/// </summary>
/// <param name="vehicleBounds">Original, object-centered bounding box that contains a car model</param>
/// <param name="vehicleWorldMatrix">Vehicle's world transformation matrix (does not include projection or view)</param>
/// <returns>An axis-aligned bounding box (AABB) that will com </returns>
protected BoundingBox TransformBoundingBox(BoundingBox vehicleBounds, Matrix vehicleWorldMatrix)
{
var vertices = vehicleBounds.GetCorners();
/// get a couple of vertices to hold the outer bounds of the transformed bounding box.
var minVertex = new Vector3(float.MaxValue);
var maxVertex = new Vector3(float.MinValue);
for(int i=0;i<vertices.Length;i++)
{
var transformedVertex = Vector3.Transform(vertices[i],vehicleWorldMatrix);
/// update min and max with the component-wise minimum of each transformed vertex
/// to find the outer limits fo teh transformed bounding box
minVertex = Vector3.Min(minVertex, transformedVertex);
maxVertex = Vector3.Max(maxVertex, transformedVertex);
}
var result = new BoundingBox(minVertex, maxVertex);
return result;
}
For each vehicle, use that method to create a temporary bounding box to use for collisions. Only test transformed bounding boxes against each other, and do not overwrite you're original bounding box as you'll need to recalculate this box from your source any time the vehicle moves.
If you're using a multi-mesh model, use BoundingBox.CreateMerged() to combine them to get a box that contains the entire model, or perform your collisions for each sub-mesh bounding box (though this can get expensive without using some sort of acceleration structure).
What I have been using is a very simple method which can fit almost any situation. Here it is:
//Create one of the matricies
//Vector3 loc = new Vector3(0, 0, 0); //Wherever the model is.
//Matrix world1 = Matrix.CreateTransform(loc);
private bool IsCollision(Model model1, Matrix world1, Model model2, Matrix world2)
{
for (int meshIndex1 = 0; meshIndex1 < model1.Meshes.Count; meshIndex1++)
{
BoundingSphere sphere1 = model1.Meshes[meshIndex1].BoundingSphere;
sphere1 = sphere1.Transform(world1);
for (int meshIndex2 = 0; meshIndex2 < model2.Meshes.Count; meshIndex2++)
{
BoundingSphere sphere2 = model2.Meshes[meshIndex2].BoundingSphere;
sphere2 = sphere2.Transform(world2);
if (sphere1.Intersects(sphere2))
return true;
}
}
return false;
}
You can change all the spheres to boxes, but this might work. Additionally, what I do is move the location one axis at a time (X axis then Y axis then Z axis). This creates smoother collision.

Collision checking on slopes

I'm working on a new game, and am trying to detect whether or not the player (on a slope) is colliding with a given mesh based off of their coordinates relative to the coordinates of the slope. I'm using this function, which doesn't seem to be working (the slope seems too small or something)
//Slopes
float slopeY = max.Y-min.Y;
float slopeZ = max.Z-min.Z;
float slopeX = max.X-min.X;
float angle = (float)Math.Atan(slopeZ/slopeY);
//Console.WriteLine(OpenTK.Math.Functions.RadiansToDegrees((float)Math.Atan(slopeZ/slopeY)).ToString()+" degrees incline");
slopeY = slopeY/slopeZ;
float slopeZX = slopeY/slopeX;
//End slopes
float surfaceposX = max.X-coord.X;
float surfaceposY = max.Y-coord.Y;
float surfaceposZ = min.Z-coord.Z;
min-=sval;
max+=sval;
//Surface coords
//End surface coords
//Y SHOULD = mx+b, where M = slope and X = surfacepos, and B = surfaceposZ
if(coord.X<max.X& coord.X>min.X&coord.Y>min.Y&coord.Y<max.Y&coord.Z>min.Z&coord.Z<max.Z) {
if(slopeY !=0) {
Console.WriteLine("Slope = "+slopeY.ToString()+"SlopeZX="+slopeZX.ToString()+" surfaceposZ="+surfaceposZ.ToString());
Console.WriteLine(surfaceposY-(surfaceposY*slopeY));
//System.Threading.Thread.Sleep(40000);
if(surfaceposY-(surfaceposZ*slopeY)<3 || surfaceposY-(surfaceposX*slopeZX)<3) {
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return false;
}
Any suggestions?
Sample output:
59.86697
6.225558 2761.331
68.3019 degrees incline
59.86698,46.12445
59.86698
6.225558 2761.332
0 degrees incline
EDIT: Partially fixed the problem. Slope detection works, but now I can walk through walls???
//Slopes
float slopeY = max.Y-min.Y;
float slopeZ = max.Z-min.Z;
float slopeX = max.X-min.X;
float angle = (float)Math.Atan(slopeZ/slopeY);
//Console.WriteLine(OpenTK.Math.Functions.RadiansToDegrees((float)Math.Atan(slopeZ/slopeY)).ToString()+" degrees incline");
slopeY = slopeY/slopeZ;
float slopey = slopeY+1/slopeZ;
float slopeZX = slopeY/slopeX;
//End slopes
float surfaceposX = min.X-coord.X;
float surfaceposY = max.Y-coord.Y;
float surfaceposZ = min.Z-coord.Z;
min-=sval;
max+=sval;
//Surface coords
//End surface coords
//Y SHOULD = mx+b, where M = slope and X = surfacepos, and B = surfaceposZ
if(coord.X<max.X& coord.X>min.X&coord.Y>min.Y&coord.Y<max.Y&coord.Z>min.Z&coord.Z<max.Z) {
if(slopeY !=0) {
Console.WriteLine("Slope = "+slopeY.ToString()+"SlopeZX="+slopeZX.ToString()+" surfaceposZ="+surfaceposZ.ToString());
Console.WriteLine(surfaceposY-(surfaceposY*slopeY));
//System.Threading.Thread.Sleep(40000);
surfaceposZ = Math.Abs(surfaceposZ);
if(surfaceposY>(surfaceposZ*slopeY) & surfaceposY-2<(surfaceposZ*slopeY) || surfaceposY>(surfaceposX*slopeZX) & surfaceposY-2<(surfaceposX*slopeZX)) {
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return false;
}
Have you considered implementing a BSP tree? Even if you work out the bugs with the code you're using now, it'll be dog slow with a mesh of any decent size/complexity. A BSP or quadtree will go a long way towards simplifying your code and improving performance, and they're very easy to implement.
Edit
Here's a link to a nice BSP tutorial and overview.
If you're only concerned with terrain (no vertical walls, doors, etc), a quadtree might be more appropriate:
Here's a nice quadtree tutorial at gamedev.net.
Both of these algorithms are intended to divide your geometry into a tree to make searching easier. In your case, you're searching for polygons for collision purposes. To build a BSP tree (very briefly):
Define a structure for the nodes in the tree:
public class BspNode
{
public List<Vector3> Vertices { get; set; }
// plane equation coefficients
float A, B, C, D;
BspNode front;
BspNode back;
public BspNode(Vector3 v1, Vector3 v2, Vector3 v3)
{
Vertices = new List<Vector3>();
Vertices.AddRange(new[] { v1, v2, v3 });
GeneratePlaneEquationCoefficients();
}
void GeneratePlaneEquationCoefficients()
{
// derive the plane equation coefficients A,B,C,D from the input vertex list.
}
bool IsInFront(Vector3 point)
{
bool pointIsInFront=true;
// substitute point.x/y/z into the plane equation and compare the result to D
// to determine if the point is in front of or behind the partition plane.
if (pointIsInFront && front!=null)
{
// POINT is in front of this node's plane, so check it against the front list.
pointIsInFront = front.IsInFront(point);
}
else if (!pointIsInFront && back != null)
{
// POINT is behind this plane, so check it against the back list.
pointIsInFront = back.IsInFront(point);
}
/// either POINT is in front and there are no front children,
/// or POINT is in back and there are no back children.
/// Either way, recursion terminates here.
return pointIsInFront;
}
/// <summary>
/// determines if the line segment defined by v1 and v2 intersects any geometry in the tree.
/// </summary>
/// <param name="v1">vertex that defines the start of the ray</param>
/// <param name="v2">vertex that defines the end of the ray</param>
/// <returns>true if the ray collides with the mesh</returns>
bool SplitsRay(Vector3 v1, Vector3 v2)
{
var v1IsInFront = IsInFront(v1);
var v2IsInFront = IsInFront(v2);
var result = v1IsInFront!=v2IsInFront;
if (!result)
{
/// both vertices are on the same side of the plane,
/// so this node doesn't split anything. Check it's children.
if (v1IsInFront && front != null)
result = front.SplitsRay(v1, v2);
else if (!v1IsInFront && back != null)
result = back.SplitsRay(v1, v2);
}
else
{
/// this plane splits the ray, but the intersection point may not be within the face boundaries.
/// 1. calculate the intersection of the plane and the ray : intersection
/// 2. create two new line segments: v1->intersection and intersection->v2
/// 3. Recursively check those two segments against the rest of the tree.
var intersection = new Vector3();
/// insert code to magically calculate the intersection here.
var frontSegmentSplits = false;
var backSegmentSplits = false;
if (front!=null)
{
if (v1IsInFront) frontSegmentSplits=front.SplitsRay(v1,intersection);
else if (v2IsInFront) frontSegmentSplits=front.SplitsRay(v2,intersection);
}
if (back!=null)
{
if (!v1IsInFront) backSegmentSplits=back.SplitsRay(v1,intersection);
else if (!v2IsInFront) backSegmentSplits=back.SplitsRay(v2,intersection);
}
result = frontSegmentSplits || backSegmentSplits;
}
return result;
}
}
Pick a "partition" plane (face) from your mesh that roughly divides the rest of the mesh in two. This is a lot easier to do with complex geometry as fully convex items (spheres and the like) tend to wind up looking like lists instead of trees.
Create a new BspNode instance from the vertices that define the partition plane.
Sort the remaining faces into two lists - one that is in front of the partition plane, and one containing those faces that are behind.
Recurse to step 2 until no more nodes are in the list.
When checking for collisions, you have two options.
Single-point: check the coordinates that the character or object is moving to against the tree by calling your root node's .IsInFront(moveDestination) If the method returns false, the target point is "inside" the mesh, and you've collided. If the method returns true, the target point is "outside" the mesh, and no collision has occurred.
Ray intersection. This one gets a little tricky. Call the root node's .SplitsRay() method with the object's current position and it's target position. If the methods returns true, moving between the two positions will transition through the mesh. This is a superior (though more complex) check because it will catch edge cases, such as when the desired movement would take an object completely through an object in one step.
I just threw that sample code together quickly; it's incomplete and probably won't even compile, but it should get you going in the right direction.
Another nice thing about the BSP: Using the .SplitsRay() method, you can determine if one point on a map is visible from another point. Some games use this to determine if NPCs/AIs can see each other or real players. You could use a slight modification of that to determine if they can hear each other walking, etc.
This may seem a lot more complicated than your original approach, but it's ultimately far more powerful and flexible. It's worth your time to investigate.

Projecting a 3D point to a 2D screen coordinate

Based on information in Chapter 7 of 3D Programming For Windows (Charles Petzold), I've attempted to write as helper function that projects a Point3D to a standard 2D Point that contains the corresponding screen coordinates (x,y):
public Point Point3DToScreen2D(Point3D point3D,Viewport3D viewPort )
{
double screenX = 0d, screenY = 0d;
// Camera is defined in XAML as:
// <Viewport3D.Camera>
// <PerspectiveCamera Position="0,0,800" LookDirection="0,0,-1" />
// </Viewport3D.Camera>
PerspectiveCamera cam = viewPort.Camera as PerspectiveCamera;
// Translate input point using camera position
double inputX = point3D.X - cam.Position.X;
double inputY = point3D.Y - cam.Position.Y;
double inputZ = point3D.Z - cam.Position.Z;
double aspectRatio = viewPort.ActualWidth / viewPort.ActualHeight;
// Apply projection to X and Y
screenX = inputX / (-inputZ * Math.Tan(cam.FieldOfView / 2));
screenY = (inputY * aspectRatio) / (-inputZ * Math.Tan(cam.FieldOfView / 2));
// Convert to screen coordinates
screenX = screenX * viewPort.ActualWidth;
screenY = screenY * viewPort.ActualHeight;
// Additional, currently unused, projection scaling factors
/*
double xScale = 1 / Math.Tan(Math.PI * cam.FieldOfView / 360);
double yScale = aspectRatio * xScale;
double zFar = cam.FarPlaneDistance;
double zNear = cam.NearPlaneDistance;
double zScale = zFar == Double.PositiveInfinity ? -1 : zFar / (zNear - zFar);
double zOffset = zNear * zScale;
*/
return new Point(screenX, screenY);
}
On testing however this function returns incorrect screen coordinates (checked by comparing 2D mouse coordinates against a simple 3D shape). Due to my lack of 3D programming experience I am confused as to why.
The block commented section contains scaling calculations that may be essential, however I am not sure how, and the book continues with the MatrixCamera using XAML. Initially I just want to get a basic calculation working regardless of how inefficient it may be compared to Matrices.
Can anyone advise what needs to be added or changed?
I've created and succesfully tested a working method by using the 3DUtils Codeplex source library.
The real work is performed in the TryWorldToViewportTransform() method from 3DUtils. This method will not work without it (see the above link).
Very useful information was also found in the article by Eric Sink: Auto-Zoom.
NB. There may be more reliable/efficient approaches, if so please add them as an answer. In the meantime this is good enough for my needs.
/// <summary>
/// Takes a 3D point and returns the corresponding 2D point (X,Y) within the viewport.
/// Requires the 3DUtils project available at http://www.codeplex.com/Wiki/View.aspx?ProjectName=3DTools
/// </summary>
/// <param name="point3D">A point in 3D space</param>
/// <param name="viewPort">An instance of Viewport3D</param>
/// <returns>The corresponding 2D point or null if it could not be calculated</returns>
public Point? Point3DToScreen2D(Point3D point3D, Viewport3D viewPort)
{
bool bOK = false;
// We need a Viewport3DVisual but we only have a Viewport3D.
Viewport3DVisual vpv =VisualTreeHelper.GetParent(viewPort.Children[0]) as Viewport3DVisual;
// Get the world to viewport transform matrix
Matrix3D m = MathUtils.TryWorldToViewportTransform(vpv, out bOK);
if (bOK)
{
// Transform the 3D point to 2D
Point3D transformedPoint = m.Transform(point3D);
Point screen2DPoint = new Point(transformedPoint.X, transformedPoint.Y);
return new Nullable<Point>(screen2DPoint);
}
else
{
return null;
}
}
Since Windows coordinates are z into the screen (x cross y), I would use something like
screenY = viewPort.ActualHeight * (1 - screenY);
instead of
screenY = screenY * viewPort.ActualHeight;
to correct screenY to accomodate Windows.
Alternately, you could use OpenGL. When you set the viewport x/y/z range, you could leave it in "native" units, and let OpenGL convert to screen coordinates.
Edit:
Since your origin is the center. I would try
screenX = viewPort.ActualWidth * (screenX + 1.0) / 2.0
screenY = viewPort.ActualHeight * (1.0 - ((screenY + 1.0) / 2.0))
The screen + 1.0 converts from [-1.0, 1.0] to [0.0, 2.0]. At which point, you divide by 2.0 to get [0.0, 1.0] for the multiply. To account for Windows y being flipped from Cartesian y, you convert from [1.0, 0.0] (upper left to lower left), to [0.0, 1.0] (upper to lower) by subtracting the previous screen from 1.0. Then, you can scale to the ActualHeight.
This doesn't address the algoritm in question but it may be useful for peple coming across this question (as I did).
In .NET 3.5 you can use Visual3D.TransformToAncestor(Visual ancestor). I use this to draw a wireframe on a canvas over my 3D viewport:
void CompositionTarget_Rendering(object sender, EventArgs e)
{
UpdateWireframe();
}
void UpdateWireframe()
{
GeometryModel3D model = cube.Content as GeometryModel3D;
canvas.Children.Clear();
if (model != null)
{
GeneralTransform3DTo2D transform = cube.TransformToAncestor(viewport);
MeshGeometry3D geometry = model.Geometry as MeshGeometry3D;
for (int i = 0; i < geometry.TriangleIndices.Count;)
{
Polygon p = new Polygon();
p.Stroke = Brushes.Blue;
p.StrokeThickness = 0.25;
p.Points.Add(transform.Transform(geometry.Positions[geometry.TriangleIndices[i++]]));
p.Points.Add(transform.Transform(geometry.Positions[geometry.TriangleIndices[i++]]));
p.Points.Add(transform.Transform(geometry.Positions[geometry.TriangleIndices[i++]]));
canvas.Children.Add(p);
}
}
}
This also takes into account any transforms on the model etc.
See also: http://blogs.msdn.com/wpf3d/archive/2009/05/13/transforming-bounds.aspx
It's not clear what you are trying to achieve with aspectRatio coeff. If the point is on the edge of field of view, then it should be on the edge of screen, but if aspectRatio!=1 it isn't. Try setting aspectRatio=1 and make window square. Are the coordinates still incorrect?
ActualWidth and ActualHeight seem to be half of the window size really, so screenX will be [-ActualWidth; ActualWidth], but not [0; ActualWidth]. Is that what you want?
screenX and screenY should be getting computed relative to screen center ...
I don't see a correction for the fact that when drawing using the Windows API, the origin is in the upper left corner of the screen. I am assuming that your coordinate system is
y
|
|
+------x
Also, is your coordinate system assuming origin in the center, per Scott's question, or is it in the lower left corner?
But, the Windows screen API is
+-------x
|
|
|
y
You would need the coordinate transform to go from classic Cartesian to Windows.

Categories

Resources