1use std::borrow::Cow;
2
3use bevy::prelude::*;
4use bytemuck::{Pod, Zeroable};
5
6use crate::prelude::PbrDebugView;
7
8#[derive(Resource, Clone, Debug, Default, Reflect)]
12#[reflect(Resource)]
13pub struct PostProcessSettings {
14 pub fog: FogSettings,
15 pub bloom: BloomSettings,
16 pub exposure: ExposureSettings,
17 pub color_grading: ColorGrading,
18 pub tonemapping: Tonemapping,
19 pub vignette: VignetteSettings,
20 pub chromatic_aberration: ChromaticAberrationSettings,
21 pub film_grain: FilmGrainSettings,
22 pub dithering: bool,
24 pub anti_aliasing: AntiAliasing,
25 pub smaa_preset: SmaaPreset,
27 pub taa: TaaSettings,
28 pub sharpening: SharpeningSettings
29}
30impl PostProcessSettings {
31 pub fn for_debug_view(&self, view: PbrDebugView) -> Cow<'_, Self> {
34 if view == PbrDebugView::Off {
35 return Cow::Borrowed(self);
36 }
37 let mut s = self.clone();
38 s.fog.enabled = false;
39 s.bloom.enabled = false;
40 s.exposure.brighten_speed = 0.0;
41 s.exposure.darken_speed = 0.0;
42 s.vignette.intensity = 0.0;
43 s.chromatic_aberration.intensity = 0.0;
44 s.film_grain.intensity = 0.0;
45 s.sharpening.enabled = false;
46 if view.is_data() {
47 s.exposure.eye_adaptation = false;
48 s.exposure.day_compensation = 0.0;
49 s.exposure.night_compensation = 0.0;
50 s.color_grading = ColorGrading::default();
51 s.tonemapping = Tonemapping::None;
52 s.dithering = false;
53 }
54 Cow::Owned(s)
55 }
56}
57
58#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Reflect)]
60pub enum AntiAliasing {
61 None,
62 #[default]
64 Fxaa,
65 Smaa,
68 Taa
73}
74
75#[derive(Clone, Debug, Reflect)]
77pub struct TaaSettings {
78 pub frame_weight: f32
81}
82impl Default for TaaSettings {
83 fn default() -> Self {
84 Self { frame_weight: 0.05 }
85 }
86}
87
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Reflect)]
90pub enum SmaaPreset {
91 Low,
92 Medium,
93 #[default]
95 High,
96 Ultra
97}
98impl SmaaPreset {
99 fn params(self) -> [f32; 4] {
101 match self {
102 Self::Low => [0.15, 4.0, 0.0, -1.0],
103 Self::Medium => [0.1, 8.0, 0.0, -1.0],
104 Self::High => [0.1, 16.0, 8.0, 0.25],
105 Self::Ultra => [0.05, 32.0, 16.0, 0.25]
106 }
107 }
108}
109
110#[derive(Clone, Debug, Reflect)]
113pub struct SharpeningSettings {
114 pub enabled: bool,
115 pub sharpness: f32
117}
118impl Default for SharpeningSettings {
119 fn default() -> Self {
120 Self {
121 enabled: false,
122 sharpness: 0.5
123 }
124 }
125}
126impl SharpeningSettings {
127 fn peak(&self) -> f32 {
129 -1.0 / (8.0 - 3.0 * self.sharpness.clamp(0.0, 1.0))
130 }
131}
132
133#[derive(Clone, Debug, Reflect)]
135pub struct FogSettings {
136 pub enabled: bool,
137 pub color: [f32; 3],
138 pub density: f32,
140 pub height_falloff: f32,
142 pub base_height: f32,
143 pub start_distance: f32,
145 pub max_opacity: f32,
147 pub sky_distance: f32,
149 pub sky_color: f32,
151 pub sun_color: [f32; 3],
153 pub sun_intensity: f32,
155 pub sun_exponent: f32
157}
158impl Default for FogSettings {
159 fn default() -> Self {
160 Self {
161 enabled: false,
162 color: [0.5, 0.6, 0.7],
163 density: 0.002,
164 height_falloff: 0.05,
165 base_height: 0.0,
166 start_distance: 0.0,
167 max_opacity: 1.0,
168 sky_distance: 1000.0,
169 sky_color: 0.0,
170 sun_color: [1.0, 0.9, 0.7],
171 sun_intensity: 0.0,
172 sun_exponent: 8.0
173 }
174 }
175}
176
177#[derive(Clone, Debug, Reflect)]
179pub struct BloomSettings {
180 pub enabled: bool,
181 pub intensity: f32,
183 pub threshold: f32,
185 pub threshold_softness: f32,
187 pub scatter: f32
189}
190impl Default for BloomSettings {
191 fn default() -> Self {
192 Self {
193 enabled: false,
194 intensity: 0.1,
195 threshold: 1.0,
196 threshold_softness: 0.5,
197 scatter: 0.7
198 }
199 }
200}
201
202#[derive(Clone, Debug, Reflect)]
205pub struct ExposureSettings {
206 pub day_compensation: f32,
208 pub night_compensation: f32,
211 pub eye_adaptation: bool,
213 pub luminance_range: [f32; 2],
215 pub low_percentile: f32,
217 pub high_percentile: f32,
219 pub min_ev: f32,
221 pub max_ev: f32,
222 pub brighten_speed: f32,
224 pub darken_speed: f32
226}
227impl Default for ExposureSettings {
228 fn default() -> Self {
229 Self {
230 day_compensation: 0.0,
231 night_compensation: 0.0,
232 eye_adaptation: false,
233 luminance_range: [-10.0, 6.0],
234 low_percentile: 0.1,
235 high_percentile: 0.9,
236 min_ev: -4.0,
237 max_ev: 4.0,
238 brighten_speed: 1.0,
239 darken_speed: 3.0
240 }
241 }
242}
243impl ExposureSettings {
244 pub fn compensation(&self, day: f32) -> f32 {
246 self.night_compensation
247 + (self.day_compensation - self.night_compensation) * day.clamp(0.0, 1.0)
248 }
249}
250
251#[derive(Clone, Debug, Reflect)]
253pub struct ColorGrading {
254 pub exposure: f32,
256 pub temperature: f32,
258 pub tint: f32,
260 pub contrast: f32,
262 pub saturation: f32,
264 pub color_filter: [f32; 3],
266 pub lift: [f32; 3],
268 pub gamma: [f32; 3],
270 pub gain: [f32; 3]
272}
273impl Default for ColorGrading {
274 fn default() -> Self {
275 Self {
276 exposure: 0.0,
277 temperature: 0.0,
278 tint: 0.0,
279 contrast: 1.0,
280 saturation: 1.0,
281 color_filter: [1.0; 3],
282 lift: [0.0; 3],
283 gamma: [1.0; 3],
284 gain: [1.0; 3]
285 }
286 }
287}
288
289#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Reflect)]
291pub enum Tonemapping {
292 None,
294 Reinhard,
295 Aces,
297 AgX,
299 #[default]
301 PbrNeutral
302}
303
304#[derive(Clone, Debug, Reflect)]
306pub struct VignetteSettings {
307 pub intensity: f32,
309 pub radius: f32,
311 pub smoothness: f32,
313 pub roundness: f32,
315 pub color: [f32; 3]
316}
317impl Default for VignetteSettings {
318 fn default() -> Self {
319 Self {
320 intensity: 0.0,
321 radius: 0.6,
322 smoothness: 0.8,
323 roundness: 1.0,
324 color: [0.0; 3]
325 }
326 }
327}
328
329#[derive(Clone, Debug, Default, Reflect)]
331pub struct ChromaticAberrationSettings {
332 pub intensity: f32
334}
335
336#[derive(Clone, Debug, Reflect)]
338pub struct FilmGrainSettings {
339 pub intensity: f32,
341 pub response: f32
343}
344impl Default for FilmGrainSettings {
345 fn default() -> Self {
346 Self {
347 intensity: 0.0,
348 response: 0.8
349 }
350 }
351}
352
353#[repr(C)]
355#[derive(Resource, Clone, Copy, Debug, Pod, Zeroable)]
356pub(crate) struct PostProcessUniform {
357 pub bloom: [f32; 4],
359 pub white_balance: [[f32; 4]; 3],
361 pub grading: [f32; 4],
363 pub color_filter: [f32; 4],
364 pub lift: [f32; 4],
365 pub gamma: [f32; 4],
366 pub gain: [f32; 4],
367 pub vignette: [f32; 4],
369 pub vignette_color: [f32; 4],
370 pub effects: [f32; 4],
372 pub time: [f32; 4],
374 pub anti_aliasing: [f32; 4],
376 pub smaa: [f32; 4],
378 pub sharpening: [f32; 4],
380 pub exposure: [f32; 4],
382 pub exposure_metering: [f32; 4],
384 pub exposure_limits: [f32; 4]
386}
387impl Default for PostProcessUniform {
388 fn default() -> Self {
389 Self::from_settings(&PostProcessSettings::default(), 0.0, 0.0, 1.0)
390 }
391}
392impl PostProcessUniform {
393 pub fn anti_aliasing(&self) -> AntiAliasing {
394 match self.anti_aliasing[0] as u32 {
395 1 => AntiAliasing::Fxaa,
396 2 => AntiAliasing::Smaa,
397 3 => AntiAliasing::Taa,
398 _ => AntiAliasing::None
399 }
400 }
401
402 pub fn from_settings(settings: &PostProcessSettings, time: f32, delta: f32, day: f32) -> Self {
404 let bloom = &settings.bloom;
405 let grading = &settings.color_grading;
406 let vignette = &settings.vignette;
407 let exposure = &settings.exposure;
408 let [min_lum, max_lum] = exposure.luminance_range;
409 let low = exposure.low_percentile.clamp(0.0, 1.0);
410 let wb = white_balance(grading.temperature, grading.tint);
411 let rgb = |c: [f32; 3]| [c[0], c[1], c[2], 0.0];
412 Self {
413 bloom: [
414 bloom.threshold.max(0.0),
415 bloom.threshold.max(0.0) * bloom.threshold_softness.clamp(0.0, 1.0),
416 bloom.scatter.clamp(0.0, 1.0),
417 if bloom.enabled {
418 bloom.intensity.max(0.0)
419 } else {
420 0.0
421 }
422 ],
423 white_balance: [wb.x_axis, wb.y_axis, wb.z_axis].map(|c| c.extend(0.0).to_array()),
424 grading: [
425 (grading.exposure + exposure.compensation(day)).exp2(),
426 grading.contrast.max(0.01),
427 grading.saturation.max(0.0),
428 settings.tonemapping as u32 as f32
429 ],
430 color_filter: rgb(grading.color_filter),
431 lift: rgb(grading.lift),
432 gamma: rgb(grading.gamma.map(|g| g.max(0.01))),
433 gain: rgb(grading.gain),
434 vignette: [
435 vignette.intensity.clamp(0.0, 1.0),
436 vignette.radius,
437 vignette.smoothness.max(0.001),
438 vignette.roundness.clamp(0.0, 1.0)
439 ],
440 vignette_color: rgb(vignette.color),
441 effects: [
442 settings.chromatic_aberration.intensity.max(0.0) * 0.01,
443 settings.film_grain.intensity.max(0.0),
444 settings.film_grain.response.clamp(0.0, 1.0),
445 if settings.dithering { 1.0 } else { 0.0 }
446 ],
447 time: [time, 0.0, 0.0, 0.0],
448 anti_aliasing: [
449 settings.anti_aliasing as u32 as f32,
450 settings.taa.frame_weight.clamp(0.01, 1.0),
451 0.0,
452 0.0
453 ],
454 smaa: settings.smaa_preset.params(),
455 sharpening: [
456 if settings.sharpening.enabled {
457 1.0
458 } else {
459 0.0
460 },
461 settings.sharpening.peak(),
462 0.0,
463 0.0
464 ],
465 exposure: [
466 if exposure.eye_adaptation { 1.0 } else { 0.0 },
467 delta.max(0.0),
468 exposure.brighten_speed.max(0.0),
469 exposure.darken_speed.max(0.0)
470 ],
471 exposure_metering: [
472 min_lum,
473 (max_lum - min_lum).max(0.01),
474 low,
475 exposure.high_percentile.clamp(low, 1.0)
476 ],
477 exposure_limits: [
478 exposure.min_ev,
479 exposure.max_ev.max(exposure.min_ev),
480 0.0,
481 0.0
482 ]
483 }
484 }
485}
486
487#[repr(C)]
489#[derive(Resource, Clone, Copy, Debug, Pod, Zeroable)]
490pub(crate) struct FogUniform {
491 pub color: [f32; 4],
493 pub params: [f32; 4],
495 pub limits: [f32; 4],
497 pub sun: [f32; 4],
499 pub sun_params: [f32; 4]
501}
502impl Default for FogUniform {
503 fn default() -> Self {
504 Self::from_settings(&FogSettings::default())
505 }
506}
507impl FogUniform {
508 pub fn from_settings(fog: &FogSettings) -> Self {
509 let [r, g, b] = fog.color;
510 let [sr, sg, sb] = fog.sun_color;
511 Self {
512 color: [r, g, b, fog.sky_color.clamp(0.0, 1.0)],
513 params: [
514 fog.density.max(0.0),
515 fog.height_falloff.max(0.0),
516 fog.base_height,
517 fog.start_distance.max(0.0)
518 ],
519 limits: [
520 fog.max_opacity.clamp(0.0, 1.0),
521 fog.sky_distance.max(0.0),
522 if fog.enabled { 1.0 } else { 0.0 },
523 0.0
524 ],
525 sun: [sr, sg, sb, fog.sun_exponent.max(1.0)],
526 sun_params: [fog.sun_intensity.max(0.0), 0.0, 0.0, 0.0]
527 }
528 }
529}
530
531const LIN_TO_LMS: Mat3 = Mat3::from_cols(
533 Vec3::new(3.904_05e-1, 7.084_16e-2, 2.310_82e-2),
534 Vec3::new(5.499_41e-1, 9.631_72e-1, 1.280_21e-1),
535 Vec3::new(8.926_32e-3, 1.357_75e-3, 9.362_45e-1)
536);
537const LMS_TO_LIN: Mat3 = Mat3::from_cols(
538 Vec3::new(2.858_47, -2.101_82e-1, -4.181_20e-2),
539 Vec3::new(-1.628_79, 1.158_20, -1.181_69e-1),
540 Vec3::new(-2.489_10e-2, 3.242_81e-4, 1.068_67)
541);
542
543fn white_balance(temperature: f32, tint: f32) -> Mat3 {
545 let t1 = temperature.clamp(-1.0, 1.0) * 100.0 / 65.0;
546 let t2 = tint.clamp(-1.0, 1.0) * 100.0 / 65.0;
547 let x = 0.31271 - t1 * if t1 < 0.0 { 0.1 } else { 0.05 };
548 let y = 2.87 * x - 3.0 * x * x - 0.275_095_07 + t2 * 0.05;
549
550 let xyz = Vec3::new(x / y, 1.0, (1.0 - x - y) / y);
552 let lms = Vec3::new(
553 0.7328 * xyz.x + 0.4296 * xyz.y - 0.1624 * xyz.z,
554 -0.7036 * xyz.x + 1.6975 * xyz.y + 0.0061 * xyz.z,
555 0.0030 * xyz.x + 0.0136 * xyz.y + 0.9834 * xyz.z
556 );
557 let d65 = Vec3::new(0.949_237, 1.035_42, 1.087_28);
558 LMS_TO_LIN * Mat3::from_diagonal(d65 / lms) * LIN_TO_LMS
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564
565 #[test]
566 fn neutral_white_balance_is_identity() {
567 let wb = white_balance(0.0, 0.0);
568 let diff = wb - Mat3::IDENTITY;
569 for c in [diff.x_axis, diff.y_axis, diff.z_axis] {
570 assert!(c.abs().max_element() < 0.01, "{wb:?}");
571 }
572 }
573
574 #[test]
575 fn exposure_compensation_blends_night_to_day() {
576 let exposure = ExposureSettings {
577 day_compensation: -1.0,
578 night_compensation: 2.0,
579 ..Default::default()
580 };
581 assert_eq!(exposure.compensation(0.0), 2.0);
582 assert_eq!(exposure.compensation(1.0), -1.0);
583 assert_eq!(exposure.compensation(0.5), 0.5);
584 }
585
586 #[test]
587 fn sharpening_peak_spans_cas_range() {
588 let peak = |sharpness| {
589 SharpeningSettings {
590 enabled: true,
591 sharpness
592 }
593 .peak()
594 };
595 assert_eq!(peak(0.0), -1.0 / 8.0);
596 assert_eq!(peak(1.0), -1.0 / 5.0);
597 }
598
599 #[test]
600 fn anti_aliasing_round_trips() {
601 for method in [
602 AntiAliasing::None,
603 AntiAliasing::Fxaa,
604 AntiAliasing::Smaa,
605 AntiAliasing::Taa
606 ] {
607 let settings = PostProcessSettings {
608 anti_aliasing: method,
609 ..Default::default()
610 };
611 assert_eq!(
612 PostProcessUniform::from_settings(&settings, 0.0, 0.0, 1.0).anti_aliasing(),
613 method
614 );
615 }
616 }
617
618 #[test]
619 fn warm_white_balance_boosts_red() {
620 let white = white_balance(0.5, 0.0) * Vec3::ONE;
621 assert!(white.x > white.z);
622 }
623}