aboutsummaryrefslogtreecommitdiff
path: root/src_testbed/lines/mod.rs
blob: a7dd7bb774a8acce52a8a178f16952295dd0f167 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#![allow(warnings)]
use bevy::render::view::NoFrustumCulling;
/**
 *
 * NOTE: this module and its submodules are only temporary. It is a copy-paste of the bevy-debug-lines
 *       crate: https://github.com/Toqozz/bevy_debug_lines (MIT license)
 * It has been partially updated to work with bevy 0.7, but hasn’t been released yet.
 * So, in the mean time, we are keeping a version here that we will replace by the
 * upstream dependency once:
 * 1. The version compatible with bevy 0.7 is released to crates.io.
 * 2. We find a way to make the 2D version work with our examples. The problem
 *    only happens when running our own examples because cargo’s unification of
 *    features will enable the `3d` feature of `bevy_debug_lines` when running
 *    a `2d` example.
 *
 */
use bevy::{
    asset::{Assets, HandleUntyped},
    pbr::{NotShadowCaster, NotShadowReceiver},
    prelude::*,
    reflect::TypeUuid,
    render::{
        mesh::{/*Indices,*/ Mesh, VertexAttributeValues},
        render_phase::AddRenderCommand,
        render_resource::PrimitiveTopology,
        render_resource::Shader,
    },
};

mod render_dim;

// This module exists to "isolate" the `#[cfg]` attributes to this part of the
// code. Otherwise, we would pollute the code with a lot of feature
// gates-specific code.
#[cfg(feature = "dim3")]
mod dim {
    pub(crate) use super::render_dim::r3d::{queue, DebugLinePipeline, DrawDebugLines};
    pub(crate) use bevy::core_pipeline::Opaque3d as Phase;
    use bevy::{asset::Handle, render::mesh::Mesh};

    pub(crate) type MeshHandle = Handle<Mesh>;
    pub(crate) fn from_handle(from: &MeshHandle) -> &Handle<Mesh> {
        from
    }
    pub(crate) fn into_handle(from: Handle<Mesh>) -> MeshHandle {
        from
    }
    pub(crate) const SHADER_FILE: &str = include_str!("debuglines.wgsl");
    pub(crate) const DIMMENSION: &str = "3d";
}
#[cfg(feature = "dim2")]
mod dim {
    pub(crate) use super::render_dim::r2d::{queue, DebugLinePipeline, DrawDebugLines};
    pub(crate) use bevy::core_pipeline::Transparent2d as Phase;
    use bevy::{asset::Handle, render::mesh::Mesh, sprite::Mesh2dHandle};

    pub(crate) type MeshHandle = Mesh2dHandle;
    pub(crate) fn from_handle(from: &MeshHandle) -> &Handle<Mesh> {
        &from.0
    }
    pub(crate) fn into_handle(from: Handle<Mesh>) -> MeshHandle {
        Mesh2dHandle(from)
    }
    pub(crate) const SHADER_FILE: &str = include_str!("debuglines2d.wgsl");
    pub(crate) const DIMMENSION: &str = "2d";
}

// See debuglines.wgsl for explanation on 2 shaders.
//pub(crate) const SHADER_FILE: &str = include_str!("debuglines.wgsl");
pub(crate) const DEBUG_LINES_SHADER_HANDLE: HandleUntyped =
    HandleUntyped::weak_from_u64(Shader::TYPE_UUID, 17477439189930443325);

pub(crate) struct DebugLinesConfig {
    depth_test: bool,
}

/// Bevy plugin, for initializing stuff.
///
/// # Usage
///
/// ```.ignore
/// use bevy::prelude::*;
/// use bevy_prototype_debug_lines::*;
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugin(DebugLinesPlugin::default())
///     .run();
/// ```
///
/// Alternatively, you can initialize the plugin with depth testing, so that
/// debug lines cut through geometry. To do this, use [`DebugLinesPlugin::with_depth_test(true)`].
/// ```.ignore
/// use bevy::prelude::*;
/// use bevy_prototype_debug_lines::*;
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugin(DebugLinesPlugin::with_depth_test(true))
///     .run();
/// ```
#[derive(Debug, Default, Clone)]
pub struct DebugLinesPlugin {
    depth_test: bool,
}

impl DebugLinesPlugin {
    /// Controls whether debug lines should be drawn with depth testing enabled
    /// or disabled.
    ///
    /// # Arguments
    ///
    /// * `val` - True if lines should intersect with other geometry, or false
    ///   if lines should always draw on top be drawn on top (the default).
    pub fn with_depth_test(val: bool) -> Self {
        Self { depth_test: val }
    }
}

impl Plugin for DebugLinesPlugin {
    fn build(&self, app: &mut App) {
        use bevy::render::{render_resource::SpecializedMeshPipelines, RenderApp, RenderStage};
        let mut shaders = app.world.get_resource_mut::<Assets<Shader>>().unwrap();
        shaders.set_untracked(
            DEBUG_LINES_SHADER_HANDLE,
            Shader::from_wgsl(dim::SHADER_FILE),
        );
        app.init_resource::<DebugLines>();
        app.add_startup_system(setup)
            .add_system_to_stage(CoreStage::PostUpdate, update.label("draw_lines"));
        app.sub_app_mut(RenderApp)
            .add_render_command::<dim::Phase, dim::DrawDebugLines>()
            .insert_resource(DebugLinesConfig {
                depth_test: self.depth_test,
            })
            .init_resource::<dim::DebugLinePipeline>()
            .init_resource::<SpecializedMeshPipelines<dim::DebugLinePipeline>>()
            .add_system_to_stage(RenderStage::Extract, extract)
            .add_system_to_stage(RenderStage::Queue, dim::queue);

        info!("Loaded {} debug lines plugin.", dim::DIMMENSION);
    }
}

