1
0
mirror of https://github.com/JustinSDK/dotSCAD.git synced 2025-08-17 20:11:50 +02:00

add convex_hull

This commit is contained in:
Justin Lin
2020-02-23 15:45:32 +08:00
parent ca9f4c7af3
commit 94bb5ee229
2 changed files with 58 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
use <util/slice.scad>;
// oa->ob ct_clk : greater than 0
function _dir(o, a, b) =
let(
ox = o[0],
oy = o[1],
ax = a[0],
ay = a[1],
bx = b[0],
by = b[1]
)
(ax - ox) * (by - oy) - (ay - oy) * (bx - ox);
function _lower_m(chain, p, m) =
(m >= 2 && _dir(chain[m - 2], chain[m - 1], p) <= 0) ? _lower_m(chain, p, m - 1) : m;
function lower_chain(points, leng, chain, m, i) =
i == leng ? chain :
let(
current_m = _lower_m(chain, points[i], m)
)
lower_chain(
points,
leng,
concat(slice(chain, 0, current_m), [points[i]]),
current_m + 1,
i + 1
);
function _upper_m(chain, p, m, t) =
(m >= t && _dir(chain[m - 2], chain[m - 1], p) <= 0) ?
_upper_m(chain, p, m - 1, t) : m;
function _upper_chain(points, chain, m, t, i) =
i < 0 ? chain :
let(
current_m = _upper_m(chain, points[i], m, t)
)
_upper_chain(
points,
concat(slice(chain, 0, current_m), [points[i]]),
current_m + 1,
t,
i - 1
);

View File

@@ -0,0 +1,12 @@
use <experimental/_impl/_convex_hull_impl.scad>;
use <util/sort.scad>;
function convex_hull(points) =
let(
sorted = sort(points, by = "x"),
leng = len(sorted),
lwr_ch = lower_chain(sorted, leng, [], 0, 0),
leng_lwr_ch = len(lwr_ch),
chain = _upper_chain(sorted, lwr_ch, leng_lwr_ch, leng_lwr_ch + 1, leng - 2)
)
[for(i = [0:len(chain) - 2]) chain[i]];