Debian Codegraph @

texmf-dist/tex/lualatex/luahyperbolic/luahyperbolic.sty

raw
1 %===========================================================================
2 % luahyperbolic.sty
3 % LuaLaTeX package for hyperbolic geometry
4 % Version : 2026/03/16
5 % Automatically generated from the following files:
6 % - complex.lua
7 % - luahyperbolic-core.lua
8 % - luahyperbolic-tikz.lua
9 % - luahyperbolic-tilings.lua
10 % source code and documentation:
11 % https://github.com/dmegy/luahyperbolic
12 % -- 2026 Damien Mégy
13 %===========================================================================
14
15 \NeedsTeXFormat{LaTeX2e}
16 \ProvidesPackage{luahyperbolic}[2026/03/16 Hyperbolic geometry package written in Lua.]
17
18 \RequirePackage{iftex}
19 \ifluatex
20 \RequirePackage{luacode}
21 \else
22 {\PackageError{luahyperbolic}
23 {Not running under LuaLaTeX}
24 {This package requires LuaLaTeX. Try compiling this document with\MessageBreak 'lualatex' instead of 'latex', 'pdflatex' or 'xelatex'. This is a fatal error; I'm aborting now.}%
25 }\stop
26 \fi
27
28 \RequirePackage{tikz}
29 %\usetikzlibrary{decorations.markings}
30
31 \begin{luacode*}
32 -- AUTO-GENERATED FILE
33 -- DO NOT EDIT
34 -- TIMESTAMP : 2026/03/16 15:39:02
35
36 -- internal modules
37 local core
38 local tikz
39 local tilings
40
41 do
42 -----------------------------------------------------------------------
43 -- @module complex
44 -- Pure Lua complex number library (LuaLaTeX oriented).
45 -- Provides arithmetic, elementary functions, geometric utilities,
46 -- and tolerant comparisons.
47 --
48 -- License:
49 -- Public Domain / CC0 1.0 Universal
50 -- 2026 Damien Mégy
51 -- This software is released into the public domain.
52 -- You may use, modify, and distribute it freely, without restriction.
53 --
54 -- SPDX-License-Identifier: CC0-1.0
55 --
56 -----------------------------------------------------------------------
57
58
59
60 local m = {}
61 m.__index = m
62
63 local sin = math.sin
64 local cos = math.cos
65 local atan2 = math.atan2
66 local exp = math.exp
67 local log = math.log
68 local sqrt = math.sqrt
69 local abs = math.abs
70
71 -- precision
72 m.EPS_INV = 1e10
73 m.EPS = 1/m.EPS_INV
74
75 function m.new(re, im)
76 return setmetatable({
77 re = re or 0,
78 im = im or 0,
79 }, m)
80 end
81
82 --- Polar constructor.
83 function m.polar(r, theta)
84 return m.new(r * cos(theta), r * sin(theta))
85 end
86
87
88 setmetatable(m, {
89 __call = function(_, re, im)
90 return m.new(re, im)
91 end,
92 })
93
94 -- -----------------------------------------
95 -- Type checking and coercion
96 -- -----------------------------------------
97
98 function m.isComplex(z)
99 return type(z) == "table" and getmetatable(z) == m
100 end
101
102 local function tocomplex(z)
103 if m.isComplex(z) then
104 return z
105 elseif type(z) == "number" then
106 return m.new(z, 0)
107 elseif type(z) == "table" and z.re and z.im then
108 return m.new(z.re, z.im)
109 else
110 error("Cannot coerce value to complex, got type " .. type(z))
111 end
112 end
113
114 -- public coerce, handles various arguments
115
116 function m.coerce(...)
117 local args = {...}
118 for i = 1, #args do
119 args[i] =tocomplex(args[i])
120 end
121 return table.unpack(args)
122 end
123
124 -- -----------------------------------------
125 -- Arithmetic metamethods
126 -- -----------------------------------------
127
128 --- Exact equality test (no tolerance).
129 -- Use `isClose` for numerical comparisons.
130 function m.__eq(a, b)
131 a, b = tocomplex(a), tocomplex(b)
132 return a.re == b.re and a.im == b.im
133 end
134
135 --- Addition metamethod.
136 function m.__add(a, b)
137 a, b = tocomplex(a), tocomplex(b)
138 return m.new(a.re + b.re, a.im + b.im)
139 end
140
141 --- Subtraction metamethod.
142 function m.__sub(a, b)
143 a, b = tocomplex(a), tocomplex(b)
144 return m.new(a.re - b.re, a.im - b.im)
145 end
146
147 --- Multiplication metamethod.
148 function m.__mul(a, b)
149 a, b = tocomplex(a), tocomplex(b)
150 return m.new(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re)
151 end
152
153 --- Division metamethod.
154 -- @error Division by zero.
155 function m.__div(a, b)
156 a, b = tocomplex(a), tocomplex(b)
157 local d = b.re * b.re + b.im * b.im
158 if d == 0 then
159 error("Division by zero in complex division")
160 end
161 return m.new((a.re * b.re + a.im * b.im) / d, (a.im * b.re - a.re * b.im) / d)
162 end
163
164
165 --- Unary minus metamethod.
166 function m.__unm(a)
167 a = tocomplex(a)
168 return m.new(-a.re, -a.im)
169 end
170
171 -- -----------------------------------------
172 -- Pretty printing
173 -- -----------------------------------------
174
175
176 --- Convert to string in the form `a+bi`.
177 function m.__tostring(z)
178 z = tocomplex(z)
179 return string.format("%g%+gi", z.re, z.im)
180 end
181
182 -- -----------------------------------------
183 -- Additional functions
184 -- -----------------------------------------
185
186 --- Approximate equality (L¹ norm).
187 -- @param a complex
188 -- @param b complex
189 -- @param eps number optional tolerance
190 -- @return boolean
191 function m.isClose(a, b, eps)
192 a, b = tocomplex(a), tocomplex(b)
193 eps = eps or m.EPS
194
195 local dr = abs(a.re - b.re)
196 local di = abs(a.im - b.im)
197
198 return dr + di <= eps -- norme L1, rapide
199 end
200
201
202 --- Compare unordered pairs with tolerance.
203 local function isClosePair(a, b, c, d)
204 return
205 (m.isClose(a, c) and m.isClose(b, d)) or
206 (m.isClose(a, d) and m.isClose(b, c))
207 end
208
209
210 --- Test whether two numbers are distinct (tolerant).
211 function m.distinct(a, b)
212 a, b = tocomplex(a), tocomplex(b)
213 return not m.isClose(a, b)
214 end
215
216
217 --- Test whether a complex number is nonzero (tolerant).
218 function m.nonzero(z)
219 z = tocomplex(z)
220 return m.distinct(z, 0)
221 end
222
223 --- Determinant
224 function m.det(a, b)
225 a, b = tocomplex(a), tocomplex(b)
226 return a.re * b.im - a.im * b.re
227 end
228
229 --- Scalar (dot) product.
230 function m.dot(a, b)
231 a, b = tocomplex(a), tocomplex(b)
232 return a.re * b.re + a.im * b.im
233 end
234
235 m.scal = m.dot
236
237 --- Normalize to unit modulus.
238 -- @return complex|nil nil if zero
239 function m.unit(z)
240 z = tocomplex(z)
241 local r = m.abs(z)
242 if r < m.EPS then
243 return nil
244 end
245 return z / r
246 end
247
248
249 --- Complex conjugate.
250 function m.conj(z)
251 z = tocomplex(z)
252 return m.new(z.re, -z.im)
253 end
254
255
256 --- Squared modulus.
257 function m.abs2(z)
258 z = tocomplex(z)
259 return z.re * z.re + z.im * z.im
260 end
261
262
263 --- Modulus.
264 function m.abs(z)
265 z = tocomplex(z)
266 return sqrt(z.re*z.re + z.im*z.im)
267 end
268
269
270 --- Argument (principal value).
271 -- Returns angle in radians in (-π, π].
272 function m.arg(z)
273 z = tocomplex(z)
274 return atan2(z.im, z.re)
275 end
276
277
278 --- Complex inversion in circle.
279 -- @param z complex
280 -- @param center complex optional
281 -- @param R number optional radius
282 function m.invert(z, center, R)
283 z = tocomplex(z)
284 center = tocomplex(center or m.ZERO)
285 R = R or 1
286
287 local dz = z - center
288 local d2 = dz.re*dz.re + dz.im*dz.im
289 assert(d2 > 0, "invert: undefined at center")
290 local inv = m.new(dz.re/d2, -dz.im/d2)
291 return center + (R*R) * inv
292 end
293
294 -- -----------------------------------------
295 -- Comparisons (methods, with optional tolerance)
296 -- -----------------------------------------
297
298
299 --- Approximate equality (method form).
300 function m:isNear(w, eps)
301 return m.isClose(self, w, eps)
302 end
303
304
305 --- Negated approximate comparison (method form).
306 function m:isNot(w, eps)
307 return not m.isClose(self, w, eps)
308 end
309
310 -- Integer check, no tolerance
311 function m:isInteger()
312 return self.im == 0 and self.re % 1 == 0
313 end
314
315 --- Test whether imaginary part is approx. zero (method form).
316 function m:isReal(eps)
317 eps = eps or m.EPS
318 return abs(self.im) <= eps
319 end
320
321 --- Test whether real part is approx. zero (method form).
322 function m:isImag(eps)
323 eps = eps or m.EPS
324 return abs(self.re) <= eps
325 end
326
327 -- Integer check with tolerance
328 function m:isNearInteger(eps)
329 eps = eps or m.EPS
330 if abs(self.im) > eps then
331 return false
332 end
333 local nearest = math.floor(self.re + 0.5)
334 return abs(self.re - nearest) <= eps
335 end
336
337
338 --- Test whether modulus is approx. 1 (method form).
339 function m:isUnit(eps)
340 eps = eps or m.EPS
341 local r = m.abs(self)
342 return abs(r-1) < eps
343 end
344
345
346 --- Test approx. colinearity with other number (method form).
347 function m:isColinear(other, eps)
348 eps = eps or m.EPS
349 return abs(m.det(self, other)) <= eps
350 end
351
352
353 --- Convert to polar coordinates.
354 -- @return r number
355 -- @return theta number
356 function m:toPolar()
357 return m.abs(self), m.arg(self)
358 -- Note : returns (0,0) for origin
359 end
360
361 --- Clone the complex number.
362 function m:clone()
363 return m.new(self.re, self.im)
364 end
365
366
367 --- e^{iθ}
368 function m.exp_i(theta)
369 return m.new(cos(theta), sin(theta))
370 end
371
372
373 --- Rotate by 90 degrees.
374 function m:rotate90()
375 return m.new(-self.im, self.re)
376 end
377
378
379 --- Rotate by angle θ (radians).
380 function m:rotate(theta)
381 local c = cos(theta)
382 local s = sin(theta)
383 return m.new(c*self.re - s*self.im, s*self.re + c*self.im)
384 end
385
386
387
388
389 --- Complex exponential.
390 function m.exp(z)
391 z = tocomplex(z)
392 local exp_r = exp(z.re)
393 return m.new(exp_r * cos(z.im), exp_r * sin(z.im))
394 end
395
396
397 --- Principal complex logarithm.
398 -- @error undefined for 0
399 function m.log(z)
400 z = tocomplex(z)
401 if z.re == 0 and z.im == 0 then
402 error("Logarithm undefined for 0")
403 end
404 -- Note : other languages return -inf+0*i
405 return m.new(log(m.abs(z)), m.arg(z))
406 end
407
408
409
410 -- fast integer power (binary exponentiation)
411 local function complex_pow_int(a, n)
412 if n == 0 then
413 return m.new(1, 0)
414 end
415
416 if n < 0 then
417 a = m.new(1, 0) / a
418 n = -n
419 end
420
421 local result = m.new(1, 0)
422 while n > 0 do
423 if n % 2 == 1 then
424 result = result * a
425 end
426 a = a * a
427 n = math.floor(n / 2)
428 end
429
430 return result
431 end
432
433 function m.__pow(a, b)
434 a, b = tocomplex(a), tocomplex(b)
435
436 -- Special cases
437 if a == 0 and b == 0 then
438 return m.ONE
439 end
440 if a == 0 and (b.re < 0 or b.im ~= 0) then
441 error("0 cannot be raised to a negative or complex power")
442 end
443 if a == 0 then
444 return m.ZERO
445 end
446 if b == 0 then
447 return m.ONE
448 end
449
450 if b:isInteger() then
451 return complex_pow_int(a, b.re)
452 end
453
454 -- (approx) integer exponent. Is rounding a good idea ?
455 if b:isNearInteger() then
456 local n = math.floor(b.re + 0.5) -- round
457 return complex_pow_int(a, n)
458 end
459
460 -- General complex power
461 return m.exp(b * m.log(a))
462 end
463
464 -----------------------------------------------------------------------
465 -- Constants
466 -----------------------------------------------------------------------
467
468 --- 1 + 0i
469 m.ONE = m.new(1, 0)
470
471 --- 0 + 0i
472 m.ZERO = m.new(0, 0)
473
474 --- i
475 m.I = m.new(0, 1)
476
477 --- Primitive cube root of unity.
478 m.J = m.new(-1/2, sqrt(3)/2)
479
480 complex = m
481 end
482
483 do
484 -----------------------------------------------------------------------
485 -- @module luahyperbolic-core
486 -- Pure Lua hyperbolic geometry
487 --
488 -- License:
489 -- Public Domain / CC0 1.0 Universal
490 -- 2026 Damien Mégy
491 -- This software is released into the public domain.
492 -- You may use, modify, and distribute it freely, without restriction.
493 --
494 -- SPDX-License-Identifier: CC0-1.0
495 --
496 -----------------------------------------------------------------------
497
498 local m = {}
499 m.module = "hyper"
500
501 -- ================ MESSAGES =====================
502
503 function m._error(msg)
504 error("[ERROR] " .. msg, 2)
505 end
506
507 function m._assert(cond, msg)
508 if not cond then
509 m._error(msg)
510 end
511 end
512
513
514 function m._assert_in_disk(...)
515 local points = {...}
516 for _, z in ipairs(points) do
517 m._assert(m._in_disk(z), "POINT NOT IN OPEN DISK : " .. complex.__tostring(z))
518 end
519 end
520
521 function m._assert_in_closed_disk(...)
522 local points = {...}
523 for _, z in ipairs(points) do
524 m._assert(m._in_closed_disk(z), "POINT NOT IN CLOSED DISK : " .. complex.__tostring(z))
525 end
526 end
527
528
529 function m._coerce_assert_in_disk(...)
530 local points = {complex.coerce(...)}
531 m._assert_in_disk(table.unpack(points))
532 return table.unpack(points)
533 end
534
535 function m._coerce_assert_in_closed_disk(...)
536 local points = {complex.coerce(...)}
537 m._assert_in_closed_disk(table.unpack(points))
538 return table.unpack(points)
539 end
540
541 -- ================= HELPERS (EUCLIDEAN GEOM AND OTHER)
542
543 -- precision
544 m.EPS = 1e-10
545
546 local PI = 3.1415926535898
547 local random = math.random
548 local min = math.min
549 local max = math.max
550 local sin = math.sin
551 local cos = math.cos
552 local atan2 = math.atan2
553 local exp = math.exp
554 local log = math.log
555 local sqrt = math.sqrt
556 local abs = math.abs
557 local sinh = math.sinh
558 local cosh = math.cosh
559 local tanh = math.tanh
560
561 local atanh = function(x)
562 return 0.5 * log((1 + x) / (1 - x))
563 end
564
565 local acosh = function(x)
566 return log(x + sqrt(x*x - 1))
567 end
568
569 local asinh = function(x)
570 return log(x + sqrt(x*x + 1))
571 end
572
573 -- public versions :
574 -- m.cosh = cosh
575 -- m.sinh = sinh
576 -- m.tanh = tanh
577 -- m.acosh = acosh
578 -- m.asinh = asinh
579 -- m.atanh = atanh
580
581
582
583
584 m._ensure_order = function (x, y, z, t)
585 -- if the "distance" along the circle from x to y is larger than x to z, swap
586 if complex.abs(x - y) > complex.abs(x - z) or complex.abs(t - z) > complex.abs(t - y) then
587 return t, x
588 else
589 return x, t
590 end
591 end
592
593
594
595 -- ==== EUCLIDEAN HELPERS
596
597 local euclid = {}
598 function euclid.interCC(c1, r1, c2, r2)
599 local d = complex.abs(c2 - c1)
600 if d < m.EPS then
601 return nil
602 end -- même si même rayon
603
604 if d > r1 + r2 + m.EPS or d < abs(r1 - r2) - m.EPS then
605 return nil -- no intersection
606 end
607
608 if abs(d - (r1 + r2)) < m.EPS or abs(d - abs(r1 - r2)) < m.EPS then
609 local p = c1 + (c2 - c1) * (r1 / d)
610 return p, p
611 end
612
613 local a = (r1 ^ 2 - r2 ^ 2 + d ^ 2) / (2 * d)
614 local h = sqrt(max(r1 ^ 2 - a ^ 2, 0))
615 local p_mid = c1 + ((c2 - c1) / d) * a
616 local offset = complex(-(c2.im - c1.im) / d * h, (c2.re - c1.re) / d * h)
617
618 return p_mid + offset, p_mid - offset
619 end
620
621 function euclid.interLC(z1, z2, c0, r)
622 local dir = z2 - z1
623 local f = z1 - c0
624 local a = complex.abs2(dir)
625 local b = 2 * (f.re * dir.re + f.im * dir.im)
626 local c = complex.abs2(f) - r * r
627
628 local disc = b * b - 4 * a * c
629 if disc < -m.EPS then
630 return nil
631 end
632 disc = max(disc, 0)
633
634 local sqrtD = sqrt(disc)
635 local t1 = (-b + sqrtD) / (2 * a)
636 local t2 = (-b - sqrtD) / (2 * a)
637
638 return z1 + dir * t1, z1 + dir * t2
639 end
640
641 -- ==============================
642
643 function m.randomPoint(rmin, rmax)
644 -- returns random point in disk or annulus with uniform density
645 rmax = rmax or 1 - m.EPS
646 rmax = min(rmax, 1 - m.EPS)
647 rmin = rmin or 0
648
649 m._assert(rmin >= 0 and rmax > rmin, "randomPoint: require 0 ≤ rmin < rmax")
650
651 local theta = 2 * PI * random()
652 local u = random()
653 local r = sqrt(u * (rmax ^ 2 - rmin ^ 2) + rmin ^ 2)
654
655 return complex(r * cos(theta), r * sin(theta))
656 end
657
658
659 function m._in_disk(z)
660 return complex.abs2(z) < 1 - m.EPS
661 end
662
663 function m._in_closed_disk(z)
664 return complex.abs2(z) < 1 + m.EPS
665 end
666
667 function m._on_circle(z)
668 return abs(complex.abs2(z) - 1) < m.EPS
669 end
670
671 function m._in_half_plane(z)
672 return z.im > m.EPS
673 end
674
675
676 -- =========================================================
677 -- ==================== HYPERBOLIC CALCULUS ================
678 -- =========================================================
679
680 function m._radial_half(r)
681 return r / (1 + sqrt(1 - r * r))
682 end
683
684 function m._radial_scale(r, t)
685 return tanh(t * atanh(r))
686 end
687
688
689 function m.distance(z, w)
690 z, w = m._coerce_assert_in_disk(z,w)
691 -- send w to 0 and z to zz with isometry :
692 local zz = (z-w)/(1-complex.conj(w)*z)
693 -- return dist(zz,0)
694 return 2 * atanh(complex.abs(zz))
695 end
696
697
698 local function same_distance(A, B, C, D)
699 local phiA = m.automorphism(A,0)
700 local phiC = m.automorphism(C,0)
701 local BB = phiA(B)
702 local DD = phiC(D)
703 return abs(complex.abs2(BB) - complex.abs2(DD)) < m.EPS
704 end
705
706 function m._midpoint_to_origin(z)
707 local r = complex.abs(z)
708 if r < m.EPS then
709 return complex(0, 0)
710 end
711 return (z / r) * m._radial_half(r)
712 end
713
714 function m.midpoint(a, b)
715 local u = m.automorphism(a, 0)(b)
716 local u_half = m._midpoint_to_origin(u)
717 return m.automorphism(-a, 0)(u_half)
718 end
719
720 function m._metric_factor(z)
721 return 2 / (1 - complex.abs2(z))
722 end
723
724
725 function m._geodesic_data(z, w)
726 m._assert(complex.distinct(z, w), "geodesic_data: points z and w are identical")
727
728 local u = w - z
729 local area = z.re * w.im - z.im * w.re -- signed!
730 if abs(area) < m.EPS then -- points are aligned with origin
731 return {
732 type = "diameter",
733 center = nil,
734 radius = math.huge,
735 direction = (u / complex.abs(u)),
736 }
737 end
738 local d1 = (complex.abs2(z) + 1) / 2
739 local d2 = (complex.abs2(w) + 1) / 2
740 local cx = (d1 * w.im - z.im * d2) / area
741 local cy = (z.re * d2 - d1 * w.re) / area
742 local c = complex(cx, cy)
743 local R = complex.abs(c - z)
744 return {
745 type = "circle",
746 center = c,
747 radius = R,
748 direction = nil,
749 }
750 end
751
752 function m.endpoints(a, b)
753 m._assert(complex.distinct(a,b), "endpoints : points must be distinct")
754 if abs(complex.det(a,b)) < 100*m.EPS then
755 local dir = (a-b) / complex.abs(a-b)
756 local e1, e2 = -dir, dir
757 return m._ensure_order(e1, a, b, e2)
758 end
759
760
761 -- should be circle case. rewrite this
762
763 local g = m._geodesic_data(a, b)
764 assert(g.type=="circle", "endpoints : problem with branch diameter/circle")
765 local c, R = g.center, g.radius
766 local e1, e2 = euclid.interCC(c, R, complex(0, 0), 1)
767 return m._ensure_order(e1, a, b, e2)
768 end
769
770 --[[
771 function m._same_geodesics(a, b, c, d)
772 local aa, bb = m.endpoints(a, b)
773 local cc, dd = m.endpoints(c, d)
774 local sameSet = complex.isSamePair(aa,bb,cc,dd)
775 return sameSet
776 end]]
777
778
779
780 function m.endpointsPerpendicularBisector(A, B)
781 m._assert(complex.distinct(A, B), "perpendicular_bisector: A and B must be distinct")
782
783 local M = m.midpoint(A, B)
784 local phi = m.automorphism(M, 0)
785 local phi_inv = m.automorphism(-M, 0)
786 local A1 = phi(A)
787 local u = A1 / complex.abs(A1)
788 local v = complex(-u.im, u.re)
789 local e1 = v
790 local e2 = -v
791 return phi_inv(e1), phi_inv(e2)
792 end
793
794 function m.endpointsAngleBisector(A, O, B)
795 m._assert(complex.distinct(A, O) and complex.distinct(O, B), "angle_bisector: O must be distinct from A and B")
796
797 local phi = m.automorphism(O, 0)
798 local phi_inv = m.automorphism(-O, 0)
799
800 local A1 = phi(A)
801 local B1 = phi(B)
802
803 local u1 = A1 / complex.abs(A1)
804 local u2 = B1 / complex.abs(B1)
805
806 local v = u1 + u2
807
808 if v:isNear(0) then
809 -- flat angle: perpendicular to common diameter
810 local perp = complex(-u1.im, u1.re)
811 return phi_inv(perp), phi_inv(-perp)
812 end
813
814 v = v / complex.abs(v)
815
816 return phi_inv(v), phi_inv(-v)
817 end
818
819 function m._circle_to_euclidean(z0, r)
820 -- returns euclidean center and radius of hyperbolic center and radius
821 local rho = tanh(r / 2)
822 local mod2 = complex.abs2(z0)
823 local denom = 1 - rho * rho * mod2
824 local c = ((1 - rho * rho) / denom) * z0
825 local R = ((1 - mod2) * rho) / denom
826
827 return c, R
828 end
829
830 function m.tangentVector(z, w)
831 local v
832 local g = m._geodesic_data(z, w)
833 if g.radius == math.huge then
834 v = w - z
835 else
836 local u = z - g.center
837 v = complex(-u.im, u.re)
838 if complex.scal(v, w - z) < 0 then
839 v = -v
840 end
841 end
842 return v
843 end
844
845 function m.angle(A, O, B)
846 -- oriented angle
847 local t1 = m.tangentVector(O, A)
848 local t2 = m.tangentVector(O, B)
849 return complex.arg(t2/t1)
850 end
851
852 -- =========== HYPERBOLIC ISOMETRES =============
853
854 function m.automorphism(a, theta)
855 theta = theta or 0 -- default angle = 0
856 a = m._coerce_assert_in_disk(a)
857 if a:isNear(0) then
858 return function(x)
859 return x
860 end
861 end
862 local rot = complex.exp_i(theta)
863 return function(z)
864 z = m._coerce_assert_in_closed_disk(z)
865 local numerator = z - a
866 local denominator = 1 - complex.conj(a) * z
867 return rot * (numerator / denominator)
868 end
869 end
870
871 function m.rotation(center, theta)
872 center = m._coerce_assert_in_disk(center)
873 theta = theta or 0
874 if abs(theta) < m.EPS then
875 return function(x)
876 return x
877 end
878 end
879 local phi = m.automorphism(center, 0)
880 local phi_inv = m.automorphism(-center, 0)
881 local rot = complex.exp_i(theta)
882 return function(z)
883 return phi_inv(rot * phi(z))
884 end
885 end
886
887 function m.symmetry(center)
888 return m.rotation(center, PI)
889 end
890
891 function m.symmetryAroundMidpoint(a, b)
892 return m.rotation(m.midpoint(a, b), PI)
893 end
894
895 local function parabolic_fix1(theta) -- angle in rad
896 local P = (1 - complex.exp_i(-theta)) / 2 -- preimage of zero
897 local phi = m.automorphism(P, 0)
898 local u = phi(1)
899 return function(z)
900 return phi(z) / u
901 end
902 end
903
904 function m.parabolic(idealPoint, theta)
905 m._assert(idealPoint:isUnit(), "parabolic : ideal point must be at infinity")
906 return function(z)
907 return idealPoint * parabolic_fix1(theta)(z / idealPoint)
908 end
909 end
910
911 function m.automorphismSending(z, w)
912 -- (hyperbolic)
913 if z:isNear(w) then
914 return function(x)
915 return x
916 end
917 end
918 local phi_z = m.automorphism(z, 0)
919 local phi_w_inv = m.automorphism(-w, 0)
920
921 return function(x)
922 return phi_w_inv(phi_z(x))
923 end
924 end
925
926 function m.automorphismFromPairs(A, B, imageA, imageB)
927 m._assert(complex.distinct(A, B), "automorphism_from_pairs : startpoints must be different")
928 m._assert(same_distance(A, B, imageA, imageB), "automorphism_from_pairs : distances don't match") -- or return nil ?
929
930 if A:isNear(imageA) and B:isNear(imageB) then
931 return function(z)
932 return z
933 end
934 end
935
936 local B1 = m.automorphism(A, 0)(B)
937 local BB1 = m.automorphism(imageA, 0)(imageB)
938 local u = complex.unit(BB1 / B1)
939
940 return function(z)
941 return m.automorphism(-imageA, 0)(u * m.automorphism(A, 0)(z))
942 end
943 end
944
945 function m.rotationFromPair(O, A, imageA)
946 return m.automorphismFromPairs(O, A, O, imageA)
947 end
948
949 function m.reflection(z1, z2)
950 -- rewrite with automorphisms ? maybe not
951 local g = m._geodesic_data(z1, z2)
952
953 if g.radius == math.huge then
954 local dir = (z2-z1) / complex.abs(z2-z1)
955 return function(z)
956 local proj = (dir * complex.conj(z)).re * dir
957 local perp = z - proj
958 return proj - perp
959 end
960 else
961 local c, R = g.center, g.radius
962 return function(z)
963 local u = z - c
964 local v = (R * R) / complex.conj(u)
965 return c + v
966 end
967 end
968 end
969
970
971 function m.projection(z1, z2)
972 local refl = m.reflection(z1, z2)
973 return function(z)
974 local z_ref = refl(z)
975 return m.midpoint(z, z_ref)
976 end
977 end
978
979 function m.pointOrbit(point, func, n)
980 local points = {}
981 for _ = 1, n do
982 point = func(point)
983 table.insert(points, point)
984 end
985 return points
986 end
987
988
989 function m.mobiusTransformation(a, b, c, d)
990 -- general Möbius transform
991 return function(z)
992 return (a * z + b) / (c * z + d)
993 end
994 end
995
996 function m.distanceToLine(z, z1, z2)
997 local p = (m.projection(z1, z2))(z)
998 return m.distance(z, p)
999 end
1000
1001 function m._on_line(z, a, b, eps)
1002 eps = eps or m.EPS
1003 local phi = m.automorphism(a,0)
1004 local zz = phi(z)
1005 local bb = phi(b)
1006 return abs(complex.det(zz,bb)) < eps
1007 end
1008
1009 function m._on_segment(z, a, b, eps)
1010 eps = eps or m.EPS
1011 return abs(m.distance(a,b) - m.distance(a,z) - m.distance(z,b)) < eps
1012 end
1013
1014 -- ========== EXPONENTIAL MAPS (vector -> point) ==========
1015
1016 -- ! local ! expose as "_exp_map_at_origin" ?
1017 local function exp_map_at_origin(v)
1018 -- input : vector, output : point
1019 if v:isNear(0) then return complex(0,0) end
1020
1021 local norm_v = complex.abs(v)
1022 return v / norm_v * tanh(norm_v / 2)
1023 end
1024
1025 --- Exponential map at a point P
1026 -- @param P complex
1027 -- @param vector complex (vector)
1028 -- @return complex
1029 function m.expMap(P, vector)
1030 P, vector = complex.coerce(P, vector)
1031 m._assert_in_disk(P)
1032 if vector:isNear(0) then
1033 return P
1034 end
1035 local w = exp_map_at_origin(vector)
1036 if P:isNear(0) then
1037 return w
1038 end
1039 return m.automorphism(-P, 0)(w)
1040 end
1041
1042
1043 -- ============ INTERPOLATE, BARYCENTERS OF 2 POINTS =====
1044
1045 function m.interpolate(a, b, t)
1046 if a:isNear(b) then return a end
1047 local phi = m.automorphism(a, 0)
1048 local phi_inv = m.automorphism(-a, 0)
1049
1050 local u = phi(b)
1051 local r = complex.abs(u)
1052 if r < m.EPS then
1053 return a
1054 end
1055
1056 local r_t = m._radial_scale(r, t)
1057 local u_t = u * (r_t / r)
1058
1059 return phi_inv(u_t)
1060 end
1061
1062 function m.barycenter2(a, wa, b, wb)
1063 local s = wa + wb
1064 m._assert(abs(s) > m.EPS, "barycenter2: sum of weights must not be zero")
1065
1066 local t = wb / s
1067 return m.interpolate(a, b, t)
1068 end
1069
1070
1071
1072 -- ============ INTERSECTIONS ==============================
1073
1074 function m.interLC(z1, z2, c0, r)
1075 local ce, Re = m._circle_to_euclidean(c0, r)
1076 local g = m._geodesic_data(z1, z2)
1077 if g.radius == math.huge then
1078 return euclid.interLC(complex(0, 0), g.direction, ce, Re)
1079 else
1080 return euclid.interCC(g.center, g.radius, ce, Re)
1081 end
1082 end
1083
1084 function m.interCC(c1, r1, c2, r2)
1085 local C1, R1 = m._circle_to_euclidean(c1, r1)
1086 local C2, R2 = m._circle_to_euclidean(c2, r2)
1087
1088 return euclid.interCC(C1, R1, C2, R2)
1089 end
1090
1091 function m.interLL(z1, z2, w1, w2)
1092 local g1 = m._geodesic_data(z1, z2)
1093 local g2 = m._geodesic_data(w1, w2)
1094 local is_diam1 = (g1.radius == math.huge)
1095 local is_diam2 = (g2.radius == math.huge)
1096
1097 if is_diam1 and is_diam2 then
1098 local u = g1.direction
1099 local v = g2.direction
1100
1101 local dot = u.re * v.re + u.im * v.im
1102 if abs(abs(dot) - 1) < m.EPS then
1103 return nil
1104 end
1105
1106 return complex(0, 0)
1107 end
1108
1109 if is_diam1 and not is_diam2 then
1110 local line_p1 = complex(0, 0)
1111 local line_p2 = g1.direction
1112 return euclid.interLC(line_p1, line_p2, g2.center, g2.radius)
1113 end
1114
1115 if not is_diam1 and is_diam2 then
1116 local line_p1 = complex(0, 0)
1117 local line_p2 = g2.direction
1118 return euclid.interLC(line_p1, line_p2, g1.center, g1.radius)
1119 end
1120
1121 local p1, p2 = euclid.interCC(g1.center, g1.radius, g2.center, g2.radius)
1122
1123 if not p1 then
1124 return nil
1125 end
1126
1127 local inside1 = m._in_disk(p1)
1128 local inside2 = m._in_disk(p2)
1129
1130 if inside1 and not inside2 then
1131 return p1
1132 elseif inside2 and not inside1 then
1133 return p2
1134 else
1135 return nil
1136 end
1137 end
1138
1139 ----------------------------------
1140 -- TRIANGLE GEOMETRY
1141 ---------------------------------
1142
1143 function m.triangleCentroid(A, B, C)
1144 -- Intersection des trois médianes.
1145 -- /!\ Pas au deux tiers des médianes
1146 local AA = m.midpoint(B, C)
1147 local BB = m.midpoint(C, A)
1148 local centroid = m.interLL(A, AA, B, BB)
1149 return centroid
1150 end
1151
1152
1153 function m.triangleIncenter(A, B, C)
1154 m._assert(
1155 complex.distinct(A, B) and complex.distinct(B, C) and complex.distinct(C, A),
1156 "incenter: points must be distinct"
1157 )
1158
1159 local e1, e2 = m.endpointsAngleBisector(A, B, C)
1160 local f1, f2 = m.endpointsAngleBisector(B, C, A)
1161 return m.interLL(e1, e2, f1, f2)
1162 end
1163
1164 ----------------
1165 -- CAUTION : orthocenter and circumcenter do not always exist
1166
1167 function m.triangleCircumcenter(A, B, C)
1168 -- WARNING returns circumcenter or nil
1169 m._assert(
1170 complex.distinct(A, B) and complex.distinct(B, C) and complex.distinct(C, A),
1171 "circumcenter: points must be distinct"
1172 )
1173
1174 local e1, e2 = m.endpointsPerpendicularBisector(A, B)
1175 local f1, f2 = m.endpointsPerpendicularBisector(A, C)
1176
1177 return m.interLL(e1, e2, f1, f2) -- can be nil
1178 end
1179
1180
1181 function m.triangleOrthocenter(A,B,C)
1182 -- Faster than projecting, no midpoint:
1183 local AA = m.reflection(B,C)(A)
1184 local BB = m.reflection(C,A)(B)
1185 return m.interLL(A,AA,B,BB) -- can be nil
1186 end
1187
1188
1189 local function side_from_angles(opposite, other1, other2)
1190 if opposite == 0 then return math.huge end
1191 local cosh_a = (cos(opposite) + cos(other1)*cos(other2)) / (sin(other1)*sin(other2))
1192 return acosh(cosh_a)
1193 end
1194
1195 function m.triangleWithAngles(alpha, beta, gamma)
1196 m._assert(alpha >= 0 and beta >= 0 and gamma >= 0, "Angles must be >=0")
1197
1198 m._assert(alpha + beta + gamma < math.pi,
1199 "Sum of angles must be less than PI")
1200
1201 local angles = {alpha, beta, gamma}
1202 table.sort(angles, function(x,y) return x > y end)
1203 alpha, beta, gamma = angles[1], angles[2], angles[3]
1204
1205 if alpha == 0 then
1206 return complex(1,0), complex.J, complex.J^2
1207 end
1208
1209 local A = complex(0,0)
1210
1211 if beta == 0 and gamma == 0 then
1212 return A, complex(1, 0), complex.polar(1, alpha)
1213 end
1214
1215
1216 if gamma == 0 then
1217 local K = (cos(alpha)*cos(beta) + 1) / (sin(alpha)*sin(beta))
1218 local r2 = (K - 1) / (K + 1)
1219 local r = sqrt(r2)
1220 return A, complex(r,0), complex.polar(1,alpha)
1221 end
1222
1223 local c = side_from_angles(gamma, alpha, beta)
1224 local rc = tanh(c/2)
1225 local b = side_from_angles(beta, gamma, alpha)
1226 local rb = tanh(b/2)
1227 local B = complex.polar(rc, 0)
1228 local C = complex.polar(rb, alpha)
1229
1230 return A,B,C
1231 end
1232
1233
1234 -- function m.triangleWithOrderedAngles(alpha, beta, gamma)
1235 -- local angles = {alpha, beta, gamma}
1236 -- local phi = {1,2,3}
1237 -- table.sort(phi, function(i,j) return angles[i] > angles[j] end)
1238 -- local p = {}
1239 -- p[1], p[2], p[3] = m.triangleWithAngles(angles[phi[1]], angles[phi[2]], angles[phi[3]])
1240 -- local psi = {} -- inverse of phi
1241 -- for i=1,3 do
1242 -- psi[p[i]] = i
1243 -- end
1244 -- return p[psi[1]], p[psi[2]], p[psi[3]]
1245 -- end
1246
1247 core = m
1248 end
1249
1250 do
1251 -----------------------------------------------------------------------
1252 -- @module luahyperbolic-tikz
1253 -- Pure Lua hyperbolic geometry
1254 --
1255 -- License:
1256 -- Public Domain / CC0 1.0 Universal
1257 -- 2026 Damien Mégy
1258 -- This software is released into the public domain.
1259 -- You may use, modify, and distribute it freely, without restriction.
1260 --
1261 -- SPDX-License-Identifier: CC0-1.0
1262 --
1263 -----------------------------------------------------------------------
1264
1265 -- ============ BEGIN MODULE "LUAHYPERBOLIC-TIKZ" ============
1266
1267 local m = {}
1268
1269 m.module = "luahyperbolic-tikz"
1270
1271 m.TIKZ_CLIP_DISK = true -- can be modified by user.
1272 m.TIKZ_BEGIN_DISK = [[
1273 \begin{scope}
1274 \clip (0,0) circle (1);
1275 ]]
1276
1277 m.GEODESIC_STYLE = "black"
1278 m.CIRCLE_STYLE = "black"
1279 m.HOROCYCLE_STYLE = "black"
1280 m.HYPERCYCLE_STYLE = "black"
1281 m.ANGLE_STYLE = "black"
1282 m.MARKING_STYLE = "black"
1283 m.LABEL_STYLE = "above left"
1284 m.DRAW_POINT_RADIUS = 0.02
1285 m.DRAW_POINT_STYLE = "white, draw=black"
1286 m.DRAW_ANGLE_DIST = 1/5
1287 m.MARKING_SIZE = "footnotesize"
1288 m.BOUNDARY_CIRCLE_STYLE = "very thick, black"
1289
1290
1291
1292 -- ========= REDEFINE ERROR (TeX error)
1293
1294 function m._error(msg)
1295 tex.error("Package " .. m.module .. " Error ", { msg })
1296 end
1297
1298 function m._warning(msg)
1299 texio.write_nl("[WARNING] " .. msg)
1300 end
1301
1302 -- ========= HELPERS (EUCLIDEAN GEOM AND OTHER)
1303
1304 local PI = 3.1415926535898
1305 local deg = math.deg
1306 local min = math.min
1307 local max = math.max
1308 local sin = math.sin
1309 local cos = math.cos
1310 local atan2 = math.atan2
1311 local exp = math.exp
1312 local log = math.log
1313 local sqrt = math.sqrt
1314 local abs = math.abs
1315 local sinh = math.sinh
1316 local cosh = math.cosh
1317 local tanh = math.tanh
1318
1319
1320 local function euclidean_circumcenter(a, b, c)
1321 a, b, c = complex.coerce(a, b, c)
1322 core._assert(abs(complex.det(b-a,c-a)) > core.EPS, "points must not be aligned")
1323 local ma2 = complex.abs2(a)
1324 local mb2 = complex.abs2(b)
1325 local mc2 = complex.abs2(c)
1326 local num = a*(mb2 - mc2) + b*(mc2 - ma2) + c*(ma2 - mb2)
1327 local den = a*complex.conj(b - c) + b*complex.conj(c - a) + c*complex.conj(a - b)
1328
1329 return num / den
1330 end
1331
1332
1333
1334
1335 local function parse_points_with_options(...)
1336 -- errors if no point provided
1337 local args = { ... }
1338 local n = #args
1339 local options = nil
1340
1341 if n >= 1 and type(args[n]) == "string" then
1342 options = args[n]
1343 n = n - 1
1344 end
1345
1346 local points = {}
1347 for i = 1, n do
1348 points[i] = args[i]
1349 end
1350
1351 core._assert(#points > 0, "parse_points_with_options : no points provided")
1352
1353 return points, options
1354 end
1355
1356
1357 -- ========== TikZ API
1358
1359 m.tikzpictureOptions = ""
1360 m.tikzBuffer = {}
1361 m.tikzNbPicturesExported = 0
1362
1363
1364 function m.tikzGetFirstLines()
1365 local firstLines = string.format(
1366 "\\begin{tikzpicture}[%s]\n",
1367 m.tikzpictureOptions
1368 )
1369 if m.TIKZ_CLIP_DISK then
1370 firstLines = firstLines .. m.TIKZ_BEGIN_DISK
1371 end
1372 return firstLines
1373 end
1374
1375 function m.tikzBegin(options)
1376 -- without drawing circle and clipping disk
1377 m.tikzpictureOptions = options or "scale=3"
1378 tex.print(m.tikzGetFirstLines())
1379 m.tikzClearBuffer()
1380
1381 end
1382
1383
1384 function m.tikzClearBuffer()
1385 m.tikzBuffer = {}
1386 end
1387
1388
1389 function m.tikzExport(filename)
1390 -- works even without filename, for automated exports
1391 m.tikzNbPicturesExported = m.tikzNbPicturesExported+1
1392 filename = filename or "hyper_picture_" ..m.tikzNbPicturesExported .. ".tikz"
1393 local f = io.open(filename, "w")
1394 f:write(m.tikzGetFirstLines())
1395 for _, line in ipairs(m.tikzBuffer) do
1396 f:write(line, "\n")
1397 end
1398 f:write("\\end{scope}\n")
1399 f:write("\\draw[".. m.BOUNDARY_CIRCLE_STYLE .."] (0,0) circle (1);\n")
1400 f:write("\\end{tikzpicture}\n")
1401 f:close()
1402 -- doesn't clear buffer, do it manually if wanted
1403 -- can be used to export different steps of the same picture
1404 end
1405
1406
1407 function m.tikzEnd(filename)
1408 tex.print("\\end{scope}")
1409 tex.print("\\draw[".. m.BOUNDARY_CIRCLE_STYLE .."] (0,0) circle (1);")
1410 tex.print("\\end{tikzpicture}")
1411 if filename ~= nil then
1412 m.tikzExport(filename)
1413 end
1414 m.tikzClearBuffer()
1415 end
1416
1417
1418 function m.tikzPrintf(fmt, ...)
1419 local line = string.format(fmt, ...)
1420 tex.print(line)
1421 table.insert(m.tikzBuffer, line)
1422 end
1423
1424 function m.tikzDefineNodes(table)
1425 -- table of complex numbers
1426 for name, z in pairs(table) do
1427 core._assert(z ~= nil, "nil point for " .. name)
1428 core._assert(z.re ~= nil and z.im ~= nil, "not a complex for " .. name)
1429 m.tikzPrintf("\\coordinate (%s) at (%f,%f);", name, z.re, z.im)
1430 end
1431 end
1432
1433 -- ========== DRAW POINT(S) ==========
1434
1435
1436 function m.drawPoint(z, options)
1437 options = options or m.DRAW_POINT_STYLE
1438 -- accept nil point (circumcenter can be nil)
1439 if z == nil then
1440 m._warning("drawPoint : point is nil, aborting")
1441 return
1442 end
1443 z = core._coerce_assert_in_closed_disk(z)
1444 m.tikzPrintf("\\fill[%s] (%f,%f) circle (%f);", options, z.re, z.im, m.DRAW_POINT_RADIUS)
1445 end
1446
1447
1448 function m.drawPoints(...)
1449 local points, options = parse_points_with_options(...)
1450 options = options or m.DRAW_POINT_STYLE
1451
1452 for i = 1, #points do
1453 m.drawPoint(points[i], options)
1454 end
1455 end
1456
1457
1458
1459 function m.drawPointOrbit(point, func, n, options)
1460 -- draws n points. Doesn't draw original point
1461 options = options or "black"
1462 local points = core.pointOrbit(point, func, n)
1463
1464 for i, z in ipairs(points) do
1465 local alpha = i / #points
1466 m.drawPoint(z, options .. ", fill opacity=" .. alpha)
1467 end
1468 end
1469
1470 -- ========== DRAW LINES, SEGMENTS ETC ==========
1471
1472 function m.drawSegment(z, w, options)
1473 options = options or m.GEODESIC_STYLE
1474 z,w = complex.coerce(z,w)
1475 core._assert(z:isNot(w), "points must be distinct")
1476 local shape = m.tikz_shape_segment(z,w)
1477 m.tikzPrintf("\\draw[%s] %s;",options, shape)
1478 end
1479
1480 function m.markSegment(z, w, markString)
1481 size = m.MARKING_SIZE
1482 z,w = complex.coerce(z,w)
1483 core._assert(z:isNot(w), "points must be distinct")
1484 local shape = m.tikz_shape_segment(z,w)
1485 m.tikzPrintf("\\path %s node[sloped,midway,font=\\%s] {%s} ;",
1486 -- m.tikzPrintf("\\path[postaction={decorate,decoration={markings, mark=at position %f with {\\node[transform shape,sloped,font=\\%s] {%s};}}}] %s;",
1487 shape,
1488 size,
1489 markString
1490 )
1491 end
1492
1493 function m.tikz_shape_segment(z, w)
1494 core._assert(z:isNot(w), "points must be distinct")
1495 local g = core._geodesic_data(z, w)
1496
1497 -- If the geodesic is (almost) a diameter, draw straight segment
1498 if g.radius == math.huge or g.radius > 100 then
1499 return string.format("(%f,%f)--(%f,%f)", z.re, z.im, w.re, w.im)
1500 else
1501 local a1 = complex.arg(z - g.center)
1502 local a2 = complex.arg(w - g.center)
1503 local delta = atan2(sin(a2 - a1), cos(a2 - a1))
1504 local a_end = a1 + delta
1505 local degPerRad = 180 / PI
1506 return string.format(
1507 "(%f,%f) ++(%f:%f) arc (%f:%f:%f)",
1508 g.center.re,
1509 g.center.im,
1510 a1 * degPerRad,
1511 g.radius,
1512 a1 * degPerRad,
1513 a_end * degPerRad,
1514 g.radius
1515 )
1516 end
1517 end
1518
1519
1520
1521 function m.tikz_shape_closed_line(a,b)
1522 -- todo : add "close" flag to decide if we close diameters ?
1523 core._assert(a:isNot(b), "points must be distinct")
1524 if not a:isUnit() or not b:isUnit() then
1525 a, b = core.endpoints(a,b)
1526 end
1527 if a:isNear(-b) then
1528 -- WARNING : HACK : close diameter as rectangle !
1529 -- (for filling with even-odd rule)
1530 local factor = 1.1
1531 a, b = factor*a, factor*b
1532 local c, d = b*complex(1,-1), a * complex(1,1)
1533 return string.format("(%f,%f) -- (%f,%f) -- (%f,%f) -- (%f,%f) -- cycle ",
1534 a.re, a.im, b.re, b.im, c.re, c.im, d.re, d.im)
1535 else
1536 local c = 2*a*b/(a+b)
1537 local r = complex.abs(c-a)
1538 -- rest of the circle will be clipped
1539 return string.format("(%f,%f) circle (%f)", c.re, c.im, r)
1540
1541 end
1542 end
1543
1544
1545
1546 function m.drawLine(a, b, options)
1547 options = options or m.GEODESIC_STYLE
1548
1549 a, b = core._coerce_assert_in_closed_disk(a,b)
1550 core._assert(not a:isNear(b), "drawLine : points must be distinct")
1551
1552 local end_a, end_b = core.endpoints(a,b)
1553 local shape = m.tikz_shape_segment(end_a,end_b)
1554 m.tikzPrintf("\\draw[%s] %s;", options, shape)
1555 end
1556
1557
1558 function m.drawLinesFromTable(pairs, options)
1559 options = options or m.GEODESIC_STYLE
1560 for _, pair in ipairs(pairs) do
1561 m.drawLine(pair[1], pair[2], options)
1562 end
1563 end
1564
1565 function m.drawPerpendicularThrough(P,A,B,options)
1566 -- perpendicular through P to geodesic (A,B)
1567 options = options or m.GEODESIC_STYLE
1568 P, A, B = core._coerce_assert_in_closed_disk(P, A, B)
1569 core._assert(A:isNot(B), "A and B must be distinct")
1570 local H = core.projection(A,B)(P)
1571 core._assert(P:isNot(H), "point must not be on line")
1572 -- todo : fix this : should be ok.
1573 m.drawLine(P,H,options)
1574 end
1575
1576
1577
1578 function m.drawPerpendicularBisector(A, B, options)
1579 options = options or m.GEODESIC_STYLE
1580 A, B = core._coerce_assert_in_closed_disk(A, B)
1581
1582 core._assert(A:isNot(B), "drawPerpendicularBisector: A and B must be distinct")
1583
1584 local e1, e2 = core.endpointsPerpendicularBisector(A, B)
1585 m.drawLine(e1, e2, options)
1586 end
1587
1588 function m.drawAngleBisector(A, O, B, options)
1589 options = options or m.GEODESIC_STYLE
1590 A, O, B = core._coerce_assert_in_closed_disk(A, O, B)
1591
1592 core._assert(complex.distinct(O,A) and complex.distinct(O,B),
1593 "angle_bisector: O must be distinct from A and B")
1594
1595 local e1, e2 = core.endpointsAngleBisector(A, O, B)
1596 m.drawLine(e1, e2, options)
1597 end
1598
1599 --- Draw a hyperbolic ray from two points: start at p1, through p2
1600 function m.drawRayFromPoints(p1, p2, options)
1601 options = options or m.GEODESIC_STYLE
1602 local _, e2 = core.endpoints(p1, p2) -- e2 is the "ahead" endpoint
1603 m.drawSegment(p1, e2, options)
1604 end
1605
1606 m.drawRay = m.drawRayFromPoints
1607
1608 --- Draw a hyperbolic ray from a start point p along a tangent vector v
1609 function m.drawRayFromVector(p, v, options)
1610 options = options or m.GEODESIC_STYLE
1611 p = core._coerce_assert_in_disk(p)
1612 -- TODO : allow point at infinity (check vector direction) FIX/TEST
1613 local q = core.expMap(p, v) -- move along v in hyperbolic space
1614 local _, e2 = core.endpoints(p, q)
1615 m.drawSegment(p, e2, options)
1616 end
1617
1618 function m.drawLineFromVector(p, v, options)
1619 options = options or m.GEODESIC_STYLE
1620 -- TODO : allow point at infinity
1621 local q = core.expMap(p, v) -- move along v in hyperbolic space
1622 m.drawLine(p, q, options)
1623 end
1624
1625 function m.drawTangentAt(center, point, options)
1626 -- draw tangent line of circle of center 'center' passing through 'point'
1627 options = options or m.GEODESIC_STYLE
1628 center, point = core._coerce_assert_in_disk(center, point)
1629 local Q = core.rotation(point, PI / 2)(center)
1630 m.drawLine(point, Q, options)
1631 end
1632
1633 -- function m.drawTangentFrom(center, radius, point)
1634 -- TODO !
1635 -- return
1636 -- end
1637
1638 -- ========== VECTORS =============
1639
1640
1641 function m.tikz_shape_euclidean_segment(a,b)
1642 return string.format(
1643 "(%f,%f) -- (%f,%f)",a.re, a.im, b.re, b.im)
1644 end
1645
1646 function m.drawVector(p, v, options)
1647 options = options or ""
1648 local norm_v = complex.abs(v)
1649 core._assert(norm_v > core.EPS, "drawVector : vector must not be zero")
1650 local u = v / norm_v
1651 local factor = (1 - complex.abs2(p))
1652 local euclid_vec = tanh(factor * norm_v / 2) * u
1653 local shape = m.tikz_shape_euclidean_segment(p, p+euclid_vec)
1654 m.tikzPrintf("\\draw[->,%s] %s;",options,shape)
1655 end
1656
1657 -- ========== FOR CONVENIENCE (draw multiple objets/segments etc
1658
1659 function m.drawLines(...)
1660 local points, options = parse_points_with_options(...)
1661 core._assert(#points % 2 == 0, "drawLines expects an even number of points, got " .. #points)
1662
1663 for i = 1, #points, 2 do
1664 m.drawLine(points[i], points[i + 1], options)
1665 end
1666 end
1667
1668 function m.drawSegments(...)
1669 local points, options = parse_points_with_options(...)
1670
1671 core._assert(#points % 2 == 0, "drawSegments expects an even number of points, got " .. #points)
1672
1673 for i = 1, #points, 2 do
1674 m.drawSegment(points[i], points[i + 1], options)
1675 end
1676 end
1677
1678 function m.markSegments(...)
1679 -- parameters : points and optional options string
1680 local points, options = parse_points_with_options(...)
1681 for i = 1, #points, 2 do
1682 m.markSegment(points[i], points[i + 1], options)
1683 end
1684 end
1685
1686 function m.drawTriangle(...)
1687 local points, options = parse_points_with_options(...)
1688
1689 core._assert(#points == 3, "drawTriangle expects exactly 3 points, got " .. #points)
1690
1691 local a, b, c = points[1], points[2], points[3]
1692 m.drawSegment(a, b, options)
1693 m.drawSegment(b, c, options)
1694 m.drawSegment(c, a, options)
1695 end
1696
1697 -- Draw a polyline from a table of points (open chain)
1698 function m.drawPolylineFromTable(points, options)
1699 options = options or m.GEODESIC_STYLE
1700 core._assert(#points >= 2, "drawPolylineFromTable expects at least 2 points, got " .. #points)
1701
1702 for i = 1, #points - 1 do
1703 m.drawSegment(points[i], points[i + 1], options)
1704 end
1705 end
1706
1707 function m.drawPolyline(...)
1708 local points, options = parse_points_with_options(...)
1709 core._assert(#points >= 2, "drawPolyline expects at least 2 points, got " .. #points)
1710 m.drawPolylineFromTable(points, options)
1711 end
1712
1713
1714 function m.drawPolygonFromTable(points, options)
1715 options = options or m.GEODESIC_STYLE
1716 core._assert(#points >= 2, "drawPolygonFromTable expects at least 2 points, got " .. #points)
1717
1718 for i = 1, #points do
1719 local z = points[i]
1720 local w = points[i % #points + 1] -- wrap around to first point
1721 m.drawSegment(z, w, options)
1722 end
1723 end
1724
1725 function m.drawPolygon(...)
1726 local points, options = parse_points_with_options(...)
1727
1728 -- a 2-gon is a polygon
1729 core._assert(#points >= 2, "drawPolygon expects at least 2 points, got " .. #points)
1730 m.drawPolygonFromTable(points, options)
1731 end
1732
1733 function m.drawRegularPolygon(center, point, nbSides, options)
1734 options = options or m.GEODESIC_STYLE
1735 core._assert(nbSides>1, "drawRegularPolygon : expects >=2 sides, got " .. nbSides)
1736 core._assert_in_disk(center)
1737 core._assert_in_disk(point)
1738 core._assert(complex.distinct(center, point), "drawRegularPolygon : center and point must be distinct")
1739 local rot = core.rotation(center, 2*PI/nbSides)
1740 local vertices = {}
1741 for k=1,nbSides do
1742 point = rot(point)
1743 table.insert(vertices, point)
1744 end
1745 m.drawPolygonFromTable(vertices, options)
1746 end
1747
1748 -- ========== DRAW CIRCLES, SEMICIRCLES, ARCS ==========
1749
1750 function m.drawCircleRadius(z0, r, options)
1751 options = options or m.CIRCLE_STYLE
1752 z0 = core._coerce_assert_in_disk(z0)
1753 local c, R = core._circle_to_euclidean(z0, r)
1754
1755 m.tikzPrintf("\\draw[%s] (%f,%f) circle (%f);", options, c.re, c.im, R)
1756 end
1757
1758 m.drawCircle = m.drawCircleRadius
1759
1760 function m.drawCircleThrough(center, point, options)
1761 options = options or m.CIRCLE_STYLE
1762 center, point = core._coerce_assert_in_disk(center, point)
1763 local r = core.distance(center, point)
1764 m.drawCircle(center, r, options)
1765 end
1766
1767 function m.drawIncircle(A, B, C, options)
1768 options = options or m.CIRCLE_STYLE
1769 A, B, C = core._coerce_assert_in_disk(A, B, C)
1770 local I = core.triangleIncenter(A, B, C)
1771 local a = core.projection(B, C)(I)
1772 m.drawCircleThrough(I, a, options)
1773 end
1774
1775 function m.drawCircumcircle(A, B, C, options)
1776 options = options or m.CIRCLE_STYLE
1777 A, B, C = core._coerce_assert_in_disk(A, B, C)
1778 local O = core.triangleCircumcenter(A, B, C)
1779 if O ~= nil then
1780 m.drawCircleThrough(O,A, options)
1781 else
1782 m._warning("drawCircumcircle : circumcenter does not exist")
1783 end
1784 end
1785
1786
1787
1788 function m.drawArc(O, A, B, options)
1789 options = options or m.CIRCLE_STYLE
1790 O, A, B = core._coerce_assert_in_disk(O, A, B)
1791
1792 -- Check points are on same hyperbolic circle
1793 local rA = core.distance(O, A)
1794 local rB = core.distance(O, B)
1795 core._assert(abs(rA - rB) < core.EPS, "drawArc: points A and B are not on the same hyperbolic circle")
1796
1797 local c, R = core._circle_to_euclidean(O, rA)
1798
1799 -- Compute angles of A and B on the Euclidean circle
1800 local function angleOnCircle(p)
1801 return deg(atan2(p.im - c.im, p.re - c.re)) % 360
1802 end
1803 local a1 = angleOnCircle(A)
1804 local a2 = angleOnCircle(B)
1805
1806 -- Keep increasing angles: TikZ arc goes from a1 to a2
1807 -- If a2 < a1, TikZ automatically interprets end > start as crossing 0°
1808 if a2 < a1 then
1809 a2 = a2 + 360
1810 end
1811
1812 m.tikzPrintf("\\draw[%s] (%f,%f) ++(%f:%f) arc (%f:%f:%f);", options, c.re, c.im, a1, R, a1, a2, R)
1813 end
1814
1815 function m.drawSemicircle(center, startpoint, options)
1816 options = options or m.CIRCLE_STYLE
1817 local endpoint = (core.symmetry(center))(startpoint)
1818 m.drawArc(center, startpoint, endpoint, options)
1819 end
1820
1821
1822
1823
1824
1825 -- ========== HOROCYCLES AND HYPERCYCLES
1826
1827 function m.drawHorocycle(idealPoint, point, options)
1828 options = options or m.HOROCYCLE_STYLE
1829
1830 core._assert(complex.isClose(complex.abs(idealPoint), 1), "drawHorocycle: ideal point must be on unit circle")
1831 core._assert(core._in_disk(point), "drawHorocycle: second point must be in disk")
1832 -- rotate :
1833 local w = point / idealPoint
1834 local x, y = w.re, w.im
1835 -- compute center and radius
1836 local a = (x ^ 2 + y ^ 2 - 1) / (2 * (x - 1))
1837 local r = abs(a - 1)
1838 local center = complex.new(a, 0)
1839 -- rotate back
1840 center = center * idealPoint
1841
1842 m.tikzPrintf("\\draw[%s] (%f,%f) circle (%f);", options, center.re, center.im, r)
1843 end
1844
1845
1846 function m.drawHypercycleThrough(P, A, B, options)
1847 options = options or m.HYPERCYCLE_STYLE
1848 P, A, B = complex.coerce(P, A, B)
1849 if not A:isUnit() or not B:isUnit() then
1850 A, B = core.endpoints(A, B)
1851 end
1852 if abs(complex.det(P-A, P-B)) < core.EPS then
1853 m.tikzPrintf("\\draw[%s] (%f,%f) -- (%f,%f);", options, A.re, A.im, B.re, B.im)
1854 return
1855 end
1856 local O = euclidean_circumcenter(P, A, B)
1857 local radius = complex.abs(O-A)
1858 m.tikzPrintf("\\draw[%s] (%f,%f) circle (%f);", options, O.re, O.im, radius)
1859 end
1860
1861
1862
1863 -- ========== DRAW ANGLES, RIGHT ANGLES
1864
1865 function m.drawAngle(A, O, B, options, distFactor)
1866 distFactor = distFactor or m.DRAW_ANGLE_DIST
1867 options = options or m.ANGLE_STYLE
1868 core._assert_in_disk(A)
1869 core._assert_in_disk(O)
1870 core._assert_in_disk(B)
1871
1872 local dOA = core.distance(O,A)
1873 local dOB = core.distance(O,B)
1874 local minDist = min(dOA,dOB)
1875 local radius= minDist*distFactor
1876 local AA = core.interpolate(O,A,radius / dOA)
1877 local BB = core.interpolate(O,B,radius/ dOB)
1878 m.drawArc(O,AA,BB, options)
1879 end
1880
1881 function m.drawRightAngle(A, O, B, options, distFactor)
1882 -- assumes angle(AOB) = +90 deg !
1883 distFactor = distFactor or m.DRAW_ANGLE_DIST
1884 options = options or m.ANGLE_STYLE
1885 core._assert_in_disk(A)
1886 core._assert_in_disk(O)
1887 core._assert_in_disk(B)
1888 local dOA = core.distance(O,A)
1889 local dOB = core.distance(O,B)
1890 local minDist = min(dOA, dOB)
1891 local radius = minDist*distFactor
1892 local AA = core.interpolate(O,A,radius / dOA)
1893 local BB = core.interpolate(O,B,radius / dOB)
1894
1895 local v = core.tangentVector(AA,A)*complex.I
1896 local w = core.tangentVector(BB,B)*(-complex.I)
1897 local VV = core.expMap(AA,v)
1898 local WW = core.expMap(BB,w)
1899 local P = core.interLL(AA,VV, BB, WW)
1900 -- fast&lazy : euclidean polyline instead of geodesic:
1901 m.tikzPrintf("\\draw[%s] (%f,%f) -- (%f,%f) -- (%f,%f);",
1902 options,
1903 AA.re, AA.im,
1904 P.re, P.im,
1905 BB.re, BB.im
1906 )
1907 end
1908
1909 -- ========== LABEL OBJETS ==================
1910
1911
1912 function m.labelPoint(z, label, options)
1913 options = options or m.LABEL_STYLE
1914 -- accept nil point (circumcenter can be nil)
1915 if z == nil then
1916 m._warning("labelPoint : point is nil, aborting")
1917 return
1918 end
1919 m.tikzPrintf("\\node[%s] at (%f,%f) {%s};", options, z.re, z.im, label)
1920 end
1921
1922 function m.labelPoints(...)
1923 -- always above left !
1924 local args = { ... }
1925 local n = #args
1926 local options = m.LABEL_STYLE -- default : "above left"
1927
1928 if n >= 3 and type(args[n]) == "string" and (n % 2 == 1) then
1929 options = args[n]
1930 n = n - 1
1931 end
1932
1933 core._assert(n % 2 == 0, "labelPoints expects pairs: (point, label)")
1934
1935 for i = 1, n, 2 do
1936 m.labelPoint(args[i], args[i + 1], options)
1937 end
1938 end
1939
1940 function m.labelSegment(A, B, label, options)
1941 options = options or m.LABEL_STYLE
1942 local midpoint = core.midpoint(A, B)
1943 m.labelPoint(midpoint, label,options)
1944 end
1945
1946
1947 -- ====================== MODULE END
1948
1949 tikz = m
1950 end
1951
1952 do
1953 -----------------------------------------------------------------------
1954 -- @module luahyperbolic-tilings
1955 -- Pure Lua hyperbolic geometry
1956 --
1957 -- License:
1958 -- Public Domain / CC0 1.0 Universal
1959 -- 2026 Damien Mégy
1960 -- This software is released into the public domain.
1961 -- You may use, modify, and distribute it freely, without restriction.
1962 --
1963 -- SPDX-License-Identifier: CC0-1.0
1964 --
1965 -----------------------------------------------------------------------
1966
1967 -- ============ BEGIN MODULE "LUAGYPERBOLIC-TILINGS" ============
1968
1969 local m = {}
1970
1971 m.module = "luahyperbolic-tilings"
1972
1973 -- for quantization (geodesic propagation)
1974 m.QUANTIZATION_SCALE = 1e9
1975
1976 local PI = 3.1415926535898
1977 local min = math.min
1978 local max = math.max
1979 local sin = math.sin
1980 local cos = math.cos
1981 local atan2 = math.atan2
1982 local exp = math.exp
1983 local log = math.log
1984 local sqrt = math.sqrt
1985 local abs = math.abs
1986 local sinh = math.sinh
1987 local cosh = math.cosh
1988 local tanh = math.tanh
1989
1990 local atanh = function(x)
1991 return 0.5 * log((1 + x) / (1 - x))
1992 end
1993
1994 local acosh = function(x)
1995 return log(x + sqrt(x*x - 1))
1996 end
1997
1998 local asinh = function(x)
1999 return log(x + sqrt(x*x + 1))
2000 end
2001
2002
2003
2004
2005 local function _quantize(x)
2006 return math.floor(x * m.QUANTIZATION_SCALE + 0.5)
2007 end
2008
2009
2010 local function _quantize_normalize_pair(a, b)
2011
2012 local ar = _quantize(a.re)
2013 local ai = _quantize(a.im)
2014 local br = _quantize(b.re)
2015 local bi = _quantize(b.im)
2016
2017 -- lexicographic sort on integers
2018 if br < ar or (br == ar and bi < ai) then
2019 ar, br = br, ar
2020 ai, bi = bi, ai
2021 end
2022
2023 return ar .. ":" .. ai .. ":" .. br .. ":" .. bi
2024 end
2025
2026
2027 -- ================== TILINGS ==============
2028
2029
2030 -- TODO : use better algorithm... use the group and work with words
2031 function m.propagateGeodesics(geodesics, depth, MAX_ENDPOINT_DISTANCE)
2032 MAX_ENDPOINT_DISTANCE = MAX_ENDPOINT_DISTANCE or 0.01
2033 core._assert(#geodesics > 1, "must have at least 2 geodesics")
2034
2035 local reflections = {}
2036 for i, side in ipairs(geodesics) do
2037 reflections[i] = core.reflection(side[1], side[2])
2038 end
2039
2040 local seen = {}
2041 local frontier = {}
2042
2043 for _, g in ipairs(geodesics) do
2044 local key = _quantize_normalize_pair(g[1], g[2])
2045 if not seen[key] then
2046 seen[key] = true
2047 frontier[#frontier + 1] = {
2048 p1 = g[1],
2049 p2 = g[2],
2050 last = nil -- no reflection yet
2051 }
2052 end
2053 end
2054
2055 for _ = 1, depth do
2056 local new_frontier = {}
2057 for _, g in ipairs(frontier) do
2058 for i, refl in ipairs(reflections) do
2059 -- avoid immediate inverse reflection
2060 if g.last ~= i then
2061 local p1_new = refl(g.p1)
2062 local p2_new = refl(g.p2)
2063 if complex.abs(p1_new - p2_new) > MAX_ENDPOINT_DISTANCE then
2064 local key = _quantize_normalize_pair(p1_new, p2_new)
2065 if not seen[key] then
2066 seen[key] = true
2067
2068 new_frontier[#new_frontier + 1] = {
2069 p1 = p1_new,
2070 p2 = p2_new,
2071 last = i
2072 }
2073 end
2074 end
2075 end
2076 end
2077 end
2078
2079 for _, g in ipairs(new_frontier) do
2080 geodesics[#geodesics + 1] = { g.p1, g.p2 }
2081 end
2082 frontier = new_frontier
2083 end
2084 return geodesics
2085 end
2086
2087
2088 function m.fillTilingFromTriangle(A, B, C, depth, options)
2089 -- fills with "even odd rule"
2090 options = options or "black"
2091 local geodesics = {
2092 {core.endpoints(A,B)},
2093 {core.endpoints(B,C)},
2094 {core.endpoints(C,A)}
2095 }
2096 geodesics = m.propagateGeodesics(geodesics, depth)
2097 local shapes = {}
2098 for _,pair in ipairs(geodesics) do
2099 table.insert(shapes,tikz.tikz_shape_closed_line(pair[1], pair[2]))
2100 end
2101 local shapes_string = table.concat(shapes, " ")
2102 tikz.tikzPrintf(
2103 "\\fill[even odd rule, %s] (0,0) circle (1) %s ;",
2104 options,
2105 shapes_string
2106 )
2107 end
2108
2109 function m.drawTilingFromTriangle(A, B, C, depth, options)
2110 options = options or tikz.GEODESIC_STYLE
2111 local geodesics = {
2112 {core.endpoints(A,B)},
2113 {core.endpoints(B,C)},
2114 {core.endpoints(C,A)}
2115 }
2116 geodesics = m.propagateGeodesics(geodesics, depth)
2117 local shapes = {}
2118 for _,pair in ipairs(geodesics) do
2119 table.insert(shapes,tikz.tikz_shape_segment(pair[1], pair[2]))
2120 end
2121 local shapes_string = table.concat(shapes, " ")
2122 tikz.tikzPrintf(
2123 "\\draw[%s] (0,0) circle (1) %s ;",
2124 options,
2125 shapes_string
2126 )
2127 end
2128
2129 function m.drawTilingFromAngles(alpha, beta, gamma, depth, options)
2130 local A, B, C = core.triangleWithAngles(alpha, beta, gamma)
2131 m.drawTilingFromTriangle(A, B, C, depth, options)
2132 end
2133
2134 function m.fillTilingFromAngles(alpha, beta, gamma, depth, options)
2135 local A, B, C = core.triangleWithAngles(alpha, beta, gamma)
2136 m.fillTilingFromTriangle(A, B, C, depth, options)
2137 end
2138
2139
2140 -- ============ END MODULE "TILINGS" ============
2141
2142 tilings = m
2143 end
2144
2145
2146 -- public API
2147 hyper = {}
2148
2149 -- structured access
2150 hyper.core = core
2151 hyper.tikz = tikz
2152 hyper.tilings = tilings
2153
2154 local function merge(dst, src)
2155 for k,v in pairs(src) do
2156 dst[k] = v
2157 end
2158 end
2159
2160 -- flattened API
2161 merge(hyper, core)
2162 merge(hyper, tikz)
2163 merge(hyper, tilings)
2164
2165
2166 \end{luacode*}
2167
2168
2169 \begin{luacode*}
2170 function parseKeyValueString(str)
2171 local options = {}
2172
2173 str = str:gsub("%s+", "") -- Remove all spaces
2174 str = str:gsub(",%s*$", "") -- Remove trailing comma if any
2175
2176 for key, value in string.gmatch(str, "([%w_]+)=([%w_%-%.!0-9]+)") do
2177 options[key] = value
2178 end
2179
2180 return options
2181 end
2182 \end{luacode*}
2183
2184
2185
2186 \DeclareDocumentCommand{\hyperbolicTiling}{ m m m O{} }{%
2187 % #1 = P, #2 = Q, #3 = R (mandatory)
2188 % #4 = options (optional, key-value string)
2189 \directlua{
2190 local function isInfinite(value)
2191 local infinity_values = {"inf", "infty", "infinity", "math.huge"}
2192 for _, v in ipairs(infinity_values) do
2193 if value == v then
2194 return true
2195 end
2196 end
2197 return false
2198 end
2199
2200 local function validate(arg)
2201 if isInfinite(arg) then
2202 return math.huge
2203 elseif tonumber(arg) and tonumber(arg) > 0 then
2204 return tonumber(arg)
2205 else
2206 error("Invalid value for argument: "..tostring(arg)..". Must be a positive integer or one of the allowed infinity values (inf, infty, infinity, math.huge).")
2207 end
2208 end
2209
2210 local P = "#1"
2211 local Q = "#2"
2212 local R = "#3"
2213
2214 P = validate(P)
2215 Q = validate(Q)
2216 R = validate(R)
2217 local options = "#4"
2218 local parsedOptions = parseKeyValueString(options)
2219
2220 local depth = tonumber(parsedOptions.depth) or 8
2221 local scale = tonumber(parsedOptions.scale) or 3
2222 local color = parsedOptions.color or "black"
2223 local backgroundcolor = parsedOptions.backgroundcolor or "white"
2224
2225 hyper.tikzBegin("scale="..scale)
2226 hyper.tikzPrintf("\\fill[color=" .. backgroundcolor .."] (0,0) circle (1);")
2227 hyper.fillTilingFromAngles(math.pi/P, math.pi/Q, math.pi/R, depth,color)
2228 hyper.tikzEnd()
2229 }%
2230 }
2231
2232
2233
2234
2235 % End of luahyperbolic.sty