Barycentric coordinates doesn't always work(3d) - c++

I have a 3d box made of 12 triangles centered at the origin. I launch a ray from the origin to random directions, the goal is to get the face that intersects with the ray.
I do this by searching all the ray/plane intersections and then determining the face their on(if any) with the Barycentric coordinates(u,v,w).
this works correctly only half the time, and generally yields unexpected results:
float triangleAREA(vec3 a, vec3 b, vec3 c)
{
return(length(cross(b-a, c-a)) / 2);
}
int isINtriangle(vec3 a, vec3 b, vec3 c, vec3 p)
{
float total_area = triangleAREA(a, b, c);
float u = triangleAREA(a, b, p);
float v = triangleAREA(a, c, p);
float w = triangleAREA(c, b, p);
if (u + v + w != total_area)
return Ray::_NOintersection;
else
{
if (u == 0 || v == 0 || w == 0)
return Ray::_Onedge_OnVertex;
else
return Ray::_INtriangle;
}
}
this is how I check if the intersection is in the same direction as the ray:
vec3 a = normalize(ray_direction); vec3 b = normalize(intersect);
if (
a.x > b.x - 1 && a.x < b.x + 1 &&
a.z > b.z - 1 && a.z < b.z + 1 &&
a.y > b.y - 1 && a.y < b.y + 1
)
this is all new to me, any help would be awesome !

This code
if (u + v + w != total_area)
is unreliable for floats. Floats don’t work same way as integers, tests for the exact equality rarely make any sense.
You should do something completely different instead. Here’s one method. The code is untested but conceptually it should work, I did similar things many times.
#include <assert.h>
// 0 when [0,p] ray goes through [0,t1,t2] plane.
// Otherwise, the sign tells relative orientation of the ray and the plane.
inline float crossDot( vec3 t1, vec3 t2, vec3 p )
{
// Depending on winding order of triangles, and coordinate system (right versus left handed),
// you may need to flip the cross() arguments
return dot( cross( t1, t2 ), p );
}
// The triangle is [a, b, c], the points must have consistent winding,
// i.e. when viewed from [0,0,0] the order must be either clockwise or counterclockwise,
// for all triangles of your mesh.
// p does not need to be normalized, length is ignored, only direction is used.
int testRayTriangle( vec3 a, vec3 b, vec3 c, vec3 p )
{
// If this assert fails because zero, you have a zero-area triangle, or a triangle that goes through [0,0,0].
// If this assert fails because negative, you need to flip cross() arguments, or fix winding order in the mesh.
assert( crossDot( a, b, c ) > 0 );
const float e1 = crossDot( a, b, p );
const float e2 = crossDot( b, c, p );
const float e3 = crossDot( c, a, p );
if( e1 < 0 || e2 < 0 || e3 < 0 )
return Ray::_NOintersection; // The ray points outwards in relation to some side plane
if( e1 > 0 && e2 > 0 && e3 > 0 )
return Ray::_INtriangle; // The ray points inwards in relation to all 3 side planes
// The ray goes through a side plane
return Ray::_Onedge_OnVertex;
}
The above code assumes eventually you gonna have more complicated meshes than your 12-triangles unit cube. If all you need is unit cube, find longest absolute dimension of your random vector, this + sign of that coordinate will tell you which of the 6 cube planes it gonna intersect. If there’s no longest dimension e.g. your ray direction is [1,1,0] then the ray goes through an edge or vertex of the cube. Otherwise, test 2 other coordinates to find which of the 2 triangles it intersects.

Related

Ray-bounded plane intersection

I'm trying to write a ray tracer in my freetime. Currently trying to do ray - bounded plane intersections.
My program is already working with infinite planes. I'm trying to work out the math for non-infinite planes. Tried to google, but all of the resources talk only about infinite planes.
My plane has a corner point (called position), from which two vectors (u and v) extend (their length correspond to the length of the sides). The ray has an origin and a direction.
First I calculate the intersection point with an infinite plane with the formula
t = normal * (position - origin) / (normal * direction)
The normal is calculated as a cross product of u and v.
Then with the formula
origin + direction * t
I get the intersection point itself.
The next step is checking if this point is in the bounds of the rectangle, and this is where I'm having trouble.
My idea was to get the relative vector intersection - position that is extending from the corner of the plane to the intersection point, then transform it to a new basis of u, normal and v then check if the lengths of the transformed vectors are shorter than the u and v vectors.
bool BoundedPlane::intersect(const Vec3f &origin, const Vec3f &direction, float &t) const {
t = normal * (position - origin) / (normal * direction);
Vec3f relative = (origin + direction * t) - position;
Mat3f transform{
Vec3f(u.x, normal.x, v.x),
Vec3f(u.y, normal.y, v.y),
Vec3f(u.z, normal.z, v.z)
};
Vec3f local = transform.mul(relative);
return t > 0 && local.x >= 0 && local.x <= u.x && local.z <= 0 && local.z <= v.z;
}
At the end I check if t is larger than 0, meaning the intersection is in front of the camera, and if the lengths of the vectors are inside the bounds. This gives me a weird line:
.
The plane should appear below the spheres like this:
(this used manual checking to see if it appears correctly if the numbers are right).
I'm not sure what I'm doing wrong, and if there's an easier way to check the bounds. Thanks in advance.
Edit1:
I moved the transformation matrix calculations into the constructor, so now the intersection test is:
bool BoundedPlane::intersect(const Vec3f &origin, const Vec3f &direction, float &t) const {
if (!InfinitePlane::intersect(origin, direction, t)) {
return false;
}
Vec3f local = transform.mul((origin + direction * t) - position);
return local.x >= 0 && local.x <= 1 && local.z >= 0 && local.z <= 1;
}
The transform member is the inverse of the transformation matrix.
Could I suggest another approach? Consider the frame with origin
position and basis vectors
u = { u.x, u.y, u.z }
v = { v.x, v.y, v.z }
direction = { direction.x, direction.y, direction.z}
Step 1: Form the matrix
M = {
{u.x, v.x, direction.x},
{u.y, v.y, direction.y},
{u.z, v.z, direction.z}
}
Step 2: Calculate the vector w, which is a solution to the 3 x 3 system of liner equations
M * w = origin - position, i.e.
w = inverse(M) * (origin - position);
Make sure that direction is not coplanar with u, v, otherwise there is no intersection and inverse(M) does not exist.
Step 3: if 0.0 <= w.x && w.x <= 1.0 && 0.0 <= w.y && w.y <= 1.0 then the line intersects the parallelogram spanned by the vectors u, v and the point of intersection is
w0 = { w.x, w.y , 0 };
intersection = position + M * w0;
else, the line does not intersect the parallelogram spanned by the vectors u, v
The idea of this algorithm is to consider the (non-orthonormal) frame position, u, v, direction. Then the matrix M changes everything in the coordinates of this new frame. In this frame, the line is vertical, parallel to the "z-"axis, the point origin has coordinates w, and the vertical line through w intersects the plane at w0.
Edit 1: Here is a templet formula for the inverse of a 3x3 matrix:
If original matrix M is
a b c
d e f
g h i
inverse is
(1 / det(M)) * {
{e*i - f*h, c*h - b*i, b*f - c*e},
{f*g - d*i, a*i - c*g, c*d - a*f},
{d*h - e*g, b*g - a*h, a*e - b*d},
}
where
det(M) = a*(e*i - f*h) + b*(f*g - d*i) + c*(d*h - e*h)
is the determinant of M.
So the inversion algorithm can be as follows:
Given
M = {
{a, b, c},
{d, e, f},
{g, h, i},
}
Calculate
inv_M = {
{e*i - f*h, c*h - b*i, b*f - c*e},
{f*g - d*i, a*i - c*g, c*d - a*f},
{d*h - e*g, b*g - a*h, a*e - b*d},
};
Calculate
det_M = a*inv_M[1][1] + b*inv_M[2][1] + c*inv_M[3][1];
Return inverse matrix of M
inv_M = (1/det_M) * inv_M;
Edit 2: Let's try another approach in order to speed things up.
Step 1: For each plane, determined by the point position and the two vectors u and v, precompute the following quatntities:
normal = cross(u, v);
u_dot_u = dot(u, u);
u_dot_v = dot(u, v);
v_dot_v = dot(v, v); // all these need to be computed only once for the u and v vectors
det = u_dot_u * v_dot_v - u_dot_v * u_dot_v; // again only once per u and v
Step 2: Now, for a given line with point origin and direction direction, as before, calculate the intersection point int_point with the plane spanned by u and v:
t = dot(normal, position - origin) / dot(normal, direction);
int_point = origin + t * direction;
rhs = int_point - position;
Step 3: Calcualte
u_dot_rhs = dot(u, rhs);
v_dot_rhs = dot(v, rhs);
w1 = (v_dot_v * u_dot_rhs - u_dot_v * v_dot_rhs) / det;
w2 = (- u_dot_v * u_dot_rhs + u_dot_u * v_dot_rhs) / det;
Step 4:
if (0 < = w1 && w1 <= 1 && 0 < = w2 && w2 <= 1 ){
int_point is in the parallelogram;
}
else{
int_point is not in the parallelogram;
}
So what I am doing here is basically finding the intersection point of the line origin, direction with the plane given by position, u, v and restricting myself to the plane, which allows me to work in 2D rather than 3D. I am representing
int_point = position + w1 * u + w2 * v;
rhs = int_point - position = w1 * u + w2 * v
and finding w1 and w2 by dot-multiplying of this vector expression with the basis vectors u and v, which results in a 2x2 linear system, which I am solving directly.

