// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use std::{array, f32::consts::TAU};

use super::{DELTA_TIME, waves::Waves, sampler::{WhiteNoise, BrownianNoise}, resampler::{Resampler, SmoothstepResampler}};

const AMPLITUDE: f32 = 0.5;
const TIME: f32 = 0.625;
const FADE_IN: f32 = TIME / 16.0;

pub fn generate() {
	let mut noise: [_; 8] = array::from_fn(|i| (SmoothstepResampler::new(BrownianNoise::new(0.25, 571247 + i as u64)), SmoothstepResampler::new(WhiteNoise::new(18904810 + i as u64))));

	super::generate("damage", TIME, AMPLITUDE, |t| {
		let mut wave = 0.0;

		for (i, (a_noise, p_noise)) in noise.iter_mut().enumerate() {
			let p = p_noise.next(20.0 * DELTA_TIME) * 15.0;
			let w = (t * (500.0 - 125.0 / TIME * t + 1250.0 / (3.0 * TIME * TIME) * t * t) * TAU * (1.125 + i as f32 * 0.5) + p).smooth_square(0.5 - 0.0625 * i as f32);
			let amplitude = (a_noise.next(2500.0 * t / TIME * DELTA_TIME) * 0.5 + 0.5) / (i as f32 + 1.0).powi(3);
			wave += w * amplitude;
		}

		let mut amplitude = 1.0 - (1.0 - (t / FADE_IN).min(1.0)).powi(2); // Fade in
		amplitude *= (1.0 - t / TIME).powi(2); // Fade out
		amplitude *= (t * (8.0 + t / TIME * 8.0) * TAU).sin() * (0.5 * t / TIME + 0.5) - 0.5 * t / TIME;
		wave * amplitude
	});
}
