concinnity-dev 0.19.119

The Concinnity dev tooling library: world authoring, the in-engine editor, the debug server, docs and packaging
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! The data half of the Shaders panel: every `Shader` the world declares, in
//! declaration order, with the Materials that name it and its files, then the
//! SdfVolume distance fields (`sdf_field_list`), and the rows the panel lists
//! them as, with the actions each row's menu offers. A file's status is its
//! Shader's latest reload outcome as it bears on that file.

use concinnity_cook::authoring::world::entry_handles;
use concinnity_core::components::ShaderStage;
use concinnity_core::gfx::render_types::MAX_SHADER_BUCKETS;

use super::sdf_field_list::{FieldDecl, field_rows};
use super::shader_diagnostics::Tone;
use super::shader_source::{self, SourceKey, same_file};
use crate::debug::hot_reload::{ReloadFailure, ReloadOutcome, ReloadSubject, ReportBoard};
use crate::editor::select_related;

// One declared file of a Shader.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DeclaredFile {
    pub(crate) stage: ShaderStage,
    // As the world line spells it.
    pub(crate) declared: String,
    // Where it is on disk (`shader_source::resolve_path`).
    pub(crate) path: String,
}

// One declared Shader.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ShaderDecl {
    pub(crate) name: String,
    // The first declared Shader shades everything no Material assigns.
    pub(crate) default: bool,
    // The Materials naming it, as entry positions and names.
    pub(crate) materials: Vec<(usize, String)>,
    pub(crate) files: Vec<DeclaredFile>,
}

impl ShaderDecl {
    pub(crate) fn file(&self, stage: ShaderStage) -> Option<&DeclaredFile> {
        self.files.iter().find(|f| f.stage == stage)
    }
}

// Every Shader the entries declare, in order, each file's on-disk path from
// `resolve` (`shader_source::resolve_path`, which can walk the assets tree, so
// the caller keeps its answers).
pub(crate) fn declared(
    entries: &[serde_json::Value],
    mut resolve: impl FnMut(&str) -> String,
) -> Vec<ShaderDecl> {
    let names = entry_handles(entries);
    entries
        .iter()
        .enumerate()
        .filter(|(_, e)| entry_type(e) == Some("Shader"))
        .enumerate()
        .filter_map(|(order, (i, e))| {
            let name = names[i].clone()?;
            let args = e.get("args");
            let file = |stage: ShaderStage| {
                let declared = args?.get(shader_source::stage_name(stage))?.as_str()?;
                Some(DeclaredFile {
                    stage,
                    declared: declared.to_string(),
                    path: resolve(declared),
                })
            };
            let files = [ShaderStage::Fragment, ShaderStage::Vertex]
                .into_iter()
                .filter_map(file)
                .collect();
            let materials = select_related::entries_using(entries, &name)
                .into_iter()
                .filter(|&m| entry_type(&entries[m]) == Some("Material"))
                .filter_map(|m| Some((m, names[m].clone()?)))
                .collect();
            Some(ShaderDecl {
                name,
                default: order == 0,
                materials,
                files,
            })
        })
        .collect()
}

// How many Shaders the entries declare.
pub(crate) fn shader_count(entries: &[serde_json::Value]) -> usize {
    entries
        .iter()
        .filter(|e| entry_type(e) == Some("Shader"))
        .count()
}

// Whether a world with `count` Shaders can declare another.
pub(crate) fn can_add_shader(count: usize) -> bool {
    count < MAX_SHADER_BUCKETS
}

// Why "+ New Shader" is unavailable at the limit.
pub(crate) fn limit_reason() -> String {
    format!("{MAX_SHADER_BUCKETS} Shaders is the most a world can declare")
}

fn entry_type(e: &serde_json::Value) -> Option<&str> {
    e.get("type").and_then(|v| v.as_str())
}

