use super::slots::Slots;
use super::{Scene, SceneError};
use crate::content::identity::{Identity, LightId};
use crate::content::light::{Light, LightShape};
use crate::shading::lights::LightRecord;
const RECORD: u64 = std::mem::size_of::<LightRecord>() as u64;
pub(crate) struct Lights {
pub slots: Slots<LightId, Light>,
buffer: wgpu::Buffer,
rects: usize,
}
impl Lights {
pub fn new(device: &wgpu::Device) -> Self {
Self {
slots: Slots::default(),
buffer: light_buffer(device, 1),
rects: 0,
}
}
pub fn buffer(&self) -> &wgpu::Buffer {
&self.buffer
}
pub fn capacity(&self) -> usize {
(self.buffer.size() / RECORD) as usize
}
pub fn holds_rect(&self) -> bool {
self.rects > 0
}
pub fn get(&self, id: LightId) -> Result<&Light, SceneError> {
self.slots.get(id).ok_or(SceneError::UnknownLight)
}
pub fn on(&self) -> impl Iterator<Item = (LightId, &Light)> {
self.slots
.iter()
.filter(|(_, light)| light.intensity > 0. && light.color.iter().any(|&c| c > 0.))
}
fn write(&self, queue: &wgpu::Queue, index: usize, light: &Light) {
crate::counters::write_buffer(
queue,
&self.buffer,
index as u64 * RECORD,
bytemuck::bytes_of(&LightRecord::new(light)),
);
}
fn reserve(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
count: usize,
) -> Result<bool, SceneError> {
let capacity = self.buffer.size() / RECORD;
if count as u64 <= capacity {
return Ok(false);
}
let limits = device.limits();
let limit = limits
.max_storage_buffer_binding_size
.min(limits.max_buffer_size)
/ RECORD;
if count as u64 > limit {
return Err(SceneError::DeviceLimit);
}
self.buffer = light_buffer(device, (count as u64).max(capacity * 2).min(limit));
for (id, light) in self.slots.iter() {
self.write(queue, id.index(), light);
}
Ok(true)
}
}
impl Lights {
pub fn move_origin(&mut self, queue: &wgpu::Queue, by: glam::Vec3) {
let mut records = Vec::new();
for (id, light) in self.slots.iter_mut() {
light.position -= by;
if records.len() <= id.index() {
records.resize(id.index() + 1, bytemuck::Zeroable::zeroed());
}
records[id.index()] = LightRecord::new(light);
}
if !records.is_empty() {
crate::counters::write_buffer(queue, &self.buffer, 0, bytemuck::cast_slice(&records));
}
}
}
fn light_buffer(device: &wgpu::Device, records: u64) -> wgpu::Buffer {
crate::counters::buffer(
device,
&wgpu::BufferDescriptor {
label: Some("scene lights"),
size: records * RECORD,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
},
)
}
fn is_rect(light: &Light) -> bool {
matches!(light.shape, LightShape::Rect { .. })
}
fn validate(light: &Light) -> Result<(), SceneError> {
let nonnegative = |value: f32| value.is_finite() && value >= 0.;
let valid = light.position.is_finite()
&& light.color.iter().all(|&channel| nonnegative(channel))
&& nonnegative(light.intensity)
&& nonnegative(light.specular)
&& nonnegative(light.fog_energy)
&& (0.0..=1.).contains(&light.shadow_opacity)
&& light.range.is_finite()
&& light.range > 0.
&& match light.shape {
LightShape::Point { radius } => radius.is_finite() && radius >= 0.,
LightShape::Spot {
direction,
inner_angle,
outer_angle,
radius,
} => {
radius.is_finite()
&& radius >= 0.
&& direction.is_finite()
&& direction.length_squared() > 0.
&& direction.normalize().is_finite()
&& inner_angle >= 0.
&& inner_angle <= outer_angle
&& outer_angle < std::f32::consts::FRAC_PI_2
}
LightShape::Rect {
direction,
width_axis,
width,
height,
} => {
let normal = direction.normalize();
normal.is_finite()
&& width_axis.is_finite()
&& width_axis
.reject_from_normalized(normal)
.normalize()
.is_finite()
&& width.is_finite()
&& width > 0.
&& height.is_finite()
&& height > 0.
&& (light.intensity / (width * height)).is_finite()
}
};
if valid {
Ok(())
} else {
Err(SceneError::InvalidLight)
}
}
impl Scene {
pub fn add_light(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
light: Light,
) -> Result<LightId, SceneError> {
self.edited();
validate(&light)?;
let count = self.lights.slots.next_index() + 1;
if self.lights.reserve(device, queue, count)? {
self.resources = super::next_generation();
}
let id = self.lights.slots.insert(light);
self.lights.rects += usize::from(is_rect(&light));
self.lights.write(queue, id.index(), &light);
Ok(id)
}
pub fn light(&self, id: LightId) -> Result<&Light, SceneError> {
self.lights.get(id)
}
pub fn set_light(
&mut self,
queue: &wgpu::Queue,
id: LightId,
light: Light,
) -> Result<(), SceneError> {
let old = *self.lights.get(id)?;
if old != light {
self.edited();
}
validate(&light)?;
self.lights.rects =
self.lights.rects + usize::from(is_rect(&light)) - usize::from(is_rect(&old));
*self.lights.slots.get_mut(id).unwrap() = light;
self.lights.write(queue, id.index(), &light);
Ok(())
}
pub fn remove_light(&mut self, id: LightId) -> Result<(), SceneError> {
self.edited();
let light = self
.lights
.slots
.remove(id)
.ok_or(SceneError::UnknownLight)?;
self.lights.rects -= usize::from(is_rect(&light));
Ok(())
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests;