3D Lighting

Directional and orbiting point lights.

▶ Run in browser

Tags: 3d

Demonstrates:

  • DirectionalLight3D for sun-like parallel illumination

  • Two coloured PointLight3D sources with intensity and range falloff

  • Point lights animated on a continuous orbit, with emissive marker bulbs

  • Grid of cubes and a ground plane lit by the combined light setup

  • Orbit camera with adjustable pitch

Controls: Left / Right - Orbit camera left / right Up / Down - Raise / lower camera pitch Escape - Quit

Run: uv run python examples/features/3d/lighting.py

Source

  1"""3D Lighting: Directional and orbiting point lights.
  2
  3# /// simvx
  4# web = { width = 1280, height = 720 }
  5# ///
  6
  7Demonstrates:
  8  - DirectionalLight3D for sun-like parallel illumination
  9  - Two coloured PointLight3D sources with intensity and range falloff
 10  - Point lights animated on a continuous orbit, with emissive marker bulbs
 11  - Grid of cubes and a ground plane lit by the combined light setup
 12  - Orbit camera with adjustable pitch
 13
 14Controls:
 15    Left / Right - Orbit camera left / right
 16    Up / Down    - Raise / lower camera pitch
 17    Escape       - Quit
 18
 19Run: uv run python examples/features/3d/lighting.py
 20"""
 21
 22import math
 23
 24from simvx.core import (
 25    Camera3D,
 26    DirectionalLight3D,
 27    Input,
 28    InputMap,
 29    Key,
 30    Material,
 31    Mesh,
 32    MeshInstance3D,
 33    Node,
 34    PointLight3D,
 35    Text2D,
 36    WorldEnvironment,
 37)
 38from simvx.graphics import App
 39
 40
 41class LightingScene(Node):
 42    def on_ready(self):
 43        InputMap.add_action("orbit_left", [Key.LEFT])
 44        InputMap.add_action("orbit_right", [Key.RIGHT])
 45        InputMap.add_action("pitch_up", [Key.UP])
 46        InputMap.add_action("pitch_down", [Key.DOWN])
 47        InputMap.add_action("quit", [Key.ESCAPE])
 48
 49        # Camera orbit parameters
 50        self._cam_angle = 0.0  # horizontal orbit angle (radians)
 51        self._cam_pitch = 0.3  # vertical pitch (radians)
 52        self._cam_dist = 15.0
 53        self._cam = Camera3D()
 54        self.add_child(self._cam)
 55        self._update_camera()
 56
 57        # Dark background so the coloured point-light pools read clearly, with
 58        # just enough ambient fill to keep unlit faces from crushing to black.
 59        env = self.add_child(WorldEnvironment())
 60        env.sky_colour_top = (0.02, 0.02, 0.03, 1.0)
 61        env.sky_colour_bottom = (0.04, 0.04, 0.05, 1.0)
 62        env.ambient_light_colour = (0.06, 0.06, 0.08, 1.0)
 63
 64        # Ground plane so the cubes + point lights don't float in pure black.
 65        ground = self.add_child(MeshInstance3D(
 66            mesh=Mesh.cube(),
 67            material=Material(colour=(0.32, 0.34, 0.38, 1.0), roughness=0.9, metallic=0.0),
 68            position=(0, 0, -1.05),
 69            scale=(20, 20, 0.1),
 70        ))
 71        _ = ground  # silence "unused" diagnostics; child is retained via add_child
 72
 73        # Grid of cubes (shared mesh)
 74        cube_mesh = Mesh.cube()
 75        colours = [
 76            (0.9, 0.2, 0.2, 1),
 77            (0.2, 0.9, 0.2, 1),
 78            (0.2, 0.2, 0.9, 1),
 79            (0.9, 0.9, 0.2, 1),
 80            (0.9, 0.2, 0.9, 1),
 81            (0.2, 0.9, 0.9, 1),
 82        ]
 83        # The scene is Z-up: lay the grid out in the XY plane, cube bases
 84        # resting on the ground (ground top is at z=-1, cube half-height 1).
 85        for i, (x, y) in enumerate([(-4, -3), (0, -3), (4, -3), (-4, 3), (0, 3), (4, 3)]):
 86            mat = Material(colour=colours[i], roughness=0.4, metallic=0.1)
 87            cube = MeshInstance3D(mesh=cube_mesh, material=mat, position=(x, y, 0), scale=(2, 2, 2))
 88            self.add_child(cube)
 89
 90        # Directional light: dimmed to a soft key so the dark scene stays moody
 91        # and the coloured point-light pools dominate rather than a daylit sun.
 92        sun = DirectionalLight3D(position=(5, 10, -5))
 93        sun.colour = (1.0, 0.95, 0.8)
 94        sun.intensity = 0.5
 95        sun.look_at((0, 0, 0))
 96        self.add_child(sun)
 97
 98        # Point lights (coloured)
 99        self._red_light = PointLight3D(position=(5, 0, 3.0))
