nightshade-api 0.47.0

Procedural high level API for the nightshade game engine
Documentation
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
use enum2schema::Schema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// A full generational entity handle as it crosses the agent boundary. Never a
/// bare index: a reused slot reads as a different handle, not the same entity
/// mutated, so a command or read against a stale handle fails rather than
/// hitting the new occupant.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Schema)]
pub struct EntityRef {
    pub id: u32,
    pub generation: u32,
}

/// Correlation id for request/response matching and the optional delta origin
/// tag. Unique per host process lifetime.
pub type CorrelationId = u64;

/// The host-assigned subscription handle. Unique for the host process lifetime,
/// never reused.
pub type SubscriptionId = u64;

/// The collection system's own monotonic batch counter. Not the freecs tick.
pub type Version = u64;

/// Whether the generic component bag may carry a component.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum WritePolicyInfo {
    /// Plain data: the bag may carry it, no side effects on write.
    Free,
    /// A named command owns this component's cascade; reject it in the bag and
    /// point the agent at the command.
    Owned { command: String },
    /// A system computes this component; no command writes it and the bag must
    /// not carry it.
    Derived,
}

/// One registry entry as the agent discovers it. Schema and example are derived
/// from the same type so they cannot drift from the wire format.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ComponentInfo {
    pub name: String,
    pub write_policy: WritePolicyInfo,
    /// Structural shape of the component's value.
    pub schema: Value,
    /// A concrete sample value (the serialized default), a complement to the
    /// schema for the flat cases.
    pub example: Value,
}

/// The command set. Named variants exist where the engine does something beyond
/// writing data (a cascade); the generic setters are the open end the registry
/// absorbs new components through.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AgentCommand {
    Reparent {
        child: EntityRef,
        new_parent: Option<EntityRef>,
    },
    DeleteEntity {
        entity: EntityRef,
    },
    LoadGltf {
        uri: String,
    },
    SelectNode {
        entity: EntityRef,
    },
    /// Make the given camera entity the active viewport camera.
    SetActiveCamera {
        entity: EntityRef,
    },
    /// Browse-and-grab a Polyhaven model by slug, loaded additively.
    LoadPolyhavenModel {
        slug: String,
        resolution: u32,
    },
    /// Spawn a parametric primitive mesh, apply a component bag (e.g.
    /// local_transform, material_ref) to it, and return its handle.
    AddPrimitive {
        kind: super::ShapeKind,
        components: Vec<(String, Value)>,
    },
    /// Spawn a light, apply a component bag, and return its handle.
    AddLight {
        kind: super::LightKind,
        components: Vec<(String, Value)>,
    },
    /// Despawn the whole current scene (everything the user or the agent has
    /// placed), leaving an empty stage with the editor camera, sun, and
    /// environment intact.
    ClearScene,
    SpawnEntity {
        components: Vec<(String, Value)>,
    },
    SetComponents {
        entity: EntityRef,
        components: Vec<(String, Value)>,
    },
    RemoveComponents {
        entity: EntityRef,
        component_types: Vec<String>,
    },
}

/// Which components and optionally which entities a subscription covers.
#[derive(Clone, Debug, Serialize, Deserialize, Schema)]
pub struct SubscriptionFilter {
    pub component_types: Vec<String>,
    pub entities: Option<Vec<EntityRef>>,
}

/// A material to create or edit in the material library. `name` keys the
/// material; every other field is optional and only the set ones are written, so
/// editing leaves untouched fields (including textures) intact.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Schema)]
pub struct MaterialSpec {
    pub name: String,
    /// Linear RGBA albedo.
    pub base_color: Option<[f32; 4]>,
    pub metallic: Option<f32>,
    pub roughness: Option<f32>,
    pub emissive_factor: Option<[f32; 3]>,
    pub emissive_strength: Option<f32>,
    pub unlit: Option<bool>,
    pub double_sided: Option<bool>,
    /// Name of an already-loaded texture for the base-color map. Built-in
    /// prototype textures are always available: "proto_light", "proto_dark",
    /// "proto_green", "proto_orange", "proto_purple", "proto_red" (grid
    /// greybox textures).
    pub base_texture: Option<String>,
    /// How many times the base texture repeats across a surface. Higher tiles the
    /// pattern more finely; set it near a surface's size in units (e.g. 6 for a
    /// 6-unit wall) so a greybox grid reads as roughly one cell per unit. Applied
    /// when a base_texture is set; defaults to a small value.
    pub tiling: Option<f32>,
    /// Name of an already-loaded texture for the normal map.
    pub normal_texture: Option<String>,
    /// Normal map intensity multiplier (1 is full strength).
    pub normal_scale: Option<f32>,
    /// Name of an already-loaded texture for the metallic (B) / roughness (G) map.
    pub metallic_roughness_texture: Option<String>,
    /// Name of an already-loaded texture for the emissive map.
    pub emissive_texture: Option<String>,
    /// Name of an already-loaded texture for the ambient-occlusion (R) map.
    pub occlusion_texture: Option<String>,
    /// Occlusion effect strength (0 none, 1 full).
    pub occlusion_strength: Option<f32>,
    /// Transparency handling: one of "Opaque", "Mask", "Blend".
    pub alpha_mode: Option<String>,
    /// Alpha threshold for the "Mask" alpha mode.
    pub alpha_cutoff: Option<f32>,
}

/// A partial update to the world's render and post-processing settings. Every
/// field is optional; only the set ones change. Read the current values from
/// `get_editor_state` (the `render` block), then send back just what you want to
/// change.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Schema)]
pub struct RenderSettingsPatch {
    pub ambient_light: Option<[f32; 4]>,
    pub bloom_enabled: Option<bool>,
    pub bloom_intensity: Option<f32>,
    pub bloom_threshold: Option<f32>,
    pub bloom_knee: Option<f32>,
    pub bloom_filter_radius: Option<f32>,
    pub ssao_enabled: Option<bool>,
    pub ssao_radius: Option<f32>,
    pub ssao_intensity: Option<f32>,
    pub ssao_bias: Option<f32>,
    pub ssao_sample_count: Option<u32>,
    pub ssgi_enabled: Option<bool>,
    pub ssgi_radius: Option<f32>,
    pub ssgi_intensity: Option<f32>,
    pub ssgi_max_steps: Option<u32>,
    pub ssr_enabled: Option<bool>,
    pub ssr_max_steps: Option<u32>,
    pub ssr_thickness: Option<f32>,
    pub ssr_max_distance: Option<f32>,
    pub ssr_stride: Option<f32>,
    pub ssr_fade_start: Option<f32>,
    pub ssr_fade_end: Option<f32>,
    pub ssr_intensity: Option<f32>,
    pub fog_enabled: Option<bool>,
    pub fog_color: Option<[f32; 3]>,
    pub fog_start: Option<f32>,
    pub fog_end: Option<f32>,
    pub dof_enabled: Option<bool>,
    pub dof_focus_distance: Option<f32>,
    pub dof_focus_range: Option<f32>,
    pub dof_max_blur_radius: Option<f32>,
    /// Depth-of-field quality: 0 low, 1 medium, 2 high.
    pub dof_quality: Option<u32>,
    pub taa_enabled: Option<bool>,
    pub render_scale: Option<f32>,
    pub ibl_blend_factor: Option<f32>,
    pub unlit_mode: Option<bool>,
    pub selection_outline_enabled: Option<bool>,
    pub selection_outline_color: Option<[f32; 4]>,
    pub exposure: Option<f32>,
    pub saturation: Option<f32>,
    pub contrast: Option<f32>,
    pub brightness: Option<f32>,
    pub gamma: Option<f32>,
    pub show_grid: Option<bool>,
    pub show_normals: Option<bool>,
    pub ssao_visualization: Option<bool>,
    pub navmesh_debug: Option<bool>,
    /// PBR debug visualization index (0 is off).
    pub pbr_debug_index: Option<u32>,
}

