dymokomi/luce-cad
Source of release 0.9.3
0.9.3 / src / surfacing / skin.lucb
## Skin (surfacing Stage 5: Alias's Skin, Plasticity's and Rhino's Loft;
## §4.6 and §6.6 of luced-3d's docs/research/SURFACING-ALIAS-PLASTICITY.md):
## a surface through sections, in the order picked.
##
## The sections are turned to run alike (each the way nearer the one
## before), made compatible (one degree, one knot vector), and their
## control points interpolated across by a B-spline of the degree asked
## (quintic, or one less than the sections), at parameters by the mean
## chord between neighbors. The interpolation is of homogeneous points,
## so sections alike up to a scale and a shift along an axis (circles
## about one axis) give exactly their surface of revolution: two circles a
## cylinder or a cone. Closed, the sections wrap round: interpolated with
## three loops more on either side (periodic in effect) and cut back
## to the loop, so the seam is smooth. With the first or last section on
## a surface (an edge, a curve on a face), Start and End continuity match
## that side G1 to G3 by Align's rows (align.lucb).
##
## A section may be a set of curves end to end (Alias's curve sets: words
## apart by `+`): Single Surface joins each set into one curve; Multiple
## Surfaces skins the sets' first curves, their second ones and so on,
## one sheet each. Proportional Crown (two sections) raises the middle
## between them along the surface's normal by a fraction of the gap.
## Skin's options: the degree across, a closed loop, the start and end
## continuity (0 G0 to 3 G3), Proportional Crown's value (a fraction of
## the gap between two sections, 0 none).
pub struct SkinOptions:
pub var degree: i64
pub var closed: bool
pub var start: i64
pub var end: i64
pub var crown: f64 = 0.0
## Alias's Flow Control (skin_connect: the sections matched by their
## own parameters, their ends joined; skin_free: by arc length, the
## isoparms spread evenly along each) and Modify Range (the stretch of
## every section used, fractions).
pub var flow: i64 = 0
pub var range: f64[2] = [0.0, 1.0]
## Explicit Control: the degrees and spans as asked (0: as built).
pub var explicit: Explicit = Explicit(false, 0, 0, 0, 0)
pub let skin_connect: i64 = 0
pub let skin_free: i64 = 1
## Explicit Control (Alias's): degrees and spans each way (u along the
## curves, v across), the net refitted to them holding its sides'
## continuity.
pub struct Explicit:
pub var on: bool
pub var degree_u: i64
pub var spans_u: i64
pub var degree_v: i64
pub var spans_v: i64
## `net` refitted by Explicit Control `e` (0: its own degree), holding
## `keep_u` and `keep_v` rows at each side (its continuity there).
func explicit_net(net: const Net*, e: const Explicit*, keep_u: usize, keep_v: usize) -> Net!:
let du = e.degree_u if e.degree_u > 0 else net.du
let dv = e.degree_v if e.degree_v > 0 else net.dv
if du < 1 or du > most_degree or dv < 1 or dv > most_degree: error(invalid, "Explicit Control's degrees are 1 to 11")
if e.spans_u < 1 or e.spans_v < 1 or e.spans_u > 128 or e.spans_v > 128: error(invalid, "Explicit Control's spans are 1 to 128")
var ku = Growing[f64]()
defer ku.close()
var kv = Growing[f64]()
defer kv.close()
try uniform_knots(du, (usize)e.spans_u, net.u_low(), net.u_high(), &ku)
try uniform_knots(dv, (usize)e.spans_v, net.v_low(), net.v_high(), &kv)
let room_u = (usize)du + (usize)e.spans_u
let room_v = (usize)dv + (usize)e.spans_v
if 2 * (keep_u + 1) > room_u or 2 * (keep_v + 1) > room_v:
var buffer: u8[200]
error(invalid, try strings.format(buffer, f"Explicit Control: holding the sides' continuity needs {2 * (keep_u + 1)} by {2 * (keep_v + 1)} control points, this has {room_u} by {room_v}"))
return try refit_net(net, du, ku.view(), dv, kv.view(), keep_u, keep_v, net.rational())
## The mean distance between the control points of `a` and `b` (alike).
func mean_gap(a: const Spline*, b: const Spline*) -> f64:
var sum = 0.0
for k in 0..<a.points.count: sum += a.points.items[k].point().subtract(b.points.items[k].point()).length()
return sum / (f64)a.points.count
## Whether `c` runs nearer `before` turned round (sampled along both).
func runs_against(c: const Spline*, before: const Spline*) -> bool:
var same = 0.0
var other = 0.0
for k in 0..<(usize)11:
let f = (f64)k / 10.0
let p = before.point_at(before.low() + (before.high() - before.low()) * f)
same += c.point_at(c.low() + (c.high() - c.low()) * f).subtract(p).length()
other += c.point_at(c.high() - (c.high() - c.low()) * f).subtract(p).length()
return other < same
## How many sections a closed Skin wraps on either side of its loop.
func wrap_of(q: usize, n: usize) -> usize:
return q + 3 * n
## The curve sets `words` names (sections apart by `;`, a set's curves by
## `+`): every curve's master onto `masters` and each set's size onto
## `sizes`.
func section_sets(set: interop.Reference[GeometrySet], words: str, masters: Growing[Master]*, sizes: Growing[usize]*) -> !:
let bytes = words.bytes
var start: usize = 0
for at in 0..<bytes.length + 1:
if at < bytes.length and bytes[at] != 59: continue
let section = (str)bytes[start..<at]
start = at + 1
if section.length == 0: continue
let before = masters.count
let inner = section.bytes
var from_at: usize = 0
for k in 0..<inner.length + 1:
if k < inner.length and inner[k] != 43: continue
if k > from_at: try masters.push(try master_of(set, (str)inner[from_at..<k], -1, Vector3()))
from_at = k + 1
if masters.count > before: try sizes.push(masters.count - before)
## The curves of one set (`masters`) joined end to end into one, on 0..1.
func joined_set(masters: const Master[]) -> Spline!:
var made = try masters[0].curve.copy()
errdefer made.close()
unit_domain(&made)
if masters.length == 1: return made
# The first runs toward the second.
let next = &masters[1].curve
let tail = made.point_at(1.0)
let head = made.point_at(0.0)
let reach = math.min(next.point_at(next.low()).subtract(tail).length(), next.point_at(next.high()).subtract(tail).length())
if math.min(next.point_at(next.low()).subtract(head).length(), next.point_at(next.high()).subtract(head).length()) < reach:
let turned_round = try reversed_spline(&made)
made.close()
made = turned_round
for k in 1..<masters.length:
var c = try masters[k].curve.copy()
defer c.close()
unit_domain(&c)
let end = made.point_at(made.high())
if c.point_at(c.high()).subtract(end).length() < c.point_at(c.low()).subtract(end).length():
let turned_round = try reversed_spline(&c)
c.close()
c = turned_round
let gap = c.point_at(c.low()).subtract(end).length()
if gap > size_of(&made) * 1e-4: error(invalid, "Skin: the curves of a set must meet end to end")
if made.degree < c.degree: try elevate(&made, (usize)(c.degree - made.degree))
if c.degree < made.degree: try elevate(&c, (usize)(made.degree - c.degree))
let longer = try joined(&made, &c)
made.close()
made = longer
return made
## Skin's nets through the sections `words` (curve sets in Align's master
## words: sections apart by `;`, a set's curves by `+`), in their order, by
## `opts`: one net (Single Surface, each set joined) or one a curve of the
## sets (`multiple`, the sets alike in size), onto `out`.
func skin_nets(set: interop.Reference[GeometrySet], words: str, opts: const SkinOptions*, multiple: bool, out: Growing[Net]*) -> !:
var masters = Growing[Master]()
defer close_masters(&masters)
var sizes = Growing[usize]()
defer sizes.close()
try section_sets(set, words, &masters, &sizes)
let n = sizes.count
if n < 2: error(invalid, "Skin needs two sections or more")
if opts.crown != 0.0 and (n != 2 or opts.closed): error(invalid, "Skin: Proportional Crown takes two open sections")
if multiple:
for k in 1..<n:
if sizes.items[k] != sizes.items[0]: error(invalid, "Skin: Multiple Surfaces needs every set to hold as many curves")
for j in 0..<sizes.items[0]:
var picked = Growing[Spline]()
defer close_splines_of(&picked)
var ends: Master*[2] = [&masters.items[j], &masters.items[(n - 1) * sizes.items[0] + j]]
for k in 0..<n:
var c = try masters.items[k * sizes.items[0] + j].curve.copy()
unit_domain(&c)
try picked.push(c)
try out.push(try skin_from(&picked, ends, opts))
return
var joined_sections = Growing[Spline]()
defer close_splines_of(&joined_sections)
var first: usize = 0
for k in 0..<n:
try joined_sections.push(try joined_set(masters.view()[first..<first + sizes.items[k]]))
first += sizes.items[k]
# Start and End continuity need the end sections single curves.
if (opts.start > 0 and sizes.items[0] != 1) or (opts.end > 0 and sizes.items[n - 1] != 1): error(invalid, "Skin: Start and End continuity take a single curve at that end (or Multiple Surfaces)")
var ends: Master*[2] = [&masters.items[0], &masters.items[masters.count - 1]]
try out.push(try skin_from(&joined_sections, ends, opts))
## Skin's net through `picked` (curves on 0..1, in order), the first and
## last sections' masters `ends` (Start and End continuity), by `opts`.
func skin_from(picked: Growing[Spline]*, ends: Master*[2], opts: const SkinOptions*) -> Net!:
let n = picked.count
if opts.degree < 1 or opts.degree > most_degree: error(invalid, "Skin's degree across is 1 to 11")
if opts.flow != skin_connect and opts.flow != skin_free: error(invalid, "Skin's Flow Control is Connect ends or Free")
if not (opts.range[0] >= 0.0 and opts.range[1] <= 1.0 and opts.range[1] - opts.range[0] > 1e-6): error(invalid, "Skin's Modify Range runs from 0 to 1 of the curves, start before end")
if opts.closed and (opts.range[0] > 0.0 or opts.range[1] < 1.0): error(invalid, "Skin's Modify Range takes open sections (a closed Skin's go round)")
var sections = Growing[Spline]()
defer close_splines_of(§ions)
for at in 0..<n:
var whole = try picked.items[at].copy()
if opts.flow == skin_free:
# By arc length: the curve refitted so its parameter is its
# length's fraction (Rebuild's, within the build's tolerance);
# the range then a stretch of its length.
var plain = try plain_curve(&whole, build_tolerance(picked.items[at..<at + 1]) * 0.1)
defer plain.close()
let even = try rebuilt_curve(&plain, build_tolerance(picked.items[at..<at + 1]) * 0.1)
whole.close()
whole = even
var c = try segment_of(&whole, opts.range[0], opts.range[1])
whole.close()
if at > 0 and runs_against(&c, §ions.items[at - 1]):
let turned_round = try reversed_spline(&c)
c.close()
c = turned_round
try sections.push(c)
try make_compatible(§ions, 1)
let tolerance = build_tolerance(sections.view())
# The sequence interpolated: closed, the loop with the degree's
# sections either side; open, the sections.
let q = fewer((usize)opts.degree, n if opts.closed else n - 1)
var order = Growing[usize]()
defer order.close()
if opts.closed:
if n < 3: error(invalid, "a closed Skin needs three sections or more")
# Three loops either side: the interpolation's end effects die
# away (geometrically) long before the loop kept.
let wrap = wrap_of(q, n)
for k in 0..<wrap: try order.push((n * wrap - wrap + k) % n)
for k in 0..<n + 1: try order.push(k % n)
for k in 0..<wrap: try order.push((k + 1) % n)
else:
for k in 0..<n: try order.push(k)
let count = order.count
var params = Growing[f64]()
defer params.close()
var run = 0.0
try params.push(0.0)
for k in 1..<count:
let gap = mean_gap(§ions.items[order.items[k]], §ions.items[order.items[k - 1]])
if not (gap > tolerance): error(invalid, "Skin: two sections in a row lie on each other")
run += gap
try params.push(run)
for k in 0..<count: params.items[k] = params.items[k] / run
var knots = Growing[f64]()
defer knots.close()
var matrix = Growing[f64]()
defer matrix.close()
try collocation(params.view(), q, &knots, &matrix)
# Each control point of the sections interpolated across: the columns.
let first = §ions.items[0]
let nu = first.points.count
var made = empty_net()
errdefer made.close()
made.du = first.degree
made.dv = (i64)q
made.nu = nu
made.nv = count
try made.ku.assign(first.knots.view())
try made.kv.assign(knots.view())
try made.points.fill(nu * count, Weighted(0.0, 0.0, 0.0, 0.0))
var values = Growing[Weighted]()
defer values.close()
var solved = Growing[Weighted]()
defer solved.close()
for i in 0..<nu:
values.clear()
for k in 0..<count: try values.push(sections.items[order.items[k]].points.items[i])
try interpolate_points(matrix.view(), values.view(), &solved)
for k in 0..<count: made.points.items[i * count + k] = solved.items[k]
if opts.closed:
# Cut back to the loop: from the first section to its return.
var columns = Growing[Spline]()
defer close_splines_of(&columns)
try curves_along(&made, 1, &columns)
var cut = Growing[Spline]()
defer close_splines_of(&cut)
for c in columns.view():
var piece = try extract(&c, params.items[wrap_of(q, n)], params.items[wrap_of(q, n) + n])
unit_domain(&piece)
try cut.push(piece)
let loop = try net_from(cut.view(), 1, &made)
made.close()
made = loop
else:
if opts.crown != 0.0: try crowned(&made, opts.crown)
for k in [(i64)0, (i64)1]:
let order_asked = opts.start if k == 0 else opts.end
if order_asked <= 0: continue
try match_side(&made, 2 + k, ends[(usize)k], order_asked, tolerance)
if opts.explicit.on:
let keep = (usize)math.max(0.0, (f64)math.max((f64)opts.start, (f64)opts.end))
let refitted = try explicit_net(&made, &opts.explicit, 0, keep)
made.close()
made = refitted
return made
## Proportional Crown on a Skin of two sections (`net` of degree 1
## across, v): raised to degree 2 across, its middle row pushed along the
## surface's normal at each control point's Greville place by twice
## `crown` times the gap there, so the middle between the sections rises
## by `crown` times the gap; then quintic across, the same surface.
func crowned(net: Net*, crown: f64) -> !:
if net.dv != 1 or net.nv != 2: error(invalid, "Skin: Proportional Crown takes two sections")
try net_elevate(net, 1, 1)
let p = (usize)net.du
# The pushes first (from the surface as it was), then applied.
var pushes = Growing[Vector3]()
defer pushes.close()
for i in 0..<net.nu:
var place = 0.0
for k in 1..<p + 1: place += net.ku.items[i + k]
place = place / (f64)math.max(1.0, (f64)p)
var parts: Weighted[16]
var shown: Weighted[16]
net.partials(place, 0.5, &parts)
euclidean_partials(&parts, &shown)
let su = Vector3(shown[4].x, shown[4].y, shown[4].z)
let sv = Vector3(shown[1].x, shown[1].y, shown[1].z)
let normal = su.cross(sv).normalized() catch failure: error(invalid, "Skin: Proportional Crown needs the surface to have a normal (sections apart)")
let gap = net.points.items[i * 3 + 2].point().subtract(net.points.items[i * 3].point()).length()
try pushes.push(normal.multiply_scalar(2.0 * crown * gap))
for i in 0..<net.nu:
let q = net.points.items[i * 3 + 1]
net.points.items[i * 3 + 1] = weighted(q.point().add(pushes.items[i]), q.w)
try net_elevate(net, 1, 3)