Section-start glows used the b_add of the most recently created bolt
type (Nebl_type) rather than the bolt being drawn, so concurrent bolts
of different types got the wrong glow offset. The cap glow already
used the correct type.
Clamp $Collision LOD to num_detail_levels - 1, the highest valid
detail level. The previous bound was harmless because the collision
code falls back to the lowest existing LOD, but it was off by one.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* Add an "On Ship Damage" script hook
Runs after resolved damage has been applied to a ship (lethal hits run before
the destruction callback). Hook variables: Target, Source, Attacker,
WeaponClass, WeaponSubtype, SourceKind (PROJECTILE, BEAM, SHOCKWAVE, COLLISION,
OTHER), DamageType, ShieldDamage, HullDamage, Quadrant, Ballistic, BeamWeapon
and LethalHit. Conditions can filter on the target ship. Nothing is computed
unless a script has registered the hook.
* Move the On Ship Damage hook call out of a lambda
ship_do_damage() now calls a file-level static function, ship_run_damage_hook(), that takes the values it needs as arguments instead of capturing the function state. Hook behaviour is unchanged.
* Report subsystem damage in the On Ship Damage hook
Adds SubsystemDamage, the total subsystem strength a damage application removed, so a hit absorbed by subsystems no longer looks like a small hull hit. The hook description now says it only runs where damage is applied, which excludes multiplayer clients.
* Address On Ship Damage review comments
- Remove WeaponClass, WeaponSubtype, Ballistic and BeamWeapon from the
hook. Scripts read these from Source when it is a weapon.
- Add a "Weapon class" condition for the On Ship Damage hook. It matches
only when the damage source is a weapon of that class; a weapon name
that does not exist never matches.
- SubsystemDamage is now a table keyed by subsystem handle that lists only
the subsystems that lost strength. The total is removed.
- Rename PROJECTILE to NON_BEAM_WEAPON.
- Classify SourceKind by damage source: COLLISION for ship, debris and
asteroid collisions; EXPLOSION for ship-death and docked-ship blasts and
asteroid blasts; WASH for engine wash; SELF for kills where the ship
damages itself; OTHER for other ship-sourced damage.
- Reword the hook description.
* Key On Ship Damage SubsystemDamage by canonical name
Lua tables cannot use subsystem handles as keys in a usable way, so key
the SubsystemDamage table by each subsystem's CanonicalName instead.
* Tag ship-vs-prop damage as a collision and use in_bounds
The ship-vs-prop collision call didn't pass DamageSource::Collision, so
the On Ship Damage hook reported those hits as OTHER. Every other
collision path was already tagged.
Also use SCP_vector::in_bounds() for the Weapon_info and Damage_types
index checks in ship_run_damage_hook().
* Add weapon_info::clone
Copies every member of a weapon class, following ship_info::clone, so a
weapon can be created from another as ship templates do. The
CLONE_UNIQUE_PTR macro moves from ship.cpp to utils/string_utils.h so
both clone functions share it.
* Group weapon_info::clone fields as the struct declares them
---------
Co-authored-by: Dustinspace217 <[email protected]>
* Measure afterburner cooldowns on the mission clock
afterburners_start()/afterburners_stop() timed the +Aburn Cooldown Time delay and
the player's 1.3 s re-engage delay with timer_get_milliseconds(), the real
clock. Under time compression a cooldown therefore lasted longer in mission
time than the table says, and it kept running while the game was paused. The
cooldown was added in 2020 and reused the retail re-engage check's real-clock
"now"; the rest of the file (ABURN_DECAY_TIME, the sound timers) already uses
mission timestamps.
Both delays now use the mission clock. The mission clock does not run outside
missions, so it can still be near zero when the first mission of a session
starts; the "last stopped" and "last started" times therefore start out
invalid instead of 0, so that no delay is in effect before the afterburner has
been used.
Without time compression or pausing, the delays behave as before.
* Drop stale afterburner comment and use fl2i for the cooldown cast
The comment described an earlier startup state rather than the current
behavior. fl2i is the project's float-to-int macro and truncates the same
way the old C-style cast did.
* Remove the remaining afterburner cooldown comment
Timestamps running on mission time is the common case, so it doesn't
need a comment.
* take a model reference when a ship changes class
ship_model_change() only loaded the model when the class had none, so a ship
switched to a class whose model had been loaded only by a select-screen
preview adopted that preview's single reference. Closing the screen then
freed the model from under the ship, and the first simulation frame asserted
in model_get(). This is what happened on a replayed mission with a restored
loadout: ship select was skipped, the weapon-select overhead loaded the new
class once, the commit switched the player to it, and the screen close
released it.
Load unconditionally, as ship_create() already does, so the ship holds its own
reference.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* reject stale model ids in model_unload and release select-screen handles at level close
model_unload only used the slot part of the id it was given, so a handle kept
across missions would free whatever model had since been loaded into that slot.
Validate the id against the slot's occupant and warn instead.
Two holders could present such handles: the weapon-select icon models under a
scripted UI that overrides the state hooks (the native close never runs), and
the ship-select 3D model global, which was never reset between missions.
Release the select-screen handles from game_level_close, and unload the
ship-select model on screen close and on every selection change.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* consolidate the select-screen resource release
The weapon side released its icons, anims, and ship class data from two
functions keyed on whether the screen was open, and the level-close path added
a third copy. Give the weapon side the same shape as the ship side: one
unconditional weapon_select_common_close(), with weapon_select_close() left as
pure UI teardown. common_select_level_close() now just calls the two common
closes, and common_select_close() calls it in turn. The ship-select 3D model
is released from ship_select_common_close() so both paths cover it.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
---------
Co-authored-by: Claude Fable 5.1 <[email protected]>
get_I_inv converts an object's inverse moment of inertia tensor from body to world coordinates for collision physics. It was written as though vm_matrix_x_matrix(dest, a, b) computes a * b, but that function computes b * a, so the result was (R)(I_inv_body)(Rt) rather than the (Rt)(I_inv_body)(R) stated in the comment. The collision response therefore used the tensor of an object facing the inverse of its actual orientation. This dates back to retail.
The result is only correct for an isotropic tensor or an unrotated object. Every retail ship has an anisotropic tensor, with a median principal-axis ratio of about 2.5 and as high as 13 for capital ships, so the spin imparted by a collision was typically about the wrong axis.
Since this changes collision behavior for every mod, the fix is controlled by the new game_settings.tbl option "$Fix collision moment of inertia:", which defaults to true for mods targeting 26.2 or later. The retail path is otherwise unchanged.
PR #2575 fixed a related bug in physics_ship_init: retail scaled the inverse moment of inertia by $Density rather than by its inverse, so a denser ship was easier to rotate rather than harder. That fix was merged without a flag. For consistency it is now controlled by "$Fix density moment of inertia:", which defaults to true for mods targeting 21.0 or later.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A subsystem's looping sounds are now switched by ship_update_subsys_sounds, split out of ship_recalc_subsys_strength, which the support-ship and automatic repair paths now also call when a subsystem comes back from zero. Previously those paths left the subsystem playing its dead sound.
Both the recalc and do_subobj_destroyed_stuff also cleared the dead-sound flag immediately after assigning the dead sound, so a revived subsystem never stopped it and a destroyed one gained another copy on each recalc. They now set the flag.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
When a destroyed subsystem was repaired, its submodels were only restored if the repair was done through a SEXP. A subsystem repaired by a support ship, by automatic repair, by a script, or through the debug console regained its hitpoints but not its submodels, so a ship could have a working turret with no model. Any -destroyed form also remained visible.
All of these now call restore_subsystem_submodels, which brings back the subsystem's submodels and hides the -destroyed submodel linked to a special-point subsystem. The -destroyed form of an ordinary submodel is hidden when the submodels are next replicated. The SEXP code uses the same function, with no change in its behavior.
Destruction outside do_subobj_destroyed_stuff now goes through a new blow_off_subsystem_submodels function, which do_subobj_destroyed_stuff also uses. It blows off both of the subsystem's submodels and shows any linked -destroyed submodel, unless the subsystem has "no disappear". This handles the cases where a subsystem appears destroyed without going through do_subobj_destroyed_stuff:
- the subsystem is destroyed at the start of the mission
- the subsystem was destroyed in the previous mission of a red-alert sequence
- the ship changes class while the subsystem's submodels are blown off
Previously the first two blew off only the first submodel, ignored "no disappear" for it, and never showed a linked -destroyed submodel; the third did nothing. For red alert, subsystems with no hitpoints at all are not treated as destroyed. For a class change, the visible state is carried over rather than inferred from hitpoints, so a subsystem set to zero without being blown up, or repaired without its submodels, keeps its appearance.
Red alert also restores the submodels of a subsystem that the mission file starts destroyed if the previous mission's data gives it hitpoints. Ship-copy-damage now shows or hides the -destroyed submodel linked to a special-point subsystem to match the copied state.
As before, the link between special-point subsystems and -destroyed submodels requires "$Link special-point subsystems to -destroyed submodels:" in game_settings.tbl.
The multiplayer hitpoint-update path is not changed. A client receives subsystem hitpoints separately from the notification that a subsystem was destroyed, so a hitpoint update sent just before the destruction could arrive after it and wrongly restore the submodels.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
- Introduced `shadow_ray_params` to simplify ray origin and cull mask management.
- Shifted shadow ray origins to TLAS-relative space for improved precision and consistency, especially for cockpit rendering.
- Refactored cascade bind functions, adding `shadow_cascade_params_bind_deferred()` for consolidated offset/count handling in deferred lighting.
- Expanded TLAS to include cockpits and additional object types, ensuring parity with rasterized shadows.
- Introduced per-instance cull masks to address cockpit self-shadowing issues.
- Improved Vulkan depth isolation for cockpit rendering via backup/restore mechanism, ensuring correct depth sampling in later passes.
- Extracted reusable helper functions for cockpit rendering state logic.
Follow-up to #7606. Restore the MaxGuardRadius property, restore the ability to set specific ranges using set-guard-range, and add scripting functions for setting the specific ranges.
Fixes#7756
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Cockpit_active was latched inside ship_render_player_ship(), which only
runs when Viewer_obj is non-null. External, chase, warp-chase, topdown,
free-camera and dead views all null Viewer_obj, so the flag froze at its
last cockpit-view value and cockpitinactive HUD gauges vanished. It was
also read before being written each frame (by the show-ship check and the
shadow helpers), so those decisions lagged a frame on any transition.
Replace it with three functions computed on demand:
- ship_cockpit_enabled(sip): the ship has a cockpit model and cockpits
aren't disabled; used by the Show_ship_only_if_cockpits_enabled checks
- ship_render_player_cockpit(sip): the above, outside topdown view;
replaces three duplicated copies of that expression
- ship_render_player_cockpit_active(): whether the viewer's cockpit is
being rendered this frame; used by the HUD cockpit-view-choice checks
With the predicate correct, the VM_CHASE special cases added for #4804
are no longer needed and are removed. In chase view, cockpitinactive
gauges now also respect pop-up state, No_ets, and setRenderOverride,
which the early return in HudGauge::canRender() used to bypass.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`support_ship_info::rearm_weapon_pool` was a dense per-weapon-class array where -1 = unlimited (the default), 0 = not rearmable, and >0 = remaining stockpile. Convert it to a sparse per-team map:
`std::array<SCP_map<int, int>, MAX_TVT_TEAMS> rearm_weapon_pool;`
`int rearm_pool_default() const; // -1, or 0 under rearm_pool_from_loadout`
Mission-file format and save output are unchanged. Also tightens the two weapon-class bounds checks in ship.cpp. This removes another `MAX_WEAPON_TYPES` sized structure on the way to lifting the weapon class limit.
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up to #7635.
Pass the firing bank explicitly through weapon_create() and beam_fire()
instead of searching the ship's banks by weapon class, which could
attribute substitution patterns to the wrong bank. Factor the
substitution logic into get_weapon_substitution_tuple() and only apply
linked/dual-fire pairing to ship-level fire, not turret fire. Skip
substitution on multiplayer clients, since the server already resolved it.
Derive turret bank indices from the weapon slot being fired rather than
the turret's bank cursor, so ammo and substitution state are tracked on
the bank that actually fired. Previously a single-selection turret could
consume ammo from a bank it never fired, and non-ammo turrets (whose
cursors stay at -1) would have skipped substitution entirely.
Use the Player_ship object flag rather than Player_obj in
ship_secondary_bank_can_dual_fire() so the server and clients agree on
dual fire for remote players, and guard ship_secondary_has_ammo() against
a negative bank index.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
With every fixed-size ship-class-indexed structure now converted to dynamic containers, we can finally remove the `MAX_SHIP_CLASSES` limit!
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* Fix estimate_ship_speed_upper_limit to handle non-ship objects gracefully
* Add collision handling for OBJ_PROP objects
Implement OBJ_PROP-specific collision messaging and logic: update player death messages, fix incorrect argument usage in collision checks, and set killer attributes for PROP collisions.
* consolidate per-bank external weapon model state into one struct
The state for a bank's external weapon model was scattered across two
structs and three naming schemes: the model instance and its weapon in
ship_weapon, the firing-point chain counter in a combined array indexed
with the bank + MAX_SHIP_PRIMARY_BANKS packing convention, and the
gatling spin rate/angle on ship itself.
Gather them into external_weapon_state, with one array for primary
banks and one for secondary banks in ship_weapon. This removes the
index-packing convention (ship_get_external_model_fp_offset now takes
the bank's state directly), and ship_delete now also frees secondary
instances should a future weapon ever create one.
No behavior change.
Co-Authored-By: Claude Fable 5 <[email protected]>
* update external weapon model spin in per-frame processing
The gatling spin state was integrated inside ship_fire_primary (spin-up)
and ship_stop_fire_primary_bank (spin-down), which entangled a per-frame
visual/state update with the firing event paths and had two quirks:
- Spin-down only ran when something called the stop-fire path, so a bank
could freeze mid-spin (e.g. AI ships that stop calling
ship_fire_primary without going through ship_stop_fire_primary).
- The spin angle only advanced when the ship class set
$Show Primary Models:, so identical weapon state evolved differently
per ship class even though the rate (which gates firing) always ran.
Banks that try to fire now just request spin-up, and
update_external_weapon_spin() -- called from ship_process_post next to
update_reload_percent(), which was moved out of the physics code for
the same reason -- integrates the rate and angle every frame. The
firing gate (no shots until the barrels reach full speed) is unchanged.
Co-Authored-By: Claude Fable 5 <[email protected]>
* make external_model_num mean what it says; gate firing offsets on drawn models
Since the original 2005 implementation, external_model_num was bashed
to model_num at parse time when no $External Model File: was given, so
every POF-rendered weapon appeared to have an external model. All the
checks downstream therefore tested 'has any model' while reading as
'has an external model', and two paths leaked the fallback into
gameplay:
- ship_fire_secondary applied the external-model firing point offset
without checking $Show Secondary Models: (unlike the primary path),
so any missile whose own in-flight POF contained gun points would
have its launch position offset on every ship in the game.
- The AI line-of-sight check, copied from ship_fire_secondary,
applied the offset with no draw check for either bank type, so for
primaries it could disagree with the actual firing path.
external_model_num now stays -1 unless $External Model File: was
given. Rendering code (ship_render_weapon_models, the HUD hardpoints
gauge, and the gatling instance helper) falls back to the weapon's own
model at the point of use, preserving the existing display of missiles
on hardpoints. Firing point offsets now require a dedicated external
model *and* the bank's models to actually be drawn, in all three
paths. In practice this does not change firing behavior, because GPNT
chunks are never added to weapon models except when explicitly built
as external models.
Co-Authored-By: Claude Fable 5 <[email protected]>
* warn on external weapon model conventions that are silently ignored
Two load-bearing conventions of the external weapon model feature had
no diagnostics:
- Only the first gun bank of an external model supplies firing points;
additional banks are silently ignored. Warn when an external model
has more than one gun bank.
- $Show Primary Models: / $Show Secondary Models: must list exactly
one bool per weapon bank; missing entries silently default to not
drawing. Warn when the list length doesn't match the bank count.
Co-Authored-By: Claude Fable 5 <[email protected]>
* orient external weapon models along their slot's firing normal
External weapon models were always rendered pointing ship-forward, and
reloading missiles slid backward along fixed -Z, regardless of the gun
or missile point's normal -- so a bank angled 45 degrees outward fired
along its normal while its mounted model pointed dead ahead. The
per-slot angle offset was also applied as a roll about ship-forward
rather than about the firing axis.
ship_get_weapon_model_slot_transform now builds the slot orientation
from the firing normal (identity for the usual dead-ahead normal, so
existing forward-facing mounts render exactly as before) with the
angle-offset roll applied about that axis, and slides reloading
missiles along the normal.
Correspondingly, ship_get_external_model_fp_offset now rotates the
external model's firing-point offset by the same slot transform, so
shots continue to emerge from the drawn barrels on angled mounts, and
now also respect the angle-offset roll (previously the offset was
added unrotated, mismatching rolled models).
Co-Authored-By: Claude Fable 5 <[email protected]>
* address review: same-frame spool-up gating; optional slot transform outputs
Move the update_external_weapon_spin() call from ship_process_post() to the top of ship_process_pre(). The update now happens before any firing attempt in the frame, so the spool-up firing gate sees the current frame's spin rate, as it did on master where the update happened inside the firing code. This also makes the ordering consistent for the AI regardless of Framerate_independent_turning.
Also make both outputs of ship_get_weapon_model_slot_transform() optional.
Co-Authored-By: Claude Fable 5 <[email protected]>
---------
Co-authored-by: Claude Fable 5 <[email protected]>
Two unrelated weapon-indexed buffers dropped their MAX_WEAPON_TYPES dependency, by different means since they have different natural bounds:
* ai_select_secondary_weapon and update_aspect_lock_information declared weapon_id_list / weapon_bank_list as [MAX_WEAPON_TYPES], but these are filled only by get_available_secondary_weapons, which appends at most one entry per secondary bank -- so they never hold more than MAX_SHIP_SECONDARY_BANKS!
* parse_allowed_weapons' allowed_weapons[MAX_WEAPON_TYPES] is genuinely weapon-class-bounded, so it becomes an SCP_vector<int> filled by the vector overload of stuff_int_list
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- A parse flag to indicate when the mission is being parsed, and a new `ship_class_index()` accessor in the ship registry, both currently unused
- Make the ship registry more robust, especially in FRED: properly update it when ships are renamed or deleted
Following PR #7429, ships belonging to wings were hashed the same way as every other ship, instead of the original hackish format where the hash was juggled around the number. This was a mostly transparent upgrade, and ship names were automatically converted from the legacy format to the new format. However, missions that referenced ships *in subsequent waves* broke; the converter only handled ships in the first wave.
This PR adds compatibility checks to `eval_ship` and `ship_registry_get` to accommodate legacy names.
* New guard-range sexp
New guard-range sexp which allows different ranges for different guarders
* cast value
* Clang
* bugfixes
* fix CI
* Address Feedback
* address feedback
* typo
* Fix two small issues
Fix copy-paste bug where setting `$Ask Help Hull Percent:` never properly got set. Fortunately this does not affect the AI, only when the AI sends a message to the player asking for help.
Fix edge-case issue: in `find_turret_enemy`, the `turret-tgt-ship-tgt` shortcut takes the parent ship's target and indexes Ships[] with it unconditionally, but `aip->target_objnum` could be a weapon or asteroid, which could be at an index higher than the ships index, and then trying to look up team could lead to bad data.
* comment formatting
Following style of 'target radius' and other useful weapon launch curve inputs, this PR adds 'Target Forward Speed' which can be useful to use as an input and then use FoF as an output to do things like make turrets have a tougher time having dynamic FoF depending on target speed.
Refactor `Ship_class_names`, `Iff_info_names`, and `Ai_class_names` to be populated once at parse time, as opposed to ad-hoc and possibly many times.
Also make `Ai_classes` and `Spawn_names` proper SCP_vectors.
The Secondary_dual_fire flag is per-ship, but not every secondary bank
can dual fire. Previously the HUD drew the dual fire link icon even
when the armed bank had only one firepoint, and firing such a bank
cleared the flag entirely, silently discarding the player's dual fire
preference for the other banks.
Extend the ignored-rather-than-cleared approach already established
for no-doublefire weapons to the single-firepoint case:
- add ship_secondary_bank_can_dual_fire() as the single source of truth
for bank validity, No_doublefire, ai_profiles restrictions, and
firepoint count
- ship_fire_secondary() now fires single and leaves the flag alone when
the bank cannot dual fire, instead of removing the flag
- the weapons gauges and the hardpoints gauge consult the helper, so the
link icon and second-firepoint highlight are no longer drawn for
incapable banks
- the dual fire toggle on a single-firepoint bank now explains why it
cannot dual fire and leaves the preference untouched
- restoring the saved dual fire preference no longer depends on bank 0's
firepoint count, since incapable banks now simply ignore the flag
- key control and force feedback also consult the helper
Co-Authored-By: Claude Fable 5 <[email protected]>
* Fix C4709 Warnings on latest VS
* more
* suppress false positive
* Switch to using any/none_of
* Address Feedback
* Fix Line endings?
* Fix commits and strip out flag_combinator
* more fixes
* nolint
Ship's implicit move operations compiled but were semantically broken in
two ways: moving copied the subsys_list sentinel's links verbatim,
leaving the bookend nodes of the intrusive subsystem list pointing at
the old sentinel address; and the raw owning warpin_effect /
warpout_effect pointers were copied without nulling the source, so a
vacated Ships[] slot aliased live WarpEffects that ship::clear() (on
slot reuse) or ship_close() (which walks every slot) would delete out
from under the destination ship.
Fix both at the member level so the compiler-generated moves are
correct by composition:
- Add ship_subsys_sentinel, derived from ship_subsys, whose move
operations re-link the bookend nodes (handling the null-linked,
self-referential-empty, and populated source states) and leave the
moved-from sentinel as an initialized empty list. Copying is
deleted. Public inheritance keeps &ship::subsys_list convertible to
ship_subsys*, so list_init, GET_FIRST, and every other call site is
unchanged.
- Convert warpin_effect and warpout_effect to std::unique_ptr. The
delete-and-null blocks in ship::clear(), ship_close(), and
ship_set_warp_effects() collapse into reset(); call sites that borrow
the pointer into a raw local now use get().
With the members handling themselves, declare ship's special member
functions: defaulted default constructor and moves, deleted copies
(previously implicit via the unique_ptr members, now stated intent).
The moves are deliberately not declared noexcept because members like
SCP_map and std::deque do not have standard-guaranteed nothrow moves;
the computed exception specification is used instead.
Co-Authored-By: Claude Fable 5 <[email protected]>
glowpoint_bank_override_map stored raw pointers into the growable global glowpoint_bank_overrides vector. Store indices instead, which survive vector reallocation. The readers also lose a redundant second map lookup (they previously called find() and then operator[] on the same key), and prop_info's parallel map gets the same conversion.
Co-Authored-By: Claude Fable 5 <[email protected]>
The hand-written ~350-line memberwise move existed only to manage the
one raw owning pointer, and silently left any member it didn't mention
uninitialized in the destination. With subsystems as a unique_ptr, the
defaulted moves and destructor are correct by composition. Copies
become explicitly deleted (use clone()). n_subsystems stays a plain
int because it is passed to varargs functions. The moves are not
declared noexcept because libstdc++ computes a potentially-throwing
implicit specification; NOLINT suppresses clang-tidy accordingly.
Co-Authored-By: Claude Fable 5 <[email protected]>
ship_render_weapon_models(), HudGaugeHardpoints::render(), and
ship_stop_fire_primary_bank() indexed Weapon_info[] with the bank's
weapon index without checking for an empty bank (-1). Banks within
num_*_banks are normally populated, but other code that iterates banks
treats them as possibly empty and guards accordingly (e.g.
ship_do_cargo_hidden, ship_page_in), so these paths now do too. In
the hardpoints gauge an empty primary bank still draws its firing
point circles.
Co-Authored-By: Claude Fable 5 <[email protected]>
The draw-distance cull for attached external weapon models checked
MR_ATTACHED_MODEL, but nothing has set that flag since commit
1ef7688fa1, so $Weapon Model Draw Distance: has been dead for years.
The check also needed the ship resolved from the render params' object
number, which is deliberately not set while weapon models render
(setting it would make model_render_queue clobber the explicitly
passed gatling model instance), and it compared against a depth
computed as if the weapon model's ship-local position were in world
space.
Carry the distance in model_render_params instead
(set_attached_model_draw_distance, negative = not an attached model),
set by ship_render_weapon_models from the ship's tabled value. When
set, model_render_queue measures depth from the eye position expressed
in the parent's frame (model_draw_list::get_view_position), which is
correct under the pushed parent transform, culls against the tabled
distance, and uses that same corrected depth for detail level
selection -- previously attached weapon models picked their LOD from a
garbage depth (roughly the eye's distance from the world origin).
MR_ATTACHED_MODEL is removed; nothing else referenced it. The unused
flags are also removed and the remaining flags are consolidated.
Co-Authored-By: Claude Fable 5 <[email protected]>
The model instance used to spin Gun_rotation submodels (gatling
barrels) was created lazily on first render, guarded by a
once-per-bank bool that nothing ever reset. If a primary bank's
weapon changed mid-mission (set-primary-weapon SEXP, scripting, rearm
precedence swap, multiplayer sync), the old weapon's instance leaked
until the ship was deleted and was silently discarded at render time
by the model/instance mismatch guard, while the new weapon never got
an instance, so its barrels never spun.
Replace the bool with a record of which weapon the instance was
created for, and move the logic into
ship_get_external_weapon_model_instance(), which recreates the
instance whenever the bank's weapon differs. This self-heals after
every swap path without needing hooks in each of them. The HUD
hardpoints gauge now goes through the same function instead of reading
the possibly-stale instance array directly.
Co-Authored-By: Claude Fable 5 <[email protected]>
The per-slot placement math for rendered external weapon models (the
angle-offset yaw plus the reload slide-back for missiles) was
duplicated four times across ship_render_weapon_models() and
HudGaugeHardpoints::render(). Extract it into
ship_get_weapon_model_slot_transform() so that future changes (such as
submodel-attached weapon banks) only need to touch one place.
This fixes a bug in the hardpoints gauge: the launcher-style secondary
branch computed the view-rotated world position but then rendered the
model at the untransformed local point, misplacing launcher models in
the rotated top/front views.
Also: hoist per-bank invariants out of the slot loops, drop the
redundant render_flags parameter of ship_render_weapon_models() (it
always equaled the flags already set on the render params), remove
long-dead commented-out code, and read the reload percentage once per
slot.
Co-Authored-By: Claude Fable 5 <[email protected]>
The logic for offsetting a shot by the external weapon model's firing
points was duplicated in ship_fire_primary(), ship_fire_secondary(),
and the AI's line-of-sight check. Extract it into
ship_get_external_model_fp_offset().
This fixes two bugs that were present in all three copies:
1. The chain counter for "chain external model fps" weapons was reset
when it reached weapon_model->n_guns (the number of gun banks)
rather than the number of firing points in the bank being indexed.
For the typical model with one gun bank the counter reset after
every shot, so chaining never advanced past the first firing point;
for a model with several gun banks the counter could index past the
end of the first bank's point array.
2. The AI line-of-sight check advanced the chain counter even though it
is only a query, desyncing the counter from the shots actually
fired. It now reads the current firing point without advancing.
Co-Authored-By: Claude Fable 5 <[email protected]>
* avoid undefined behavior from UNREACHABLE on reachable code paths
UNREACHABLE expands to __assume(false) / __builtin_unreachable() in
release builds, which is undefined behavior if the code is ever actually
reached. Many UNREACHABLE sites only guard against unexpected-but-
possible runtime states (values from tables, mission/save files, network
packets, scripting, or user input), so reaching them should degrade
gracefully rather than invoke UB.
Replace UNREACHABLE with Assertion(false, ...) at all such sites. It
still pops an error in debug builds, but in release it is a harmless
no-op that simply falls through to the following code. Sites that are
genuinely unreachable by local invariants (e.g. a switch over a bounded
random number) are left as UNREACHABLE.
A few converted sites had no safe fall-through -- an uninitialized read,
null dereference, or null call would have followed -- so they also get a
minimal recovery: initialize the value, guard the dereference, return
early, or skip the offending item.
Where the converted site was a simple guard of the form
if (x) { Assertion(false, ...); return; }
hoist the check onto the invariant instead:
Assertion(!x, ...);
if (x) { return; }
This states the expectation directly and shows the offending value in
the debug popup, while keeping the same graceful runtime degradation.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
* addendum
After consultation with Lafiel, use UNREACHABLE in situations that are effectively impossible even if not provably impossible. UNREACHABLE = "this shouldn't ever happen"; Assertion = "if this ever happens, it's a coding error". Also fix a few other sites and change a couple to Warnings.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Create a `ship_level_close()` function and call it from `game_level_close()`. Among other tasks, this clears out any PRESENT or DEATH_ROLL statuses to prevent SEXPs or scripts from obtaining references to ships that have been deleted.
Follow-up to #7522.
* Extract shadows into own shader and render pass
# Conflicts:
# code/def_files/data/effects/main-g.sdr
* Consolidate render queue code
* More cleanup
* Fix missing clear of shadow buffer inter frame
* Request capability for viewport layer rendering
* instanced shadows
* Fix issues
* Switch to PCF+PCSS and proper textures for it
* Smooth PCSS toggle
* Fix for windows
* Fix OGL error
* Cleanup of old flag
* Expose shadow smoothness
* Fix missing uniform
* Make number of shadow cascades dynamic
* Progress on cockpit shadow integration
* Wrangle Cockpit and show-ship shadows into correct behaviour
* Cleanup
* make player ship shadow table options more intuitive
* Cleanup
* Only read from correct set of shadow maps, also stretch first main-scene map to 0
* Remove now non-necessary validation
* Make shadow cascade buffer more typesafe and less wasteful
* Don't allocate cockpit cascades if not used
* Cleanup
* Final fixes
* Fix Warnings
* clang tidy
* Fix missing fallback for shader precaching
* That weird FOV multiplier that always ruins your day
* Avoid shadow geometry artifacts by using hardware depth clamping
* Correctly handle shadow cascade overrides with hardcoded length
* GCC9 and its sad state of C++17 support.
* Address Feedback
# Conflicts:
# code/graphics/shadows.cpp
Set model instances to -1 when objects are deleted, and guard against null model instances in `modelinstance_replace_active_texture`. This may fix a crash in Event Horizon.