trying to fix the clipping bugs
[meshfrac] / src / geom.c
index 25c4d0a..996a484 100644 (file)
@@ -10,19 +10,19 @@ float plane_dist(const struct plane *p, const cgm_vec3 *pt)
 
 float plane_sdist(const struct plane *p, const cgm_vec3 *pt)
 {
-       cgm_vec3 v = p->pt;
-       cgm_vsub(&v, pt);
+       cgm_vec3 v = *pt;
+       cgm_vsub(&v, &p->pt);
        return cgm_vdot(&v, &p->norm);
 }
 
-void midplane(struct plane *p, const cgm_vec3 *a, const cgm_vec3 *b)
+void midplane(struct plane *p, const cgm_vec3 *a, const cgm_vec3 *b, float offs)
 {
        p->norm = *b;
        cgm_vsub(&p->norm, a);
        cgm_vnormalize(&p->norm);
-       p->pt.x = a->x + p->norm.x * 0.5f;
-       p->pt.y = a->y + p->norm.y * 0.5f;
-       p->pt.z = a->z + p->norm.z * 0.5f;
+       p->pt.x = (a->x + b->x) * 0.5f + p->norm.x * offs;
+       p->pt.y = (a->y + b->y) * 0.5f + p->norm.y * offs;
+       p->pt.z = (a->z + b->z) * 0.5f + p->norm.z * offs;
 }
 
 void poly_normal(const struct poly *poly, cgm_vec3 *n)
@@ -170,7 +170,10 @@ static int clip_edge(struct poly *pout, const struct vertex *v0, const struct ve
                        return 1;
                } else {
                        /* going out */
-                       t = ray_plane(&ray, plane);
+                       if((t = ray_plane(&ray, plane)) < 0.0f) {
+                               t = 0.0f;
+                       }
+                       assert(t <= 1.0f);
                        cgm_raypos(&vnew.pos, &ray, t);
 
                        cgm_vlerp(&vnew.norm, &v0->norm, &v1->norm, t);
@@ -183,7 +186,10 @@ static int clip_edge(struct poly *pout, const struct vertex *v0, const struct ve
                /* start outside */
                if(d1 >= 0) {
                        /* going in */
-                       t = ray_plane(&ray, plane);
+                       if((t = ray_plane(&ray, plane)) < 0.0f) {
+                               t = 0.0f;
+                       }
+                       assert(t <= 1.0f);
                        cgm_raypos(&vnew.pos, &ray, t);
 
                        cgm_vlerp(&vnew.norm, &v0->norm, &v1->norm, t);