Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto Batching #41

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions examples/batching_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
prelude::*,
};
use bevy_polyline::{prelude::*, PolylineSettings};

const SIDE_LEN: i32 = 60;
const POLY_CUBE_SIDE_LEN: i32 = 3;

fn main() {
App::new()
.insert_resource(Msaa { samples: 4 })
.add_plugins(DefaultPlugins.set(WindowPlugin {
window: WindowDescriptor {
present_mode: bevy::window::PresentMode::Immediate,
..default()
},
..default()
}))
.add_plugin(PolylinePlugin)
.add_plugin(FrameTimeDiagnosticsPlugin::default())
.add_plugin(LogDiagnosticsPlugin::default())
.add_startup_system(setup)
.add_system(toggle_batching)
.add_system(rotator_system)
.run();
}

fn toggle_batching(mut settings: ResMut<PolylineSettings>, input: Res<Input<KeyCode>>) {
if input.just_pressed(KeyCode::Space) {
settings.batching_enabled = !settings.batching_enabled;
info!("Batching enabled: {}", settings.batching_enabled);
}
}

fn setup(mut commands: Commands, mut polyline_materials: ResMut<Assets<PolylineMaterial>>) {
let n_entities = SIDE_LEN.pow(3);
let n_lines = n_entities * POLY_CUBE_SIDE_LEN.pow(3);
info!("Rendering {n_entities} polyline entities, with a total of {n_lines} lines.");

let material = polyline_materials.add(PolylineMaterial {
width: 4.0,
color: Color::WHITE,
perspective: true,
..Default::default()
});

let mut list = Vec::new();

for x in 0..SIDE_LEN {
for y in 0..SIDE_LEN {
for z in 0..SIDE_LEN {
let x = (x * 2 - SIDE_LEN / 2) as f32;
let y = (y * 2 - SIDE_LEN / 2) as f32;
let z = (z * 2 - SIDE_LEN / 2) as f32;

let poly_cube_origin = Vec3::new(x, y, z);

list.push(PolylineBundle {
polyline: Polyline::new(
(0..POLY_CUBE_SIDE_LEN.pow(3))
.map(|i| {
let ix = i % POLY_CUBE_SIDE_LEN;
let iy = i / POLY_CUBE_SIDE_LEN % POLY_CUBE_SIDE_LEN;
let iz = i / POLY_CUBE_SIDE_LEN.pow(2) % POLY_CUBE_SIDE_LEN;
Vec3::new(ix as f32, iy as f32, iz as f32)
/ (POLY_CUBE_SIDE_LEN as f32)
+ poly_cube_origin
})
.collect(),
),
material: material.clone(),
..Default::default()
});
}
}
}
commands.spawn_batch(list);

// camera
commands.spawn((
Camera3dBundle {
transform: Transform::from_xyz(-2.0, 2.5, -5.0).looking_at(Vec3::ZERO, Vec3::Y),
..Camera3dBundle::default()
},
Rotates,
));
}

/// this component indicates what entities should rotate
#[derive(Component)]
struct Rotates;