Is it possible generate normal map from heightmap texture from math point of view?

My view is that you can not generate normal map only from height map texture?
Am I right or not?
Math Arguments:
Assume that surface is given a continuous bijection from
S = [0,1]
T = [0,1]
Let's call SxT as image space.
It can be proved from differentional geometry that normal to that parametric surface is
If assume that mapping from SxT image space to geometric euclidian space is very simple then we can retrive:
Then you can calculate such partial derivatives with some difference scheme.
We came to that simple formula, only with bold suggestion and this suggestion is absolutely not true.
Sample of the problem from graphics.
Let assume we have triangle in geometric eclidian space with 3 vertices.
Terms are:
normalmap --
it is normal for point with (u,v,1-u-v) barycentric coordinates fetched from (u,v) from suitable 2d texture, and it is in local coord. system relative to triangle.
heihtmap --
it is geometric offset for point with (u,v,1-u-v) barycentric coordinates in normal direction relative to triangle localspace fetched from (u,v) from suitable 2d texture.
During building normalmap we absolutely ignore how heightmap is distributed near (u,v,1-u-v) eculidian point. And we retrive only some approximation of normal map.
Ohh, looks like my comment was too brief.
It's easier to write a full answer with code to describe the method.
I'm going to use a pseudocode mix of C++ and GLSL.
constexpr int width = 32, height = 32;
constexpr float height_scale = 16.0f; // Change if necessary.
float hmap[W][H] = {...};
float normalmap[W][H];
vec3 GetPoint(ivec2 a)
{
a.x %= W;
a.y %= H;
return {a.x, a.y, hmap[a.x][a.y] * height_scale};
}
vec3 GetNormal(ivec2 a, bool loop_hmap)
{
vec3 o = GetPoint(a),
a = GetPoint({a.x + 1, a.y}),
b = GetPoint({a.x, a.y + 1}),
c = GetPoint({a.x - 1, a.y}),
d = GetPoint({a.x, a.y - 1});
vec3 n1 = normalize(cross(a-o, b-o));
vec3 n2 = normalize(cross(b-o, c-o));
vec3 n3 = normalize(cross(c-o, d-o));
vec3 n4 = normalize(cross(d-o, a-o));
if (loop_hmap)
return normalize(n1+n2+n3+n4);
else
{
vec3 sum = {0,0,0};
bool b1 = (a.x+1 >= 0 && a.y >= 0 && a.x+1 < W && a.y < H);
bool b2 = (a.x >= 0 && a.y+1 >= 0 && a.x < W && a.y+1 < H);
bool b3 = (a.x-1 >= 0 && a.y >= 0 && a.x-1 < W && a.y < H);
bool b4 = (a.x >= 0 && a.y-1 >= 0 && a.x < W && a.y-1 < H);
if (b1 && b2) sum += n1;
if (b2 && b3) sum += n2;
if (b3 && b4) sum += n3;
if (b4 && b1) sum += n4;
return normalize(sum);
}
}
int main()
{
for (int i = 0; i < H; i++)
for (int j = 0; j < W; j++)
normalmap[j][i] = GetNormal(j, i, 0);
}
loop_hmap argument of GetNormal() changes how the function computes normals for edge pixels. 1 should be used for tiled textures, like sand and water. 0 should be used for nontiled textures, like items, mobs, trees.
For me my own initial question is invalid and it has a bug!!!
I – original parametric surface with domain as cartesian product of [0,1] and range of it as euclidean space
II - normal to original surface
III - modified original surface with heightmap
IV - normal map which we want to receive with even ignoring geometric modification of the surface by “III”
Final step IV includes a lot of stuff to differentiate: H(s,t) and original definition of the function...I don't perform futher analytic of that equations...But as for me you can't generate normalmap only from (heightmap)...
P.S. To perform futher analytics if you want to do it retrive *.docx file from that place https://yadi.sk/d/Qqx-jO1Ugo3uL As I know it impossible to convert formulas in ms word to latex, but in any case please use it asa draft.

