Debian Codegraph @

texmf-dist/tex/lualatex/luahyperbolic/luahyperbolic-core.lua

raw
1 -----------------------------------------------------------------------
2 -- @module luahyperbolic-core
3 -- Pure Lua hyperbolic geometry
4 --
5 -- License:
6 -- Public Domain / CC0 1.0 Universal
7 -- 2026 Damien Mégy
8 -- This software is released into the public domain.
9 -- You may use, modify, and distribute it freely, without restriction.
10 --
11 -- SPDX-License-Identifier: CC0-1.0
12 --
13 -----------------------------------------------------------------------
14
15 local complex = require("complex")
16 local m = {}
17 m.module = "hyper"
18
19 -- ================ MESSAGES =====================
20
21 function m._error(msg)
22 error("[ERROR] " .. msg, 2)
23 end
24
25 function m._assert(cond, msg)
26 if not cond then
27 m._error(msg)
28 end
29 end
30
31
32 function m._assert_in_disk(...)
33 local points = {...}
34 for _, z in ipairs(points) do
35 m._assert(m._in_disk(z), "POINT NOT IN OPEN DISK : " .. complex.__tostring(z))
36 end
37 end
38
39 function m._assert_in_closed_disk(...)
40 local points = {...}
41 for _, z in ipairs(points) do
42 m._assert(m._in_closed_disk(z), "POINT NOT IN CLOSED DISK : " .. complex.__tostring(z))
43 end
44 end
45
46
47 function m._coerce_assert_in_disk(...)
48 local points = {complex.coerce(...)}
49 m._assert_in_disk(table.unpack(points))
50 return table.unpack(points)
51 end
52
53 function m._coerce_assert_in_closed_disk(...)
54 local points = {complex.coerce(...)}
55 m._assert_in_closed_disk(table.unpack(points))
56 return table.unpack(points)
57 end
58
59 -- ================= HELPERS (EUCLIDEAN GEOM AND OTHER)
60
61 -- precision
62 m.EPS = 1e-10
63
64 local PI = 3.1415926535898
65 local random = math.random
66 local min = math.min
67 local max = math.max
68 local sin = math.sin
69 local cos = math.cos
70 local atan2 = math.atan2
71 local exp = math.exp
72 local log = math.log
73 local sqrt = math.sqrt
74 local abs = math.abs
75 local sinh = math.sinh
76 local cosh = math.cosh
77 local tanh = math.tanh
78
79 local atanh = function(x)
80 return 0.5 * log((1 + x) / (1 - x))
81 end
82
83 local acosh = function(x)
84 return log(x + sqrt(x*x - 1))
85 end
86
87 local asinh = function(x)
88 return log(x + sqrt(x*x + 1))
89 end
90
91 -- public versions :
92 -- m.cosh = cosh
93 -- m.sinh = sinh
94 -- m.tanh = tanh
95 -- m.acosh = acosh
96 -- m.asinh = asinh
97 -- m.atanh = atanh
98
99
100
101
102 m._ensure_order = function (x, y, z, t)
103 -- if the "distance" along the circle from x to y is larger than x to z, swap
104 if complex.abs(x - y) > complex.abs(x - z) or complex.abs(t - z) > complex.abs(t - y) then
105 return t, x
106 else
107 return x, t
108 end
109 end
110
111
112
113 -- ==== EUCLIDEAN HELPERS
114
115 local euclid = {}
116 function euclid.interCC(c1, r1, c2, r2)
117 local d = complex.abs(c2 - c1)
118 if d < m.EPS then
119 return nil
120 end -- même si même rayon
121
122 if d > r1 + r2 + m.EPS or d < abs(r1 - r2) - m.EPS then
123 return nil -- no intersection
124 end
125
126 if abs(d - (r1 + r2)) < m.EPS or abs(d - abs(r1 - r2)) < m.EPS then
127 local p = c1 + (c2 - c1) * (r1 / d)
128 return p, p
129 end
130
131 local a = (r1 ^ 2 - r2 ^ 2 + d ^ 2) / (2 * d)
132 local h = sqrt(max(r1 ^ 2 - a ^ 2, 0))
133 local p_mid = c1 + ((c2 - c1) / d) * a
134 local offset = complex(-(c2.im - c1.im) / d * h, (c2.re - c1.re) / d * h)
135
136 return p_mid + offset, p_mid - offset
137 end
138
139 function euclid.interLC(z1, z2, c0, r)
140 local dir = z2 - z1
141 local f = z1 - c0
142 local a = complex.abs2(dir)
143 local b = 2 * (f.re * dir.re + f.im * dir.im)
144 local c = complex.abs2(f) - r * r
145
146 local disc = b * b - 4 * a * c
147 if disc < -m.EPS then
148 return nil
149 end
150 disc = max(disc, 0)
151
152 local sqrtD = sqrt(disc)
153 local t1 = (-b + sqrtD) / (2 * a)
154 local t2 = (-b - sqrtD) / (2 * a)
155
156 return z1 + dir * t1, z1 + dir * t2
157 end
158
159 -- ==============================
160
161 function m.randomPoint(rmin, rmax)
162 -- returns random point in disk or annulus with uniform density
163 rmax = rmax or 1 - m.EPS
164 rmax = min(rmax, 1 - m.EPS)
165 rmin = rmin or 0
166
167 m._assert(rmin >= 0 and rmax > rmin, "randomPoint: require 0 ≤ rmin < rmax")
168
169 local theta = 2 * PI * random()
170 local u = random()
171 local r = sqrt(u * (rmax ^ 2 - rmin ^ 2) + rmin ^ 2)
172
173 return complex(r * cos(theta), r * sin(theta))
174 end
175
176
177 function m._in_disk(z)
178 return complex.abs2(z) < 1 - m.EPS
179 end
180
181 function m._in_closed_disk(z)
182 return complex.abs2(z) < 1 + m.EPS
183 end
184
185 function m._on_circle(z)
186 return abs(complex.abs2(z) - 1) < m.EPS
187 end
188
189 function m._in_half_plane(z)
190 return z.im > m.EPS
191 end
192
193
194 -- =========================================================
195 -- ==================== HYPERBOLIC CALCULUS ================
196 -- =========================================================
197
198 function m._radial_half(r)
199 return r / (1 + sqrt(1 - r * r))
200 end
201
202 function m._radial_scale(r, t)
203 return tanh(t * atanh(r))
204 end
205
206
207 function m.distance(z, w)
208 z, w = m._coerce_assert_in_disk(z,w)
209 -- send w to 0 and z to zz with isometry :
210 local zz = (z-w)/(1-complex.conj(w)*z)
211 -- return dist(zz,0)
212 return 2 * atanh(complex.abs(zz))
213 end
214
215
216 local function same_distance(A, B, C, D)
217 local phiA = m.automorphism(A,0)
218 local phiC = m.automorphism(C,0)
219 local BB = phiA(B)
220 local DD = phiC(D)
221 return abs(complex.abs2(BB) - complex.abs2(DD)) < m.EPS
222 end
223
224 function m._midpoint_to_origin(z)
225 local r = complex.abs(z)
226 if r < m.EPS then
227 return complex(0, 0)
228 end
229 return (z / r) * m._radial_half(r)
230 end
231
232 function m.midpoint(a, b)
233 local u = m.automorphism(a, 0)(b)
234 local u_half = m._midpoint_to_origin(u)
235 return m.automorphism(-a, 0)(u_half)
236 end
237
238 function m._metric_factor(z)
239 return 2 / (1 - complex.abs2(z))
240 end
241
242
243 function m._geodesic_data(z, w)
244 m._assert(complex.distinct(z, w), "geodesic_data: points z and w are identical")
245
246 local u = w - z
247 local area = z.re * w.im - z.im * w.re -- signed!
248 if abs(area) < m.EPS then -- points are aligned with origin
249 return {
250 type = "diameter",
251 center = nil,
252 radius = math.huge,
253 direction = (u / complex.abs(u)),
254 }
255 end
256 local d1 = (complex.abs2(z) + 1) / 2
257 local d2 = (complex.abs2(w) + 1) / 2
258 local cx = (d1 * w.im - z.im * d2) / area
259 local cy = (z.re * d2 - d1 * w.re) / area
260 local c = complex(cx, cy)
261 local R = complex.abs(c - z)
262 return {
263 type = "circle",
264 center = c,
265 radius = R,
266 direction = nil,
267 }
268 end
269
270 function m.endpoints(a, b)
271 m._assert(complex.distinct(a,b), "endpoints : points must be distinct")
272 if abs(complex.det(a,b)) < 100*m.EPS then
273 local dir = (a-b) / complex.abs(a-b)
274 local e1, e2 = -dir, dir
275 return m._ensure_order(e1, a, b, e2)
276 end
277
278
279 -- should be circle case. rewrite this
280
281 local g = m._geodesic_data(a, b)
282 assert(g.type=="circle", "endpoints : problem with branch diameter/circle")
283 local c, R = g.center, g.radius
284 local e1, e2 = euclid.interCC(c, R, complex(0, 0), 1)
285 return m._ensure_order(e1, a, b, e2)
286 end
287
288 --[[
289 function m._same_geodesics(a, b, c, d)
290 local aa, bb = m.endpoints(a, b)
291 local cc, dd = m.endpoints(c, d)
292 local sameSet = complex.isSamePair(aa,bb,cc,dd)
293 return sameSet
294 end]]
295
296
297
298 function m.endpointsPerpendicularBisector(A, B)
299 m._assert(complex.distinct(A, B), "perpendicular_bisector: A and B must be distinct")
300
301 local M = m.midpoint(A, B)
302 local phi = m.automorphism(M, 0)
303 local phi_inv = m.automorphism(-M, 0)
304 local A1 = phi(A)
305 local u = A1 / complex.abs(A1)
306 local v = complex(-u.im, u.re)
307 local e1 = v
308 local e2 = -v
309 return phi_inv(e1), phi_inv(e2)
310 end
311
312 function m.endpointsAngleBisector(A, O, B)
313 m._assert(complex.distinct(A, O) and complex.distinct(O, B), "angle_bisector: O must be distinct from A and B")
314
315 local phi = m.automorphism(O, 0)
316 local phi_inv = m.automorphism(-O, 0)
317
318 local A1 = phi(A)
319 local B1 = phi(B)
320
321 local u1 = A1 / complex.abs(A1)
322 local u2 = B1 / complex.abs(B1)
323
324 local v = u1 + u2
325
326 if v:isNear(0) then
327 -- flat angle: perpendicular to common diameter
328 local perp = complex(-u1.im, u1.re)
329 return phi_inv(perp), phi_inv(-perp)
330 end
331
332 v = v / complex.abs(v)
333
334 return phi_inv(v), phi_inv(-v)
335 end
336
337 function m._circle_to_euclidean(z0, r)
338 -- returns euclidean center and radius of hyperbolic center and radius
339 local rho = tanh(r / 2)
340 local mod2 = complex.abs2(z0)
341 local denom = 1 - rho * rho * mod2
342 local c = ((1 - rho * rho) / denom) * z0
343 local R = ((1 - mod2) * rho) / denom
344
345 return c, R
346 end
347
348 function m.tangentVector(z, w)
349 local v
350 local g = m._geodesic_data(z, w)
351 if g.radius == math.huge then
352 v = w - z
353 else
354 local u = z - g.center
355 v = complex(-u.im, u.re)
356 if complex.scal(v, w - z) < 0 then
357 v = -v
358 end
359 end
360 return v
361 end
362
363 function m.angle(A, O, B)
364 -- oriented angle
365 local t1 = m.tangentVector(O, A)
366 local t2 = m.tangentVector(O, B)
367 return complex.arg(t2/t1)
368 end
369
370 -- =========== HYPERBOLIC ISOMETRES =============
371
372 function m.automorphism(a, theta)
373 theta = theta or 0 -- default angle = 0
374 a = m._coerce_assert_in_disk(a)
375 if a:isNear(0) then
376 return function(x)
377 return x
378 end
379 end
380 local rot = complex.exp_i(theta)
381 return function(z)
382 z = m._coerce_assert_in_closed_disk(z)
383 local numerator = z - a
384 local denominator = 1 - complex.conj(a) * z
385 return rot * (numerator / denominator)
386 end
387 end
388
389 function m.rotation(center, theta)
390 center = m._coerce_assert_in_disk(center)
391 theta = theta or 0
392 if abs(theta) < m.EPS then
393 return function(x)
394 return x
395 end
396 end
397 local phi = m.automorphism(center, 0)
398 local phi_inv = m.automorphism(-center, 0)
399 local rot = complex.exp_i(theta)
400 return function(z)
401 return phi_inv(rot * phi(z))
402 end
403 end
404
405 function m.symmetry(center)
406 return m.rotation(center, PI)
407 end
408
409 function m.symmetryAroundMidpoint(a, b)
410 return m.rotation(m.midpoint(a, b), PI)
411 end
412
413 local function parabolic_fix1(theta) -- angle in rad
414 local P = (1 - complex.exp_i(-theta)) / 2 -- preimage of zero
415 local phi = m.automorphism(P, 0)
416 local u = phi(1)
417 return function(z)
418 return phi(z) / u
419 end
420 end
421
422 function m.parabolic(idealPoint, theta)
423 m._assert(idealPoint:isUnit(), "parabolic : ideal point must be at infinity")
424 return function(z)
425 return idealPoint * parabolic_fix1(theta)(z / idealPoint)
426 end
427 end
428
429 function m.automorphismSending(z, w)
430 -- (hyperbolic)
431 if z:isNear(w) then
432 return function(x)
433 return x
434 end
435 end
436 local phi_z = m.automorphism(z, 0)
437 local phi_w_inv = m.automorphism(-w, 0)
438
439 return function(x)
440 return phi_w_inv(phi_z(x))
441 end
442 end
443
444 function m.automorphismFromPairs(A, B, imageA, imageB)
445 m._assert(complex.distinct(A, B), "automorphism_from_pairs : startpoints must be different")
446 m._assert(same_distance(A, B, imageA, imageB), "automorphism_from_pairs : distances don't match") -- or return nil ?
447
448 if A:isNear(imageA) and B:isNear(imageB) then
449 return function(z)
450 return z
451 end
452 end
453
454 local B1 = m.automorphism(A, 0)(B)
455 local BB1 = m.automorphism(imageA, 0)(imageB)
456 local u = complex.unit(BB1 / B1)
457
458 return function(z)
459 return m.automorphism(-imageA, 0)(u * m.automorphism(A, 0)(z))
460 end
461 end
462
463 function m.rotationFromPair(O, A, imageA)
464 return m.automorphismFromPairs(O, A, O, imageA)
465 end
466
467 function m.reflection(z1, z2)
468 -- rewrite with automorphisms ? maybe not
469 local g = m._geodesic_data(z1, z2)
470
471 if g.radius == math.huge then
472 local dir = (z2-z1) / complex.abs(z2-z1)
473 return function(z)
474 local proj = (dir * complex.conj(z)).re * dir
475 local perp = z - proj
476 return proj - perp
477 end
478 else
479 local c, R = g.center, g.radius
480 return function(z)
481 local u = z - c
482 local v = (R * R) / complex.conj(u)
483 return c + v
484 end
485 end
486 end
487
488
489 function m.projection(z1, z2)
490 local refl = m.reflection(z1, z2)
491 return function(z)
492 local z_ref = refl(z)
493 return m.midpoint(z, z_ref)
494 end
495 end
496
497 function m.pointOrbit(point, func, n)
498 local points = {}
499 for _ = 1, n do
500 point = func(point)
501 table.insert(points, point)
502 end
503 return points
504 end
505
506
507 function m.mobiusTransformation(a, b, c, d)
508 -- general Möbius transform
509 return function(z)
510 return (a * z + b) / (c * z + d)
511 end
512 end
513
514 function m.distanceToLine(z, z1, z2)
515 local p = (m.projection(z1, z2))(z)
516 return m.distance(z, p)
517 end
518
519 function m._on_line(z, a, b, eps)
520 eps = eps or m.EPS
521 local phi = m.automorphism(a,0)
522 local zz = phi(z)
523 local bb = phi(b)
524 return abs(complex.det(zz,bb)) < eps
525 end
526
527 function m._on_segment(z, a, b, eps)
528 eps = eps or m.EPS
529 return abs(m.distance(a,b) - m.distance(a,z) - m.distance(z,b)) < eps
530 end
531
532 -- ========== EXPONENTIAL MAPS (vector -> point) ==========
533
534 -- ! local ! expose as "_exp_map_at_origin" ?
535 local function exp_map_at_origin(v)
536 -- input : vector, output : point
537 if v:isNear(0) then return complex(0,0) end
538
539 local norm_v = complex.abs(v)
540 return v / norm_v * tanh(norm_v / 2)
541 end
542
543 --- Exponential map at a point P
544 -- @param P complex
545 -- @param vector complex (vector)
546 -- @return complex
547 function m.expMap(P, vector)
548 P, vector = complex.coerce(P, vector)
549 m._assert_in_disk(P)
550 if vector:isNear(0) then
551 return P
552 end
553 local w = exp_map_at_origin(vector)
554 if P:isNear(0) then
555 return w
556 end
557 return m.automorphism(-P, 0)(w)
558 end
559
560
561 -- ============ INTERPOLATE, BARYCENTERS OF 2 POINTS =====
562
563 function m.interpolate(a, b, t)
564 if a:isNear(b) then return a end
565 local phi = m.automorphism(a, 0)
566 local phi_inv = m.automorphism(-a, 0)
567
568 local u = phi(b)
569 local r = complex.abs(u)
570 if r < m.EPS then
571 return a
572 end
573
574 local r_t = m._radial_scale(r, t)
575 local u_t = u * (r_t / r)
576
577 return phi_inv(u_t)
578 end
579
580 function m.barycenter2(a, wa, b, wb)
581 local s = wa + wb
582 m._assert(abs(s) > m.EPS, "barycenter2: sum of weights must not be zero")
583
584 local t = wb / s
585 return m.interpolate(a, b, t)
586 end
587
588
589
590 -- ============ INTERSECTIONS ==============================
591
592 function m.interLC(z1, z2, c0, r)
593 local ce, Re = m._circle_to_euclidean(c0, r)
594 local g = m._geodesic_data(z1, z2)
595 if g.radius == math.huge then
596 return euclid.interLC(complex(0, 0), g.direction, ce, Re)
597 else
598 return euclid.interCC(g.center, g.radius, ce, Re)
599 end
600 end
601
602 function m.interCC(c1, r1, c2, r2)
603 local C1, R1 = m._circle_to_euclidean(c1, r1)
604 local C2, R2 = m._circle_to_euclidean(c2, r2)
605
606 return euclid.interCC(C1, R1, C2, R2)
607 end
608
609 function m.interLL(z1, z2, w1, w2)
610 local g1 = m._geodesic_data(z1, z2)
611 local g2 = m._geodesic_data(w1, w2)
612 local is_diam1 = (g1.radius == math.huge)
613 local is_diam2 = (g2.radius == math.huge)
614
615 if is_diam1 and is_diam2 then
616 local u = g1.direction
617 local v = g2.direction
618
619 local dot = u.re * v.re + u.im * v.im
620 if abs(abs(dot) - 1) < m.EPS then
621 return nil
622 end
623
624 return complex(0, 0)
625 end
626
627 if is_diam1 and not is_diam2 then
628 local line_p1 = complex(0, 0)
629 local line_p2 = g1.direction
630 return euclid.interLC(line_p1, line_p2, g2.center, g2.radius)
631 end
632
633 if not is_diam1 and is_diam2 then
634 local line_p1 = complex(0, 0)
635 local line_p2 = g2.direction
636 return euclid.interLC(line_p1, line_p2, g1.center, g1.radius)
637 end
638
639 local p1, p2 = euclid.interCC(g1.center, g1.radius, g2.center, g2.radius)
640
641 if not p1 then
642 return nil
643 end
644
645 local inside1 = m._in_disk(p1)
646 local inside2 = m._in_disk(p2)
647
648 if inside1 and not inside2 then
649 return p1
650 elseif inside2 and not inside1 then
651 return p2
652 else
653 return nil
654 end
655 end
656
657 ----------------------------------
658 -- TRIANGLE GEOMETRY
659 ---------------------------------
660
661 function m.triangleCentroid(A, B, C)
662 -- Intersection des trois médianes.
663 -- /!\ Pas au deux tiers des médianes
664 local AA = m.midpoint(B, C)
665 local BB = m.midpoint(C, A)
666 local centroid = m.interLL(A, AA, B, BB)
667 return centroid
668 end
669
670
671 function m.triangleIncenter(A, B, C)
672 m._assert(
673 complex.distinct(A, B) and complex.distinct(B, C) and complex.distinct(C, A),
674 "incenter: points must be distinct"
675 )
676
677 local e1, e2 = m.endpointsAngleBisector(A, B, C)
678 local f1, f2 = m.endpointsAngleBisector(B, C, A)
679 return m.interLL(e1, e2, f1, f2)
680 end
681
682 ----------------
683 -- CAUTION : orthocenter and circumcenter do not always exist
684
685 function m.triangleCircumcenter(A, B, C)
686 -- WARNING returns circumcenter or nil
687 m._assert(
688 complex.distinct(A, B) and complex.distinct(B, C) and complex.distinct(C, A),
689 "circumcenter: points must be distinct"
690 )
691
692 local e1, e2 = m.endpointsPerpendicularBisector(A, B)
693 local f1, f2 = m.endpointsPerpendicularBisector(A, C)
694
695 return m.interLL(e1, e2, f1, f2) -- can be nil
696 end
697
698
699 function m.triangleOrthocenter(A,B,C)
700 -- Faster than projecting, no midpoint:
701 local AA = m.reflection(B,C)(A)
702 local BB = m.reflection(C,A)(B)
703 return m.interLL(A,AA,B,BB) -- can be nil
704 end
705
706
707 local function side_from_angles(opposite, other1, other2)
708 if opposite == 0 then return math.huge end
709 local cosh_a = (cos(opposite) + cos(other1)*cos(other2)) / (sin(other1)*sin(other2))
710 return acosh(cosh_a)
711 end
712
713 function m.triangleWithAngles(alpha, beta, gamma)
714 m._assert(alpha >= 0 and beta >= 0 and gamma >= 0, "Angles must be >=0")
715
716 m._assert(alpha + beta + gamma < math.pi,
717 "Sum of angles must be less than PI")
718
719 local angles = {alpha, beta, gamma}
720 table.sort(angles, function(x,y) return x > y end)
721 alpha, beta, gamma = angles[1], angles[2], angles[3]
722
723 if alpha == 0 then
724 return complex(1,0), complex.J, complex.J^2
725 end
726
727 local A = complex(0,0)
728
729 if beta == 0 and gamma == 0 then
730 return A, complex(1, 0), complex.polar(1, alpha)
731 end
732
733
734 if gamma == 0 then
735 local K = (cos(alpha)*cos(beta) + 1) / (sin(alpha)*sin(beta))
736 local r2 = (K - 1) / (K + 1)
737 local r = sqrt(r2)
738 return A, complex(r,0), complex.polar(1,alpha)
739 end
740
741 local c = side_from_angles(gamma, alpha, beta)
742 local rc = tanh(c/2)
743 local b = side_from_angles(beta, gamma, alpha)
744 local rb = tanh(b/2)
745 local B = complex.polar(rc, 0)
746 local C = complex.polar(rb, alpha)
747
748 return A,B,C
749 end
750
751
752 -- function m.triangleWithOrderedAngles(alpha, beta, gamma)
753 -- local angles = {alpha, beta, gamma}
754 -- local phi = {1,2,3}
755 -- table.sort(phi, function(i,j) return angles[i] > angles[j] end)
756 -- local p = {}
757 -- p[1], p[2], p[3] = m.triangleWithAngles(angles[phi[1]], angles[phi[2]], angles[phi[3]])
758 -- local psi = {} -- inverse of phi
759 -- for i=1,3 do
760 -- psi[p[i]] = i
761 -- end
762 -- return p[psi[1]], p[psi[2]], p[psi[3]]
763 -- end
764
765 return m