use bevy_asset::Handle;1use bevy_camera::{2primitives::{CubeMapFace, CubemapFrusta, CubemapLayout, Frustum, CUBE_MAP_FACES},3visibility::{self, CubemapVisibleEntities, Visibility, VisibilityClass},4};5use bevy_color::Color;6use bevy_ecs::prelude::*;7use bevy_image::Image;8use bevy_math::Mat4;9use bevy_reflect::prelude::*;10use bevy_transform::components::{GlobalTransform, Transform};1112use crate::{13cluster::{ClusterVisibilityClass, GlobalVisibleClusterableObjects},14light_consts,15};1617/// A light that emits light in all directions from a central point.18///19/// Real-world values for `intensity` (luminous power in lumens) based on the electrical power20/// consumption of the type of real-world light are:21///22/// | Luminous Power (lumen) (i.e. the intensity member) | Incandescent non-halogen (Watts) | Incandescent halogen (Watts) | Compact fluorescent (Watts) | LED (Watts) |23/// |------|-----|----|--------|-------|24/// | 200 | 25 | | 3-5 | 3 |25/// | 450 | 40 | 29 | 9-11 | 5-8 |26/// | 800 | 60 | | 13-15 | 8-12 |27/// | 1100 | 75 | 53 | 18-20 | 10-16 |28/// | 1600 | 100 | 72 | 24-28 | 14-17 |29/// | 2400 | 150 | | 30-52 | 24-30 |30/// | 3100 | 200 | | 49-75 | 32 |31/// | 4000 | 300 | | 75-100 | 40.5 |32///33/// Source: [Wikipedia](https://en.wikipedia.org/wiki/Lumen_(unit)#Lighting)34///35/// ## Shadows36///37/// To enable shadows, set the `shadows_enabled` property to `true`.38///39/// To control the resolution of the shadow maps, use the [`PointLightShadowMap`] resource.40#[derive(Component, Debug, Clone, Copy, Reflect)]41#[reflect(Component, Default, Debug, Clone)]42#[require(43CubemapFrusta,44CubemapVisibleEntities,45Transform,46Visibility,47VisibilityClass48)]49#[component(on_add = visibility::add_visibility_class::<ClusterVisibilityClass>)]50pub struct PointLight {51/// The color of this light source.52pub color: Color,5354/// Luminous power in lumens, representing the amount of light emitted by this source in all directions.55pub intensity: f32,5657/// Cut-off for the light's area-of-effect. Fragments outside this range will not be affected by58/// this light at all, so it's important to tune this together with `intensity` to prevent hard59/// lighting cut-offs.60pub range: f32,6162/// Simulates a light source coming from a spherical volume with the given63/// radius.64///65/// This affects the size of specular highlights created by this light, as66/// well as the soft shadow penumbra size. Because of this, large values may67/// not produce the intended result -- for example, light radius does not68/// affect shadow softness or diffuse lighting.69pub radius: f32,7071/// Whether this light casts shadows.72pub shadows_enabled: bool,7374/// Whether soft shadows are enabled.75///76/// Soft shadows, also known as *percentage-closer soft shadows* or PCSS,77/// cause shadows to become blurrier (i.e. their penumbra increases in78/// radius) as they extend away from objects. The blurriness of the shadow79/// depends on the [`PointLight::radius`] of the light; larger lights result80/// in larger penumbras and therefore blurrier shadows.81///82/// Currently, soft shadows are rather noisy if not using the temporal mode.83/// If you enable soft shadows, consider choosing84/// [`ShadowFilteringMethod::Temporal`] and enabling temporal antialiasing85/// (TAA) to smooth the noise out over time.86///87/// Note that soft shadows are significantly more expensive to render than88/// hard shadows.89///90/// [`ShadowFilteringMethod::Temporal`]: crate::ShadowFilteringMethod::Temporal91#[cfg(feature = "experimental_pbr_pcss")]92pub soft_shadows_enabled: bool,9394/// Whether this point light contributes diffuse lighting to meshes with95/// lightmaps.96///97/// Set this to false if your lightmap baking tool bakes the direct diffuse98/// light from this point light into the lightmaps in order to avoid99/// counting the radiance from this light twice. Note that the specular100/// portion of the light is always considered, because Bevy currently has no101/// means to bake specular light.102///103/// By default, this is set to true.104pub affects_lightmapped_mesh_diffuse: bool,105106/// A bias used when sampling shadow maps to avoid "shadow-acne", or false shadow occlusions107/// that happen as a result of shadow-map fragments not mapping 1:1 to screen-space fragments.108/// Too high of a depth bias can lead to shadows detaching from their casters, or109/// "peter-panning". This bias can be tuned together with `shadow_normal_bias` to correct shadow110/// artifacts for a given scene.111pub shadow_depth_bias: f32,112113/// A bias applied along the direction of the fragment's surface normal. It is scaled to the114/// shadow map's texel size so that it can be small close to the camera and gets larger further115/// away.116pub shadow_normal_bias: f32,117118/// The distance from the light to near Z plane in the shadow map.119///120/// Objects closer than this distance to the light won't cast shadows.121/// Setting this higher increases the shadow map's precision.122///123/// This only has an effect if shadows are enabled.124pub shadow_map_near_z: f32,125}126127impl Default for PointLight {128fn default() -> Self {129PointLight {130color: Color::WHITE,131intensity: light_consts::lumens::VERY_LARGE_CINEMA_LIGHT,132range: 20.0,133radius: 0.0,134shadows_enabled: false,135affects_lightmapped_mesh_diffuse: true,136shadow_depth_bias: Self::DEFAULT_SHADOW_DEPTH_BIAS,137shadow_normal_bias: Self::DEFAULT_SHADOW_NORMAL_BIAS,138shadow_map_near_z: Self::DEFAULT_SHADOW_MAP_NEAR_Z,139#[cfg(feature = "experimental_pbr_pcss")]140soft_shadows_enabled: false,141}142}143}144145impl PointLight {146pub const DEFAULT_SHADOW_DEPTH_BIAS: f32 = 0.08;147pub const DEFAULT_SHADOW_NORMAL_BIAS: f32 = 0.6;148pub const DEFAULT_SHADOW_MAP_NEAR_Z: f32 = 0.1;149}150151/// Add to a [`PointLight`] to add a light texture effect.152/// A texture mask is applied to the light source to modulate its intensity,153/// simulating patterns like window shadows, gobo/cookie effects, or soft falloffs.154#[derive(Clone, Component, Debug, Reflect)]155#[reflect(Component, Debug)]156#[require(PointLight)]157pub struct PointLightTexture {158/// The texture image. Only the R channel is read.159pub image: Handle<Image>,160/// The cubemap layout. The image should be a packed cubemap in one of the formats described by the [`CubemapLayout`] enum.161pub cubemap_layout: CubemapLayout,162}163164/// Controls the resolution of [`PointLight`] shadow maps.165///166/// ```167/// # use bevy_app::prelude::*;168/// # use bevy_light::PointLightShadowMap;169/// App::new()170/// .insert_resource(PointLightShadowMap { size: 2048 });171/// ```172#[derive(Resource, Clone, Debug, Reflect)]173#[reflect(Resource, Debug, Default, Clone)]174pub struct PointLightShadowMap {175/// The width and height of each of the 6 faces of the cubemap.176///177/// Defaults to `1024`.178pub size: usize,179}180181impl Default for PointLightShadowMap {182fn default() -> Self {183Self { size: 1024 }184}185}186187// NOTE: Run this after assign_lights_to_clusters!188pub fn update_point_light_frusta(189global_lights: Res<GlobalVisibleClusterableObjects>,190mut views: Query<(Entity, &GlobalTransform, &PointLight, &mut CubemapFrusta)>,191changed_lights: Query<192Entity,193(194With<PointLight>,195Or<(Changed<GlobalTransform>, Changed<PointLight>)>,196),197>,198) {199let view_rotations = CUBE_MAP_FACES200.iter()201.map(|CubeMapFace { target, up }| Transform::IDENTITY.looking_at(*target, *up))202.collect::<Vec<_>>();203204for (entity, transform, point_light, mut cubemap_frusta) in &mut views {205// If this light hasn't changed, and neither has the set of global_lights,206// then we can skip this calculation.207if !global_lights.is_changed() && !changed_lights.contains(entity) {208continue;209}210211// The frusta are used for culling meshes to the light for shadow mapping212// so if shadow mapping is disabled for this light, then the frusta are213// not needed.214// Also, if the light is not relevant for any cluster, it will not be in the215// global lights set and so there is no need to update its frusta.216if !point_light.shadows_enabled || !global_lights.entities.contains(&entity) {217continue;218}219220let clip_from_view = Mat4::perspective_infinite_reverse_rh(221core::f32::consts::FRAC_PI_2,2221.0,223point_light.shadow_map_near_z,224);225226// ignore scale because we don't want to effectively scale light radius and range227// by applying those as a view transform to shadow map rendering of objects228// and ignore rotation because we want the shadow map projections to align with the axes229let view_translation = Transform::from_translation(transform.translation());230let view_backward = transform.back();231232for (view_rotation, frustum) in view_rotations.iter().zip(cubemap_frusta.iter_mut()) {233let world_from_view = view_translation * *view_rotation;234let clip_from_world = clip_from_view * world_from_view.compute_affine().inverse();235236*frustum = Frustum::from_clip_from_world_custom_far(237&clip_from_world,238&transform.translation(),239&view_backward,240point_light.range,241);242}243}244}245246247