worked on raytracing

This commit is contained in:
k-a-z-u
2017-09-13 17:06:55 +02:00
parent 686151b511
commit 7eb3a16e48
3 changed files with 287 additions and 62 deletions

View File

@@ -3,6 +3,7 @@
//#include <KLib/geo/Line.h>
#include "Point2.h"
#include "Ray2.h"
class Line2 {
@@ -141,6 +142,69 @@ public:
}
bool getSegmentIntersectionInt(const Line2& other, Point2& result) const {
int mul = 100;
const float p0_x = std::round(p1.x*mul), p1_x = std::round(p2.x*mul), p2_x = std::round(other.p1.x*mul), p3_x = std::round(other.p2.x*mul);
const float p0_y = std::round(p1.y*mul), p1_y = std::round(p2.y*mul), p2_y = std::round(other.p1.y*mul), p3_y = std::round(other.p2.y*mul);
const float s1_x = p1_x - p0_x;
const float s1_y = p1_y - p0_y;
const float s2_x = p3_x - p2_x;
const float s2_y = p3_y - p2_y;
const float s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
const float t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
result.x = (p0_x + (t * s1_x)) / mul;
result.y = (p0_y + (t * s1_y)) / mul;
return true;
}
return false;
}
/** does the line intersect with the given ray? */
bool intersects(const Ray2& ray, Point2& result) const {
//https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect/565282#565282
const float p0_x = p1.x, p1_x = p2.x;
const float p0_y = p1.y, p1_y = p2.y;
const float p2_x = ray.start.x;//, p3_x = other.p2.x;
const float p2_y = ray.start.y;//, p3_y = other.p2.y;
const float s1_x = p1_x - p0_x;
const float s1_y = p1_y - p0_y;
const float s2_x = ray.dir.x; // p3_x - p2_x;
const float s2_y = ray.dir.y; // p3_y - p2_y;
// ray_start + s * ray_dir
const float s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
// before the ray's start?
if (s < 0) {return false;}
// line.p1 + t * (line.p2-line.p1)
const float t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);
// t must be between 0 and 1, otherwise we are before the line's start / after the line's end
if (t < 0 || t > 1) {return false;}
// intersection
result.x = (p0_x + (t * s1_x));
result.y = (p0_y + (t * s1_y));
return true;
}
};
#endif // LINE2D_H