avian_fdm 0.1.0

6-DoF Flight Dynamics Model for Bevy + Avian 0.6
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
//! Debug gizmo systems for FDM overlays.
//!
//! Each `debug_render_*` function is a Bevy system added by [`AircraftFdmDebugPlugin`].
//! They run in `PostUpdate`, after transform propagation, and are gated by the
//! `FdmGizmos` config group being enabled.
//!
//! [`AircraftFdmDebugPlugin`]: super::AircraftFdmDebugPlugin

use crate::_bevy::*;
use avian3d::prelude::{
    ComputedCenterOfMass, ComputedMass, ConstantForce, ConstantTorque, Rotation,
};

use super::configuration::{FdmDebugRender, FdmGizmos};
use crate::components::{
    AeroZone, AircraftGeometry, Failure, FlightState, GizmoContours, GizmoShape, ZoneForce,
};

//
// Centre of gravity
//

/// Draw a sphere at the aircraft's centre of gravity (CG).
///
/// Uses Avian's [`ComputedCenterOfMass`] (local offset from entity origin) and
/// [`Rotation`] (physics rotation) to compute the world-space CG position.
pub(super) fn debug_render_cg(
    mut gizmos: Gizmos<FdmGizmos>,
    store: Res<GizmoConfigStore>,
    query: Query<(&GlobalTransform, &Rotation, &ComputedCenterOfMass), With<AircraftGeometry>>,
) {
    let config = store.config::<FdmGizmos>().1;
    let Some(color) = config.cg_color else { return };

    for (gt, rot, com) in &query {
        let cg = gt.translation() + rot.0 * com.0;
        gizmos.sphere(
            Isometry3d::from_translation(cg),
            config.marker_radius,
            color,
        );
    }
}

//
// Aerodynamic centres
//

/// Draw a sphere at each zone's aerodynamic centre (AC).
///
/// The AC is stored as [`AeroZone::ac_offset`] in the zone's local frame.
/// `GlobalTransform::transform_point` converts it to world space.
///
/// Rendered as a 3-axis cross (±X/Y/Z arms) so it remains clearly visible
/// even when the AC coincides with the zone entity origin, where a sphere
/// wireframe would blend into the zone outlines.
pub(super) fn debug_render_ac(
    mut gizmos: Gizmos<FdmGizmos>,
    store: Res<GizmoConfigStore>,
    query: Query<(&GlobalTransform, &AeroZone)>,
) {
    let config = store.config::<FdmGizmos>().1;
    let Some(color) = config.ac_color else { return };

    let arm = config.marker_radius;
    for (gt, zone) in &query {
        let ac = gt.transform_point(zone.ac_offset);
        gizmos.line(ac - Vec3::X * arm, ac + Vec3::X * arm, color);
        gizmos.line(ac - Vec3::Y * arm, ac + Vec3::Y * arm, color);
        gizmos.line(ac - Vec3::Z * arm, ac + Vec3::Z * arm, color);
    }
}

//
// Force arrows
//

/// Draw a combined aero force arrow per zone, originating from the zone AC.
///
/// Uses [`AeroZone::ac_offset`] and the zone's [`GlobalTransform`] to find the
/// world-space AC. Running in `PostUpdate` after transform propagation means
/// there is no one-frame lag.
pub(super) fn debug_render_zone_forces(
    mut gizmos: Gizmos<FdmGizmos>,
    store: Res<GizmoConfigStore>,
    query: Query<(&ZoneForce, &GlobalTransform, &AeroZone)>,
) {
    let config = store.config::<FdmGizmos>().1;
    let Some(color) = config.lift_color else {
        return;
    };

    for (zf, zone_gt, zone) in &query {
        if zf.force.length_squared() < 100.0 {
            continue;
        }
        let start = zone_gt.transform_point(zone.ac_offset);
        gizmos.arrow(start, start + zf.force * config.force_scale, color);
    }
}

