1use bevy::{
9 asset::RenderAssetUsages,
10 color::palettes::basic::YELLOW,
11 core_pipeline::core_2d::{Transparent2d, CORE_2D_DEPTH_FORMAT},
12 math::{ops, FloatOrd},
13 mesh::{Indices, MeshVertexAttribute, VertexBufferLayout},
14 prelude::*,
15 render::{
16 mesh::RenderMesh,
17 render_asset::RenderAssets,
18 render_phase::{
19 AddRenderCommand, DrawFunctions, PhaseItemExtraIndex, SetItemPipeline,
20 ViewSortedRenderPhases,
21 },
22 render_resource::{
23 BlendState, ColorTargetState, ColorWrites, CompareFunction, DepthBiasState,
24 DepthStencilState, Face, FragmentState, MultisampleState, PipelineCache,
25 PrimitiveState, PrimitiveTopology, RenderPipelineDescriptor, SpecializedRenderPipeline,
26 SpecializedRenderPipelines, StencilFaceState, StencilState, TextureFormat,
27 VertexFormat, VertexState, VertexStepMode,
28 },
29 sync_component::SyncComponentPlugin,
30 sync_world::{MainEntityHashMap, RenderEntity},
31 view::{ExtractedView, RenderVisibleEntities, ViewTarget},
32 Extract, Render, RenderApp, RenderStartup, RenderSystems,
33 },
34 sprite_render::{
35 extract_mesh2d, init_mesh_2d_pipeline, DrawMesh2d, Material2dBindGroupId, Mesh2dPipeline,
36 Mesh2dPipelineKey, Mesh2dTransforms, MeshFlags, RenderMesh2dInstance, SetMesh2dBindGroup,
37 SetMesh2dViewBindGroup,
38 },
39};
40use std::f32::consts::PI;
41
42fn main() {
43 App::new()
44 .add_plugins((DefaultPlugins, ColoredMesh2dPlugin))
45 .add_systems(Startup, star)
46 .run();
47}
48
49fn star(
50 mut commands: Commands,
51 mut meshes: ResMut<Assets<Mesh>>,
53) {
54 let mut star = Mesh::new(
62 PrimitiveTopology::TriangleList,
63 RenderAssetUsages::RENDER_WORLD,
64 );
65
66 let mut v_pos = vec![[0.0, 0.0, 0.0]];
79 for i in 0..10 {
80 let a = i as f32 * PI / 5.0;
82 let r = (1 - i % 2) as f32 * 100.0 + 100.0;
84 v_pos.push([r * ops::sin(a), r * ops::cos(a), 0.0]);
86 }
87 star.insert_attribute(Mesh::ATTRIBUTE_POSITION, v_pos);
89 let mut v_color: Vec<u32> = vec![LinearRgba::BLACK.as_u32()];
92 v_color.extend_from_slice(&[LinearRgba::from(YELLOW).as_u32(); 10]);
93 star.insert_attribute(
94 MeshVertexAttribute::new("Vertex_Color", 1, VertexFormat::Uint32),
95 v_color,
96 );
97
98 let mut indices = vec![0, 1, 10];
108 for i in 2..=10 {
109 indices.extend_from_slice(&[0, i, i - 1]);
110 }
111 star.insert_indices(Indices::U32(indices));
112
113 commands.spawn((
115 ColoredMesh2d,
117 Mesh2d(meshes.add(star)),
119 ));
120
121 commands.spawn(Camera2d);
122}
123
124#[derive(Component, Default)]
126pub struct ColoredMesh2d;
127
128#[derive(Resource)]
130pub struct ColoredMesh2dPipeline {
131 mesh2d_pipeline: Mesh2dPipeline,
133 shader: Handle<Shader>,
135}
136
137fn init_colored_mesh_2d_pipeline(
138 mut commands: Commands,
139 mesh2d_pipeline: Res<Mesh2dPipeline>,
140 colored_mesh2d_shader: Res<ColoredMesh2dShader>,
141) {
142 commands.insert_resource(ColoredMesh2dPipeline {
143 mesh2d_pipeline: mesh2d_pipeline.clone(),
144 shader: colored_mesh2d_shader.0.clone(),
146 });
147}
148
149impl SpecializedRenderPipeline for ColoredMesh2dPipeline {
151 type Key = Mesh2dPipelineKey;
152
153 fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
154 let formats = vec![
157 VertexFormat::Float32x3,
159 VertexFormat::Uint32,
161 ];
162
163 let vertex_layout =
164 VertexBufferLayout::from_vertex_formats(VertexStepMode::Vertex, formats);
165
166 let format = match key.contains(Mesh2dPipelineKey::HDR) {
167 true => ViewTarget::TEXTURE_FORMAT_HDR,
168 false => TextureFormat::bevy_default(),
169 };
170
171 RenderPipelineDescriptor {
172 vertex: VertexState {
173 shader: self.shader.clone(),
175 buffers: vec![vertex_layout],
177 ..default()
178 },
179 fragment: Some(FragmentState {
180 shader: self.shader.clone(),
182 targets: vec![Some(ColorTargetState {
183 format,
184 blend: Some(BlendState::ALPHA_BLENDING),
185 write_mask: ColorWrites::ALL,
186 })],
187 ..default()
188 }),
189 layout: vec![
191 self.mesh2d_pipeline.view_layout.clone(),
193 self.mesh2d_pipeline.mesh_layout.clone(),
195 ],
196 primitive: PrimitiveState {
197 cull_mode: Some(Face::Back),
198 topology: key.primitive_topology(),
199 ..default()
200 },
201 depth_stencil: Some(DepthStencilState {
202 format: CORE_2D_DEPTH_FORMAT,
203 depth_write_enabled: false,
204 depth_compare: CompareFunction::GreaterEqual,
205 stencil: StencilState {
206 front: StencilFaceState::IGNORE,
207 back: StencilFaceState::IGNORE,
208 read_mask: 0,
209 write_mask: 0,
210 },
211 bias: DepthBiasState {
212 constant: 0,
213 slope_scale: 0.0,
214 clamp: 0.0,
215 },
216 }),
217 multisample: MultisampleState {
218 count: key.msaa_samples(),
219 mask: !0,
220 alpha_to_coverage_enabled: false,
221 },
222 label: Some("colored_mesh2d_pipeline".into()),
223 ..default()
224 }
225 }
226}
227
228type DrawColoredMesh2d = (
230 SetItemPipeline,
232 SetMesh2dViewBindGroup<0>,
234 SetMesh2dBindGroup<1>,
236 DrawMesh2d,
238);
239
240const COLORED_MESH2D_SHADER: &str = r"
243// Import the standard 2d mesh uniforms and set their bind groups
244#import bevy_sprite_render::mesh2d_functions
245
246// The structure of the vertex buffer is as specified in `specialize()`
247struct Vertex {
248 @builtin(instance_index) instance_index: u32,
249 @location(0) position: vec3<f32>,
250 @location(1) color: u32,
251};
252
253struct VertexOutput {
254 // The vertex shader must set the on-screen position of the vertex
255 @builtin(position) clip_position: vec4<f32>,
256 // We pass the vertex color to the fragment shader in location 0
257 @location(0) color: vec4<f32>,
258};
259
260/// Entry point for the vertex shader
261@vertex
262fn vertex(vertex: Vertex) -> VertexOutput {
263 var out: VertexOutput;
264 // Project the world position of the mesh into screen position
265 let model = mesh2d_functions::get_world_from_local(vertex.instance_index);
266 out.clip_position = mesh2d_functions::mesh2d_position_local_to_clip(model, vec4<f32>(vertex.position, 1.0));
267 // Unpack the `u32` from the vertex buffer into the `vec4<f32>` used by the fragment shader
268 out.color = vec4<f32>((vec4<u32>(vertex.color) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(255u)) / 255.0;
269 return out;
270}
271
272// The input of the fragment shader must correspond to the output of the vertex shader for all `location`s
273struct FragmentInput {
274 // The color is interpolated between vertices by default
275 @location(0) color: vec4<f32>,
276};
277
278/// Entry point for the fragment shader
279@fragment
280fn fragment(in: FragmentInput) -> @location(0) vec4<f32> {
281 return in.color;
282}
283";
284
285pub struct ColoredMesh2dPlugin;
287
288#[derive(Resource)]
291struct ColoredMesh2dShader(Handle<Shader>);
292
293#[derive(Resource, Deref, DerefMut, Default)]
295pub struct RenderColoredMesh2dInstances(MainEntityHashMap<RenderMesh2dInstance>);
296
297impl Plugin for ColoredMesh2dPlugin {
298 fn build(&self, app: &mut App) {
299 let mut shaders = app.world_mut().resource_mut::<Assets<Shader>>();
301 let shader = shaders.add(Shader::from_wgsl(COLORED_MESH2D_SHADER, file!()));
304
305 app.add_plugins(SyncComponentPlugin::<ColoredMesh2d>::default());
306
307 app.get_sub_app_mut(RenderApp)
309 .unwrap()
310 .insert_resource(ColoredMesh2dShader(shader))
311 .add_render_command::<Transparent2d, DrawColoredMesh2d>()
312 .init_resource::<SpecializedRenderPipelines<ColoredMesh2dPipeline>>()
313 .init_resource::<RenderColoredMesh2dInstances>()
314 .add_systems(
315 RenderStartup,
316 init_colored_mesh_2d_pipeline.after(init_mesh_2d_pipeline),
317 )
318 .add_systems(
319 ExtractSchedule,
320 extract_colored_mesh2d.after(extract_mesh2d),
321 )
322 .add_systems(
323 Render,
324 queue_colored_mesh2d.in_set(RenderSystems::QueueMeshes),
325 );
326 }
327}
328
329pub fn extract_colored_mesh2d(
331 mut commands: Commands,
332 mut previous_len: Local<usize>,
333 query: Extract<
336 Query<
337 (
338 Entity,
339 RenderEntity,
340 &ViewVisibility,
341 &GlobalTransform,
342 &Mesh2d,
343 ),
344 With<ColoredMesh2d>,
345 >,
346 >,
347 mut render_mesh_instances: ResMut<RenderColoredMesh2dInstances>,
348) {
349 let mut values = Vec::with_capacity(*previous_len);
350 for (entity, render_entity, view_visibility, transform, handle) in &query {
351 if !view_visibility.get() {
352 continue;
353 }
354
355 let transforms = Mesh2dTransforms {
356 world_from_local: (&transform.affine()).into(),
357 flags: MeshFlags::empty().bits(),
358 };
359
360 values.push((render_entity, ColoredMesh2d));
361 render_mesh_instances.insert(
362 entity.into(),
363 RenderMesh2dInstance {
364 mesh_asset_id: handle.0.id(),
365 transforms,
366 material_bind_group_id: Material2dBindGroupId::default(),
367 automatic_batching: false,
368 tag: 0,
369 },
370 );
371 }
372 *previous_len = values.len();
373 commands.try_insert_batch(values);
374}
375
376pub fn queue_colored_mesh2d(
378 transparent_draw_functions: Res<DrawFunctions<Transparent2d>>,
379 colored_mesh2d_pipeline: Res<ColoredMesh2dPipeline>,
380 mut pipelines: ResMut<SpecializedRenderPipelines<ColoredMesh2dPipeline>>,
381 pipeline_cache: Res<PipelineCache>,
382 render_meshes: Res<RenderAssets<RenderMesh>>,
383 render_mesh_instances: Res<RenderColoredMesh2dInstances>,
384 mut transparent_render_phases: ResMut<ViewSortedRenderPhases<Transparent2d>>,
385 views: Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
386) {
387 if render_mesh_instances.is_empty() {
388 return;
389 }
390 for (visible_entities, view, msaa) in &views {
392 let Some(transparent_phase) = transparent_render_phases.get_mut(&view.retained_view_entity)
393 else {
394 continue;
395 };
396
397 let draw_colored_mesh2d = transparent_draw_functions.read().id::<DrawColoredMesh2d>();
398
399 let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples())
400 | Mesh2dPipelineKey::from_hdr(view.hdr);
401
402 for (render_entity, visible_entity) in visible_entities.iter::<Mesh2d>() {
404 if let Some(mesh_instance) = render_mesh_instances.get(visible_entity) {
405 let mesh2d_handle = mesh_instance.mesh_asset_id;
406 let mesh2d_transforms = &mesh_instance.transforms;
407 let mut mesh2d_key = mesh_key;
409 let Some(mesh) = render_meshes.get(mesh2d_handle) else {
410 continue;
411 };
412 mesh2d_key |= Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology());
413
414 let pipeline_id =
415 pipelines.specialize(&pipeline_cache, &colored_mesh2d_pipeline, mesh2d_key);
416
417 let mesh_z = mesh2d_transforms.world_from_local.translation.z;
418 transparent_phase.add(Transparent2d {
419 entity: (*render_entity, *visible_entity),
420 draw_function: draw_colored_mesh2d,
421 pipeline: pipeline_id,
422 sort_key: FloatOrd(mesh_z),
425 batch_range: 0..1,
427 extra_index: PhaseItemExtraIndex::None,
428 extracted_index: usize::MAX,
429 indexed: mesh.indexed(),
430 });
431 }
432 }
433 }
434}