// What became of a file the last time its Shader reloaded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FileStatus {
    // Nothing reloaded since the world was built: it runs as built.
    Built,
    // The Shader is not in the running world yet; it joins at the next rebuild.
    NotLive,
    // Compiled and swapped in, with this many warnings in the file.
    Ok(usize),
    // Compiled; its scene is not loaded, so it installs when the scene loads.
    AppliesOnLoad(usize),
    // The reload failed on an error in this file, or in no file of its own.
    Failed,
    // The reload failed on an error in another of the Shader's files.
    SiblingFailed,
}

impl FileStatus {
    pub(crate) fn label(self) -> String {
        match self {
            FileStatus::Built => "as built".to_string(),
            FileStatus::NotLive => "after rebuild".to_string(),
            FileStatus::Ok(0) => "ok".to_string(),
            FileStatus::Ok(1) => "1 warning".to_string(),
            FileStatus::Ok(n) => format!("{n} warnings"),
            FileStatus::AppliesOnLoad(_) => "on scene load".to_string(),
            FileStatus::Failed => "failed".to_string(),
            FileStatus::SiblingFailed => "other file failed".to_string(),
        }
    }

    pub(crate) fn tone(self) -> Tone {
        match self {
            FileStatus::Built | FileStatus::NotLive | FileStatus::Ok(0) => Tone::Info,
            FileStatus::AppliesOnLoad(0) => Tone::Info,
            FileStatus::Ok(_) | FileStatus::AppliesOnLoad(_) => Tone::Warning,
            FileStatus::Failed | FileStatus::SiblingFailed => Tone::Error,
        }
    }
}

// The status of `file` of `shader` on `board`.
pub(crate) fn file_status(
    board: &ReportBoard,
    shader: &ShaderDecl,
    file: &DeclaredFile,
) -> FileStatus {
    let subject = ReloadSubject::shader(&shader.name);
    if board.is_live(&subject) == Some(false) {
        return FileStatus::NotLive;
    }
    let Some(latest) = board.latest(&subject) else {
        return FileStatus::Built;
    };
    let warnings_here = |warnings: &[concinnity_cook::compile::program::Diagnostic]| {
        warnings
            .iter()
            .filter(|w| same_file(&w.path, &file.path))
            .count()
    };
    match &latest.outcome {
        ReloadOutcome::Swapped { warnings, .. } => FileStatus::Ok(warnings_here(warnings)),
        ReloadOutcome::AppliesOnLoad { warnings } => {
            FileStatus::AppliesOnLoad(warnings_here(warnings))
        }
        ReloadOutcome::Failed(ReloadFailure::Compile(failed)) => {
            let in_sibling = |path: &str| {
                shader
                    .files
                    .iter()
                    .any(|f| f.stage != file.stage && same_file(path, &f.path))
            };
            let here = failed.errors().any(|e| same_file(&e.path, &file.path));
            match !here && failed.errors().any(|e| in_sibling(&e.path)) {
                true => FileStatus::SiblingFailed,
                false => FileStatus::Failed,
            }
        }
        ReloadOutcome::Failed(_) => FileStatus::Failed,
    }
}

// What a row of the panel stands for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RowKind {
    // Shader `i`'s name; a click or its menu's Edit opens its form, and its
    // menu duplicates or deletes it.
    Header(usize),
    // A line of information under a Shader, or a control that is unavailable.
    Note,
    // The Materials naming Shader `i`; a click selects them.
    Materials(usize),
    // One file of a Shader; a click opens it, and a vertex file's menu
    // removes it.
    File(SourceKey),
    // "+ Add vertex file" under Shader `i`, which declares none.
    AddVertex(usize),
    // A section's title.
    Section,
    // Distance field `i`'s file; a click opens it, and its menu opens it,
    // selects its volumes, or deletes them.
    Field(usize),
    // A volume reading the field above, by name; a click opens its form.
    FieldVolume(String),
    // "+ New Shader".
    New,
}

// An action a row's "..." menu offers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MenuItem {
    Edit,
    Duplicate,
    Delete,
    // Stop declaring the vertex file; the file stays on disk.
    RemoveVertex,
    Open,
    SelectVolumes,
}

