bevy/crates/bevy_gizmos/src/pipeline_2d.rs
ira 001b3eb97c
Instanced line rendering for gizmos based on bevy_polyline (#8427)
# Objective

Adopt code from
[bevy_polyline](https://github.com/ForesightMiningSoftwareCorporation/bevy_polyline)
for gizmo line-rendering.
This adds configurable width and perspective rendering for the lines.

Many thanks to @mtsr for the initial work on bevy_polyline. Thanks to
@aevyrie for maintaining it, @nicopap for adding the depth_bias feature
and the other
[contributors](https://github.com/ForesightMiningSoftwareCorporation/bevy_polyline/graphs/contributors)
for squashing bugs and keeping bevy_polyline up-to-date.

#### Before

![Before](https://user-images.githubusercontent.com/29694403/232831591-a8e6ed0c-3a09-4413-80fa-74cb8e0d33dd.png)
#### After - with line perspective

![After](https://user-images.githubusercontent.com/29694403/232831692-ba7cbeb7-e63a-4f8e-9b1b-1b80c668f149.png)

Line perspective is not on by default because with perspective there is
no default line width that works for every scene.

<details><summary>After - without line perspective</summary>
<p>

![After - no
perspective](https://user-images.githubusercontent.com/29694403/232836344-0dbfb4c8-09b7-4cf5-95f9-a4c26f38dca3.png)

</p>
</details>

Somewhat unexpectedly, the performance is improved with this PR.
At 200,000 lines in many_gizmos I get ~110 FPS on main and ~200 FPS with
this PR.
I'm guessing this is a CPU side difference as I would expect the
rendering technique to be more expensive on the GPU to some extent, but
I am not entirely sure.

---------

Co-authored-by: Jonas Matser <github@jonasmatser.nl>
Co-authored-by: Aevyrie <aevyrie@gmail.com>
Co-authored-by: Nicola Papale <nico@nicopap.ch>
Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2023-06-13 06:49:47 +00:00

166 lines
5.1 KiB
Rust

use crate::{
line_gizmo_vertex_buffer_layouts, DrawLineGizmo, LineGizmo, LineGizmoUniformBindgroupLayout,
SetLineGizmoBindGroup, LINE_SHADER_HANDLE,
};
use bevy_app::{App, Plugin};
use bevy_asset::Handle;
use bevy_core_pipeline::core_2d::Transparent2d;
use bevy_ecs::{
prelude::Entity,
schedule::IntoSystemConfigs,
system::{Query, Res, ResMut, Resource},
world::{FromWorld, World},
};
use bevy_render::{
render_asset::RenderAssets,
render_phase::{AddRenderCommand, DrawFunctions, RenderPhase, SetItemPipeline},
render_resource::*,
texture::BevyDefault,
view::{ExtractedView, Msaa, ViewTarget},
Render, RenderApp, RenderSet,
};
use bevy_sprite::{Mesh2dPipeline, Mesh2dPipelineKey, SetMesh2dViewBindGroup};
use bevy_utils::FloatOrd;
pub struct LineGizmo2dPlugin;
impl Plugin for LineGizmo2dPlugin {
fn build(&self, app: &mut App) {
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else { return };
render_app
.add_render_command::<Transparent2d, DrawLineGizmo2d>()
.init_resource::<SpecializedRenderPipelines<LineGizmoPipeline>>()
.add_systems(Render, queue_line_gizmos_2d.in_set(RenderSet::Queue));
}
fn finish(&self, app: &mut App) {
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else { return };
render_app.init_resource::<LineGizmoPipeline>();
}
}
#[derive(Clone, Resource)]
struct LineGizmoPipeline {
mesh_pipeline: Mesh2dPipeline,
uniform_layout: BindGroupLayout,
}
impl FromWorld for LineGizmoPipeline {
fn from_world(render_world: &mut World) -> Self {
LineGizmoPipeline {
mesh_pipeline: render_world.resource::<Mesh2dPipeline>().clone(),
uniform_layout: render_world
.resource::<LineGizmoUniformBindgroupLayout>()
.layout
.clone(),
}
}
}
#[derive(PartialEq, Eq, Hash, Clone)]
struct LineGizmoPipelineKey {
mesh_key: Mesh2dPipelineKey,
strip: bool,
}
impl SpecializedRenderPipeline for LineGizmoPipeline {
type Key = LineGizmoPipelineKey;
fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
let format = if key.mesh_key.contains(Mesh2dPipelineKey::HDR) {
ViewTarget::TEXTURE_FORMAT_HDR
} else {
TextureFormat::bevy_default()
};
let shader_defs = vec![
#[cfg(feature = "webgl")]
"SIXTEEN_BYTE_ALIGNMENT".into(),
];
let layout = vec![
self.mesh_pipeline.view_layout.clone(),
self.uniform_layout.clone(),
];
RenderPipelineDescriptor {
vertex: VertexState {
shader: LINE_SHADER_HANDLE.typed(),
entry_point: "vertex".into(),
shader_defs: shader_defs.clone(),
buffers: line_gizmo_vertex_buffer_layouts(key.strip),
},
fragment: Some(FragmentState {
shader: LINE_SHADER_HANDLE.typed(),
shader_defs,
entry_point: "fragment".into(),
targets: vec![Some(ColorTargetState {
format,
blend: Some(BlendState::ALPHA_BLENDING),
write_mask: ColorWrites::ALL,
})],
}),
layout,
primitive: PrimitiveState::default(),
depth_stencil: None,
multisample: MultisampleState {
count: key.mesh_key.msaa_samples(),
mask: !0,
alpha_to_coverage_enabled: false,
},
label: Some("LineGizmo Pipeline 2D".into()),
push_constant_ranges: vec![],
}
}
}
type DrawLineGizmo2d = (
SetItemPipeline,
SetMesh2dViewBindGroup<0>,
SetLineGizmoBindGroup<1>,
DrawLineGizmo,
);
#[allow(clippy::too_many_arguments)]
fn queue_line_gizmos_2d(
draw_functions: Res<DrawFunctions<Transparent2d>>,
pipeline: Res<LineGizmoPipeline>,
mut pipelines: ResMut<SpecializedRenderPipelines<LineGizmoPipeline>>,
pipeline_cache: Res<PipelineCache>,
msaa: Res<Msaa>,
line_gizmos: Query<(Entity, &Handle<LineGizmo>)>,
line_gizmo_assets: Res<RenderAssets<LineGizmo>>,
mut views: Query<(&ExtractedView, &mut RenderPhase<Transparent2d>)>,
) {
let draw_function = draw_functions.read().get_id::<DrawLineGizmo2d>().unwrap();
for (view, mut transparent_phase) in &mut views {
let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples())
| Mesh2dPipelineKey::from_hdr(view.hdr);
for (entity, handle) in &line_gizmos {
let Some(line_gizmo) = line_gizmo_assets.get(handle) else { continue };
let pipeline = pipelines.specialize(
&pipeline_cache,
&pipeline,
LineGizmoPipelineKey {
mesh_key,
strip: line_gizmo.strip,
},
);
transparent_phase.add(Transparent2d {
entity,
draw_function,
pipeline,
sort_key: FloatOrd(0.),
batch_range: None,
});
}
}
}