100        self._red_light.colour = (1.0, 0.2, 0.1)
101        self._red_light.intensity = 2.6
102        self._red_light.range = 12.0
103        self.add_child(self._red_light)
104
105        self._blue_light = PointLight3D(position=(-5, 0, 3.0))
106        self._blue_light.colour = (0.1, 0.3, 1.0)
107        self._blue_light.intensity = 2.6
108        self._blue_light.range = 12.0
109        self.add_child(self._blue_light)
110
111        # Small visible markers at the light positions: emissive so they
112        # read as bright "bulbs" even though they don't contribute light
113        # themselves (the PointLight3D beside them does).
114        marker_mesh = Mesh.sphere(radius=0.18, rings=12, segments=16)
115        self._red_marker = self.add_child(MeshInstance3D(
116            mesh=marker_mesh,
117            material=Material(
118                colour=(1.0, 0.25, 0.15, 1.0),
119                emissive_colour=(1.0, 0.25, 0.15, 6.0),
120                roughness=0.4, metallic=0.0,
121            ),
122            position=self._red_light.position,
123        ))
124        self._blue_marker = self.add_child(MeshInstance3D(
125            mesh=marker_mesh,
126            material=Material(
127                colour=(0.2, 0.4, 1.0, 1.0),
128                emissive_colour=(0.2, 0.4, 1.0, 6.0),
129                roughness=0.4, metallic=0.0,
130            ),
131            position=self._blue_light.position,
132        ))
133
134        # HUD
135        self._hud = Text2D(
136            text="Arrow keys: orbit camera | ESC to quit",
137            position=(10, 10), font_scale=1.5,
138        )
139        self.add_child(self._hud)
140        self._fps_text = Text2D(text="FPS: --", position=(10, 35), font_scale=1.0)
141        self.add_child(self._fps_text)
142
143        self._time = 0.0
144        self._fps_accum = 0.0
145        self._fps_frames = 0
146
147    def _update_camera(self):
148        d = self._cam_dist
149        a = self._cam_angle
150        p = self._cam_pitch
151        x = d * math.cos(p) * math.sin(a)
152        y = -d * math.cos(p) * math.cos(a)
153        z = d * math.sin(p)
154        self._cam.position = (x, y, z)
155        self._cam.look_at((0, 0, 0), up=(0, 0, 1))
156
157    def on_update(self, dt):
158        if Input.is_action_just_pressed("quit"):
159            self.app.quit()
160            return
161
162        self._time += dt
163
164        # FPS counter (update every 0.5s)
165        self._fps_accum += dt
166        self._fps_frames += 1
167        if self._fps_accum >= 0.5:
168            fps = self._fps_frames / self._fps_accum
169            self._fps_text.text = f"FPS: {fps:.0f}"
170            self._fps_accum = 0.0
171            self._fps_frames = 0
172
173        # Camera orbit via arrow keys
174        rot_speed = 1.5
175        if Input.is_action_pressed("orbit_right"):
176            self._cam_angle += rot_speed * dt
177        if Input.is_action_pressed("orbit_left"):
178            self._cam_angle -= rot_speed * dt
179        if Input.is_action_pressed("pitch_up"):
180            self._cam_pitch = min(self._cam_pitch + rot_speed * dt, 1.4)
181        if Input.is_action_pressed("pitch_down"):
182            self._cam_pitch = max(self._cam_pitch - rot_speed * dt, -0.2)
183        self._update_camera()
184
185        # Orbit point lights in the (Z-up) XY ground plane at a fixed height,
186        # keeping the visible markers glued to them so you can see where each
187        # light actually is.
188        r = 5.0
189        h = 3.0
190        red_pos = (r * math.cos(self._time), r * math.sin(self._time), h)
191        blue_pos = (r * math.cos(self._time + math.pi), r * math.sin(self._time + math.pi), h)
192        self._red_light.position = red_pos
193        self._red_marker.position = red_pos
194        self._blue_light.position = blue_pos
195        self._blue_marker.position = blue_pos
196
197
198if __name__ == "__main__":
199    app = App(title="Lighting Demo", width=1280, height=720)
200    app.run(LightingScene())