use nightshade::prelude::nalgebra_glm::Mat4;
use nightshade::prelude::*;
#[inline]
pub fn set_position(world: &mut World, entity: Entity, position: Vec3) {
if let Some(transform) =
world.get_mut::<nightshade::ecs::transform::components::LocalTransform>(entity)
{
transform.translation = position;
}
}
#[inline]
pub fn set_scale(world: &mut World, entity: Entity, scale: Vec3) {
if let Some(transform) =
world.get_mut::<nightshade::ecs::transform::components::LocalTransform>(entity)
{
transform.scale = scale;
}
}
#[inline]
pub fn set_rotation(world: &mut World, entity: Entity, axis: Vec3, radians: f32) {
if let Some(transform) =
world.get_mut::<nightshade::ecs::transform::components::LocalTransform>(entity)
{
transform.rotation = nalgebra_glm::quat_angle_axis(radians, &axis.normalize());
}
}
#[inline]
pub fn rotate(world: &mut World, entity: Entity, axis: Vec3, radians: f32) {
if let Some(transform) =
world.get_mut::<nightshade::ecs::transform::components::LocalTransform>(entity)
{
transform.rotation =
nalgebra_glm::quat_angle_axis(radians, &axis.normalize()) * transform.rotation;
}
}
pub fn position(world: &World, entity: Entity) -> Vec3 {
if world
.get::<freecs::dynamic::ChildOf>(entity)
.map(|child_of| child_of.0)
.is_none()
{
return world
.get::<nightshade::ecs::transform::components::LocalTransform>(entity)
.map(|transform| transform.translation)
.unwrap_or_else(Vec3::zeros);
}
let matrix = world_matrix(world, entity);
nalgebra_glm::vec3(matrix[(0, 3)], matrix[(1, 3)], matrix[(2, 3)])
}
pub(crate) fn local_matrix(transform: &LocalTransform) -> Mat4 {
nalgebra_glm::translation(&transform.translation)
* nalgebra_glm::quat_to_mat4(&transform.rotation)
* nalgebra_glm::scaling(&transform.scale)
}
pub(crate) fn world_matrix(world: &World, entity: Entity) -> Mat4 {
let matrix = world
.get::<nightshade::ecs::transform::components::LocalTransform>(entity)
.map(local_matrix)
.unwrap_or_else(Mat4::identity);
match world
.get::<freecs::dynamic::ChildOf>(entity)
.map(|child_of| child_of.0)
{
Some(parent_entity) => world_matrix(world, parent_entity) * matrix,
None => matrix,
}
}