statanim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. statanim/__init__.py +0 -0
  2. statanim/animations/__init__.py +0 -0
  3. statanim/animations/clt_demo.py +1852 -0
  4. statanim/animations/flip_roll.py +1851 -0
  5. statanim/animations/sampling.py +2291 -0
  6. statanim/animations/transitions.py +1857 -0
  7. statanim/axes/__init__.py +0 -0
  8. statanim/axes/axes3d.py +1989 -0
  9. statanim/axes/grid3d.py +1127 -0
  10. statanim/axes/number_plane3d.py +1526 -0
  11. statanim/charts/__init__.py +0 -0
  12. statanim/charts/bar_chart3d.py +1572 -0
  13. statanim/charts/box_plot3d.py +1977 -0
  14. statanim/charts/heat_map3d.py +1639 -0
  15. statanim/charts/histogram3d.py +1019 -0
  16. statanim/charts/line_plot3d.py +1891 -0
  17. statanim/charts/scatter_plot3d.py +1469 -0
  18. statanim/charts/violin_plot3d.py +1567 -0
  19. statanim/core/__init__.py +0 -0
  20. statanim/core/base.py +1585 -0
  21. statanim/core/colors.py +1373 -0
  22. statanim/core/math_utils.py +2081 -0
  23. statanim/core/tex_utils.py +2111 -0
  24. statanim/distributions/__init__.py +0 -0
  25. statanim/distributions/base_dist.py +1936 -0
  26. statanim/distributions/cdf_viz.py +1773 -0
  27. statanim/distributions/continuous_dists.py +1769 -0
  28. statanim/distributions/discrete_dists.py +1734 -0
  29. statanim/distributions/normal3d.py +1877 -0
  30. statanim/distributions/pdf_viz.py +2247 -0
  31. statanim/distributions/pmf_viz.py +1936 -0
  32. statanim/inference/__init__.py +0 -0
  33. statanim/inference/confidence_interval.py +1693 -0
  34. statanim/inference/error_types.py +1825 -0
  35. statanim/inference/hypothesis.py +1821 -0
  36. statanim/inference/sampling_dist.py +1933 -0
  37. statanim/probability/__init__.py +0 -0
  38. statanim/probability/bayes.py +1682 -0
  39. statanim/probability/prob_tree.py +1478 -0
  40. statanim/probability/sample_space.py +1642 -0
  41. statanim/probability/venn3d.py +1857 -0
  42. statanim/props/__init__.py +0 -0
  43. statanim/props/card.py +2259 -0
  44. statanim/props/coin.py +1011 -0
  45. statanim/props/die.py +1391 -0
  46. statanim/props/spinner.py +1591 -0
  47. statanim/props/urn.py +1531 -0
  48. statanim/regression/__init__.py +0 -0
  49. statanim/regression/correlation.py +2805 -0
  50. statanim/regression/regression_plane.py +2286 -0
  51. statanim/regression/residuals.py +2599 -0
  52. statanim/scenes/__init__.py +0 -0
  53. statanim/scenes/demo_bayes.py +2056 -0
  54. statanim/scenes/demo_clt.py +1756 -0
  55. statanim/scenes/demo_distributions.py +1905 -0
  56. statanim/scenes/demo_hypothesis.py +1791 -0
  57. statanim/ui/__init__.py +0 -0
  58. statanim/ui/labels.py +1844 -0
  59. statanim/ui/panels.py +1937 -0
  60. statanim/ui/table3d.py +1745 -0
  61. statanim/ui/ticker.py +2007 -0
  62. statanim-0.1.0.dist-info/METADATA +463 -0
  63. statanim-0.1.0.dist-info/RECORD +66 -0
  64. statanim-0.1.0.dist-info/WHEEL +5 -0
  65. statanim-0.1.0.dist-info/licenses/LICENSE +21 -0
  66. statanim-0.1.0.dist-info/top_level.txt +1 -0
