bool Foam::triangleFuncs::intersect
(
    const point& va0,
    const point& va10,
    const point& va20,

    const point& vb0,
    const point& vb10,
    const point& vb20,

    point& pInter0,
    point& pInter1
)
{
    // Get triangle normals
    vector na = va10 ^ va20;
    na/mag(na);

    vector nb = vb10 ^ vb20;
    nb/mag(nb);

    // Calculate intersection of triangle a with plane of b
    point planeB0;
    point planeB1;
    if (!intersect(va0, va10, va20, vb0, nb, planeB0, planeB1))
    {
        return false;
    }

    //       ,,  triangle b with plane of a
    point planeA0;
    point planeA1;
    if (!intersect(vb0, vb10, vb20, va0, na, planeA0, planeA1))
    {
        return false;
    }

    // Now check if intersections overlap (w.r.t. intersection of the two
    // planes)

    vector intersection(na ^ nb);

    scalar coordB0 = planeB0 & intersection;
    scalar coordB1 = planeB1 & intersection;

    scalar coordA0 = planeA0 & intersection;
    scalar coordA1 = planeA1 & intersection;

    // Put information in indexable form for sorting.
    List<point*> pts(4);
    boolList isFromB(4);
    SortableList<scalar> sortCoords(4);

    pts[0] = &planeB0;
    isFromB[0] = true;
    sortCoords[0] = coordB0;

    pts[1] = &planeB1;
    isFromB[1] = true;
    sortCoords[1] = coordB1;

    pts[2] = &planeA0;
    isFromB[2] = false;
    sortCoords[2] = coordA0;

    pts[3] = &planeA1;
    isFromB[3] = false;
    sortCoords[3] = coordA1;

    sortCoords.sort();

    const labelList& indices = sortCoords.indices();

    if (isFromB[indices[0]] == isFromB[indices[1]])
    {
        // Entry 0 and 1 are of same region (both a or both b). Hence that
        // region does not overlap.
        return false;
    }
    else
    {
        // Different type. Start of overlap at indices[1], end at indices[2]
        pInter0 = *pts[indices[1]];
        pInter1 = *pts[indices[2]];

        return true;
    }
}
bool QgsGeometrySelfIntersectionCheckError::isEqual( QgsGeometryCheckError *other ) const
{
  return QgsGeometryCheckError::isEqual( other ) &&
         static_cast<QgsGeometrySelfIntersectionCheckError *>( other )->intersection().segment1 == intersection().segment1 &&
         static_cast<QgsGeometrySelfIntersectionCheckError *>( other )->intersection().segment2 == intersection().segment2;
}
Esempio n. 3
0
bool intersects(const std::vector<tpoint>& lhs, const std::vector<tpoint>& rhs)
{
	return !intersection(lhs, rhs).empty();
}
FloatRect SourceGraphic::determineAbsolutePaintRect(const FloatRect& requestedRect)
{
    FloatRect srcRect = intersection(m_sourceRect, requestedRect);
    addAbsolutePaintRect(srcRect);
    return srcRect;
}
Esempio n. 5
0
 int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
     return  (C - A) * (D - B) + (G - E) * (H - F) - 
             max(intersection(A, C, E, G), intersection(E, G, A, C)) 
             * 
             max(intersection(B, D, F, H), intersection(F, H, B, D));
 }
Esempio n. 6
0
std::pair<Vect2,double> VectFuns::intersection(const Vect2& so1, const Vect2& so2, double dto, const Vect2& si1, const Vect2& si2) {
	Vect2 vo = so2.Sub(so1).Scal(1/dto);
	Vect2 vi = si2.Sub(si1).Scal(1/dto);      // its ok to use any time here,  all times are relative to so
	return intersection(so1,vo,si1,vi);
}
Esempio n. 7
0
 BitWord& operator-=(const BitWord& bw) 
 { 
  BitWord intersection(*this);
  return (*this) ^= (intersection &= bw);
 };
Esempio n. 8
0
CoordinateSequence*
LineSegment::closestPoints(const LineSegment& line)
{
	// test for intersection
	Coordinate intPt;
	if ( intersection(line, intPt) )
	{
		CoordinateSequence *cl=new CoordinateArraySequence(new vector<Coordinate>(2, intPt));
		return cl;
	}

	/*
	 * if no intersection closest pair contains at least one endpoint.
	 * Test each endpoint in turn.
	 */
	CoordinateSequence *closestPt=new CoordinateArraySequence(2);
	//vector<Coordinate> *cv = new vector<Coordinate>(2);

	double minDistance=DoubleMax;
	double dist;

	Coordinate close00;
	closestPoint(line.p0, close00);
	minDistance = close00.distance(line.p0);

	closestPt->setAt(close00, 0);
	closestPt->setAt(line.p0, 1);

	Coordinate close01;
	closestPoint(line.p1, close01);
	dist = close01.distance(line.p1);
	if (dist < minDistance) {
		minDistance = dist;
		closestPt->setAt(close01,0);
		closestPt->setAt(line.p1,1);
		//(*cv)[0] = close01;
		//(*cv)[1] = line.p1; 
	}

	Coordinate close10;
	line.closestPoint(p0, close10);
	dist = close10.distance(p0);
		if (dist < minDistance) {
		minDistance = dist;
		closestPt->setAt(p0,0);
		closestPt->setAt(close10,1);
		//(*cv)[0] = p0;
		//(*cv)[1] = close10;
	}

	Coordinate close11;
	line.closestPoint(p1, close11);
	dist = close11.distance(p1);
	if (dist < minDistance) {
		minDistance = dist;
		closestPt->setAt(p1,0);
		closestPt->setAt(close11,1);
		//(*cv)[0] = p1;
		//(*cv)[1] = *close11;
	}

	return closestPt;
}
		AURORA_CITR_FOREACH(EdgeSet, constrainedEdges, itr)
		{
			if (intersection(edge, *itr))
				return true;
		}