impl MenuItem {
    pub(crate) fn caption(self) -> &'static str {
        match self {
            MenuItem::Edit => "Edit",
            MenuItem::Duplicate => "Duplicate",
            MenuItem::Delete => "Delete",
            MenuItem::RemoveVertex => "Remove",
            MenuItem::Open => "Open",
            MenuItem::SelectVolumes => "Select volumes",
        }
    }

    pub(crate) fn danger(self) -> bool {
        matches!(self, MenuItem::Delete | MenuItem::RemoveVertex)
    }
}

// One row as drawn: its caption, an optional right-hand badge, whether it is
// indented under its Shader, and whether it is the open file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Row {
    pub(crate) kind: RowKind,
    pub(crate) text: String,
    pub(crate) badge: Option<(String, Tone)>,
    pub(crate) indent: bool,
    pub(crate) selected: bool,
}

impl Row {
    // Whether a click on the row's body does anything.
    pub(crate) fn clickable(&self) -> bool {
        !matches!(self.kind, RowKind::Note | RowKind::Section)
    }

    // What the row's menu offers; a row without a menu shows no dots. The
    // fragment file has none, since a Shader cannot go without it.
    pub(crate) fn menu(&self) -> &'static [MenuItem] {
        match &self.kind {
            RowKind::Header(_) => &[MenuItem::Edit, MenuItem::Duplicate, MenuItem::Delete],
            RowKind::File(SourceKey::Shader {
                stage: ShaderStage::Vertex,
                ..
            }) => &[MenuItem::RemoveVertex],
            RowKind::Field(_) => &[MenuItem::Open, MenuItem::SelectVolumes, MenuItem::Delete],
            _ => &[],
        }
    }
}

// The panel's rows: per Shader its name, the Materials naming it, a row per
// file and "+ Add vertex file" when it declares none, then the distance
// fields, then "+ New Shader", which at the Shader limit creates only SDF
// fields. `open` is the file the source panel shows.
pub(crate) fn rows(
    shaders: &[ShaderDecl],
    fields: &[FieldDecl],
    board: &ReportBoard,
    open: Option<&SourceKey>,
) -> Vec<Row> {
    let mut out = Vec::new();
    for (i, shader) in shaders.iter().enumerate() {
        out.push(Row {
            kind: RowKind::Header(i),
            text: shader.name.clone(),
            badge: shader.default.then(|| ("default".to_string(), Tone::Info)),
            indent: false,
            selected: false,
        });
        out.push(materials_row(i, shader));
        for file in &shader.files {
            let key = SourceKey::shader(&shader.name, file.stage);
            let status = file_status(board, shader, file);
            out.push(Row {
                selected: open == Some(&key),
                kind: RowKind::File(key),
                text: format!(
                    "{}  {}",
                    shader_source::stage_name(file.stage),
                    file.declared
                ),
                badge: Some((status.label(), status.tone())),
                indent: true,
            });
        }
        if shader.file(ShaderStage::Vertex).is_none() {
            out.push(Row {
                kind: RowKind::AddVertex(i),
                text: "+ Add vertex file".to_string(),
                badge: None,
                indent: true,
                selected: false,
            });
        }
    }
    out.extend(field_rows(fields, board, open));
    out.push(Row {
        kind: RowKind::New,
        text: "+ New Shader".to_string(),
        badge: (!can_add_shader(shaders.len()))
            .then(|| ("SDF fields only".to_string(), Tone::Info)),
        indent: false,
        selected: false,
    });
    out
}

