Boost.Geometry 怎样筛出框选命中的路径?
用 R 树筛选包围盒,再判断真实折线是否穿过选框。
示例实测 Boost 1.88.0 返回两条候选路径。水平线命中,斜线只有包围盒与选框相交。
框选时,哪条路径真的碰到了选框?
雕刻图稿编辑器里,用户想框选铭牌左上角的路径。若每次拖动都扫描画布上的所有线段,图稿越复杂,框选需要检查的线段就越多。Boost.Geometry 是 Boost 的 C++ 几何库。本篇用 1.88.0 自带的 R 树按轴对齐包围盒筛选候选,再用真实折线验证是否相交。本文实现的是相交选中。
Boost 1.88.0 发布页 · Boost.Geometry 固定版本源码 · Boost Software License 1.0
先筛包围盒,再检查原路径
示例把每条折线的包围盒和路径编号存入 R 树。节点的包围盒覆盖它的所有子项。查询时,spatial_query 访问内部节点时执行 bounds_tag 检查,与选择框分离的子树可以直接跳过。在叶节点,它通过 value_tag 检查条目。我们存的是包围盒,查询交给我们的仍是盒子相交的候选。最后,bg::intersects(paths[id], marquee) 才用折线与选择框判断实际命中。查看内部节点与叶节点的判断
这次矩形选框是 [0,2] × [8,10]。从 (1,1) 到 (9,9) 的对角线,其包围盒在左上角与选框重叠。这段线在 x ≤ 2 处的 y 也 ≤ 2,原线段因此落在选框外。位于 y = 9 的水平线则真正穿过选框。另外两条远处路径的包围盒与选框分离。示例用容量很小的 quadratic<2> 触发节点拆分,便于从源码跟读递归过程。
若许多长斜线的包围盒互相覆盖,候选数可能接近全部路径。真实编辑器还要在变换后重算索引边界,按统一坐标系把屏幕选择框换算到图稿坐标,并根据选择规则处理笔画宽度、曲线和边界接触。这个示例只测零宽折线在图稿平面内的相交。
在本地构建并运行
在 macOS 或 Linux 的新工作目录运行。需要 curl、tar 和 C++17 编译器。本例只用 Boost.Geometry 的模板头文件,直接引用完整 Boost 1.88.0 源码包。实测环境为 Apple Silicon macOS。
查看示例源码
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string_view>
#include <utility>
#include <vector>
#include <boost/geometry.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/version.hpp>
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;
using Point = bg::model::d2::point_xy<double>;
using Path = bg::model::linestring<Point>;
using Box = bg::model::box<Point>;
using Entry = std::pair<Box, std::size_t>;
int main() {
static_assert(BOOST_VERSION == 108800, "This demo pins Boost 1.88.0");
const std::vector<Path> paths{
{{1, 1}, {9, 9}},
{{0, 9}, {9, 9}},
{{12, 12}, {16, 12}},
{{18, 14}, {21, 15}},
};
const std::vector<std::string_view> labels{
"diagonal", "horizontal", "far-a", "far-b",
};
// A small node capacity makes the tree split even for this tiny fixture.
bgi::rtree<Entry, bgi::quadratic<2>> index;
for (std::size_t id = 0; id < paths.size(); ++id) {
index.insert({bg::return_envelope<Box>(paths[id]), id});
}
const Box marquee{{0, 8}, {2, 10}};
std::vector<Entry> candidates;
index.query(bgi::intersects(marquee), std::back_inserter(candidates));
std::sort(candidates.begin(), candidates.end(),
[](const Entry& a, const Entry& b) { return a.second < b.second; });
std::cout << "Boost " << BOOST_VERSION / 100000 << '.'
<< BOOST_VERSION / 100 % 1000 << '.' << BOOST_VERSION % 100 << '\n';
for (const auto& entry : candidates) {
const auto id = entry.second;
std::cout << labels[id] << ": "
<< (bg::intersects(paths[id], marquee) ? "hit" : "box only")
<< '\n';
}
}mkdir boost-geometry-study && cd boost-geometry-study
curl -fsSL https://archives.boost.io/release/1.88.0/source/boost_1_88_0.tar.bz2 -o boost.tar.bz2
tar -xjf boost.tar.bz2
curl -fsSLO https://www.juyaoai.com/examples/boost-geometry-path-selection/demo.cpp
c++ -std=c++17 -I boost_1_88_0 demo.cpp -o boost-geometry-demo
./boost-geometry-demo运行结果
Boost 1.88.0
diagonal: box only
horizontal: hit
box only 表示包围盒命中、原路径未命中。把选框改成 [0,2] × [0,2] 再运行,命中应改为对角线。两个小例子可作为编辑器重写框选逻辑时的回归用例。