/*
 *  segment.cpp
 *  VSweep
 *
 *  Created by Chema on 10/18/10.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */

#include <algorithm>
#include "basicas.h"
#include "segment.h"


void Edge::init(const DReal3* a, const DReal3*b) {
    vx_[0] = a;
    vx_[1] = b;
}

void Edge::reset(Edge::list& aet) {
    std::sort(vx_,vx_+2,ptr_lessLexicoOrderYXZ<dreal,3>);
    const DReal3& b = *vx_[0];
    const DReal3& t = *vx_[1];
    p_=DReal2(b[0],b[2]);
    y_=b[1];
    dzdy_=0;dxdy_=0;
    if (b[1]!=t[1]) {
        dxdy_ = (t[0]-b[0])/(t[1]-b[1]);
        dzdy_ = (t[2]-b[2])/(t[1]-b[1]);
    }
    aitr_=aet.end();
}

void Edge::inc(dreal level) {
    dreal dy=level-y_;
    p_[0]+=dxdy_*dy;
    p_[1]+=dzdy_*dy;
    y_=level;
}

void Segment::init(Edge* l, Edge* r) {
    hot_=false;
//    d_=Edge::eLeft;
    aeg_[Edge::eLeft]=l;
    aeg_[Edge::eRight]=r;
}

void Segment::reset(Event::queue& events) {
    if(aeg_[0] && aeg_[1]) {
        dreal dx = (*aeg_[1]).p_[0]-(*aeg_[0]).p_[0];
        dreal dy = (*aeg_[1]).p_[1]-(*aeg_[0]).p_[1];
        m_= dx>EPSILON6? dy/dx:0;
    }
}

void Segment::activateEdges(Edge::list& aet) {
    // add Segment edges to active edge list
    for (unsigned i=0;i<2;i++) {
        Edge* eg = aeg_[i];
        if (eg->aitr_==aet.end()) {
            aet.push_front(eg);
            eg->aitr_=aet.begin();
        }
    }
}

void Segment::deActivateEdges(Edge::list& aet) {
    // remove Segment edges from active edge list
    for (unsigned i=0;i<2;i++) {
        Edge* eg = aeg_[i];
        if (eg) {
            if (eg->aitr_!= aet.end()) {
                aet.erase(eg->aitr_);
                eg->aitr_=aet.end();
            }
        }
    }
}






