/* Segment en 2D */ /* */ /* Auteur: Nicolas JANEY */ /* nicolas.janey@univ-fcomte.fr */ /* Novembre 2010 */ #include #include #include #include "Segment2D.h" #include "Position2D.h" #include "Rectangle2D.h" #include "Trace.h" Segment2D::Segment2D(void) { pi = new Position2D(); pf = new Position2D(); } Segment2D::Segment2D(Position2D *p1,Position2D *p2) { pi = new Position2D(p1); pf = new Position2D(p2); } Segment2D::Segment2D(Segment2D *s) { pi = new Position2D(s->pi); pf = new Position2D(s->pf); } Segment2D::~Segment2D(void) { delete(pi); delete(pf); } void Segment2D::print(void) { pi->print(); printf("\n"); pf->print(); printf("\n"); } static int round(double v) { return((int) (v + (( v > 0.0 ) ? 0.4999 : -0.4999))); } void Segment2D::trace(void) { traceSegment(round(pi->c[0]),round(pi->c[1]), round(pf->c[0]),round(pf->c[1])); } double intersection(double ai,double bi, double af,double bf,double val) { if ( af-ai != 0 ) return(bi + (val-ai)/(af-ai)*(bf-bi)); else return(1000000.0); } int code(Position2D *p,Rectangle2D *r) { int code = 0; if ( p->c[0] < r->ig->c[0] ) code += 1; if ( p->c[0] > r->sd->c[0] ) code += 2; if ( p->c[1] < r->ig->c[1] ) code += 4; if ( p->c[1] > r->sd->c[1] ) code += 8; return(code); } int Segment2D::clip(Rectangle2D *r) { int c1,c2; c1 = code(pi,r); c2 = code(pf,r); while ( ( c1 || c2 ) && ( (c1&c2) == 0 ) ) { if ( !c1 ) { Position2D p = *pi; *pi = *pf; *pf = p; int aux = c1; c1 = c2; c2 = aux; } if ( (c1&0x01) != 0 ) { pi->c[1] = intersection(pi->c[0],pi->c[1], pf->c[0],pf->c[1], r->ig->c[0]); pi->c[0] = r->ig->c[0]; } else if ( (c1&0x02) != 0 ) { pi->c[1] = intersection(pi->c[0],pi->c[1], pf->c[0],pf->c[1], r->sd->c[0]); pi->c[0] = r->sd->c[0]; } else if ( (c1&0x04) != 0 ) { pi->c[0] = intersection(pi->c[1],pi->c[0], pf->c[1],pf->c[0], r->ig->c[1]); pi->c[1] = r->ig->c[1]; } else if ( (c1&0x08) != 0 ) { pi->c[0] = intersection(pi->c[1],pi->c[0], pf->c[1],pf->c[0], r->sd->c[1]); pi->c[1] = r->sd->c[1]; } c1 = code(pi,r); } return ( !c1 && !c2); }