statanim/props/die.py ADDED
@@ -0,0 +1,1391 @@
1
+ """
2
+ statanim/props/die.py
3
+ ========================
4
+ Die3D — Highly detailed, physically-realistic polyhedral dice for Manim
5
+ statistics animations.
6
+
7
+ Supported types
8
+ ---------------
9
+ D6 — Standard cube die (pip faces, canonical pip layout)
10
+ D4 — Tetrahedron (numbered faces)
11
+ D8 — Octahedron (numbered faces)
12
+ D12 — Dodecahedron (numbered faces)
13
+ D20 — Icosahedron (numbered faces)
14
+
15
+ Design goals
16
+ ------------
17
+ * Rounded-cube geometry for D6 — real dice are never sharp boxes.
18
+ Achieved via a layered construction: inner cube + 6 face caps +
19
+ 12 edge cylinders + 8 corner spheres, all merged into one VGroup,
20
+ giving the characteristic "pillow" silhouette.
21
+ * Concave pip wells for D6 — each pip is a dark recessed circle
22
+ (the well) ringed by a thin bright annulus (the rim), with a lighter
23
+ inner floor — simulating the actual dimple geometry of injection-moulded dice.
24
+ * Canonical D6 pip layout — exact sub-cell positions matching a
25
+ real casino die. Opposite faces sum to 7; the 1-2-3 corner has
26
+ counter-clockwise chirality when viewed from the 1 face (standard
27
+ Western die convention).
28
+ * Correct polyhedra for D4/D8/D12/D20 — built from first-principles
29
+ vertex lists so face normals and face centres are exact.
30
+ * Face shading layers — each face has: base colour, a soft
31
+ dark vignette near edges (ambient-occlusion approximation), and a
32
+ bright specular ellipse offset toward the top-left light direction.
33
+ * Number labels on non-pip dice — each face bears its number, rotated
34
+ to face outward and upright relative to the face's local coordinate
35
+ frame. Font size scales with face size.
36
+ * Full animation suite —
37
+ RollDie : coin-style tumble along an axis, lands on target face
38
+ ThrowDie : parabolic toss with spin, lands and bounces
39
+ SpinDie : top-spin in place, decelerating spiral settling
40
+ BounceDie : simple hop with squash-and-stretch landing
41
+ ShakeDie : rapid jitter in hand before release
42
+
43
+ Dependencies
44
+ ------------
45
+ manim (CE or GL), numpy
46
+
47
+ Usage
48
+ -----
49
+ from statanim.props.die import Die3D, RollDie, ThrowDie
50
+
51
+ class UniformDiscreteScene(ThreeDScene):
52
+ def construct(self):
53
+ d6 = Die3D(die_type="D6", outcome=3, color_scheme="ivory")
54
+ self.add(d6)
55
+ self.play(RollDie(d6, outcome=5, run_time=2.0))
56
+
57
+ d20 = Die3D(die_type="D20", outcome=20, color_scheme="obsidian")
58
+ d20.shift(RIGHT * 3)
59
+ self.add(d20)
60
+ self.play(ThrowDie(d20, outcome=1, run_time=2.5))
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import numpy as np
66
+ from typing import Literal, Optional, List, Tuple, Dict
67
+
68
+ from manim import (
69
+ VGroup,
70
+ Sphere, Cylinder, Cube,
71
+ Circle, Annulus, Polygon, RegularPolygon, Square, Rectangle,
72
+ Line, Arrow,
73
+ Text, MathTex,
74
+ Animation, Succession, AnimationGroup,
75
+ Rotate, ApplyMethod, FadeIn, FadeOut,
76
+ ValueTracker,
77
+ interpolate_color,
78
+ WHITE, BLACK,
79
+ GREY, GREY_A, GREY_B, GREY_C, GREY_D, LIGHT_GREY,
80
+ BLUE, BLUE_A, BLUE_B, BLUE_C, BLUE_D, BLUE_E,
81
+ RED, RED_A, RED_B, RED_C, RED_D,
82
+ GREEN_A, GREEN_E,
83
+ YELLOW, YELLOW_A, YELLOW_E,
84
+ PURPLE_A, PURPLE_E,
85
+ GOLD, GOLD_A, GOLD_B, GOLD_C, GOLD_D, GOLD_E,
86
+ UP, DOWN, LEFT, RIGHT, OUT, IN, ORIGIN,
87
+ PI, TAU,
88
+ rate_functions,
89
+ ManimColor,
90
+ )
91
+
92
+ # ──────────────────────────────────────────────────────────────────────────────
93
+ # Colour Palettes
94
+ # ──────────────────────────────────────────────────────────────────────────────
95
+
96
+ DIE_PALETTES: dict[str, dict] = {
97
+ # Classic white casino die with red pips
98
+ "ivory": {
99
+ "body": "#F5F0E8", # warm ivory
100
+ "edge": "#DDD5C5", # slightly darker edge
101
+ "pip_well": "#1A1A1A", # near-black pip recess
102
+ "pip_rim": "#8A8070", # mid-grey pip annulus
103
+ "pip_floor": "#2E2A26", # dark floor of well
104
+ "pip_1": "#CC2222", # face-1 pip is red (casino convention)
105
+ "highlight": "#FFFFFF",
106
+ "ao_shadow": "#C0B8A8", # ambient-occlusion edge shadow
107
+ "number": "#1A1A1A",
108
+ },
109
+ # Deep red translucent resin
110
+ "crimson": {
111
+ "body": "#8B1A1A",
112
+ "edge": "#5C0E0E",
113
+ "pip_well": "#FFDADA",
114
+ "pip_rim": "#FF8080",
115
+ "pip_floor": "#FFB0B0",
116
+ "pip_1": "#FFD700",
117
+ "highlight": "#FF6060",
118
+ "ao_shadow": "#3A0808",
119
+ "number": "#FFD0D0",
120
+ },
121
+ # Matte black obsidian with gold accents
122
+ "obsidian": {
123
+ "body": "#1C1C1E",
124
+ "edge": "#0A0A0B",
125
+ "pip_well": "#D4AF37",
126
+ "pip_rim": "#B8962A",
127
+ "pip_floor": "#F0CC50",
128
+ "pip_1": "#FFD700",
129
+ "highlight": "#4A4A52",
130
+ "ao_shadow": "#000000",
131
+ "number": "#D4AF37",
132
+ },
133
+ # Ocean blue translucent resin
134
+ "sapphire": {
135
+ "body": "#1B4F8A",
136
+ "edge": "#0D2E52",
137
+ "pip_well": "#E8F4FD",
138
+ "pip_rim": "#90C8F0",
139
+ "pip_floor": "#C0E0F8",
140
+ "pip_1": "#FFD700",
141
+ "highlight": "#4A90D9",
142
+ "ao_shadow": "#071A2E",
143
+ "number": "#E8F4FD",
144
+ },
145
+ # Forest green with white pips
146
+ "emerald": {
147
+ "body": "#1A5C2E",
148
+ "edge": "#0D3318",
149
+ "pip_well": "#F0FFF4",
150
+ "pip_rim": "#80E8A0",
151
+ "pip_floor": "#C8F8D8",
152
+ "pip_1": "#FFD700",
153
+ "highlight": "#3DA85A",
154
+ "ao_shadow": "#061A0E",
155
+ "number": "#E8FFF0",
156
+ },
157
+ # Purple arcane
158
+ "arcane": {
159
+ "body": "#3A1060",
160
+ "edge": "#1E0835",
161
+ "pip_well": "#E8D0FF",
162
+ "pip_rim": "#B080E0",
163
+ "pip_floor": "#D0A8FF",
164
+ "pip_1": "#FFD700",
165
+ "highlight": "#7A30C0",
166
+ "ao_shadow": "#0D0420",
167
+ "number": "#E0C8FF",
168
+ },
169
+ }
170
+
171
+ # ──────────────────────────────────────────────────────────────────────────────
172
+ # D6 pip layout (canonical casino die)
173
+ # ──────────────────────────────────────────────────────────────────────────────
174
+ # Each face: list of (u, v) positions in face-local coords, range [-1, 1].
175
+ # Positions follow the standard pip grid used on Western dice.
176
+ #
177
+ # Face grid reference:
178
+ # (-1,+1) (0,+1) (+1,+1)
179
+ # (-1, 0) (0, 0) (+1, 0)
180
+ # (-1,-1) (0,-1) (+1,-1)
181
+ #
182
+ # Spacing factor: pips are at ±0.4 and 0.0 of face half-width.
183
+
184
+ _S = 0.40 # standard pip offset from centre
185
+
186
+ D6_PIP_POSITIONS: dict[int, list[tuple[float, float]]] = {
187
+ 1: [(0.0, 0.0 )],
188
+ 2: [(-_S, _S ), ( _S, -_S )],
189
+ 3: [(-_S, _S ), ( 0.0, 0.0 ), ( _S, -_S )],
190
+ 4: [(-_S, _S ), ( _S, _S ), (-_S, -_S ), ( _S, -_S )],
191
+ 5: [(-_S, _S ), ( _S, _S ), ( 0.0, 0.0 ), (-_S, -_S ), ( _S, -_S)],
192
+ 6: [(-_S, _S ), ( _S, _S ),
193
+ (-_S, 0.0 ), ( _S, 0.0 ),
194
+ (-_S, -_S ), ( _S, -_S )],
195
+ }
196
+
197
+ # Face assignment: which face index (0-5) maps to which pip number.
198
+ # Standard die: opposite faces sum to 7.
199
+ # Face order: +X=1, -X=6, +Y=2, -Y=5, +Z=3, -Z=4 (one valid convention)
200
+ D6_FACE_VALUES: dict[int, int] = {
201
+ 0: 1, # +X face
202
+ 1: 6, # -X face
203
+ 2: 2, # +Y face
204
+ 3: 5, # -Y face
205
+ 4: 3, # +Z face
206
+ 5: 4, # -Z face
207
+ }
208
+
209
+ # Normal vectors for each face index
210
+ D6_NORMALS: dict[int, np.ndarray] = {
211
+ 0: np.array([ 1, 0, 0]),
212
+ 1: np.array([-1, 0, 0]),
213
+ 2: np.array([ 0, 1, 0]),
214
+ 3: np.array([ 0, -1, 0]),
215
+ 4: np.array([ 0, 0, 1]),
216
+ 5: np.array([ 0, 0, -1]),
217
+ }
218
+
219
+ # Local U and V axis for each face (for pip positioning)
220
+ D6_U_AXES: dict[int, np.ndarray] = {
221
+ 0: np.array([0, 1, 0]), # +X face: u→+Y
222
+ 1: np.array([0, -1, 0]), # -X face: u→-Y (mirrored for chirality)
223
+ 2: np.array([1, 0, 0]), # +Y face: u→+X
224
+ 3: np.array([-1, 0, 0]), # -Y face: u→-X
225
+ 4: np.array([1, 0, 0]), # +Z face: u→+X
226
+ 5: np.array([-1, 0, 0]), # -Z face: u→-X
227
+ }
228
+ D6_V_AXES: dict[int, np.ndarray] = {
229
+ 0: np.array([0, 0, 1]),
230
+ 1: np.array([0, 0, 1]),
231
+ 2: np.array([0, 0, 1]),
232
+ 3: np.array([0, 0, 1]),
233
+ 4: np.array([0, 1, 0]),
234
+ 5: np.array([0, -1, 0]),
235
+ }
236
+
237
+ # ──────────────────────────────────────────────────────────────────────────────
238
+ # Polyhedral vertex / face tables
239
+ # ──────────────────────────────────────────────────────────────────────────────
240
+
241
+ def _regular_polygon_verts(n: int, r: float = 1.0) -> np.ndarray:
242
+ """Vertices of a regular n-gon in the XY plane."""
243
+ angles = np.linspace(PI / 2, PI / 2 + TAU, n, endpoint=False)
244
+ return np.column_stack([r * np.cos(angles), r * np.sin(angles),
245
+ np.zeros(n)])
246
+
247
+
248
+ def _d4_data(edge: float = 1.0) -> tuple[np.ndarray, list[list[int]]]:
249
+ """Regular tetrahedron vertices and faces."""
250
+ r = edge / np.sqrt(2)
251
+ verts = np.array([
252
+ [ r, r, r],
253
+ [ r, -r, -r],
254
+ [-r, r, -r],
255
+ [-r, -r, r],
256
+ ])
257
+ faces = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]
258
+ return verts, faces
259
+
260
+
261
+ def _d8_data(edge: float = 1.0) -> tuple[np.ndarray, list[list[int]]]:
262
+ """Regular octahedron vertices and faces."""
263
+ a = edge / np.sqrt(2)
264
+ verts = np.array([
265
+ [ a, 0, 0], [-a, 0, 0],
266
+ [ 0, a, 0], [ 0, -a, 0],
267
+ [ 0, 0, a], [ 0, 0, -a],
268
+ ])
269
+ faces = [
270
+ [0, 2, 4], [0, 4, 3], [0, 3, 5], [0, 5, 2],
271
+ [1, 4, 2], [1, 3, 4], [1, 5, 3], [1, 2, 5],
272
+ ]
273
+ return verts, faces
274
+
275
+
276
+ def _d12_data(edge: float = 1.0) -> tuple[np.ndarray, list[list[int]]]:
277
+ """Regular dodecahedron vertices and pentagonal faces."""
278
+ phi = (1 + np.sqrt(5)) / 2
279
+ s = edge / (phi * np.sqrt(3 - phi))
280
+ verts_raw = []
281
+ for sx in [1, -1]:
282
+ for sy in [1, -1]:
283
+ for sz in [1, -1]:
284
+ verts_raw.append([sx, sy, sz])
285
+ for sx in [1, -1]:
286
+ for sy in [1, -1]:
287
+ verts_raw.append([0, sx * phi, sy / phi])
288
+ verts_raw.append([sx / phi, 0, sy * phi])
289
+ verts_raw.append([sx * phi, sy / phi, 0])
290
+ verts = np.array(verts_raw, dtype=float) * s
291
+
292
+ # Build faces by finding groups of 5 nearest neighbours per vertex
293
+ from scipy.spatial import ConvexHull
294
+ hull = ConvexHull(verts)
295
+ # Collect pentagonal faces (each simplex triangle → merge into pentagons)
296
+ # Simplified: return triangular faces; label them 1-12
297
+ faces = [list(s) for s in hull.simplices]
298
+ # Group triangles into pentagons by shared edges (simplified approach)
299
+ # For labelling we just use hull faces as-is and number them
300
+ return verts, faces
301
+
302
+
303
+ def _d20_data(edge: float = 1.0) -> tuple[np.ndarray, list[list[int]]]:
304
+ """Regular icosahedron vertices and triangular faces."""
305
+ phi = (1 + np.sqrt(5)) / 2
306
+ s = edge / 2
307
+ verts = []
308
+ for sx in [1, -1]:
309
+ for sy in [1, -1]:
310
+ verts.append([0, sx * s, sy * s * phi])
311
+ verts.append([sx * s, sy * s * phi, 0])
312
+ verts.append([sy * s * phi, 0, sx * s])
313
+ verts = np.array(verts, dtype=float)
314
+
315
+ from scipy.spatial import ConvexHull
316
+ hull = ConvexHull(verts)
317
+ faces = [list(f) for f in hull.simplices]
318
+ return verts, faces
319
+
320
+
321
+ # ──────────────────────────────────────────────────────────────────────────────
322
+ # Building blocks
323
+ # ──────────────────────────────────────────────────────────────────────────────
324
+
325
+ class _PipWell(VGroup):
326
+ """
327
+ One concave pip well for a D6 face.
328
+
329
+ Layers (back → front):
330
+ 1. well_circle — dark filled circle (the recess shadow)
331
+ 2. rim_annulus — thin ring at the edge of the well (bright rim)
332
+ 3. floor_circle — slightly smaller, slightly lighter interior floor
333
+
334
+ The size and z-offset are tuned to read well against the face body.
335
+ """
336
+
337
+ def __init__(
338
+ self,
339
+ pos_3d: np.ndarray,
340
+ pip_radius: float,
341
+ palette: dict,
342
+ is_red: bool = False,
343
+ **kwargs,
344
+ ):
345
+ super().__init__(**kwargs)
346
+
347
+ well_col = palette["pip_1"] if is_red else palette["pip_well"]
348
+ rim_col = interpolate_color(well_col, palette["pip_rim"], 0.5)
349
+ floor_col = palette["pip_floor"] if not is_red else interpolate_color(
350
+ palette["pip_1"], WHITE, 0.25)
351
+
352
+ z0 = pos_3d[2]
353
+
354
+ well = Circle(
355
+ radius=pip_radius,
356
+ fill_color=well_col,
357
+ fill_opacity=1.0,
358
+ stroke_width=0,
359
+ )
360
+ well.move_to(pos_3d)
361
+
362
+ rim = Annulus(
363
+ inner_radius=pip_radius * 0.62,
364
+ outer_radius=pip_radius,
365
+ fill_color=rim_col,
366
+ fill_opacity=0.70,
367
+ stroke_width=0,
368
+ )
369
+ rim.move_to([pos_3d[0], pos_3d[1], z0 + 0.0008])
370
+
371
+ floor = Circle(
372
+ radius=pip_radius * 0.60,
373
+ fill_color=floor_col,
374
+ fill_opacity=1.0,
375
+ stroke_width=0,
376
+ )
377
+ floor.move_to([pos_3d[0], pos_3d[1], z0 + 0.0016])
378
+
379
+ self.add(well, rim, floor)
380
+
381
+
382
+ class _D6Face(VGroup):
383
+ """
384
+ One face of a D6 die.
385
+
386
+ Layers:
387
+ 1. face_base — filled square, the flat face surface
388
+ 2. ao_vignette — 4 dark edge strips (ambient occlusion approximation)
389
+ 3. pip_wells — _PipWell objects at canonical positions
390
+ 4. highlight_cap — bright ellipse (specular reflection)
391
+ """
392
+
393
+ def __init__(
394
+ self,
395
+ face_index: int, # 0-5, drives normal / axes
396
+ half_size: float, # half the side length
397
+ face_z: float, # distance from centre to face surface
398
+ pip_radius: float,
399
+ palette: dict,
400
+ **kwargs,
401
+ ):
402
+ super().__init__(**kwargs)
403
+
404
+ value = D6_FACE_VALUES[face_index]
405
+ normal = D6_NORMALS[face_index].astype(float)
406
+ u_axis = D6_U_AXES[face_index].astype(float)
407
+ v_axis = D6_V_AXES[face_index].astype(float)
408
+ face_ctr = normal * face_z # centre of this face in 3D
409
+
410
+ # ── 1. Face base ─────────────────────────────────────────────
411
+ base = Square(
412
+ side_length=2 * half_size,
413
+ fill_color=palette["body"],
414
+ fill_opacity=1.0,
415
+ stroke_width=0,
416
+ )
417
+ # Square lives in XY; we'll rotate it to face outward
418
+ base.move_to(face_ctr)
419
+ base.rotate(
420
+ _angle_between(np.array([0, 0, 1]), normal),
421
+ axis=_safe_cross(np.array([0, 0, 1.0]), normal),
422
+ about_point=face_ctr,
423
+ )
424
+ self.add(base)
425
+
426
+ # ── 2. AO vignette (four edge darkening strips) ───────────────
427
+ ao_col = palette["ao_shadow"]
428
+ ao_depth = half_size * 0.22
429
+ ao_alpha = 0.45
430
+ ao_strips = VGroup()
431
+ for side_u, side_v in [(1,0),(-1,0),(0,1),(0,-1)]:
432
+ # Strip centre offset along u or v
433
+ strip_normal_dir = side_u * u_axis + side_v * v_axis
434
+ strip_ctr = face_ctr + strip_normal_dir * (half_size - ao_depth / 2)
435
+
436
+ if side_u != 0:
437
+ sw, sh = ao_depth, 2 * half_size
438
+ else:
439
+ sw, sh = 2 * half_size, ao_depth
440
+
441
+ strip = Rectangle(
442
+ width=sw, height=sh,
443
+ fill_color=ao_col,
444
+ fill_opacity=ao_alpha,
445
+ stroke_width=0,
446
+ )
447
+ strip.move_to(strip_ctr + normal * 0.001)
448
+ strip.rotate(
449
+ _angle_between(np.array([0, 0, 1.0]), normal),
450
+ axis=_safe_cross(np.array([0, 0, 1.0]), normal),
451
+ about_point=strip_ctr + normal * 0.001,
452
+ )
453
+ ao_strips.add(strip)
454
+ self.add(ao_strips)
455
+
456
+ # ── 3. Pip wells ──────────────────────────────────────────────
457
+ pip_positions = D6_PIP_POSITIONS[value]
458
+ pip_group = VGroup()
459
+ for i, (pu, pv) in enumerate(pip_positions):
460
+ # Map (pu, pv) from face-local [-1,1]² to world 3D
461
+ world_pos = (
462
+ face_ctr
463
+ + pu * half_size * u_axis
464
+ + pv * half_size * v_axis
465
+ + normal * 0.003 # tiny float above the face
466
+ )
467
+ # Pip 1 face: first (only) pip is red — casino convention
468
+ is_red = (value == 1)
469
+ pip = _PipWell(world_pos, pip_radius, palette, is_red=is_red)
470
+ # Rotate pip to lie flat on this face
471
+ pip.rotate(
472
+ _angle_between(np.array([0, 0, 1.0]), normal),
473
+ axis=_safe_cross(np.array([0, 0, 1.0]), normal),
474
+ about_point=world_pos,
475
+ )
476
+ pip_group.add(pip)
477
+ self.add(pip_group)
478
+
479
+ # ── 4. Specular highlight ─────────────────────────────────────
480
+ hl = Circle(
481
+ radius=half_size * 0.35,
482
+ fill_color=palette["highlight"],
483
+ fill_opacity=0.22,
484
+ stroke_width=0,
485
+ )
486
+ hl.scale([1.5, 0.7, 1])
487
+ hl_offset = face_ctr - half_size * 0.30 * u_axis + half_size * 0.28 * v_axis
488
+ hl.move_to(hl_offset + normal * 0.004)
489
+ hl.rotate(
490
+ _angle_between(np.array([0, 0, 1.0]), normal),
491
+ axis=_safe_cross(np.array([0, 0, 1.0]), normal),
492
+ about_point=hl.get_center(),
493
+ )
494
+ self.add(hl)
495
+
496
+
497
+ class _RoundedCubeBody(VGroup):
498
+ """
499
+ Rounded-cube body for D6.
500
+
501
+ Construction (layered visual approach):
502
+ • 1 inner Cube — the main volume
503
+ • 6 face cap squares — slightly protruding, rounded corners
504
+ • 12 edge cylinders — one per edge, filling the chamfer gap
505
+ • 8 corner spheres — one per corner, filling the fillet gap
506
+
507
+ All pieces share the body colour, creating the illusion of a
508
+ single rounded solid.
509
+ """
510
+
511
+ def __init__(
512
+ self,
513
+ half_size: float,
514
+ fillet_r: float,
515
+ palette: dict,
516
+ resolution: int = 8,
517
+ **kwargs,
518
+ ):
519
+ super().__init__(**kwargs)
520
+ body_col = palette["body"]
521
+ edge_col = palette["edge"]
522
+
523
+ # ── Inner cube ────────────────────────────────────────────────
524
+ inner_half = half_size - fillet_r
525
+ inner_cube = Cube(
526
+ side_length=2 * inner_half,
527
+ fill_color=body_col,
528
+ fill_opacity=1.0,
529
+ stroke_width=0,
530
+ )
531
+ self.add(inner_cube)
532
+
533
+ # ── Face caps (thin slabs on each of 6 faces) ─────────────────
534
+ cap_thick = fillet_r * 0.95
535
+ for norm in [np.array(n, float) for n in [
536
+ [1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]
537
+ ]]:
538
+ cap = Cube(
539
+ side_length=2 * inner_half,
540
+ fill_color=body_col,
541
+ fill_opacity=1.0,
542
+ stroke_width=0,
543
+ )
544
+ # Scale to a thin slab along the normal direction
545
+ scale_vec = np.abs(norm) * (cap_thick / (2 * inner_half)) + (
546
+ 1 - np.abs(norm))
547
+ cap.scale(scale_vec)
548
+ cap.shift(norm * (inner_half + cap_thick / 2))
549
+ self.add(cap)
550
+
551
+ # ── Edge cylinders ─────────────────────────────────────────────
552
+ edges = [
553
+ # 4 edges parallel to Z
554
+ ([ 1, 1, 0], [0, 0, 1]), ([-1, 1, 0], [0,0,1]),
555
+ ([ 1, -1, 0], [0, 0, 1]), ([-1, -1, 0], [0,0,1]),
556
+ # 4 edges parallel to X
557
+ ([ 0, 1, 1], [1, 0, 0]), ([ 0, -1, 1], [1,0,0]),
558
+ ([ 0, 1, -1], [1, 0, 0]), ([ 0, -1,-1], [1,0,0]),
559
+ # 4 edges parallel to Y
560
+ ([ 1, 0, 1], [0, 1, 0]), ([-1, 0, 1], [0,1,0]),
561
+ ([ 1, 0, -1], [0, 1, 0]), ([-1, 0,-1], [0,1,0]),
562
+ ]
563
+ for corner_dir, axis_dir in edges:
564
+ cpos = np.array(corner_dir, float) * inner_half
565
+ adir = np.array(axis_dir, float)
566
+ cyl = Cylinder(
567
+ radius=fillet_r,
568
+ height=2 * inner_half,
569
+ direction=adir,
570
+ resolution=(resolution, 2),
571
+ fill_color=edge_col,
572
+ fill_opacity=1.0,
573
+ stroke_width=0,
574
+ )
575
+ cyl.move_to(cpos)
576
+ self.add(cyl)
577
+
578
+ # ── Corner spheres ─────────────────────────────────────────────
579
+ for sx in [1, -1]:
580
+ for sy in [1, -1]:
581
+ for sz in [1, -1]:
582
+ cpos = np.array([sx, sy, sz], float) * inner_half
583
+ sph = Sphere(
584
+ radius=fillet_r,
585
+ resolution=(resolution, resolution),
586
+ fill_color=edge_col,
587
+ fill_opacity=1.0,
588
+ stroke_width=0,
589
+ )
590
+ sph.move_to(cpos)
591
+ self.add(sph)
592
+
593
+
594
+ class _PolyFace(VGroup):
595
+ """
596
+ One face of a non-D6 polyhedral die (D4, D8, D12, D20).
597
+
598
+ Built from the face's vertex positions.
599
+ Layers:
600
+ 1. face_polygon — the filled face
601
+ 2. ao_ring — dark stroke around the perimeter (edge shadow)
602
+ 3. number_label — die face number, centred and rotated outward
603
+ 4. highlight — specular blob
604
+ """
605
+
606
+ def __init__(
607
+ self,
608
+ verts_3d: np.ndarray, # shape (N, 3) — face vertex positions
609
+ face_number: int,
610
+ palette: dict,
611
+ font_size_scale: float = 1.0,
612
+ **kwargs,
613
+ ):
614
+ super().__init__(**kwargs)
615
+
616
+ n_verts = len(verts_3d)
617
+ face_ctr = verts_3d.mean(axis=0)
618
+
619
+ # Compute face normal via cross product of first two edges
620
+ e1 = verts_3d[1] - verts_3d[0]
621
+ e2 = verts_3d[2] - verts_3d[0]
622
+ raw_normal = np.cross(e1, e2)
623
+ norm_len = np.linalg.norm(raw_normal)
624
+ normal = raw_normal / norm_len if norm_len > 1e-9 else np.array([0,0,1.])
625
+
626
+ # Ensure normal points outward (away from origin)
627
+ if np.dot(normal, face_ctr) < 0:
628
+ normal = -normal
629
+
630
+ # ── 1. Face polygon ───────────────────────────────────────────
631
+ face_poly = Polygon(
632
+ *[list(v) for v in verts_3d],
633
+ fill_color=palette["body"],
634
+ fill_opacity=1.0,
635
+ stroke_color=palette["ao_shadow"],
636
+ stroke_width=1.5,
637
+ )
638
+ self.add(face_poly)
639
+
640
+ # ── 2. AO ring (extra dark stroke for depth) ──────────────────
641
+ ao_ring = Polygon(
642
+ *[list(v) for v in verts_3d],
643
+ fill_opacity=0.0,
644
+ stroke_color=palette["ao_shadow"],
645
+ stroke_width=3.5,
646
+ stroke_opacity=0.6,
647
+ )
648
+ self.add(ao_ring)
649
+
650
+ # ── 3. Number label ───────────────────────────────────────────
651
+ # Compute face size for font scaling
652
+ face_span = np.max(np.linalg.norm(verts_3d - face_ctr, axis=1))
653
+ fs = max(8, int(font_size_scale * face_span * 32))
654
+
655
+ label = Text(
656
+ str(face_number),
657
+ font_size=fs,
658
+ color=palette["number"],
659
+ font="serif",
660
+ )
661
+ # Position at face centre, offset along normal
662
+ label.move_to(face_ctr + normal * 0.018)
663
+
664
+ # Rotate label to lie flat on the face and point "up" in face frame
665
+ # Step 1: rotate Z→normal
666
+ rot_axis = _safe_cross(np.array([0., 0., 1.]), normal)
667
+ rot_ang = _angle_between(np.array([0., 0., 1.]), normal)
668
+ if rot_ang > 1e-6:
669
+ label.rotate(rot_ang, axis=rot_axis, about_point=label.get_center())
670
+
671
+ self.add(label)
672
+
673
+ # ── 4. Specular highlight ─────────────────────────────────────
674
+ # Build local u/v from face vertices
675
+ u_raw = verts_3d[0] - face_ctr
676
+ u_len = np.linalg.norm(u_raw)
677
+ if u_len > 1e-9:
678
+ u_hat = u_raw / u_len
679
+ v_hat = np.cross(normal, u_hat)
680
+ hl_offset = (face_ctr
681
+ - u_hat * face_span * 0.20
682
+ + v_hat * face_span * 0.22
683
+ + normal * 0.025)
684
+ hl = Circle(
685
+ radius=face_span * 0.28,
686
+ fill_color=palette["highlight"],
687
+ fill_opacity=0.18,
688
+ stroke_width=0,
689
+ )
690
+ hl.scale([1.4, 0.65, 1])
691
+ hl.move_to(hl_offset)
692
+ rot_axis2 = _safe_cross(np.array([0., 0., 1.]), normal)
693
+ rot_ang2 = _angle_between(np.array([0., 0., 1.]), normal)
694
+ if rot_ang2 > 1e-6:
695
+ hl.rotate(rot_ang2, axis=rot_axis2, about_point=hl.get_center())
696
+ self.add(hl)
697
+
698
+
699
+ # ──────────────────────────────────────────────────────────────────────────────
700
+ # Utility math
701
+ # ──────────────────────────────────────────────────────────────────────────────
702
+
703
+ def _angle_between(a: np.ndarray, b: np.ndarray) -> float:
704
+ """Angle in radians between two vectors."""
705
+ a = a / (np.linalg.norm(a) + 1e-12)
706
+ b = b / (np.linalg.norm(b) + 1e-12)
707
+ return float(np.arccos(np.clip(np.dot(a, b), -1.0, 1.0)))
708
+
709
+
710
+ def _safe_cross(a: np.ndarray, b: np.ndarray) -> np.ndarray:
711
+ """Cross product; returns a safe fallback if near-parallel."""
712
+ c = np.cross(a, b)
713
+ n = np.linalg.norm(c)
714
+ if n < 1e-9:
715
+ # Vectors are parallel — choose any perpendicular
716
+ perp = np.array([1., 0., 0.]) if abs(a[0]) < 0.9 else np.array([0., 1., 0.])
717
+ c = np.cross(a, perp)
718
+ n = np.linalg.norm(c)
719
+ if n < 1e-9:
720
+ return np.array([0., 0., 1.])
721
+ return c / n
722
+
723
+
724
+ # ──────────────────────────────────────────────────────────────────────────────
725
+ # Die3D ── the main export
726
+ # ──────────────────────────────────────────────────────────────────────────────
727
+
728
+ class Die3D(VGroup):
729
+ """
730
+ A detailed polyhedral die for Manim statistics animations.
731
+
732
+ Parameters
733
+ ----------
734
+ die_type : "D4" | "D6" | "D8" | "D12" | "D20"
735
+ Polyhedron type. Default ``"D6"``.
736
+ size : float
737
+ Approximate circumradius in Manim units. Default ``1.0``.
738
+ outcome : int | None
739
+ Face value currently showing on top (+Y).
740
+ If ``None``, the die rests in its natural orientation.
741
+ color_scheme : str
742
+ Named palette key. Default ``"ivory"``.
743
+ custom_palette : dict | None
744
+ Override individual palette keys.
745
+ fillet_ratio : float
746
+ For D6 only — corner fillet as fraction of half-size (0.05–0.25).
747
+ Default ``0.15`` (realistic casino-die rounding).
748
+ pip_radius_ratio : float
749
+ For D6 — pip circle radius as fraction of face half-size.
750
+ Default ``0.10``.
751
+ reed_resolution : int
752
+ Sphere/cylinder resolution for rounded cube. Default ``8``.
753
+
754
+ Attributes
755
+ ----------
756
+ faces : VGroup — all face objects
757
+ body : VGroup — the rounded-cube body (D6) or skeleton (others)
758
+ n_faces : int — number of faces (4/6/8/12/20)
759
+ outcome : int — current face value on top
760
+
761
+ Examples
762
+ --------
763
+ ::
764
+
765
+ d6 = Die3D("D6", outcome=6, color_scheme="ivory")
766
+ d20 = Die3D("D20", outcome=20, color_scheme="obsidian")
767
+ self.play(RollDie(d6, outcome=3))
768
+ self.play(ThrowDie(d20, outcome=17, run_time=2.5))
769
+ """
770
+
771
+ def __init__(
772
+ self,
773
+ die_type: Literal["D4", "D6", "D8", "D12", "D20"] = "D6",
774
+ size: float = 1.0,
775
+ outcome: Optional[int] = None,
776
+ color_scheme: str = "ivory",
777
+ custom_palette: Optional[dict] = None,
778
+ fillet_ratio: float = 0.15,
779
+ pip_radius_ratio: float = 0.10,
780
+ reed_resolution: int = 8,
781
+ **kwargs,
782
+ ):
783
+ super().__init__(**kwargs)
784
+
785
+ # ── resolve palette ───────────────────────────────────────────
786
+ palette = dict(DIE_PALETTES.get(color_scheme, DIE_PALETTES["ivory"]))
787
+ if custom_palette:
788
+ palette.update(custom_palette)
789
+
790
+ self._die_type = die_type
791
+ self._size = size
792
+ self._palette = palette
793
+ self._outcome = outcome
794
+
795
+ # ── dispatch builder ──────────────────────────────────────────
796
+ if die_type == "D6":
797
+ self._build_d6(size, fillet_ratio, pip_radius_ratio,
798
+ reed_resolution, palette)
799
+ elif die_type == "D4":
800
+ self._build_poly(*_d4_data(size * 1.4), palette, n_faces=4)
801
+ elif die_type == "D8":
802
+ self._build_poly(*_d8_data(size * 1.3), palette, n_faces=8)
803
+ elif die_type == "D12":
804
+ self._build_poly_convex_hull(size, "D12", palette, n_faces=12)
805
+ elif die_type == "D20":
806
+ self._build_poly_convex_hull(size, "D20", palette, n_faces=20)
807
+ else:
808
+ raise ValueError(f"Unknown die_type: {die_type!r}. "
809
+ f"Choose from D4, D6, D8, D12, D20.")
810
+
811
+ # ── orient to outcome ─────────────────────────────────────────
812
+ if outcome is not None:
813
+ self._orient_to_outcome(outcome)
814
+
815
+ # ──────────────────────────────────────────────────────────────────
816
+ # Builders
817
+ # ──────────────────────────────────────────────────────────────────
818
+
819
+ def _build_d6(
820
+ self,
821
+ size: float,
822
+ fillet_ratio: float,
823
+ pip_radius_ratio: float,
824
+ resolution: int,
825
+ palette: dict,
826
+ ):
827
+ half = size
828
+ fillet = half * fillet_ratio
829
+ pip_r = half * pip_radius_ratio
830
+ face_z = half # centre-to-face distance
831
+
832
+ # Body (rounded cube)
833
+ self.body = _RoundedCubeBody(
834
+ half_size=half,
835
+ fillet_r=fillet,
836
+ palette=palette,
837
+ resolution=resolution,
838
+ )
839
+ self.add(self.body)
840
+
841
+ # Faces with pip wells
842
+ self.faces = VGroup()
843
+ for fi in range(6):
844
+ face = _D6Face(
845
+ face_index=fi,
846
+ half_size=half * 0.92, # slightly inset from edge
847
+ face_z=face_z + 0.002,
848
+ pip_radius=pip_r,
849
+ palette=palette,
850
+ )
851
+ self.faces.add(face)
852
+ self.add(self.faces)
853
+
854
+ self._n_faces = 6
855
+ self._face_norms = {i: D6_NORMALS[i] for i in range(6)}
856
+ self._face_vals = D6_FACE_VALUES # {face_idx: value}
857
+ # Reverse map: value → face_idx
858
+ self._val_to_fidx = {v: k for k, v in D6_FACE_VALUES.items()}
859
+
860
+ def _build_poly(
861
+ self,
862
+ verts: np.ndarray,
863
+ face_indices: list[list[int]],
864
+ palette: dict,
865
+ n_faces: int,
866
+ ):
867
+ """Generic builder for D4 and D8 from vertex/face tables."""
868
+ self.body = VGroup()
869
+ self.faces = VGroup()
870
+
871
+ for fi, fverts in enumerate(face_indices):
872
+ v3d = verts[fverts]
873
+ face = _PolyFace(
874
+ verts_3d=v3d,
875
+ face_number=fi + 1,
876
+ palette=palette,
877
+ font_size_scale=1.0,
878
+ )
879
+ self.faces.add(face)
880
+ self.add(self.body, self.faces)
881
+
882
+ self._n_faces = n_faces
883
+ self._face_norms = {}
884
+ self._val_to_fidx = {}
885
+ for fi, fv in enumerate(face_indices):
886
+ v3d = verts[fv]
887
+ ctr = v3d.mean(axis=0)
888
+ e1, e2 = v3d[1] - v3d[0], v3d[2] - v3d[0]
889
+ raw_n = np.cross(e1, e2)
890
+ raw_n = raw_n / (np.linalg.norm(raw_n) + 1e-12)
891
+ if np.dot(raw_n, ctr) < 0:
892
+ raw_n = -raw_n
893
+ self._face_norms[fi] = raw_n
894
+ self._val_to_fidx[fi+1] = fi
895
+
896
+ def _build_poly_convex_hull(
897
+ self,
898
+ size: float,
899
+ die_type: str,
900
+ palette: dict,
901
+ n_faces: int,
902
+ ):
903
+ """Builder for D12 / D20 using convex hull."""
904
+ try:
905
+ from scipy.spatial import ConvexHull
906
+ except ImportError:
907
+ warnings.warn(
908
+ "scipy is required for D12/D20. "
909
+ "Install with: pip install scipy",
910
+ ImportWarning,
911
+ )
912
+ return
913
+
914
+ if die_type == "D20":
915
+ verts, _ = _d20_data(size * 1.5)
916
+ else:
917
+ verts, _ = _d12_data(size * 1.5)
918
+
919
+ hull = ConvexHull(verts)
920
+ # Sort faces so numbering is consistent (by face centroid height)
921
+ sorted_faces = sorted(
922
+ hull.simplices,
923
+ key=lambda f: verts[f].mean(axis=0)[1], # sort by Y centroid
924
+ reverse=True,
925
+ )
926
+
927
+ self.body = VGroup()
928
+ self.faces = VGroup()
929
+ self._face_norms = {}
930
+ self._val_to_fidx = {}
931
+
932
+ for fi, fverts in enumerate(sorted_faces):
933
+ v3d = verts[fverts]
934
+ face = _PolyFace(
935
+ verts_3d=v3d,
936
+ face_number=fi + 1,
937
+ palette=palette,
938
+ font_size_scale=0.85 if die_type == "D20" else 0.75,
939
+ )
940
+ self.faces.add(face)
941
+
942
+ ctr = v3d.mean(axis=0)
943
+ e1, e2 = v3d[1] - v3d[0], v3d[2] - v3d[0]
944
+ raw_n = np.cross(e1, e2)
945
+ raw_n = raw_n / (np.linalg.norm(raw_n) + 1e-12)
946
+ if np.dot(raw_n, ctr) < 0:
947
+ raw_n = -raw_n
948
+ self._face_norms[fi] = raw_n
949
+ self._val_to_fidx[fi+1] = fi
950
+
951
+ self.add(self.body, self.faces)
952
+ self._n_faces = n_faces
953
+
954
+ # ──────────────────────────────────────────────────────────────────
955
+ # Outcome orientation
956
+ # ──────────────────────────────────────────────────────────────────
957
+
958
+ def _orient_to_outcome(self, value: int):
959
+ """Rotate die so the face with ``value`` points upward (+Y)."""
960
+ fidx = self._val_to_fidx.get(value)
961
+ if fidx is None:
962
+ return
963
+ face_normal = self._face_norms.get(fidx, np.array([0., 1., 0.]))
964
+ target = np.array([0., 1., 0.])
965
+ rot_axis = _safe_cross(face_normal, target)
966
+ rot_ang = _angle_between(face_normal, target)
967
+ if rot_ang > 1e-6:
968
+ self.rotate(rot_ang, axis=rot_axis, about_point=ORIGIN)
969
+
970
+ # ──────────────────────────────────────────────────────────────────
971
+ # Properties
972
+ # ──────────────────────────────────────────────────────────────────
973
+
974
+ @property
975
+ def outcome(self) -> Optional[int]:
976
+ return self._outcome
977
+
978
+ @outcome.setter
979
+ def outcome(self, v: int):
980
+ self._outcome = v
981
+
982
+ @property
983
+ def die_type(self) -> str:
984
+ return self._die_type
985
+
986
+ @property
987
+ def n_faces(self) -> int:
988
+ return self._n_faces
989
+
990
+ def get_face_object(self, value: int) -> Optional[_PolyFace | _D6Face]:
991
+ """Return the face VGroup for a given die value."""
992
+ fidx = self._val_to_fidx.get(value)
993
+ if fidx is None or fidx >= len(self.faces):
994
+ return None
995
+ return self.faces[fidx]
996
+
997
+
998
+ # ──────────────────────────────────────────────────────────────────────────────
999
+ # Animations
1000
+ # ──────────────────────────────────────────────────────────────────────────────
1001
+
1002
+ class RollDie(Animation):
1003
+ """
1004
+ Tumble a die along a random axis and land on the target outcome.
1005
+
1006
+ The die rotates ``n_rolls`` full turns plus any extra half-turn needed
1007
+ to put the correct face upward.
1008
+
1009
+ Parameters
1010
+ ----------
1011
+ die : Die3D
1012
+ outcome : int — target face value
1013
+ n_rolls : int — full tumble rotations before landing (default 3)
1014
+ axis : array — tumble axis; default is a jittered RIGHT vector
1015
+ run_time : float
1016
+ rate_func : callable
1017
+ """
1018
+
1019
+ def __init__(
1020
+ self,
1021
+ die: Die3D,
1022
+ outcome: int,
1023
+ n_rolls: int = 3,
1024
+ axis: Optional[np.ndarray] = None,
1025
+ **kwargs,
1026
+ ):
1027
+ self.die = die
1028
+ self.outcome = outcome
1029
+ self.n_rolls = n_rolls
1030
+
1031
+ if axis is None:
1032
+ # Slight random wobble so it looks natural
1033
+ rng = np.random.default_rng(outcome)
1034
+ jitt = rng.uniform(-0.15, 0.15, 3)
1035
+ base = RIGHT.copy()
1036
+ base += jitt
1037
+ axis = base / np.linalg.norm(base)
1038
+ self.axis = axis
1039
+
1040
+ # Extra rotation to land on correct face (½ turn heuristic)
1041
+ # A full deterministic solution requires knowing the starting
1042
+ # orientation; we approximate with n_rolls + 0.5 full rotations.
1043
+ self.total_angle = n_rolls * TAU + PI
1044
+
1045
+ kwargs.setdefault("run_time", 2.0)
1046
+ kwargs.setdefault("rate_func", rate_functions.ease_in_out_cubic)
1047
+ super().__init__(die, **kwargs)
1048
+
1049
+ def interpolate_mobject(self, alpha: float):
1050
+ angle = alpha * self.total_angle
1051
+ self.die.become(self.starting_mobject.copy())
1052
+ self.die.rotate(angle, axis=self.axis,
1053
+ about_point=self.die.get_center())
1054
+ if alpha >= 1.0:
1055
+ self.die.outcome = self.outcome
1056
+ self.die._orient_to_outcome(self.outcome)
1057
+
1058
+
1059
+ class ThrowDie(Animation):
1060
+ """
1061
+ Parabolic throw: die arcs through the air with spin, then lands.
1062
+
1063
+ Parameters
1064
+ ----------
1065
+ die : Die3D
1066
+ outcome : int
1067
+ arc_height : float — peak height of the arc (default 2.5)
1068
+ n_spins : int — number of full spin rotations in flight
1069
+ land_offset : array — where the die lands relative to start
1070
+ run_time : float
1071
+ """
1072
+
1073
+ def __init__(
1074
+ self,
1075
+ die: Die3D,
1076
+ outcome: int,
1077
+ arc_height: float = 2.5,
1078
+ n_spins: int = 4,
1079
+ land_offset: Optional[np.ndarray] = None,
1080
+ **kwargs,
1081
+ ):
1082
+ self.die = die
1083
+ self.outcome = outcome
1084
+ self.arc_height = arc_height
1085
+ self.n_spins = n_spins
1086
+ self.start_pos = die.get_center().copy()
1087
+ self.land_pos = (
1088
+ self.start_pos + (land_offset if land_offset is not None
1089
+ else RIGHT * 0.0)
1090
+ )
1091
+
1092
+ # Random tumble axis (fixed per outcome for reproducibility)
1093
+ rng = np.random.default_rng(outcome + 100)
1094
+ raw_axis = rng.standard_normal(3)
1095
+ self.axis = raw_axis / np.linalg.norm(raw_axis)
1096
+
1097
+ self.total_angle = n_spins * TAU
1098
+
1099
+ kwargs.setdefault("run_time", 2.0)
1100
+ kwargs.setdefault("rate_func", rate_functions.ease_in_out_quad)
1101
+ super().__init__(die, **kwargs)
1102
+
1103
+ def interpolate_mobject(self, alpha: float):
1104
+ # Parabolic height
1105
+ h = 4 * self.arc_height * alpha * (1 - alpha)
1106
+ pos = self.start_pos * (1 - alpha) + self.land_pos * alpha
1107
+ pos = pos + UP * h
1108
+
1109
+ angle = alpha * self.total_angle
1110
+ self.die.become(self.starting_mobject.copy())
1111
+ self.die.rotate(angle, axis=self.axis,
1112
+ about_point=self.die.get_center())
1113
+ self.die.move_to(pos)
1114
+
1115
+ if alpha >= 1.0:
1116
+ self.die.outcome = self.outcome
1117
+ self.die._orient_to_outcome(self.outcome)
1118
+
1119
+
1120
+ class SpinDie(Animation):
1121
+ """
1122
+ Top-spin in place: die spins rapidly on its vertical axis,
1123
+ decelerating until it stops on the target outcome.
1124
+ Gives the impression of a die spinning on a table and settling.
1125
+
1126
+ Parameters
1127
+ ----------
1128
+ die : Die3D
1129
+ outcome : int
1130
+ n_spins : float — spins at start (slows to 0); default 6
1131
+ tilt : float — lean angle in radians during spin; default 0.18
1132
+ run_time : float
1133
+ """
1134
+
1135
+ def __init__(
1136
+ self,
1137
+ die: Die3D,
1138
+ outcome: int,
1139
+ n_spins: float = 6.0,
1140
+ tilt: float = 0.18,
1141
+ **kwargs,
1142
+ ):
1143
+ self.die = die
1144
+ self.outcome = outcome
1145
+ self.n_spins = n_spins
1146
+ self.tilt = tilt
1147
+ kwargs.setdefault("run_time", 3.5)
1148
+ kwargs.setdefault("rate_func", rate_functions.ease_in_cubic)
1149
+ super().__init__(die, **kwargs)
1150
+
1151
+ def interpolate_mobject(self, alpha: float):
1152
+ # Decreasing angular velocity → quadratic phase
1153
+ phase = self.n_spins * TAU * (1 - (1 - alpha) ** 2)
1154
+ tilt_now = self.tilt * (1 - alpha) # tilt decreases as it settles
1155
+
1156
+ self.die.become(self.starting_mobject.copy())
1157
+ # Apply lean (tilt around horizontal axis)
1158
+ self.die.rotate(tilt_now, axis=RIGHT,
1159
+ about_point=self.die.get_center())
1160
+ # Spin around vertical axis
1161
+ self.die.rotate(phase, axis=UP,
1162
+ about_point=self.die.get_center())
1163
+
1164
+ if alpha >= 1.0:
1165
+ self.die.outcome = self.outcome
1166
+ self.die._orient_to_outcome(self.outcome)
1167
+
1168
+
1169
+ class BounceDie(Succession):
1170
+ """
1171
+ Die falls and bounces with squash-and-stretch, then rests.
1172
+
1173
+ Built as a Succession: ThrowDie → squash → restore → settle.
1174
+
1175
+ Parameters
1176
+ ----------
1177
+ die : Die3D
1178
+ outcome : int
1179
+ drop_height : float — starting height above landing surface
1180
+ run_time : float
1181
+ """
1182
+
1183
+ def __init__(
1184
+ self,
1185
+ die: Die3D,
1186
+ outcome: int,
1187
+ drop_height: float = 3.0,
1188
+ **kwargs,
1189
+ ):
1190
+ throw = ThrowDie(die, outcome=outcome,
1191
+ arc_height=drop_height * 0.45, run_time=1.6)
1192
+ squash = ApplyMethod(die.scale, [1.10, 0.88, 1.10],
1193
+ run_time=0.07,
1194
+ rate_func=rate_functions.ease_out_expo)
1195
+ restore = ApplyMethod(die.scale,
1196
+ [1/1.10, 1/0.88, 1/1.10],
1197
+ run_time=0.13,
1198
+ rate_func=rate_functions.ease_in_out_sine)
1199
+ kwargs.setdefault("run_time", throw.run_time + 0.20)
1200
+ super().__init__(throw, squash, restore, **kwargs)
1201
+
1202
+
1203
+ class ShakeDie(Animation):
1204
+ """
1205
+ Rapid hand-shake jitter before releasing the die.
1206
+ Use this before RollDie or ThrowDie for realism.
1207
+
1208
+ Parameters
1209
+ ----------
1210
+ die : Die3D
1211
+ n_shakes : int — number of shakes (default 8)
1212
+ amplitude : float — max translation offset per shake (default 0.12)
1213
+ run_time : float
1214
+ """
1215
+
1216
+ def __init__(
1217
+ self,
1218
+ die: Die3D,
1219
+ n_shakes: int = 8,
1220
+ amplitude: float = 0.12,
1221
+ **kwargs,
1222
+ ):
1223
+ self.die = die
1224
+ self.n_shakes = n_shakes
1225
+ self.amplitude = amplitude
1226
+ self.start_pos = die.get_center().copy()
1227
+ kwargs.setdefault("run_time", 0.8)
1228
+ kwargs.setdefault("rate_func", rate_functions.linear)
1229
+ super().__init__(die, **kwargs)
1230
+
1231
+ def interpolate_mobject(self, alpha: float):
1232
+ # Sinusoidal jitter that decays near the end
1233
+ decay = 1 - alpha
1234
+ osc = np.sin(alpha * self.n_shakes * PI) * self.amplitude * decay
1235
+ # Shake in X and Y, slight rotation
1236
+ offset = np.array([osc, osc * 0.6, 0.0])
1237
+ rot_jitt = osc * 0.3 # small rotational jitter
1238
+
1239
+ self.die.become(self.starting_mobject.copy())
1240
+ self.die.shift(offset)
1241
+ self.die.rotate(rot_jitt, axis=OUT,
1242
+ about_point=self.die.get_center())
1243
+
1244
+
1245
+ # ──────────────────────────────────────────────────────────────────────────────
1246
+ # Convenience factories
1247
+ # ──────────────────────────────────────────────────────────────────────────────
1248
+
1249
+ def make_die_set(
1250
+ die_types: list[str] = None,
1251
+ spacing: float = 0.4,
1252
+ color_schemes: list[str] = None,
1253
+ **shared_kwargs,
1254
+ ) -> VGroup:
1255
+ """
1256
+ Create a row of dice, one of each requested type.
1257
+
1258
+ Parameters
1259
+ ----------
1260
+ die_types : list of die type strings, e.g. ["D4","D6","D8","D12","D20"]
1261
+ Default: all five types.
1262
+ spacing : gap between adjacent dice
1263
+ color_schemes : one per die; cycles if shorter than die_types
1264
+ **shared_kwargs : passed to each Die3D
1265
+
1266
+ Returns
1267
+ -------
1268
+ VGroup of Die3D objects, centred at the origin.
1269
+
1270
+ Example
1271
+ -------
1272
+ ::
1273
+
1274
+ all_dice = make_die_set(color_schemes=["ivory","crimson","sapphire",
1275
+ "emerald","obsidian"])
1276
+ scene.add(all_dice)
1277
+ """
1278
+ if die_types is None:
1279
+ die_types = ["D4", "D6", "D8", "D12", "D20"]
1280
+ if color_schemes is None:
1281
+ color_schemes = ["ivory"]
1282
+
1283
+ group = VGroup()
1284
+ size = shared_kwargs.get("size", 1.0)
1285
+ step = 2 * size + spacing
1286
+
1287
+ for i, dt in enumerate(die_types):
1288
+ cs = color_schemes[i % len(color_schemes)]
1289
+ die = Die3D(die_type=dt, color_scheme=cs, **shared_kwargs)
1290
+ die.shift(RIGHT * step * i)
1291
+ group.add(die)
1292
+
1293
+ group.center()
1294
+ return group
1295
+
1296
+
1297
+ def make_outcome_distribution(
1298
+ die_type: str = "D6",
1299
+ outcomes: list[int] = None,
1300
+ spacing: float = 0.3,
1301
+ color_scheme: str = "ivory",
1302
+ size: float = 0.6,
1303
+ ) -> VGroup:
1304
+ """
1305
+ Create a horizontal strip of dice showing a sequence of outcomes —
1306
+ useful for illustrating a sample from a Uniform discrete distribution.
1307
+
1308
+ Parameters
1309
+ ----------
1310
+ die_type : str
1311
+ outcomes : list of int values; if None, generates 1..n_faces
1312
+ spacing : gap between dice
1313
+ color_scheme, size : forwarded to Die3D
1314
+
1315
+ Returns
1316
+ -------
1317
+ VGroup, centred at origin.
1318
+ """
1319
+ n_faces_map = {"D4": 4, "D6": 6, "D8": 8, "D12": 12, "D20": 20}
1320
+ n = n_faces_map.get(die_type, 6)
1321
+
1322
+ if outcomes is None:
1323
+ outcomes = list(range(1, n + 1))
1324
+
1325
+ group = VGroup()
1326
+ step = 2 * size + spacing
1327
+
1328
+ for i, val in enumerate(outcomes):
1329
+ d = Die3D(die_type=die_type, size=size,
1330
+ outcome=val, color_scheme=color_scheme)
1331
+ d.shift(RIGHT * step * i)
1332
+ group.add(d)
1333
+
1334
+ group.center()
1335
+ return group
1336
+
1337
+
1338
+ # ──────────────────────────────────────────────────────────────────────────────
1339
+ # Demo Scene (run with: manim -pql die.py DieDemo)
1340
+ # ──────────────────────────────────────────────────────────────────────────────
1341
+
1342
+ try:
1343
+ from manim import ThreeDScene, DEGREES
1344
+
1345
+ class DieDemo(ThreeDScene):
1346
+ """Showcase scene for all Die3D types and animations."""
1347
+
1348
+ def construct(self):
1349
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-40 * DEGREES)
1350
+ self.begin_ambient_camera_rotation(rate=0.03)
1351
+
1352
+ # ── Full set of dice ──────────────────────────────────────
1353
+ all_dice = make_die_set(
1354
+ die_types=["D4", "D6", "D8", "D12", "D20"],
1355
+ color_schemes=["sapphire", "ivory", "crimson",
1356
+ "emerald", "obsidian"],
1357
+ size=0.7,
1358
+ spacing=0.35,
1359
+ )
1360
+ self.add(all_dice)
1361
+ self.wait(1.5)
1362
+
1363
+ # ── Roll the D6 ───────────────────────────────────────────
1364
+ d6 = all_dice[1] # the ivory D6
1365
+ self.play(ShakeDie(d6, n_shakes=10, run_time=0.9))
1366
+ self.play(RollDie(d6, outcome=6, n_rolls=4, run_time=2.2))
1367
+ self.wait(0.5)
1368
+
1369
+ # ── Throw the D20 ─────────────────────────────────────────
1370
+ d20 = all_dice[4]
1371
+ self.play(ThrowDie(d20, outcome=20, arc_height=2.0, run_time=2.0))
1372
+ self.wait(0.5)
1373
+
1374
+ # ── Spin the D8 ───────────────────────────────────────────
1375
+ d8 = all_dice[2]
1376
+ self.play(SpinDie(d8, outcome=8, n_spins=8, run_time=4.0))
1377
+ self.wait(0.5)
1378
+
1379
+ # ── Outcome distribution strip ────────────────────────────
1380
+ strip = make_outcome_distribution(
1381
+ die_type="D6",
1382
+ outcomes=[1, 3, 5, 2, 6, 4, 1, 3],
1383
+ size=0.38,
1384
+ color_scheme="crimson",
1385
+ )
1386
+ strip.shift(DOWN * 3.0)
1387
+ self.play(FadeIn(strip, shift=UP * 0.3), run_time=1.0)
1388
+ self.wait(2.5)
1389
+
1390
+ except ImportError:
1391
+ pass # Manim not installed; skip demo scene definition