use crate::nodes::node::{TextureSource, Type};
use crate::nodes::tsl::*;
use crate::nodes::NodeRef;
use crate::textures::DataTexture;
#[derive(Clone, Debug)]
pub struct BatchEntry {
pub indirect: DataTexture,
pub matrices: DataTexture,
pub colors: Option<DataTexture>,
}
impl std::hash::Hash for BatchEntry {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.indirect.id().hash(state);
self.matrices.id().hash(state);
self.colors.as_ref().map(|t| t.id()).hash(state);
}
}
pub fn batch_color() -> NodeRef {
varying_property("vBatchColor", Type::Vec4, false)
}
fn batch_indirect_index() -> NodeRef {
varying_property("vBatchIndirectId", Type::U32, true)
}
fn texture_width(map: &DataTexture) -> NodeRef {
to_var(
None,
texture_size(TextureSource::Data(map.clone()), int(0))
.x()
.to(Type::I32),
)
}
pub fn batch(entry: &BatchEntry) -> Vec<NodeRef> {
let mut statements = Vec::new();
let indirect_size = texture_width(&entry.indirect);
let ix = to_var(
None,
instance_index().to(Type::I32).modulo(indirect_size.clone()),
);
let iy = to_var(
None,
instance_index().to(Type::I32).div(indirect_size.clone()),
);
statements.push(indirect_size);
statements.push(ix.clone());
statements.push(iy.clone());
let indirect_id = texture_load_texel(&entry.indirect, ivec2(ix, iy), Type::U32);
statements.push(batch_indirect_index().assign(indirect_id.clone()));
let matrices_size = texture_width(&entry.matrices);
let j = to_var(
None,
indirect_id.to(Type::F32).mul(float(4.0)).to(Type::I32),
);
let mx = to_var(None, j.modulo(matrices_size.clone()));
let my = to_var(None, j.div(matrices_size.clone()));
statements.push(matrices_size);
statements.push(j);
statements.push(mx.clone());
statements.push(my.clone());
if let Some(colors) = &entry.colors {
let colors_size = texture_width(colors);
let cx = to_var(None, indirect_id.to(Type::I32).modulo(colors_size.clone()));
let cy = to_var(None, indirect_id.to(Type::I32).div(colors_size.clone()));
statements.push(colors_size);
statements.push(cx.clone());
statements.push(cy.clone());
let color = texture_load_texel(colors, ivec2(cx, cy), Type::Vec4);
statements.push(batch_color().assign(color));
}
let matrix = join(
Type::Mat4,
vec![
texture_load_texel(&entry.matrices, ivec2(mx.clone(), my.clone()), Type::Vec4),
texture_load_texel(
&entry.matrices,
ivec2(mx.add(int(1)), my.clone()),
Type::Vec4,
),
texture_load_texel(
&entry.matrices,
ivec2(mx.add(int(2)), my.clone()),
Type::Vec4,
),
texture_load_texel(&entry.matrices, ivec2(mx.add(int(3)), my), Type::Vec4),
],
);
let bm = join(
Type::Mat3,
vec![
matrix.element(0).xyz(),
matrix.element(1).xyz(),
matrix.element(2).xyz(),
],
);
statements.push(
position_local().assign(
matrix
.mul(vec4_join(vec![position_local(), float(1.0)]))
.xyz(),
),
);
let transformed = normal_local().div(join(
Type::Vec3,
vec![
bm.element(0).dot(bm.element(0)),
bm.element(1).dot(bm.element(1)),
bm.element(2).dot(bm.element(2)),
],
));
statements.push(normal_local().assign(bm.mul(transformed).xyz()));
statements
}