Problems with a simple raytracer in c++

What it does is basically checking for collisions against an array of triangles and drawing an image based on the color of the triangle it hits. I think my problem lies in the collision detection. Code here:
for (int i = 0; i < triangles.size(); i++){
vec3 v0 = triangles[i].v0;
vec3 v1 = triangles[i].v1;
vec3 v2 = triangles[i].v2;
vec3 e1 = v1 - v0;
vec3 e2 = v2 - v0;
vec3 b = start - v0;
mat3 A(-dir, e1, e2);
vec3 x = glm::inverse(A) * b;
if (x.x > 0 && x.y > 0 && (x.x + x.y < 1) && (x.z - start.z>= 0)){
return true;
}
}
...where "dir" is the direction of the ray coming from the camera, calculated as "x - SCREEN_WIDTH / 2, y - SCREEN_HEIGHT / 2, focalLength". SCREEN_WIDTH, SCREEN_HEIGHT and focalLength are constants. Start is the position of the camera, set to 0,0,0.
What I'm not sure about is what x really is and what I should check for before returning true. "x.x > 0 && x.y > 0 && (x.x + x.y < 1)" is supposed to check if the ray hits not only on the same plane but actually inside the triangle, and the last part ("x.z - start.z>= 0", the one I'm least sure about), if the collision happened in front of the camera.
I get images, but no matter how much I try it's never right. It's supposed to be a classic TestModel of a room with different colored walls and two shapes in it. The closest I think I've been is getting four of five walls right, with the far one missing and a part of one of the shapes on the other side of it.
I'm not familiar with the matrix formulation for triangle intersection - it sounds quite expensive.
My own code is below, where my e1 and e2 are equivalent to yours - i.e. they represent the edge vectors from v0 to v1 and v2 respectively:
// NB: triangles are assumed to be in world space
vector3 pvec = vector3::cross(ray.direction(), e2);
double det = e1.dot(pvec);
if (::fabs(det) < math::epsilon) return 0;
double invDet = 1.0 / det;
vector3 tvec(p0, ray.origin());
double u = tvec.dot(pvec) * invDet;
if (u < 0 || u > 1) return 0;
vector3 qvec = vector3::cross(tvec, e1);
double v = ray.direction().dot(qvec) * invDet;
if (v < 0 || u + v > 1) return 0;
double t = e2.dot(qvec) * invDet;
if (t > math::epsilon) { // avoid self intersection
// hit found at distance "t"
}
I suspect the problem is in your calculation of the ray vector, which should be normalised.