/// Draw thrust arrows on engine zones.
pub(super) fn debug_render_thrust(
    mut gizmos: Gizmos<FdmGizmos>,
    store: Res<GizmoConfigStore>,
    query: Query<(&ZoneForce, &GlobalTransform), With<crate::components::EngineZone>>,
) {
    let config = store.config::<FdmGizmos>().1;
    let Some(color) = config.thrust_color else {
        return;
    };

    for (zf, zone_gt) in &query {
        if zf.force.length_squared() < 1.0 {
            continue;
        }
        let start = zone_gt.translation();
        gizmos.arrow(start, start + zf.force * config.force_scale, color);
    }
}

/// Draw the total aero+thrust force, weight, and net-force arrows from the CG.
pub(super) fn debug_render_resultant(
    mut gizmos: Gizmos<FdmGizmos>,
    store: Res<GizmoConfigStore>,
    query: Query<
        (
            &Transform,
            &Rotation,
            &ConstantForce,
            &ComputedMass,
            &ComputedCenterOfMass,
        ),
        With<AircraftGeometry>,
    >,
) {
    let config = store.config::<FdmGizmos>().1;

    for (tf, rot, cf, mass, com) in &query {
        let cg = tf.translation + rot.0 * com.0;
        let scale = config.force_scale;

        if let Some(color) = config.total_force_color {
            gizmos.arrow(cg, cg + cf.0 * scale, color);
        }

        let weight = Vec3::new(0.0, -mass.value() * 9.806_65, 0.0);

        if let Some(color) = config.weight_color {
            gizmos.arrow(cg, cg + weight * scale, color);
        }

        if let Some(net_color) = config.resultant_color {
            let net = cf.0 + weight;
            if net.length_squared() > 1.0 {
                gizmos.arrow(cg, cg + net * scale, net_color);
            }
        }
    }
}

//
// Moment arcs
//

/// Draw pitch, roll, and yaw moment arrows centered on the CG.
///
/// Each arrow points along the corresponding body axis (X = roll, Y = pitch,
/// Z = yaw in Bevy convention) and is scaled by moment magnitude. Colors are
/// taken from [`FdmGizmos::roll_moment_color`], `pitch_moment_color`, and
/// `yaw_moment_color`.
pub(super) fn debug_render_moments(
    mut gizmos: Gizmos<FdmGizmos>,
    store: Res<GizmoConfigStore>,
    query: Query<
        (
            &Transform,
            &Rotation,
            &ComputedCenterOfMass,
            &ConstantTorque,
        ),
        With<AircraftGeometry>,
    >,
) {
    let config = store.config::<FdmGizmos>().1;

    for (tf, rot, com, torque) in &query {
        let cg = tf.translation + rot.0 * com.0;
        let scale = config.force_scale;

        // Decompose torque into body-frame components and draw each axis.
        // Torque is already in world frame; project onto body axes for display.
        let t = torque.0;
        if t.length_squared() < 1.0 {
            continue;
        }

        // Body axes in world space.
        let body_x = rot.0 * Vec3::X; // roll axis
        let body_y = rot.0 * Vec3::Y; // pitch axis
        let body_z = rot.0 * Vec3::Z; // yaw axis

        let t_roll = t.dot(body_x);
        let t_pitch = t.dot(body_y);
        let t_yaw = t.dot(body_z);

        if let Some(color) = config.roll_moment_color {
            if t_roll.abs() > 0.1 {
                gizmos.arrow(cg, cg + body_x * t_roll * scale, color);
            }
        }
        if let Some(color) = config.pitch_moment_color {
            if t_pitch.abs() > 0.1 {
                gizmos.arrow(cg, cg + body_y * t_pitch * scale, color);
            }
        }
        if let Some(color) = config.yaw_moment_color {
            if t_yaw.abs() > 0.1 {
                gizmos.arrow(cg, cg + body_z * t_yaw * scale, color);
            }
        }
    }
}

//
// Zone health wireframes
//

