Coverage for src/manimgx/mobjects/lights.py: 100%
70 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
1"""Lights: what lights the mobjects that have a [material][manimgx.Material] in a
2three-dimensional scene. A light is a mobject that draws nothing: placed, moved and
3animated like any, and a scene's lights are the ones in it. Its intensity is what a white
4matte surface shows: 1 makes such a surface facing the light white."""
6from __future__ import annotations
8from warnings import deprecated
10__all__ = [
11 "AmbientLight",
12 "EnvironmentLight",
13 "Light",
14 "PointLight",
15 "SpotLight",
16 "SunLight",
17]
19import functools
20import itertools
21from dataclasses import dataclass
22from pathlib import Path
23from typing import TYPE_CHECKING, ClassVar, Unpack
25import numpy as np
27from manimgx import _engine
28from manimgx.caches import forgets
29from manimgx.constants import LEFT, ORIGIN, OUT, PI, RIGHT, UP
30from manimgx.drawing.paint import WHITE, Look, ManimColor, ParsableManimColor
31from manimgx.mobject import VectorizedPoint
33if TYPE_CHECKING:
34 from manimgx.typing import Point3DLike
37class Light(VectorizedPoint):
38 """A light: its color and how bright it is, at its point (each kind reads the point its
39 own way).
41 Args:
42 location: Where it is, in scene coordinates.
43 color: Its color.
44 intensity: How bright it is: 1 makes a white matte surface facing it white.
45 **kwargs: [Look keywords][manimgx.drawing.paint.Look] (a name, a z-index).
46 """
48 kind: ClassVar[int] = 0
49 """How the renderer reads it: 0 ambient, 1 sun, 2 point, 3 spot, 4 environment."""
51 def __init__(
52 self,
53 location: Point3DLike = ORIGIN,
54 color: ParsableManimColor = WHITE,
55 intensity: float = 1.0,
56 **kwargs: Unpack[Look],
57 ) -> None:
58 self.light_color = ManimColor(color)
59 self.intensity = intensity
60 super().__init__(location, **kwargs)
63class AmbientLight(Light):
64 """Light from every direction alike: the sky, or a room's light come back from its walls.
65 It lights what no other light reaches, so that nothing goes black.
67 Args:
68 color: Its color.
69 intensity: How bright it is: 1 makes a white matte surface white, from every side.
70 **kwargs: [Look keywords][manimgx.drawing.paint.Look].
72 Examples:
73 ```python
74 import manimgx as m
77 class AmbientLightExample(m.ThreeDScene):
78 def construct(self) -> None:
79 self.set_camera_orientation(phi=70 * m.DEGREES, theta=-40 * m.DEGREES)
80 self.add(m.AmbientLight(m.BLUE_A, intensity=0.4))
81 self.add(m.Sphere(resolution=(48, 48)).set_material(m.Material()))
82 ```
83 """
85 kind: ClassVar[int] = 0
87 def __init__(
88 self,
89 color: ParsableManimColor = WHITE,
90 intensity: float = 0.1,
91 **kwargs: Unpack[Look],
92 ) -> None:
93 super().__init__(ORIGIN, color, intensity, **kwargs)
96class SunLight(Light):
97 """Parallel light from far away, coming from where its point is as seen from the origin:
98 move the point around the origin to turn the light.
100 Args:
101 location: Where the light comes from: its direction from the origin.
102 color: Its color.
103 intensity: How bright it is: 1 makes a white matte surface facing it white.
104 shadows: Whether what it lights casts shadows (on the mobjects with a material).
105 **kwargs: [Look keywords][manimgx.drawing.paint.Look].
107 Examples:
108 ```python
109 import manimgx as m
112 class SunLightExample(m.ThreeDScene):
113 def construct(self) -> None:
114 self.set_camera_orientation(phi=65 * m.DEGREES, theta=-45 * m.DEGREES)
115 sun = m.SunLight(5 * m.RIGHT + 3 * m.OUT)
116 self.add(sun, m.AmbientLight(intensity=0.15))
117 self.add(m.Sphere(resolution=(48, 48)).set_material(m.Material()))
118 self.play(
119 m.Rotate(sun, m.PI, axis=m.OUT, about_point=m.ORIGIN), run_time=3
120 )
121 ```
122 """
124 kind: ClassVar[int] = 1
126 def __init__(
127 self,
128 location: Point3DLike = 4 * UP + 3 * LEFT + 5 * OUT,
129 color: ParsableManimColor = WHITE,
130 intensity: float = 1.0,
131 shadows: bool = True,
132 **kwargs: Unpack[Look],
133 ) -> None:
134 self.shadows = shadows
135 super().__init__(location, color, intensity, **kwargs)
138class PointLight(Light):
139 """Light from its point in every direction, a bulb's: it falls off with the square of the
140 distance, and fades out entirely by `radius`.
142 Args:
143 location: Where it is, in scene coordinates.
144 color: Its color.
145 intensity: How bright it is one unit away: 1 makes a white matte surface facing it
146 there white.
147 radius: How far its light reaches, in scene units.
148 **kwargs: [Look keywords][manimgx.drawing.paint.Look].
150 Examples:
151 ```python
152 import manimgx as m
155 class PointLightExample(m.ThreeDScene):
156 def construct(self) -> None:
157 self.set_camera_orientation(phi=70 * m.DEGREES, theta=-30 * m.DEGREES)
158 lamp = m.PointLight(2 * m.OUT + 2 * m.LEFT, m.ORANGE, intensity=6)
159 self.add(lamp, m.AmbientLight(intensity=0.05))
160 floor = m.Surface(
161 lambda u, v: [u, v, -1], u_range=[-4, 4], v_range=[-4, 4]
162 )
163 self.add(floor.set_material(m.Material(roughness=0.4)))
164 self.play(lamp.animate.shift(4 * m.RIGHT), run_time=3)
165 ```
166 """
168 kind: ClassVar[int] = 2
170 def __init__(
171 self,
172 location: Point3DLike = 3 * OUT,
173 color: ParsableManimColor = WHITE,
174 intensity: float = 1.0,
175 radius: float = 20.0,
176 **kwargs: Unpack[Look],
177 ) -> None:
178 self.radius = radius
179 super().__init__(location, color, intensity, **kwargs)
182class SpotLight(PointLight):
183 """A point light's cone: from its point to the point `toward`, as wide as `angle` either
184 side of its axis, its edge softened over the outer `softness` of the angle.
186 Args:
187 location: Where it is, in scene coordinates.
188 toward: The point it shines toward.
189 color: Its color.
190 intensity: How bright it is one unit away, on its axis.
191 radius: How far its light reaches, in scene units.
192 angle: Half its cone's opening, in radians.
193 softness: The fraction of `angle`, at the cone's edge, over which its light fades.
194 shadows: Whether what it lights casts shadows (on the mobjects with a material).
195 **kwargs: [Look keywords][manimgx.drawing.paint.Look].
197 Examples:
198 ```python
199 import manimgx as m
202 class SpotLightExample(m.ThreeDScene):
203 def construct(self) -> None:
204 self.set_camera_orientation(phi=60 * m.DEGREES, theta=-60 * m.DEGREES)
205 self.add(
206 m.SpotLight(
207 4 * m.OUT, toward=m.ORIGIN, intensity=20, angle=m.PI / 8
208 )
209 )
210 floor = m.Surface(
211 lambda u, v: [u, v, 0], u_range=[-4, 4], v_range=[-4, 4]
212 )
213 self.add(floor.set_material(m.Material(roughness=0.7)))
214 ```
215 """
217 kind: ClassVar[int] = 3
219 def __init__(
220 self,
221 location: Point3DLike = 4 * OUT,
222 toward: Point3DLike = ORIGIN,
223 color: ParsableManimColor = WHITE,
224 intensity: float = 1.0,
225 radius: float = 20.0,
226 angle: float = PI / 6,
227 softness: float = 0.2,
228 shadows: bool = True,
229 **kwargs: Unpack[Look],
230 ) -> None:
231 self.shadows = shadows
232 self.toward = np.asarray(toward, dtype=float)
233 self.angle = angle
234 self.softness = softness
235 super().__init__(location, color, intensity, radius, **kwargs)
238@dataclass(frozen=True, slots=True, eq=False)
239class Picture:
240 """An environment's picture as the engine takes it: equirectangular (its width twice its
241 height), each pixel RGBE (a byte of red, green, blue and a shared exponent), row by row
242 from the top; `id` names it to the player (the views that show it carry the id)."""
244 id: int
245 width: int
246 height: int
247 rgbe: bytes
250_PICTURE_IDS = itertools.count(1) # (0: the studio; a view carries an id as a float32)
253@forgets
254@functools.lru_cache(maxsize=4)
255def _picture(data: bytes) -> Picture:
256 """A Radiance picture's immutable contents, decoded once while remembered (the engine
257 halves it until no wider than 4096)."""
258 width, height, rgbe = _engine.read_hdr(data)
259 return Picture(next(_PICTURE_IDS), width, height, bytes(rgbe))
262class EnvironmentLight(Light):
263 """Light from all around: a picture of the surroundings, each direction's light the
264 picture's there, as at the place it was taken. Metals mirror it, rough ones blur it,
265 and matte surfaces take its light from every side. A sun in the picture lights as a
266 sun does: its light comes from its direction alone, and it casts shadows. A scene
267 lights by one picture (a second environment light shows the first's).
269 The picture is a panorama (equirectangular: a Radiance `.hdr` file, its width twice
270 its height), its up the scene's up (`OUT`), its centre seen looking along `RIGHT`.
271 Rotate the light to turn its surroundings: its points are where it is and, a unit
272 away, its picture's `RIGHT` and up.
274 Args:
275 picture: A Radiance (`.hdr`) file's path; None, a studio's (built in: a dim room
276 with softboxes: a key light where Manim's light source is, a fill, a strip for
277 rims, a light overhead).
278 color: Its tint: the picture's light times this color.
279 intensity: How bright it is: the picture's light times this (a picture of light
280 1 all around makes a white matte surface white).
281 shadows: Whether its picture's sun, if it has one, casts shadows (on the mobjects
282 with a material).
283 **kwargs: [Look keywords][manimgx.drawing.paint.Look].
285 Examples:
286 ```python
287 import manimgx as m
290 class EnvironmentLightExample(m.ThreeDScene):
291 def construct(self) -> None:
292 self.set_camera_orientation(phi=70 * m.DEGREES, theta=-50 * m.DEGREES)
293 studio = m.EnvironmentLight()
294 self.add(studio)
295 for i, roughness in enumerate([0.05, 0.35, 0.8]):
296 ball = m.Sphere(radius=0.8, resolution=(64, 64)).set_color(m.GREY_A)
297 ball.set_material(m.Material(metallic=1, roughness=roughness))
298 self.add(ball.shift(2 * (i - 1) * m.RIGHT))
299 self.play(m.Rotate(studio, m.TAU, axis=m.OUT), run_time=4)
300 ```
301 """
303 kind: ClassVar[int] = 4
304 shared: ClassVar[frozenset[str]] = Light.shared | {"picture"} # a value, read once
306 def __init__(
307 self,
308 picture: str | Path | None = None,
309 color: ParsableManimColor = WHITE,
310 intensity: float = 1.0,
311 shadows: bool = True,
312 **kwargs: Unpack[Look],
313 ) -> None:
314 # (None: the studio, which the engine makes)
315 self.picture = None if picture is None else _picture(Path(picture).read_bytes())
316 self.shadows = shadows
317 super().__init__(ORIGIN, color, intensity, **kwargs)
318 # its picture's right and up, a unit from its point: turned with it
319 self.add(VectorizedPoint(RIGHT), VectorizedPoint(OUT))
321 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
322 def axes(self) -> tuple[np.ndarray, np.ndarray]:
323 """Its picture's `RIGHT` and up in the scene, as it is turned: unit vectors, at a right
324 angle."""
325 origin = self.points[0]
326 right, up = (s.points[0] - origin for s in self.submobjects[:2])
327 up = up / max(float(np.linalg.norm(up)), 1e-9)
328 right = right - up * float(right @ up)
329 return right / max(float(np.linalg.norm(right)), 1e-9), up