Skip to main content

steel_core/chunk/light/
mod.rs

1//! Light storage primitives used by chunk and world lighting.
2
3use steel_registry::blocks::{block_state_ext::BlockStateExt, shapes::VoxelShape};
4use steel_utils::{BlockStateId, Direction, SectionPos};
5
6use crate::physics::shapes::{face_shape_occludes, merged_face_occludes};
7
8/// Maximum light value stored by vanilla lighting.
9pub const MAX_LIGHT_LEVEL: u8 = 15;
10/// Minimum opacity used while propagating vanilla light.
11pub const MIN_LIGHT_OPACITY: u8 = 1;
12/// Opacity returned when a block face fully blocks light.
13pub const LIGHT_BLOCKED: u8 = MAX_LIGHT_LEVEL + 1;
14/// Vanilla stores one extra light section below and above the build height.
15pub const LIGHT_SECTION_PADDING: i32 = 1;
16
17/// Number of blocks along one edge of a light section.
18pub const DATA_LAYER_EDGE: usize = 16;
19/// Number of blocks in a light section.
20pub const DATA_LAYER_BLOCK_COUNT: usize = DATA_LAYER_EDGE * DATA_LAYER_EDGE * DATA_LAYER_EDGE;
21/// Number of packed bytes in a light section.
22pub const DATA_LAYER_SIZE: usize = DATA_LAYER_BLOCK_COUNT / 2;
23const CHUNK_EDGE: usize = 16;
24const CHUNK_COLUMN_COUNT: usize = CHUNK_EDGE * CHUNK_EDGE;
25const NEGATIVE_INFINITY: i32 = i32::MIN;
26
27/// Vanilla light layer kind.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum LightLayer {
30    /// Sky light propagated from dimensions with skylight.
31    Sky,
32    /// Block light emitted by blocks.
33    Block,
34}
35
36/// Real chunk-section emptiness transition that must be applied before block checks.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub struct LightSectionEmptinessChange {
39    /// World section whose real block-section emptiness changed.
40    pub section_pos: SectionPos,
41    /// New emptiness value for the real block section.
42    pub empty: bool,
43}
44
45/// Returns whether vanilla must re-check lighting after a block-state change.
46#[must_use]
47pub fn has_different_light_properties(old_state: BlockStateId, new_state: BlockStateId) -> bool {
48    old_state != new_state
49        && (old_state.get_light_dampening() != new_state.get_light_dampening()
50            || old_state.get_light_emission() != new_state.get_light_emission()
51            || old_state.use_shape_for_light_occlusion()
52            || new_state.use_shape_for_light_occlusion())
53}
54
55/// Returns vanilla's simple opacity for light propagation.
56///
57/// Vanilla clamps block light dampening to at least one while propagating
58/// through neighbors.
59#[must_use]
60pub fn get_light_opacity(state: BlockStateId) -> u8 {
61    state.get_light_dampening().max(MIN_LIGHT_OPACITY)
62}
63
64/// Returns the occlusion shape vanilla lighting uses for a block state.
65#[must_use]
66pub fn light_occlusion_shape(state: BlockStateId) -> VoxelShape {
67    if !state.get_block().config.can_occlude || !state.use_shape_for_light_occlusion() {
68        return VoxelShape::EMPTY;
69    }
70
71    state.get_occlusion_shape()
72}
73
74/// Returns vanilla's `LightEngine.getLightDampeningInto` result.
75#[must_use]
76pub fn get_light_block_into(
77    from_state: BlockStateId,
78    to_state: BlockStateId,
79    direction: Direction,
80    simple_opacity: u8,
81) -> u8 {
82    let from_shape = light_occlusion_shape(from_state);
83    let to_shape = light_occlusion_shape(to_state);
84    if from_shape.is_empty() && to_shape.is_empty() {
85        return simple_opacity;
86    }
87
88    if merged_face_occludes(from_shape, to_shape, direction) {
89        LIGHT_BLOCKED
90    } else {
91        simple_opacity
92    }
93}
94
95/// Returns whether the selected state faces fully occlude light.
96#[must_use]
97pub fn light_face_occludes(
98    from_state: BlockStateId,
99    to_state: BlockStateId,
100    direction: Direction,
101) -> bool {
102    let from_shape = light_occlusion_shape(from_state);
103    let to_shape = light_occlusion_shape(to_state);
104    face_shape_occludes(from_shape, direction, to_shape, direction.opposite())
105}
106
107mod cache;
108mod data_layer;
109mod packet;
110mod propagation;
111mod queue;
112mod section_storage;
113mod sky_propagation;
114mod sky_sources;
115mod storage;
116mod work_gate;
117mod workset;
118
119pub use cache::{
120    CachedLightBlock, CachedLightChunk, CachedLightSection, LIGHT_CACHE_CHUNK_SLOTS,
121    LIGHT_CACHE_DIAMETER, LIGHT_CACHE_RADIUS, LIGHT_CACHE_SECTION_RADIUS, LightCacheChunkScope,
122    LightCacheLayout, LightCacheSetupChunks, LightCacheSetupRadius, LightChunkSectionSlots,
123    LightChunkSlotArray, LightSectionSlotArray, LightUpdateNotificationCache, PackedLightBlockPos,
124};
125pub use data_layer::{DataLayer, DataLayerLengthError};
126pub use packet::{build_chunk_light_update_packet, build_chunk_light_update_packet_for_sections};
127pub use propagation::{
128    BlockLightChunkEdgeChecks, BlockLightPropagationContext, BlockLightPropagationContextError,
129    BlockLightUpdateResult, check_block_light_chunk_edges, force_load_block_light_chunk,
130    load_block_light_chunk, propagate_block_light_changes,
131    propagate_block_light_changes_with_empty_sections, propagate_block_light_chunk,
132};
133pub use queue::{
134    LightAxisDirection, LightDirectionSet, LightDirectionSetIter, LightPropagationQueue,
135    LightPropagationQueues, LightQueueEntry, LightQueueFlags, PackedLightPropagationQueue,
136    PackedLightPropagationQueues, PackedLightQueueEntry, QueuedLightUpdate,
137};
138pub use section_storage::{LightSectionRange, LightSectionRangeError};
139pub use sky_propagation::{
140    SkyLightChunkEdgeChecks, SkyLightPropagationContext, SkyLightPropagationContextError,
141    SkyLightUpdateResult, check_sky_light_chunk_edges, force_load_sky_light_chunk,
142    load_sky_light_chunk, propagate_sky_light_changes,
143    propagate_sky_light_changes_with_empty_sections, propagate_sky_light_chunk,
144    propagate_sky_light_chunk_without_edge_checks,
145};
146pub use sky_sources::ChunkSkyLightSources;
147pub use storage::{
148    ChunkLightData, ChunkLightEmptinessMapLengthError, ChunkLightLayerStorage, LightSection,
149    LightSectionData,
150};
151pub(crate) use work_gate::{LightWorkWindowGate, LightWorkWindowReservation};
152pub use workset::{
153    LightChunkReadCache, LightLayerEdit, LightSectionReadCache, LightWorkset,
154    LightWorksetSetupError,
155};
156
157#[cfg(test)]
158mod tests {
159    use steel_registry::{
160        blocks::{block_state_ext::BlockStateExt, properties::BlockStateProperties},
161        init_vanilla_registry, vanilla_blocks,
162    };
163    use steel_utils::BlockStateId;
164    use steel_utils::{BlockPos, ChunkPos, SectionPos};
165
166    use crate::{
167        behavior::init_behaviors,
168        chunk::section::{ChunkSection, Sections},
169    };
170
171    use super::{
172        ChunkLightData, ChunkSkyLightSources, DATA_LAYER_SIZE, DataLayer, LightLayer, LightSection,
173        LightSectionData, LightSectionRange, MAX_LIGHT_LEVEL, build_chunk_light_update_packet,
174        build_chunk_light_update_packet_for_sections, get_light_opacity,
175        has_different_light_properties,
176    };
177
178    fn init_light_tests() {
179        init_vanilla_registry();
180        init_behaviors();
181    }
182
183    fn empty_sections(section_count: usize) -> Sections {
184        let sections: Vec<ChunkSection> = (0..section_count)
185            .map(|_| ChunkSection::new_empty())
186            .collect();
187        Sections::from_owned(sections.into_boxed_slice())
188    }
189
190    fn single_section_with_block(local_y: usize, state: BlockStateId) -> Sections {
191        let mut section = ChunkSection::new_empty();
192        section.set_block_state(0, local_y, 0, state);
193        Sections::from_owned(vec![section].into_boxed_slice())
194    }
195
196    fn new_test_sky_sources() -> ChunkSkyLightSources {
197        let Ok(sources) = ChunkSkyLightSources::new(0, 16) else {
198            panic!("valid single-section height rejected");
199        };
200        sources
201    }
202
203    fn mask_bit(mask: &[u64], index: usize) -> bool {
204        (mask[index / 64] & (1 << (index % 64))) != 0
205    }
206
207    #[test]
208    fn data_layer_uses_vanilla_low_nibble_first_order() {
209        let mut layer = DataLayer::new();
210
211        layer.set(0, 0, 0, 5);
212        layer.set(1, 0, 0, 12);
213        layer.set(1, 2, 3, 31);
214
215        assert_eq!(layer.get(0, 0, 0), 5);
216        assert_eq!(layer.get(1, 0, 0), 12);
217        assert_eq!(layer.get(1, 2, 3), MAX_LIGHT_LEVEL);
218        assert_eq!(layer.get(2, 2, 3), 0);
219
220        let bytes = layer.to_bytes();
221        assert_eq!(bytes[0], 0xC5);
222    }
223
224    #[test]
225    fn data_layer_preserves_homogeneous_non_zero_without_backing_bytes() {
226        let layer = DataLayer::filled(15);
227
228        assert!(layer.is_homogeneous());
229        assert!(!layer.is_empty());
230        assert_eq!(layer.homogeneous_value(), Some(15));
231        assert!(layer.to_bytes().iter().all(|byte| *byte == 0xFF));
232    }
233
234    #[test]
235    fn light_section_range_matches_vanilla_padded_section_range() {
236        let range = LightSectionRange::from_world_height(-64, 384)
237            .expect("vanilla overworld height should produce a light range");
238
239        assert_eq!(range.min_section_y(), -5);
240        assert_eq!(range.max_section_y_exclusive(), 21);
241        assert_eq!(range.section_count(), 26);
242        assert_eq!(range.chunk_section_count(), 24);
243        assert_eq!(range.section_index(-5), Some(0));
244        assert_eq!(range.section_y(25), Some(20));
245        assert_eq!(range.section_index(21), None);
246    }
247
248    #[test]
249    fn chunk_light_packet_omits_missing_and_internal_sections() {
250        let mut light = ChunkLightData::for_valid_world_height(0, 16);
251        *light.sky.section_mut(0).expect("real section in range") =
252            LightSection::internal(LightSectionData::homogeneous(15));
253        *light.block.section_mut(0).expect("real section in range") = LightSection::missing();
254
255        let packet = build_chunk_light_update_packet(&light, true);
256
257        assert!(!mask_bit(&packet.sky_y_mask.0, 1));
258        assert!(!mask_bit(&packet.empty_sky_y_mask.0, 1));
259        assert!(packet.sky_updates.is_empty());
260        assert!(!mask_bit(&packet.block_y_mask.0, 1));
261        assert!(!mask_bit(&packet.empty_block_y_mask.0, 1));
262        assert!(packet.block_updates.is_empty());
263    }
264
265    #[test]
266    fn chunk_light_packet_uses_empty_mask_for_visible_zero_sections() {
267        let mut light = ChunkLightData::for_valid_world_height(0, 16);
268        *light.block.section_mut(0).expect("real section in range") =
269            LightSection::visible(LightSectionData::homogeneous(0));
270
271        let packet = build_chunk_light_update_packet(&light, true);
272
273        assert!(!mask_bit(&packet.block_y_mask.0, 1));
274        assert!(mask_bit(&packet.empty_block_y_mask.0, 1));
275        assert!(packet.block_updates.is_empty());
276    }
277
278    #[test]
279    fn chunk_light_packet_expands_visible_homogeneous_non_zero_sections() {
280        let mut light = ChunkLightData::for_valid_world_height(0, 16);
281        *light.sky.section_mut(0).expect("real section in range") =
282            LightSection::visible(LightSectionData::homogeneous(15));
283
284        let packet = build_chunk_light_update_packet(&light, true);
285
286        assert!(mask_bit(&packet.sky_y_mask.0, 1));
287        assert!(!mask_bit(&packet.empty_sky_y_mask.0, 1));
288        assert_eq!(packet.sky_updates.len(), 1);
289        assert_eq!(packet.sky_updates[0].len(), DATA_LAYER_SIZE);
290        assert!(packet.sky_updates[0].iter().all(|byte| *byte == 0xFF));
291    }
292
293    #[test]
294    fn chunk_light_packet_omits_sky_layer_when_dimension_has_no_skylight() {
295        let mut light = ChunkLightData::for_valid_world_height(0, 16);
296        *light.sky.section_mut(0).expect("real section in range") =
297            LightSection::visible(LightSectionData::homogeneous(15));
298
299        let packet = build_chunk_light_update_packet(&light, false);
300
301        assert!(packet.sky_updates.is_empty());
302        assert!(!mask_bit(&packet.sky_y_mask.0, 1));
303        assert!(!mask_bit(&packet.empty_sky_y_mask.0, 1));
304    }
305
306    #[test]
307    fn changed_section_packet_preserves_ascending_light_section_order() {
308        let chunk_pos = ChunkPos::new(3, -2);
309        let mut light = ChunkLightData::for_valid_world_height(0, 48);
310        *light.block.section_mut(2).expect("upper section in range") =
311            LightSection::visible(LightSectionData::homogeneous(3));
312        *light.block.section_mut(0).expect("lower section in range") =
313            LightSection::visible(LightSectionData::homogeneous(7));
314
315        let packet = build_chunk_light_update_packet_for_sections(
316            chunk_pos,
317            &light,
318            true,
319            &[],
320            &[
321                SectionPos::new(chunk_pos.0.x, 2, chunk_pos.0.y),
322                SectionPos::new(chunk_pos.0.x, 0, chunk_pos.0.y),
323            ],
324        );
325
326        assert_eq!(packet.block_updates.len(), 2);
327        assert!(packet.block_updates[0].iter().all(|byte| *byte == 0x77));
328        assert!(packet.block_updates[1].iter().all(|byte| *byte == 0x33));
329    }
330
331    #[test]
332    fn chunk_light_data_reads_visible_block_and_sky_light() {
333        let mut light = ChunkLightData::for_valid_world_height(0, 16);
334        let pos = BlockPos::new(1, 2, 3);
335        let mut data = LightSectionData::homogeneous(0);
336        data.set(1, 2, 3, 12);
337        *light.block.section_mut(0).expect("real section in range") = LightSection::visible(data);
338
339        assert_eq!(light.get_light_value(LightLayer::Block, pos), 12);
340        assert_eq!(light.get_light_value(LightLayer::Sky, pos), 15);
341    }
342
343    #[test]
344    fn sections_collect_block_light_sources_in_scalable_lux_order() {
345        init_light_tests();
346
347        let torch = vanilla_blocks::TORCH.default_state();
348        let lantern = vanilla_blocks::SEA_LANTERN.default_state();
349        let mut lower = ChunkSection::new_empty();
350        lower.set_block_state(3, 4, 5, torch);
351        lower.set_block_state(1, 0, 0, lantern);
352        let mut upper = ChunkSection::new_empty();
353        upper.set_block_state(15, 15, 15, lantern);
354        let sections =
355            Sections::from_owned(vec![lower, ChunkSection::new_empty(), upper].into_boxed_slice());
356
357        assert_eq!(
358            sections.block_light_sources(ChunkPos::new(2, -3), -16),
359            vec![
360                BlockPos::new(33, -16, -48),
361                BlockPos::new(35, -12, -43),
362                BlockPos::new(47, 31, -33),
363            ]
364        );
365    }
366
367    #[test]
368    fn light_opacity_uses_vanilla_minimum_opacity() {
369        init_light_tests();
370        let air = vanilla_blocks::AIR.default_state();
371        let stone = vanilla_blocks::STONE.default_state();
372
373        assert_eq!(get_light_opacity(air), 1);
374        assert_eq!(get_light_opacity(stone), 15);
375    }
376
377    #[test]
378    fn different_light_properties_match_vanilla_conditions() {
379        init_light_tests();
380        let air = vanilla_blocks::AIR.default_state();
381        let stone = vanilla_blocks::STONE.default_state();
382
383        assert!(!has_different_light_properties(air, air));
384        assert!(has_different_light_properties(air, stone));
385
386        let light = vanilla_blocks::LIGHT.default_state();
387        let dim_light = light.set_value(&BlockStateProperties::LEVEL, 7);
388        assert!(has_different_light_properties(light, dim_light));
389    }
390
391    #[test]
392    fn sky_light_sources_empty_chunk_extends_below_world() {
393        init_light_tests();
394        let sections = empty_sections(1);
395        let mut sources = new_test_sky_sources();
396
397        sources.fill_from_sections(&sections);
398
399        assert_eq!(sources.get_lowest_source_y(0, 0), i32::MIN);
400        assert_eq!(sources.get_lowest_source_y(15, 15), i32::MIN);
401        assert_eq!(sources.get_highest_lowest_source_y(), i32::MIN);
402    }
403
404    #[test]
405    fn sky_light_sources_find_lowest_occluding_edge() {
406        init_light_tests();
407        let stone = vanilla_blocks::STONE.default_state();
408        let sections = single_section_with_block(4, stone);
409        let mut sources = new_test_sky_sources();
410
411        sources.fill_from_sections(&sections);
412
413        assert_eq!(sources.get_lowest_source_y(0, 0), 5);
414        assert_eq!(sources.get_lowest_source_y(1, 0), i32::MIN);
415        assert_eq!(sources.get_highest_lowest_source_y(), 5);
416    }
417
418    #[test]
419    fn sky_light_sources_update_adds_and_removes_occluding_edge() {
420        init_light_tests();
421        let air = vanilla_blocks::AIR.default_state();
422        let stone = vanilla_blocks::STONE.default_state();
423        let sections = empty_sections(1);
424        let mut sources = new_test_sky_sources();
425        sources.fill_from_sections(&sections);
426
427        let added = sources.update(0, 4, 0, |_x, y, _z| if y == 4 { stone } else { air });
428
429        assert!(added);
430        assert_eq!(sources.get_lowest_source_y(0, 0), 5);
431
432        let removed = sources.update(0, 4, 0, |_x, _y, _z| air);
433
434        assert!(removed);
435        assert_eq!(sources.get_lowest_source_y(0, 0), i32::MIN);
436    }
437
438    #[test]
439    fn sky_light_sources_update_ignores_changes_below_current_source_edge() {
440        init_light_tests();
441        let stone = vanilla_blocks::STONE.default_state();
442        let sections = single_section_with_block(10, stone);
443        let mut sources = new_test_sky_sources();
444        sources.fill_from_sections(&sections);
445
446        let changed = sources.update(0, 4, 0, |_x, _y, _z| stone);
447
448        assert!(!changed);
449        assert_eq!(sources.get_lowest_source_y(0, 0), 11);
450    }
451}