inline Line operator-(const Line & line, const Vector & vec) { return Line(line.getCoor1() - vec, line.getCoor1() - vec); }
/************************************************************************ * * * Calculate some line info * * */ void Line::some_info(int moving) { char str[100]; // holds text to be displayed in info window int i; // counter int num_points ; // number of data points underneath this line float *pdata ; // pointer to image data (intensities) // Don't do anything if there is no line profile display active if (! Win_line_info::winlineinfo){ return; } // Do not do anything if we are not the active ROI if (position_in_active_list(this) > 0){ return; } Gframe *gf = owner_frame; Imginfo *img = gf->imginfo; //fix_line_direction(); // Calculate and print out the line length // ASSUME THE "SPAN" (GetRatioFast/GetRatioMedium) GIVES THE DISTANCE // FROM ONE EDGE OF THE PICTURE TO THE OTHER, RATHER THAN THE // DISTANCE BETWEEN CENTERS OF THE OPPOSITE EDGE DATELS. // THEREFORE, WE DIVIDE BY THE NUMBER OF DATELS, RATHER THAN THE // NUMBER OF DATELS MINUS 1. float xscale = img->GetRatioFast() / img->GetFast(); float yscale = img->GetRatioMedium() / img->GetMedium(); float lenx = second_point_on_data.x - first_point_on_data.x; float lenxcm = lenx * xscale; float leny = second_point_on_data.y - first_point_on_data.y; float lenycm = leny * yscale; float line_len = (double) sqrt((lenxcm*lenxcm) + (lenycm*lenycm)); sprintf (str, "Length of line: %.4g cm", line_len); Win_line_info::show_line_length(str); // Print the line end coords. sprintf (str,"Coordinates: (%.1f, %.1f) to (%.1f, %.1f)", first_point_on_data.x, first_point_on_data.y, second_point_on_data.x, second_point_on_data.y); Win_line_info::show_coordinates(str) ; int x0 = (int)first_point_on_data.x; int x1 = (int)second_point_on_data.x; int y0 = (int)first_point_on_data.y; int y1 = (int)second_point_on_data.y; num_points = abs(x1 - x0); if ( abs(y1 - y0) > num_points ){ num_points = abs(y1 - y0); } num_points++; if (gf->imginfo->type != TYPE_FLOAT){ msgerr_print ("Data type not supported"); return; } float *project = 0; if (Win_line_info::projection_type == ON_LINE){ project = new float [num_points]; for (pdata=FirstPixel(), i=0; pdata, i<num_points; pdata=NextPixel()){ project[i++] = *pdata; } }else if (! moving){ // projection_type == ACROSS_LINE // Increase number of points, so we don't miss any pixels. num_points *= 2; project = new float [num_points]; // Step through "num_points" equally spaced points along the line. Fpoint orig; Fpoint slope; Fpoint clip[2]; Fpoint ends[2]; float dx = lenx / (num_points - 1); float dy = leny / (num_points - 1); orig.x = first_point_on_data.x; orig.y = first_point_on_data.y; slope.x = -lenycm / xscale; // Slope of normal to the line slope.y = lenxcm / yscale; // in pixel units. clip[0].x = clip[0].y = 0; clip[1].x = img->GetFast() - 1; clip[1].y = img->GetMedium() - 1; float t; for (i=0; i<num_points; i++, orig.x += dx, orig.y += dy){ // Erect a normal to the line at this (orig) location that // just fits in the data space. The slope of the normal is // (-lenx/leny). The following routine returns the endpoints // of the required line. extend_line(orig, // A point on the line slope, // Slope of the line clip, // Clipping corners ends); // Returns endpoints // Find the maximum value along the line. Line *line = new Line(ends[0], ends[1]); line->owner_frame = gf; t = *(pdata = line->FirstPixel()); for ( ; pdata; pdata=line->NextPixel()){ if (*pdata > t){ t = *pdata; } } project[i] = t; delete line; } } if (project){ Win_line_info::set_projection_type(-1); Win_line_info::show_projection(project, num_points, line_len); delete [] project; } } // Line::some_info
float Sphere::Distance(const Line &line) const { return line.Distance(*this); }
void LineManager::pushSheepIntoLine(int _line,SheepWhite* _sheep) { Line* line = this->getLine(_line); line->pushDequeWhite(_sheep); }
void LineManager::eraseSheepIntoLine(int _line,SheepWhite* _sheep) { Line* line = this->getLine(_line); line->eraseDequeWhite(_sheep); }
QDebug operator<<(QDebug dbg, const Line &line) { dbg.nospace() << "# " << line.comment() << "\n" << line.prismSideA() << " # sida A\n" << line.prismSideB() << " # side B\n" << line.length() << " # side C\n"; return dbg.maybeSpace(); }
bool check(const Line &u, const Line &v, const Line &w) { return w.include(intersect(u, v)); }
double ObjectDetectionAlgorithmTeamB::rateObject(Object& consideredObject, Line& lineToCheck, Model databaseObject, int currentLineNumber, float maxRatingPerLine){ const Line* lastFoundLine = consideredObject.getLines()[currentLineNumber-1]; const Line* lastDBLine = databaseObject.getLines()[currentLineNumber-1]; const Line* currentDBLine = databaseObject.getLines()[currentLineNumber]; // if incoming line is already part of object return for(uint i = 0; i < consideredObject.getLines().size(); i++){ if(consideredObject.getLines()[i]->getStart() == lineToCheck.getStart() && consideredObject.getLines()[i]->getEnd() == lineToCheck.getEnd()){ return 0; } } //points from lineToCheck cv::Point2i pointToCheckStart; cv::Point2i pointToCheckEnd; //points from lastFoundLine cv::Point2i lastPointToCheckStart; cv::Point2i lastPointToCheckEnd; //points from currentDBLine cv::Point2i dbStartPoint; cv::Point2i dbEndPoint; //points from lastDBLine cv::Point2i lastDBPointStart; cv::Point2i lastDBPointEnd; pointToCheckStart = lineToCheck.getStart(); pointToCheckEnd = lineToCheck.getEnd(); lastPointToCheckStart = lastFoundLine->getStart(); lastPointToCheckEnd = lastFoundLine->getEnd(); dbStartPoint = currentDBLine->getStart(); dbEndPoint = currentDBLine->getEnd(); lastDBPointStart = lastDBLine->getStart(); lastDBPointEnd = lastDBLine->getEnd(); //make vector between start and end point cv::Point2i vectorCurrentPoint; cv::Point2i vectorCurrentPointLast; cv::Point2i vectorDbPoint; cv::Point2i vectorDbPointLast; cv::Point2i vectorBetweenDBLines; cv::Point2i vectorBetweenObjectLines; cv::Point2i vectorBetweenObjectLinesReverse; //the vector of the the start and end point, for current and last line //b - a vectorCurrentPoint = pointToCheckEnd - pointToCheckStart; vectorCurrentPointLast = lastPointToCheckEnd - lastPointToCheckStart; vectorDbPoint = dbEndPoint - dbStartPoint; vectorDbPointLast = lastDBPointEnd - lastDBPointStart; //space beetwen the two lines vectorBetweenDBLines = dbStartPoint - lastDBPointEnd; // ****************************************************************************** // rotate first and second line of considered object if neccessary to match model // ****************************************************************************** if(currentLineNumber == 1){ cv::Point2i vToStart; cv::Point2i vToEnd; // if this vector length matches with model rotate only first line vToStart = pointToCheckStart - lastPointToCheckStart; // if this vector length matches with model rotate both lines vToEnd = pointToCheckEnd - lastPointToCheckStart; // get lengths of vectors double vToStartLength = getLineLength(vToStart.x, vToStart.y); double vToEndLength = getLineLength(vToEnd.x, vToEnd.y); // get relative length compared to current line double lengthCurrentLineLast = getLineLength(vectorCurrentPointLast.x, vectorCurrentPointLast.y); double relVStartLength = vToStartLength/lengthCurrentLineLast; double relVEndLength = vToEndLength/lengthCurrentLineLast; // get realtive length compared to current line of model double distanceBetweenDBLines = getLineLength(vectorBetweenDBLines.x, vectorBetweenDBLines.y); double lengthDbLineLast = getLineLength(vectorDbPointLast.x, vectorDbPointLast.y); double relDistanceBetweenDBPoints = distanceBetweenDBLines/lengthDbLineLast; // calc the variance from lines to db lines double var1 = relDistanceBetweenDBPoints - relVStartLength; double var2 = relDistanceBetweenDBPoints - relVEndLength; // maximum variance double threshold = 0.2; // check if a line has to be rotated if(var1 < threshold && var1 > -threshold){ // rotate only first line -> cannot switch lines of object as they are saved -> delete line and create new cv::Point2i start = consideredObject.getLines()[0]->getEnd(); cv::Point2i end = consideredObject.getLines()[0]->getStart(); consideredObject.clearLines(); consideredObject.addLine(Line(start, end)); // fix old values lastPointToCheckStart = consideredObject.getLines()[0]->getStart(); lastPointToCheckEnd = consideredObject.getLines()[0]->getEnd(); vectorCurrentPointLast = lastPointToCheckEnd - lastPointToCheckStart; }else if(var2 < threshold && var2 > -threshold){ // rotate both lines // first line -> cannot switch lines of object as they are saved -> delete line and create new cv::Point2i start = consideredObject.getLines()[0]->getEnd(); cv::Point2i end = consideredObject.getLines()[0]->getStart(); consideredObject.clearLines(); consideredObject.addLine(Line(start, end)); // current line lineToCheck.switchStartAndEnd(); // fix old values pointToCheckStart = lineToCheck.getStart(); pointToCheckEnd = lineToCheck.getEnd(); vectorCurrentPoint = pointToCheckEnd - pointToCheckStart; lastPointToCheckStart = consideredObject.getLines()[0]->getStart(); lastPointToCheckEnd = consideredObject.getLines()[0]->getEnd(); vectorCurrentPointLast = lastPointToCheckEnd - lastPointToCheckStart; } } vectorBetweenObjectLines = pointToCheckStart - lastPointToCheckEnd; // if this suits later line has to be rotated vectorBetweenObjectLinesReverse = pointToCheckEnd - lastPointToCheckEnd; //calculate angle between current and last line, skalarprodukt without cos //phi = (a1*b1) + (an * bn) / |a| * |b| double currentPointAngle = getAngleOfLines(vectorCurrentPoint, vectorCurrentPointLast); double dbPointAngle = getAngleOfLines(vectorDbPoint, vectorDbPointLast); //get the length double lengthCurrentLine = getLineLength(vectorCurrentPoint.x, vectorCurrentPoint.y); double lengthCurrentLineLast = getLineLength(vectorCurrentPointLast.x, vectorCurrentPointLast.y); double lengthDbCurrentLine = getLineLength(vectorDbPoint.x, vectorDbPoint.y); double lengthDbLineLast = getLineLength(vectorDbPointLast.x, vectorDbPointLast.y); double distanceBetweenDBLines = getLineLength(vectorBetweenDBLines.x, vectorBetweenDBLines.y); double distanceBetweenObjectLines = getLineLength(vectorBetweenObjectLines.x, vectorBetweenObjectLines.y); double distanceBetweenObjectLinesReverse = getLineLength(vectorBetweenObjectLinesReverse.x, vectorBetweenObjectLinesReverse.y); //now compare and set the rating, the current line to db current line double distanceThreshold1 = maxDistanceThreshold; double distanceThreshold2 = maxDistanceThreshold - (maxDistanceThreshold/3); double distanceThreshold3 = maxDistanceThreshold - (maxDistanceThreshold/3*2); double tenPointRating = maxRatingPerLine / 10; double lengthAndPosiRating = 0;// tenPointRating; // get a relative value of distance that says how much space is between end of last line and start of new line compared to the length of line double relDistanceBetweenDBPoints = distanceBetweenDBLines/lengthDbLineLast; double relDistanceBetweenLinePoints = distanceBetweenObjectLines/lengthCurrentLineLast; double relDistanceBetweenLinePointsRevert = distanceBetweenObjectLinesReverse/lengthCurrentLineLast; double relValNorm = relDistanceBetweenDBPoints - relDistanceBetweenLinePoints; double relValRev = relDistanceBetweenDBPoints - relDistanceBetweenLinePointsRevert; // rotate line if vector between end of last line and end of current line fits in order to match model if(relValRev < distanceThreshold1 && relValRev > -distanceThreshold1){ lineToCheck.switchStartAndEnd(); } //check the distance if((relValNorm < distanceThreshold1 && relValNorm > -distanceThreshold1) || (relValRev < distanceThreshold1 && relValRev > -distanceThreshold1)) { lengthAndPosiRating = tenPointRating; if((relValNorm < distanceThreshold2 && relValNorm > -distanceThreshold2) || (relValRev < distanceThreshold2 && relValRev > -distanceThreshold2)) { lengthAndPosiRating = tenPointRating * 2.0; if((relValNorm < distanceThreshold3 && relValNorm > -distanceThreshold3) || (relValRev < distanceThreshold3 && relValRev > -distanceThreshold3)) { lengthAndPosiRating = tenPointRating * 3.0; } } // check length of currLine/lastLine compared to db lines if((lengthDbCurrentLine / lengthDbLineLast) - (lengthCurrentLine / lengthCurrentLineLast) > -distanceThreshold2/5 && (lengthDbCurrentLine / lengthDbLineLast) - (lengthCurrentLine / lengthCurrentLineLast) < distanceThreshold2/5) { lengthAndPosiRating += tenPointRating * 2; if((lengthDbCurrentLine / lengthDbLineLast) - (lengthCurrentLine / lengthCurrentLineLast) > -distanceThreshold3/5 && (lengthDbCurrentLine / lengthDbLineLast) - (lengthCurrentLine / lengthCurrentLineLast) < distanceThreshold3/5) { lengthAndPosiRating += tenPointRating*2; } } } else//rate when point coord. are very wrong { lengthAndPosiRating = 0; } //now compare the angle double angleThreshold1 = maxAngleThreshold - (maxAngleThreshold/3*2); double angleThreshold2 = maxAngleThreshold - (maxAngleThreshold/3); double angleThreshold3 = maxAngleThreshold; double angleRating; // as angle can be positive and negative consider both double relPosAngleVal = dbPointAngle - currentPointAngle; double relNegAngleVal = dbPointAngle + currentPointAngle; if((relPosAngleVal <= angleThreshold3 && relPosAngleVal >= -angleThreshold3) || (relNegAngleVal <= angleThreshold3 && relNegAngleVal >= -angleThreshold3)) { angleRating = tenPointRating ; if((relPosAngleVal <= angleThreshold2 && relPosAngleVal >= -angleThreshold2) || (relNegAngleVal <= angleThreshold2 && relNegAngleVal >= -angleThreshold2)) { angleRating = tenPointRating * 2; if((relPosAngleVal <= angleThreshold1 && relPosAngleVal >= -angleThreshold1) || (relNegAngleVal <= angleThreshold1 && relNegAngleVal >= -angleThreshold1)) { angleRating = tenPointRating * 3; } } } else { angleRating = 0; } if(fastMode){ if(lengthAndPosiRating == 0 || angleRating == 0){ return 0; } } // if(lengthAndPosiRating > 0 && angleRating > 0){ return lengthAndPosiRating + angleRating; // } // else return 0; }
void ShortSpliner::Process(ChangeQueue &changeQ) { //changeQ.UpdateCurrent(); changeQ.CalcBounds(); /* point dumb[4],d,ld; pointf offset, polyp; Ppoly_t **obs; polygon_t *poly; int i, j, npoly, sides; extern void polygon_init(node_t *); Ppoint_t p,q; vconfig_t *vconfig; Pedge_t *barriers; char *str; */ double SEP = gd<GraphGeom>(changeQ.current).separation.Len(); /* build configuration */ int N = current->nodes().size(); vector<Ppoly_t*> obs; obs.resize(N,0); vector<Ppoly_t> polys; polys.resize(N); vector<Line> polydat; polydat.resize(N); int i = 0; for(Layout::node_iter ni = current->nodes().begin(); ni!=current->nodes().end(); ++ni) { obs[i] = &polys[i]; polydat[i] = gd<NodeGeom>(*ni).region.shape + gd<NodeGeom>(*ni).pos; reverse(polydat[i].begin(),polydat[i].end()); // pathplan wants CW polys[i].ps = reinterpret_cast<Ppoint_t*>(&*polydat[i].begin()); polys[i].pn = polydat[i].size()-1; ++i; } int npoly = i; vconfig_t *vconfig; if (!Plegal_arrangement(&*obs.begin(),npoly)) { //if (Verbose) fprintf(stderr,"nodes touch - falling back to straight line edges\n"); vconfig = 0; } else vconfig = Pobsopen(&*obs.begin(),npoly); /* route edges */ for(Layout::graphedge_iter ei = current->edges().begin(); ei!=current->edges().end(); ++ei) { Layout::Edge *e = *ei; NodeGeom &tg = gd<NodeGeom>(e->tail), &hg = gd<NodeGeom>(e->head); EdgeGeom &eg = gd<EdgeGeom>(e); Ppoint_t p = *reinterpret_cast<Ppoint_t*>(&tg.pos), q = *reinterpret_cast<Ppoint_t*>(&hg.pos); Line unclipped; unclipped.degree = 1; if (vconfig && (e->tail != e->head)) { Ppolyline_t line; int pp, qp; /* determine the polygons (if any) that contain the endpoints */ pp = qp = POLYID_NONE; for (i = 0; i < npoly; i++) { if ((pp == POLYID_NONE) && in_poly(*obs[i], p)) pp = i; if ((qp == POLYID_NONE) && in_poly(*obs[i], q)) qp = i; } if(!Pobspath(vconfig, p, pp, q, qp, &line)) throw ClockwiseShapes(); Ppolyline_t spline; Pvector_t slopes[2]; int n_barriers; Pedge_t *barriers; make_barriers(&*obs.begin(), npoly, pp, qp, &barriers, &n_barriers); slopes[0].x = slopes[0].y = 0.0; slopes[1].x = slopes[1].y = 0.0; Coord *begin,*end; spline.ps = 0; if(!Proutespline (barriers, n_barriers, line, slopes, &spline)) { begin = reinterpret_cast<Coord*>(spline.ps); end = begin+spline.pn; unclipped.degree = 3; } else { begin = reinterpret_cast<Coord*>(line.ps); end = begin+line.pn; unclipped.degree = 1; } unclipped.clear(); unclipped.insert(unclipped.begin(),begin,end); // free(spline.ps); // oh right, globals, good. free(barriers); free(line.ps); } if(unclipped.empty()) { unclipped.resize(4); unclipped[0] = tg.pos; unclipped[3] = hg.pos; if (e->tail != e->head) { Coord d = (unclipped[3] - unclipped[0])/3.0; unclipped[1] = unclipped[0]+d; unclipped[2] = unclipped[3]-d; } else { /* self arc */ Coord d(tg.region.boundary.Width()/2.0+.66 * SEP,0.0); unclipped[1] = unclipped[2] = unclipped[0]+d; unclipped[1].y += d.x; unclipped[2].y -= d.x; } } gd<EdgeGeom>(e).pos.ClipEndpoints(unclipped,tg.pos,eg.tailClipped?&tg.region:0, hg.pos,eg.headClipped?&hg.region:0); changeQ.ModEdge(e,DG_UPD_MOVE); } }
glm::vec2 Line::getNormal(const Line& line) { return line.getNormal(); }
bool Triangle::Intersects( const Line& l, bool TwoSided ) const { return l.Intersects( *this, TwoSided ); }
void Line::setLine(const Line& line) { setLine(line.getPoint1(), line.getPoint2()); }
Line::Line(const Line& line) throw(Exception::FatalError) { setLine(line.getPoint1(), line.getPoint2()); }
void Fractal_Element::AddLine(Line newLine) { m_lines.push_back(newLine); m_baseline.SetPosition(m_lines[0].GetStart(), newLine.GetFinish()); }
//void LineGroup::GetRawLines_(vector<cv::Vec4i> detected_lines) void LineGroup::GetRawLines(int dim, ntuple_list detected_lines) { /*** for (int i=0; i< detected_lines.size(); i++) { cv::Vec4d detected_lines_line = detected_lines[i]; CvPoint start_pt = cvPoint((int)detected_lines_line[0],(int)detected_lines_line[1]); CvPoint end_pt = cvPoint((int)detected_lines_line[2],(int)detected_lines_line[3]); Line target = Line(start_pt, end_pt); bool sorted = false; if(target.length <= length_threshold) continue; if (line_groups.size() == 0) { line_groups.push_back(vector<Line>()); line_groups[0].push_back(target); } else { for(int j=0; j< line_groups.size();j++) { vector<Line> group = line_groups[j]; for(int k=0; k < group.size(); k ++) { Line sorted_line = group[k]; if (abs(sorted_line.Get_theta() - target.Get_theta()) <= 0.12 || abs(abs(sorted_line.Get_theta() - target.Get_theta()) - Pi) < 0.12) { if (abs(sorted_line.Get_distance() - target.Get_distance()) <= 35/2) { line_groups[j].push_back(target); sorted = true; break; } } } if (sorted) break; } if (!sorted) { vector<Line> temp = vector<Line>(); temp.push_back(target); line_groups.push_back(temp); } } } ****/ for(int i=0; i< detected_lines->size; i++) { CvPoint start_pt = cvPoint((int)detected_lines->values[i*dim+0],(int)detected_lines->values[i*dim+1]); CvPoint end_pt = cvPoint((int)detected_lines->values[i*dim+2],(int)detected_lines->values[i*dim+3]); Line target = Line(start_pt, end_pt); bool sorted = false; if(target.length <= length_threshold) continue; if (line_groups.size() == 0) { line_groups.push_back(vector<Line>()); line_groups[0].push_back(target); } else { for(int j=0; j< line_groups.size();j++) { vector<Line> group = line_groups[j]; for(int k=0; k < group.size(); k ++) { Line sorted_line = group[k]; if (abs(sorted_line.Get_theta() - target.Get_theta()) <= 0.12 || abs(abs(sorted_line.Get_theta() - target.Get_theta()) - Pi) < 0.12) { if (abs(sorted_line.Get_distance() - target.Get_distance()) <= 35/2) { line_groups[j].push_back(target); sorted = true; break; } } } if (sorted) break; } if (!sorted) { vector<Line> temp = vector<Line>(); temp.push_back(target); line_groups.push_back(temp); } } } }
void draw_line(cairo_t* cr, Line const& l) { double angle = l.angle(); draw_segment(cr, l.origin(), angle, m_length); draw_segment(cr, l.origin(), angle, -m_length); }
Line::Line(const Line &other) { p_a = other.aVec(); p_b = other.bVec(); p_c = other.cVec(); p_is_tagged = other.tagged(); p_verts_computed = false; p_offset_a = other.offsetA(); p_offset_b = other.offsetB(); p_comment = other.comment(); p_position_a = other.positionA(); p_position_b = other.positionB(); p_prism_side_a = other.prismSideA(); p_prism_side_b = other.prismSideB(); p_vertices.set(3, 10, 0); computePrism(); computeVertices(); }
bool Line::operator==(const Line& other) const { return ( ((other.getStartpoint() == mStartpoint) && (other.getEndpoint() == mEndpoint)) || (other.getStartpoint() == mEndpoint) && (other.getEndpoint() == mStartpoint)); }
Line::Line(const Line &se){ _size = se.size(); _data = new char[_size]; Line::memcpy(_data, se._data, _size); }
/* * Calculate some line info */ void Line::someInfo(bool isMoving, bool clear) { const int buflen = 100; int i; // counter int num_points; // number of data points underneath this line float *pdata; // pointer to image data (intensities) if (isMoving && getReal("aipInfoUpdateOnMove", 0) == 0) { return; // Don't update while still dragging ROI } if (firstTime) { deleteOldFiles(baseFilename); firstTime = false; } // Do not do anything if we are not the active ROI //if (RoiManager::get()->getFirstActive() != this) { //return; //} // Remember that we are the line to update if (clear) { RoiManager::infoLine = NULL; } else { RoiManager::infoLine = this; } setReal("aipLineInfoNumber", getRoiNumber(), true); spImgInfo_t img = pOwnerFrame->getFirstImage(); spDataInfo_t di = img->getDataInfo(); // Calculate and print out the line length double wd = di->getSpan(0); double ht = di->getSpan(1); double xscale = wd / di->getFast(); double yscale = ht / di->getMedium(); double lenx = pntData->coords[1].x - pntData->coords[0].x; double lenxcm = lenx * xscale; double leny = pntData->coords[1].y - pntData->coords[0].y; double lenycm = leny * yscale; double line_len = (double) sqrt((lenxcm*lenxcm) + (lenycm*lenycm)); char buf[buflen]; if (clear) { sprintf(buf, "Length:"); } else { sprintf(buf, "Length: %.3f cm", line_len); } if (strcmp(buf, lengthStr)) { strcpy(lengthStr, buf); setString("aipProfileLengthMsg", buf, true); } // Print the line end coords. if (clear) { sprintf(buf, "Start:"); } else { sprintf(buf, "Start: (%.2f, %.2f)", pntData->coords[0].x, pntData->coords[0].y); } if (strcmp(buf, startStr)) { strcpy(startStr, buf); setString("aipProfileDataCoordsStartMsg", buf, true); } if (clear) { sprintf(buf, "End:"); } else { sprintf(buf, "End: (%.2f, %.2f)", pntData->coords[1].x, pntData->coords[1].y); } if (strcmp(buf, endStr)) { strcpy(endStr, buf); setString("aipProfileDataCoordsEndMsg", buf, true); } int x0 = (int)pntData->coords[0].x; int x1 = (int)pntData->coords[1].x; int y0 = (int)pntData->coords[0].y; int y1 = (int)pntData->coords[1].y; num_points = abs(x1 - x0); if (abs(y1 - y0) > num_points ) { num_points = abs(y1 - y0); } num_points++; float *project = 0; string ylabel = "Intensity"; showMIP = getReal("aipProfileMIP", 0) != 0; if (!clear && showMIP == false) { project = new float[num_points]; for (pdata=firstPixel(), i=0; pdata && i<num_points; pdata=nextPixel()) { project[i++] = *pdata; } } else if (!clear && !isMoving) { // showMIP == true ylabel = "MIP"; // Increase number of points, so we don't miss any pixels. num_points *= 2; project = new float[num_points]; // Step through "num_points" equally spaced points along the line. Dpoint orig; Dpoint slope; Dpoint clip[2]; Dpoint ends[2]; float dx = lenx / (num_points - 1); float dy = leny / (num_points - 1); orig.x = pntData->coords[0].x; orig.y = pntData->coords[0].y; slope.x = -lenycm / xscale; // Slope of normal to the line slope.y = lenxcm / yscale; // in pixel units. clip[0].x = clip[0].y = 0; clip[1].x = di->getFast() - 1; clip[1].y = di->getMedium() - 1; float t; for (i=0; i<num_points; i++, orig.x += dx, orig.y += dy) { // Erect a normal to the line at this (orig) location that // just fits in the data space. The slope of the normal is // (-lenx/leny). The following routine returns the endpoints // of the required line. extend_line(orig, // A point on the line slope, // Slope of the line clip, // Clipping corners ends); // Returns endpoints // Find the maximum value along the line. Line *line = new Line(ends[0], ends[1]); line->pOwnerFrame = pOwnerFrame; t = *(pdata = line->firstPixel()); for (; pdata; pdata=line->nextPixel()) { if (*pdata > t) { t = *pdata; } } project[i] = t; delete line; } } drawProfile(project, num_points, line_len, ylabel); delete[] project; }
bool Line::parallel_to(const Line &line) const { return this->parallel_to(line.direction()); }
Intersection Sphere::getIntersection(const Line& line, double minDist, double maxDist) { Intersection intersection; double b = 2 * (line.dx().x()*(line.x0().x() - center().x()) + line.dx().y()*(line.x0().y() - center().y()) + line.dx().z()*(line.x0().z() - center().z())); double c = (line.x0().x() - center().x())*(line.x0().x() - center().x()) + (line.x0().y() - center().y())*(line.x0().y() - center().y()) + (line.x0().z() - center().z())*(line.x0().z() - center().z()) - radius()*radius(); double delta = b * b - 4 * c; double t0, t1, t = -1; if (delta < 0) { return intersection; } if (delta == 0){ t0 = (-1 * b + sqrt(delta)) / 2.0; if (t0 >= 0){ t = t0; } } else { t0 = (-1 * b + sqrt(delta)) / 2.0; t1 = (-1 * b - sqrt(delta)) / 2.0; if (t0 < t1){ t = t0; } else { t = t1; } } if (t >= minDist && t <= maxDist) { Intersection inter(true, *this, line, t); return inter; } return intersection; }
void LineManager::pushSheepIntoLine(int _line,SheepBlack* _sheep) { Line* line = this->getLine(_line); line->pushDequeBlack(_sheep); }
bool Rectangle::Intersects(const Line& line) const { return line.Intersects(*this); }
void LineManager::eraseSheepIntoLine(int _line,SheepBlack* _sheep) { Line* line = this->getLine(_line); line->eraseDequeBlack(_sheep); }
void ColoredCubeApp::initApp() { D3DApp::initApp(); audio->playCue(MAIN_TRACK); srand(time(0)); left = Vector3(1,0,0); right = Vector3(-1,0,0); forward = Vector3(0,0,-1); back = Vector3(0,0,1); up = Vector3(0,1,0); down = Vector3(0,-1,0); zero = Vector3(0,0,0); whiteBox.init(md3dDevice, 1.0f, WHITE); redBox.init(md3dDevice, 1.0f, RED); blueBox.init(md3dDevice, 1.0f, BLUE); greenBox.init(md3dDevice, 1.0f, GREEN); crimBox.init(md3dDevice, 0.8f, CRIMSON); dRedBox.init(md3dDevice, 0.8f, DARKRED); dBlueBox.init(md3dDevice, 0.25f, DARKBLUE); line.init(md3dDevice, 10.0f, GREEN); ////// New Stuff added by Steve ////// gLine.init(md3dDevice, 10.0f, GREEN); rLine.init(md3dDevice, 10.0f, RED); bLine.init(md3dDevice, 10.0f, BLUE); xLine.init(&rLine, Vector3(0,0,0), 10); xLine.setPosition(Vector3(0,0,0)); yLine.init(&gLine, Vector3(0,0,0), 10); yLine.setPosition(Vector3(0,0,0)); yLine.setRotationZ(ToRadian(90)); zLine.init(&bLine, Vector3(0,0,0), 10); zLine.setPosition(Vector3(0,0,0)); zLine.setRotationY(ToRadian(90)); numberOfObstacles = 50; float obstacleScale = 2.5f; float playerScale = 2.67f; Vector3 oScale(obstacleScale, obstacleScale, obstacleScale); Vector3 pScale(playerScale, playerScale, playerScale); playerBox.init(md3dDevice, playerScale, WHITE); player.init(&playerBox, sqrt(playerScale * 2.0f), Vector3(0, 2, 0), Vector3(0, 0, 0), 10, pScale, audio); player.linkInput(input); int posZ = 0; int posX = 0; int chance = 0; int r = 0; float floorSpeed = floor.getSpeed(); for (int i=0; i<numberOfObstacles; ++i) { Box* box = new Box(); box->init(md3dDevice, obstacleScale, GREEN); obstacleBoxes.push_back(box); Obstacle o; o.init(box, sqrt(5.0f), Vector3(0,0,200), Vector3(0,0,-1), 0, Vector3(oScale)); o.setInActive(); obstacles.push_back(o); } ///Set obstacle cluster variables clusterSize = 1; clusterSizeVariation = 3; clusterSeparation = 100; cubeSeparation = 30; lineJiggle = 3; cubeJiggle = 3; clusterJiggle = 10; floorMovement = 0.0f; //Other floor variables floorClusterCounter = 0; floorClusterThreshold = 7; floorSpeedIncrease = 5; //New spectrum HUD by Andy specHudBox[0].init(md3dDevice, .5f, 1.0f, 1.0f, RED, YELLOW); specHudBox[1].init(md3dDevice, .5f, 1.0f, 1.0f, YELLOW, GREEN); specHudBox[2].init(md3dDevice, .5f, 1.0f, 1.0f, GREEN, CYAN); specHudBox[3].init(md3dDevice, .5f, 1.0f, 1.0f, CYAN, BLUE); specHudBox[4].init(md3dDevice, .5f, 1.0f, 1.0f, BLUE, MAGENTA); specHudBox[5].init(md3dDevice, .5f, 1.0f, 1.0f, MAGENTA, RED); cursorBox.init(md3dDevice, .15f, 1.0f, .75f, BLACK, BLACK); Vector3 specPos = Vector3(11.0f, 25.0f, -5.0f); spectrum[0].init(&specHudBox[0], 1.0f,specPos + Vector3(0.0f,0.0f,0.0f), Vector3(0.0f,0.0f,0.0f), 0, Vector3(0.0f,0.0f,0.0f)); spectrum[1].init(&specHudBox[1], 1.0f,specPos + Vector3(2.0f,0.0f,0.0f), Vector3(0.0f,0.0f,0.0f), 0, Vector3(0.0f,0.0f,0.0f)); spectrum[2].init(&specHudBox[2], 1.0f,specPos + Vector3(4.0f,0.0f,0.0f), Vector3(0.0f,0.0f,0.0f), 0, Vector3(0.0f,0.0f,0.0f)); spectrum[3].init(&specHudBox[3], 1.0f,specPos + Vector3(6.0f,0.0f,0.0f), Vector3(0.0f,0.0f,0.0f), 0, Vector3(0.0f,0.0f,0.0f)); spectrum[4].init(&specHudBox[4], 1.0f,specPos + Vector3(8.0f,0.0f,0.0f), Vector3(0.0f,0.0f,0.0f), 0, Vector3(0.0f,0.0f,0.0f)); spectrum[5].init(&specHudBox[5], 1.0f,specPos + Vector3(10.0f,0.0f,0.0f), Vector3(0.0f,0.0f,0.0f), 0, Vector3(0.0f,0.0f,0.0f)); cursor.init(&cursorBox,1.0f,specPos + Vector3(-.80f, -1.0f, 0.0f), Vector3(0.0f,0.0f,0.0f), 0, Vector3(0.0f,0.0f,0.0f)); gameObject1.init(&whiteBox, sqrt(2.0f), Vector3(-10,0,0), Vector3(0,0,0), 0,Vector3(2,2,2)); gameObject2.init(&redBox, sqrt(2.0f), Vector3(4,0,0), Vector3(0,0,0), 0,Vector3(2,2,2)); gameObject3.init(&redBox, sqrt(2.0f), Vector3(-4,0,0), Vector3(0,0,0), 0,Vector3(2,2,2)); floor.init(md3dDevice); gameOver = false; activeMessage = false; messageTimer = 0.0f; //init lights - using pointlights lightType = 1; numberOfLights = 1; for (int i=0; i<numberOfLights; ++i) { Light l; l.pos = Vector3(0, 50, -17); l.ambient = Color(0.67f, 0.67f, 0.67f); l.diffuse = Color(1.0f, 1.0f, 1.0f); l.specular = Color(1.0f, 1.0f, 1.0f); l.att.x = 1.5f; l.att.y = 0.0f; l.att.z = 0.0f; l.range = 97.0f; lights.push_back(l); } buildFX(); buildVertexLayouts(); }
int MatFinder::runFinderOnCurrentPosition() { Board::Side sideToMove = cb_->getActiveSide(); Utils::output("Starting board is :\n" + cb_->to_string() + "\n"); Utils::output("Doing some basic evaluation on submitted position...\n"); sendCurrentPositionToEngine(); lines_.assign(Options::getMaxLines(), Line::emptyLine); sendToEngine("go depth " + to_string(Options::getPlayforMovetime())); waitBestmove(); Utils::output("Evaluation is :\n"); Utils::output(getPrettyLines()); //TODO: check if (!lines_[0].empty()) { Side winning; if ((lines_[0].getEval() < 0 && sideToMove == Side::WHITE) || (lines_[0].getEval() > 0 && sideToMove == Side::BLACK)) winning = Side::BLACK; else winning = Side::WHITE; engine_play_for_ = (winning == Side::WHITE)? Side::BLACK:Side::WHITE; } Utils::output("Engine will play for : " + Board::to_string(engine_play_for_) + "\n"); //Main loop while (true) { Line bestLine; Side active = cb_->getActiveSide(); Utils::output("[" + Board::to_string(active) + "] Depth " + to_string(addedMoves_) + "\n"); sendCurrentPositionToEngine(); Utils::output(cb_->to_string(), 2); //Thinking according to the side the engine play for int moveTime = (active == engine_play_for_ || !addedMoves_) ? Options::getPlayforMovetime() : Options::getPlayagainstMovetime(); //Compute optimal multipv int pv = updateMultiPV(); //Scaling moveTime //According to number of lines //moveTime = (int)(moveTime * ((float) // ((float)pv/(float)Options::getMaxLines()) // )); //if (moveTime <= 600) // moveTime = 600; //Acccording to depth //moveTime += 10 * addedMoves_; //Initialize vector with empty lines lines_.assign(Options::getMaxLines(), Line::emptyLine); //Increase movetime with depth sendToEngine("go depth " + to_string(moveTime)); Utils::output("[" + Board::to_string(active) + "] Thinking... (" + to_string(moveTime) + ")\n", 1); //Wait for engine to finish thinking waitBestmove(); Utils::output(getPrettyLines(), 2); bestLine = getBestLine(); if (bestLine.empty() || bestLine.isMat() || fabs(bestLine.getEval()) > Options::getMateEquiv()) { //Handle the case where we should backtrack if (addedMoves_ > 0) { Utils::output("\tBacktracking " + cb_->getUciMoves().back() + " (addedMove#" + to_string(addedMoves_) + ")\n"); /* * We did a "mistake" : a line previously unbalanced is now a * draw, we should better the backtracking by, for example, * increasing attacking time */ if (bestLine.empty()) Utils::output("\n\n\n\n DEFENDER SURVIVED \n\n\n\n ", 1); //Remove opposite side previous move addedMoves_--; cb_->undoMove(); if (active == engine_play_for_) { //Remove our previous move if we had one, since the //mat is "recorded" by engine //(not the case if starting side is not the side //the engine play for) if (addedMoves_ > 0) { addedMoves_--; cb_->undoMove(); } } continue; } else { //This is the end (hold your breath and count to ten) break; } } //If we are here, we just need to handle the next move Utils::output("[" + Board::to_string(active) + "] Chosen line : \n", 1); Utils::output("\t" + getPrettyLine(bestLine, Options::movesDisplayed) + "\n", 1); string next = bestLine.firstMove(); Utils::output("\tNext move is " + next + "\n", 3); addedMoves_++; cb_->uciApplyMove(next); } //Display info at the end of computation Utils::output("[End] Finder is done. Starting board was : \n"); Utils::output(cb_->to_string() + "\n"); if (engine_play_for_ == sideToMove) Utils::output("All lines should now be draw or mat :\n"); else Utils::output("Best line should be mat or draw.\n"); Utils::output(getPrettyLines()); Utils::output("[End] Full best line is : \n"); Utils::output("[End] " + getPrettyLine(lines_[0]) + "\n"); Utils::output("[End] " + Utils::listToString(lines_[0].getMoves()) + "\n"); return 0; }
//------------------------------------------------------------------------------------- Polygon shclip(Polygon argp) { // Use Sutherland-Hodgman Algorithm to clip the polygon. // Clip edges of each polygon vector<Point> vecbuff; vector<Point> vecp = argp.getparr(); Point buffp1, buffp2; Line buffl; int x1; int y1; int x2; int y2; // Clipping edge: x=a if (vecp.size() >= 2) { // Due to the for loop setting, we need to use a different method if vecp.size<2. if (a <= vecp[0].getx()) { // S-h Algorithm preprarition: If first point is inside, add it. vecbuff.push_back(argp.getp(0)); } for (int i = 0; i < vecp.size()-1; i++) { buffp1 = vecp[i]; buffp2 = vecp[i+1]; x1 = buffp1.getx(); x2 = buffp2.getx(); if (a<=x1 && a<=x2) { // S-h Algorithm case 1 vecbuff.push_back(buffp2); }else if (a<=x1 && x2<a) { // S-h Algorithm case 2 buffl.setp(buffp1, buffp2); int ya = buffl.cal_inter_wlr(a).gety(); buffp2.set(a, ya); if (buffp1 != buffp2) { // This part is to avoid pushing consecutive same vertices into one polygon. vecbuff.push_back(buffp2); } }else if (x1<a && x2>=a) { // S-h Algorithm case 4 buffl.setp(buffp1, buffp2); int ya = buffl.cal_inter_wlr(a).gety(); buffp1.set(a, ya); if (buffp1 != buffp2) { // Avoiding pushing consecutive same vertices into one polygon vecbuff.push_back(buffp1); } vecbuff.push_back(buffp2); } // else: S-h Algorithm case 3, just ignore } vecp.clear(); vecp = vecbuff; vecbuff.clear(); if (vecp.back() != vecp[0]) { vecp.push_back(vecp[0]); } }else vecp.clear(); // Clipping edge: y=b if (vecp.size() >= 2) { // Due to the for loop setting, we need to use a different method if vecp.size<2. if (b <= vecp[0].gety()) { // S-h Algorithm preprarition: If first point is inside, add it. vecbuff.push_back(vecp[0]); } for (int i = 0; i < vecp.size()-1; i++) { buffp1 = vecp[i]; buffp2 = vecp[i+1]; y1 = buffp1.gety(); y2 = buffp2.gety(); if (b<=y1 && b<=y2) { // S-h Algorithm case 1 vecbuff.push_back(buffp2); }else if (b<=y1 && y2<b) { // S-h Algorithm case 2 buffl.setp(buffp1, buffp2); int xb = buffl.cal_inter_wtb(b).getx(); buffp2.set(xb, b); if (buffp1 != buffp2) { vecbuff.push_back(buffp2); } }else if (y1<b && b<=y2) { // S-h Algorithm case 4 buffl.setp(buffp1, buffp2); int xb = buffl.cal_inter_wtb(b).getx() ; buffp1.set(xb, b); if (buffp1 != buffp2) { vecbuff.push_back(buffp1); } vecbuff.push_back(buffp2); } // else: S-h Algorithm case 3, just ignore } vecp.clear(); vecp = vecbuff; vecbuff.clear(); if (vecp.back() != vecp[0]) { vecp.push_back(vecp[0]); } } else vecp.clear(); // Clipping edge: x=c if (vecp.size() >= 2) { // Due to the for loop setting, we need to use a different method if vecp.size<2. if (vecp[0].getx() <= c) { // S-h Algorithm preprarition: If first point is inside, add it. vecbuff.push_back(vecp[0]); } for (int i = 0; i < vecp.size()-1; i++) { buffp1 = vecp[i]; buffp2 = vecp[i+1]; x1 = buffp1.getx(); x2 = buffp2.getx(); if (x1<=c && x2<=c) { // S-h Algorithm case 1 vecbuff.push_back(buffp2); }else if (x1<=c && c<x2) { // S-h Algorithm case 2 buffl.setp(buffp1, buffp2); int yc = buffl.cal_inter_wlr(c).gety(); buffp2.set(c, yc); if (buffp1 != buffp2) { vecbuff.push_back(buffp2); } }else if (c<x1 && x2<=c) { // S-h Algorithm case 4 buffl.setp(buffp1, buffp2); int yc = buffl.cal_inter_wlr(c).gety(); buffp1.set(c, yc); if (buffp1 != buffp2) { vecbuff.push_back(buffp1); } vecbuff.push_back(buffp2); } // else: S-h Algorithm case 3, just ignore } vecp.clear(); vecp = vecbuff; vecbuff.clear(); if (vecp.back() != vecp[0]) { vecp.push_back(vecp[0]); } }else vecp.clear(); // Clipping edge: y=d if (vecp.size() >= 2) { if (vecp[0].gety() <= d) { // S-h Algorithm preprarition: If first point is inside, add it. vecbuff.push_back(vecp[0]); } for (int i = 0; i < vecp.size()-1; i++) { buffp1 = vecp[i]; buffp2 = vecp[i+1]; y1 = buffp1.gety(); y2 = buffp2.gety(); if (y1<=d && y2<=d) { // S-h Algorithm case 1 vecbuff.push_back(buffp2); }else if (y1<=d && d<y2) { // S-h Algorithm case 2 buffl.setp(buffp1, buffp2); int xd = buffl.cal_inter_wtb(d).getx(); buffp2.set(xd, d); if (buffp1 != buffp2) { vecbuff.push_back(buffp2); } }else if (d<y1 && y2<=d) { // S-h Algorithm case 4 buffl.setp(buffp1, buffp2); int xd = buffl.cal_inter_wtb(d).getx(); buffp1.set(xd, d); if (buffp1 != buffp2) { vecbuff.push_back(buffp1); } vecbuff.push_back(buffp2); } // else: S-h Algorithm case 3, just ignore } vecp.clear(); vecp = vecbuff; vecbuff.clear(); if (vecp.back() != vecp[0]) { vecp.push_back(vecp[0]); } }else vecp.clear(); argp.setp(vecp); vecp.clear(); return argp; }
Point3D::Point3D(Line a , Line b) { double m = (a.getParallel().getV1()*(b.getPoint().getY() - a.getPoint().getY()) + a.getParallel().getV2()*(a.getPoint().getX() - b.getPoint().getX()))/ (a.getParallel().getV2()*b.getParallel().getV1() - a.getParallel().getV1()*b.getParallel().getV2()); x = b.getPoint().getX() + m*b.getParallel().getV1(); y = b.getPoint().getY() + m*b.getParallel().getV2(); z = b.getPoint().getZ() + m*b.getParallel().getV3(); }
// react to keys void keyboard(unsigned char k, int x, int y) { switch(k) { case 27: { OSG::osgExit(); exit(0); } break; case ' ': // send a ray through the clicked pixel /* Intersection testing for rays is done using an IntersectAction. The ray itself is calculated by the SimpleSceneManager, given the clicked pixel. It needs to be set up with the line that is to be intersected. A line is a semi-infinite ray which has a starting point and a direction, and extends in the direction to infinity. To do the actual test the Action's apply() method is used. The results can be received from the Action. The main difference is if something was hit or not, which is returned in didHit(). If an intersection did occur, the other data elements are valid, otherwise they are undefined. The information that is stored in the action is the object which was hit, the triangle of the object that was hit (in the form of its index) and the actual hit position. */ { Line l; l = mgr->calcViewRay(x, y); std::cerr << "From " << l.getPosition () << ", dir " << l.getDirection() << std::endl; IntersectAction *act = IntersectAction::create(); act->setLine(l); act->apply(fileroot); beginEditCP(isectPoints); isectPoints->setValue(l.getPosition(), 0); isectPoints->setValue(l.getPosition() + l.getDirection(), 1); // did we hit something? if (act->didHit()) { // yes!! print and highlight it std::cerr << " object " << act->getHitObject () << " tri " << act->getHitTriangle() << " at " << act->getHitPoint (); mgr->setHighlight(act->getHitObject()); // stop the ray on the hit surface Pnt3f is = l.getPosition() + l.getDirection() * act->getHitT(); isectPoints->setValue(is, 1); // find the triangle that was hit TriangleIterator it(act->getHitObject()); it.seek(act->getHitTriangle()); // Draw its normal at the intersection point isectPoints->setValue(is, 2); isectPoints->setValue(is + act->getHitNormal() * 5, 3); // calculate its vertex positions in world space Matrix m; act->getHitObject()->getToWorld(m); // and turn them into a triangle Pnt3f p = it.getPosition(0); m.mult(p, p); isectPoints->setValue(p, 4); p = it.getPosition(1); m.mult(p, p); isectPoints->setValue(p, 5); p = it.getPosition(2); m.mult(p, p); isectPoints->setValue(p, 6); } else { // no, get rid of the triangle and highlight. isectPoints->setValue(Pnt3f(0,0,0), 2); isectPoints->setValue(Pnt3f(0,0,0), 3); isectPoints->setValue(Pnt3f(0,0,0), 4); mgr->setHighlight(NullFC); } endEditCP(isectPoints); // free the action delete act; // the geometry won't notice automatically, tell it that the // points changed beginEditCP(testgeocore, Geometry::PositionsFieldMask); endEditCP (testgeocore, Geometry::PositionsFieldMask); std::cerr << std::endl; glutPostRedisplay(); } break; } }