How to do ray plane intersection?

How do I calculate the intersection between a ray and a plane?
Code
This produces the wrong results.
float denom = normal.dot(ray.direction);
if (denom > 0)
{
float t = -((center - ray.origin).dot(normal)) / denom;
if (t >= 0)
{
rec.tHit = t;
rec.anyHit = true;
computeSurfaceHitFields(ray, rec);
return true;
}
}
Parameters
ray represents the ray object.
ray.direction is the direction vector.
ray.origin is the origin vector.
rec represents the result object.
rec.tHit is the value of the hit.
rec.anyHit is a boolean.
My function has access to the plane:
center and normal defines the plane
As wonce commented, you want to also allow the denominator to be negative, otherwise you will miss intersections with the front face of your plane. However, you still want a test to avoid a division by zero, which would indicate the ray being parallel to the plane. You also have a superfluous negation in your computation of t. Overall, it should look like this:
float denom = normal.dot(ray.direction);
if (abs(denom) > 0.0001f) // your favorite epsilon
{
float t = (center - ray.origin).dot(normal) / denom;
if (t >= 0) return true; // you might want to allow an epsilon here too
}
return false;
First consider the math of the ray-plane intersection:
In general one intersects the parametric form of the ray, with the implicit form of the geometry.
So given a ray of the form x = a * t + a0, y = b * t + b0, z = c * t + c0;
and a plane of the form: A x * B y * C z + D = 0;
now substitute the x, y and z ray equations into the plane equation and you will get a polynomial in t. you then solve that polynomial for the real values of t. With those values of t you can back substitute into the ray equation to get the real values of x, y and z.
Here it is in Maxima:
Note that the answer looks like the quotient of two dot products!
The normal to a plane is the first three coefficients of the plane equation A, B, and C.
You still need D to uniquely determine the plane.
Then you code that up in the language of your choice like so:
Point3D intersectRayPlane(Ray ray, Plane plane)
{
Point3D point3D;
// Do the dot products and find t > epsilon that provides intersection.
return (point3D);
}
Math
Define:
Let the ray be given parametrically by q = p + t*v for initial point p and direction vector v for t >= 0.
Let the plane be the set of points r satisfying the equation dot(n, r) + d = 0 for normal vector n = (a, b, c) and constant d. Fully expanded, the plane equation may also be written in the familiar form ax + by + cz + d = 0.
The ray-plane intersection occurs when q satisfies the plane equation. Substituting, we have:
d = -dot(n, q)
= -dot(n, p + t * v)
= -dot(n, p) + t * dot(n, v)
Rearranging:
t = -(dot(n, p) + d) / dot(n, v)
This value of t can be used to determine the intersection by plugging it back into p + t*v.
Example implementation
std::optional<vec3> intersectRayWithPlane(
vec3 p, vec3 v, // ray
vec3 n, float d // plane
) {
float denom = dot(n, v);
// Prevent divide by zero:
if (abs(denom) <= 1e-4f)
return std::nullopt;
// If you want to ensure the ray reflects off only
// the "top" half of the plane, use this instead:
//
// if (-denom <= 1e-4f)
// return std::nullopt;
float t = -(dot(n, p) + d) / dot(n, v);
// Use pointy end of the ray.
// It is technically correct to compare t < 0,
// but that may be undesirable in a raytracer.
if (t <= 1e-4)
return std::nullopt;
return p + t * v;
}
implementation of vwvan's answer
Vector3 Intersect(Vector3 planeP, Vector3 planeN, Vector3 rayP, Vector3 rayD)
{
var d = Vector3.Dot(planeP, -planeN);
var t = -(d + Vector3.Dot(rayP, planeN)) / Vector3.Dot(rayD, planeN);
return rayP + t * rayD;
}