/// Draw zone outline wireframes using [`GizmoShape`] and [`GizmoContours`].
///
/// Color is chosen by zone type unless overridden by [`FdmDebugRender`]:
/// - Green: control surface (non-zero `control_role`)
/// - Cyan: lifting surface (non-zero CL at a sample alpha)
/// - Orange: non-aero zone (e.g. engine)
/// - Grey: structural / drag-only
///
/// Zones with a [`Failure`] component are tinted toward grey as damage
/// accumulates. A fully failed zone (`remaining = 0.0`) is drawn grey
/// regardless of its type.
///
/// The global [`FdmGizmos::zone_color`] acts as an on/off gate; set to `None`
/// to disable. Per-entity [`FdmDebugRender::zone_color`] overrides the color
/// (damage tint still applies on top).
#[allow(clippy::unnecessary_cast)]
#[allow(clippy::type_complexity)]
pub(super) fn debug_render_zones(
    mut gizmos: Gizmos<FdmGizmos>,
    store: Res<GizmoConfigStore>,
    query: Query<
        (
            &GlobalTransform,
            Option<&AeroZone>,
            Option<&GizmoContours>,
            Option<&GizmoShape>,
            Option<&FdmDebugRender>,
            Option<&Failure>,
        ),
        Or<(With<GizmoShape>, With<GizmoContours>)>,
    >,
) {
    let config = store.config::<FdmGizmos>().1;
    if config.zone_color.is_none() {
        return;
    }

    for (zone_gt, aero, contours, shape, dbg_render, failure) in &query {
        let base_color = dbg_render
            .and_then(|d| d.zone_color)
            .unwrap_or_else(|| zone_type_color(aero));
        let remaining = failure.map_or(1.0, |f| f.remaining as f32);
        let color = damage_tint(base_color, remaining);

        let wt = zone_gt.compute_transform();
        let zone_to_world = |local: Vec3| wt.translation + wt.rotation * local;
        let iso_at = |extra_rot: Quat| Isometry3d::new(wt.translation, wt.rotation * extra_rot);

        if let Some(contour_data) = contours {
            for line in &contour_data.lines {
                if line.len() < 2 {
                    continue;
                }
                let pts: Vec<Vec3> = line.iter().map(|p| zone_to_world(*p)).collect();
                gizmos.linestrip(pts, color);
            }
            if shape.is_none() {
                continue;
            }
        }

        if let Some(gs) = shape {
            draw_zone_shape(&mut gizmos, gs, &iso_at, &zone_to_world, color);
        }
    }
}

fn zone_type_color(aero: Option<&AeroZone>) -> Color {
    if aero.is_none() {
        Color::srgba(0.95, 0.65, 0.15, 0.9) // orange - engine / non-aero
    } else if aero.is_some_and(|a| a.control_role.is_some()) {
        Color::srgba(0.3, 1.0, 0.5, 0.7) // green - control surface
    } else if aero.is_some_and(|a| a.cl.evaluate(0.1, 2e6).abs() > 0.01) {
        Color::srgba(0.4, 0.85, 1.0, 0.7) // cyan - lifting surface
    } else {
        Color::srgba(0.6, 0.6, 0.6, 0.6) // grey - structural / drag-only
    }
}

/// Blend `color` toward grey proportional to damage (`remaining` 0 -> 1).
///
/// At `remaining = 1.0` the color is unchanged. At `remaining = 0.0` the
/// result is fully grey (`srgba(0.55, 0.55, 0.55, 0.6)`).
fn damage_tint(color: Color, remaining: f32) -> Color {
    let grey = Color::srgba(0.55, 0.55, 0.55, 0.6);
    color.mix(&grey, 1.0 - remaining)
}