// Number of meshes to separate line buffers into.
// We don't really do culling currently but this is a gateway to that.
const MESH_COUNT: usize = 4;
// Maximum number of points for each individual mesh.
const MAX_POINTS_PER_MESH: usize = 2_usize.pow(16);
const _MAX_LINES_PER_MESH: usize = MAX_POINTS_PER_MESH / 2;
/// Maximum number of points.
pub const MAX_POINTS: usize = MAX_POINTS_PER_MESH * MESH_COUNT;
/// Maximum number of unique lines to draw at once.
pub const MAX_LINES: usize = MAX_POINTS / 2;

fn setup(mut cmds: Commands, mut meshes: ResMut<Assets<Mesh>>) {
    // Spawn a bunch of meshes to use for lines.
    for i in 0..MESH_COUNT {
        // Create a new mesh with the number of vertices we need.
        let mut mesh = Mesh::new(PrimitiveTopology::LineList);
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            VertexAttributeValues::Float32x3(Vec::with_capacity(MAX_POINTS_PER_MESH)),
        );
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_COLOR,
            VertexAttributeValues::Uint32(Vec::with_capacity(MAX_POINTS_PER_MESH)),
        );
        // https://github.com/Toqozz/bevy_debug_lines/issues/16
        //mesh.set_indices(Some(Indices::U16(Vec::with_capacity(MAX_POINTS_PER_MESH))));

        cmds.spawn_bundle((
            dim::into_handle(meshes.add(mesh)),
            NotShadowCaster,
            NotShadowReceiver,
            NoFrustumCulling,
            Transform::default(),
            GlobalTransform::default(),
            Visibility::default(),
            ComputedVisibility::default(),
            DebugLinesMesh(i),
        ));
    }
}

fn update(
    debug_line_meshes: Query<(&dim::MeshHandle, &DebugLinesMesh)>,
    time: Res<Time>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut lines: ResMut<DebugLines>,
) {
    // For each debug line mesh, fill its buffers with the relevant positions/colors chunks.
    for (mesh_handle, debug_lines_idx) in debug_line_meshes.iter() {
        let mesh = meshes.get_mut(dim::from_handle(mesh_handle)).unwrap();
        use VertexAttributeValues::{Float32x3, Uint32};
        if let Some(Float32x3(vbuffer)) = mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION) {
            vbuffer.clear();
            if let Some(new_content) = lines
                .positions
                .chunks(MAX_POINTS_PER_MESH)
                .nth(debug_lines_idx.0)
            {
                vbuffer.extend(new_content);
            }
        }

        if let Some(Uint32(cbuffer)) = mesh.attribute_mut(Mesh::ATTRIBUTE_COLOR) {
            cbuffer.clear();
            if let Some(new_content) = lines
                .colors
                .chunks(MAX_POINTS_PER_MESH)
                .nth(debug_lines_idx.0)
            {
                cbuffer.extend(new_content);
            }
        }

        /*
        // https://github.com/Toqozz/bevy_debug_lines/issues/16
        if let Some(Indices::U16(indices)) = mesh.indices_mut() {
            indices.clear();
            if let Some(new_content) = lines.durations.chunks(_MAX_LINES_PER_MESH).nth(debug_lines_idx.0) {
                indices.extend(
                    new_content.iter().enumerate().map(|(i, _)| i as u16).flat_map(|i| [i * 2, i*2 + 1])
                );
            }
        }
        */
    }

    // Processes stuff like getting rid of expired lines and stuff.
    lines.update(time.delta_seconds());
}

/// Move the DebugLinesMesh marker Component to the render context.
fn extract(mut commands: Commands, query: Query<Entity, With<DebugLinesMesh>>) {
    for entity in query.iter() {
        commands.get_or_spawn(entity).insert(RenderDebugLinesMesh);
    }
}

#[derive(Component)]
pub(crate) struct DebugLinesMesh(usize);

#[derive(Component)]
pub(crate) struct RenderDebugLinesMesh;

/// Bevy resource providing facilities to draw lines.
///
/// # Usage
/// ```.ignore
/// use bevy::prelude::*;
/// use bevy_prototype_debug_lines::*;
///
/// // Draws 3 horizontal lines, which disappear after 1 frame.
/// fn some_system(mut lines: ResMut<DebugLines>) {
///     lines.line(Vec3::new(-1.0, 1.0, 0.0), Vec3::new(1.0, 1.0, 0.0), 0.0);
///     lines.line_colored(
///         Vec3::new(-1.0, 0.0, 0.0),
///         Vec3::new(1.0, 0.0, 0.0),
///         0.0,
///         Color::WHITE
///     );
///     lines.line_gradient(
///         Vec3::new(-1.0, -1.0, 0.0),
///         Vec3::new(1.0, -1.0, 0.0),
///         0.0,
///         Color::WHITE, Color::PINK
///     );
/// }
/// ```
#[derive(Default)]
pub struct DebugLines {
    pub positions: Vec<[f32; 3]>,
    //pub colors: Vec<[f32; 4]>,
    pub colors: Vec<u32>,
    pub durations: Vec<f32>,
}

impl DebugLines {
    /// Draw a line i