/// Global sky and environment controls, beyond what the UI buttons expose. Every
/// field is optional; only the set ones are applied.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Schema)]
pub struct Environment {
    /// One of: None, Sky, CloudySky, Space, Nebula, Sunset, DayNight, Hdr.
    pub atmosphere: Option<String>,
    pub show_sky: Option<bool>,
    /// Linear RGBA background used when the atmosphere is None.
    pub clear_color: Option<[f32; 4]>,
    /// Hour of day (0..24) for the DayNight atmosphere.
    pub hour: Option<f32>,
    pub exposure: Option<f32>,
    /// Fetch an .hdr from this URL and use it as the skybox (sets atmosphere Hdr).
    pub hdri_uri: Option<String>,
}

/// Host to worker. Every variant carries a correlation id except the resync
/// request, which is keyed by subscription.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AgentRequest {
    ListComponentTypes {
        correlation_id: CorrelationId,
    },
    Query {
        correlation_id: CorrelationId,
        component_types: Vec<String>,
    },
    GetComponents {
        correlation_id: CorrelationId,
        entity: EntityRef,
        component_types: Vec<String>,
    },
    Command {
        correlation_id: CorrelationId,
        command: AgentCommand,
    },
    Subscribe {
        correlation_id: CorrelationId,
        filter: SubscriptionFilter,
    },
    Unsubscribe {
        correlation_id: CorrelationId,
        subscription_id: SubscriptionId,
    },
    /// Drive the playback of an entity's animation player.
    ControlAnimation {
        correlation_id: CorrelationId,
        entity: EntityRef,
        command: super::AnimationCommand,
    },
    /// Apply a partial update to the world render and post-processing settings.
    SetRenderSettings {
        correlation_id: CorrelationId,
        settings: RenderSettingsPatch,
    },
    /// The flattened scene hierarchy as the editor's tree panel sees it.
    SceneTree {
        correlation_id: CorrelationId,
    },
    /// Perform any editor action a user could trigger from the UI: spawning,
    /// greybox tools, prefabs, play mode, tags, layers, undo, saving.
    EditorAction {
        correlation_id: CorrelationId,
        action: Box<super::EditorAction>,
    },
    /// Read the editor state: render settings, the current selection (with its
    /// name and transform), entity counts, mode, and project. The asset catalog
    /// is separate (see ListAssets) so this stays small.
    GetEditorState {
        correlation_id: CorrelationId,
    },
    /// Set the sky and environment.
    SetEnvironment {
        correlation_id: CorrelationId,
        environment: Environment,
    },
    /// Create or edit a named material in the library.
    SetMaterial {
        correlation_id: CorrelationId,
        material: MaterialSpec,
    },
    /// List every material in the library with its core PBR properties.
    ListMaterials {
        correlation_id: CorrelationId,
    },
    /// The asset-browser index lists (Khronos models, Polyhaven HDRIs and
    /// models). Split out of the editor state because the catalog is large and
    /// rarely needed. `search` filters Polyhaven and Khronos entries by a
    /// case-insensitive substring of the name, slug, category, or tag.
    ListAssets {
        correlation_id: CorrelationId,
        search: Option<String>,
    },
    /// Capture the rendered viewport as a PNG. With `camera`, a frame is
    /// rendered from that camera and the active camera is restored afterward;
    /// without it, the current view is captured. `max_dimension` downscales the
    /// capture (preserving aspect) so the longer side fits.
    Screenshot {
        correlation_id: CorrelationId,
        camera: Option<EntityRef>,
        max_dimension: Option<u32>,
    },
}

/// A read against a stale handle returns this distinct outcome, never the new
/// occupant's data.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum GetResult {
    Live {
        entity: EntityRef,
        components: Vec<(String, Value)>,
    },
    NotLive {
        entity: EntityRef,
    },
}