Esempio n. 10
0
void AngleList::makeAngles(int sides, float startAngle, float stopAngle)
{

    double twoPi = 3.14159 * 2.0;
    float twoPiInv = 1.0f / (float)twoPi;

    if (sides < 1)
        throw "number of sides not greater than zero";
    if (stopAngle <= startAngle)
        throw "stopAngle not greater than startAngle";

    if ((sides == 3 || sides == 4 || sides == 24))
    {
        startAngle *= twoPiInv;
        stopAngle *= twoPiInv;

        const Angle *sourceAngles;
        int sourceAnglesLen;
        if (sides == 3) {
            sourceAngles = (Angle *)&angles3;
            sourceAnglesLen = 4;
        } else if (sides == 4) {
            sourceAngles = (Angle *)&angles4;
            sourceAnglesLen = 5;
        } else {
        	sourceAngles = (Angle *)&angles24;
        	sourceAnglesLen = 25;
        }

        int startAngleIndex = (int)(startAngle * sides);
        int endAngleIndex = sourceAnglesLen - 1;
        if (stopAngle < 1.0f)
            endAngleIndex = (int)(stopAngle * sides) + 1;
        if (endAngleIndex == startAngleIndex)
            endAngleIndex++;

        for (int angleIndex = startAngleIndex; angleIndex < endAngleIndex + 1; angleIndex++)
        {
            angles.push_back(sourceAngles[angleIndex]);
            if (sides == 3)
                normals.push_back(normals3[angleIndex]);
            else if (sides == 4)
                normals.push_back(normals4[angleIndex]);
        }

        if (startAngle > 0.0f)
            angles[0] = interpolatePoints(startAngle, angles[0], angles[1]);

        if (stopAngle < 1.0f)
        {
            int lastAngleIndex = angles.size() - 1;
            angles[lastAngleIndex] = interpolatePoints(stopAngle, angles[lastAngleIndex - 1], angles[lastAngleIndex]);
        }
    }
    else
    {
        double stepSize = twoPi / sides;

        int startStep = (int)(startAngle / stepSize);
        double angle = stepSize * startStep;
        int step = startStep;
        double stopAngleTest = stopAngle;
        if (stopAngle < twoPi)
        {
            stopAngleTest = stepSize * ((int)(stopAngle / stepSize) + 1);
            if (stopAngleTest < stopAngle)
                stopAngleTest += stepSize;
            if (stopAngleTest > twoPi)
                stopAngleTest = twoPi;
        }

        while (angle <= stopAngleTest)
        {
            Angle newAngle;
            newAngle.angle = (float)angle;
            newAngle.X = (float)cos(angle);
            newAngle.Y = (float)sin(angle);
            angles.push_back(newAngle);
            step += 1;
            angle = stepSize * step;
        }

        if (startAngle > angles[0].angle)
        {
            Angle newAngle;
            intersection(angles[0].X, angles[0].Y, angles[1].X, angles[1].Y, 0.0f, 0.0f, (float)cos(startAngle), (float)sin(startAngle));
            newAngle.angle = startAngle;
            newAngle.X = iX;
            newAngle.Y = iY;
            angles[0] = newAngle;
        }

        int index = angles.size() - 1;
        if (stopAngle < angles[index].angle)
        {
            Angle newAngle;
            intersection(angles[index - 1].X, angles[index - 1].Y, angles[index].X, angles[index].Y, 0.0f, 0.0f, (float)cos(stopAngle), (float)sin(stopAngle));
            newAngle.angle = stopAngle;
            newAngle.X = iX;
            newAngle.Y = iY;
            angles[index] = newAngle;
        }
    }
}
Esempio n. 11
0
/** Calculate least squares baseline solution from a set of single difference
 * observations and carrier phase ambiguities.
 *
 * \param num_sdiffs Number of single difference observations
 * \param sdiffs      Set of single differenced observations, length
 *                    `num_sdiffs`, sorted by PRN
 * \param ref_ecef    The reference position in ECEF frame, for computing the
 *                    sat direction vectors
 * \param num_ambs    Number of carrier phase ambiguities
 * \param single_ambs Array of (carrier phase ambiguity, prn) pairs.
 *                    length `num_ambs`
 * \param num_used    Pointer to where to store number of satellites used in the
 *                    baseline solution
 * \param b           The output baseline in meters
 * \param disable_raim   True disables raim check/repair
 * \param raim_threshold Threshold for raim checks.
 * \return            0 on success,
 *                   -1 if there were insufficient observations to calculate the
 *                      baseline (the solution was under-constrained),
 *                   -2 if an error occurred
 */
s8 baseline_(u8 num_sdiffs, const sdiff_t *sdiffs, const double ref_ecef[3],
             u8 num_ambs, const ambiguity_t *single_ambs,
             u8 *num_used, double b[3],
             bool disable_raim, double raim_threshold)
{
  if (num_sdiffs < 4 || num_ambs < 4) {
    /* For a position solution, we need at least 4 sats. */
    return -1;
  }

  assert(sdiffs != NULL);
  assert(ref_ecef != NULL);
  assert(single_ambs != NULL);
  assert(num_used != NULL);
  assert(b != NULL);

  assert(is_set(num_ambs, sizeof(ambiguity_t), single_ambs, cmp_amb));
  assert(is_set(num_sdiffs, sizeof(sdiff_t), sdiffs, cmp_sdiff));

  assert(num_sdiffs <= MAX_CHANNELS);

  /* Could use min(num_ambs, num_sdiffs) */
  ambiguity_t intersection_ambs[num_ambs];
  sdiff_t intersection_sdiffs[num_ambs];

  s32 intersection_size = intersection(
      num_ambs,   sizeof(ambiguity_t), single_ambs, intersection_ambs,
      num_sdiffs, sizeof(sdiff_t),     sdiffs,      intersection_sdiffs,
      cmp_amb_sdiff);

  if (intersection_size < 4) {
    /* For a position solution, we need at least 4 sats. */
    return -1;
  }
  u8 num_dds = intersection_size - 1;

  /* Choose ref sat based on SNR. */
  gnss_signal_t ref_sid = choose_reference_sat(intersection_size, intersection_sdiffs);

  /* Calculate double differenced measurements. */
  sdiff_t sdiff_ref_first[intersection_size];
  u32 sdiff_ref_index = remove_element(intersection_size, sizeof(sdiff_t),
                                       intersection_sdiffs,
                                       &(sdiff_ref_first[1]),  /* New set */
                                       &ref_sid, cmp_sdiff_sid);
  memcpy(sdiff_ref_first, &intersection_sdiffs[sdiff_ref_index],
         sizeof(sdiff_t));

  double dd_meas[2 * num_dds];

  for (u32 i = 0; i < num_dds; i++) {
    dd_meas[i] =
      sdiff_ref_first[i+1].carrier_phase - sdiff_ref_first[0].carrier_phase;
    dd_meas[i + num_dds] =
      sdiff_ref_first[i+1].pseudorange - sdiff_ref_first[0].pseudorange;
  }

  double DE[num_dds * 3];
  assign_de_mtx(intersection_size, sdiff_ref_first, ref_ecef, DE);

  /* Calculate double differenced ambiguities. */
  double dd_ambs[num_dds];
  diff_ambs(ref_sid, intersection_size, intersection_ambs, dd_ambs);

  /* Compute least squares solution. */
  *num_used = intersection_size;
  return lesq_solve_raim(num_dds, dd_meas, dd_ambs, DE, b,
                         disable_raim, raim_threshold, 0, 0, 0);
}
Esempio n. 12
0
File: rect.hpp Progetto: otgaard/zap
 bool intersection(const vec2<T>& P) const { return intersection(P.x, P.y); }