fn materials_row(i: usize, shader: &ShaderDecl) -> Row {
    let names: Vec<&str> = shader.materials.iter().map(|(_, n)| n.as_str()).collect();
    let (kind, text) = match (names.is_empty(), shader.default) {
        (false, _) => (
            RowKind::Materials(i),
            format!("used by {}", names.join(", ")),
        ),
        (true, true) => (
            RowKind::Note,
            "shades every Material naming no Shader".to_string(),
        ),
        (true, false) => (RowKind::Note, "no Material names it".to_string()),
    };
    Row {
        kind,
        text,
        badge: None,
        indent: true,
        selected: false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::debug::hot_reload::{ReloadOutcome, ReloadReports};
    use concinnity_cook::compile::program::{CompileFailure, Diagnostic, Severity};
    use serde_json::json;

    fn entries() -> Vec<serde_json::Value> {
        vec![
            json!({"type": "Shader", "args": {"$id": "lit", "fragment": "/cn-none/lit.hlsl"}}),
            json!({"type": "Material", "args": {"$id": "plain"}}),
            json!({"type": "Shader", "args": {
                "$id": "reeds",
                "fragment": "/cn-none/reeds.hlsl",
                "vertex": "/cn-none/sway.hlsl",
            }}),
            json!({"type": "Material", "args": {"$id": "reed_mat", "shader": "reeds"}}),
            json!({"type": "Material", "args": {"$id": "marsh_mat", "shader": "reeds"}}),
            json!({"type": "Prop", "args": {"$id": "p", "material": "reed_mat"}}),
        ]
    }

    // Declaration order, the default badge on the first, the vertex file only
    // when declared, and the Materials naming each Shader (and nothing else).
    #[test]
    fn shaders_are_listed_in_declaration_order() {
        let shaders = declared(&entries(), str::to_string);
        let names: Vec<&str> = shaders.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, ["lit", "reeds"]);
        assert!(shaders[0].default && !shaders[1].default);
        assert_eq!(shaders[0].files.len(), 1);
        assert!(shaders[0].file(ShaderStage::Vertex).is_none());
        let vertex = shaders[1].file(ShaderStage::Vertex).unwrap();
        assert_eq!(vertex.declared, "/cn-none/sway.hlsl");
        assert!(shaders[0].materials.is_empty());
        assert_eq!(
            shaders[1].materials,
            [(3, "reed_mat".to_string()), (4, "marsh_mat".to_string())]
        );
    }

    #[test]
    fn an_anonymous_shader_is_listed_under_its_label() {
        let entries = vec![json!({"type": "Shader", "args": {"fragment": "/cn-none/a.hlsl"}})];
        assert_eq!(declared(&entries, str::to_string)[0].name, "Shader#0");
    }

    // The rows: each Shader's header (the default badged), its Materials, its
    // files, then the new-Shader row; the open file is selected.
    #[test]
    fn rows_list_each_shader_then_the_new_row() {
        let shaders = declared(&entries(), str::to_string);
        let open = SourceKey::shader("reeds", ShaderStage::Vertex);
        let rows = rows(&shaders, &[], &ReportBoard::default(), Some(&open));
        let texts: Vec<&str> = rows.iter().map(|r| r.text.as_str()).collect();
        assert_eq!(
            texts,
            [
                "lit",
                "shades every Material naming no Shader",
                "fragment  /cn-none/lit.hlsl",
                "+ Add vertex file",
                "reeds",
                "used by reed_mat, marsh_mat",
                "fragment  /cn-none/reeds.hlsl",
                "vertex  /cn-none/sway.hlsl",
                "+ New Shader",
            ]
        );
        assert_eq!(rows[0].badge, Some(("default".to_string(), Tone::Info)));
        assert_eq!(rows[3].kind, RowKind::AddVertex(0));
        assert!(rows[3].clickable());
        assert_eq!(rows[4].badge, None);
        assert_eq!(rows[5].kind, RowKind::Materials(1));
        assert!(!rows[1].clickable());
        assert!(rows[7].selected && !rows[6].selected);
        assert_eq!(rows[8].kind, RowKind::New);
        assert!(rows[8].clickable());
        assert_eq!(rows[8].badge, None);
    }

    // A header's menu edits, duplicates or deletes its Shader; only a vertex
    // file's menu removes the file, since the fragment is required.
    #[test]
    fn menus_edit_duplicate_delete_or_remove_the_vertex_file() {
        let shaders = declared(&entries(), str::to_string);
        let rows = rows(&shaders, &[], &ReportBoard::default(), None);
        let menu = |i: usize| rows[i].menu().to_vec();
        assert_eq!(rows[4].kind, RowKind::Header(1));
        assert_eq!(
            menu(4),
            [MenuItem::Edit, MenuItem::Duplicate, MenuItem::Delete]
        );
        assert!(rows[4].clickable(), "the header's body opens its form");
        assert!(menu(6).is_empty(), "the fragment file");
        assert_eq!(menu(7), [MenuItem::RemoveVertex]);
        assert!(menu(5).is_empty() && menu(3).is_empty());
        assert!(MenuItem::Delete.danger() && !MenuItem::Edit.danger());
        assert!(!MenuItem::Duplicate.danger());
    }

    // At the Shader limit "+ New Shader" still creates SDF fields, and says
    // that is all it creates.
    #[test]
    fn the_new_row_creates_only_fields_at_the_shader_limit() {
        let full: Vec<serde_json::Value> = (0..MAX_SHADER_BUCKETS)
            .map(|i| json!({"type": "Shader", "args": {"$id": format!("s{i}"), "fragment": "/cn-none/s.hlsl"}}))
            .collect();
        assert!(!can_add_shader(shader_count(&full)));
        assert!(can_add_shader(shader_count(&full[1..])));
        let shaders = declared(&full, str::to_string);
        let rows = rows(&shaders, &[], &ReportBoard::default(), None);
        let last = rows.last().unwrap();
        assert_eq!(last.kind, RowKind::New);
        assert!(last.clickable());
        assert_eq!(
            last.badge,
            Some(("SDF fields only".to_string(), Tone::Info))
        );
    }

    fn error_in(path: &str) -> Diagnostic {
        Diagnostic {
            path: path.to_string(),
            line: 1,
            column: 1,
            severity: Severity::Error,
            message: "bad".to_string(),
            context: String::new(),
        }
    }

    fn failed(path: &str) -> ReloadOutcome {
        ReloadOutcome::Failed(ReloadFailure::Compile(CompileFailure {
            owner: "Shader 'reeds'".to_string(),
            failures: Vec::new(),
            diagnostics: vec![error_in(path)],
            hint: "",
        }))
    }

    fn statuses(board: &ReportBoard) -> Vec<FileStatus> {
        let shaders = declared(&entries(), str::to_string);
        shaders[1]
            .files
            .iter()
            .map(|f| file_status(board, &shaders[1], f))
            .collect()
    }

    fn board(name: &str, outcome: ReloadOutcome) -> ReportBoard {
        let reports = ReloadReports::default();
        reports.arm([ReloadSubject::shader("lit"), ReloadSubject::shader("reeds")]);
        reports.publish(&[crate::debug::hot_reload::ReloadReport {
            subject: ReloadSubject::shader(name),
            outcome,
        }]);
        reports.snapshot()
    }

    // A failure marks the file its error is in; its sibling reads that another
    // file failed. An error in no file of the Shader fails both.
    #[test]
    fn a_failure_is_charged_to_the_file_it_names() {
        use FileStatus::*;
        assert_eq!(
            statuses(&board("reeds", failed("/cn-none/sway.hlsl"))),
            [SiblingFailed, Failed]
        );
        assert_eq!(
            statuses(&board("reeds", failed("main_bindless.hlsl"))),
            [Failed, Failed]
        );
    }

    #[test]
    fn warnings_count_per_file_and_a_new_shader_waits_for_the_rebuild() {
        use FileStatus::*;
        let warning = Diagnostic {
            severity: Severity::Warning,
            ..error_in("/cn-none/reeds.hlsl")
        };
        let swapped = ReloadOutcome::Swapped {
            frame_time: std::time::Duration::ZERO,
            warnings: vec![warning.clone()],
        };
        assert_eq!(statuses(&board("reeds", swapped)), [Ok(1), Ok(0)]);
        let later = ReloadOutcome::AppliesOnLoad {
            warnings: vec![warning],
        };
        assert_eq!(
            statuses(&board("reeds", later)),
            [AppliesOnLoad(1), AppliesOnLoad(0)]
        );
        assert_eq!(statuses(&ReportBoard::default()), [Built, Built]);
        let reports = ReloadReports::default();
        reports.arm([ReloadSubject::shader("lit")]);
        assert_eq!(statuses(&reports.snapshot()), [NotLive, NotLive]);
    }
}