use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use bevy::{
color::LinearRgba,
render::{
render_resource::{LoadOp, Operations, RenderPassColorAttachment, StoreOp},
texture::CachedTexture,
},
};
#[derive(Clone)]
pub struct ColorAttachment {
pub texture: CachedTexture,
pub resolve_target: Option<CachedTexture>,
clear_color: Option<LinearRgba>,
is_first_call: Arc<AtomicBool>,
}
impl ColorAttachment {
pub fn new(
texture: CachedTexture,
resolve_target: Option<CachedTexture>,
clear_color: Option<LinearRgba>,
) -> Self {
Self {
texture,
resolve_target,
clear_color,
is_first_call: Arc::new(AtomicBool::new(true)),
}
}
pub fn get_attachment(&self) -> RenderPassColorAttachment {
if let Some(resolve_target) = self.resolve_target.as_ref() {
let first_call = self.is_first_call.fetch_and(false, Ordering::SeqCst);
RenderPassColorAttachment {
view: &resolve_target.default_view,
depth_slice: None,
resolve_target: Some(&self.texture.default_view),
ops: Operations {
load: match (self.clear_color, first_call) {
(Some(clear_color), true) => LoadOp::Clear(clear_color.into()),
(None, _) | (Some(_), false) => LoadOp::Load,
},
store: StoreOp::Store,
},
}
} else {
self.get_unsampled_attachment()
}
}
pub fn get_unsampled_attachment(&self) -> RenderPassColorAttachment {
let first_call = self.is_first_call.fetch_and(false, Ordering::SeqCst);
RenderPassColorAttachment {
view: &self.texture.default_view,
depth_slice: None,
resolve_target: None,
ops: Operations {
load: match (self.clear_color, first_call) {
(Some(clear_color), true) => LoadOp::Clear(clear_color.into()),
(None, _) | (Some(_), false) => LoadOp::Load,
},
store: StoreOp::Store,
},
}
}
pub(crate) fn mark_as_cleared(&self) {
self.is_first_call.store(false, Ordering::SeqCst);
}
}