Esempio n. 13
0
void RenderLayerClipper::calculateClipRects(const ClipRectsContext& clipRectsContext, ClipRects& clipRects) const
{
    if (!m_renderer->layer()->parent()) {
        // The root layer's clip rect is always infinite.
        clipRects.reset(PaintInfo::infiniteRect());
        return;
    }

    ClipRectsType clipRectsType = clipRectsContext.clipRectsType;
    bool useCached = clipRectsType != TemporaryClipRects;

    // For transformed layers, the root layer was shifted to be us, so there is no need to
    // examine the parent. We want to cache clip rects with us as the root.
    RenderLayer* parentLayer = clipRectsContext.rootLayer != m_renderer->layer() ? m_renderer->layer()->parent() : 0;

    // Ensure that our parent's clip has been calculated so that we can examine the values.
    if (parentLayer) {
        if (useCached && parentLayer->clipper().clipRects(clipRectsContext)) {
            clipRects = *parentLayer->clipper().clipRects(clipRectsContext);
        } else {
            ClipRectsContext parentContext(clipRectsContext);
            parentContext.overlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize; // FIXME: why?
            parentLayer->clipper().calculateClipRects(parentContext, clipRects);
        }
    } else {
        clipRects.reset(PaintInfo::infiniteRect());
    }

    // A fixed object is essentially the root of its containing block hierarchy, so when
    // we encounter such an object, we reset our clip rects to the fixedClipRect.
    if (m_renderer->style()->position() == FixedPosition) {
        clipRects.setPosClipRect(clipRects.fixedClipRect());
        clipRects.setOverflowClipRect(clipRects.fixedClipRect());
        clipRects.setFixed(true);
    } else if (m_renderer->style()->hasInFlowPosition()) {
        clipRects.setPosClipRect(clipRects.overflowClipRect());
    } else if (m_renderer->style()->position() == AbsolutePosition) {
        clipRects.setOverflowClipRect(clipRects.posClipRect());
    }

    // Update the clip rects that will be passed to child layers.
    if ((m_renderer->hasOverflowClip() && (clipRectsContext.respectOverflowClip == RespectOverflowClip || m_renderer->layer() != clipRectsContext.rootLayer)) || m_renderer->hasClip()) {
        // This layer establishes a clip of some kind.

        // This offset cannot use convertToLayerCoords, because sometimes our rootLayer may be across
        // some transformed layer boundary, for example, in the RenderLayerCompositor overlapMap, where
        // clipRects are needed in view space.
        LayoutPoint offset;
        offset = roundedLayoutPoint(m_renderer->localToContainerPoint(FloatPoint(), clipRectsContext.rootLayer->renderer()));
        RenderView* view = m_renderer->view();
        ASSERT(view);
        if (view && clipRects.fixed() && clipRectsContext.rootLayer->renderer() == view) {
            offset -= view->frameView()->scrollOffsetForFixedPosition();
        }

        if (m_renderer->hasOverflowClip()) {
            ClipRect newOverflowClip = toRenderBox(m_renderer)->overflowClipRect(offset, clipRectsContext.overlayScrollbarSizeRelevancy);
            if (m_renderer->style()->hasBorderRadius())
                newOverflowClip.setHasRadius(true);
            clipRects.setOverflowClipRect(intersection(newOverflowClip, clipRects.overflowClipRect()));
            if (m_renderer->isPositioned())
                clipRects.setPosClipRect(intersection(newOverflowClip, clipRects.posClipRect()));
        }
        if (m_renderer->hasClip()) {
            LayoutRect newPosClip = toRenderBox(m_renderer)->clipRect(offset);
            clipRects.setPosClipRect(intersection(newPosClip, clipRects.posClipRect()));
            clipRects.setOverflowClipRect(intersection(newPosClip, clipRects.overflowClipRect()));
            clipRects.setFixedClipRect(intersection(newPosClip, clipRects.fixedClipRect()));
        }
    }
}
Esempio n. 14
0
//--------------------------------------------------------------------------
void BoundingBoxTests::testOperations()
{
  // Check the center
  CPPUNIT_ASSERT_EQUAL(true, vector::eq(Vector3f(1.5f, 1.5f, 1.5f), a2.center()));
  CPPUNIT_ASSERT_EQUAL(true, vector::eq(Vector3f(0), a4.center()));
  Vector3f c(AABB3f::DUMMY.center());
  for (size_t i = 0_z; i < 3_z; ++i)
    {
      CPPUNIT_ASSERT_EQUAL(true, std::isnan(c[i]));
    }

  // Check volume comparaison
  CPPUNIT_ASSERT_EQUAL(1.0f, a2.volume());
  CPPUNIT_ASSERT_EQUAL(4.0f * 4.0f * 4.0f, (a2 * 4.0f).volume());
  a5 =  a2 * 4.0f;
  CPPUNIT_ASSERT_EQUAL(true, (a5 > a2));
  CPPUNIT_ASSERT_EQUAL(false, (a5 < a2));
  CPPUNIT_ASSERT_EQUAL(true, (a2 >= a3));
  CPPUNIT_ASSERT_EQUAL(true, (a2 <= a3));
  CPPUNIT_ASSERT_EQUAL(true, (a2 == a3));
  CPPUNIT_ASSERT_EQUAL(true, (a6 > a3));

  // Check if a point is contained or not to an AABB.
  CPPUNIT_ASSERT_EQUAL(true, a2.contains(Vector3f(1.5f, 1.5f, 1.5f)));
  CPPUNIT_ASSERT_EQUAL(true, a2.contains(a2.center()));
  CPPUNIT_ASSERT_EQUAL(false, a2.contains(a2.center() * 3.0f));
  CPPUNIT_ASSERT_EQUAL(true, a6.contains(a2.center() * 3.0f));

  // Box containing others
  CPPUNIT_ASSERT_EQUAL(true, a1.contains(a1));
  CPPUNIT_ASSERT_EQUAL(false, a8.contains(a1));
  CPPUNIT_ASSERT_EQUAL(true, a6.contains(a1));
  CPPUNIT_ASSERT_EQUAL(false, AABB3f(0, 1).contains(AABB3f(1, 2))); // corner case

  // Clamp
  //checkBox(clamp(a1, a1.m_bbmin, a1.m_bbmax), a1.m_bbmin, a1.m_bbmax);
  //checkBox(clamp(a1 * 4.0f, a1.m_bbmin, a1.m_bbmax), a1.m_bbmin, a1.m_bbmax);

  // Box collisions
  CPPUNIT_ASSERT_EQUAL(false, a2.collides(a4));
  CPPUNIT_ASSERT_EQUAL(true, a2.collides(AABB3f(Vector3f(2,2,2), Vector3f(3,3,3))));
  CPPUNIT_ASSERT_EQUAL(true, a6.collides(a4));

  checkBox(intersection(a3, a3), a3.m_bbmin, a3.m_bbmax);
  checkBox(merge(a3, a3), a3.m_bbmin, a3.m_bbmax);
  checkBox(intersection(a3, a6), a3.m_bbmin, a3.m_bbmax);

  checkBox(merge(a6, a6), a6.m_bbmin, a6.m_bbmax);
  checkBox(merge(a6, a3), a6.m_bbmin, a6.m_bbmax);
  checkBox(merge(a3, a6), a6.m_bbmin, a6.m_bbmax);
  checkBox(intersection(a6, a3), a3.m_bbmin, a3.m_bbmax);
  checkBox(intersection(a3, a6), a3.m_bbmin, a3.m_bbmax);
  checkBox(merge(a2, a3), a3.m_bbmin, a2.m_bbmax);

  // Try intersection with disjoint AABB.
  checkBoxDummy(intersection(a2, a3));
  checkBoxDummy(intersection(a5, a3));

  // Check intersecation at an AABB corner.
  checkBox(intersection(a7, AABB3f(0, 1)), Vector3f(1), Vector3f(1));
  checkBox(intersection(AABB3f(0, 1), AABB3f(-1, 0)), Vector3f(0), Vector3f(0));

  // AABB collisions
  CPPUNIT_ASSERT_EQUAL(true, a4.collides(a4));
  CPPUNIT_ASSERT_EQUAL(false, a4.collides(a2));
  CPPUNIT_ASSERT_EQUAL(false, a2.collides(a4));
  CPPUNIT_ASSERT_EQUAL(true, a2.collides(AABB3f(Vector3f(2,2,2), Vector3f(3,3,3))));
  CPPUNIT_ASSERT_EQUAL(true, a6.collides(a4));
  CPPUNIT_ASSERT_EQUAL(true, a4.collides(a6));

  //

  CPPUNIT_ASSERT_EQUAL(std::numeric_limits<float>::infinity(), a6.volume());
  CPPUNIT_ASSERT_EQUAL(true, vector::eq(Vector3f(std::numeric_limits<float>::infinity()),
                                        a6.size()));
}
void FrameBuffer::fillPolygon(Polygon* polygon, int yMin, int yMax){
  
  int nLine = polygon->getNLine();
  for (int yScanline = yMin; yScanline <= yMax; ++yScanline) {

    // printf("y: %d\n", yScanline);    
    // fflush(stdout);

    std::vector<intersection> intersectEdge; 
    for (int e = 0; e < nLine; ++e) {
      if (isIntersect(polygon, e, yScanline)) {
        int type = isHorizontalLine(polygon, e);
        int x;
        if (type) {
          x = getMiddleX(polygon, e);
        } else {
          x = xIntersect(polygon, e, yScanline);
        }
        intersectEdge.push_back(intersection(e, x, type));
      }
    }

    std::sort(intersectEdge.begin(), intersectEdge.end());

    std::vector<intersection>::iterator i = intersectEdge.begin(), j;

    if (i!=intersectEdge.end()) {
      while ((i+1) != intersectEdge.end()) {
        if ((((i+1)->x - i->x) < 5) &&
          (!isCriticalPoint(polygon, (*i).edge,(*(i+1)).edge, yScanline))) {
          
          i = intersectEdge.erase(i);

        } else {
          if ((i+1)->type == 1) {

            // warning: this conditional maybe cause a bug
            if ((i+2) != intersectEdge.end()) {
              if (isCriticalPoint(polygon, (*i).edge,(*(i+2)).edge, yScanline)) {
                i++;
                i = intersectEdge.erase(i);
              } else {
                i++;
                i->x = (i+1)->x;
                i++;
              }
            } else {
              i++;
            }

          } else {
            i++;
          }
        }
      }
    }


    int fillRed = polygon->getFillRed();
    int fillGreen = polygon->getFillGreen();
    int fillBlue = polygon->getFillBlue();

    for (int i = 0; i+1 < intersectEdge.size(); i+=2) {
      int e = intersectEdge[i].edge;
      for (int x = intersectEdge[i].x; x < intersectEdge[i+1].x; x++) {
        plot(x, yScanline, fillRed, fillGreen, fillBlue);
      }
    }

  }
}
QImage Triangledetection::detect(const QImage &source, const QImage &imageBase)
{
    //QImage binary = detectionContour(extraireRouge(source));
    QImage binary = detectionContour(source);
    QImage detection = binary.convertToFormat(QImage::Format_RGB888);

    QVector<QPoint> ligne = hough(detection);
    std::cout << "-> Nombre de ligne detecté : " << ligne.size() << std::endl;

    QVector<QPoint> ligne_angle0,ligne_angle60,ligne_angle120;
    QPoint inter1,inter2,inter3;
    int l1,l2,l3;



    //Avoir les lignes avec des angles pouvant appartenir à un panneau (+ ou - 1°)
    avoirLigneAngle(ligne,ligne_angle0,90,1);
    avoirLigneAngle(ligne,ligne_angle0,270,1);

    avoirLigneAngle(ligne,ligne_angle60,150,1);
    avoirLigneAngle(ligne,ligne_angle60,330,1);

    avoirLigneAngle(ligne,ligne_angle120,210,1);
    avoirLigneAngle(ligne,ligne_angle120,30,1);

    //On determine les intersections et les longueurs des segments
    for(int i=0;i<ligne_angle0.size();i++)
    {
        for(int j=0;j<ligne_angle60.size();j++)
        {
            for(int k=0;k<ligne_angle120.size();k++)
            {

                inter1 = intersection(ligne_angle0[i],ligne_angle60[j]);
                inter2 = intersection(ligne_angle60[j],ligne_angle120[k]);
                inter3 = intersection(ligne_angle120[k],ligne_angle0[i]);

                l1 = distance(inter1,inter2);
                l2 = distance(inter2,inter3);
                l3 = distance(inter3,inter1);

                //Si les distance sont les mêmes et que tous les points sont dans l'image => on a un triangle
                if(l1 == l2 && l2 == l3 && l1 > 30 && l1 < 100 && estPointImage(detection,inter1) && estPointImage(detection,inter2) && estPointImage(detection,inter3))
                {
                    Triangle a;
                    a.p1 = inter1;
                    a.p2 = inter2;
                    a.p3 = inter3;
                    liste_triangle.push_back(a);
                }
            }
        }
    }

    std::cout<<"-> Nombre de triangle detectés avant élimination des doublons : " << liste_triangle.size() << std::endl;

    //On supprime les triangle doublons
    supprimerDoublon();

    //Dessiner les triangles à l'écran
    for(int i=0;i<liste_triangle.size();i++)
        dessiner(detection,liste_triangle[i],qRgb(0,255,127));


    //Generer les images avec les cercles reconnus
    for(int i=0;i<liste_triangle.size();i++)
    {
        int minX = liste_triangle[i].p1.x();
        int minY = liste_triangle[i].p1.y();
        int maxX = liste_triangle[i].p1.x();
        int maxY = liste_triangle[i].p1.y();
        if (liste_triangle[i].p2.x()<minX) minX = liste_triangle[i].p2.x();
        if (liste_triangle[i].p2.y()<minY) minY = liste_triangle[i].p2.y();
        if (liste_triangle[i].p2.x()>maxX) maxX = liste_triangle[i].p2.x();
        if (liste_triangle[i].p2.y()>maxY) maxY = liste_triangle[i].p2.y();
        if (liste_triangle[i].p3.x()<minX) minX = liste_triangle[i].p3.x();
        if (liste_triangle[i].p3.y()<minY) minY = liste_triangle[i].p3.y();
        if (liste_triangle[i].p3.x()>maxX) maxX = liste_triangle[i].p3.x();
        if (liste_triangle[i].p3.y()>maxY) maxY = liste_triangle[i].p3.y();


        QImage BlueRoadSigns = QImage(maxX-minX, maxY-minY, QImage::Format_RGB32);

        for(int row = 0;row<maxY-minY;row++)
        {
            for (int col=0;col<maxX-minX;col++)
            {
                QColor clrCurrent(imageBase.pixel(col+minX,row+minY));

                int red = clrCurrent.red();
                int green = clrCurrent.green();
                int blue = clrCurrent.blue();

                BlueRoadSigns.setPixel(col, row, qRgb(red,green,blue));
            }
        }

        liste_TrianglesReconnu.push_back(BlueRoadSigns);
    }

    std::cout<<"-> Nombre de triangle detectés : " << liste_triangle.size() << std::endl;

    return detection;
}
Esempio n. 17
0
static bool initializeIndicator(TextIndicatorData& data, Frame& frame, const Range& range, FloatSize margin, bool indicatesCurrentSelection)
{
    Vector<FloatRect> textRects;

    // FIXME (138888): Ideally we wouldn't remove the margin in this case, but we need to
    // ensure that the indicator and indicator-with-highlight overlap precisely, and
    // we can't add a margin to the indicator-with-highlight.
    if (indicatesCurrentSelection && !(data.options & TextIndicatorOptionIncludeMarginIfRangeMatchesSelection))
        margin = FloatSize();

    FrameSelection::TextRectangleHeight textRectHeight = (data.options & TextIndicatorOptionTightlyFitContent) ? FrameSelection::TextRectangleHeight::TextHeight : FrameSelection::TextRectangleHeight::SelectionHeight;

    if ((data.options & TextIndicatorOptionUseBoundingRectAndPaintAllContentForComplexRanges) && hasNonInlineOrReplacedElements(range))
        data.options |= TextIndicatorOptionPaintAllContent;
    else {
        if (data.options & TextIndicatorOptionDoNotClipToVisibleRect)
            frame.selection().getTextRectangles(textRects, textRectHeight);
        else
            frame.selection().getClippedVisibleTextRectangles(textRects, textRectHeight);
    }

    if (textRects.isEmpty()) {
        RenderView* renderView = frame.contentRenderer();
        if (!renderView)
            return false;
        FloatRect boundingRect = range.absoluteBoundingRect();
        if (data.options & TextIndicatorOptionDoNotClipToVisibleRect)
            textRects.append(boundingRect);
        else {
            // Clip to the visible rect, just like getClippedVisibleTextRectangles does.
            // FIXME: We really want to clip to the unobscured rect in both cases, I think.
            // (this seems to work on Mac, but maybe not iOS?)
            FloatRect visibleContentRect = frame.view()->visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect);
            textRects.append(intersection(visibleContentRect, boundingRect));
        }
    }

    FloatRect textBoundingRectInRootViewCoordinates;
    FloatRect textBoundingRectInDocumentCoordinates;
    Vector<FloatRect> textRectsInRootViewCoordinates;
    for (const FloatRect& textRect : textRects) {
        FloatRect textRectInDocumentCoordinatesIncludingMargin = textRect;
        textRectInDocumentCoordinatesIncludingMargin.inflateX(margin.width());
        textRectInDocumentCoordinatesIncludingMargin.inflateY(margin.height());
        textBoundingRectInDocumentCoordinates.unite(textRectInDocumentCoordinatesIncludingMargin);

        FloatRect textRectInRootViewCoordinates = frame.view()->contentsToRootView(enclosingIntRect(textRectInDocumentCoordinatesIncludingMargin));
        textRectsInRootViewCoordinates.append(textRectInRootViewCoordinates);
        textBoundingRectInRootViewCoordinates.unite(textRectInRootViewCoordinates);
    }

    Vector<FloatRect> textRectsInBoundingRectCoordinates;
    for (auto rect : textRectsInRootViewCoordinates) {
        rect.moveBy(-textBoundingRectInRootViewCoordinates.location());
        textRectsInBoundingRectCoordinates.append(rect);
    }

    // Store the selection rect in window coordinates, to be used subsequently
    // to determine if the indicator and selection still precisely overlap.
    data.selectionRectInRootViewCoordinates = frame.view()->contentsToRootView(enclosingIntRect(frame.selection().selectionBounds()));
    data.textBoundingRectInRootViewCoordinates = textBoundingRectInRootViewCoordinates;
    data.textRectsInBoundingRectCoordinates = textRectsInBoundingRectCoordinates;

    return takeSnapshots(data, frame, enclosingIntRect(textBoundingRectInDocumentCoordinates), textRects);
}
Esempio n. 18
0
IntRect RenderWidget::windowClipRect() const
{
    return intersection(view().frameView().contentsToWindow(m_clipRect), view().frameView().windowClipRect());
}
Esempio n. 19
0
 V3d intersect(Line3d o) {
   return *intersection(o);
 }