/// One entity's subscribed slice in a snapshot.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SnapshotEntity {
    pub entity: EntityRef,
    pub components: Vec<(String, Value)>,
}

/// A full point-in-time view of the subscribed slice, stamped with the version
/// the collection system assigned at its slot.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Snapshot {
    pub version: Version,
    pub entities: Vec<SnapshotEntity>,
}

/// A cheap digest of a subscribed slice at a stated version, for the third
/// (drift-catching) layer of desync detection.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Checksum {
    pub version: Version,
    pub digest: u64,
}

/// The five delta kinds. Value-changes come from change detection; structural
/// changes from the freecs structural log. Never coalesced. `origin` is a
/// correlation tag only and never gates whether a delta is applied.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Delta {
    Changed {
        entity: EntityRef,
        component: String,
        value: Value,
        origin: Option<CorrelationId>,
    },
    Added {
        entity: EntityRef,
        component: String,
        value: Value,
        origin: Option<CorrelationId>,
    },
    Removed {
        entity: EntityRef,
        component: String,
        origin: Option<CorrelationId>,
    },
    Spawned {
        entity: EntityRef,
        components: Vec<(String, Value)>,
        origin: Option<CorrelationId>,
    },
    Despawned {
        entity: EntityRef,
        origin: Option<CorrelationId>,
    },
}

/// One frame's emission. Contiguous per subscriber (`next.base == prev.target`),
/// applied atomically. Ordered creates, then values, then deletes. Every frame
/// emits exactly one batch while tracking is on, empty frames included.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeltaBatch {
    pub base_version: Version,
    pub target_version: Version,
    pub deltas: Vec<Delta>,
    pub checksum: Option<Checksum>,
}

/// Worker to host.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AgentResponse {
    ComponentTypes {
        correlation_id: CorrelationId,
        components: Vec<ComponentInfo>,
    },
    QueryResult {
        correlation_id: CorrelationId,
        entities: Vec<EntityRef>,
    },
    GetResult {
        correlation_id: CorrelationId,
        result: GetResult,
    },
    /// A command landed. Independent of the delta stream. For long-running
    /// commands this fires at the version the last effect lands.
    CommandApplied {
        correlation_id: CorrelationId,
        version: Version,
    },
    /// An additive glTF load finished, reporting the spawned root handles so the
    /// agent can position the model by its root.
    Loaded {
        correlation_id: CorrelationId,
        version: Version,
        roots: Vec<EntityRef>,
    },
    CommandFailed {
        correlation_id: CorrelationId,
        error: String,
    },
    CommandProgress {
        correlation_id: CorrelationId,
        stage: String,
    },
    Subscribed {
        correlation_id: CorrelationId,
        subscription_id: SubscriptionId,
        snapshot: Snapshot,
    },
    Unsubscribed {
        correlation_id: CorrelationId,
        subscription_id: SubscriptionId,
    },
    /// The current editor state (render settings, selection, counts, project).
    EditorState {
        correlation_id: CorrelationId,
        state: Value,
    },
    /// The material library.
    Materials {
        correlation_id: CorrelationId,
        materials: Value,
    },
    /// The asset-browser index lists.
    Assets {
        correlation_id: CorrelationId,
        assets: Value,
    },
    /// A captured viewport frame as a base64 PNG.
    Screenshot {
        correlation_id: CorrelationId,
        width: u32,
        height: u32,
        png_base64: String,
    },
    /// One batch per tracking-on frame, broadcast to the host fan-out.
    Batch { batch: DeltaBatch },
    /// The flattened scene hierarchy, depth-first.
    SceneTree {
        correlation_id: CorrelationId,
        rows: Value,
    },
    /// Command, event, and error log lines from the running scene, streamed to
    /// the host fan-out as they happen (script errors, collisions, despawns,
    /// applied commands, toasts). Drained by the host with `poll_log`.
    Log { entries: Value },
}