fn rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<Rotates>>) {
for mut transform in query.iter_mut() {
*transform = Transform::from_rotation(Quat::from_rotation_y(
(4.0 * std::f32::consts::PI / 50.0) * time.delta_seconds(),
)) * *transform;
}
}
9 changes: 3 additions & 6 deletions examples/depth_bias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut pbr_materials: ResMut<Assets<StandardMaterial>>,
mut polylines: ResMut<Assets<Polyline>>,
mut materials: ResMut<Assets<PolylineMaterial>>,
) {
commands
Expand All @@ -76,9 +75,9 @@ fn setup(
let bottom = Vec3::Y * -100.0;
// Show the middle as a vertical red bar.
commands.spawn(PolylineBundle {
polyline: polylines.add(Polyline {
polyline: Polyline {
vertices: vec![top, bottom],
}),
},
material: materials.add(PolylineMaterial {
width: 5.0,
color: Color::RED,
Expand All @@ -94,9 +93,7 @@ fn setup(
let left = Vec3::new(0.0, bias * 35.0, -500.0);
let right = Vec3::new(0.0, bias * 35.0, 500.0);
commands.spawn(PolylineBundle {
polyline: polylines.add(Polyline {
vertices: vec![left, right],
}),
polyline: Polyline::new(vec![left, right]),
material: materials.add(PolylineMaterial {
width: 1.0,
color: Color::hsl((bias + 1.0) / 2.0 * 270.0, 1.0, 0.5),
Expand Down
24 changes: 10 additions & 14 deletions examples/linestrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,18 @@ fn setup(
mut meshes: ResMut<Assets<Mesh>>,
mut standard_materials: ResMut<Assets<StandardMaterial>>,
mut polyline_materials: ResMut<Assets<PolylineMaterial>>,
mut polylines: ResMut<Assets<Polyline>>,
) {
commands.spawn(PolylineBundle {
polyline: polylines.add(Polyline {
vertices: vec![
Vec3::new(-0.5, -0.5, -0.5),
Vec3::new(0.5, -0.5, -0.5),
Vec3::new(0.5, 0.5, -0.5),
Vec3::new(-0.5, 0.5, -0.5),
Vec3::new(-0.5, 0.5, 0.5),
Vec3::new(0.5, 0.5, 0.5),
Vec3::new(0.5, -0.5, 0.5),
Vec3::new(-0.5, -0.5, 0.5),
],
..Default::default()
}),
polyline: Polyline::new(vec![
Vec3::new(-0.5, -0.5, -0.5),
Vec3::new(0.5, -0.5, -0.5),
Vec3::new(0.5, 0.5, -0.5),
Vec3::new(-0.5, 0.5, -0.5),
Vec3::new(-0.5, 0.5, 0.5),
Vec3::new(0.5, 0.5, 0.5),
Vec3::new(0.5, -0.5, 0.5),
Vec3::new(-0.5, -0.5, 0.5),
]),
material: polyline_materials.add(PolylineMaterial {
width: 2.0,
color: Color::RED,
Expand Down
11 changes: 2 additions & 9 deletions examples/minimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,9 @@ fn main() {
.run();
}

fn setup(
mut commands: Commands,
mut polyline_materials: ResMut<Assets<PolylineMaterial>>,
mut polylines: ResMut<Assets<Polyline>>,
) {
fn setup(mut commands: Commands, mut polyline_materials: ResMut<Assets<PolylineMaterial>>) {
commands.spawn(PolylineBundle {
polyline: polylines.add(Polyline {
vertices: vec![-Vec3::ONE, Vec3::ONE],
..Default::default()
}),
polyline: Polyline::new(vec![-Vec3::ONE, Vec3::ONE]),
material: polyline_materials.add(PolylineMaterial {
width: 10.0,
color: Color::RED,
Expand Down
40 changes: 13 additions & 27 deletions examples/nbody.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use lazy_static::*;
use rand::{prelude::*, Rng};
use ringbuffer::{ConstGenericRingBuffer, RingBufferExt, RingBufferWrite};

const NUM_BODIES: usize = 512;
const NUM_BODIES: usize = 256;
const TRAIL_LENGTH: usize = 1024;
const MINIMUM_ANGLE: f32 = 1.48341872; // == acos(5 degrees)

Expand All @@ -21,7 +21,7 @@ fn main() {
.insert_resource(ClearColor(Color::BLACK))
.insert_resource(Msaa { samples: 4 })
.insert_resource(Simulation {
scale: 1e5,
scale: 4e5,
..Default::default()
})
.add_plugins(DefaultPlugins.set(WindowPlugin {
Expand All @@ -44,12 +44,9 @@ fn main() {
.run();
}

fn setup(
mut commands: Commands,
mut polyline_materials: ResMut<Assets<PolylineMaterial>>,
mut polylines: ResMut<Assets<Polyline>>,
) {
fn setup(mut commands: Commands, mut polyline_materials: ResMut<Assets<PolylineMaterial>>) {
let mut rng = StdRng::seed_from_u64(0);

for _index in 0..NUM_BODIES {
let r = rng.gen_range(2f32..800f32);
let theta = rng.gen_range(0f32..2.0 * PI);
Expand All @@ -59,6 +56,7 @@ fn setup(
r * f32::sin(theta),
);
let size = rng.gen_range(50f32..1000f32);

commands.spawn((
Body {
mass: size,
Expand All @@ -68,9 +66,7 @@ fn setup(
},
Trail(ConstGenericRingBuffer::<Vec3A, TRAIL_LENGTH>::new()),
PolylineBundle {
polyline: polylines.add(Polyline {
vertices: Vec::with_capacity(TRAIL_LENGTH),
}),
polyline: Polyline::new(Vec::with_capacity(TRAIL_LENGTH)),
material: polyline_materials.add(PolylineMaterial {
width: (size * 0.1).powf(1.8),
color: Color::hsl(rng.gen_range(0.0..360.0), 1.0, rng.gen_range(0.4..2.0)),
Expand Down Expand Up @@ -167,7 +163,7 @@ const EPSILON: f32 = 1.;
fn nbody_system(
time: Res<Time>,
mut simulation: ResMut<Simulation>,
mut query: Query<(Entity, &mut Body, &mut Trail, &Handle<Polyline>)>,
mut query: Query<(Entity, &mut Body, &mut Trail, &Polyline)>,
) {
let mut bodies = query.iter_mut().collect::<Vec<_>>();
// dbg!(&bodies);
Expand Down Expand Up @@ -212,11 +208,8 @@ fn nbody_system(
}
}

fn update_trails(
mut polylines: ResMut<Assets<Polyline>>,
mut query: Query<(&Body, &mut Trail, &Handle<Polyline>)>,
) {
query.for_each_mut(|(body, mut trail, polyline)| {
fn update_trails(mut query: Query<(&Body, &mut Trail, &mut Polyline)>) {
query.for_each_mut(|(body, mut trail, mut polyline)| {
if let Some(position) = trail.0.back() {
let last_vec = *position - body.position;
let last_last_vec = if let Some(position) = trail.0.get(-2) {
Expand All @@ -227,24 +220,17 @@ fn update_trails(
let gt_min_angle = last_vec.dot(last_last_vec) > MINIMUM_ANGLE;
if gt_min_angle {
trail.0.push(body.position);
polylines.get_mut(polyline).unwrap().vertices =
trail.0.iter().map(|v| Vec3::from(*v)).collect()
polyline.vertices = trail.0.iter().map(|v| Vec3::from(*v)).collect()
} else {
// If the last point didn't actually add much of a curve, just overwrite it.
if polylines.get_mut(polyline).unwrap().vertices.len() > 1 {
if polyline.vertices.len() > 1 {
*trail.0.get_mut(-1).unwrap() = body.position;
*polylines
.get_mut(polyline)
.unwrap()
.vertices
.last_mut()
.unwrap() = body.position.into();
*polyline.vertices.last_mut().unwrap() = body.position.into();
}
}
} else {
trail.0.push(body.position);
polylines.get_mut(polyline).unwrap().vertices =
trail.0.iter().map(|v| Vec3::from(*v)).collect()
polyline.vertices = trail.0.iter().map(|v| Vec3::from(*v)).collect()
}
});
}
Expand Down
12 changes: 12 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,18 @@ pub mod prelude {
pub const SHADER_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(Shader::TYPE_UUID, 12823766040132746065);

#[derive(Resource)]
pub struct PolylineSettings {
pub batching_enabled: bool,
}
impl Default for PolylineSettings {
fn default() -> Self {
Self {
batching_enabled: true,
}
}
}

pub struct PolylinePlugin;

impl Plugin for PolylinePlugin {
Expand Down
1 change: 0 additions & 1 deletion src/material.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,6 @@ pub struct PolylineMaterialPlugin;
impl Plugin for PolylineMaterialPlugin {
fn build(&self, app: &mut App) {
app.add_asset::<PolylineMaterial>()
.add_plugin(ExtractComponentPlugin::<Handle<PolylineMaterial>>::default())
.add_plugin(RenderAssetPlugin::<PolylineMaterial>::default());
if let Ok(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
Expand Down
Loading