Esempio n. 20
0
void
BridgeDetector::coverage(double angle, Polygons* coverage) const
{
    // Clone our expolygon and rotate it so that we work with vertical lines.
    ExPolygon expolygon = this->expolygon;
    expolygon.rotate(PI/2.0 - angle, Point(0,0));
    
    /*  Outset the bridge expolygon by half the amount we used for detecting anchors;
        we'll use this one to generate our trapezoids and be sure that their vertices
        are inside the anchors and not on their contours leading to false negatives. */
    ExPolygons grown;
    offset(expolygon, &grown, this->extrusion_width/2.0);
    
    // Compute trapezoids according to a vertical orientation
    Polygons trapezoids;
    for (ExPolygons::const_iterator it = grown.begin(); it != grown.end(); ++it)
        it->get_trapezoids2(&trapezoids, PI/2.0);
    
    // get anchors, convert them to Polygons and rotate them too
    Polygons anchors;
    for (ExPolygons::const_iterator anchor = this->_anchors.begin(); anchor != this->_anchors.end(); ++anchor) {
        Polygons pp = *anchor;
        for (Polygons::iterator p = pp.begin(); p != pp.end(); ++p)
            p->rotate(PI/2.0 - angle, Point(0,0));
        anchors.insert(anchors.end(), pp.begin(), pp.end());
    }
    
    Polygons covered;
    for (Polygons::const_iterator trapezoid = trapezoids.begin(); trapezoid != trapezoids.end(); ++trapezoid) {
        Lines lines = trapezoid->lines();
        Lines supported;
        intersection(lines, anchors, &supported);
        
        // not nice, we need a more robust non-numeric check
        for (size_t i = 0; i < supported.size(); ++i) {
            if (supported[i].length() < this->extrusion_width) {
                supported.erase(supported.begin() + i);
                i--;
            }
        }

        if (supported.size() >= 2) covered.push_back(*trapezoid);        
    }
    
    // merge trapezoids and rotate them back
    Polygons _coverage;
    union_(covered, &_coverage);
    for (Polygons::iterator p = _coverage.begin(); p != _coverage.end(); ++p)
        p->rotate(-(PI/2.0 - angle), Point(0,0));
    
    // intersect trapezoids with actual bridge area to remove extra margins
    // and append it to result
    intersection(_coverage, this->expolygon, coverage);
    
    /*
    if (0) {
        my @lines = map @{$_->lines}, @$trapezoids;
        $_->rotate(-(PI/2 - $angle), [0,0]) for @lines;
        
        require "Slic3r/SVG.pm";
        Slic3r::SVG::output(
            "coverage_" . rad2deg($angle) . ".svg",
            expolygons          => [$self->expolygon],
            green_expolygons    => $self->_anchors,
            red_expolygons      => $coverage,
            lines               => \@lines,
        );
    }
    */
}
Esempio n. 21
0
bool DirSet::contains(DirSet dirSet) const {
  return intersection(dirSet) == dirSet;
}
Esempio n. 22
0
bool
BridgeDetector::detect_angle()
{
    if (this->_edges.empty() || this->_anchors.empty()) return false;
    
    /*  Outset the bridge expolygon by half the amount we used for detecting anchors;
        we'll use this one to clip our test lines and be sure that their endpoints
        are inside the anchors and not on their contours leading to false negatives. */
    Polygons clip_area;
    offset(this->expolygon, &clip_area, +this->extrusion_width/2);
    
    /*  we'll now try several directions using a rudimentary visibility check:
        bridge in several directions and then sum the length of lines having both
        endpoints within anchors */
    
    // we test angles according to configured resolution
    std::vector<double> angles;
    for (int i = 0; i <= PI/this->resolution; ++i)
        angles.push_back(i * this->resolution);
    
    // we also test angles of each bridge contour
    {
        Polygons pp = this->expolygon;
        for (Polygons::const_iterator p = pp.begin(); p != pp.end(); ++p) {
            Lines lines = p->lines();
            for (Lines::const_iterator line = lines.begin(); line != lines.end(); ++line)
                angles.push_back(line->direction());
        }
    }
    
    /*  we also test angles of each open supporting edge
        (this finds the optimal angle for C-shaped supports) */
    for (Polylines::const_iterator edge = this->_edges.begin(); edge != this->_edges.end(); ++edge) {
        if (edge->first_point().coincides_with(edge->last_point())) continue;
        angles.push_back(Line(edge->first_point(), edge->last_point()).direction());
    }
    
    // remove duplicates
    double min_resolution = PI/180.0;  // 1 degree
    std::sort(angles.begin(), angles.end());
    for (size_t i = 1; i < angles.size(); ++i) {
        if (Slic3r::Geometry::directions_parallel(angles[i], angles[i-1], min_resolution)) {
            angles.erase(angles.begin() + i);
            --i;
        }
    }
    /*  compare first value with last one and remove the greatest one (PI) 
        in case they are parallel (PI, 0) */
    if (Slic3r::Geometry::directions_parallel(angles.front(), angles.back(), min_resolution))
        angles.pop_back();
    
    BridgeDirectionComparator bdcomp(this->extrusion_width);
    double line_increment = this->extrusion_width;
    bool have_coverage = false;
    for (std::vector<double>::const_iterator angle = angles.begin(); angle != angles.end(); ++angle) {
        Polygons my_clip_area = clip_area;
        ExPolygons my_anchors = this->_anchors;
        
        // rotate everything - the center point doesn't matter
        for (Polygons::iterator it = my_clip_area.begin(); it != my_clip_area.end(); ++it)
            it->rotate(-*angle, Point(0,0));
        for (ExPolygons::iterator it = my_anchors.begin(); it != my_anchors.end(); ++it)
            it->rotate(-*angle, Point(0,0));
    
        // generate lines in this direction
        BoundingBox bb;
        for (ExPolygons::const_iterator it = my_anchors.begin(); it != my_anchors.end(); ++it)
            bb.merge((Points)*it);
        
        Lines lines;
        for (coord_t y = bb.min.y; y <= bb.max.y; y += line_increment)
            lines.push_back(Line(Point(bb.min.x, y), Point(bb.max.x, y)));
        
        Lines clipped_lines;
        intersection(lines, my_clip_area, &clipped_lines);
        
        // remove any line not having both endpoints within anchors
        for (size_t i = 0; i < clipped_lines.size(); ++i) {
            Line &line = clipped_lines[i];
            if (!Slic3r::Geometry::contains(my_anchors, line.a)
                || !Slic3r::Geometry::contains(my_anchors, line.b)) {
                clipped_lines.erase(clipped_lines.begin() + i);
                --i;
            }
        }
        
        std::vector<double> lengths;
        double total_length = 0;
        for (Lines::const_iterator line = clipped_lines.begin(); line != clipped_lines.end(); ++line) {
            double len = line->length();
            lengths.push_back(len);
            total_length += len;
        }
        if (total_length) have_coverage = true;
        
        // sum length of bridged lines
        bdcomp.dir_coverage[*angle] = total_length;
        
        /*  The following produces more correct results in some cases and more broken in others.
            TODO: investigate, as it looks more reliable than line clipping. */
        // $directions_coverage{$angle} = sum(map $_->area, @{$self->coverage($angle)}) // 0;
        
        // max length of bridged lines
        bdcomp.dir_avg_length[*angle] = !lengths.empty()
            ? *std::max_element(lengths.begin(), lengths.end())
            : 0;
    }
    
    // if no direction produced coverage, then there's no bridge direction
    if (!have_coverage) return false;
    
    // sort directions by score
    std::sort(angles.begin(), angles.end(), bdcomp);
    
    this->angle = angles.front();
    if (this->angle >= PI) this->angle -= PI;
    
    #ifdef SLIC3R_DEBUG
    printf("  Optimal infill angle is %d degrees\n", (int)Slic3r::Geometry::rad2deg(this->angle));
    #endif
    
    return true;
}
int main(int argc, char **argv)
{
  ros::init(argc, argv, "updating_particles");
  ros::NodeHandle n;
  PlotRayUtils plt;
  RayTracer rayt;

  std::random_device rd;
  std::normal_distribution<double> randn(0.0,0.000001);

  ROS_INFO("Running...");

  ros::Publisher pub_init = 
    n.advertise<particle_filter::PFilterInit>("/particle_filter_init", 5);
  ros::ServiceClient srv_add = 
    n.serviceClient<particle_filter::AddObservation>("/particle_filter_add");


 
  ros::Duration(1).sleep();
  // pub_init.publish(getInitialPoints(plt));
 
  geometry_msgs::Point obs;
  geometry_msgs::Point dir;
  double radius = 0.00;

  int i = 0;
  //for(int i=0; i<20; i++){
  while (i < NUM_TOUCHES) {
    // ros::Duration(1).sleep();
    //tf::Point start(0.95,0,-0.15);
    //tf::Point end(0.95,2,-0.15);
    tf::Point start, end;
    // randomSelection(plt, rayt, start, end);
    fixedSelection(plt, rayt, start, end);

    Ray measurement(start, end);
    
    double distToPart;
    if(!rayt.traceRay(measurement, distToPart)){
      ROS_INFO("NO INTERSECTION, Skipping");
      continue;
    }
    tf::Point intersection(start.getX(), start.getY(), start.getZ());
    intersection = intersection + (end-start).normalize() * (distToPart - radius);
	std::cout << "Intersection at: " << intersection.getX() << "  " << intersection.getY() << "   " << intersection.getZ() << std::endl;
    tf::Point ray_dir(end.x()-start.x(),end.y()-start.y(),end.z()-start.z());
    ray_dir = ray_dir.normalize();
    obs.x=intersection.getX() + randn(rd); 
    obs.y=intersection.getY() + randn(rd); 
    obs.z=intersection.getZ() + randn(rd);
    dir.x=ray_dir.x();
    dir.y=ray_dir.y();
    dir.z=ray_dir.z();
    // obs.x=intersection.getX(); 
    // obs.y=intersection.getY(); 
    // obs.z=intersection.getZ();

    // pub_add.publish(obs);
    
    // plt.plotCylinder(start, end, 0.01, 0.002, true);
    plt.plotRay(Ray(start, end));
    // ros::Duration(1).sleep();

    particle_filter::AddObservation pfilter_obs;
    pfilter_obs.request.p = obs;
    pfilter_obs.request.dir = dir;
    if(!srv_add.call(pfilter_obs)){
      ROS_INFO("Failed to call add observation");
    }

    ros::spinOnce();
    while(!rayt.particleHandler.newParticles){
      ROS_INFO_THROTTLE(10, "Waiting for new particles...");
      ros::spinOnce();
      ros::Duration(.1).sleep();
    }
    i ++;
  }
  // std::ofstream myfile;
  // myfile.open("/home/shiyuan/Documents/ros_marsarm/diff.csv", std::ios::out|std::ios::app);
  // myfile << "\n";
  // myfile.close();
  // myfile.open("/home/shiyuan/Documents/ros_marsarm/time.csv", std::ios::out|std::ios::app);
  // myfile << "\n";
  // myfile.close();
  // myfile.open("/home/shiyuan/Documents/ros_marsarm/diff_trans.csv", std::ios::out|std::ios::app);
  // myfile << "\n";
  // myfile.close();
  // myfile.open("/home/shiyuan/Documents/ros_marsarm/diff_rot.csv", std::ios::out|std::ios::app);
  // myfile << "\n";
  // myfile.close();
  // myfile.open("/home/shiyuan/Documents/ros_marsarm/workspace_max.csv", std::ios::out|std::ios::app);
  // myfile << "\n";
  // myfile.close();
  // myfile.open("/home/shiyuan/Documents/ros_marsarm/workspace_min.csv", std::ios::out|std::ios::app);
  // myfile << "\n";
  // myfile.close();
  ROS_INFO("Finished all action");

}
point ptoline(point p,line l)
{
	point t=p;
	t.x+=l.a.y-l.b.y,t.y+=l.b.x-l.a.x;
	return intersection(p,t,l.a,l.b);
}
Esempio n. 25
0
inline bool QwtRasterData::ContourPlane::intersect(
    const QwtPoint3D vertex[3], QPointF line[2],
    bool ignoreOnPlane ) const
{
    bool found = true;

    // Are the vertices below (-1), on (0) or above (1) the plan ?
    const int eq1 = compare( vertex[0].z() );
    const int eq2 = compare( vertex[1].z() );
    const int eq3 = compare( vertex[2].z() );

    /*
        (a) All the vertices lie below the contour level.
        (b) Two vertices lie below and one on the contour level.
        (c) Two vertices lie below and one above the contour level.
        (d) One vertex lies below and two on the contour level.
        (e) One vertex lies below, one on and one above the contour level.
        (f) One vertex lies below and two above the contour level.
        (g) Three vertices lie on the contour level.
        (h) Two vertices lie on and one above the contour level.
        (i) One vertex lies on and two above the contour level.
        (j) All the vertices lie above the contour level.
     */

    static const int tab[3][3][3] =
    {
        // jump table to avoid nested case statements
        { { 0, 0, 8 }, { 0, 2, 5 }, { 7, 6, 9 } },
        { { 0, 3, 4 }, { 1, 10, 1 }, { 4, 3, 0 } },
        { { 9, 6, 7 }, { 5, 2, 0 }, { 8, 0, 0 } }
    };

    const int edgeType = tab[eq1+1][eq2+1][eq3+1];
    switch ( edgeType )
    {
        case 1:
            // d(0,0,-1), h(0,0,1)
            line[0] = vertex[0].toPoint();
            line[1] = vertex[1].toPoint();
            break;
        case 2:
            // d(-1,0,0), h(1,0,0)
            line[0] = vertex[1].toPoint();
            line[1] = vertex[2].toPoint();
            break;
        case 3:
            // d(0,-1,0), h(0,1,0)
            line[0] = vertex[2].toPoint();
            line[1] = vertex[0].toPoint();
            break;
        case 4:
            // e(0,-1,1), e(0,1,-1)
            line[0] = vertex[0].toPoint();
            line[1] = intersection( vertex[1], vertex[2] );
            break;
        case 5:
            // e(-1,0,1), e(1,0,-1)
            line[0] = vertex[1].toPoint();
            line[1] = intersection( vertex[2], vertex[0] );
            break;
        case 6:
            // e(-1,1,0), e(1,0,-1)
            line[0] = vertex[2].toPoint();
            line[1] = intersection( vertex[0], vertex[1] );
            break;
        case 7:
            // c(-1,1,-1), f(1,1,-1)
            line[0] = intersection( vertex[0], vertex[1] );
            line[1] = intersection( vertex[1], vertex[2] );
            break;
        case 8:
            // c(-1,-1,1), f(1,1,-1)
            line[0] = intersection( vertex[1], vertex[2] );
            line[1] = intersection( vertex[2], vertex[0] );
            break;
        case 9:
            // f(-1,1,1), c(1,-1,-1)
            line[0] = intersection( vertex[2], vertex[0] );
            line[1] = intersection( vertex[0], vertex[1] );
            break;
        case 10:
            // g(0,0,0)
            // The CONREC algorithm has no satisfying solution for
            // what to do, when all vertices are on the plane.

            if ( ignoreOnPlane )
                found = false;
            else
            {
                line[0] = vertex[2].toPoint();
                line[1] = vertex[0].toPoint();
            }
            break;
        default:
            found = false;
    }

    return found;
}
point ptoline(point p,point l1,point l2)
{
	point t=p;
	t.x+=l1.y-l2.y,t.y+=l2.x-l1.x;
	return intersection(p,t,l1,l2);
}
Esempio n. 27
0
void WebChromeClient::scroll(const IntSize& scrollDelta, const IntRect& scrollRect, const IntRect& clipRect)
{
    m_page->pageDidScroll();
    m_page->drawingArea()->scroll(intersection(scrollRect, clipRect), scrollDelta);
}
Esempio n. 28
0
int main(int argc, char* argv[])
{
  try
  {
    terrama2::core::initializeTerraMA();
    terrama2::core::registerFactories();


    {
      QCoreApplication app(argc, argv);
      auto& serviceManager = terrama2::core::ServiceManager::getInstance();
      std::map<std::string, std::string> connInfo { {"PG_HOST", TERRAMA2_DATABASE_HOST},
                                                    {"PG_PORT", TERRAMA2_DATABASE_PORT},
                                                    {"PG_USER", TERRAMA2_DATABASE_USERNAME},
                                                    {"PG_PASSWORD", TERRAMA2_DATABASE_PASSWORD},
                                                    {"PG_DB_NAME", TERRAMA2_DATABASE_DBNAME},
                                                    {"PG_CONNECT_TIMEOUT", "4"},
                                                    {"PG_CLIENT_ENCODING", "UTF-8"}
                                                  };
      serviceManager.setLogConnectionInfo(connInfo);
      serviceManager.setInstanceId(1);

      auto dataManager = std::make_shared<terrama2::services::collector::core::DataManager>();

      addInput(dataManager);
      addOutput(dataManager);
      addStaticDataSeries(dataManager);

      terrama2::services::collector::core::Service service(dataManager);
      service.start();

      terrama2::services::collector::core::Collector* collector(new terrama2::services::collector::core::Collector());
      terrama2::services::collector::core::CollectorPtr collectorPtr(collector);
      collector->id = 1;
      collector->projectId = 1;
      collector->serviceInstanceId = 1;

      collector->inputDataSeries = 1;
      collector->outputDataSeries = 2;
      collector->inputOutputMap.emplace(1, 2);

      terrama2::services::collector::core::Intersection* intersection(new terrama2::services::collector::core::Intersection());
      terrama2::services::collector::core::IntersectionPtr intersectionPtr(intersection);

      // Adds the attribute "SIGLA" to the collected occurrences.
      intersection->collectorId = collector->id;
      std::vector<std::string> attrVec;
      attrVec.push_back("sigla");
      intersection->attributeMap[3] = attrVec;
      collector->intersection = intersectionPtr;


      dataManager->add(collectorPtr);

      QTimer timer;
      QObject::connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit()));
      timer.start(300000);
      app.exec();

      service.stopService();
    }

    terrama2::core::finalizeTerraMA();
  }
  catch(...)
  {
    // TODO: o que fazer com uncaught exception
    std::cout << "\n\nException...\n" << std::endl;
  }

  return 0;
}
Esempio n. 29
0
int main(int argc, char **argv) {
	// Parse configs
	int height = -1;
	int width = -1;
	int iterations = -1;
	if (argc != 4) {
		printUsage();
		return -1;
	} else {
		height = atoi(argv[1]);
		width = atoi(argv[2]);
		iterations = atoi(argv[3]);
	}
	std::cout << "Height: " << height << std::endl;
	std::cout << "Width: " << width << std::endl;
	std::cout << "Iterations: " << iterations << std::endl << std::endl;


	// Create a grid of and fill with intersections
	// And enter 1 vehicle to each direction of each intersection
	int carId = 0;
	grid g = grid(height, width);
	for (int row = 0; row < height; ++row)
	{
		for (int col = 0; col < width; ++col)
		{
			g.addIntersection(row, col, intersection());
			// North
			for (int i = 0; i < 1; ++i)
			{
				g.enterVehicle(row, col, carId++, NORTH);
			}

			// South
			for (int i = 0; i < 1; ++i)
			{
				g.enterVehicle(row, col, carId++, SOUTH);
			}

			// West
			for (int i = 0; i < 1; ++i)
			{
				g.enterVehicle(row, col, carId++, WEST);
			}

			// East
			for (int i = 0; i < 1; ++i)
			{
				g.enterVehicle(row, col, carId++, EAST);
			}
		}
	}

	std::cout << "Before sim" << std::endl;
	g.print();

	// Record start time
	clock_t start = clock();

	// For each sim iteration
	for (int t = 0; t < iterations; ++t)
	{
		g.control();

		// For each intersection
		for (int row = 0; row < height; ++row)
		{
			for (int col = 0; col < width; ++col)
			{
				g.enterVehicle(row, col, g.exitVehicle(row - 1, col, SOUTH), NORTH);
				g.enterVehicle(row, col, g.exitVehicle(row + 1, col, NORTH), SOUTH);
				g.enterVehicle(row, col, g.exitVehicle(row, col - 1, EAST), WEST);
				g.enterVehicle(row, col, g.exitVehicle(row, col + 1, WEST), EAST);
			}
		}

//		std::cout << "Iteration #" << t << std::endl;
// 		g.print();
	}

	// Record time elapsed
	double timeElapsed = (clock() - start) / (double) CLOCKS_PER_SEC;

	std::cout << "After sim" << std::endl;
	g.print();

	std::cout << "Time: " << timeElapsed << "s";

	return 0;
}
Esempio n. 30
0
static void insertIntersection(UPolygon *subject, UPolygon* clipping,
                               PointNode* A, PointNode* B, PointNode* C, PointNode* D)
{

        IntersectionParameters* param = intersection(*A,*B, *C,*D);
        if (isnan(param->t)) //the lines are parallel
            return;

        Vector b = *B - *A;
        PointNode intersection = *A+b*param->t;

        if (isnan(param->u))// we know that the point isn't within t
            return;

        PointNode *newPoint = NULL;

        // the point is on line segment AB
        if (0 < param->u && param->u < 1) {
            // we have a valid intersection point
            if (param->t == 0) {
                newPoint = A;
                newPoint->setT(param->t, subject->name);
            }
            else if (param->t==1) {
                newPoint = B;
                newPoint->setT(param->t, subject->name);
            }
            else {
                newPoint = new PointNode(intersection.x, intersection.y);
                newPoint->setT(param->t, subject->name);
                newPoint->inbound = param->inbound;

                // insert it into AB
                PointNode* prev = A;
                PointNode* next = A->next[subject->name];
                while (next != NULL && next->t[subject->name] < param->t) {
                    prev = next;
                    next = next->next[subject->name];
                }
                prev->setNext(newPoint, subject->name);
                newPoint->setNext(next, subject->name);
            }
            newPoint->setT(param->u, clipping->name);
            //insert into CD
            PointNode* prev = C;
            PointNode* next = C->next[clipping->name];
            while (next !=NULL && next->t[clipping->name] < param->u) {
                prev = next;
                next = next->next[clipping->name];
            }
            prev->setNext(newPoint, clipping->name);
            newPoint->setNext(next, clipping->name);

        }
        else if ((param->u == 0 ||  param->u == 1) &&
                 (0 < param->t  &&  param->t < 1)) {
           // we can ignore them if the point it an endpoint in both
           // polygons - any following we do will just wrap around
            if (param->u == 0)
                newPoint = C;
            else
                newPoint = D;

            newPoint->setT(param->t, subject->name);
            newPoint->setT(param->u, clipping->name);
            newPoint->inbound = param->inbound;

            // insert it into AB
            PointNode* prev = A;
            PointNode* next = A->next[subject->name];
            while (next != NULL && next->t[subject->name] < param->t) {
                prev = next;
                next = next->next[subject->name];

            }
            prev->setNext(newPoint, subject->name);
            newPoint->setNext(next, subject->name);
       }
       delete param;

}