私のコードを試すことができます。私はboost::geometry
を使用しています。私はmain関数に小さなテストケースを入れます。
2つのポイントを属性とするクラスLineを定義します。
クロス積は、2本の線が交差しているかどうかを知る簡単な方法です。 2Dでは、2D平面の法線ベクトル上の外積の投影である垂れ下がりドットプロダクト(perp
関数を参照)を計算することができます。それを計算するには、各行の方向ベクトルを取得する必要があります(getVector
メソッドを参照)。
2Dでは、perpドット積とパラメトリック方程式を使用して2つの線の交点を得ることができます。私は説明hereを見つけた。
intersect
関数は、2つの線が交差するかどうかを確認するブール値を返します。交差する場合は、参照によって交点を計算します。
#include <cmath>
#include <iostream>
#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
namespace bg = boost::geometry;
// Define two types Point and Vector for a better understanding
// (even if they derive from the same class)
typedef bg::model::d2::point_xy<double> Point;
typedef bg::model::d2::point_xy<double> Vector;
// Class to define a line with two points
class Line
{
public:
Line(const Point& point1,const Point& point2): p1(point1), p2(point2) {}
~Line() {}
// Extract a direction vector
Vector getVector() const
{
Vector v(p2);
bg::subtract_point(v,p1);
return v;
}
Point p1;
Point p2;
};
// Compute the perp dot product of vectors v1 and v2
double perp(const Vector& v1, const Vector& v2)
{
return bg::get<0>(v1)*bg::get<1>(v2)-bg::get<1>(v1)*bg::get<0>(v2);
}
// Check if lines l1 and l2 intersect
// Provide intersection point by reference if true
bool intersect(const Line& l1, const Line& l2, Point& inter)
{
Vector v1 = l1.getVector();
Vector v2 = l2.getVector();
if(std::abs(perp(v1,v2))>0.)
{
// Use parametric equation of lines to find intersection point
Line l(l1.p1,l2.p1);
Vector v = l.getVector();
double t = perp(v,v2)/perp(v1,v2);
inter = v1;
bg::multiply_value(inter,t);
bg::add_point(inter,l.p1);
return true;
}
else return false;
}
int main(int argc, char** argv)
{
Point p1(0.,0.);
Point p2(1.,0.);
Point p3(0.,1.);
Point p4(0.,2.);
Line l1(p1,p2);
Line l2(p3,p4);
Point inter;
if(intersect(l1,l2,inter))
{
std::cout<<"Coordinates of intersection: "<<inter.x()<<" "<<inter.y()<<std::endl;
}
return 0;
}
EDIT:詳細外積とPERP内積+上のあなたがリンクする、またはライブラリのための勧告を求めている場合(トピックオフ)tol
引数
を削除し、その後、あなたの質問がオフになっています-トピック。そうでなければ、あなたの質問は広範に及ぶ。 –
どのように線を表すのですか?2点?ハフ空間? m、p? –
各行はy = kx + bと表され、交点xとyの値は等しいので、方程式{y = k1x + b1; y = k2x + b2} – user3514538