Draw arbitrary plane from plane equation, OpenGL

I have a plane defined by the standard plane equation a*x + b*y + c*z + d = 0, which I would like to be able to draw using OpenGL. How can I derive the four points needed to draw it as a quadrilateral in 3D space?
My plane type is defined as:
struct Plane {
float x,y,z; // plane normal
float d;
};
void DrawPlane(const Plane & p)
{
???
}
EDIT:
So, rethinking the question, what I actually wanted was to draw a discreet representation of a plane in 3D space, not an infinite plane.
Base on the answer provided by #a.lasram, I have produced this implementation, which doest just that:
void DrawPlane(const Vector3 & center, const Vector3 & planeNormal, float planeScale, float normalVecScale, const fColorRGBA & planeColor, const fColorRGBA & normalVecColor)
{
Vector3 tangent, bitangent;
OrthogonalBasis(planeNormal, tangent, bitangent);
const Vector3 v1(center - (tangent * planeScale) - (bitangent * planeScale));
const Vector3 v2(center + (tangent * planeScale) - (bitangent * planeScale));
const Vector3 v3(center + (tangent * planeScale) + (bitangent * planeScale));
const Vector3 v4(center - (tangent * planeScale) + (bitangent * planeScale));
// Draw wireframe plane quadrilateral:
DrawLine(v1, v2, planeColor);
DrawLine(v2, v3, planeColor);
DrawLine(v3, v4, planeColor);
DrawLine(v4, v1, planeColor);
// And a line depicting the plane normal:
const Vector3 pvn(
(center[0] + planeNormal[0] * normalVecScale),
(center[1] + planeNormal[1] * normalVecScale),
(center[2] + planeNormal[2] * normalVecScale)
);
DrawLine(center, pvn, normalVecColor);
}
Where OrthogonalBasis() computes the tangent and bi-tangent from the plane normal.
To see the plane as if it's infinite you can find 4 quad vertices so that the clipped quad and the clipped infinite plane form the same polygon. Example:
Sample 2 random points P1 and P2 on the plane such as P1 != P2.
Deduce a tangent t and bi-tangent b as
t = normalize(P2-P1); // get a normalized tangent
b = cross(t, n); // the bi-tangent is the cross product of the tangent and the normal
Compute the bounding sphere of the view frustum. The sphere would have a diameter D (if this step seems difficult, just set D to a large enough value such as the corresponding sphere encompasses the frustum).
Get the 4 quad vertices v1 , v2 , v3 and v4 (CCW or CW depending on the choice of P1 and P2):
v1 = P1 - t*D - b*D;
v2 = P1 + t*D - b*D;
v3 = P1 + t*D + b*D;
v4 = P1 - t*D + b*D;
One possibility (possibly not the cleanest) is to get the orthogonal vectors aligned to the plane and then choose points from there.
P1 = < x, y, z >
t1 = random non-zero, non-co-linear vector with P1.
P2 = norm(P1 cross t1)
P3 = norm(P1 cross P2)
Now all points in the desired plane are defined as a starting point plus a linear combination of P2 and P3. This way you can get as many points as desired for your geometry.
Note: the starting point is just your plane normal < x, y, z > multiplied by the distance from the origin: abs(d).
Also of interest, with clever selection of t1, you can also get P2 aligned to some view. Say you are looking at the x, y plane from some z point. You might want to choose t1 = < 0, 1, 0 > (as long as it isn't co-linear to P1). This yields P2 with 0 for the y component, and P3 with 0 for the x component.