diff --git a/gradle.properties b/gradle.properties
index 23e0989..0436e1f 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -12,7 +12,7 @@ mapping_version=2023.09.03-1.20.1
mod_id=improved_aerodynamics
mod_name=VS: Improved Aerodynamics
mod_license=MIT
-mod_version=0.4.5
+mod_version=0.4.8
azurelib_version=3.2.7
mod_group_id=dev.lumareth.improvedaerodynamics
mod_authors=Lumareth
diff --git a/logs/debug.log b/logs/debug.log
new file mode 100644
index 0000000..e69de29
diff --git a/logs/latest.log b/logs/latest.log
new file mode 100644
index 0000000..e69de29
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/Config.java b/src/main/java/dev/lumareth/improvedAerodynamics/Config.java
index 6b72d49..bf7a1c8 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/Config.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/Config.java
@@ -123,6 +123,12 @@ public final class Config {
.comment("Improved flight model: multiplier for the extra lift the vortices make at high angles of attack")
.defineInRange("vortexLiftStrength", 1.0D, 0.0D, 3.0D);
+ public static final ForgeConfigSpec.BooleanValue SWEEP_EFFECTS = BUILDER
+ .comment("Improved flight model: swept wings behave like swept wings. Sweep lowers the lift slope, moves the drag rise",
+ "near the speed of sound to higher speeds, and decides where the stall starts: at the tips of an aft swept wing,",
+ "at the root of a forward swept one, which keeps its ailerons working when the rest of the wing lets go")
+ .define("sweepEffects", true);
+
public static final ForgeConfigSpec.DoubleValue FBW_AUTHORITY = BUILDER
.comment("Flight computer (auto trim): largest total pitch input, as a fraction of full deflection, the computer may use.",
"A craft with strongly relaxed stability needs close to 1")
@@ -255,7 +261,8 @@ public final class Config {
.defineInRange("stalledPitchFactor", 0.3, 0.0, 1.0);
public static final ForgeConfigSpec.DoubleValue CURSOR_AIM_MIN_SPEED = BUILDER.comment("Below this speed in blocks per second the pilot does not fly the craft: the cursor moves the elevators and",
- "rudder directly instead, so they follow it while taxiing and rotating for takeoff")
+ "rudder directly instead, so they follow it while taxiing and rotating for takeoff. With the improved flight",
+ "model that also holds above it until the wings can lift the craft's weight")
.defineInRange("minSpeed", 15.0, 0.0, 200.0);
static {
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/ConfigCommands.java b/src/main/java/dev/lumareth/improvedAerodynamics/ConfigCommands.java
index 87552f9..a26985b 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/ConfigCommands.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/ConfigCommands.java
@@ -50,6 +50,7 @@ public final class ConfigCommands {
new Option<>("transonic_peak_drag", Config.TRANSONIC_PEAK_DRAG, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("supersonic_drag", Config.SUPERSONIC_DRAG, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("vortex_lift", Config.VORTEX_LIFT, BoolArgumentType.bool(), Boolean.class),
+ new Option<>("sweep_effects", Config.SWEEP_EFFECTS, BoolArgumentType.bool(), Boolean.class),
new Option<>("vortex_stall_bonus", Config.VORTEX_STALL_BONUS, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("vortex_lift_strength", Config.VORTEX_LIFT_STRENGTH, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("flight_computer_authority", Config.FBW_AUTHORITY, DoubleArgumentType.doubleArg(), Double.class),
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/flight/AeroState.java b/src/main/java/dev/lumareth/improvedAerodynamics/flight/AeroState.java
index 07e28cf..310c700 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/flight/AeroState.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/flight/AeroState.java
@@ -84,6 +84,8 @@ public final class AeroState implements PhysicsBridge.Publishable {
double controlRate = Double.NaN;
// Cursor aim is rolling the craft over to reach a cursor far below the nose
boolean reversing;
+ // Cursor aim moves the surfaces straight from the cursor because the craft is not flying yet (or any more)
+ boolean directMode = true;
// Cursor aim's integral of the turn rate error (angular acceleration, ship axes), so it reaches the rate it asks for
final Vector3d rateIntegral = new Vector3d();
// What cursor aim did last, for /aero cursor_debug: rates in rad/s, lift as load factor (g)
@@ -99,6 +101,8 @@ public final class AeroState implements PhysicsBridge.Publishable {
// responses. Until then Warium's keys: W (Pitch+) is usually nose down, D (Yaw+) nose right
double pitchSign = -1.0;
double yawSign = 1.0;
+ // The same for roll, +1 when Roll+ rolls the craft right (Warium's C key)
+ double rollSign = 1.0;
final AutoTrim.Targets trimTargets = new AutoTrim.Targets();
volatile double savedTrim;
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/flight/AeroSurface.java b/src/main/java/dev/lumareth/improvedAerodynamics/flight/AeroSurface.java
index 2372454..7cb19bf 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/flight/AeroSurface.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/flight/AeroSurface.java
@@ -7,6 +7,8 @@ package dev.lumareth.improvedAerodynamics.flight;
* @param key BlockPos.asLong of the block
* @param x block center
* @param facingX Warium's "facing" of the block, the chord direction of the surface
+ * @param facingKnown whether the block says its direction; if not, the facing is a stand in until WingShape gives it
+ * the direction the craft's other surfaces agree on
* @param pressure Warium's air pressure factor at the block's altitude
* @param fluidFactor Warium's multiplier for blocks under water (1 in air)
* @param speedMultiplier Warium's aerodynamicSpeedMultiplier game rule / 100, at least 1
@@ -15,16 +17,25 @@ package dev.lumareth.improvedAerodynamics.flight;
* @param aspectRatio span squared over area of the wing the block belongs to, 0 if not known yet
* @param wingGroup whether the wing the block belongs to contains WING blocks, not only control surfaces or stabilizers
* @param flap whether the block was made a flap with shift-right-click, it then also follows its node's flap setting
+ * @param sweep sweep of the half wing the block belongs to, radians: positive when its tip lies further towards
+ * +facing than its root. Whether that is forward or aft sweep depends on which way the air comes
+ * @param spanFraction where along its half wing the block sits, 0 at the root and 1 at the tip
*/
-public record AeroSurface(long key, SurfaceType type, boolean slab, double x, double y, double z, int facingX, int facingZ,
- double pressure, double fluidFactor, double speedMultiplier,
+public record AeroSurface(long key, SurfaceType type, double x, double y, double z, int facingX, int facingZ,
+ boolean facingKnown, double pressure, double fluidFactor, double speedMultiplier,
long node, ControlAxis axis1, double multiplier1, ControlAxis axis2, double multiplier2,
- double brakeInput, double aspectRatio, boolean wingGroup, boolean flap) {
+ double brakeInput, double aspectRatio, boolean wingGroup, boolean flap, double sweep, double spanFraction) {
public static final long NO_NODE = Long.MIN_VALUE;
- AeroSurface withWingShape(double aspectRatio, boolean wingGroup) {
- return new AeroSurface(key, type, slab, x, y, z, facingX, facingZ, pressure, fluidFactor, speedMultiplier,
- node, axis1, multiplier1, axis2, multiplier2, brakeInput, aspectRatio, wingGroup, flap);
+ AeroSurface withWingShape(double aspectRatio, boolean wingGroup, double sweep, double spanFraction) {
+ return new AeroSurface(key, type, x, y, z, facingX, facingZ, facingKnown, pressure, fluidFactor, speedMultiplier,
+ node, axis1, multiplier1, axis2, multiplier2, brakeInput, aspectRatio, wingGroup, flap, sweep, spanFraction);
+ }
+
+ /** The same surface facing along the x axis (true) or the z axis, the direction now counting as known. */
+ AeroSurface withFacingAxis(boolean alongX) {
+ return new AeroSurface(key, type, x, y, z, alongX ? 1 : 0, alongX ? 0 : 1, true, pressure, fluidFactor, speedMultiplier,
+ node, axis1, multiplier1, axis2, multiplier2, brakeInput, aspectRatio, wingGroup, flap, sweep, spanFraction);
}
/** Warium's "Direction.getClockWise(Axis.Y)" of the facing, the span direction of a horizontal surface. */
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/flight/CursorAimDebug.java b/src/main/java/dev/lumareth/improvedAerodynamics/flight/CursorAimDebug.java
index 73c4309..83d83fb 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/flight/CursorAimDebug.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/flight/CursorAimDebug.java
@@ -67,8 +67,12 @@ public final class CursorAimDebug {
}
AimBasis basis = AimBasis.of(vehicle.level(), vehicle.blockPosition());
AeroState.NodeState state = basis != null ? AeroState.nodeState(basis.nodePos().asLong()) : null;
- if (state == null || !state.debugActive) {
- return "Cursor aim: not flying (off, too slow or no physics)";
+ if (state == null) {
+ return "Cursor aim: no physics for this node (not moving)";
+ }
+ if (!state.debugActive) {
+ return state.directMode ? String.format(Locale.ROOT, "Cursor aim: direct control, wings lift %4.1fg of the 1.1g it waits for",
+ state.debugLoadFactor) : "Cursor aim: off";
}
return String.format(Locale.ROOT, "pitch %5.1f/%5.1f deg/s plan %5.1f lift %4.1fg stall %4.2f",
Math.toDegrees(state.debugActualPitch), Math.toDegrees(state.debugCommandedPitch),
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/flight/CursorPilot.java b/src/main/java/dev/lumareth/improvedAerodynamics/flight/CursorPilot.java
index e814ce7..4dcddfe 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/flight/CursorPilot.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/flight/CursorPilot.java
@@ -19,7 +19,8 @@ import org.joml.Vector3d;
* by pushing: the pilot rolls until the cursor is above the canopy and pulls, a reversal or split-S. It keeps at it
* until the reticle is close to the cursor, or the cursor is moved above the nose again. A cursor only a little below
* the nose is reached with the elevators alone, gently, so the craft can still be flown down to a landing;
- *
below {@code minSpeed} there is too little airflow to fly by: the cursor moves elevators and rudder directly;
+ * until the wings can carry the craft (and always below {@code minSpeed}) there is nothing to fly by: the cursor
+ * moves elevators and rudder directly, for taxiing and rotating on the takeoff run;
* close to the reticle it levels the wings and puts the reticle on the cursor with rudder and elevator, so
* aiming does not rock the wings.
*
@@ -49,6 +50,13 @@ final class CursorPilot {
private static final double MAX_ERROR_FOR_INTEGRAL = 0.5;
// Bank the pilot rolls to at full sideways deflection even when the wings cannot hold the turn level
private static final double MIN_BANK = Math.toRadians(20.0);
+ // Load factor the wings must be able to make before the rate loop takes over from flying the surfaces directly, and
+ // below which it hands back, apart so it does not switch back and forth
+ private static final double FLYING_LOAD_ENTER = 1.1;
+ private static final double FLYING_LOAD_EXIT = 0.9;
+ // Aileron input per radian of bank error, and taken off per rad/s of roll rate, when flying the surfaces directly
+ private static final double DIRECT_BANK_GAIN = 1.5;
+ private static final double DIRECT_ROLL_DAMPING = 0.5;
// Smallest pull allowed, as a share of the turn rate, when gravity takes most of the lift
private static final double MIN_PULL_SHARE = 0.2;
// Time constant of easing the pull back in and out of a stall
@@ -110,20 +118,37 @@ final class CursorPilot {
double levelUp = cu * Math.cos(bank) - cr * Math.sin(bank);
double levelVertical = Math.atan2(levelUp, Math.hypot(cf, levelRight));
- if (speed < Config.CURSOR_AIM_MIN_SPEED.get()) {
- // Too slow for the rate loop: the cursor moves the surfaces directly, rudder towards it (which also steers on
- // the ground) and elevator up or down, so the controls follow the cursor while taxiing and rotating
+ // Flying or not: the rate loop only makes sense once the wings can carry the craft. Below that (taxiing, the
+ // takeoff run, a stall) it would plan with almost no lift, ask for almost no pitch rate, and the angle of attack
+ // limiter would forbid rotating a nose high craft on its gear, so the elevators would hardly move. So the cursor
+ // moves the surfaces directly until the wings can lift a bit more than the craft's weight, and again once they
+ // fall a bit short of it. Without a stall model only the minimum speed decides
+ double liftMargin = Config.CURSOR_AIM_LIFT_MARGIN.get();
+ boolean slow = speed < Config.CURSOR_AIM_MIN_SPEED.get();
+ state.debugLoadFactor = liftMargin * liftAcceleration / GRAVITY;
+ if (slow || !Double.isFinite(liftAcceleration)) {
+ state.directMode = slow;
+ } else {
+ double loadFactor = liftMargin * liftAcceleration / GRAVITY;
+ state.directMode = state.directMode ? loadFactor < FLYING_LOAD_ENTER : loadFactor < FLYING_LOAD_EXIT;
+ }
+ if (state.directMode) {
+ // The cursor moves the surfaces directly, rudder towards it (which also steers on the ground) and elevator up
+ // or down, so the controls follow the cursor while taxiing and rotating. The ailerons bank towards a cursor to
+ // the side and otherwise hold the wings level, damped by the roll rate so they do not rock the craft
state.reversing = false;
state.rateIntegral.zero();
state.debugActive = false;
double pitch = clamp(state.pitchSign * saturate(vertical / fullAngle) - state.trimOutput, -1.0, 1.0);
double yaw = state.yawSign * saturate(sideways / fullAngle);
- return withInputs(node, pitch, yaw, 0.0);
+ double bankCommand = maxBank * saturate(sideways / fullAngle);
+ double rollRate = w[0] * f[0] + w[1] * f[1] + w[2] * f[2];
+ double roll = state.rollSign * clamp(DIRECT_BANK_GAIN * (bankCommand - bank) - DIRECT_ROLL_DAMPING * rollRate, -1.0, 1.0);
+ return withInputs(node, pitch, yaw, roll);
}
// What this craft can do right now. Lift: pitch rate at the highest usable lift (a = L / m, rate = a / v), and
// the bank whose level turn needs that load factor. Without a stall model only the control limit applies
- double liftMargin = Config.CURSOR_AIM_LIFT_MARGIN.get();
double usableLift = liftMargin * liftAcceleration;
double liftRate = usableLift > 0.0 ? usableLift / speed : Double.POSITIVE_INFINITY;
double controlRate = state.controlRate > 0.0 ? state.controlRate : Double.POSITIVE_INFINITY;
@@ -235,7 +260,6 @@ final class CursorPilot {
state.debugCommandedPitch = pitchRate;
state.debugActualPitch = actualPitch;
state.debugMaxPull = maxPull;
- state.debugLoadFactor = liftAcceleration / GRAVITY;
state.debugStallRatio = stallRatio;
state.debugActive = true;
@@ -261,6 +285,7 @@ final class CursorPilot {
private static void learnSigns(AeroState.NodeState state, double[] f, double[] r, double[] u) {
state.pitchSign = sign(state.pitchResponse, r, 1.0, state.pitchSign);
state.yawSign = sign(state.yawResponse, u, -1.0, state.yawSign);
+ state.rollSign = sign(state.rollResponse, f, 1.0, state.rollSign);
}
private static double sign(Vector3d response, double[] axis, double direction, double previous) {
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/flight/ImprovedAero.java b/src/main/java/dev/lumareth/improvedAerodynamics/flight/ImprovedAero.java
index 7d3bce8..d9f0e35 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/flight/ImprovedAero.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/flight/ImprovedAero.java
@@ -38,6 +38,12 @@ final class ImprovedAero {
private static final double REFERENCE_SPEED = 40.0;
// Oswald efficiency of a finite wing
private static final double EFFICIENCY = 0.85;
+ // Airfoil efficiency in the DATCOM lift slope formula
+ private static final double AIRFOIL_EFFICIENCY = 0.95;
+ // How far sweep moves the stall angle between root and tip: at 45 degrees of sweep the tip of an aft swept wing
+ // stalls about 18% earlier than the middle of the half wing and the root as much later, the other way round when
+ // swept forward
+ private static final double SWEEP_STALL_SPREAD = 0.25;
private ImprovedAero() {
}
@@ -52,12 +58,13 @@ final class ImprovedAero {
/** The config values the model reads, taken once per evaluation. */
record Tuning(double liftScale, double stallAngleScale, double thinDrag,
boolean transonic, double speedOfSound, double transonicPeakDrag, double supersonicDrag,
- boolean vortex, double vortexStallBonus, double vortexLiftStrength) {
+ boolean vortex, double vortexStallBonus, double vortexLiftStrength, boolean sweep) {
static Tuning read() {
return new Tuning(Config.LIFT_SCALE.get(), Config.STALL_ANGLE_SCALE.get(), Config.STABILIZER_DRAG.get(),
Config.TRANSONIC_DRAG.get(), Config.SPEED_OF_SOUND.get(), Config.TRANSONIC_PEAK_DRAG.get(),
Config.SUPERSONIC_DRAG.get(),
- Config.VORTEX_LIFT.get(), Config.VORTEX_STALL_BONUS.get(), Config.VORTEX_LIFT_STRENGTH.get());
+ Config.VORTEX_LIFT.get(), Config.VORTEX_STALL_BONUS.get(), Config.VORTEX_LIFT_STRENGTH.get(),
+ Config.SWEEP_EFFECTS.get());
}
}
@@ -93,8 +100,12 @@ final class ImprovedAero {
// Warium's own per-block drag, lower for thin surfaces since they stabilize with lift, not drag. Shock waves
// multiply it near the speed of sound; this is the only zero-lift drag a craft has, induced and stall drag
// below are not affected
+ // Of the airflow only the part across the leading edge counts for the shock waves, so a swept wing's drag rise
+ // comes at a higher speed
+ double aftSweep = aftSweep(s, vx * s.facingX() + vz * s.facingZ(), tuning);
double shockDrag = tuning.transonic()
- ? TransonicDrag.multiplier(localSpeed / tuning.speedOfSound(), tuning.transonicPeakDrag(), tuning.supersonicDrag())
+ ? TransonicDrag.multiplier(localSpeed * Math.cos(aftSweep) / tuning.speedOfSound(), tuning.transonicPeakDrag(),
+ tuning.supersonicDrag())
: 1.0;
double parasitic = -localSpeed * (s.type().thin ? tuning.thinDrag() : s.type().parasiticDrag) * shockDrag * p / m;
out.addForce(r, vx * parasitic, vy * parasitic, vz * parasitic);
@@ -130,7 +141,7 @@ final class ImprovedAero {
// Low aspect ratio wings keep their flow attached longer thanks to leading-edge vortices. Control surfaces
// in a wing's group stall with the wing instead of before it
double vortexFactor = vortexFactor(s, tuning);
- double critical = criticalAngle(s, tuning, vortexFactor);
+ double critical = criticalAngle(s, tuning, vortexFactor, aftSweep);
double absAlpha = Math.abs(alpha);
if (alpha >= 0.0) {
critical += FLAP_STALL_GAIN * flapShift;
@@ -147,7 +158,7 @@ final class ImprovedAero {
// Finite wing theory: lift slope and induced drag follow from the wing's aspect ratio
double aspectRatio = s.aspectRatio();
double inducedDrag = aspectRatio > 0.0 ? 1.0 / (Math.PI * EFFICIENCY * aspectRatio) : INDUCED_DRAG;
- double attachedLift = liftSlope(s) * alpha;
+ double attachedLift = liftSlope(s, aftSweep) * alpha;
if (s.type() == SurfaceType.WING) {
attachedLift += VortexLift.liftCoefficient(alpha, vortexFactor, tuning.vortexLiftStrength());
}
@@ -181,10 +192,11 @@ final class ImprovedAero {
double vz = v[2] + w[0] * r[1] - w[1] * r[0];
double u = vx * s.facingX() + vz * s.facingZ();
double planeSpeedSq = u * u + vy * vy;
+ double aftSweep = aftSweep(s, u, tuning);
double vortexFactor = vortexFactor(s, tuning);
double flapShift = FLAP_ALPHA_FACTOR * flap;
- double alpha = criticalAngle(s, tuning, vortexFactor) + FLAP_STALL_GAIN * flapShift - STALL_BLEND;
- double lift = liftSlope(s) * alpha;
+ double alpha = criticalAngle(s, tuning, vortexFactor, aftSweep) + FLAP_STALL_GAIN * flapShift - STALL_BLEND;
+ double lift = liftSlope(s, aftSweep) * alpha;
if (s.type() == SurfaceType.WING) {
lift += VortexLift.liftCoefficient(alpha, vortexFactor, tuning.vortexLiftStrength());
}
@@ -206,7 +218,7 @@ final class ImprovedAero {
}
double flapShift = FLAP_ALPHA_FACTOR * flap;
double alpha = Math.atan2(-vy, Math.abs(u)) + Math.toRadians(s.type().camber) + flapShift;
- double critical = criticalAngle(s, tuning, vortexFactor(s, tuning)) + FLAP_STALL_GAIN * flapShift;
+ double critical = criticalAngle(s, tuning, vortexFactor(s, tuning), aftSweep(s, u, tuning)) + FLAP_STALL_GAIN * flapShift;
return alpha / critical;
}
@@ -215,17 +227,52 @@ final class ImprovedAero {
? VortexLift.factor(s.aspectRatio()) : 0.0;
}
- /** Angle of attack (radians, camber and flaps included) at which the surface starts to stall, without flaps. */
- private static double criticalAngle(AeroSurface s, Tuning tuning, double vortexFactor) {
- double baseStall = s.slab() ? SurfaceType.SLAB_STALL_ANGLE
- : s.wingGroup() && s.type().controllable ? SurfaceType.WING.stallAngle : s.type().stallAngle;
- return Math.toRadians(baseStall) * (1.0 + tuning.vortexStallBonus() * vortexFactor) * tuning.stallAngleScale();
+ /**
+ * Angle of attack (radians, camber and flaps included) at which the surface starts to stall, without flaps. On a
+ * swept wing the air drifts along the span towards whichever end lies aft and thickens the boundary layer there, so
+ * that end stalls first: the tips of an aft swept wing, the root of a forward swept one.
+ */
+ private static double criticalAngle(AeroSurface s, Tuning tuning, double vortexFactor, double aftSweep) {
+ // Slab and full block variants stall alike: which one a builder picks is about looks, not airfoil thickness
+ double baseStall = s.wingGroup() && s.type().controllable ? SurfaceType.WING.stallAngle : s.type().stallAngle;
+ double spanwise = 1.0 - SWEEP_STALL_SPREAD * Math.sin(aftSweep) * (2.0 * s.spanFraction() - 1.0);
+ return Math.toRadians(baseStall) * (1.0 + tuning.vortexStallBonus() * vortexFactor) * tuning.stallAngleScale() * spanwise;
}
- /** Lift slope per radian from finite wing theory, from the wing's aspect ratio. */
- private static double liftSlope(AeroSurface s) {
+ /**
+ * Lift slope per radian from finite wing theory, from the wing's aspect ratio, lowered by sweep as the DATCOM
+ * formula has it. Scaled so an unswept wing keeps the slope it always had.
+ */
+ private static double liftSlope(AeroSurface s, double aftSweep) {
double aspectRatio = s.aspectRatio();
- return aspectRatio > 0.0 ? 2.0 * Math.PI / (1.0 + 2.0 / aspectRatio) : LIFT_SLOPE;
+ if (!(aspectRatio > 0.0)) {
+ return LIFT_SLOPE * Math.cos(aftSweep);
+ }
+ double slope = 2.0 * Math.PI / (1.0 + 2.0 / aspectRatio);
+ if (aftSweep == 0.0) {
+ return slope;
+ }
+ return slope * datcomSlope(aspectRatio, aftSweep) / datcomSlope(aspectRatio, 0.0);
+ }
+
+ /** DATCOM lift slope of a swept wing, per radian. */
+ private static double datcomSlope(double aspectRatio, double sweep) {
+ double tan = Math.tan(sweep);
+ double root = Math.sqrt(4.0 + aspectRatio * aspectRatio * (1.0 + tan * tan) / (AIRFOIL_EFFICIENCY * AIRFOIL_EFFICIENCY));
+ return 2.0 * Math.PI * aspectRatio / (2.0 + root);
+ }
+
+ /**
+ * The surface's sweep as the air sees it, radians: positive swept aft (tips behind the root), negative swept forward,
+ * 0 with sweep effects off. Warium's surfaces work with the air coming from either end of the chord, so which of the
+ * two a wing is follows from the direction of the flow along its facing.
+ */
+ private static double aftSweep(AeroSurface s, double u, Tuning tuning) {
+ if (!tuning.sweep() || s.sweep() == 0.0 || u == 0.0) {
+ return 0.0;
+ }
+ // Moving along +facing (u > 0), a tip further towards +facing (sweep > 0) leads the root: forward sweep
+ return -s.sweep() * Math.signum(u);
}
static double smoothstep(double edge0, double edge1, double x) {
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/flight/SurfaceType.java b/src/main/java/dev/lumareth/improvedAerodynamics/flight/SurfaceType.java
index ac474cc..3f309d8 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/flight/SurfaceType.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/flight/SurfaceType.java
@@ -15,9 +15,6 @@ public enum SurfaceType {
VERTICAL_CONTROL_SURFACE(true, true, false, 15.0, 0.0, 0.0),
AIR_BRAKE(false, false, false, 0.0, 0.0, 0.0);
- // Slab variants are thinner and stall earlier
- static final double SLAB_STALL_ANGLE = 12.0;
-
/** Surface stands upright, so its lift acts sideways. */
final boolean vertical;
/** Deflects with pilot input. */
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/flight/WariumCapture.java b/src/main/java/dev/lumareth/improvedAerodynamics/flight/WariumCapture.java
index a3a7401..4ad1ea8 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/flight/WariumCapture.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/flight/WariumCapture.java
@@ -73,9 +73,8 @@ public final class WariumCapture {
}
private static AeroSurface createSurface(ServerLevel level, AeroState aero) {
- Direction facing = facing(state);
- ResourceLocation id = ForgeRegistries.BLOCKS.getKey(state.getBlock());
- boolean slab = id != null && id.getPath().contains("slab");
+ Direction direction = facing(state);
+ Direction facing = direction != null ? direction : Direction.NORTH;
double speedMultiplier = Math.max(1, level.getGameRules().getInt(ValkyrienWariumModGameRules.AERODYNAMIC_SPEED_MULTIPLIER) / 100);
double pressure = PressureGetProcedure.execute(level, pos.getX(), pos.getY(), pos.getZ());
@@ -102,10 +101,10 @@ public final class WariumCapture {
}
}
- return new AeroSurface(pos.asLong(), type, slab, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5,
- facing.getStepX(), facing.getStepZ(), pressure, fluidFactor(level), speedMultiplier,
+ return new AeroSurface(pos.asLong(), type, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5,
+ facing.getStepX(), facing.getStepZ(), direction != null, pressure, fluidFactor(level), speedMultiplier,
node, ControlAxis.of(key), ControlAxis.multiplier(key), ControlAxis.of(key2), ControlAxis.multiplier(key2),
- brakeInput, 0.0, false, flap);
+ brakeInput, 0.0, false, flap, 0.0, 0.0);
}
/** Registers a node's inputs once per tick, and saves its trim to it now and then so it survives reloading. */
@@ -161,16 +160,28 @@ public final class WariumCapture {
return inLiquid ? underWater : 1.0;
}
- /** Warium's way of reading a block's direction: its "facing", else the positive end of its "axis", else north. */
+ /**
+ * The block's chord direction: its "facing" (Warium's way), or "orientation" (Warframes' slab wings), else the
+ * positive end of its "axis". Null if it has none that lies horizontal, as on Warframes' plain slab wings and
+ * stabilizers, or only one that says which side the block sits on, as on Warframes' layer blocks. Warium's own lift
+ * ignores direction, so such blocks get the direction the rest of the craft's surfaces agree on, see WingShape.
+ */
private static Direction facing(BlockState blockState) {
- Property> facing = blockState.getBlock().getStateDefinition().getProperty("facing");
- if (facing instanceof DirectionProperty directionProperty) {
- return blockState.getValue(directionProperty);
+ java.util.Collection> properties = blockState.getBlock().getStateDefinition().getProperties();
+ ResourceLocation id = ForgeRegistries.BLOCKS.getKey(blockState.getBlock());
+ if (id != null && id.getPath().contains("_layer")) {
+ return null;
+ }
+ for (String name : new String[]{"facing", "orientation"}) {
+ Property> property = blockState.getBlock().getStateDefinition().getProperty(name);
+ if (property != null && properties.contains(property) && blockState.getValue(property) instanceof Direction value) {
+ return value.getAxis().isHorizontal() ? value : null;
+ }
}
Property> axis = blockState.getBlock().getStateDefinition().getProperty("axis");
if (axis instanceof EnumProperty> enumProperty && blockState.getValue(enumProperty) instanceof Direction.Axis value) {
- return Direction.fromAxisAndDirection(value, Direction.AxisDirection.POSITIVE);
+ return value.isHorizontal() ? Direction.fromAxisAndDirection(value, Direction.AxisDirection.POSITIVE) : null;
}
- return Direction.NORTH;
+ return null;
}
}
diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/flight/WingShape.java b/src/main/java/dev/lumareth/improvedAerodynamics/flight/WingShape.java
index f264928..07b7914 100644
--- a/src/main/java/dev/lumareth/improvedAerodynamics/flight/WingShape.java
+++ b/src/main/java/dev/lumareth/improvedAerodynamics/flight/WingShape.java
@@ -10,12 +10,21 @@ import java.util.Collection;
*
* Neighbouring blocks of the same kind and facing form one wing. Horizontal wings also join across gaps of up to
* {@link #MAX_GAP} blocks along the span, so the two halves of a wing either side of a fuselage count as one wing and
- * the span is the full wingspan. Air brakes are not wings and are left alone.
+ * the span is the full wingspan. Blocks that only touch at an edge on the same level join too, so a swept wing built
+ * as a diagonal counts as one wing. Air brakes are not wings and are left alone.
+ *
+ * Horizontal wings also get their sweep: for each half (either side of the middle of the span) the line through its
+ * blocks' chordwise positions against their distance from the middle, whose slope is the tangent of the sweep. And every
+ * block learns how far out along its half it sits, which decides where a swept wing starts to stall.
*/
final class WingShape {
private static final int MAX_GAP = 6;
private static final double MIN_ASPECT_RATIO = 0.5;
private static final double MAX_ASPECT_RATIO = 12.0;
+ private static final double MAX_SWEEP = Math.toRadians(60.0);
+ // A half wing needs this many blocks and this much spread along the span before a sweep is read from it
+ private static final int MIN_SWEEP_BLOCKS = 3;
+ private static final double MIN_SPAN_VARIANCE = 0.5;
private WingShape() {
}
@@ -23,6 +32,23 @@ final class WingShape {
static AeroSurface[] withAspectRatios(Collection surfaces) {
AeroSurface[] all = surfaces.toArray(new AeroSurface[0]);
int n = all.length;
+ // Blocks that do not say their direction take the axis most of the craft's surfaces face along. The sign does
+ // not matter: lift works with the air coming from either end, and sweep is judged from the flow
+ int alongX = 0;
+ int alongZ = 0;
+ for (AeroSurface s : all) {
+ if (s.facingKnown() && s.type() != SurfaceType.AIR_BRAKE) {
+ alongX += Math.abs(s.facingX());
+ alongZ += Math.abs(s.facingZ());
+ }
+ }
+ if (alongX + alongZ > 0) {
+ for (int i = 0; i < n; i++) {
+ if (!all[i].facingKnown()) {
+ all[i] = all[i].withFacingAxis(alongX >= alongZ);
+ }
+ }
+ }
int[] cell = new int[n * 3];
Long2IntOpenHashMap index = new Long2IntOpenHashMap(n * 2);
index.defaultReturnValue(-1);
@@ -52,6 +78,12 @@ final class WingShape {
}
// Gaps along the span of horizontal wings, only in one direction since the other side finds this block
if (!s.type().vertical) {
+ // Blocks touching only at an edge on the same level, a diagonal wing
+ for (int a = -1; a <= 1; a += 2) {
+ for (int b = -1; b <= 1; b += 2) {
+ union(parent, i, index.get(key(s, x + s.rightX() * a + s.facingX() * b, y, z + s.rightZ() * a + s.facingZ() * b)));
+ }
+ }
for (int gap = 2; gap <= MAX_GAP + 1; gap++) {
union(parent, i, index.get(key(s, x + s.rightX() * gap, y, z + s.rightZ() * gap)));
}
@@ -75,6 +107,28 @@ final class WingShape {
minSpan[root] = Math.min(minSpan[root], span);
maxSpan[root] = Math.max(maxSpan[root], span);
}
+ // Sweep: per wing and side of its middle, least squares sums of the distance from the middle (o) and the
+ // position along the chord axis (c, the positive x or z axis)
+ double[] sums = new double[n * 2 * 5];
+ for (int i = 0; i < n; i++) {
+ if (all[i].type() == SurfaceType.AIR_BRAKE || all[i].type().vertical) {
+ continue;
+ }
+ int root = find(parent, i);
+ double offset = spanCoordinate(all[i], cell, i) - (minSpan[root] + maxSpan[root]) / 2.0;
+ if (offset == 0.0) {
+ continue;
+ }
+ int at = (root * 2 + (offset > 0.0 ? 1 : 0)) * 5;
+ double o = Math.abs(offset);
+ double c = chordCoordinate(all[i], cell, i);
+ sums[at] += 1.0;
+ sums[at + 1] += o;
+ sums[at + 2] += c;
+ sums[at + 3] += o * o;
+ sums[at + 4] += o * c;
+ }
+
for (int i = 0; i < n; i++) {
if (all[i].type() == SurfaceType.AIR_BRAKE) {
continue;
@@ -82,11 +136,50 @@ final class WingShape {
int root = find(parent, i);
double span = maxSpan[root] - minSpan[root] + 1;
double aspectRatio = span * span / count[root];
- all[i] = all[i].withWingShape(Math.max(MIN_ASPECT_RATIO, Math.min(MAX_ASPECT_RATIO, aspectRatio)), hasWing[root]);
+ double sweep = 0.0;
+ double spanFraction = 0.0;
+ if (!all[i].type().vertical) {
+ double offset = spanCoordinate(all[i], cell, i) - (minSpan[root] + maxSpan[root]) / 2.0;
+ double halfSpan = (maxSpan[root] - minSpan[root]) / 2.0;
+ spanFraction = halfSpan > 0.0 ? Math.abs(offset) / halfSpan : 0.0;
+ // Blocks on the middle line take the sweep of the side with more blocks
+ int side = offset > 0.0 ? 1 : offset < 0.0 ? 0 : sums[(root * 2 + 1) * 5] >= sums[root * 2 * 5] ? 1 : 0;
+ double axisSweep = halfSweep(sums, (root * 2 + side) * 5);
+ // Measured along the positive axis, stored along the block's own facing
+ sweep = axisSweep * (all[i].facingX() + all[i].facingZ());
+ }
+ all[i] = all[i].withWingShape(Math.max(MIN_ASPECT_RATIO, Math.min(MAX_ASPECT_RATIO, aspectRatio)), hasWing[root],
+ sweep, spanFraction);
}
return all;
}
+ /** Sweep of one half wing from its sums, radians, positive when the tip lies towards the positive chord axis. */
+ private static double halfSweep(double[] sums, int at) {
+ double count = sums[at];
+ if (count < MIN_SWEEP_BLOCKS) {
+ return 0.0;
+ }
+ double meanO = sums[at + 1] / count;
+ double meanC = sums[at + 2] / count;
+ double variance = sums[at + 3] / count - meanO * meanO;
+ if (variance < MIN_SPAN_VARIANCE) {
+ return 0.0;
+ }
+ double slope = (sums[at + 4] / count - meanO * meanC) / variance;
+ return Math.max(-MAX_SWEEP, Math.min(MAX_SWEEP, Math.atan(slope)));
+ }
+
+ /** Position along the span axis of a horizontal block, the same coordinate the span is measured in. */
+ private static double spanCoordinate(AeroSurface s, int[] cell, int i) {
+ return cell[i * 3] * Math.abs(s.rightX()) + cell[i * 3 + 2] * Math.abs(s.rightZ());
+ }
+
+ /** Position along the chord axis (the positive x or z axis the facing lies on). */
+ private static double chordCoordinate(AeroSurface s, int[] cell, int i) {
+ return cell[i * 3] * Math.abs(s.facingX()) + cell[i * 3 + 2] * Math.abs(s.facingZ());
+ }
+
/** Position plus everything that must match for two blocks to be the same wing. */
private static long key(AeroSurface s, int x, int y, int z) {
long kind = (s.type().vertical ? 2 : 0) | (s.facingX() != 0 ? 1 : 0);