fn draw_zone_shape(
    gizmos: &mut Gizmos<FdmGizmos>,
    shape: &GizmoShape,
    iso_at: &impl Fn(Quat) -> Isometry3d,
    zone_to_world: &impl Fn(Vec3) -> Vec3,
    color: Color,
) {
    match shape {
        GizmoShape::Box { x, y, z } => {
            gizmos.primitive_3d(&Cuboid::new(*x, *y, *z), iso_at(Quat::IDENTITY), color);
        }
        GizmoShape::Cylinder {
            radius,
            length,
            axis,
        } => {
            gizmos
                .primitive_3d(
                    &Cylinder::new(*radius, *length),
                    iso_at(Quat::from_rotation_arc(Vec3::Y, *axis)),
                    color,
                )
                .resolution(32);
        }
        GizmoShape::Cone { radius, length } => {
            gizmos.primitive_3d(
                &Cone {
                    radius: *radius,
                    height: *length,
                },
                iso_at(Quat::from_rotation_z(-std::f32::consts::FRAC_PI_2)),
                color,
            );
        }
        GizmoShape::Sphere { radius } => {
            gizmos
                .primitive_3d(
                    &bevy_math::primitives::Sphere::new(*radius),
                    iso_at(Quat::IDENTITY),
                    color,
                )
                .resolution(32);
        }
        GizmoShape::Quad { corners } => {
            let pts: Vec<Vec3> = corners
                .iter()
                .chain(std::iter::once(&corners[0]))
                .map(|c| zone_to_world(*c))
                .collect();
            gizmos.linestrip(pts, color);
        }
        GizmoShape::Strut { start, end } => {
            gizmos.line(zone_to_world(*start), zone_to_world(*end), color);
        }
    }
}

//
// Angle-of-attack / wind indicator
//

/// Draw the relative-wind arrow and angle-of-attack / sideslip indicators.
///
/// Draws from the CG:
/// - A wind arrow in the freestream direction (opposite of velocity), length
///   proportional to airspeed, colored by [`FdmGizmos::wind_color`].
/// - A short body-axis forward arrow showing where the nose points.
/// - A label line showing the AoA angle between the two (no text; the angle
///   between nose-arrow and wind-arrow is the visual AoA).
#[allow(clippy::unnecessary_cast)]
pub(super) fn debug_render_wind(
    mut gizmos: Gizmos<FdmGizmos>,
    store: Res<GizmoConfigStore>,
    query: Query<
        (&Transform, &Rotation, &ComputedCenterOfMass, &FlightState),
        With<AircraftGeometry>,
    >,
) {
    let config = store.config::<FdmGizmos>().1;
    let Some(color) = config.wind_color else {
        return;
    };

    for (tf, rot, com, fs) in &query {
        if fs.airspeed_ms < 1.0 {
            continue;
        }

        let cg = tf.translation + rot.0 * com.0;

        // Body-frame forward (nose direction) in world space.
        let nose_dir = rot.0 * Vec3::X;

        // Freestream direction: the wind comes from opposite the velocity vector.
        // Reconstruct velocity direction from alpha and beta in body frame, then
        // rotate to world. Body-frame velocity components from AoA / sideslip:
        // u = cos(alpha)*cos(beta), v = sin(beta), w = sin(alpha)*cos(beta)
        let (sa, ca) = (fs.alpha_rad.sin() as f32, fs.alpha_rad.cos() as f32);
        let (sb, cb) = (fs.beta_rad.sin() as f32, fs.beta_rad.cos() as f32);
        let vel_body_dir = Vec3::new(ca * cb, sb, sa * cb); // unit vector
        let vel_world_dir = rot.0 * vel_body_dir;

        // Arrow scale: use a fixed 2 m length so it doesn't dwarf force arrows.
        let arm = 2.0_f32;

        // Wind arrow: from CG in the freestream direction (into-wind = -vel).
        gizmos.arrow(cg, cg - vel_world_dir * arm, color);

        // Nose arrow: shows aircraft heading for quick AoA reading.
        gizmos.arrow(cg, cg + nose_dir * arm, color.with_alpha(0.5));
    }
}