diff options
Diffstat (limited to 'core/math')
-rw-r--r-- | core/math/geometry.cpp | 146 | ||||
-rw-r--r-- | core/math/geometry.h | 217 | ||||
-rw-r--r-- | core/math/math_funcs.h | 10 | ||||
-rw-r--r-- | core/math/transform.h | 71 | ||||
-rw-r--r-- | core/math/transform_2d.h | 31 |
5 files changed, 245 insertions, 230 deletions
diff --git a/core/math/geometry.cpp b/core/math/geometry.cpp index 8314cb827c..f37db90929 100644 --- a/core/math/geometry.cpp +++ b/core/math/geometry.cpp @@ -34,9 +34,10 @@ #include "thirdparty/misc/clipper.hpp" #include "thirdparty/misc/triangulator.h" -#define SCALE_FACTOR 100000.0 // based on CMP_EPSILON +#define SCALE_FACTOR 100000.0 // Based on CMP_EPSILON. -/* this implementation is very inefficient, commenting unless bugs happen. See the other one. +// This implementation is very inefficient, commenting unless bugs happen. See the other one. +/* bool Geometry::is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) { Vector<int> indices = Geometry::triangulate_polygon(p_polygon); @@ -124,8 +125,8 @@ struct _FaceClassify { }; static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) { - /* connect faces, error will occur if an edge is shared between more than 2 faces */ - /* clear connections */ + // Connect faces, error will occur if an edge is shared between more than 2 faces. + // Clear connections. bool error = false; @@ -195,13 +196,6 @@ static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) { if (p_faces[i].links[j].face == -1) p_faces[i].valid = false; } - /*printf("face %i is valid: %i, group %i. connected to %i:%i,%i:%i,%i:%i\n",i,p_faces[i].valid,p_faces[i].group, - p_faces[i].links[0].face, - p_faces[i].links[0].edge, - p_faces[i].links[1].face, - p_faces[i].links[1].edge, - p_faces[i].links[2].face, - p_faces[i].links[2].edge);*/ } return error; } @@ -249,10 +243,10 @@ PoolVector<PoolVector<Face3> > Geometry::separate_objects(PoolVector<Face3> p_ar if (error) { - ERR_FAIL_COND_V(error, PoolVector<PoolVector<Face3> >()); // invalid geometry + ERR_FAIL_COND_V(error, PoolVector<PoolVector<Face3> >()); // Invalid geometry. } - /* group connected faces in separate objects */ + // Group connected faces in separate objects. int group = 0; for (int i = 0; i < len; i++) { @@ -264,7 +258,7 @@ PoolVector<PoolVector<Face3> > Geometry::separate_objects(PoolVector<Face3> p_ar } } - /* group connected faces in separate objects */ + // Group connected faces in separate objects. for (int i = 0; i < len; i++) { @@ -376,7 +370,7 @@ static inline void _plot_face(uint8_t ***p_cell_status, int x, int y, int z, int static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z) { if (p_cell_status[x][y][z] & 3) - return; // nothing to do, already used and/or visited + return; // Nothing to do, already used and/or visited. p_cell_status[x][y][z] = _CELL_PREV_FIRST; @@ -384,29 +378,20 @@ static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, uint8_t &c = p_cell_status[x][y][z]; - //printf("at %i,%i,%i\n",x,y,z); - if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) { - /* Haven't been in here, mark as outside */ + // Haven't been in here, mark as outside. p_cell_status[x][y][z] |= _CELL_EXTERIOR; - //printf("not marked as anything, marking exterior\n"); } - //printf("cell step is %i\n",(c&_CELL_STEP_MASK)); - if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) { - /* if not done, increase step */ + // If not done, increase step. c += 1 << 2; - //printf("incrementing cell step\n"); } if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) { - /* Go back */ - //printf("done, going back a cell\n"); - + // Go back. switch (c & _CELL_PREV_MASK) { case _CELL_PREV_FIRST: { - //printf("at end, finished marking\n"); return; } break; case _CELL_PREV_Y_POS: { @@ -440,8 +425,6 @@ static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, continue; } - //printf("attempting new cell!\n"); - int next_x = x, next_y = y, next_z = z; uint8_t prev = 0; @@ -475,8 +458,6 @@ static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, default: ERR_FAIL(); } - //printf("testing if new cell will be ok...!\n"); - if (next_x < 0 || next_x >= len_x) continue; if (next_y < 0 || next_y >= len_y) @@ -484,13 +465,9 @@ static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, if (next_z < 0 || next_z >= len_z) continue; - //printf("testing if new cell is traversable\n"); - if (p_cell_status[next_x][next_y][next_z] & 3) continue; - //printf("move to it\n"); - x = next_x; y = next_y; z = next_z; @@ -507,17 +484,6 @@ static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, i if (p_cell_status[x][y][z] & _CELL_EXTERIOR) return; -/* static const Vector3 vertices[8]={ - Vector3(0,0,0), - Vector3(0,0,1), - Vector3(0,1,0), - Vector3(0,1,1), - Vector3(1,0,0), - Vector3(1,0,1), - Vector3(1,1,0), - Vector3(1,1,1), - }; -*/ #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1) static const uint8_t indices[6][4] = { @@ -529,22 +495,6 @@ static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, i { 0, 4, 6, 2 }, }; - /* - - {0,1,2,3}, - {0,1,4,5}, - {0,2,4,6}, - {4,5,6,7}, - {2,3,7,6}, - {1,3,5,7}, - - {0,2,3,1}, - {0,1,5,4}, - {0,4,6,2}, - {7,6,4,5}, - {7,3,2,6}, - {7,5,1,3}, -*/ for (int i = 0; i < 6; i++) { @@ -607,9 +557,9 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e } } - global_aabb.grow_by(0.01); // avoid numerical error + global_aabb.grow_by(0.01); // Avoid numerical error. - // determine amount of cells in grid axis + // Determine amount of cells in grid axis. int div_x, div_y, div_z; if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH) @@ -632,7 +582,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e voxelsize.y /= div_y; voxelsize.z /= div_z; - // create and initialize cells to zero + // Create and initialize cells to zero. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x); for (int i = 0; i < div_x; i++) { @@ -650,7 +600,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e } } - // plot faces into cells + // Plot faces into cells. for (int i = 0; i < face_count; i++) { @@ -662,7 +612,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f); } - // determine which cells connect to the outside by traversing the outside and recursively flood-fill marking + // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking. for (int i = 0; i < div_x; i++) { @@ -691,7 +641,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e } } - // build faces for the inside-outside cell divisors + // Build faces for the inside-outside cell divisors. PoolVector<Face3> wrapped_faces; @@ -706,7 +656,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e } } - // transform face vertices to global coords + // Transform face vertices to global coords. int wrapped_faces_count = wrapped_faces.size(); PoolVector<Face3>::Write wrapped_facesw = wrapped_faces.write(); @@ -753,7 +703,7 @@ Vector<Vector<Vector2> > Geometry::decompose_polygon_in_convex(Vector<Point2> po inp.SetOrientation(TRIANGULATOR_CCW); in_poly.push_back(inp); TriangulatorPartition tpart; - if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { //failed! + if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed. ERR_PRINT("Convex decomposing failed!"); return decomp; } @@ -781,7 +731,7 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes #define SUBPLANE_SIZE 1024.0 - real_t subplane_size = 1024.0; // should compute this from the actual plane + real_t subplane_size = 1024.0; // Should compute this from the actual plane. for (int i = 0; i < p_planes.size(); i++) { Plane p = p_planes[i]; @@ -789,7 +739,7 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes Vector3 ref = Vector3(0.0, 1.0, 0.0); if (ABS(p.normal.dot(ref)) > 0.95) - ref = Vector3(0.0, 0.0, 1.0); // change axis + ref = Vector3(0.0, 0.0, 1.0); // Change axis. Vector3 right = p.normal.cross(ref).normalized(); Vector3 up = p.normal.cross(right).normalized(); @@ -827,20 +777,20 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes real_t dist0 = clip.distance_to(edge0_A); real_t dist1 = clip.distance_to(edge1_A); - if (dist0 <= 0) { // behind plane + if (dist0 <= 0) { // Behind plane. new_vertices.push_back(vertices[k]); } - // check for different sides and non coplanar + // Check for different sides and non coplanar. if ((dist0 * dist1) < 0) { - // calculate intersection + // Calculate intersection. Vector3 rel = edge1_A - edge0_A; real_t den = clip.normal.dot(rel); if (Math::is_zero_approx(den)) - continue; // point too short + continue; // Point too short. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den; Vector3 inters = edge0_A + rel * dist; @@ -854,11 +804,11 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes if (vertices.size() < 3) continue; - //result is a clockwise face + // Result is a clockwise face. MeshData::Face face; - // add face indices + // Add face indices. for (int j = 0; j < vertices.size(); j++) { int idx = -1; @@ -882,7 +832,7 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes face.plane = p; mesh.faces.push_back(face); - //add edge + // Add edge. for (int j = 0; j < face.indices.size(); j++) { @@ -972,7 +922,7 @@ PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int for (int j = 1; j <= p_lats; j++) { - //todo this is stupid, fix + // FIXME: This is stupid. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized(); Vector3 pos = angle * p_radius; planes.push_back(Plane(pos, angle)); @@ -1032,12 +982,12 @@ struct _AtlasWorkRectResult { void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) { - //super simple, almost brute force scanline stacking fitter - //it's pretty basic for now, but it tries to make sure that the aspect ratio of the - //resulting atlas is somehow square. This is necessary because video cards have limits - //on texture size (usually 2048 or 4096), so the more square a texture, the more chances - //it will work in every hardware. - // for example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a + // Super simple, almost brute force scanline stacking fitter. + // It's pretty basic for now, but it tries to make sure that the aspect ratio of the + // resulting atlas is somehow square. This is necessary because video cards have limits. + // On texture size (usually 2048 or 4096), so the more square a texture, the more chances. + // It will work in every hardware. + // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a // 256x8192 atlas (won't work anywhere). ERR_FAIL_COND(p_rects.size() == 0); @@ -1066,7 +1016,7 @@ void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_resu for (int j = 0; j < w; j++) hmax.write[j] = 0; - //place them + // Place them. int ofs = 0; int limit_h = 0; for (int j = 0; j < wrects.size(); j++) { @@ -1101,7 +1051,7 @@ void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_resu if (end_w > max_w) max_w = end_w; - if (ofs == 0 || end_h > limit_h) //while h limit not reached, keep stacking + if (ofs == 0 || end_h > limit_h) // While h limit not reached, keep stacking. ofs += wrects[j].s.width; } @@ -1112,7 +1062,7 @@ void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_resu results.push_back(result); } - //find the result with the best aspect ratio + // Find the result with the best aspect ratio. int best = -1; real_t best_aspect = 1e20; @@ -1152,7 +1102,7 @@ Vector<Vector<Point2> > Geometry::_polypaths_do_operation(PolyBooleanOperation p } Path path_a, path_b; - // Need to scale points (Clipper's requirement for robust computation) + // Need to scale points (Clipper's requirement for robust computation). for (int i = 0; i != p_polypath_a.size(); ++i) { path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR); } @@ -1160,19 +1110,19 @@ Vector<Vector<Point2> > Geometry::_polypaths_do_operation(PolyBooleanOperation p path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR); } Clipper clp; - clp.AddPath(path_a, ptSubject, !is_a_open); // forward compatible with Clipper 10.0.0 - clp.AddPath(path_b, ptClip, true); // polylines cannot be set as clip + clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0. + clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip. Paths paths; if (is_a_open) { - PolyTree tree; // needed to populate polylines + PolyTree tree; // Needed to populate polylines. clp.Execute(op, tree); OpenPathsFromPolyTree(tree, paths); } else { - clp.Execute(op, paths); // works on closed polygons only + clp.Execute(op, paths); // Works on closed polygons only. } - // Have to scale points down now + // Have to scale points down now. Vector<Vector<Point2> > polypaths; for (Paths::size_type i = 0; i < paths.size(); ++i) { @@ -1214,16 +1164,16 @@ Vector<Vector<Point2> > Geometry::_polypath_offset(const Vector<Point2> &p_polyp ClipperOffset co; Path path; - // Need to scale points (Clipper's requirement for robust computation) + // Need to scale points (Clipper's requirement for robust computation). for (int i = 0; i != p_polypath.size(); ++i) { path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR); } co.AddPath(path, jt, et); Paths paths; - co.Execute(paths, p_delta * SCALE_FACTOR); // inflate/deflate + co.Execute(paths, p_delta * SCALE_FACTOR); // Inflate/deflate. - // Have to scale points down now + // Have to scale points down now. Vector<Vector<Point2> > polypaths; for (Paths::size_type i = 0; i < paths.size(); ++i) { diff --git a/core/math/geometry.h b/core/math/geometry.h index 82d9884e9b..8b0a51c651 100644 --- a/core/math/geometry.h +++ b/core/math/geometry.h @@ -47,37 +47,37 @@ class Geometry { public: static real_t get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) { - Vector2 d1 = q1 - p1; // Direction vector of segment S1 - Vector2 d2 = q2 - p2; // Direction vector of segment S2 + Vector2 d1 = q1 - p1; // Direction vector of segment S1. + Vector2 d2 = q2 - p2; // Direction vector of segment S2. Vector2 r = p1 - p2; - real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative - real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative + real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative. + real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative. real_t f = d2.dot(r); real_t s, t; - // Check if either or both segments degenerate into points + // Check if either or both segments degenerate into points. if (a <= CMP_EPSILON && e <= CMP_EPSILON) { - // Both segments degenerate into points + // Both segments degenerate into points. c1 = p1; c2 = p2; return Math::sqrt((c1 - c2).dot(c1 - c2)); } if (a <= CMP_EPSILON) { - // First segment degenerates into a point + // First segment degenerates into a point. s = 0.0; t = f / e; // s = 0 => t = (b*s + f) / e = f / e t = CLAMP(t, 0.0, 1.0); } else { real_t c = d1.dot(r); if (e <= CMP_EPSILON) { - // Second segment degenerates into a point + // Second segment degenerates into a point. t = 0.0; s = CLAMP(-c / a, 0.0, 1.0); // t = 0 => s = (b*t - c) / a = -c / a } else { - // The general nondegenerate case starts here + // The general nondegenerate case starts here. real_t b = d1.dot(d2); - real_t denom = a * e - b * b; // Always nonnegative + real_t denom = a * e - b * b; // Always nonnegative. // If segments not parallel, compute closest point on L1 to L2 and - // clamp to segment S1. Else pick arbitrary s (here 0) + // clamp to segment S1. Else pick arbitrary s (here 0). if (denom != 0.0) { s = CLAMP((b * f - c * e) / denom, 0.0, 1.0); } else @@ -88,7 +88,7 @@ public: //If t in [0,1] done. Else clamp t, recompute s for the new value // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a - // and clamp s to [0, 1] + // and clamp s to [0, 1]. if (t < 0.0) { t = 0.0; s = CLAMP(-c / a, 0.0, 1.0); @@ -105,14 +105,14 @@ public: static void get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2, Vector3 &c1, Vector3 &c2) { -//do the function 'd' as defined by pb. I think is is dot product of some sort +// Do the function 'd' as defined by pb. I think is is dot product of some sort. #define d_of(m, n, o, p) ((m.x - n.x) * (o.x - p.x) + (m.y - n.y) * (o.y - p.y) + (m.z - n.z) * (o.z - p.z)) - //calculate the parametric position on the 2 curves, mua and mub + // Calculate the parametric position on the 2 curves, mua and mub. real_t mua = (d_of(p1, q1, q2, q1) * d_of(q2, q1, p2, p1) - d_of(p1, q1, p2, p1) * d_of(q2, q1, q2, q1)) / (d_of(p2, p1, p2, p1) * d_of(q2, q1, q2, q1) - d_of(q2, q1, p2, p1) * d_of(q2, q1, p2, p1)); real_t mub = (d_of(p1, q1, q2, q1) + mua * d_of(q2, q1, p2, p1)) / d_of(q2, q1, q2, q1); - //clip the value between [0..1] constraining the solution to lie on the original curves + // Clip the value between [0..1] constraining the solution to lie on the original curves. if (mua < 0) mua = 0; if (mub < 0) mub = 0; if (mua > 1) mua = 1; @@ -125,38 +125,38 @@ public: Vector3 u = p_to_a - p_from_a; Vector3 v = p_to_b - p_from_b; Vector3 w = p_from_a - p_to_a; - real_t a = u.dot(u); // always >= 0 + real_t a = u.dot(u); // Always >= 0 real_t b = u.dot(v); - real_t c = v.dot(v); // always >= 0 + real_t c = v.dot(v); // Always >= 0 real_t d = u.dot(w); real_t e = v.dot(w); - real_t D = a * c - b * b; // always >= 0 + real_t D = a * c - b * b; // Always >= 0 real_t sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 real_t tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 - // compute the line parameters of the two closest points - if (D < CMP_EPSILON) { // the lines are almost parallel - sN = 0.0; // force using point P0 on segment S1 - sD = 1.0; // to prevent possible division by 0.0 later + // Compute the line parameters of the two closest points. + if (D < CMP_EPSILON) { // The lines are almost parallel. + sN = 0.0; // Force using point P0 on segment S1 + sD = 1.0; // to prevent possible division by 0.0 later. tN = e; tD = c; - } else { // get the closest points on the infinite lines + } else { // Get the closest points on the infinite lines sN = (b * e - c * d); tN = (a * e - b * d); - if (sN < 0.0) { // sc < 0 => the s=0 edge is visible + if (sN < 0.0) { // sc < 0 => the s=0 edge is visible. sN = 0.0; tN = e; tD = c; - } else if (sN > sD) { // sc > 1 => the s=1 edge is visible + } else if (sN > sD) { // sc > 1 => the s=1 edge is visible. sN = sD; tN = e + b; tD = c; } } - if (tN < 0.0) { // tc < 0 => the t=0 edge is visible + if (tN < 0.0) { // tc < 0 => the t=0 edge is visible. tN = 0.0; - // recompute sc for this edge + // Recompute sc for this edge. if (-d < 0.0) sN = 0.0; else if (-d > a) @@ -165,9 +165,9 @@ public: sN = -d; sD = a; } - } else if (tN > tD) { // tc > 1 => the t=1 edge is visible + } else if (tN > tD) { // tc > 1 => the t=1 edge is visible. tN = tD; - // recompute sc for this edge + // Recompute sc for this edge. if ((-d + b) < 0.0) sN = 0; else if ((-d + b) > a) @@ -177,14 +177,14 @@ public: sD = a; } } - // finally do the division to get sc and tc + // Finally do the division to get sc and tc. sc = (Math::is_zero_approx(sN) ? 0.0 : sN / sD); tc = (Math::is_zero_approx(tN) ? 0.0 : tN / tD); - // get the difference of the two closest points + // Get the difference of the two closest points. Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc) - return dP.length(); // return the closest distance + return dP.length(); // Return the closest distance. } static inline bool ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) { @@ -192,7 +192,7 @@ public: Vector3 e2 = p_v2 - p_v0; Vector3 h = p_dir.cross(e2); real_t a = e1.dot(h); - if (Math::is_zero_approx(a)) // parallel test + if (Math::is_zero_approx(a)) // Parallel test. return false; real_t f = 1.0 / a; @@ -210,16 +210,15 @@ public: if (v < 0.0 || u + v > 1.0) return false; - // at this stage we can compute t to find out where - // the intersection point is on the line + // At this stage we can compute t to find out where + // the intersection point is on the line. real_t t = f * e2.dot(q); if (t > 0.00001) { // ray intersection if (r_res) *r_res = p_from + p_dir * t; return true; - } else // this means that there is a line intersection - // but not a ray intersection + } else // This means that there is a line intersection but not a ray intersection. return false; } @@ -230,7 +229,7 @@ public: Vector3 e2 = p_v2 - p_v0; Vector3 h = rel.cross(e2); real_t a = e1.dot(h); - if (Math::is_zero_approx(a)) // parallel test + if (Math::is_zero_approx(a)) // Parallel test. return false; real_t f = 1.0 / a; @@ -248,16 +247,15 @@ public: if (v < 0.0 || u + v > 1.0) return false; - // at this stage we can compute t to find out where - // the intersection point is on the line + // At this stage we can compute t to find out where + // the intersection point is on the line. real_t t = f * e2.dot(q); - if (t > CMP_EPSILON && t <= 1.0) { // ray intersection + if (t > CMP_EPSILON && t <= 1.0) { // Ray intersection. if (r_res) *r_res = p_from + rel * t; return true; - } else // this means that there is a line intersection - // but not a ray intersection + } else // This means that there is a line intersection but not a ray intersection. return false; } @@ -267,13 +265,11 @@ public: Vector3 rel = (p_to - p_from); real_t rel_l = rel.length(); if (rel_l < CMP_EPSILON) - return false; // both points are the same + return false; // Both points are the same. Vector3 normal = rel / rel_l; real_t sphere_d = normal.dot(sphere_pos); - //Vector3 ray_closest=normal*sphere_d; - real_t ray_distance = sphere_pos.distance_to(normal * sphere_d); if (ray_distance >= p_sphere_radius) @@ -285,7 +281,7 @@ public: if (inters_d2 >= CMP_EPSILON) inters_d -= Math::sqrt(inters_d2); - // check in segment + // Check in segment. if (inters_d < 0 || inters_d > rel_l) return false; @@ -304,9 +300,9 @@ public: Vector3 rel = (p_to - p_from); real_t rel_l = rel.length(); if (rel_l < CMP_EPSILON) - return false; // both points are the same + return false; // Both points are the same. - // first check if they are parallel + // First check if they are parallel. Vector3 normal = (rel / rel_l); Vector3 crs = normal.cross(Vector3(0, 0, 1)); real_t crs_l = crs.length(); @@ -314,8 +310,7 @@ public: Vector3 z_dir; if (crs_l < CMP_EPSILON) { - //blahblah parallel - z_dir = Vector3(1, 0, 0); //any x/y vector ok + z_dir = Vector3(1, 0, 0); // Any x/y vector OK. } else { z_dir = crs / crs_l; } @@ -323,12 +318,12 @@ public: real_t dist = z_dir.dot(p_from); if (dist >= p_radius) - return false; // too far away + return false; // Too far away. - // convert to 2D + // Convert to 2D. real_t w2 = p_radius * p_radius - dist * dist; if (w2 < CMP_EPSILON) - return false; //avoid numerical error + return false; // Avoid numerical error. Size2 size(Math::sqrt(w2), p_height * 0.5); Vector3 x_dir = z_dir.cross(Vector3(0, 0, 1)).normalized(); @@ -375,7 +370,7 @@ public: return false; } - // convert to 3D again + // Convert to 3D again. Vector3 result = p_from + (rel * min); Vector3 res_normal = result; @@ -416,19 +411,18 @@ public: real_t den = p.normal.dot(dir); - //printf("den is %i\n",den); if (Math::abs(den) <= CMP_EPSILON) - continue; // ignore parallel plane + continue; // Ignore parallel plane. real_t dist = -p.distance_to(p_from) / den; if (den > 0) { - //backwards facing plane + // Backwards facing plane. if (dist < max) max = dist; } else { - //front facing plane + // Front facing plane. if (dist > min) { min = dist; min_index = i; @@ -436,8 +430,8 @@ public: } } - if (max <= min || min < 0 || min > rel_l || min_index == -1) // exit conditions - return false; // no intersection + if (max <= min || min < 0 || min > rel_l || min_index == -1) // Exit conditions. + return false; // No intersection. if (p_res) *p_res = p_from + dir * min; @@ -453,16 +447,16 @@ public: Vector3 n = p_segment[1] - p_segment[0]; real_t l2 = n.length_squared(); if (l2 < 1e-20) - return p_segment[0]; // both points are the same, just give any + return p_segment[0]; // Both points are the same, just give any. real_t d = n.dot(p) / l2; if (d <= 0.0) - return p_segment[0]; // before first point + return p_segment[0]; // Before first point. else if (d >= 1.0) - return p_segment[1]; // after first point + return p_segment[1]; // After first point. else - return p_segment[0] + n * d; // inside + return p_segment[0] + n * d; // Inside. } static Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 *p_segment) { @@ -471,11 +465,11 @@ public: Vector3 n = p_segment[1] - p_segment[0]; real_t l2 = n.length_squared(); if (l2 < 1e-20) - return p_segment[0]; // both points are the same, just give any + return p_segment[0]; // Both points are the same, just give any. real_t d = n.dot(p) / l2; - return p_segment[0] + n * d; // inside + return p_segment[0] + n * d; // Inside. } static Vector2 get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 *p_segment) { @@ -484,16 +478,16 @@ public: Vector2 n = p_segment[1] - p_segment[0]; real_t l2 = n.length_squared(); if (l2 < 1e-20) - return p_segment[0]; // both points are the same, just give any + return p_segment[0]; // Both points are the same, just give any. real_t d = n.dot(p) / l2; if (d <= 0.0) - return p_segment[0]; // before first point + return p_segment[0]; // Before first point. else if (d >= 1.0) - return p_segment[1]; // after first point + return p_segment[1]; // After first point. else - return p_segment[0] + n * d; // inside + return p_segment[0] + n * d; // Inside. } static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) { @@ -508,27 +502,25 @@ public: return (cn.cross(an) > 0) == orientation; } - //static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon); - static Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 *p_segment) { Vector2 p = p_point - p_segment[0]; Vector2 n = p_segment[1] - p_segment[0]; real_t l2 = n.length_squared(); if (l2 < 1e-20) - return p_segment[0]; // both points are the same, just give any + return p_segment[0]; // Both points are the same, just give any. real_t d = n.dot(p) / l2; - return p_segment[0] + n * d; // inside + return p_segment[0] + n * d; // Inside. } static bool line_intersects_line_2d(const Vector2 &p_from_a, const Vector2 &p_dir_a, const Vector2 &p_from_b, const Vector2 &p_dir_b, Vector2 &r_result) { - // see http://paulbourke.net/geometry/pointlineplane/ + // See http://paulbourke.net/geometry/pointlineplane/ const real_t denom = p_dir_b.y * p_dir_a.x - p_dir_b.x * p_dir_a.y; - if (Math::is_zero_approx(denom)) { // parallel? + if (Math::is_zero_approx(denom)) { // Parallel? return false; } @@ -556,11 +548,11 @@ public: real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y); - // Fail if segment C-D crosses line A-B outside of segment A-B. + // Fail if segment C-D crosses line A-B outside of segment A-B. if (ABpos < 0 || ABpos > 1.0) return false; - // (4) Apply the discovered position to line A-B in the original coordinate system. + // (4) Apply the discovered position to line A-B in the original coordinate system. if (r_result) *r_result = p_from_a + B * ABpos; @@ -593,7 +585,7 @@ public: real_t d = p_normal.dot(p_sphere_pos) - p_normal.dot(p_triangle[0]); - if (d > p_sphere_radius || d < -p_sphere_radius) // not touching the plane of the face, return + if (d > p_sphere_radius || d < -p_sphere_radius) // Not touching the plane of the face, return. return false; Vector3 contact = p_sphere_pos - (p_normal * d); @@ -613,25 +605,25 @@ public: for (int i = 0; i < 3; i++) { - // check edge cylinder + // Check edge cylinder. Vector3 n1 = verts[i] - verts[i + 1]; Vector3 n2 = p_sphere_pos - verts[i + 1]; - ///@TODO i could discard by range here to make the algorithm quicker? dunno.. + ///@TODO Maybe discard by range here to make the algorithm quicker. - // check point within cylinder radius + // Check point within cylinder radius. Vector3 axis = n1.cross(n2).cross(n1); - axis.normalize(); // ugh + axis.normalize(); real_t ad = axis.dot(n2); if (ABS(ad) > p_sphere_radius) { - // no chance with this edge, too far away + // No chance with this edge, too far away. continue; } - // check point within edge capsule cylinder + // Check point within edge capsule cylinder. /** 4th TEST INSIDE EDGE POINTS **/ real_t sphere_at = n1.dot(n2); @@ -640,8 +632,7 @@ public: r_triangle_contact = p_sphere_pos - axis * (axis.dot(n2)); r_sphere_contact = p_sphere_pos - axis * p_sphere_radius; - // point inside here - //printf("solved inside edge\n"); + // Point inside here. return true; } @@ -651,48 +642,51 @@ public: Vector3 n = (p_sphere_pos - verts[i + 1]).normalized(); - //r_triangle_contact=verts[i+1]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2)); r_triangle_contact = verts[i + 1]; r_sphere_contact = p_sphere_pos - n * p_sphere_radius; - //printf("solved inside point segment 1\n"); return true; } if (n2.distance_squared_to(n1) < r2) { Vector3 n = (p_sphere_pos - verts[i]).normalized(); - //r_triangle_contact=verts[i]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2)); r_triangle_contact = verts[i]; r_sphere_contact = p_sphere_pos - n * p_sphere_radius; - //printf("solved inside point segment 1\n"); return true; } - break; // It's pointless to continue at this point, so save some cpu cycles + break; // It's pointless to continue at this point, so save some CPU cycles. } return false; } + static inline bool is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) { + + return p_point.distance_squared_to(p_circle_pos) <= p_circle_radius * p_circle_radius; + } + static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) { Vector2 line_vec = p_to - p_from; Vector2 vec_to_line = p_from - p_circle_pos; - /* create a quadratic formula of the form ax^2 + bx + c = 0 */ + // Create a quadratic formula of the form ax^2 + bx + c = 0 real_t a, b, c; a = line_vec.dot(line_vec); b = 2 * vec_to_line.dot(line_vec); c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius; - /* solve for t */ + // Solve for t. real_t sqrtterm = b * b - 4 * a * c; - /* if the term we intend to square root is less than 0 then the answer won't be real, so it definitely won't be t in the range 0 to 1 */ + // If the term we intend to square root is less than 0 then the answer won't be real, + // so it definitely won't be t in the range 0 to 1. if (sqrtterm < 0) return -1; - /* if we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection) then the following can be skipped and we can just return the equivalent of res1 */ + // If we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection) + // then the following can be skipped and we can just return the equivalent of res1. sqrtterm = Math::sqrt(sqrtterm); real_t res1 = (-b - sqrtterm) / (2 * a); real_t res2 = (-b + sqrtterm) / (2 * a); @@ -718,7 +712,6 @@ public: int outside_count = 0; for (int a = 0; a < polygon.size(); a++) { - //real_t p_plane.d = (*this) * polygon[a]; real_t dist = p_plane.distance_to(polygon[a]); if (dist < -CMP_POINT_IN_PLANE_EPSILON) { location_cache[a] = LOC_INSIDE; @@ -735,11 +728,11 @@ public: if (outside_count == 0) { - return polygon; // no changes + return polygon; // No changes. } else if (inside_count == 0) { - return Vector<Vector3>(); //empty + return Vector<Vector3>(); // Empty. } long previous = polygon.size() - 1; @@ -839,16 +832,6 @@ public: return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type); } - static Vector<Point2> transform_points_2d(const Vector<Point2> &p_points, const Transform2D &p_mat) { - - Vector<Point2> points; - - for (int i = 0; i < p_points.size(); ++i) { - points.push_back(p_mat.xform(p_points[i])); - } - return points; - } - static Vector<int> triangulate_delaunay_2d(const Vector<Vector2> &p_points) { Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points); @@ -894,7 +877,7 @@ public: return sum > 0.0f; } - /* alternate implementation that should be faster */ + // Alternate implementation that should be faster. static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) { int c = p_polygon.size(); if (c < 3) @@ -910,7 +893,8 @@ public: further_away_opposite.y = MIN(p[i].y, further_away_opposite.y); } - further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312); // make point outside that won't intersect with points in segment from p_point + // Make point outside that won't intersect with points in segment from p_point. + further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312); int intersections = 0; for (int i = 0; i < c; i++) { @@ -926,7 +910,8 @@ public: static PoolVector<PoolVector<Face3> > separate_objects(PoolVector<Face3> p_array); - static PoolVector<Face3> wrap_geometry(PoolVector<Face3> p_array, real_t *p_error = NULL); ///< create a "wrap" that encloses the given geometry + // Create a "wrap" that encloses the given geometry. + static PoolVector<Face3> wrap_geometry(PoolVector<Face3> p_array, real_t *p_error = NULL); struct MeshData { @@ -1008,17 +993,17 @@ public: Vector<Point2> H; H.resize(2 * n); - // Sort points lexicographically + // Sort points lexicographically. P.sort(); - // Build lower hull + // Build lower hull. for (int i = 0; i < n; ++i) { while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) k--; H.write[k++] = P[i]; } - // Build upper hull + // Build upper hull. for (int i = n - 2, t = k + 1; i >= 0; i--) { while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) k--; diff --git a/core/math/math_funcs.h b/core/math/math_funcs.h index af845ca01e..9078abea68 100644 --- a/core/math/math_funcs.h +++ b/core/math/math_funcs.h @@ -300,6 +300,11 @@ public: } static _ALWAYS_INLINE_ bool is_equal_approx(real_t a, real_t b) { + // Check for exact equality first, required to handle "infinity" values. + if (a == b) { + return true; + } + // Then check for approximate equality. real_t tolerance = CMP_EPSILON * abs(a); if (tolerance < CMP_EPSILON) { tolerance = CMP_EPSILON; @@ -308,6 +313,11 @@ public: } static _ALWAYS_INLINE_ bool is_equal_approx(real_t a, real_t b, real_t tolerance) { + // Check for exact equality first, required to handle "infinity" values. + if (a == b) { + return true; + } + // Then check for approximate equality. return abs(a - b) < tolerance; } diff --git a/core/math/transform.h b/core/math/transform.h index 4c8d915305..90e2b07583 100644 --- a/core/math/transform.h +++ b/core/math/transform.h @@ -34,6 +34,7 @@ #include "core/math/aabb.h" #include "core/math/basis.h" #include "core/math/plane.h" +#include "core/pool_vector.h" class Transform { public: @@ -82,6 +83,9 @@ public: _FORCE_INLINE_ AABB xform(const AABB &p_aabb) const; _FORCE_INLINE_ AABB xform_inv(const AABB &p_aabb) const; + _FORCE_INLINE_ PoolVector<Vector3> xform(const PoolVector<Vector3> &p_array) const; + _FORCE_INLINE_ PoolVector<Vector3> xform_inv(const PoolVector<Vector3> &p_array) const; + void operator*=(const Transform &p_transform); Transform operator*(const Transform &p_transform) const; @@ -154,22 +158,29 @@ _FORCE_INLINE_ Plane Transform::xform_inv(const Plane &p_plane) const { } _FORCE_INLINE_ AABB Transform::xform(const AABB &p_aabb) const { - /* define vertices */ - Vector3 x = basis.get_axis(0) * p_aabb.size.x; - Vector3 y = basis.get_axis(1) * p_aabb.size.y; - Vector3 z = basis.get_axis(2) * p_aabb.size.z; - Vector3 pos = xform(p_aabb.position); - //could be even further optimized - AABB new_aabb; - new_aabb.position = pos; - new_aabb.expand_to(pos + x); - new_aabb.expand_to(pos + y); - new_aabb.expand_to(pos + z); - new_aabb.expand_to(pos + x + y); - new_aabb.expand_to(pos + x + z); - new_aabb.expand_to(pos + y + z); - new_aabb.expand_to(pos + x + y + z); - return new_aabb; + + /* http://dev.theomader.com/transform-bounding-boxes/ */ + Vector3 min = p_aabb.position; + Vector3 max = p_aabb.position + p_aabb.size; + Vector3 tmin, tmax; + for (int i = 0; i < 3; i++) { + tmin[i] = tmax[i] = origin[i]; + for (int j = 0; j < 3; j++) { + real_t e = basis[i][j] * min[j]; + real_t f = basis[i][j] * max[j]; + if (e < f) { + tmin[i] += e; + tmax[i] += f; + } else { + tmin[i] += f; + tmax[i] += e; + } + } + } + AABB r_aabb; + r_aabb.position = tmin; + r_aabb.size = tmax - tmin; + return r_aabb; } _FORCE_INLINE_ AABB Transform::xform_inv(const AABB &p_aabb) const { @@ -198,4 +209,32 @@ _FORCE_INLINE_ AABB Transform::xform_inv(const AABB &p_aabb) const { return ret; } +PoolVector<Vector3> Transform::xform(const PoolVector<Vector3> &p_array) const { + + PoolVector<Vector3> array; + array.resize(p_array.size()); + + PoolVector<Vector3>::Read r = p_array.read(); + PoolVector<Vector3>::Write w = array.write(); + + for (int i = 0; i < p_array.size(); ++i) { + w[i] = xform(r[i]); + } + return array; +} + +PoolVector<Vector3> Transform::xform_inv(const PoolVector<Vector3> &p_array) const { + + PoolVector<Vector3> array; + array.resize(p_array.size()); + + PoolVector<Vector3>::Read r = p_array.read(); + PoolVector<Vector3>::Write w = array.write(); + + for (int i = 0; i < p_array.size(); ++i) { + w[i] = xform_inv(r[i]); + } + return array; +} + #endif // TRANSFORM_H diff --git a/core/math/transform_2d.h b/core/math/transform_2d.h index c44678674a..e8b44ab197 100644 --- a/core/math/transform_2d.h +++ b/core/math/transform_2d.h @@ -32,6 +32,7 @@ #define TRANSFORM_2D_H #include "core/math/rect2.h" // also includes vector2, math_funcs, and ustring +#include "core/pool_vector.h" struct Transform2D { // Warning #1: basis of Transform2D is stored differently from Basis. In terms of elements array, the basis matrix looks like "on paper": @@ -110,6 +111,8 @@ struct Transform2D { _FORCE_INLINE_ Vector2 xform_inv(const Vector2 &p_vec) const; _FORCE_INLINE_ Rect2 xform(const Rect2 &p_rect) const; _FORCE_INLINE_ Rect2 xform_inv(const Rect2 &p_rect) const; + _FORCE_INLINE_ PoolVector<Vector2> xform(const PoolVector<Vector2> &p_array) const; + _FORCE_INLINE_ PoolVector<Vector2> xform_inv(const PoolVector<Vector2> &p_array) const; operator String() const; @@ -199,4 +202,32 @@ Rect2 Transform2D::xform_inv(const Rect2 &p_rect) const { return new_rect; } +PoolVector<Vector2> Transform2D::xform(const PoolVector<Vector2> &p_array) const { + + PoolVector<Vector2> array; + array.resize(p_array.size()); + + PoolVector<Vector2>::Read r = p_array.read(); + PoolVector<Vector2>::Write w = array.write(); + + for (int i = 0; i < p_array.size(); ++i) { + w[i] = xform(r[i]); + } + return array; +} + +PoolVector<Vector2> Transform2D::xform_inv(const PoolVector<Vector2> &p_array) const { + + PoolVector<Vector2> array; + array.resize(p_array.size()); + + PoolVector<Vector2>::Read r = p_array.read(); + PoolVector<Vector2>::Write w = array.write(); + + for (int i = 0; i < p_array.size(); ++i) { + w[i] = xform_inv(r[i]); + } + return array; +} + #endif // TRANSFORM_2D_H |