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]>
Changing Lighting in the options recompiles every shader, but Vulkan kept drawing with the pipelines it had already
built, and a pipeline keeps the shader code it was created from. So the new lighting level only showed up after a
restart. OpenGL applies it at once.
After the recompile, mark the cached pipelines stale. At the start of the next frame, before anything is recorded,
wait for the GPU and drop them; the next draws build them again from the new shaders. The recompile can run in the
middle of a frame (from the options menu or a script), so the drop waits for the next frame instead of happening there.
The recompile also rebuilds the anti-aliasing family that is not in use, which cannot compile under the current mode.
Its cached pipeline used to hide that; now the failed variant is dropped so it compiles again when that mode returns.
Fixes#7967
Co-authored-by: Dustinspace217 <[email protected]>
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().
The Vulkan light shaft pass reuses OpenGL's sun position formula, whose
texture V grows upward. The Vulkan fullscreen triangle in post-v.sdr has
V = 0 at the top of the screen, and ls-f.sdr steps from fragTexCoord
toward sun_pos in that space, so the shafts radiated from a point mirrored
vertically from the sun. Flip the vertical coordinate before upload.
Co-authored-by: Saga port <saga-port@invalid>
Co-authored-by: Claude Opus 5.5 <[email protected]>
* android build support
* Update es_compatibility.h
* Support reporting flags in android
* include pref_path in json v2
* add vulkan headers
* shaderc includes
* remove headers
* force use prebuilt vulkan
* fix vulkan inverted screen
* fix find sdl3 precompiled android
* Update CMakeLists.txt
* replace sdl2 android function names for sdl3 versions
* change sdl includes in osapi
* fix sdl3 includes, again
* rename function to sdl3 name
* remove unused definition
* copy libshaderc_shared.so to output in android
* do not look for vulkan-loader in android
* revert changes to SDL2.cmake
* add comment to vulkan pretransform setup
* cleanup maxsize function
* rename new android functions in osapi
* android trap back button
* Remove calculate_max_resize_max_size
* touch ui opacity control
* change opacity control to int
* fix opacity slider
* Corrected android working folder fallback and set borderless mode as default
* Implement shared helper for JNI calls
* Add version tag and sha256 to android prebuilt libs
* vulkan android check eSuboptimal
* An already requested rebuild also avoids redundant Android surface queries
* add cache bool to cmakelist
* set string ids
FRED2 can switch to its classic menus, where every editor dialog is in a single
Editors menu. This adds the same option to QtFRED, as a Preferences checkbox on
the Appearance tab.
The classic Editors and Misc menus live in FredView.ui beside the grouped menus
and reuse the same actions, so shortcuts and checked states are shared. Turning
the option on hides the Objects, Environment, Mission, Narrative and Tools
menus and shows the classic ones.
OpenGL's shadow pass calls gr_zbias(-1024), which sets a polygon offset of
factor 1, units 1024 (gropengltnl.cpp, gropengl.cpp). The Vulkan shadow pass
set a constant bias of -1024 with no slope term: the opposite sign, on a
depth buffer that uses the same less-than test. Use OpenGL's values.
Co-authored-by: Dustinspace217 <[email protected]>
Each VulkanRenderFrame signaled its own rendering-finished semaphore and
presented with it. The frame's fence only says the submit has finished, not
that the presentation engine has consumed the semaphore, so the next submit
on that frame could signal a semaphore that is still pending, which the
validation layer reports as VUID-vkQueueSubmit-pSignalSemaphores-00067.
Move the semaphore to the renderer, one per swap chain image, recreated with
the swap chain, and pass the one for the acquired image to submitAndPresent.
Acquiring an image again means its previous present has been consumed.
Co-authored-by: Dustinspace217 <[email protected]>
irrmap-f.sdr declares the Material set's texture binding as a samplerCube,
but vulkan_calculate_irrmap filled the array with the 2D fallback and only
replaced element 0 with the environment map, which the validation layer
reports as VUID-vkCmdDraw-viewType-07752 on every irradiance pass. Fill it
with the cube fallback instead.
Co-authored-by: Dustinspace217 <[email protected]>
VulkanDistortion creates a linear/repeat sampler for its noise textures,
matching OpenGL's GL_REPEAT on Distortion_texture, but getTextureInfo
handed out the post-processing linearSampler instead, which clamps. The
sampler that was built for it is now the one used.
Co-authored-by: Dustinspace217 <[email protected]>
Squad logos are drawn with a material depth bias of 1 so they sit on top
of the hull. Under Vulkan the bias was written to the dynamic state but
the pipeline was built with depth bias disabled, so it never applied.
applyMaterial now calls vulkan_zbias with the material's bias before
building the pipeline config, the same way opengl_tnl_set_material calls
gr_zbias.
vulkan_zbias also passed its two values in the wrong order:
glPolygonOffset takes (slope factor, constant units) while
setDepthBias here takes (constant, slope).
Co-authored-by: Dustinspace217 <[email protected]>
vulkan_calculate_irrmap ended the swap chain render pass first and then
had four early returns (pipeline, UBO create, UBO allocate, UBO map)
before resumeSwapChainPass, so any of those failures left the rest of
the frame recording draws outside a render pass. End the pass only after
the setup that can fail.
Co-authored-by: Dustinspace217 <[email protected]>
A BLAS was destroyed immediately when its model was unloaded or when the
vertex heap grew and the BLAS had to be rebuilt, while the TLAS of a
frame still on the GPU could reference it by device address. Queue the
acceleration structure and its buffer on the deletion queue instead, the
same way ensureTlasCapacity already retires the TLAS. The deletion queue
is flushed after ray tracing shuts down, so shutdown defers too.
A built TLAS also kept pointing at retired BLASes for later frames: the
live shadow TLAS binding is only refreshed when a mission frame rebuilds
it, and buildTlas keeps the previous TLAS when it has no instances. With
ray-traced shadows on, flying a mission and then leaving and re-entering
the tech room (which frees every model on exit) bound such a TLAS on
every tech room frame. So when BLASes are retired, the built frame TLASes
are retired with them and the binding goes back to the empty fallback
TLAS until the next rebuild. onModelUnloaded reports whether it retired
anything, so the binding refresh only runs then.
Co-authored-by: Dustinspace217 <[email protected]>
The runtime shader compiler cached SPIR-V on disk without checking the
write, and accepted any cached file whose size was a multiple of four.
A file cut short by a crash or a full disk was handed to the driver as a
shader module. With half-length cache files in place, master crashes in
the NVIDIA driver on entering SM1-01 under -vulkan.
Cached files are now checked before use: the SPIR-V magic word, and the
instruction word counts must end exactly at the end of the file on an
OpFunctionEnd. A file that fails is logged, recompiled and rewritten.
Fresh compiler output is checked the same way before it is cached, so a
module the check would reject is never written, and the log says so.
New cache files are written to a temporary file unique to the writer and
renamed over the old .spv only after a complete write and close, so a
game crash, or a second game writing the same shader, never leaves a
partial .spv. A power loss still can; the read check catches that.
purgeOldCache now also removes old temporary files.
Co-authored-by: Dustinspace217 <[email protected]>
The default-material shader transforms each vertex by the model matrix
before testing it against the clip plane. Vulkan always passed the
identity, so a clip plane given in world space (for example the warp
plane on a squad logo) was tested against model-space positions. OpenGL
passes gr_model_matrix_stack.get_transform(); do the same here.
Co-authored-by: Dustinspace217 <[email protected]>
Under Vulkan a mission's $Environment Map was never uploaded: the
irradiance and lighting passes only use ENVMAP when its texture slot
already has an image view, and nothing created one for a bitmap that was
only bm_load'ed. OpenGL uploads it the first time it binds it as a
cubemap.
Add VulkanTextureManager::ensureCubemapUploaded(), called from both
passes. It locks the map the way OpenGL does for TCACHE_TYPE_CUBEMAP.
The lock uploads through bm_data(), which now sends uncompressed DDS
cubemaps (bm_is_compressed() returns 0 for them; comp_type identifies
them) to uploadCubemap() as DXT ones already went. If the slot still
holds no cube after the lock, because the data was already resident, it
uploads it directly. A map that cannot be used is remembered by bitmap
signature (handles are reused across missions) and warned about once in
debug builds, and the irradiance pass is skipped instead of sampling a
non-cube view.
uploadCubemap() also assumed uncompressed cubemaps had one mip level and
read the six faces back to back. DDS stores face0[mip0..mipN],
face1[...], so faces 1-5 read the tail of face 0's mip chain. It now
uses the file's mip count, expands 24-bit data over the whole chain,
generates a chain for a one-level uncompressed cubemap as OpenGL does
(the lighting pass samples by roughness), copies mip 0 for every array
layer, cleans up the image when the staging map fails, and clears
isCubemap as soon as it retires the old image.
Co-authored-by: Dustinspace217 <[email protected]>
A mission's $Environment Map is used as a cubemap without checking. Naming
an ordinary 2D texture made OpenGL copy six faces out of a one-face image
and crash when the mission started (issue #2245). Check the loaded bitmap
with a new bm_is_cubemap(); if it is not a cubemap, warn, release it and
build the generated environment map, as for a mission that names none.
DX10 (BC7) DDS files carry no cube flag through the loader, so they are let
through unchecked, as before.
Co-authored-by: Dustinspace217 <[email protected]>
* Vulkan: bind all four model-matrix attribute locations for decals
The Vulkan shader input mask had one bit per listed attribute, so the
pipeline dropped the MATRIX4 attributes at locations 9-11 and the decal
vertex shader read three of its four instance-matrix columns from unbound
inputs. No decal was ever drawn in Vulkan.
The mask now covers four locations for VATTRIB_MODEL_MATRIX. It is built
by shader_vertex_input_mask() in shader_types so both Vulkan call sites
share it and a unit test covers it without a Vulkan build.
Fixes#7866
* Vulkan: build the decal pipeline with the material's shader flags
The decal pipeline config set the shader type but not the flags, so the
decal shader variant was always compiled without USE_NORMAL_MAP and fell
back to screen-space derivative normals for angle rejection. Far more of
the decal volume passed the angle test than in OpenGL, which lit the
decals brighter and wider. The pipeline now takes the flags the material
reports, as the other draw paths already do.
* Review fixes: exact input-mask test, decal flag polarity test, mask width check
Pin the full mask per shader type instead of the presence of the matrix
bits, so an expansion of any other attribute fails; pin that a decal
without a normal map is the one that reads the scene normal buffer; add a
compile-time bound on the mask width; trim two comments.
---------
Co-authored-by: Dustinspace217 <[email protected]>
* qtFRED: rotate around the centre of a multi-selection
Rotate Around Object (Alt+R) and the orbit pivot both used the current
object's position, so with several ships marked the camera still
circled whichever one happened to be current. Add
EditorViewport::selectionCenter(), which returns the centroid of the
marked objects when more than one is marked and the given object's
position otherwise, and use it at the three places that chose the
point: the look-at camera update, orbitCameraGetPivot(), and the Alt+R
handler that turns the camera toward the target when the mode is
switched on.
orbitCameraGetPivot() also serves middle-mouse orbit and wheel zoom in
normal mode, so those pivot on the selection centre as well. Every
marked type counts at full weight, including waypoints and jump nodes.
With a single object marked nothing changes.
Fixes#7724
* Make EditorViewport::selectionCenter const
It only reads the marked-object list and the editor's marked count;
clang-tidy (readability-make-member-function-const) flagged it in CI.
* Mirror the multi-selection orbit pivot to FRED, trim comments
FRED gets the same selection_center() as qtFRED's selectionCenter(),
used at the same three places: the look-at camera update, the orbit
pivot, and the Rotate Around Object toggle. Also removes the qtFRED
comments flagged in review.
* Make the selection-center pivot optional and share object bounds
Look-at and orbit use the current object again unless the new option is
on (qtFRED: Preferences > Controls; FRED: View menu), and the selection
center is now the bounding-box midpoint. view_universe in both editors,
the pivot, and qtFRED's selection radius all use get_object_bounds() in
missioneditor/common.
* Reset the cached orbit pivot when the selection-center option changes
Wheel zoom reuses the orbit pivot until the camera moves, so without this
the option only took effect for scrolling after the next camera move.
* Address review: move and rename the selection-centroid option
- FRED: the option moves from the View menu to Settings (and Misc in the
classic layout), under Move Ships When Undocking, with hover help, and is
renamed Rotate Around Selection Centroid.
- qtFRED: the checkbox moves next to Move Ships When Undocking in the
preferences dialog, with the same name.
- setOrbitSelectionCenter only resets the orbit when the value changes.
- get_object_bounds iterates with list_range.
- The bounds test resets the object system with obj_init and takes objects
off the free list, so it leaves a valid state for other tests.
* Rename the option to Selection Midpoint, move it to qtFRED's Controls tab, and document it
* Fix overlapping Appearance rows in qtFRED Preferences, realign a settings line
The last commit renumbered the Viewport label size row of the Appearance
group from 4 to 3, which is the Long list menu style row, so the label
size pair fell out of the layout and its spin box drew over the group
title. Put it back at row 4.
---------
Co-authored-by: Dustinspace217 <[email protected]>
* 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]>
* Make cfread_string_len read no more than fits in the buffer
The char* version only checked the stored length with an Assertion, so in
release builds a string longer than the buffer was read past its end, and a
negative length wrote before it. It now reads at most buffer_size - 1
characters, skips the rest so the next read stays aligned, always terminates
the buffer, and logs when characters are dropped.
The SCP_string version clamps a negative or past-the-end length to what the
file still holds, so a corrupt length can't cause a huge allocation.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* Warn when cfread_string_len cuts or rejects a string
The char* version now reads up to the full buffer, so a string that fills it
exactly without a terminator is caught rather than cut silently. Both versions
clamp the stored length to what the file still holds and check the read limit
before reading, since cfseek does not; inside a limited pilot section a corrupt
length, negative or too long, throws cfile::max_read_length so the loader can
drop the section. A cut string, a corrupt length or a failed read gets a
Warning, and a failed read no longer leaves the file position off by the bytes
it did read. A buffer size of 0 skips the string without writing to the buffer.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* Write the cfread_string_len warnings inline with format arguments
* Share one core between the cfread_string_len overloads
Both overloads now read the length, work out what is stored, read the
body and warn through the same three steps. A length that does not fit
the file throws inside a limited section even when the section ends at
the end of the file, a zero-size buffer still warns about a corrupt
length, and a cut-off length field warns (or throws inside a limited
section) instead of reading as an empty string.
* Share cfread's read-size check with cfread_string_len
The string reader had its own copy of the read-limit check, without the
clamp to end-of-file that cfread does first, so a truncated last section
threw where it used to load. Both now call cf_check_read_size. A negative
length still throws inside a limited section, a cut-off length field only
warns, the cut warning counts bytes, and the helpers sit in an anonymous
namespace.
* Keep cfread_string_len quiet at a clean end of file
A string read at a clean end of file now returns an empty string without a
warning, as cfread_int does; a length field cut partway still warns, so a
truncated pilot list no longer raises one warning per remaining entry. A
zero-size buffer warns when it drops a string, and an invalid file reads as an
empty string again. Adds tests for an empty string inside a limited section,
the one-short boundary, a length still past the limit after the clamp, a
length field cut by the limit, the string returned after a failed read, and
cfread at end of file.
* Warn when a length field is missing before the end of a file
A failed length read now counts as a clean end of file only when cfeof says
so, so a file whose recorded size is larger than its data still warns. Tests
now pin the read-limit check after the end-of-file clamp, cfread at the end of
file past the limit, a length field cut short on disk, the zero-buffer
Assertion in Debug, and an empty string into a zero-size buffer.
* Close the test file before removing it in the cfile temp-file guards
Windows cannot delete an open file, and a failed ASSERT returns with the
file still open, so the guard now closes it first.
---------
Co-authored-by: Dustinspace217 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
A new pilot, or one whose last ship isn't in the current mod, has no last
flown ship. create_default_player_ship() then shows a popup and returns an
error; release builds carry on with the mission's own player ship, but
debug builds asserted. Drop the assert so both builds behave the same.
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.
* GLES Shaders and Vulkan Clip fallback
* clip fallback: change defined name, set from engine side and invert usage
* Proposed changes and fixes
Fixed:
-The OpenGL ES option stays on when OpenGL is off (issue #7984)
-Missing precision in copy-f, volumetric-f and smaa-resolve-f
-msaa-f including z-compress before precision quantification
-missing float literals in volumetric-f
-Fixed decals blending
-Restored glBindFragDataLocation() for use in legacy external shaders
-Enabled GL_ARB_explicit_attrib_location ext for GLSL version below 330 in GL
-Guarded enabling/disabling of GL_CLIP_DISTANCE0_EXT and GL_DEPTH_CLAMP
-Restored PI in lighting.sdr
-removed "External shaders only" indication from cmakelists.txt
A new pilot, or one whose last ship isn't in the current mod, has no last
flown ship. create_default_player_ship() then shows a popup and returns an
error; release builds carry on with the mission's own player ship, but
debug builds asserted. Drop the assert so both builds behave the same.
Two subsystem handles are equal when both are valid and refer to the same
subsystem on the same ship. Invalid handles compare as not equal, matching
the other handle types.
The jump node dialog only copied control text into its member variables
in OnClose(), so update_data() calls from selection changes, saves, and
the dialog's own node menu applied stale values and discarded the edit.
Call UpdateData(TRUE) inside update_data(), as the waypoint path dialog
does. This regressed when the dialog was split out of the waypoint
dialog in 78b957982.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* fix FastDebug QtFRED linking the debug CRT
FastDebug builds in the DLL-runtime tree (used whenever qtFRED is
enabled) compiled with /MDd and, since #7450, linked Qt's debug
libraries. Both import ucrtbased.dll, MSVCP140D.dll and
VCRUNTIME140D.dll, which Microsoft does not license for redistribution,
so end users could not run the FastDebug qtFRED shipped in nightlies
and releases. Static Qt is ruled out by the LGPL, so the only shippable
shape is the release CRT plus release Qt.
On MSVC, _DEBUG is the CRT's own contract: /MTd and /MDd define it
themselves, and the STL headers select msvcprtd.lib and
_ITERATOR_DEBUG_LEVEL=2 from it. Stop force-defining it for FastDebug
on MSVC; the engine keys its debug behaviour on NDEBUG, and the few
_DEBUG guards in code/ are switched to NDEBUG so they keep working.
The static tree is unchanged: /MTd still defines _DEBUG there.
Fixes#7915
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* derive the MSVC runtime choice once
The "DLL runtime or not" condition was spelled out in the toolchain and
twice in fred2 with "keep in sync" comments, and gtest_force_shared_crt
and antlr4's WITH_STATIC_CRT had already drifted: they only looked at
MSVC_USE_RUNTIME_DLL, so a qtFRED tree with tests enabled would have
asked both for the static CRT. That is harmless today only because our
flag strings carry no literal /MD for them to rewrite.
Compute FSO_MSVC_RUNTIME_DLL once in toolchain-msvc.cmake and use it
everywhere. InstallRequiredSystemLibraries deliberately stays keyed on
MSVC_USE_RUNTIME_DLL: the qtFRED deploy ships no compiler runtime.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* remove FastDebug runtime leftovers
The /MD -> /MDd substitution on the FastDebug flag strings has done
nothing since the runtime moved to CMAKE_MSVC_RUNTIME_LIBRARY: the
Release flags it copies contain no runtime switch. The commented-out
_ITERATOR_DEBUG_LEVEL=0 lines for gtest and the OpenXR loader belong to
the scheme #7450 removed from the toolchain.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* use the release CRT for all FastDebug builds
Microsoft's documentation marks the static debug libraries (libcmtd,
libucrtd, libvcruntimed) "Not redistributable" and states that debug
versions of an application may only be copied to machines used for
testing, and the license grants distribution rights only for code on
the REDIST list, which contains no debug library in any form. So the
statically linked FastDebug game and FRED2 are no more shippable than
the /MDd qtFRED was.
Link every FastDebug build against the release runtime. The engine's
debug behaviour keys on NDEBUG, which FastDebug still leaves undefined,
so asserts, warnings and mprintf are unaffected; only the debug CRT's
heap checking goes, and that remains available in Debug builds. FRED2's
static MFC library follows the CRT: the debug variant requires the debug
runtime.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* keep the debug icon, version flag and FRED2 asserts without _DEBUG
The resource compiler only ever sees the explicit definitions, so with
_DEBUG no longer defined for FastDebug the game lost its debug icon and
both editors lost the VS_FF_DEBUG version flag. Key those on NDEBUG,
which FastDebug still leaves undefined.
FRED2 also used MFC's ASSERT, VERIFY, ASSERT_VALID and TRACE0, which are
all compiled out without _DEBUG. Convert them to the FSO equivalents
FRED2 already uses nearly everywhere else: Assert, Verify, a null check
in place of ASSERT_VALID (AssertValid only exists in debug MFC), and
mprintf. The AssertValid/Dump overrides and DEBUG_NEW stay under
_DEBUG, as they must.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
---------
Co-authored-by: Claude Fable 5.1 <[email protected]>
Vulkan never read the material's texture addressing, so MR_FORCE_CLAMP
skyboxes were sampled with a wrapping sampler, producing seams. Set it
on every material draw, as OpenGL does in opengl_tnl_set_material().
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Lower Vulkan version requirement to 1.4.304, which should be the lowest
version supported without requiring code changes. This should also offer
out of the box support on current Linux distros, such as Debian 13 (trixie)
and Ubuntu 25.10 (questing) & 26.04 (resolute).
Also make sure that the shaderc headers are available and added to the
include path on Linux when using system libraries.
The game pauses when its window loses focus. With in-game options on, that is
governed by the Game.UnfocusedPause option (default on), and the legacy
-no_unfocused_pause flag is ignored, as other legacy flags are. An unattended
run started with -noninteractive therefore stopped as soon as another window
was in front, for example when several test instances run side by side.
-noninteractive means nobody is at the keyboard to resume the game, so
pause_if_unfocused() now returns false for it. This covers all three focus
paths (game_poll, game_pause, game_unpause). Interactive runs are unchanged.
Silence CMake build type warnings when using a multi-config generator.
Fix macOS deployment target specification. It must be set before
the first project() command to work properly, and needs to be a cached
value so that it can be overridden by the user. This in particular is
required for Xcode 27 where the minimum deployment target is 12.0 and
using anything less is a hard fail rather than a warning.
Fix Xcode scheme only containing qtFred as a buildable target.
Fix various Xcode warnings when a static library contains files without
any symbols.
Allow FSO/qtFRED cmdline arguments and working directory to be set via their
respective options (FSO_RUN_ARGUMENTS & FSO_FREESPACE_PATH) in Xcode.
Fix product identifier mismatch and unset minimum system version warnings
in Info.plist file.
* only strip the legacy M/S suffix from the last pilot when needed
player_select_get_last_pilot_info() chopped any trailing uppercase M or S
from the LastPlayer value, a holdover from the pre-pilot-file era. Pilots
whose callsigns end in M or S (e.g. BOSS) were never found as the last
pilot. Now the suffix is only removed when the full callsign is not a
pilot but the shortened one is. This also avoids indexing before the
string when LastPlayer is empty.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* route all pilot selection through one commit function
player_select_close() and player_finish_select() each had their own copy
of the code that loads a pilot as the active Player, and the copies had
drifted apart. Both now call player_select_commit_pilot().
This fixes two bugs:
* -pilot did not work with the retail pilot select screen.
player_finish_select() loaded the requested pilot, but then
player_select_close() loaded the highlighted pilot (the most recent
one) over it. The close handler now skips the load if a pilot has
already been committed.
* player_finish_select() ignored its is_multi parameter when setting
player_was_multi, so scripted selection of a multiplayer pilot saved
it as single-player.
Scripted selection also now saves the pilot file, as the retail screen
already did. The background bitmap handle starts out as -1 so that the
close handler doesn't release bitmap 0 when the screen was never set up.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* select pilots automatically at game init, through the normal commit path
-startgame, -connect and -almission (via Cmdline_use_last_pilot) used
player_select_get_last_pilot(), which loaded the last pilot directly
without most of the setup that a normal selection does. It skipped
valid_pilot(), multi_options_init_globals() and saving the pilot file.
Because it never entered the pilot select state, it also turned off the
main hall's fallback for an unavailable campaign. Meanwhile -pilot and
-benchmark_mode were handled on the pilot select screen itself, which
scripted UIs replace entirely.
All of these now go through player_select_try_auto_select() at
GS_EVENT_GAME_INIT. It picks the -pilot callsign, else the last pilot
if it still exists, else the most recently saved pilot. It shows the
startup warning popups, validates the pilot, and commits it through
player_select_commit_pilot(). The pilot is multiplayer if -startgame or
-connect was given, and single-player otherwise. If there are no
pilots, or validation fails, the pilot select screen is shown as usual.
The main hall now allows the campaign fallback whenever a pilot has just
been committed, not only when coming from the pilot select state.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* select a pilot automatically for -start_mission
-start_mission skips the main hall, but it still waited on the pilot
select screen. It now uses the same automatic pilot selection as the
other quickstart options, so the screen only appears if there are no
pilots. The pilot is committed as single-player, consistent with the
main hall forcing single-player mode for -start_mission.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* skip the intro movie for quickstart options
When the command line asks to skip pilot selection (-start_mission,
-pilot, -startgame, -connect, -almission, -benchmark_mode), the intro
movie now doesn't play either. It could take several minutes before the
game even reached the pilot. The OnIntroAboutToPlay hook still runs, as
it does when the mod table disables the intro.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
This should be a safe minimum for us when system libraries are either
required or preferred. Most current Linux distros that have SDL3 should
support this version or better.
* 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]>
During phase 1 of the FS2 ship/weapon select animation, the wireframe
is supposed to be revealed as the scanline moves down. That relied on
the clip plane set up for the grid carrying over to the wireframe
render. 90a2676f1 replaced the grid's clip plane with line trimming,
which left the phase 1 wireframe unclipped, so it popped in all at once.
Clip the wireframe in both phase 1 and phase 2.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The actively-pursues filter added to "$fix ai target recovery:" in #7736 was applied to every target search. But a ship's target is not only used for pursuit: it also drives the ship's turrets, other ships' guard reactions, and attacker counts. In retail SM1-04, the friendly Knossos (which does not pursue fighters) was made to target the Behemoth instead of a Mara, which caused the Mara guards to react to the protected Knossos endlessly instead of rushing the player.
The filter now applies only where the target is chosen for maneuvering:
* find_enemy() and get_nearest_objnum() take a required for_pursuit parameter; automatic searches pass ai_targets_for_pursuit(), which is true only in AIM_CHASE or AIM_STRAFE
* guard reactions, retaliation (dynamic chase), and the retargets in ai_big_chase_attack() and ai_big_maybe_enter_strafe_mode() skip ships the attacker won't pursue, via the new ai_declines_pursuit()
* ai_attack_wing() prefers living wing members the ship will pursue; if there are none, it holds a member as an explicit order to attack an unpursued ship does
* get_nearest_objnum() holds an unpursued member of the enemy wing rather than leaving the wing
Since refused targets are no longer picked for pursuit, ai_chase() no longer needs to drop them. Retail behavior is unchanged when the flag is disabled.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Several ai_info fields remember which order set them up (enemy_wing,
guard_objnum/signature/wingnum) or which mode a dynamic goal interrupted
(previous_mode, resume_goal_time), but nothing cleared them when a new
order took over. A ship that once guarded a wing would be yanked back
into AIM_GUARD whenever a wingmate died; a stale previous_mode of
AIM_GUARD could make a former guard abandon a counterattack; a stale
enemy_wing biased every find_enemy() toward a long-ago target; and a
resume_goal_time left over from a dynamic chase suppressed target
acquisition for up to 20 seconds into the next order.
Add ai_reset_order_state(), called when ai_process_mission_orders()
takes up a goal and when ai_do_default_behavior() runs. Each order's
own setup repopulates the fields it needs. enemy_wing is reset under
either $fix stale ai order state or $fix ai target recovery, since it
affects target selection; the rest only under the new flag.
maybe_set_dynamic_chase() wrote aip->mode into previous_submode, a
retail typo that left previous_mode untracked for dynamic chases. Under
the flag, save both fields properly, but not when a dynamic goal is
already in progress, so a nested interruption does not clobber the mode
to return to. Apply the same guard to the strafe/chase transitions in
aibig.cpp.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The load screen background was drawn in the fixed 1024x768 layout, so an
image larger than that overshot the screen and only a corner was visible.
Set the screen scale to the background's dimensions, as the main hall and
title splash already do, and draw the loading animation in the same
layout.
The loading animation is assumed to match the default loading background
(or the default layout, if there is none). That reference is fit into
the mission's background the way menus are fit into the screen: scaled by
the limiting dimension and centered in the other. So a mission can use a
background of any resolution or aspect ratio without the animation
changing size or position relative to it. Retail assets behave as
before.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
On a HiDPI monitor with OS scaling, every Qt widget in qtFRED scales
but the ship labels, waypoint labels and coordinate readout drawn by
the engine inside the viewport do not, because the engine draws them in
physical pixels. At 200% they come out half the size of everything
around them.
FredRenderer already receives the window's device pixel ratio as the
scale argument of render_frame(). Remember it there and multiply it into
the label font scale at every label site, so the user's Preferences
value stays "100% = normal size on screen" regardless of OS scaling.
Fixes#7727
The warning fired for any 3D shockwave model without a glow map, but it turns out that situation is fine. Drop the warning along with the cmdline include it required.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
get_ship(), get_wing(), get_object() and get_parse_object() only assigned
their out-pointer on success. When a lookup failed (no bytes left, or a net
signature that no longer resolves, e.g. a ship destroyed before the packet
was processed) the caller's uninitialized local was left as stack garbage,
so its nullptr check could pass and the next line would write through it.
multi_sexp_set_camera_target() used the object without checking at all.
Set the out-pointer to nullptr up front, so every caller's existing nullptr
check works. This also clears the C4701/C4703 "potentially uninitialized"
warnings MSVC 2026 reports for the callers in sexp.cpp when it inlines these
getters at link time.
The failure checks after parsing (bad detail levels, debris objects or
parents, and too many textures) run after the TXTR and GLOW chunks have
already loaded bitmaps, but model_load only deleted the polymodel, so
those bitmap slots were never released. Page out the textures and free
the model through model_free, as the virtual POF cache already does for
models it loads.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Retail models (111 of them in sparky_fs2.vp) store -1 as their cross
section count, meaning none, which the original loader silently accepted.
Routing the count through pof_read_count made every such model warn on
load. Read it directly and floor it at zero, as before.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A virtual POF ignored the load status of its base POF, so a base that
failed to load (missing, bad version, or rejected after parsing) was
still built upon and reported as a successful load. Likewise, every
operation that copies from another POF used it even if that POF had
failed to load.
Return FAIL from read_virtual_model_file when the base POF fails, and
have the operations skip, with a warning, any source POF that failed.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
When appending submodels would take the combined POF past
MAX_MODEL_TEXTURES, the limit was only noticed partway through, after the
submodel array had been grown, subsystems copied, and n_textures
incremented past the limit, which later loops over maps[] then overran.
Work out the texture mapping first, and give up before touching the model.
Also skip the -1 texture id of untextured flat polygons, which was being
assigned a texture slot, and which replace_textures_used then used to
index Num_verts and Num_polies.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Clamping the TXTR count keeps maps[] safe, but texture indices are baked
into the BSP data, so a model declaring more than MAX_MODEL_TEXTURES
textures cannot be built correctly. Keep the clamp so that the chunk is
still read in full, then fail the load after parsing.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
process_tmap and process_tmap2 used the texture index from the BSP data
to index Num_polies and Num_verts without checking it, so a corrupt
model wrote past both arrays while its vertex buffers were built. The
collision tree parser already treats such an index as a fatal error, but
it runs afterward. Raise the same error here, and skip the polygon in
case the error is continued past.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The post-parse sanity checks and the bad-version check returned FAIL
without closing the POF. Nothing reads the file after the chunk loop, so
close it there, and close it before the bad-version return too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
MSVC 14.50 (v145) no longer targets Windows 7, 8, or 8.1, so building
with it would quietly drop those platforms. The VS 2026 runner images
include the v143 compiler but ship ATL and MFC only for the latest
toolset, and both are needed: ATL by SAPI speech (sphelper.h) and MFC
by FRED2. Install the 14.44 ATL/MFC components before configuring and
keep building with v143, matching the 26.0 release.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
All default Windows runners should now be moved over the Visual Studio 2026,
with the exception of windows-2022 (which may be retired before long). So
move to windows-2025 and update the CMake generator to use vs2026 as well.
Directional, point, and cone lights left local_vec, local_vec2, and some of
the type-specific fields uninitialized until something rotated or set them.
The sun copies in Static_light were never rotated at all until the previous
commit, so light_apply_rgb's sun term read uninitialized memory. Zero every
field up front, which also covers what the tube light did by hand.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
light_apply_rgb works in the model's local frame, but nothing rotated the
lights into that frame before insignias were drawn: light_rotate_all() was
only called for the briefing and tech room lights, and even then it skipped
Static_light, the separate copies of the sun lights that light_apply_rgb
reads. So the sun term used a stale, never-set direction and the point
lights were treated as if they sat at the model's origin.
Rotate the lights, including the sun copies, once the insignia's instance
is set up, and light each vertex at its actual position, which includes
the insignia's offset.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
In debug builds, subsystems found in a model but missing from ships.tbl
are meant to be dumped to data/tables/<model>.subsystems as stub table
entries. Since subsystem matching was deferred until after the model
file is read (#4590), the dump file was already closed by the time
do_new_subsystem ran, so it was always empty and deleted. Worse, ss_fp
was left pointing at a closed CFILE slot, which another file could reuse
before do_new_subsystem wrote to it, and the dump file leaked whenever a
load failed.
Open the dump file on the first unmatched subsystem instead, and close it
once the deferred subsystems have been matched. This also means no file
is created and deleted for models without unmatched subsystems. Reset
the once-per-model warning flags there as well, rather than only when
the dump file opened successfully.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The insignia normal array was declared with the vertex limit, filled in by
face index, and read by vertex index. An insignia with more than 81 faces
therefore wrote past the array, into the following insignia or, for the
sixth and final slot, past the insignia list into the rest of the
polymodel. And the renderer lit each vertex with the normal of whichever
face shared its index, or with a zero normal (ambient light only) when
there was no such face.
A normal belongs to a face, so size the array by the face limit and light
all three corners of each face with that face's normal.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A subobject that named itself, or one of its own descendants, as its parent
made the depth walk loop forever, and would have done the same to every
later walk up the hierarchy. Since each SOBJ chunk adds only one link, any
cycle must lead back to the subobject being read, so detect that during the
walk and treat the subobject as parentless.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
When a ship flying into a fighterbay has to route around the carrier,
create_model_path puts tangent and bisect points ahead of the bay path.
The departure speed ramp treated the first point of the AI path as the
start of the bay path: it started once the ship passed that point and
measured the path length from there. On a detoured path the ramp
therefore began slowing the ship while it was still flying around the
hull, and the ship entered the bay slower than intended. The ramp
fraction was also not clamped, so the target speed could exceed max
speed.
Under the new ai_profiles flag "$fix fighterbay speed ramp:"
(Fix_bay_speed_ramp), the departure ramp starts at the first point of
the bay path itself and the ramp fraction is clamped to [0, 1]. The
flag is enabled by default for mods targeting 26.2.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Settings in game_settings.tbl were logged as they were parsed, so a setting was only logged if it appeared in a table. A setting enabled through $Target Version was never logged, and a setting that appeared in more than one table was logged once per table, possibly with different values.
The settings are now logged by mod_table_log_settings, which runs at the end of mod_table_init. The version-gated settings that previously had no log line now have one: framerate independent turning, scripted velocity, asteroid bounding box checks, the expensive turret target check, skybox depth consistency, zero-radius explosions, and insignias as decals.
Messages that describe the table text itself, such as deprecated options, removed file extensions, and out-of-range values, are still logged at parse time.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[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]>
set_accel_for_docking took the model path from the first point of the
AI path. When a departing ship has to route around the carrier,
create_model_path prepends detour points whose path_num is -1, so the
path name was read from pm->paths[-1]. That usually yields junk and a
missed metadata lookup, but crashes when the memory before the paths
array is unmapped. Use aip->mp_index, which both bay path builders set
to the model path index.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
When the ship a path leads into moves, modify_model_path_points
re-globalizes the path's model points in place.
It always rewrote nverts points, but create_model_exit_path can build
a path with fewer, in which case the rewrite would run past the end of
the path into Path_points entries that may belong to other ships. No
current caller builds such a path, but the rewrite now covers only the
points the path actually holds.
A subsystem path gives its second-to-last point a random offset when
created, but the refresh did not pass that point back in, so the
offset was lost the first time the target moved. Record the
randomized vertex in ai_info and, under the new ai_profiles flag
"$fix subsystem path randomization on refresh:"
(Fix_model_path_refresh_randomization), reapply it on refresh. The
flag is enabled by default for mods targeting 26.2.
Also rename a parameter in `get_base_path_info` (which is currently
unused) for clarity.
Co-Authored-By: Claude Opus 5.5 (1M context) <[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]>
qtFRED's team loadout dialog enabled its team combo and its copy-to-other-teams button on MISSION_TYPE_MULTI, which encompasses more than just Team-versus-Team. Gate both on Num_teams, which is what FRED's own loadout editor uses, and build the team list from the teams the mission actually has.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Add generate_ship_usage_list_team alongside the weaponry twin that already existed in missioneditor/common, so both loadout editors can drop their TVT/non-TVT branches and simply iterate Num_teams.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
An empty list such as `( )` leaves get_sexp() with no start node, but it still passed that -1 to get_operator_const() for the ai-chase-any-except compatibility check and, outside FRED, for preloading. This tripped the out-of-range assertion in debug builds. Return the empty list directly instead.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Element counts were taken straight from the file, so a corrupt POF could
supply a negative count (stored alongside a null array) or one larger than
the fixed-size array it feeds. Add pof_read_count() to floor every count at
zero and clamp it to the destination's capacity, reading past the discarded
entries where more data follows in the same chunk.
The upper bounds that were checked at all were checked with debug-only
Asserts, or with an Error() that returns if the user picks Debug, so the
overflowing loop after it was reachable in both cases.
Also validate the submodel indices in SOBJ and TGUN/TMIS, the vertex indices
in insignia faces, and bounds-check the split plane array before writing to
it rather than after.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Current_filename_sub dates back to the use of *_ex() parsing functions for parsing .eff files, which were superseded by the Bookmarks feature. Today it is entirely redundant to Current_filename. A read that throws now leaves Current_filename naming the file that failed, rather than the file parsed before it, as it should.
Also clear Current_filename in stop_parse, so that a warning issued between the end of one parse and the start of the next no longer blames the last file parsed, and null out Mp there so it stops dangling into the freed parse buffer. Also delete the vestigial Mp_save.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
* Fix QtFRED root notifications when inserting nested operators
Only emit rootNodeFormulaChanged when the wrapped node is a formula
root. Inserting above a nested expression previously reported a child
as an event, goal, or cutscene root, causing assertions and out-of-bounds
accesses in the receiving dialog model.
Co-Authored-By: OpenAI Codex
* Give each QtFRED ship independently owned arrival and departure cues
Pass the tree model to the cue update handlers and serialize a separate
expression for each eligible ship. Sharing one formula across selected
ships caused double frees on subsequent edits and left other ships
referencing freed nodes when only one ship was changed.
This also avoids allocating unused expressions when cue updates are
disabled or no selected ships are eligible.
Co-Authored-By: OpenAI Codex
* Synchronize QtFRED item editability after SEXP node changes
Update native Qt editability alongside the shared model flags so
variable and container references cannot be edited as plain text.
Restore inline editing when a reference is replaced with ordinary data,
and preserve item flags when moving or copying branches.
Reject edit requests for protected items before setting the editing
state, preventing later programmatic changes from being treated as
user edits.
Co-Authored-By: OpenAI Codex
When parsing a SEXP, a variable reference's node type was decided solely by whether it was quoted: "@Var" became a string variable and @Var a numeric variable, regardless of how the variable was declared. A hand-edited SEXP with the wrong quoting therefore produced either a misleading "Not a number" error or a silently mistyped node that was saved back with the wrong quoting.
get_sexp now takes the node type from the variable's declared type, and flags a reference whose quoting contradicts it. check_sexp_syntax reports such references (or any variable node whose type disagrees with its variable) as the new recoverable error SEXP_CHECK_VARIABLE_TYPE_MISMATCH: FRED flags it, and the game warns but still loads the mission, which runs correctly because the node type has been corrected. Saving from FRED writes the corrected quoting.
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Check each 3D shockwave model when it is loaded and warn if none of its textures has a glow map. The check is skipped when glow maps are disabled, since they are not loaded then.
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
The overflow flag and screen position were read from a temp vertex
already returned to the pool, which only worked because nothing
allocated in between. Copy them out first.
The clamps that keep the indicator away from the top and left of the
clip rectangle subtracted the clip origin instead of adding it, and
dropped it from the clamped value. Inert while the origin is zero, but
wrong for any other clip rectangle.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
A 3D shockwave's glow map already takes its frame from the shockwave's
elapsed time so the animation spans the shockwave's life. Do the same
for an animated base texture, and skip the radius fade for it, since the
artist's frames then control the brightness the way they do for the glow.
A static base texture still fades with the radius.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Models drawn without lighting under deferred rendering copy their base
colour into the emissive buffer and zero the ambient occlusion factor,
but still write their real diffuse and specular data to the G-buffer.
Each direct light then adds diffuse and specular on top of the emissive
copy, and the environment map adds its specular term, so the "no
lighting" flag only appeared to work in dark scenes.
Zero the diffuse and specular outputs after the emissive copy. The
specular alpha is the Fresnel factor, so clearing the whole vector also
removes the grazing-angle sheen.
Fixes#3999
Co-Authored-By: Claude Fable 5.1 <[email protected]>
3D shockwaves pass `1 - radius/outer_radius` as the warp alpha, which `model_render_determine_color` turns into the material colour for additive draws. Since a481999a2 (SamuelCho's OpenGL Code commit in August 2016), the model fragment shader has not multiplied the diffuse sample by that colour in the unlit branch, so the base texture stayed at full brightness and vanished abruptly. The same path carries the warp effect's radius fade and the alpha of unlit transparent weapons.
Clamp the alpha before converting it to a byte, as the pre-2016 code did; thrusters pass 1.2, and without the clamp they would now render dim.
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]>
Neither editor had a teardown to match FSO's game_shutdown(), so the engine
data they set up was never freed. Add editor_free_engine_data() to free it,
and call it from a new fred_shutdown() in FRED and from qtFRED's shutdown(),
before the graphics system closes.
Also:
- Delete FRED's modeless editors if they are still open at exit.
- Make FRED's dialog tooltips and sexp tree image lists members, since
they were leaked or depended on OnDestroy() being called.
- Parent qtFRED's item models so they are deleted with their widgets.
- Enable the CRT leak report in qtFRED, which previously had none.
- In qtFRED, call shutdown() last in closeEvent(), since it destroys the
window.
- Make the preferences path and user SID strings function-level statics,
so MFC's leak dump no longer reports them as leaks.
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Bug:
"No matter what value I'm setting in default_settings table with the entry below, it doesn't affect any new pilots I create."
Cause:
The skill option's table parser only sets Game_skill_level directly. Every other place that asks for "the default" ignores it and uses the hard-coded DEFAULT_SKILL_LEVEL (1, which is "Easy"), so the tabled value gets overwritten twice:
At startup (freespace.cpp:1919-1920): default_settings_init() sets Game_skill_level from your table. Then loadInitialValues() runs right after. If Game.SkillLevel isn't saved in the ini yet, it falls back to default_func. That returned the constant 1, and bind_to wrote it back over your value.
When a pilot is created (managepilot.cpp:100): init_new_pilot() does Game_skill_level = game_get_default_skill_level(), which also just returned the constant.
This PR follows the same strategy of settings like sound volume to allow modders to specify a default setting for difficulty.
HudGaugeOffscreen::calculatePosition could return without writing its
outputs, either when the eye vertex overflowed or when the clipped
point landed a pixel or two inside the clip rectangle. The caller drew
anyway, so the indicator appeared at a random spot with a random
orientation that changed every frame. This showed up when targeting a
subsystem on a distant ship, where the clip loses enough precision to
hit the second case.
calculatePosition now returns whether it found a position, and both
callers skip drawing when it did not. The inside case falls back to
the nearest screen edge, since the point is already known to be off
screen, so the indicator stays steady instead of blinking.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The projected point was the subsystem but the stored position was the
hull centre, so the offscreen indicator sized its triangles for a
different point than the one it clipped against.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The expression used & instead of |, so neither PF_OVERFLOW nor
PF_PROJECTED was ever set on that path.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
swap_bsp_sortnorm2 swapped the bounding box at offsets 8 and 20, which
re-swapped the front list offset and left the real box (at 16 and 28)
unswapped. swap_bsp_tmap2poly never swapped the chunk's bounding box
or normal. Both corrupted models using these chunks on big-endian
builds.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
If prebuilt Vulkan was disabled, but a system-wide Vulkan install wasn't
found, then a fallback was available using prebuilt libs. Unfortunately
this does ultimately require the prebuilt libs be available which isn't
always wanted (or possible), so drop the fallback and just require Vulkan
instead.
Fixes#7786
Report leaks after static destruction via _CRTDBG_LEAK_CHECK_DF instead of calling _CrtDumpMemoryLeaks() at the end of main(), which incorrectly reported every global container as a memory leak.
Also fix the three remaining real leaks which were discovered after all the noise was cleared up:
- Mc_point_list was never freed, because its atexit cleanup was only registered by code that no longer runs. But the list was only a temporary array of pointers used while building the collision tree, so remove it and have model_collide_parse_bsp_defpoints() copy the vertices directly into the tree's point list.
- model_batch_buffer's Mem_alloc copy was never freed. But the copy is actually not necessary, so remove it and pass Submodel_matrices directly.
- Goal_target_names strings were only freed when the next mission was parsed, so the last mission's names leaked at exit. Hold them in SCP_vm_unique_ptr so they are freed with the vector.
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]>
The Linux Debug legs fail memcheck on six "definitely lost" contexts
(480 bytes in 12 blocks), all allocated under the temporary
SDL_InitSubSystem(SDL_INIT_VIDEO) in resolution_default(). SDL probes its
real video backends, dlopens libX11, and keeps a few small blocks across
the matching SDL_QuitSubSystem().
These are the same six contexts #7657 suppressed via fun:X11_CreateDevice.
That suppression stopped matching when #7774 bumped the prebuilt libs:
62c89ef6 shipped libSDL3.so.0.2.14 with a full .symtab (433 distinct X11_*
symbols), b57636e0 ships a stripped libSDL3.so.0.4.14 (none). X11_CreateDevice
is a static function, so valgrind can no longer resolve it and every libSDL3
frame prints as ???. Every PR branch based on post-bump master fails this leg.
Rather than rewrite the suppression around object wildcards, stop allocating
the memory in the first place. The unit tests never open a window and the
runners are headless, so pin SDL_VIDEODRIVER=dummy: SDL skips backend probing
entirely, libX11 is never loaded, and the leaks do not happen. It also makes
the tests behave identically whether or not the runner has a display. No test
depends on the real desktop mode; the only resolution test sets an explicit
override.
The os_init suppression stays. That leak is from SDL_Init(SDL_INIT_EVENTS)
and SDL_hid_init(), not from video, so the dummy driver does not affect it.
The X11_CreateDevice block also stays, as a backstop for running memcheck by
hand, now with a comment recording why it is inert in CI.
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Views that don't render the cockpit (external, chase, topdown, etc.) left
Cockpit_depth_texture holding the last cockpit-view frame, so the lightshaft
pass painted that silhouette. Fixes#7568.
Co-authored-by: Claude Opus 5 <[email protected]>
* Add command-line option overrides to options system
- Extend `OptionsManager` to support storing and displaying reasons for overrides.
- Update related code paths to prioritize command-line overrides, ensure correct option resolution, and display override details in the UI.
- Add unit tests for override behavior and round-trip validation.
- Remove unused legacy functions (`removeVSyncOption`, `removeWindowModeOption`) in favor of the new system.
* Add unit tests for `Graphics.Anisotropy` option validation with and without OpenGL
* Add support for associating command-line option names to `OptionsManager` overrides
- Update HDR, shadow rendering, and graphics API option overrides to include their respective command-line flag names.
- Refactor `Graphics.RenderAPI` to use the `GraphicsAPI` enum instead of raw integers for better type safety and clarity.
- Ensure Vulkan support logic and fallback behavior function correctly with the updated options system.
- Update unit tests to validate override functionality and enum-based API configuration.
* Remove unused `removeVSyncOption` function
* Apply the PR review feedback for the command-line option overrides
Delete the unit-test run artifacts that this branch committed by mistake, and
add .gitignore rules for the files that the unittests binary writes.
Give an override priority over an in-session edit again. The options UI now
shows a disabled control for an overridden option, and setConfigValue()
refuses an edit for an overridden key. Before this change, a save wrote the
edit to the config file and applied it to the bound global, but getValue()
kept returning the override. The game and the options menu then showed
different values for the rest of the session.
Add a setOverride() overload that takes a JSON value. Every command-line flag
now builds its override with json_integer, json_real, json_true, json_false
or json_pack, in place of a hand-formatted string.
Make Graphics.CockpitFOV and Graphics.CockpitFOVToggle independent of the
order in which the options manager loads them, and remove the forced override
on the player's toggle preference. The toggle listener also replaces an
identical bind_to() call that made the listener dead code.
Add 16 to the values of Graphics.MSAASamples. The -msaa flag accepts 16, so an
override with that value made printValues() report an invalid value.
Keep the render API that the caller gives to gr_init(). Only a Default value
now comes from the Graphics.RenderAPI option, so FRED and the unit tests keep
the backend that they ask for.
Make the default_func of Graphics.Shadows and Graphics.ShadowRenderMethod
return their global. A constant discarded the value that -enable_shadows and
the mod table set. Set Max_rt_shadow_local_lights to 4, because 3 is not one
of the values that the option offers.
Also: resolve -lang one time, share the render API name with version.cpp,
correct the stale comments, and add unit tests with a fixture that clears the
overrides after each test.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UGh4ZM2u4oUGSbrP122Uyr
* Fix the order-dependent crash in the MSAA option test
The test `MsaaOverrideAcceptsEverySampleCountTheFlagAllows` calls
`getValidValues()`. `Option<T>` makes a display string for each value, and the
display function of `Graphics.MSAASamples` calls `XSTR()`. `XSTR()` runs
`Int3()` if `lcl_xstr_init()` did not run before. Only `FSTestFixture` runs it,
and `Xstr_inited` stays set for the remainder of the process. Thus the shuffled
test order decided if the test passed or if it stopped the test binary with
SIGILL.
Move that one test to a new fixture that derives from `FSTestFixture`. The
fixture initializes localization, and it also clears the overrides after each
test. Refresh the comment that told that the test binary never runs
`lcl_init()`.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UGh4ZM2u4oUGSbrP122Uyr
---------
Co-authored-by: Claude Opus 5 <[email protected]>
FRED and qtFRED no longer overwrite a hand-edited arrival cue on the wing
containing the player start. The cue is editable when the wing has multiple
waves (where it governs the arrival of subsequent waves) and read-only
otherwise. Waves and threshold are now editable for the single-player
player wing, while the arrival delay remains locked; the arrival location
is editable in both editors.
Both error checkers flag a single-wave player wing with a custom cue as a
potential issue, and the engine now warns and aborts the mission load,
rather than tripping an Assert, if the player start ship was not created
at mission start.
Also fix an unguarded read of Ships[Player_start_shipnum] in both editors.
Co-authored-by: Claude Fable 5 <[email protected]>
* Safeguard divide by 0 for extra collision avoidance
Extra collision avoidance could have divided by zero, so just safeguard that possibility.
* one more div 0 failsafe
With every fixed-size weapon-class-indexed structure now converted to dynamic containers, we can finally remove the `MAX_WEAPON_TYPES` limit!
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* Automatically generate the isValid() Lua API function for handle types
If an ADE object's stored type has an isValid() member, ade_obj now registers an isValid function for it automatically. An explicit ADE_FUNC(isValid, ...) declared after the ADE_OBJ replaces the generated one, so types with special semantics (e.g. sound) keep their own. The 67 hand-written functions that merely delegated to the member are removed, and 26 types that previously exposed no isValid() gain one.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* Add ADE_OBJ_VALIDATOR for index-based Lua handles
Int-index handles (shipclass, weaponclass, team, etc.) can now declare their validity predicate with a single ADE_OBJ_VALIDATOR or ADE_OBJ_VALIDATOR_RANGE line after the ADE_OBJ. The registered validator drives the generated isValid() function and is also honored by ade_set_args when the mod table asks for nil instead of invalid objects, which previously never applied to these handles. The 19 hand-written range-check functions are replaced, and loadout_ship, default_primary, default_secondary, and support_rearm_pool_team gain isValid(). Add a validator to HudGauge while we're at it.
Also fully qualify the scripting namespace in LuaConvert.h so its templates can be instantiated from the unit tests.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
---------
Co-authored-by: Claude Fable 5.1 <[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]>
Chase view deltas are not reset on mission init, so ensure they are reset to prevent the viewing jumps that can be seen at the start of mission in chase view. Also ensure perspective and slew lock are properly resotred.
Every copied bank was written to the same array slot, so all but the last
were lost, and the slots left behind kept their zero-initialized contents.
A zeroed bitmap handle is slot 0 rather than -1, so the paging code would
then page out an unrelated bitmap.
Co-Authored-By: Claude Opus 5 (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]>
Multi-line and tabbed strings drawn with a scaleMultiplier != 1 overlapped
or misaligned because the font code advanced newlines and tabs by the
unscaled font height/tab width -- most visible in FRED's viewport labels
now that they honor an adjustable font scale.
Scale the newline and tab advance in both the rendering and measurement
paths of each backend: the NVG path (gr_string and NVGFont::getStringSize)
and the VFNT path (gr_string_old and VFNTFont::getStringSize), which also
gains tab handling. The tab width is hoisted onto the shared FSFont base
so both backends share it.
While here, pass the FSFont wrapper to gr_string_old instead of a bag of
scalars, make its font pointer const, and consolidate the
get_char_width_old externs into a single declaration in font_internal.h.
Co-Authored-By: Claude Opus 4.8 (1M context) <[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 bitmap and model handle leakage in the ship/weapon select screens, and make release symmetric with load:
* Initialize each team only once in `ship_select_common_init`
* Unload every team's map in `ss_unload_team_icons`, not just the active one.
* Add a per-team unload helper and use it in the load-all functions
Also drop the stray per-icon Cur_Anim unload, and call `wl_free_ship_class_data` before loading in `wl_init_ship_class_data`.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Convert the mission ship/weapon select screens' per-class UI state from dense MAX_SHIP_CLASSES / MAX_WEAPON_TYPES arrays to sparse containers keyed by loadout-pool membership, matching the Ss_pool / Wl_pool maps they shadow:
ss_icon_info Ss_icons_teams[][MAX_SHIP_CLASSES] -> SCP_map<int, ss_icon_info>[]
wl_icon_info Wl_icons_teams[][MAX_WEAPON_TYPES] -> SCP_map<int, wl_icon_info>[]
wl_ship_class_info Wl_ships[MAX_SHIP_CLASSES] -> SCP_map<int, wl_ship_class_info>
int Plist[] / Slist[] + manual size counters -> SCP_vector<int>
The ship-select active list is replaced outright by a vector of ship classes rebuilt on each interface sync, plus the existing scroll offset. active_list_remove() was dead code and is deleted.
Behavior fixes required by the conversion:
* wl_set_disabled_weapons now computes usability flags for the pool
weapons plus every weapon currently in a slot's banks, instead of all
weapon classes. (Bank weapons are not guaranteed pool members.)
* The two mouse-region handlers that read Plist[Plist_start+index] for
raw indices 0..3 now bounds-check against the list size (as does
ss_get_ship_class_from_list).
* wl_unload_icons and the ss unloaders early-return on a null team
pointer instead of asserting and dereferencing.
The ship side loads icons for every pool class including exhausted 0-count entries while the weapon side loads only positive counts, preserving the existing asymmetry.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Mission flags are saved to the mission file as the full 64-bit flagset value, but three issues prevented anything larger than 32 bits from being saved as intended:
* `stuff_flagset` parsed the value with `stuff_long`, where `atol` clamps anything above `LONG_MAX`
* `flagset::from_u64` cast the incoming value to `unsigned long`, truncating bits 32-63
* `flagset::to_u64` used `bitset::to_ulong` where it should use `bitset::to_ullong`
Fix these issues and add `static_assert` in the flagset functions to defend against future issues. Also use the proper UINT64_T_ARG where it should be used.
This was first triggered by `Limited_support_rearm_pool`, the first mission flag to occupy bit 31. Only mission flags are affected; the other flagset serialization paths were audited and are safe.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The giveOrder scripting function now accepts optional DockerPoint and
DockeePoint arguments for ORDER_DOCK, each given as a dockpoint name or
one-based index (matching the setDocked convention). DockerPoint refers
to a dockpoint on the ordering ship and DockeePoint to one on the target.
If only one point is specified, a compatible point is chosen automatically
on the other ship using the same dock-type precedence as the existing
automatic dockpoint negotiation. When neither is specified, behavior is
unchanged.
Fixes#7119
Co-Authored-By: Claude Opus 4.8 (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]>
The ship texture replacement dialog builds parallel per-slot arrays sized to pm->n_textures, but only populates the "main"/subtype map entries for real textures; blank and duplicate texture slots are left as empty-map placeholders (with an empty default name). The dialog constructor then force-selected row 0, and getMap()/setMap() raised a fatal error_display when "main" was absent, so any ship whose first texture slot is blank or a duplicate crashed the dialog on open.
getMap()/setMap() now treat an empty default name as a non-editable placeholder. The constructor also selects the first real texture row rather than blindly row 0.
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
- Clean up `check_sexp_syntax` to use `eval_ship` (and incidentally `eval_wing` and `eval_prop`) rather than the old lookups.
- Disable SEXP node caching while FRED is running. Also use smart pointers and fix a cache memory leak.
* Fix path that could lead to unnormalized vector
TLDR:
Within `ai_chase` the value for `predicted_enemy_pos` could remain unitialized because not every else branch was accounted for. This could lead to downstream effects and trigger unnormalized vector asserts.
More Detail:
The trigger
`predicted_enemy_pos` is declared with no initializer — `aicode.cpp:8991`
The lead-prediction gate at `9110` falls through: needs `real_dot_to_enemy >= 0.25f and target_time >= 1.0f`, and not seek-lock-with-aspect.
`ai_get_weapon` returns `nullptr` — 9125 → 7113, which bails on `current_primary_bank < 0`
Every assignment lived inside `if (wip)`, and there was no else — so the variable stayed unwritten
First read of uninitialized stack memory at 9167
Passed to `ai_chase_attack` at 9198, becomes the goal point
Target beyond 500m selects the `rvec` branch, which routes into `vm_vector_2_matrix_norm` and the `fvec` assert
Commonly this uninitialized value would result in a plausible float. In that case nothing asserts and the ship just flies at a garbage point — so this was likely causing erratic no-primary AI behavior far more often than it was crashing. The assert only fired on the subset where the residue happened to be NaN, Inf, or astronomically large.
This PR adds that final else branch, though given it's an AI change it is via flag. The flag is auto-enabled for 26.2 and onward though.
Happy to discuss!
* fix typo
* no need for flag
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]>
FRED2, qtFRED, and the shared mission save code each carried their own copy of the loadout usage builders. The weaponry pair already had shared versions in missioneditor/common; this converts those to the SCP_map<int,int> signature the editors now use, adds the missing ship builder alongside them, and deletes both editors' private copies.
FRED2's playerstarteditor/freddoc and qtFRED's Editor/ErrorChecker all call the shared functions now, following the update_custom_wing_indexes consolidation precedent. missionsave's used_pool becomes a map as well, which removes its MAX_WEAPON_TYPES stack array.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
team_data was the last persistence-adjacent structure sized by MAX_SHIP_CLASSES: four parallel ship arrays plus four parallel weapon arrays (one slot per mission-file loadout line, holding a class or a sexp variable name, and a count or a sexp variable name) with manual num_*_choices counters, plus a dense per-class weapon_required flag array. Convert all of it to the sparse-container family:
ship_list / ship_list_variables / ship_count / ship_count_variables
-> SCP_vector<loadout_entry> ship_choices
weaponry_pool / weaponry_count / weaponry_pool_variable /
weaponry_amount_variable
-> SCP_vector<loadout_entry> weapon_choices
bool weapon_required[MAX_WEAPON_TYPES]
-> SCP_set<int> required_weapons
where loadout_entry is {class_index, count, class_variable, count_variable}, with empty variable strings meaning the value was given literally. num_ship_choices / num_weapon_choices become .size().
Intentional behavior fixes, all previously latent memory errors or
data bugs:
* is_ship_assignable stored an alt ship CLASS in a variable used as a
loadout list INDEX when default_to_this_class was false, then
swapped to ship_list[class] - garbage for any mission where the two
domains diverge. It now swaps to the alt class itself, per the
evident intent.
* The default-ship fallback read ship_list[0] even when a team had
zero ship choices; it now leaves default_ship at -1, and
ss_fixup_team_data guards its append of the default ship accordingly.
* FRED2's dumpstats indexed Ships[] with a ship class when printing
loadout entries; it now prints the entry's class or variable name
directly.
* Team parse now clears the previous mission's entries explicitly
rather than relying on overwrite-in-place.
This clears the largest remaining cluster of MAX_SHIP_CLASSES references on the way to lifting the ship class limit.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Generalize the unreleased "$fix target updating with strafe:" ai_profiles flag
into "$fix ai target recovery:", which now also covers two more ways a ship
holding a standing chase order could park in AIM_NONE forever:
* a ship already in AIM_NONE with a standing chase order (attack-any etc.) now
clears its active goal so the order is re-processed, closing the window where
retargeting finds a new enemy before the strafe clause can fire
* target selection (find_enemy/get_nearest_objnum) now skips ships outside the
attacker's actively-pursues list, and ai_chase() drops self-chosen targets it
refuses, instead of holding a target it will never attack
Retail behavior is unchanged when the flag is disabled; explicit orders on
non-pursued targets are still declined as before.
Co-authored-by: Claude Fable 5 <[email protected]>
The text labels drawn in the main editor viewport were always rendered at the fixed FONT1 size. Add options to scale the font from 50% to 400%.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`sexp_percent_ships_arrive_depart_destroy_disarm_disable_scan` could have an edge case where the total value (ie the denominator) is 0 and thus crashes FSO. This could happen if `Cancel_future_waves_of_any_wing_launched_from_an_exited_ship` is used and the death or departure of a mothership triggers the total of a wing to change that is later checked in a sexp such a 'percent-destroyed` or other similar sexps.
Fix is just to add an early out if the total value is 0.
Root cause
Commit 87ea04fa5 "change atan2_safe to atan2" (July 2024) replaced FSO's custom atan2_safe with the standard atan2. The old function returned a different range:
range returned
old atan2_safe (-PI/2, 3PI/2)
standard atan2 (-PI, PI]
do_view_track_target() in playercontrol.cpp:417 computes the padlock heading as a raw subtraction of two extracted headings:
chase_slew_angles.h = forward_angles.h - view_angles.h;
The forward vector rotated into the player's own frame is always (0,0,1), so forward_angles.h is always PI/2. With the old range that subtraction landed in (-PI, PI) — symmetric, and the ±120° neck clamp below applied evenly. With standard atan2 it lands in [-PI/2, 3PI/2) instead: -90° to the left, but +270° to the right.
Leftward travel dead-ends at 90° (straight abeam) instead of 120°, and the moment a target crosses just past the player's left shoulder the value wraps to a large positive number and gets clamped to +120° — the camera snaps hard right.
The fix
Rather than reverting atan2_safe (standard atan2 is correct, and other callers depend on the new range), this PR wraps the heading difference back into (-PI, PI] before the neck clamp, using the same "over-the-top correction" idiom already used by do_view_external() a few hundred lines down:
// Do over-the-top correction.
// Headings are extracted with atan2, so each one lies in (-PI, PI] and their difference can be
// nearly a full circle in either direction. Without wrapping it back into (-PI, PI], a target just
// past the left shoulder reads as being almost all the way around to the right instead.
if (chase_slew_angles.h > PI)
chase_slew_angles.h -= PI2;
else if (chase_slew_angles.h < -PI)
chase_slew_angles.h += PI2;
FRED2's AltShipClassDlg kept two fixed-size parallel arrays mapping combobox rows back to engine indices:
int ship_class_indices[MAX_SHIP_CLASSES] // row -> Ship_info index
int string_variable_indices[MAX_SEXP_VARIABLES] // row -> Sexp_variables index
Both are pure UI plumbing. Delete them and attach each index to its combobox row via CComboBox::SetItemData/GetItemData. Besides removing the arrays, this drops the num_string_variables index offset math the parallel arrays forced and bounds the reverse lookups by the combobox item count instead of MAX_SHIP_CLASSES.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Shield_sys_types (the per-ship-class shield status in the FRED2/qtFRED Shield System dialog) was a dense array/vector sized to MAX_SHIP_CLASSES, one of the last cap-blocking structures. It is a poor fit for a dense container: it is derived, ephemeral editor state, and sparse in practice, since only the ship classes present in the mission ever get a meaningful value. Its default (HasShields) is exactly the "absent" case.
Convert it to a map keyed by ship class:
FRED2: int Shield_sys_types[MAX_SHIP_CLASSES] -> SCP_map<int, int>
qtFRED: SCP_vector<GlobalShieldStatus> Shield_sys_types -> SCP_map<int, GlobalShieldStatus>
(and the ShieldSystemDialogModel::_types copy likewise)
No file-format or behavior change: shield status is still derived from and applied to the same ship flags.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The sexp tree refactor (#7301) moved the OPF listing logic into a shared
model that asks the editor for campaign-aware lists via virtual methods
on SexpTreeEditorInterface. QtFRED's campaign editor got the necessary
overrides, but FRED2's never did, so its OPF_MISSION_NAME /
OPF_GOAL_NAME / OPF_EVENT_NAME dropdowns fell back to the currently
loaded mission's data instead of the campaign's.
Backport the overrides to FRED2, restoring its pre-refactor behavior
(including listing only missions at earlier campaign levels), and hoist
QtFRED's loadAndFindCampaignMission helper into missioneditor/common so
both editors share one copy.
Co-Authored-By: Claude Fable 5 <[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.
Ensure proper checks for model_num and instance validity when accessing OBJ_RAW_POF and OBJ_PROP objects. Prevents crashes from out-of-bounds or missing data in Pof_objects and Props.
PR #7082 rearranged the FRED2 menu layout to match qtFRED (see issue #6985),
but some users preferred the previous Editors/Misc layout. This adds a
"Classic menu layout" toggle (under Settings in the current layout, and under
Misc in the classic layout) that swaps the whole menu bar on demand. The
choice is persisted to the registry and reapplied on startup.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Reset the selected item when we open a new menu. This keeps the display state and internal state in sync if the player mixes arrow presses and number presses. Follow-up to #7688.
* 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
Convert MsgItems from an array to a vector, and remove the associated limit value and counter.
* vectorize msgitems
* appeasement
* leave me alone clang
* remove optional
* cleanup
* changes requested
* clang
* clang what is WRONG with you
* feedback
* remove flag in .h
Prevent the mission from being modified via the ship editor's window update when it is already being cleared or loaded. This mirrors existing guards in `delete_object` and `delete_ship`.
No other FRED2 dialogs are vulnerable. QtFRED uses a different ship editor mechanism which is not affected by this issue.
An operator that isn't enclosed in parentheses could trigger an UNREACHABLE, which crashes in Debug and is undefined behavior in Release. Catch it in a more appropriate way.
TLDR: This is a long description, but it boils down to exposing 2 hardcoded AI values and updating 1 value in the optional 'better collision avoidance' behavior allows mods to substantially fix fighters ramming into capital ships they are attacking.
AI accidentally ramming into big ships while trying to evade fire from a hostile turret or a dogfight makes some sense given a chaotic combat situation. What does not seem good though is AI not being able to attack a large stationary target that is not shooting back and has no fighters around. This is especially evident in mods that use the new strafing AI fields, where AI will fly to a distant point then turn around to do an attack run, then once close enough pick another strafing run to conduct. In these situations, AI will commonly not pull up from the attack run in time, especially for mods that use different speeds or AI damp values compared to retail.
Fortunately, there exposing two values to the AI profiles allows modders to tune these values, the strafe retreat time and strafe retreat distance. By default these values are 2 seconds and 100 meters, which is commonly far too short for mods with higher speeds or larger damp values. Exposing these values allows modders to make the AI far more effective and virtually eliminate ramming into stationary ships they are attacking. For example, on current 26.0 with FotG testing we register 2-4 rams of a stationary target per minute. Using the new exposed values in this branch eliminates the ramming (after 10 minutes of firing no ramming occurs across multiple runs of this and other test missions).
Furthermore, this PR helps `better_collision_avoidance_triggered` function (enabled by using `better collision avoidance` in the `ai_profiles.tbl` fix an edge case with predicting collisions. On current master the `delta_time` value used in this function was `0`, which was only ever used eventually downstream in the `will_collide_with_big_ship` function call. This `will_collide_with_big_ship` function had an early return on line 7620:
```
int will_collide_with_big_ship(object *objp, vec3d *goal_point, object *big_objp, vec3d *collision_point, float delta_time)
{
float radius;
vec3d end_pos;
radius = big_objp->radius + delta_time * objp->phys_info.speed;
if (vm_vec_dist_quick(&big_objp->pos, &objp->pos) > radius) {
return 0;
}
```
This early return and the passing of `0` to the `delta_time` from `better_collision_avoidance_triggered` meant that the early out radius distance was only the big object's radius, and did not project any forward time. In other words, better collision avoidance only actually checked or triggered when the small ship was within the radius distance of the large ship. Thus, with ships that had geometry reach right to the edge of the object radius, it could result in the small ship not having enough time to react to avoid a collision. Notably, all other calls to `will_collide_with_big_ship` use a `delta_time` of 5-10. As such, this PR also fixes that edge case by ensuring the better collision avoidance also incorporates some lead travel time by passing a non-zero value for delta time. Given `better_collision_avoidance_triggered` aggression factor is 3.5 by default, it fit well in testing to pass this value to `delta_time`. That aggression factor is already tuneable for mods, so also using it here provides extra adaptability.
Overall these values and updates were tested and substantially remove collision accidents, especially with ships with high speeds and/or higher damps. The PR boils down to exposing two values to the AI profiles table and updating values in the optional 'better collision avoidance' flag, so it will not affect retail. Happy to discuss as well, thanks!
Seems like props were missing from the object type list, so adding them in this relatively small PR. Happy to edit or do something differently if folks want though!
* 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
Bind the existing fsspeech_* wrappers into the ui.Briefing, ui.CommandBriefing,
ui.Debriefing, and ui.TechRoom scripting sections so Lua UIs (e.g. SCPUI, which
overrides the native screens) can drive synthesized speech again.
Each section gets playTextToSpeech, stopTextToSpeech, pauseTextToSpeech,
isTextToSpeechPlaying, and isTextToSpeechEnabled. Briefing/command-brief/debrief
use FSSPEECH_FROM_BRIEFING; the tech room uses FSSPEECH_FROM_TECHROOM. fsspeech_play
already self-gates on the Speech.* options, so these are no-ops when speech is off.
Restore the original flag values that were consolidated in #7588. Since the flags are saved in the mission file as an integer, the original values must be preserved.
Since `MR_ATTACHED_MODEL` was removed in the original PR, that is renamed to `MR_EMPTY_SLOT6`.
The game settings flag '$Hide main Rearm/Repair items in Comms Gauge:' hides the 'Rearm and Repair' lines in the HUD Comms menu from appearing, which is useful for mods that do not have repair ships and thus those lines confuse players. Unfortunately, the newer `COMMS_MENU_SELECT` control bindings do not properly account for hidden menu items, so using those controls on a comms menu with 'Rearm and Repair' hidden means the selection index gets off and also confuses the player.
This PR fixes that by allowing `hud_squadmsg_selection_move_down()` and `hud_squadmsg_selection_move_up()` to skip hidden menu items. Tested and works as expected.
For folks using the COMMS_MENU_SELECT controls, there is also a current UI confusion when the comms menu is first brought up because the first item is selected, but the `Display_selector` does not show. Thus, players are unsure what item is actively selected even though one is actively selected. In the original comms menu select PR this was set to on by default, but then switched to off by default by a different developer a bit later. This choice is especially useful for mods that have many players with gamepads such as Event Horizon. Alternatively, mods that already have many number keys utilized for other gameplay aspects seem to prefer to keep the comms menu visuals as is and only show the selection if the player uses those keys. Given there is clearly arguments for both reasons, ideally modders should be able to choose how it displays for their own mods (always or off for the first pop-up of the Comms menu). Thus, this PR adds that as a cleanup game option, too. This also was tested and works as expected.
* Fix scripting copy-paste bug
The iterators for secondary banks for lua access had a copy-paste bug from primaries, so we should fix that. The early == -1 break masks it whenever a ship uses 3 or fewer secondary banks, which is probably why it went unnoticed.
Also add some additional low-hanging fruit optimizations.
* radar distance and other cleanup
* clang
Convert the allowed-ships and allowed-weapons lists to sets, rather than naive vectors that stored a true/false for every class. Since these are ordered sets, iteration occurs in the same sequence as iteration of `Ship_info` or `Weapon_info`. Associated data structures such as `Granted_ships` and `Granted_weapons` are converted as well.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Use the SDL gamepad API to add full gamepad support. Adds rumble for supported
gamepads and changes the FF in-game options to take immediate effect instead
of requiring a restart.
Additionally this makes changes to allow gamepad triggers to be used as both
an axis and a button. This support is specific to gamepads since we can
explicitly identify the trigger with the API and act on it accordingly. FSO
control config doesn't currently support such an action directly however so
we have to hack it in just a bit. Due to this the control binding will show
the trigger axis name bound to a button control only while a gamepad is
connected, otherwise it shows a button name associated with the trigger.
* Secure forum posting by adding authentication header support
* Add check for missing FORUM_SECRET environment variable in ci/post/main.py
* also error out when the forum secret is not supplied
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.
Convert ship/weapon loadout pools from naive per-class arrays to ordered maps that list loadout entries. Each entry represents a ship/weapon class and its count. An absent entry means the class is not in this mission's loadout. Since these are ordered maps, iteration of the map keys occurs in the same sequence as iteration of `Ship_info` or `Weapon_info`.
Includes several bugfixes:
- `csg_read_loadout` now clears both pools before reading. Previously the pools were only zeroed in `mission_campaign_init`
- `restore_wss_data`: non-transmitted classes are now absent rather than memset to 0
- a copy-paste bug where the weapon pool entries were bounds-checked against MAX_SHIP_CLASSES
- `wss_maybe_restore_loadout`: the pool write-back now preserves loadout membership instead of writing a count for every class
- `ss_dump_to_list`/`ss_swap_list_slot`: returning a slot ship whose class is not in the pool now makes it available instead of silently losing it. Unreachable in retail but reachable via script
- off-by-one errors in the Lua `Ship_Pool`/`Weapon_Pool` indexers
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
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.
Refactor shadow flag handling in shaders to improve compatibility with small-shader mode. Add support for Vulkan's `-no_large_shaders` switch to split model ubershaders for better driver compatibility. Adjust related comments and preprocessor checks for clarity.
Extend the various maps to add a `contains` function, just as several other containers already add `contains`.
Also add `at_or` and `value_or` functions to provide ways to query for map values without inserting anything by default, as `operator[]` does. If the map does not contain the key, the default value is returned. Use `at_or` to return a const reference and `value_or` to return a value. (These are only added to `SCP_map` and `SCP_unordered_map`; a `SCP_multimap` equivalent isn't as clearly useful.)
Also add Class Template Argument Deduction (CTAD) guides, per existing precedent. And delete function overloads that are intrinsic footguns.
* qtfred: render briefing map via offscreen target for an accurate view
The briefing map widget rendered directly into the window at the widget's
size, which broke at display scaling > 100% (the briefing filled only the
top-left 1/dpr of the surface) and never matched the in-game framing or
icon proportions.
Render the briefing once into an offscreen render target at the reference
resolution (Briefing_window_resolution, retail default 888x371) using the
same setup the game uses, then letterbox-blit that finished image into the
widget. Scaling a canonical image means icon sizes, grid, line thickness
and text all scale together, so the editor view is a faithful WYSIWYG copy
of the briefing at any widget size or DPI.
Mouse picking and dragging now map input into reference-resolution space
via the blit rectangle. Selection brackets are drawn as a crisp window-
space overlay after the blit (editor UI, not part of the briefing image).
* qtfred: make the briefing map a resizable plain widget
The briefing map used a native QWindow embedded via createWindowContainer.
Native child windows paint over their siblings and won't shrink inside a
constrained layout, so the map couldn't resize with the dialog without
overlapping the surrounding controls.
Now that the briefing renders into an off-screen render target, read the
finished frame back into a QImage and paint it (aspect-fit, letterboxed)
in an ordinary QWidget. Selection brackets are drawn as a QPainter overlay
and mouse input maps through the paint rectangle. The widget participates
in the layout like any other, so it clips and resizes cleanly.
Drop the map's aspect-ratio pin and minimum size (the image scales to any
size), leaving the left pane free to shrink so the dialog resizes in every
direction without clipping.
* qtfred: pin briefing map resolution to the retail map size
The briefing map was composed at Briefing_window_resolution (the "$FRED
Briefing window resolution" table setting). That setting is only consumed
by FRED2 (an icon-scale-vs-window-size hack) and is ignored by the game
and SCPUI, so honoring it in QtFRED could only make the editor preview
diverge from the shipped briefing.
Pin the compose/render resolution to Brief_grid_coords[GR_1024] instead --
the retail briefing map size, and what Lua's ui.drawBriefingMap() defaults
to -- so the editor is an unconditional WYSIWYG preview of the game and
follows retail automatically if that constant ever changes. BriefingViewport
getSize() is the single source of truth; renderFrame() reads it rather than
duplicating the lookup.
* qtfred: cycle through stacked briefing icons on repeated clicks
Clicking the briefing map always selected the top-most icon under the
cursor, so overlapping icons underneath were unreachable.
The hit-test now collects every icon under the cursor (top-most first).
A plain click advances to the next icon underneath the currently-selected
one, wrapping bottom to top, so repeated clicks roll through the whole
stack; if nothing in the stack is selected it takes the top-most.
Shift-click and empty-space clicks are unchanged.
* qtfred: themed checkerboard matte behind the briefing map
Fill the briefing map's letterbox/pillarbox bars with a subtle,
theme-appropriate grey checkerboard so the (pure-black) map's edges are
clearly distinguishable from the surrounding matte. Two close grey shades
per theme keep it quiet; the tile is cached and rebuilt only when the
editor theme changes.
Add a shared Theme::currentThemeIsDark() that returns the effective dark
state from the applied theme preference (resolving System against the OS
scheme) and adopt it here, in VariableDialog's row tints, and in the help
browser's isDarkMode() in place of three separate palette-lightness checks.
The ship editor, wing editor, waypoint path dialog, and jump node
dialog all had near-identical code to check whether a new name
conflicts with an existing ship, wing, waypoint path, jump node, or
target priority group (or is empty, or begins with '<'). Both FRED2
and qtFRED carried their own copies of this logic.
Extract it into a single check_name_conflict() function in
code/missioneditor/common.cpp, shared by both editors, and replace the
duplicated validation at each call site with a one-line call:
- FRED2: shipeditordlg, wing_editor, waypointpathdlg, jumpnodedlg
- qtFRED: ShipEditorDialogModel, WaypointEditorDialogModel,
JumpNodeEditorDialogModel, and Editor::validate_wing_name
This also aligns a few small behavioral differences that had crept in
between the two editors: the waypoint and jump node dialogs now skip
empty wing slots (wave_count == 0) when checking for wing-name
collisions, and the qtFRED wing editor now rejects names beginning
with '<'.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
* Prioritize items that begin with search string
Items that begin with the search string should be prioritized before those that simply contain the search string.
* Add Search Operators option
* Add Safety to Action Handler
I didn't see any crashes, but this matches the pattern of other keyboard shortcuts.
* Allow search for numeric nodes
The working code existed already
* Limit matches on operator search
This limits matches on operator searches by setting a minimum size that a string match has to meet. Function returns -1 on failure, and the warning has been removed to allow this behavior.
* Try this option name better
* Add keyboard shortcut for search
This allows ctrl+s (which can be listed instead of spacebar) to initiate search. There is a new menu item added as well.
* Put this in the correct place
* Address Feedback
* Wrong state
We want the item to be inserted here, not ignored.
Due to a long-standing bug, the groups-of-4 argument count check for
send-message-list and send-message-chain never actually worked, so
missions through 25.0 could includes sexps with truncated argument lists
that recovered gracefully at runtime. Now that the check works, don't
punish those missions: introduce SEXP_CHECK_BAD_ARG_COUNT_BENIGN, which
warns but does not prevent the mission from loading.
To make sexp tree validation more robust, check_sexp_syntax now defers
recoverable errors rather than returning them immediately; otherwise
a recoverable error could mask a fatal error deeper in the tree.
Also fix a stale-variable bug in FRED's fred_check_sexp that could
produce a bogus empty dialog.
Co-Authored-By: Claude Fable 5 <[email protected]>
Since #7646 switched from the bundled hidapi to SDL_hidapi, no space mouse is
found. SDL_hid_enumerate() nominally auto-inits HIDAPI, but in practice it only
reliably reports an already-connected device when SDL_hid_init() has been called
up front. Call SDL_hid_init() once in os_init() (before SDL_Init), balanced by
SDL_hid_exit() in os_deinit(). io::spacemouse (qtFRED's only consumer) then
enumerates the device correctly.
Fix reported bug where pressing D did not toggle Show Distances: the menu
and toolbar actions both claimed D, producing an ambiguous shortcut
overload. Removed the duplicate from the toolbar action. Applied the same
fix to Space (Selection Lock), which was owned by both a QAction and the
configurable ControlBindings; ControlBindings now owns it exclusively.
Restore/align several FRED2 accelerators and reshuffle dialog keys:
- X = Rotate Locally (routed through the transform local-axes button)
- Ctrl+Shift+P/Shift+P = Props, Shift+L = Team Loadout
- Shift+V = Variables & Containers, Ctrl+Shift+V = Toggle Viewpoint
(new action mirroring FRED2's OnToggleViewpoint)
- Shift+U = Volumetric Nebula, Shift+M = Shield System
Add Shift+F1 to toggle the sexp help pane for the session (without
changing the saved preference) in the Ship, Wing, Mission Events, Goals,
and Cutscenes editors.
Add F6 / Shift+F6 to cycle Next / Prev in the Ship, Wing, Waypoint,
Jump Node, and Prop editors.
Repro: create a prop, File -> New Mission & Discard, then create the same prop
again. Asserts in model_get with "Index collision between model <other>.pof and
requested model N".
model_unload() walks Ship_info and Weapon_info clearing any cached model_num
that pointed at the model being freed, but never did the same for Prop_info.
props_level_close() only clears the prop instances, so prop_info::model_num
survived the discard pointing at a freed slot. Placing that prop class again hit
EditorViewport::create_object_on_grid, which reads pip->model_num directly to
size the placement distance, and by then the slot had been reused by an
unrelated model.
Adds the matching Prop_info pass. Doing it in model_unload rather than
props_level_close mirrors how the two closest analogues are handled -- Ship_info
and Weapon_info are likewise class tables holding a cached handle for placeable
objects -- and covers any unload path, not just level close. (asteroid_level_close
solves the same problem for Asteroid_info from the other direction.)
This is not OFP-specific; SCP master has props and the same missing pass.
New initial orders start with no committed target (_object == -1). The
target combo visually defaults to its first item, but with signals blocked
that selection is never pushed to the model, and re-picking the already-shown
item emits no change signal. Ship/player targets auto-commit their first
valid entry inline during population; waypoint paths, individual waypoints,
ship classes, and wings did not, so a new order of those types stayed
uncommitted and failed validation on apply.
Add a uniform fallback after the target combos are populated: if a new order
has no committed target, commit the currently-shown default. No-op for ships
(already committed) and existing orders (loaded with a target already set).
Fix a regression from #7393: `last_targeted_subobject` must be updated when the player's target and target subsystem are changed, or the subsystem will be retargeted due to `hud_target_change_check`.
Also fix related issues:
- the `ship.Target` and `ship.TargetSubsystem` scripting setters now use the standard `set_target_objnum` function and also correctly handle the new target subsystem
- fix an indexing error in `order.TargetSubsystem`
Co-Authored-By: Claude Fable 5 <[email protected]>
Quick follow-up to #7635. Even though you can't set dual-fire when a non-dual-fire bank is active, you should be able to *un*set it. Reorder the conditions so this is possible.
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]>
* ci: run clang-tidy on macOS and Linux clang builds
Install a version-matched clang-tidy on macOS and make the shared runner portable across both CI environments.
* ci: keep valgrind compatible with clang debug builds
Emit DWARF4 debug information and suppress SDL's one-time initialization allocation so memcheck can report actionable failures.
* ci: suppress SDL3/libX11 video backend leaks under valgrind
Now that the `[ "$CONFIGURATION" = "Debug" ]` typo is fixed, valgrind
actually runs on the Linux Debug legs again, and memcheck fails the build
on six "definitely lost" contexts (480 bytes) that all originate inside
SDL3's X11 backend at X11_CreateDevice, reached from SDL_VideoInit.
These aren't ours to fix: both call sites (os_init's SDL_Init and the
temporary video init in resolution_default(), reached via gr_init) already
pair their init with a matching quit, and the allocations are made and
kept by SDL/libX11 across SDL_VideoQuit. Collapsing the repeated init/quit
cycles would only reduce the block count, not the number of leak contexts,
so the build would still fail.
The suppression is truncated at X11_CreateDevice on purpose: it stays
caller-agnostic (covering both the os_init and gr_init paths) and avoids
matching on SDL_InitSubSystem_REAL.part.0, whose .part.0 suffix is a
partial-inlining artifact of how SDL3 happened to be built.
Co-Authored-By: Claude Opus 5 <[email protected]>
* ci: suppress glibc dlopen loader leaks under valgrind
The Linux clang-16 Debug leg fails memcheck on a single zero-byte block
lost in glibc's `_dl_find_object_update()`, reached from `dlopen()` while
SDL probes its video backends. It is loader bookkeeping that glibc keeps
by design, and it only shows up on some legs because it depends on how
many objects the loader has mapped by that point.
The file already carried three suppressions for this class, but each
pinned a full, exact glibc stack, so every new loader code path costs
another CI round. Replace them with a single block matching on
`_dl_open`: nothing of ours runs below that frame, only loader internals
and the static constructors of shared libraries the loader brings in, so
this gives up no coverage we care about while retiring the whole class.
All three removed blocks contain `_dl_open` themselves and are therefore
subsumed by it.
Both new suppressions match `definite,possible` rather than `definite`
alone, since `--errors-for-leak-kinds` defaults to `definite,possible`
and the same allocations would otherwise fail the build if valgrind ever
reported them as possibly lost instead.
Co-Authored-By: Claude Opus 5 <[email protected]>
---------
Co-authored-by: Claude Opus 5 <[email protected]>
Gunships and other custom ship classes may run through the primary weapon code despite having no primary banks. Add a few guards to prevent this from causing crashes.
Fixes a crash reported in Causality: The Great War.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Vendor the CMake modules FSO actually used from the ~150-file rpavlik
submodule into cmake/, then drop the submodule:
- EnableExtraCompilerWarnings.cmake (toolchain warning flags)
- CreateLaunchers.cmake + its CleanDirectoryList.cmake dependency and
launcher-templates/ (IDE launcher generation for the game and FREDs)
- MSVCMultipleProcessCompile.cmake + its ListCombinations.cmake dependency
Also remove the dead cotire module-path entry and the vestigial
ENABLE_COTIRE option (cotire is never invoked and its directory no longer
exists), and repoint the submodule-initialized check at libRocket.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
* remove hidapi lib in favor of SDL_hidapi
Funtionally identical under the hood, but offering maximum capability and
compatability without adding any system dependencies. The main difference on
our side is that hidapi functions and types will be prefixed with "SDL_". And
SDL will dynamically load in the hidapi features best supported by the running
operating system.
* remove residual SDL_hid_exit call
* 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
* Fix Vulkan render target readback orientation to match OpenGL behavior
* Add render target pass resumption after Vulkan shadow rendering
Ensure that Vulkan render targets resume rendering properly after shadow passes, particularly for off-screen targets like SCPUI's 3D previews, to prevent unintended content leakage onto the screen.
* Skip alpha writes for additive batched bitmaps in render targets to preserve coverage and prevent opaque artifacts.
* Add external subpass dependencies to Vulkan render passes to fix read/write hazards
Introduce explicit memory dependencies for color attachments sampled between passes to prevent flickering and graphical artifacts caused by read-after-write and write-after-read hazards.
* Support fractional alpha values in createColor function and preserve 0-255 compatibility
Ensure SDL video is temporarily initialized if needed during startup to safely query desktop display mode, preventing reliance on a potentially dead subsystem and avoiding silent fallback to invalid resolutions.
* Add layer rename and bold current layer in Move to Layer menu
Bold the object's current layer in the Move to Layer context menus
instead of marking it with a checkbox.
Add a Rename Layer button to the Layer Manager dialog. Renaming
rewrites the per-object fred_layer string on every object assigned to
the layer. The Default layer cannot be renamed.
* Add layer rename to Scene Browser right-click menu
Right-clicking a layer row in the Scene Browser now shows a small
context menu with Rename Layer, which opens a rename box and applies
the rename through the same viewport path as the Layer Manager dialog.
The Default layer cannot be renamed.
Address FXAA/SMAA shader selection logic by aligning it with the current anti-aliasing mode. Fix undefined behavior for discarded non-edge pixels during the FXAA main pass by transitioning Scene_ldr to a load-preserving layout. Optimize compatibility across IMR and tiled GPUs, preventing visual artifacts.
Disable raytraced-shadow and HDR settings in the options menu when unsupported by the current renderer, reducing UI clutter and ensuring only relevant options are displayed.
Introduce load-variant render passes to Vulkan textures, enabling content preservation during mid-frame readbacks. Changes include creating `renderPassLoad`, flushing command buffers for readbacks, and resuming rendering into targets with `loadOp=eLoad` to avoid clearing previously rendered content.
This commit introduces optional depth/stencil attachments for Vulkan render targets, enabling z-testing and addressing earlier limitations where depth-tested geometry rendered in submission order without depth attachments. Changes include resource allocation, attachment handling, and layout transitions.
* Shadow overhaul round 2: PCSS, dynamic cascades, cockpit/instanced shadows
Squashed snapshot of lafiel/shadow_overhaul_2's continuation work
(d3922aa87..010f9d2d9), which has no separate upstream PR of its own.
* Add Vulkan rendering backend
Squashed snapshot of the Vulkan backend as vendored into this branch
(ce2d1e85f..6ce539463, authored by Mara van der Laan with build/CI
fixes by Taylor Richards). This work has its own upstream PR #7553
(notimaginative:vulkan-pr-new) and is not otherwise original to true-hdr.
* Add true HDR output, RT shadows, and PCSS shadows for Vulkan
Squashed snapshot of true-hdr's own integration work: true HDR
framebuffer output, wiring the shadow overhaul into the Vulkan
backend (raytraced + cascaded shadow maps), logging refactors, log
filter UI, and CI/build fixes.
* refactor: update Vulkan logging calls to use `nprintf` for scoped logging
* fix: correct shadow cascade count in Vulkan logging calls
* fix: fall back to PATH-resolved ccache when CCACHE_PATH is stale
CI hardcodes /usr/local/bin/ccache, but macOS runners on Apple Silicon
hosts install Homebrew (and ccache) under /opt/homebrew instead,
causing all four Mac configs to fail with "No such file or directory".
* Fix vulkan texture readback to correctly handle transparent pipelines
* Put the pixel swizzles into a util file
* OOB safety check
* Fix fog handling
* Fix MSAA in Vulkan
* fix: enable SMAA for vulkan
* adapt the post-processing AA shaders to hdr
* fix clang-tidy warnings: concatenate nested namespaces, static methods
pixel_swizzle.{h,cpp}: collapse `namespace graphics { namespace util {`
into `namespace graphics::util {` (modernize-concat-nested-namespaces).
VulkanState.h/VulkanDraw.h: getClearColor()/setClearColor() only touch
gr_screen and other globals, no instance state, so make them static
(readability-convert-member-functions-to-static) and drop the
top-level const on getClearColor()'s return type
(readability-const-return-type).
* fix clang-tidy warning
* Extend raytraced shadows to all directional lights
RT shadows previously only shadowed the first directional light in the
scene, even though multi-sun missions push more than one directional
light into the engine. The TLAS raytraced shadows query against is
already light-agnostic, so this extends both the deferred lighting
pass and the forward MODEL shader to shadow every directional light
(capped by a new Max Raytraced Shadow Lights option, configurable via
the in-game Options menu or the Lab's Scene rendering options).
Cascaded shadow maps are untouched: they're built for a single light
only, so the deferred pass still limits itself to one shadowed
directional light whenever CSM (not raytracing) is the active method.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016DA6JHJ3twz2oHGQcZ1Udc
* refactor: improve shader flag handling and render target finalization in Vulkan backend
- Consolidate shader flag setup logic in VulkanPostProcessingLighting to simplify configuration.
- Fix dead field usage in VulkanDraw by ensuring correct image view selection for environment maps.
- Add mip chain regeneration in VulkanRenderer::endRenderTarget to ensure correct mip levels for cubemaps.
* fix: ensure correct mip chain initialization in cubemap rendering
- Add mip chain generation to VulkanDraw for cubemaps with multiple mip levels.
- Fix potential issue with uninitialized mip levels above level 0 in deferred-f.sdr sampling paths.
* fix: don't crash on startup when environment locale is unavailable
std::locale("") pulls in the process's environment locale categories
(LC_CTYPE, LC_MONETARY, LC_PAPER, etc.), and throws std::runtime_error
if any of them names a locale not installed on the host (e.g.
mismatched regional-format overrides). Since SCP_default_locale is
constructed during static initialization, before main() and before any
of our own exception handling exists, an uncaught throw here aborted
the whole process before the game even started. Fall back to the
classic "C" locale instead, which is sufficient since this locale is
only ever used for ASCII case-folding (SCP_toupper/tolower/isdigit).
Co-Authored-By: Claude Sonnet 5 <[email protected]>
* `feat: add raytraced shadows for local lights and optimize TLAS management`
* Make the Commandline authoritative for -res and -vulkan / -opengl
* address BMagnu's comments on the original PR
* update prebuilt version hash to 62c89ef6
* refactor: standardize graphics API handling and document Vulkan limitations in qtFRED
- Updated `AboutDialogModel.cpp` to use `GraphicsAPI` enum for better clarity.
- Ensured qtFRED falls back to OpenGL when Vulkan is requested.
- Added detailed documentation in `qtfred/README.md` regarding Vulkan backend limitations and requirements.
* chore: include cmdline library in main and mission management modules
* docs: add known issue for blank render viewport under Wayland in README.md
* fix CI issues
* chore: add `GR_DEBUG_SCOPE` markers across Vulkan post-processing and rendering paths for improved debugging
* feat: improve Vulkan HDR pipeline with separate encode paths for SDR and HDR10
- Added an HDR10-specific output encode pass in `VulkanRenderer` and `VulkanPostProcessor` that applies PQ/BT.2020 transfer.
- Introduced an optimized SDR fallback path with direct blit support for devices that can skip shader draws.
- Updated `m_sceneLdrCompressed` to provide [0,1]-clamped proxies for HDR edge detection.
- Refactored `copyImageToImage` and added `blitImageToImage` to allow format conversions and optimized transfers.
- Replaced `hdr_mode` with explicit HDR10 flags and data structures for clearer state handling.
* refactor: encapsulate SMAA processing and refactor VulkanPostProcessor
- Moved SMAA-specific logic into `VulkanSMAA` class for better separation of concerns.
- Simplified `initSMAA`, `shutdownSMAA`, and `executeSMAA` logic by leveraging `VulkanLDR` and `PostProcessContext` abstractions.
- Improved initialization and cleanup code with clearer resource lifecycle management.
- Updated debug markers and messages to reference `VulkanSMAA`.
- Enhanced flexibility of fullscreen triangle rendering API with additional parameters (`sampleCount`, `bindGlobalSet`).
* Update Vulkan porting credits in AboutDialogModel
* fix CI issues again
* fix: correct Y-flip in viewport setup for Vulkan light volumes
- Adjusted viewport height to negative value to account for G-buffer render pass's negative Y-axis convention.
- Ensured proper alignment of point and tube light volumes with actual light positions.
* feat: add user-adjustable gamma correction to SDR and HDR10 output paths
- Added gamma correction to HDR10 path, applying user settings before PQ/BT.2020 encode.
- Replaced the SDR blit-only path with an encode pass that applies gamma correction, ensuring consistent behavior across devices.
- Refactored VulkanPostProcessor and associated shaders to support gamma slider adjustments for both SDR and HDR output.
* fix: ensure proper uniform and cull mode setup for Vulkan sphere rendering
- Added uniform buffer setup and default material uniforms in `vulkan_draw_sphere`.
- Disabled face culling in material definition for sphere rendering to align behavior with OpenGL.
* Ensure memory flushes after UBO updates and add explicit pipeline barrier for MoltenVK compatibility.
* fix: add clear pass for SMAA edge detection to prevent persistent artifacts
* feat: add Vulkan debug-utils messenger, opt-in sync validation, frame diagnostics
Groundwork for the renderer-review fix series (.agents/plans/
vulkan-renderer-review-fixes.md, Phase 0):
- Register a VK_EXT_debug_utils messenger (preferred) instead of only the
deprecated VK_EXT_debug_report callback, which is kept as a fallback for
loaders without debug-utils. The messenger config is also chained into
instance creation so vkCreateInstance-time messages are captured.
Validation errors/warnings now go to the main log via mprintf.
- New -gr_sync_validation cmdline flag (implies -gr_debug): chains
VkValidationFeaturesEXT with synchronization validation into instance
creation when VK_LAYER_KHRONOS_validation is available. This is the
regression net for the synchronization fixes in the following commits.
- Frame stats now report descriptor sets/writes allocated per frame and the
total pipeline count (descriptor-manager counters; DescriptorWriter::flush
moved out-of-line to report into the manager).
Co-Authored-By: Claude Fable 5 <[email protected]>
* refactor: unify Vulkan render-pass begins, clamp in-pass clears, add per-frame UBO ring
Phase 1 of the renderer-review fix series: shared helpers that the
correctness fixes build on.
- New VulkanRenderer::beginTrackedRenderPass(PassBeginDesc): every render-pass
begin on the frame command buffer now records vkCmdBeginRenderPass and
updates the state tracker (pass, color attachment count, sample count,
render area, viewport) in one place. Converted: setupFrame,
beginSceneRendering (both branches), resumeSceneRendering,
endSceneRendering, beginRenderTarget (viewport kept for gr_set_viewport),
resumeSwapChainPass, plus new resumeScenePassAfterCopy() shared by
copyEffectTexture/copySceneDepthForParticles and
rebeginSwapChainPassAfterReadback() shared by both readbackFramebuffer
exits (~200 lines of duplicated begin/clear/viewport blocks removed).
- The state tracker records the active render area; all four
vkCmdClearAttachments sites clamp their rects against it and skip empty
results. Previously gr_screen-sized clear rects could exceed a smaller
off-screen render target's render area, which is invalid API usage.
- New PerFrameUboRing utility (VulkanPerFrameUbo.h/.cpp): a persistently
mapped uniform buffer with one slot region per frame in flight and a
self-flushing alloc(). Used by the next commit to fix the cross-frame
UBO races.
Deliberate behavior deltas (all safe-direction): the helper always sets
colorAttachmentCount/sampleCount (some sites previously inherited stale
values), and resumeSwapChainPass/resumeSceneRendering now also reset the
standard flipped viewport instead of leaving the previous one.
Co-Authored-By: Claude Fable 5 <[email protected]>
* fix: eliminate Vulkan cross-frame UBO/buffer races, make gr_sync honest
Phase 2 of the renderer-review fix series: with two frames in flight, several
host-visible resources were rewritten by the CPU while the previous frame's
GPU work could still be reading them.
- The post-processing scratch UBO is now a PerFrameUboRing (per-frame-in-
flight slot regions, persistently mapped, self-flushing alloc). All the
per-pass map/unmap/cursor bookkeeping in bloom/LDR/fog/SMAA is deleted;
the cursor resets exactly once per frame via the new
VulkanPostProcessor::beginFrame() hook in setupFrame.
This also fixes two latent bugs: (a) fog consumed scratch slots mid-scene
and bloom's later same-frame cursor reset overwrote them before submission
whenever fog+bloom were both active; (b) volumetric_fog_data (288 bytes)
overflowed the 256-byte slots - the memcpy spilled into the neighboring
slot and the shader's bound range ended before the aspect/fov/noise
fields. Slots are now 512 bytes (static_assert at the fog call site) and
the per-frame budget is 32 slots.
- The dedicated tonemap, output-encode, and MSAA-resolve UBOs (each a single
instance rewritten per frame, i.e. racy; the MSAA one also never flushed)
are deleted entirely - those passes build their structs on the stack and
allocate from the scratch ring.
- Static-buffer rewrites orphan instead of racing: getVkBuffer() stamps a
last-used frame number, and a full-content updateBufferData() on a Static
buffer used within the last MAX_FRAMES_IN_FLIGHT frames defers the old
VkBuffer to the deletion queue and writes a fresh one. Offset writes
(GPU-heap appends to fresh regions) and PersistentMapping buffers (the
engine holds their mapped pointer and syncs via gr_sync) are exempt.
- gr_sync_wait now honors its contract: VulkanRenderFrame::waitForFinish
takes a timeout and reports expiry without consuming the fence;
VulkanRenderer::waitForFrame returns false for fences taken during the
still-recording frame (previously it waited on a stale or idle slot and
reported success) and resolves the frame->slot mapping correctly. This
makes UniformBufferManager's segment-fence throttling actually protective
on Vulkan for the first time.
Co-Authored-By: Claude Fable 5 <[email protected]>
* Refactor framebuffer and target lifecycle: centralized creation/resizing logic, improved resource management across Vulkan post-processing subsystems.
* Improve Vulkan cross-frame sync with explicit access masks and validation updates
- Unified Vulkan validation flag handling in setup, separating engine debug output from synchronization validation.
- Specified access masks and stage flags to address cross-frame WRITE_AFTER_WRITE vulnerabilities, notably in G-buffer, post-processing, and MSAA resolve paths.
- Adjusted subpass dependencies and image layout transitions to prevent read-after-write and write-after-write hazards, detected using `-gr_sync_validation`.
- Fixed uniform buffer and barrier transitions to ensure proper ordering in render passes across frames.
* Refactor Vulkan render-pass dependencies and sync stages for clarity and future testing
- Clarified dependency logic for cross-pass and cross-frame synchronization, ensuring explicit stage and access flag comments match observed behavior.
- Adjusted subpass dependencies to decouple render-pass compatibility definitions from dependency assumptions.
- Highlighted MoltenVK-specific issues and retained workarounds with notes for re-testing on macOS hardware.
- Updated synchronization barriers and validation notes to address historical inconsistencies across platforms.
* Remove transfer queue support; consolidate all operations into the graphics queue
- Removed transfer queue handling, simplifying buffer and queue logic to use the graphics queue for all transfer operations.
- Updated buffer sharing modes and removed related code paths and parameters for transfer queue families.
- Introduced exclusive buffer access, noting async transfer and queue ownership transfers are future work.
- Limited enabled device features to only those actively used by the renderer, reducing unnecessary feature requests (e.g., robustBufferAccess).
* Refactor frame advancement and descriptor management in VulkanRenderer
- Removed `endFrame()` from `VulkanDescriptorManager`, replacing it with `setCurrentFrame(frameIndex)` for explicit frame synchronization.
- Centralized frame index advancement within `VulkanRenderer` to ensure consistency across components.
- Invalidated cached descriptor set bindings at render-pass boundaries to handle raw recorder staleness correctly.
- Optimized pipeline descriptor rebind logic by removing redundant clears during pipeline changes.
* Refactor `PipelineConfig::hash` and Global descriptor set management for improved hashing and memoization efficiency
- Replaced inefficient shift-based hashing in `PipelineConfig::hash` with a robust `hashCombine` strategy to minimize bucket collisions.
- Introduced `maskBits` helper to streamline bitmask creation for boolean fields.
- Implemented memoization for Global (Set 0) descriptor sets, reducing redundant rebuilds across frames and improving performance.
- Added dirty state tracking (`m_globalSetDirty`) and invalidation logic for Global set updates following relevant input changes (e.g., TLAS or UBO modifications).
* Refactor Vulkan post-processing output logic: extracted shared `encodeToSwapChainPass` method to streamline HDR and SDR output paths.
* Optimize Vulkan descriptor set management with per-frame memoization
- Added memoization for Material (Set 1) and PerDraw (Set 2) descriptor sets to reuse cached sets across frames if inputs remain unchanged.
- Implemented precise input tracking for Material and PerDraw descriptor sets to detect and rebuild only when necessary.
- Reduced redundant Vulkan descriptor allocations and writes, improving performance on repeated or batched draw calls.
* Fix Vulkan access masks for G-buffer and scene pass transitions
- Added `eColorAttachmentRead` to access masks in multiple barriers to ensure proper synchronization for load operations (e.g., `loadOp=eLoad`) across render passes.
- Prevented `READ_AFTER_WRITE` synchronization validation issues in deferred and multi-pass rendering scenarios.
- Updated comments to clarify the reasoning behind the access mask changes and load dependencies.
* Refactor Vulkan resource management and indexed draw logic
- Consolidated destruction queue methods in `VulkanDeletionQueue` using a shared `queueHandle` template to reduce redundancy.
- Introduced `ModelDrawParams` structure and `computeModelDrawParams` function to unify indexed draw parameters for models and shadows.
- Simplified draw logic by eliminating repeated calculation of indexed draw parameters and improving code reuse.
* Add `releaseAnimationSlotRef` for ref-count handling of shared animation texture arrays
- Introduced `releaseAnimationSlotRef` to manage reference counting for shared animation texture-array slots, preventing premature destruction of shared resources.
- Updated `flushTextures` and related methods to integrate `releaseAnimationSlotRef` for shared slot cleanup.
- Refactored staging buffer creation into `createStagingBuffer` for 3D texture uploads and shared path consistency.
- Enhanced texture upload logic with improved tracking and logging for re-upload cases, aiding preloading gap analysis.
- Added instrumentation for on-demand mid-frame texture uploads in `FrameStats`.
* Refactor Vulkan resource and texture management, extend debug logging
- Updated smart pointer usage for consistency across Vulkan resource managers (`std::make_unique`).
- Removed redundant `cubeImageView` member and related cleanup logic; unified sampling view management.
- Added per-instance debug log counters (avoiding static state) for Vulkan texture uploads and bindings, improving visibility during initialization and run-time.
- Optimized `VulkanRenderer` property/feature getters by caching physical device properties and features during device creation.
- Improved memory region flushing logic for out-of-date offsets, aligning with Vulkan Memory Allocator behavior.
- Refactored render pass state tracking to reapply dynamic state reliably after mid-frame render passes.
- Enhanced validation and error handling for mismatched update texture formats.
* fix CI build warning
* Fix on-demand YUV texture locking and set alpha uniform for movie rendering in Vulkan
- Corrected bitmap lock type from `BMP_TEX_OTHER` to `BMP_AABITMAP` for YUV textures during on-demand loading.
- Updated movie rendering to bind alpha from the `MovieData` UBO (set 2, binding 4) for Vulkan, aligning behavior with OpenGL implementation.
* revert inadvertent changes introduced by a squash commit
* address ci issues
* remove wip stuff from code comments that make no sense to people who aren't me
* Remove unused LD_LIBRARY_PATH export and fix shader shadow map sampling.
* Refactor batched rendering uniform setup in Vulkan
- Removed unused fields from `genericData` uniform block, simplifying shader definitions.
- Updated Vulkan material uniform handling to align with OpenGL's batched rendering logic.
- Introduced `batched_data` struct for streamlined UBO updates, improving maintainability and clarity.
* Add `-hdr` command-line option for HDR nits configuration
- Introduced `-hdr` parameter to set paper white and peak luminance in nits, overriding in-game HDR settings.
- Added input validation with error feedback for incorrect format.
* Remove unused `MODEL_SDR_FLAG_SHADOW_MAP` macro from shader flags
* clean up unrelated changes
* Invalidate Vulkan state tracker bindings after external command buffer modifications
- Added `invalidateExternalBindings()` to `VulkanStateTracker` to handle stale pipelines, descriptors, and dynamic states caused by external Vulkan commands (e.g., ImGui renders mid-pass).
- Updated ImGui rendering flow to call `invalidateExternalBindings()` post-draw, ensuring consistent pipeline state for subsequent engine renders.
- Adjusted image usage flags to account for `eTransferSrc` in texture readbacks.
- Fixed barrier `dstAccessMask` and pipeline stage flags to ensure proper synchronization for image transitions.
* Add a few more generically useful lines to the log
* Simplify Qt deployment logic and improve handling for system-installed Qt on Linux
* add cmdline headers to make qtFred compile
* use VK_KHR_synchronization2 for sync and barrier purposes
* Simplify and clean up Qt deployment logic in CMake for qtfred
* update get_bitmap_from_texture to match the new API
* Enhance `-hdr` command-line option to force HDR output and support optional nits configuration with improved input validation and overrides.
* Improve Vulkan robustness, add device feature checks, and refine memory/logging.
- Added depth clamping support gated by device feature checks, with fallback where unsupported.
- Improved deferred lighting UBO overflow handling with user-accessible warnings and buffer size adjustments.
- Enhanced Vulkan logging for validation, allocation, and debugging:
- Automatic logging for descriptor pool exhaustion/fragmentation.
- Vertex format and resource destruction checks.
- Notifications for generic layout transitions and volumetric texture uploads.
- Consolidated shader logic to ensure Vulkan and OpenGL parity.
* Remove HDR10 encode shader and consolidate gamma correction logic for SDR and HDR10. Replace `Verify` assertions with `Assert`
* Add braces to conditional in object lighting logic for clarity
* Refine Vulkan memory allocation checks with `Verification` for improved error handling and messaging.
* Refine VulkanBuffer resize logic to preserve contents with CPU-side copy and add safeguards for non-coherent memory scenarios.
* Add detailed comments explaining descriptor array capacity constants in VulkanDescriptorManager
* Gate shadow support on depth clamp feature availability and clarify its necessity with improved comments.
---------
Co-authored-by: BMagnu <[email protected]>
Co-authored-by: Mara van der Laan <[email protected]>
Co-authored-by: Claude <[email protected]>
Accessible from the Tools menu, this dialog lists all ships or all
wings (selectable via a drop-down) and provides Move to top/up/down/
bottom buttons. Moves are applied immediately via the slot
reassignment utilities in missioneditor/common.h, using adjacent swaps
so the relative order of other entries is preserved.
Co-Authored-By: Claude Fable 5 <[email protected]>
reassign_wing_slot moves a wing between Wings[] slots, fixing up every
back-reference: Ships[i].wingnum, the Starting/Squadron/TVT_wings caches
(via update_custom_wing_indexes), the FRED-side parallel array
wing_objects, and cur_wing (passed via FredWingSlotConfig so non-FRED
callers can opt out). swap_wing_slots wraps it as a three-leg swap
through a temporary empty slot.
Also consolidates update_custom_wing_indexes (previously duplicated
verbatim in fred2/management.cpp and qtfred Editor) into common.cpp so
the new utility — and any future caller — has one shared implementation.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
reassign_ship_slot moves a ship between Ships[] slots, fixing up every
back-reference: Objects[].instance, Ai_info[].shipnum, Wings[].ship_index[],
Player_start_shipnum, Ship_registry's cached shipnum, and the FRED-side
parallel arrays Fred_alt_names/Fred_callsigns plus cur_ship (passed via
FredShipSlotConfig so non-FRED callers can opt out). swap_ship_slots
wraps it as a three-leg swap through a temporary empty slot.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
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]>
Move the New/Insert/Delete message buttons directly above the message
name field so creating a message and naming it no longer requires
travelling past the message text box.
Also focus and select the name field after New Msg and Insert Msg so
the placeholder name can be replaced by typing immediately, without an
extra click.
Menubar entries and keyboard shortcuts (e.g. Shift+E for the event
editor) created a new dialog instance on every activation. Route the
non-modal dialog slots through a showSingleInstanceDialog helper that
raises and focuses an already-open instance instead of creating a
second one.
Ship/Wing/Prop and the error checker keep their existing member-pointer
guards since other code references those open instances.
Although #7249 added the new support features to `check_for_25_1_data()`, the new fields were still written to the mission file in all formats except retail. Use a version check when writing the fields too.
The object list in orient_editor::OnInitDialog() predates props, so
every prop in the mission fired the "Unknown object type" warning when
the dialog opened, and props could not be selected as point-to targets.
Add them to the list like qtFRED does since #7402.
Co-Authored-By: Claude Fable 5 <[email protected]>
render_one_model() never passed the ship's team color to the model
renderer, so ships with an assigned team color displayed with their
class defaults. Set it the same way qtFRED does since #7403.
Co-Authored-By: Claude Fable 5 <[email protected]>
The team color combo box is only populated and enabled in single-edit
mode for a ship class that uses team colors. In multi-edit (or for a
class without team colors) the combo stays disabled, and OnOK() fell
into the unconditional else branch that reset the current ship's
team_name to none. Only apply the combo selection when the combo is
actually enabled, matching the qtFRED fix in #7403.
Co-Authored-By: Claude Fable 5 <[email protected]>
The ship flags dialog disables these checkboxes only when the selection
consists solely of player starts. In a mixed selection (player start plus
regular ship), OnOK() ran update_ship() on the marked player starts too,
and set_reinforcement() would emplace a reinforcement entry for the player
before the ship_name_lookup() (which skips player starts) failed, leaving
a bogus Reinforcements entry that persisted into the saved mission, plus
an Int3() in debug builds. Skip both flags for OBJ_START, matching the
qtFRED fix in #7402.
Co-Authored-By: Claude Fable 5 <[email protected]>
gr_opengl_tcache_set() leaves the previous binding active when it
fails, so the glTexParameteri calls that follow would modify the filter
state of an unrelated texture. Only set the parameter when the volume
texture actually bound.
Co-Authored-By: Claude Fable 5 <[email protected]>
At texture detail below maximum, opengl_create_texture() culls texture
dimensions on upload, but user bitmaps are streaming surfaces
(streamed animations, video) whose frames are updated through
gr_update_texture() with the bitmap's own dimensions. Once culled, the
glTexSubImage3D update exceeds the texture's actual size, so OpenGL
rejects it with GL_INVALID_VALUE and the animation silently freezes on
its first, downsampled frame. Culling them also saves nothing, since
full-size frame data is streamed every frame regardless.
Also assert in gr_opengl_update_texture() that the update dimensions
match the texture, so any future mismatch of this kind is caught in
debug builds instead of failing silently.
Co-Authored-By: Claude Fable 5 <[email protected]>
* Fix AI Bug with Strafing
Bug:
When a fighter or bomber enters strafe mode attacking a large ship, that large ship may die or depart, which results in the fighter/bomber AI slowing down to 0 and then not moving until another order is issued. This is most apparent in mods that force strafe to be used more via the ai profile flags (such as FotG).
Cause:
This bug is caused by the following. A fighter/bomber whose strafe target is destroyed drops to AIM_NONE (see ai_execute_behavior) with its active_goal still set, so a standing order like attack-any is never re-processed and the ship slows to zero and remains still until another order is issued.
Fix:
If we're chasing or strafing against large ship but have lost our target, we need to clear the active goal to ensure ai_process_mission_orders() re-evaluates our orders next frame. Of course gate this behind a flag.
Tested and update fixes the issue. We are very much hoping this can be a part of a point-release since it is substantially needed for FotG missions and we want to release in the next month or so. Happy to answer any questions or discuss, too!
* target 26.2
* Fix heap overrun in texture readback for the model transparency scan
gr_opengl_get_bitmap_from_texture() sized its readback buffer from the
texture cache slot dimensions and the bmpman frame count, but
glGetTexImage() returns whatever the bound GL texture actually contains.
When texture detail below maximum culls textures on upload, the two can
disagree, and the readback overruns the buffer (observed as heap
corruption when loading Zeus.pof with Texture Detail: Minimum). Size
the readback from the dimensions and layer count OpenGL itself reports
for the texture, and pad the staging buffer to 4x4 block granularity in
case a driver writes tiny compressed mips back in whole blocks.
The readback now also allocates the returned buffer and reports the
dimensions of the data it returns, because the second half of the bug
was on the consumer side: bitmap_lookup indexed the readback data by
the bitmap's own dimensions, so with any culling in effect the
transparency scan read mostly uninitialized memory. bitmap_lookup (and
its cache) now carries the actual readback dimensions, and it skips the
texture cleanly if the readback fails.
Also pairs the cache's vm_malloc allocations with vm_free instead of
free, and no longer ignores a failed tcache_set before reading back.
Co-Authored-By: Claude Fable 5 <[email protected]>
* Harden the transparency-scan texture readback
Return fully opaque from bitmap_lookup::get_channel_alpha() when the
bitmap has no alpha channel, since indexing channel 3 of a 3-channel
buffer reads out of bounds (currently unreachable because the only
caller checks bm_has_alpha_channel() first, but no longer a trap).
Per review, also assert at maximum texture detail, where no culling
occurs on upload, that the readback dimensions OpenGL reports match the
texture cache slot, so any future slot mismatch is caught immediately
in debug builds instead of surfacing as corruption.
Co-Authored-By: Claude Fable 5 <[email protected]>
* Fix inverted dimension check in opengl_export_render_target
The validation rejected the export only if both the width and the
height mismatched the texture cache slot, so a texture wrong in one
dimension passed through into opengl_get_texture, which trusts the
caller-supplied dimensions for its mipmap loop.
Co-Authored-By: Claude Fable 5 <[email protected]>
---------
Co-authored-by: Claude Fable 5 <[email protected]>
* Adapt particle at runtime
* Refactor EffectHosts
* fix issues
* cleanup
* Remove live transitive particles
* paticle hosts now do local correctly
* Fix effecthostparticle local mode
* again
* Set particle host orientation
* I don't like mixed local and global vectors
* agaiiin
* Fix validity check
* parent foo
* Fix bugs, hopefully finally
* refactor
* Flip new table option for intuitiveness
* Fix support for GCC9 due to issues with LWG3052
* Address feedback
In single-player missions, the "Set as Player Ship" button is supposed to make
the selected ship the one and only player start. FRED did this correctly, but
qtFRED routed the button through the same setPlayer() toggle used by the
multiplayer "Player Ship" checkbox, which only promoted the selected ship and
never demoted the previous player start. Since the checkbox is disabled in
single player, there was no way to demote the old start, so single-player
missions could accumulate multiple player starts.
Consolidate the exclusive logic into a shared helper,
set_single_player_start() in missioneditor/common.cpp, and call it from both
FRED's OnSetAsPlayerShip() and a new qtFRED model method,
makeSolePlayerStart(), which the button now uses. This also avoids
setPlayer()'s early return on stale dialog state, which could cause the button
to silently do nothing.
Follow-up to #7600.
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]>
* Add intermediate framebuffer for gamma correction to prevent flickering
* Fix frozen SCPUI briefing screen by resetting color mask before gamma pass
A masked draw pass inside the briefing map render leaves the GL color
mask fully disabled, and the Rocket UI material path never restores it.
Before cc63bfa7 this didn't matter: the frame was presented with a pure
glBlitFramebuffer, which ignores the color mask. The gamma-by-shader
change turned presentation into a regular draw, which respects the
mask, so every flip wrote nothing and the screen froze on stale
swapchain content while the engine kept rendering correctly underneath.
Hovering a briefing icon appended draws whose materials re-enabled
color writes, which is why the screen only updated while hovering.
Neutralize color mask and stencil state before the gamma draw, matching
the blend and depth-buffer neutralization already done there.
Fixes#7590
Co-Authored-By: Claude Fable 5 <[email protected]>
* Skip the gamma-correction pass when gamma is 1.0
The gamma shader is an identity transform at gamma 1.0, so present
Back_framebuffer directly via glBlitFramebuffer in that case (the same
present path used before the gamma shader was introduced), saving a
fullscreen draw per frame. The shader pass through GammaBlit_framebuffer
only runs when the effective gamma actually differs from 1.0.
Co-Authored-By: Claude Fable 5 <[email protected]>
* Reuse Scene_ldr_texture as the gamma-correction pass target
Scene_ldr_texture is dead scratch by flip time: all of its consumers
(tonemap, FXAA/SMAA, the final post-process pass) write before reading
within gr_opengl_post_process_end(), which completes before the flip,
and the gamma pass fully overwrites it before blitting it to the
window. Attaching it to GammaBlit_framebuffer instead of allocating a
dedicated texture saves a screen-sized RGBA8 allocation (~8 MB at
1080p, ~33 MB at 4K).
The dedicated allocation remains as a fallback for the case where the
scene textures were clamped to GL_max_renderbuffer_size and don't cover
the screen.
Co-Authored-By: Claude Fable 5 <[email protected]>
---------
Co-authored-by: Claude Fable 5 <[email protected]>
This allows double click to initiate search when a non-parent item is double clicked. Double clicking a parent will still expand/contract an item. Spacebar will also still initiate edit.
The defaulted moves copied the conditionally-owned name and its
ownership flag without clearing the source, so reallocation of
Builtin_messages (mods append custom types via #Message Types) freed
every strdup'd name out from under the surviving elements. Hand-write
the moves to reset the source and free the destination's old name.
Also fix copy-assignment, which leaked the old name and was unsafe
under self-assignment.
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]>
weapons_page_in(), weapons_page_in_cheats(), and weapon_page_in() each
duplicated the same ~60-line block for loading a weapon's models and
graphics. Extract it into a weapon_page_in_one() helper; the cheats
variant passes load_graphics = false to preserve its behavior of
loading only model geometry.
Also fix the tautological Assertion in the default render_type case:
the old condition was always true inside that branch, so it could never
fire. It now asserts render_type == WRT_NONE, which is the only other
legitimate value (invisible weapons).
Co-Authored-By: Claude Fable 5 <[email protected]>
FRED takes a long time opening mods that have a lot of particle entries in the particles table such as FotG (can take over a minute or more sometimes), so given FRED never renders or pages in particles, just skip the parsing.
* Fix two shockwave bugs
Bug:
Ship and SEXP created shockwaves with 0 speed last forever. A shockwave speed <= 0 is an "instant" shockwave, but the speed is used as a denominator for total_time. Dividing by 0 that creates in infinite shockwave (frozen at its initial radius of 1.0).
Fix:
Thus, add a safeguard to protect against the infinite duration. Note, ship-death and sexp shockwave run shockwave straight to shockwave_create(), whereas weapon shockwaves run weapon_do_area_effect() if <= 0 speed.
Bug:
It is possible the shockwave may have lifetime shorter than one frame (e.g. high speed, small radius), which by default results in shockwave applying no damage.
Fix:
Provide optional fix to ensure shockwave is not killed until after this frame's damage pass has run.
Tested and work as expected.
* just the 1expire fix
* comment cleanup
If a player ship is changed to a regular ship, be sure that
Player_start_shipnum does not still point to the old ship.
Consolidate the several near-duplicate copies of the "repoint
Player_start_shipnum to a valid player start" logic, in both FRED and
qtFRED, into a single shared helper, ensure_valid_player_start_shipnum()
in missioneditor/common.cpp.
Also add some guards in situations where Player_start_shipnum might
be -1.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
In both FRED2 and QtFRED, object_check_collision() only dispatched to
model_collide() for OBJ_SHIP and OBJ_START, leaving OBJ_PROP to fall
through to fvi_ray_sphere(). For flat, wide props the bounding sphere is
much larger than the visible geometry, making it impossible to
click-deselect without clicking far outside the model bounds.
Add an OBJ_PROP branch that calls model_collide() with the prop's model
and instance numbers, consistent with how OBJ_SHIP and OBJ_START are
handled, and move the mc.model_instance_num default initialisation above
the dispatch so the prop branch can override it with the real instance
number. In FRED2, also add an early-out guard for unoccupied prop slots
(QtFRED already gates on Show_props).
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Clean up volition_linked_list / list_range in linklist.h:
* Merge the copy-pasted iterator and const_iterator classes into a
single basic_iterator template.
* Make operator* and operator-> return the element pointer by value
and const-qualify them. Previously operator* returned a mutable
reference to the iterator's own internal pointer, so writing through
a dereference silently reseated the iterator rather than modifying
the list, and a stored reference could dangle.
* Add the five iterator traits typedefs plus a default constructor so
the iterators work with non-modifying <algorithm> functions such as
std::find_if, std::distance, and std::reverse_iterator.
* Add the implicit iterator -> const_iterator conversion and allow
iterator/const_iterator comparisons in either order, as the
standard's container requirements specify.
* Deduce list_range's node type from the head's next pointer rather
than from the head pointer itself (preserving the head's constness),
so that a list headed by a type derived from the node type -- such
as the self-relinking ship subsystem sentinel -- iterates as its
node type.
* Make the constructors explicit, remove a stale <utility> include,
and document that elements must not be removed from the list (nor
freed) inside a range-for loop, since the iterator reads the current
element's next pointer when it advances.
No behavior change at any existing call site; all existing loop
binding patterns compile unchanged.
Co-Authored-By: Claude Fable 5 <[email protected]>
Add const to query methods that the sexp_tree refactor left non-const:
- FRED2/qtFRED views: node, type, handle, and root lookups; label-edit
eligibility; annotation key resolution and comment getters; qtFRED's
validOperatorsForNode
- SexpTreeOPF: all instance get_listing_opf_* functions plus the
dispatcher and get_default_value (the class holds only a reference
to its model, so these are read-only by construction)
- SexpTreeModel: compute_context_menu_state and the two remaining
ctx_* helpers, which write only their state out-parameter
- ISexpTreeUI: the two read-only navigation callbacks
(ui_get_child_item, ui_has_children) in the interface and both
frontend implementations
Also convert the four listing functions that use no editor state at all
(species, language, functional_when_eval_type, wing_formation) to
static, removing the NOLINT suppressions that had silenced clang-tidy's
convert-to-static warning since before the refactor.
Co-Authored-By: Claude Fable 5 <[email protected]>
Add "Move to top / up / down / to bottom" controls -- vertical icon-button
strips beside both the event tree and the message list -- so events and
messages can be reordered in place.
Also add an "Insert Msg" button that inserts a message at the current
selection, mirroring the existing "Insert Event".
Tweak the message-area layout, drop the "Messages" label, and edit the
AFX_DIALOG_LAYOUT table for proper behavior when the dialog is resized.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Root-label annotations (event-name comments/colors) that lose their
node — e.g. because their event was deleted — could survive
indefinitely and surface on the wrong items:
- saveToGlobal's root-key branch kept an unresolvable annotation in
Event_annotations with an empty path instead of marking it for
pruning, so once a zombie was persisted in a mission file it
survived every save/load cycle.
- getByKey(-1) matched annotations whose node_index had been reset to
the unresolved sentinel, so such a zombie's comment could display on
any item that has no annotation key of its own.
Guard findByKey against the -1 sentinel, and prune any annotation
whose rebuilt path is empty at save time. (The complementary
in-session fixes — removing a root-label annotation when its event is
deleted and re-keying it when insert-operator changes the formula
node — are handled in the shared model and actions by 'Keep event
annotations attached to their node across tree mutations'.)
Also restore root-label comments in the FRED2 help box: update_help
resolved comments by model node index, which is -1 for labels. Route
it through a get_item_comment virtual that the event editor's tree
overrides with its annotation key lookup, matching pre-refactor
behavior. (qtFRED renders comments per-item via NoteRole, which
already covers labels; its help box does not show comments by design.)
Co-Authored-By: Claude Fable 5 <[email protected]>
Annotation +Path: values written by pre-refactor FRED were built over
the UI tree, where each event's root item is the event-name label and
every element after the event index is a child position at successive
levels below it: [event] is the label, [event, 0] the top operator
(the label's only child), [event, 0, k...] its descendants. The
refactored SexpAnnotationModel built paths over tree_nodes[], which
represents the label's single child directly as the formula node, so
paths came out one level shallower: existing missions' annotations
resolved one level too deep (and were re-saved wrong), and a
top-operator annotation produced the length-1 path that decodes as a
root-label key, silently migrating onto the event label.
Emit and consume the label-level child position in
buildPath/resolveFromPath to preserve the on-disk contract. Child 0
resolves to the formula node and any other index fails resolution,
matching the old traverse_path behavior of walking off the label's
sibling list. Annotations on the event label itself are unaffected:
they remain the length-1 path handled by the root-key branch.
Co-Authored-By: Claude Fable 5 <[email protected]>
Post-refactor successor of fix/annotations, rebuilt for the shared sexp
tree model introduced by the sexp_tree refactor (#7301). The refactor
re-keyed annotations from UI item handles to tree_nodes[] indices, which
fixed most of the original decoupling by construction and already prunes
regular-node annotations in free_node2(). Two gaps remained, plus one
qtFRED regression:
- free_node2() only removed annotations keyed by node index, never a
root-label annotation keyed rootKey(formula). Deleting an event left
that annotation live, so a later event whose formula reused the slot
inherited the deleted event's annotation. Remove the root key too;
since the global Event_annotations are only rewritten at save, the
removal still survives a Cancel.
- Inserting an operator above a labeled root changes the event's formula
node, orphaning the root-label annotation keyed to the old index.
Re-key it in insert_operator() so it follows the event. (This is the
only such flow: replace_operator() reuses the node in place.)
- qtFRED reorderByRootFormulaOrder() reloaded annotations from the
global state, discarding any annotation edits made since the dialog
was opened. A root reorder changes neither node indices nor formulas,
so drop the reload.
Co-Authored-By: Claude Fable 5 <[email protected]>
A change introduced by #7529 caused a shader compile error on Mac due to an
attempted swizzle of texture(sampler2DArrayShadow,...), which returns a single
float value rather than a vector.
The buffer round-trip was left over from the pre-refactor char-array
days: *item = *list already copies the text, and no caller reads the
buffer after the call. Removing it also removes the unbounded strcpy
into the callers' 256-byte stack buffers.
Co-Authored-By: Claude Fable 5 <[email protected]>
The only caller, SexpTreeActions::insert_operator(), passes a freshly
allocated tree_nodes index as the parent, and allocate_node() reuses
freed slots, so 0 is a valid parent index. The old 'if (parent)' test
(and qtFRED's 'parent > 0' copy of it) treated node 0 as attach-at-
tree-root, visually reparenting the wrapped branch to the root while
the model data placed it under node 0. Since the assertion already
requires parent >= 0, attach to the parent's handle unconditionally.
Co-Authored-By: Claude Fable 5 <[email protected]>
SexpTreeOPF and SexpTreeActions hold references to their owning model
and UI, and SexpTreeModel owns an OPF member back-referencing itself,
so a copy would compile (copy construction was not implicitly deleted,
only copy assignment) but leave the copy's _opf silently bound to the
original model. Nothing copies or moves these classes today; delete
the operations so nothing can.
The other sexp tree types were checked and are correct as-is:
SexpContextMenuState already deletes copy and implements move via
swap; SexpAnnotationModel and the item structs are deliberate value
types; sexp_list_item's shallow copy with manual destroy() is the
inherited idiom its callers rely on; the views are non-copyable via
their MFC/Qt base classes.
Co-Authored-By: Claude Fable 5 <[email protected]>
When Qt6 falls back to using prebuilt libs force the option to enabled to
avoid an erroneous, but otherwise harmless, system lib usage message during
reconfigure.
Only the event, goals, cutscenes, and campaign dialogs install a
SexpTreeEditorInterface; the ship, wing, message, briefing, and
debriefing editors left _model._interface null, and the shared OPF
code dereferences it unconditionally (getMessages, getMissionNames,
getMissionGoals, getMissionEvents). Right-clicking e.g. the
event-name argument of is-event-true-delay in a ship arrival cue
crashed FRED.
Install a default-constructed interface at construction, mirroring
qtFRED initializeEditor. The base implementations match the old
m_mode == 0 global fallbacks and the empty flag set keeps all
flag-gated paths behaving as before; dialogs that provide editor
context overwrite the fallback as they always did.
Co-Authored-By: Claude Fable 5 <[email protected]>
FRED2 rejects an icon ID edit that would collide with another icon,
warning and reverting the field, but qtFRED's setIconId() applied the
value unconditionally. Two icons could be given the same ID in a stage
(making find_icon and forward propagation ambiguous), or a global rename
could merge two distinct icon chains by reusing a downstream ID.
setIconId() now mirrors FRED2:
- An ID is a single-icon concept, so it operates on the current icon
rather than the whole selection (applying one ID to several selected
icons would itself create a same-stage collision).
- Rejects an ID already used by another icon in the current stage.
- When propagating forward (Change Locally off), rejects an ID already
used in a later stage, since the rename would merge two icons.
- Otherwise applies the change and renames the icon's forward copies by
matching the old ID, respecting Change Locally.
It returns false when a change is rejected; the dialog resets the spin
box to the model's value. The spin box is switched to non-keyboard-
tracking so validation runs when the edit is committed (focus-out/Enter)
rather than on every keystroke, avoiding a modal warning on a transient
value mid-typing.
Co-Authored-By: Claude Fable 5 <[email protected]>
- OnMakeIcon() left closeup_label uninitialized. The icon arrays are
only cleared at mission reset, and delete_icon shifts structs down
leaving stale copies behind, so a newly created icon could inherit a
deleted icon's closeup label and then propagate/save it. Clear it,
matching qtFRED's makeIcon.
- Case-only label edits (e.g. "alpha" to "Alpha") did not propagate
forward: the change detection used stricmp, so a case-only change was
treated as no change and applied only locally. Use strcmp for both
label and closeup_label. qtFRED already compares case-sensitively.
- OnPropagateIcons() propagated a snapshot that could predate the text
typed into the icon fields, since it never committed pending dialog
edits first. Call update_data(1) before propagating.
- copy_stage() copied every stage field except draw_grid, so inserting,
deleting, or reordering stages reset the grid-disabled flag. Copy it
through (and default it to true for freshly created stages). qtFRED's
copyStageData already preserves it.
Co-Authored-By: Claude Fable 5 <[email protected]>
- Negative icon IDs are now rejected. FRED2 assigned the ID edit box
value unconditionally even though it only validated collisions for
non-negative values, so a negative ID could slip through and silently
break find_icon()/propagation. It now reverts to the previous ID (with
a warning, but only when the value was actually changed, to avoid a
message-box loop on refresh). qtFRED gets a matching defensive guard in
setIconId().
- OnMakeIcon() now skips IDs that are already in use. It previously used
Cur_brief_id++, but Cur_brief_id is only advanced at mission parse, so
a manual ID edit that raised an icon ID above it would cause the next
new icon to silently collide. The new get_unused_briefing_icon_id()
helper advances Cur_brief_id past any value already taken by an icon in
the current briefing. qtFRED's makeIcon() already computes maxId + 1,
which inherently skips existing IDs.
Co-Authored-By: Claude Fable 5 <[email protected]>
- get_next_icon() used `stage_loop > num_stages` as its terminating
check, allowing it to read one stage past the live range. On a full
MAX_BRIEF_STAGES briefing this is a genuine out-of-bounds array
access; below capacity it reads a non-live stage. Changed to `>=`.
- Icon scale_factor and the editable flag bits (highlight, mirror,
wing, cargo) were always written locally, ignoring the "Change
Locally" checkbox and never propagating forward like the other
attributes. Route them through the same reset_icon_loop/get_next_icon
propagation so they match id/label/type/team/ship_class (and qtFRED).
Co-Authored-By: Claude Opus 4.8 (1M context) <[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]>
The SWH_SECONDARY case of the ship_bank setter was copy-pasted from the
primary case and still assigned primary_bank_* fields; it now assigns
the secondary_bank_* fields.
Co-Authored-By: Claude Fable 5 <[email protected]>
Never called from anywhere, even dating back to retail FRED. It also
contained a latent bug: add_pending_message was missing a break, so it
would have filled every free slot in the buffer with the same message.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Since FS1 retail, a large ship could get permanently stuck circling its
final waypoint. Waypoint completion requires the ship center to pass
within MIN_DIST_TO_WAYPOINT_GOAL + sqrt(radius) of the point (~37m for
a 1000m-radius capital ship), and the check only runs when the ship
covers 0.1m in a single frame (a framerate-dependent minimum speed).
At any speed that passes that gate, a capital ship turning at
2PI/(3*rotation_time) has a turning circle of hundreds of meters, so
once it overshoots a misaligned final leg it can never re-aim into the
completion bubble: an endless overshoot-turnaround-miss loop.
Add ai_profiles flag "$fix big ship waypoint completion:"
(Fix_big_ship_waypoint_completion), enabled by default for mods
targeting 26.2. With the flag set:
- big/huge ships complete a waypoint anywhere within their own radius
of it (matching what the docking path code has always done), while
small ships keep the retail sqrt(radius) tolerance; and
- the completion check runs every frame instead of requiring 0.1m of
travel per frame, removing the framerate-dependent minimum speed
(which at 240fps is 24 m/s, enough to affect fighters too).
With the flag unset, behavior is unchanged from retail.
Co-Authored-By: Claude Fable 5 <[email protected]>
For standard translation offsets, the wrong axis was being used for translation. Fix that. Also fix a string offset when parsing a custom axis.
Follow-up to #4582 and #3056.
When an icon is deleted, remove any lines that reference it, and fix the
indexes of lines that reference the icons shifted down to fill the gap.
Previously stale lines silently reattached to the wrong icons. This
matches the behavior of qtFRED's deleteCurrentIcon.
Co-authored-by: Claude Fable 5 <[email protected]>
* fix stale color_to_draw causing draw_model_icon crash with model_id of -1
In draw_wing_block(), color_to_draw was initialized once outside the
slot loop while bitmap_to_draw was reset every iteration. Once any
slot in the wing took the model-icon path, color_to_draw stayed
non-NULL for all remaining slots. A later slot whose icon had no
model (model_index == -1) and no bitmap frame to draw (e.g. a carried
icon that has not moved yet, or an icon ani with missing frames) then
fell into the color branch and called draw_model_icon() with a model
index of -1, crashing in model_clear_instance().
Reset color_to_draw each iteration, and give draw_model_icon() the
same model_id guard that draw_model_rotating() already has.
Co-Authored-By: Claude Fable 5 <[email protected]>
* guard against NULL color_to_draw when an icon ani is missing frames
In draw_ship_icon_with_number() and wl_render_icon(), a bitmap-based
icon takes the bitmap branch initially, so color_to_draw is never
assigned. If a hot/selected/disabled state then swaps in an icon ani
frame that does not exist (e.g. a single-frame or truncated icon ani),
the frame index is -1, the final dispatch falls into the color/model
branch, and gr_set_color_fast() dereferences a NULL color.
Fall back to the normal icon color in that case.
Co-Authored-By: Claude Fable 5 <[email protected]>
---------
Co-authored-by: Claude Fable 5 <[email protected]>
The Align button repositions wing members by assigning objp->pos and objp->orient directly, skipping the post-move bookkeeping that the viewport drag and orient editor paths perform. A wing member with a docked partner (e.g. an attached support ship) would be moved to its formation slot while the partner stayed behind with broken dock geometry.
Fix by calling object_moved() for each repositioned member, which resets the Docked_already_handled flags and drags docked partners along. No-op for undocked ships.
Verified in FRED by docking a ship to a wing member and pressing Align.
Co-authored-by: Claude Fable 5 <[email protected]>
When FRED2 saves a mission, OnSaveDocument() reloads it via
load_mission(MPF_FAST_RELOAD). That reload calls clear_mission() ->
fred_render_init() -> create_default_grid(), which rebuilds The_grid as
the default origin-centered XZ plane, discarding any adjustments made in
the Adjust Grid dialog (e.g. the X-Z Plane Y Level). The grid is editor
display state and is not stored in the mission file, so the reload had
nothing to restore it from.
The camera (view_pos/view_orient) is already preserved across this reload;
apply the same preserve-and-restore pattern to the grid by capturing its
orientation, center, dimensions, and square size before clear_mission()
and rebuilding it with create_grid() afterward.
qtfred is unaffected because its save path does not reload the mission.
Fixes#7548
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
I somehow added an older, broken version of the cache-master workflow during
the recent workflow update. This should fix the architecture bug preventing
the Mac cache from working properly, as well as increasing the max cache size
from 500 MiB to 750 MiB.
clone() allocated fresh vert/radius_list buffers without freeing the
ones already owned, so assigning over a live batcher leaked both. It
also never copied buffer_offset, and the copy constructor called it
with no member initialization at all -- so every copy-constructed
batcher carried an uninitialized buffer_offset. Free the existing
buffers in clone(), copy buffer_offset, and delegate the copy
constructor to the default constructor so clone() sees initialized
members (which is also what makes its new frees safe on that path).
Also add noexcept move operations, which the user-declared copy
operations had suppressed, so by-value handling can transfer the
buffers instead of deep-copying them.
None of these defects were reachable from current callers (the static
batch maps mutate entries in place); this closes the latent hazards.
Co-Authored-By: Claude Fable 5 <[email protected]>
A sweep for the w_bank pattern (raw owning handles in types that are
copied, moved, or shifted by value) found four more instances:
p_object: the destructor frees dock_list, which suppresses the implicit
move operations, so Parse_objects growth copied elements -- safe only
because dock lists happen to be built after parsing finishes. Wrap
dock_list in the new util::reset_on_move<> (a handle whose move resets
the source) and explicitly default the rule of five (with a user-defined
move assignment that frees any existing dock list before the memberwise
transfer), so moves now transfer the dock list.
DecalDefinition: the defaulted moves copied the bitmap handles without
resetting the source, so destroying a moved-from element would
bm_release live handles -- safe only because DecalDefinitions grows
before loadBitmaps runs. Wrap the handles in reset_on_move<int, -1>.
cmission: FRED's remove_mission overwrote the removed slot's five
vm_strdup'd strings without freeing them (a leak on every removal) and
left the vacated slot aliasing the surviving copy (a double-free if the
slot is later reused without reassigning every string). Factor the
string cleanup out of mission_campaign_clear into
mission_campaign_free_mission_strings and call it before the overwrite,
nulling the vacated slot afterward.
Undo_stack: the destructor deletes the tracked items, but the implicit
shallow copy was used to transfer stacks into the undo system, kept safe
only by an immediately-following untrack() call. Delete the copy
operations, default the move constructor and implement move assignment
as clear-then-exchange, so an assigned-over stack deletes its own items
first and the source is guaranteed empty.
Co-Authored-By: Claude Fable 5 <[email protected]>
w_bank: add a move constructor. object_copy_including_array_member
returns by value, and without a move constructor the return fell back
to the shallow copy constructor whenever NRVO was not applied (e.g.
MSVC debug builds), after which the local's destructor deleted the
freshly allocated arrays -- leaving the stored bank dangling and
double-deleting at model unload. Also add noexcept to the move
operations, replace the destructor call in move-assignment with
explicit delete[]s (using an object after its lifetime has ended is
undefined behavior), guard against self-move, and document that the
defaulted copy constructor is intentionally shallow for
object_copy_including_array_member's copy-then-replace pattern.
LuaThread: declare the defaulted move operations noexcept. This
exposed that LuaTable was not movable at all (its user-declared
destructor suppressed the implicit moves), so LuaThread's implicit
move spec was formally throwing -- a hard error on gcc 9, which
still requires the spec on a defaulted redeclaration to match the
implicit one. Restore LuaTable's rule of five and declare the
LuaValue and LuaFunction copy operations noexcept (they only copy a
shared_ptr, a raw pointer, and an enum), making the noexcept claims
hold throughout the hierarchy.
Co-Authored-By: Claude Fable 5 <[email protected]>
Disable static libstdc++/libc++ by default now that we've moved to using a
base of Ubuntu 22.04. Using a static c++ library also poses a possible issue
with our prebuilt Qt6 libs since they are dynamically linked.
Disable automatic use of libc++ when static c++ library is enabled. The
options can and should be used independently.
Disable using libc++ for clang by default since it conflicts with the prebuilt
Qt6 libs as well as the system Qt6 libs on most Linux distros. An message has
been added to QtFRED config to error/warn if this is likely to be a problem.
CJumpNode stored a private m_pos field that duplicated the position
already held by its Objects[] entry. The field was set once during
construction and never updated afterward, so any subsequent movement
(e.g. FRED dragging) would leave m_pos stale while Objects[m_objnum].pos
held the authoritative value. Every external caller already used
GetSCPObject()->pos instead; GetPosition() had zero call sites.
- Remove the m_pos field and its initialization in both constructors,
the move constructor, and the move-assignment operator.
- Pass the constructor's position argument directly to obj_create()
instead of routing through m_pos.
- Repoint GetPosition() at Objects[m_objnum].pos so it always returns
the live, up-to-date position.
- Add GetRadius() to expose the cached m_radius, and use it in
jumpnode_get_which_in() instead of the redundant model_get_radius()
call.
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Use Qt deployment cmake script for all platforms. This uses the platform
specific method where possible (windeployqt/macdeployqt) and a generic
deployment script on other platforms.
This also uses a crazy RPATH hack on Linux, which is necessary for it to
find the prebuilt Qt libs and deploy them. Qt does not appear to allow
passing tool options for the generic deployment script so we can't tell
the relavent cmake functions where to look for our libraries even though
they support such functionality.
With the new QtFRED help changes it gets the filename wrong, including the
names of multiple files by mistake. This tweaks the find command to ignore
those other files.
Move shutdown to run before Qt destroys the opengl context
disconnect visibility changes as it accidently runs after windows destruction due to QT weirdness
If the carrier a fighter launched from was destroyed earlier in the
mission, its Ships[] entry retains stale bay door state while its
object and model instance are already freed (objnum/model_instance_num
== -1). When the fighter later departs, ai_manage_bay_doors would still
try to animate the dead carrier's bay doors, calling
model_get_instance(-1) and asserting/crashing.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
* clean, fix, and update workflows
Add support for Windows ARM64 builds.
Try to rely on build defaults for various options so that workflow
modifications aren't required for basic feature changes.
Remove Vulkan and Qt setup from workflow, instead relying on new
prebuilt libs.
Update SFTP image and Linux build image to newer release.
Add ccache setup for macOS.
Update ccache action to a version compatible with Node v24.
* add tts support
* correct type
* more robust method binding and hide volume option
* missing ifndef
* thread safe jnienv
* check jni env before use it
* remove opt in volume option and cleanup
* cleanup
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
* long project will be long
* add shared foundation files
* unify some shared types across both editors
* sexptreemodel framework
* move opf functions to the model
* move shared functions into the model
* move variable/container stuff to the model
* sexptreeactions and ui interface
* wire the model into the ui
* move some shared logic to the model
* move more methods to the model
* move clipboard to model
* create new right click menu model
* begin connecting the new right click menu
* wire up the new right click menu in fred
* wire up the new right click menu in qtfred
* move help text and visuals to model
* move menu option enable disable to model
* wire up sexp_tree to the model
* rename sexp_tree files to sexp_tree_ui
* fix build errors
* fix warning
* remove all opf forwarders
* remove some forwarder methods
* connect qtfred events editor directly to model
* wite plan for unifying tree types
* replace legacy m_mode with treeflags
* fix qtfred campaign dialog
* fix qtfred ship/wing dialog trees
* build error
* documentation
* more documentation
* even more documentation
* move more opf functions to opf file
* clean up context menu function
* move default argument to opf file
* build errors
* fix qtfred dialogs and annoations
* new shared annotations model
* sexp_tree_ui to sexp_tree_view
* documentation pass
* document annotations model
* delete the plan
* move event annotations to the new model
* generic cleanup
* remove some old defines
* cleanup includes
* more cleanup
* parenthesis
* more parenthesis
* variable collisions
* too many parenthesis this time
* clang modernization
* variable names again
* more clang and assertions
* static cast
* clang again
* fix some bugs and issues
* Refactor sexp tree action duplication into SexpTreeActions
* fix a few more minor issues
* avoid clang false positive
* rebase tweaks
* fix annotations issue
* fix typo and two small bugs claude found
* fix event editor tree widget loading
* fix ship and wing sexp tree editors in qtfred
* fix qtfred briefing and debriefing trees
* fix a regression Claude found
* address feedback
* fix annotations for root items in qtfred by copying fred's method
* address feedback
* rescope variables
* clang
brief_stage owns its icons and lines buffers through raw pointers, so the
implicitly generated copy/move operations silently alias those buffers
across two stages. Delete them and provide a custom swap() that
exchanges members (keeping each slot with a distinct buffer), plus a
reset() that restores the default-constructed state.
Update brief_compact_stages, the only code that assigned brief_stage
objects: shift stages down by swapping (equivalent, since the removed
stage buffers were already freed and the tail is cleared afterward) and
clear the tail entries with reset().
Co-Authored-By: Claude Fable 5 <[email protected]>
Replaces the copy-then-reset idiom with std::exchange in five
steal-and-reset move constructors and assignment operators.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The numeric branch of the OPF_GAME_SND check in check_sexp_syntax never
actually ran until the type2 variable-overload bug was fixed, so missions
using a sound index of -1 ("no sound" / "default") loaded fine. Now that
the check is live, explicitly allow -1, which the runtime already treats as
an invalid (unset) sound. Also return the more descriptive
SEXP_CHECK_INVALID_GAME_SND / SEXP_CHECK_INVALID_FIREBALL error codes, and
let nested-operator (SEXP_ATOM_LIST) arguments fall through since their type
is already validated upstream.
Also route the Lua SEXP soundentry argument through sexp_get_sound_index so
it accepts a table index, an operator, or a name like the core SEXPs do,
instead of only a name.
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
If invalid UTF-8 is encountered, return the standard Unicode replacement character 0xFFFD. When incrementing or decrementing, make a best effort to follow the code's instructions. It might produce one or more � characters, but that's better than an Error and a hard crash.
Also move character constants to standardized locations.
CButton::SetBitmap blits a bitmap verbatim and does not perform the
magic-color substitution MFC applies when loading toolbar bitmaps. So a
button bitmap's background -- the legacy C0C0C0 gray baked into play.bmp
et al., or a magenta transparency key -- was drawn literally, reading as
a dark/colored rectangle instead of matching the real button face
(~F0F0F0 on modern Windows), and a disabled bitmap button embossed its
whole opaque rectangle into a solid gray square.
Add load_button_icon() to management.{cpp,h}, which builds an icon from
a button bitmap by keying out a background color into a transparency
mask. Driven through BS_ICON/SetIcon, the OS blends it with the button
face and grays it correctly when disabled. Route every play/media button
through it (event editor, briefing, debriefing, command brief, music
player, sound environment). Also add load_btnface_mapped() -- a
toolbar-style color remap -- kept as a lighter alternative for
always-enabled buttons.
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
MMessage's avi_info/wave_info unions hold strdup'd filenames in FRED
(indices in the game), but moves copied the pointers without nulling
the source, so every vector shift on Messages left moved-from elements
aliasing live allocations -- one careless edit away from a double-free.
Wrap each union in a MessageMediaRef struct whose moves null the source
and whose copies stay shallow (the event editor's backup pattern copies
then re-strdups). MMessage keeps its implicit copy and gains a correct
implicit move; access syntax at all use sites is unchanged.
Add a message_free_media_names() helper and use it at the FRED
delete/wipe sites. Two fixes ride along: messages_init() now frees
mission messages' media names before discarding them, closing a leak
that fired on every mission load in FRED; and the message editor's
OnDelete now uses the move-based array_remove_slot instead of a
copy-shift that left a stale aliasing tail.
No destructor: the active union member depends on Fred_running, and
shallow copies alias, so freeing remains explicit.
Co-authored-by: Claude Fable 5 <[email protected]>
Turrets with initial animations flip animation angles every frame in the techroom. The commit returns TriStateBool from model_get_cached_ui_render_instance specifically so callers can run setup only when a new instance is created, but only `render_tech_model` (the Lua path) actually checks it.
Since the instance is cached and persists across frames, every frame re-runs clearShipData + initial-animation start on an already-animated instance, re-applying the initial animations relative to the current (already-animated) pose. This is what seems to produces the per-frame flip/jitter.
This PR caches it to prevent this, and fixes#7526. Tests confirm it works as expected.
Center reticle does not move if player is looking around, but there is a bug where the drawn firepoints of the center reticle do impromperly sway when the player is looking around. This is b/c the live global Eye_matrix, which has the free-look rotation baked into it by `object_get_eye()` then `compute_slew_matrix(eye_orient, &Viewer_slew_angles)`
Thus, do note use `Eye_matrix` b/c firepoints will sway if looking around, instead just use 'object_get_eye' with the properly set values.
Tested and fire-points work as normal but also fix the issue when looking around in free-look or TrackIR.
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.
Several dialogs already null their global at the top of DestroyWindow, but a few do not: briefing, debriefing, event, background, message, cutscene, goal, and Fred_view_wnd. OnClose nulls in those five cover the user-initiated close path, but any teardown that bypasses OnClose leaves a dangling pointer that could be dereferenced.
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
A user-declared destructor, even an empty one, suppresses the implicit
move operations, so waypoint and waypoint_list were silently copy-only:
every Waypoint_lists erase, insert, and reallocation deep-copied entire
lists, and inserting a waypoint mid-path copied every shifted waypoint.
Removing the destructors restores the implicit moves (correct and
noexcept, since the members are vec3d/int and SCP_vector/SCP_string),
turning those shifts into pointer steals. The implicit deep copies
remain available and unchanged. Waypoint identity is index-encoded in
Objects[].instance and renumbered on insert/erase, so relocation
semantics are unaffected.
Co-Authored-By: Claude Fable 5 <[email protected]>
Due to a copy-paste error, the event editor would always be marked modified. Fix the comparison.
This bug originally appeared in QtFRED also, but no longer does.
Follow-up to #6529.
* Fix 'ignore if dead' flag
Fixes#7508.
The subsystem flag "ignore if dead" that many mods use is supposed to "prevent homing weapons from attempting to hit the now destroyed submodel and instead tells them to home on the main hull of the target."
Though, in actuality, the code makes the weapon dumb fire instead of home. This bug means if you destroy a subsystem with this flag, then lock onto it with an aspect weapon and fire the weapon, the weapon will just dumb fire.
With `wp->homing_subsys` cleared as this PR does, the homing code at `weapons.cpp`:5730 falls into its else branch and picks an attack point on the ship body (`ai_big_pick_attack_point / hobjp->pos`) — which is what the flag promises. Javelins, which can only home on engines, will still correctly try to re-acquire another engine in the block just below and drop lock if there's none.
This fix is tested and now the flag works as expected.
* fix for javelins
Fixes a startup assertion failure in Star Fox: Event Horizon, where a Lua
call to gr.freeAllModels() wiped Polygon_model_instances but left the UI
render instance cache holding stale indices. The next state transition
called model_clear_cached_ui_render_instances() which asserted in
model_delete_instance().
Closes#7513
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
After a drag-drop that consumed the last unit of a roster class, the
active list could shrink while SS_active_list_start was non-zero,
making items above the stuck offset (including default ships returned
to the pool, such as Seth fighters) unreachable: the up-arrow handler
short-circuits when size <= max_show without resetting the offset.
- Clamp the preserved scroll offset in ss_synch_interface() against
SS_active_list_size - MAX_ICONS_ON_SCREEN.
- Harden common_scroll_down_pressed() to reset *start to 0 when the
whole list fits on screen.
Fixes#6240
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
* framework for support ship rearm pool and flags
* scripting api
* FRED support
* QtFRED support
* do not save non-player-allowed weapons
* tvt and mission versioning
* fix variable name
* minor fixes and clarity
* oops
* add qtfred help docs
* fixes and cleanup
* clang and readability
* address feedback
* address feedback
* new mine weapon type
* some fixes and cleanup
* fix some parsing issues
* make sure mines get plotted
* make mine spawned objects can get a correct target
* some cleanup and additional features
* chasing mines
* some Lua tweaks
* generalize proximity detonations
* minor tweaks
* collapse namespace
* address feedback
* ship texture replacement stylization pass
* refactor UI to be dynamic
* properly save textures and load them on apply
* clang
* address feedback
* clang
Implement a spherical-coordinate orbit camera for both the MFC (FRED2)
and Qt (qtFRED) editors, providing intuitive 3D viewport navigation
similar to other 3D editing tools.
Controls:
- Middle mouse drag: orbit rotate around pivot point
- Shift + middle mouse drag: pan the pivot point
- Right mouse drag: orbit rotate (alternative to middle mouse)
- Shift + right mouse drag: pan (alternative to shift + middle mouse)
- Mouse wheel: zoom in/out
- Right click without drag: context menu (preserving existing feature)
Camera pivot selection:
- If an object is selected, orbit around that object
- Otherwise, intersect the camera forward ray with the current grid
plane to find a natural pivot point
- Falls back to grid center if the camera is parallel to the grid
Grid-plane awareness:
- Orbit axes are derived from The_grid->gmatrix using vm_vec_rotate
and vm_vec_unrotate, so the camera orbits correctly on all three
grid planes (XZ, XY, YZ), not just the default XZ plane
- The look-at matrix uses the grid's up vector (uvec) rather than a
hardcoded world-up direction
Robust zoom/pan scaling:
- Zoom uses an exponential formula (powf) so the distance multiplier
is always positive regardless of physics_speed setting (1-500)
- Pan uses a clamped speed factor to avoid excessive movement at high
physics_speed values
State management:
- Keyboard camera movement (process_controls) invalidates orbit state,
so the next mouse drag re-initializes from the current view
- Orbit state is per-viewport in qtFRED (EditorViewport members) and
global in FRED2 (matching existing conventions in each codebase)
Implementation:
- FRED2: orbit math in fredrender.cpp, mouse handlers in fredview.cpp
- qtFRED: orbit math in EditorViewport.cpp, mouse/wheel handlers in
renderwidget.cpp; RenderWindow::event() updated to forward middle
button and wheel events to RenderWidget
Also fix an AND vs OR bug in FRED's process_controls().
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
The OPF_SUBSYSTEM argument-conversion path in LuaSEXP only verified
has_shipp() before calling ship_entry->objp(). A ship registry entry
retains its shipnum after the ship is destroyed or departed, but its
objnum is reset to -1, so objp() either asserts (debug) or dereferences
Objects[-1] (release) when the entry is looked up by Lua scripting
during, for example, an OnMissionAboutToEnd hook.
Tighten the check to has_objp() so absent ships short-circuit to an
empty handle, and correct the early-return type from l_Ship to
l_Subsystem. Apply the matching type correction to OPF_DOCKER_POINT,
which has the same return-type mismatch but no CTD because it never
dereferences objp().
Fixes#7206.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two related fixes flagged by an audit of vm_vector_2_matrix_norm callers:
ParticleEffectAction: locals.direction defaulted to vmd_zero_vector,
which would trip vm_vector_2_matrix_norm's unit-length assertion (and
divide by zero in release) when an action program emitted a particle
effect without first running a Set Direction action. Default to
vmd_z_vector so the unset-direction path always feeds a unit vector.
matrix_h / Lua orientation type: the element indexer (m[1..9] = x)
wrote arbitrary floats straight into mtx.a1d[idx] and the resulting
non-orthonormal matrix could flow into obj->orient via the Orientation
virt-vars on object/modelinstance/subsystem, breaking downstream engine
code that assumes the basis vectors are unit length. getInterpolated
had the same problem by design (pure linear interp, no normalization).
Adds a fourth MatrixState, NeedsOrthonormalize, which the indexer
setter and getInterpolated use to flag their output. ValidateMatrix
and ValidateAngles now call vm_orthogonalize_matrix when they observe
that state, so any consumer that reads through GetMatrix/GetAngles
gets a valid orientation without each call site needing its own guard.
getInterpolated is also marked ADE_FUNC_DEPRECATED at FSO 26.0 in
favor of rotationalInterpolate; mods targeting older versions keep
the legacy linear blend (now safely orthonormalized on use).
Per @BMagnu's review feedback on #7493: factor the yborder calculation
and clip-rect application into two file-local helpers so future changes
to the letterbox proportions live in one place.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
game_render_hud calls gr_reset_clip() before game_flash_diminish, so the
sunspot palette flash was painting over the black bars during the
supernova camera cut. Re-apply the letterbox clip around gr_flash when
it would otherwise overdraw the bars (supernova HIT+ or GM_DEAD),
matching the condition already used in game_set_view_clip.
Partial fix for #4152.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Setting SDL_HINT_JOYSTICK_THREAD=1 before SDL_InitSubSystem(SDL_INIT_JOYSTICK)
tells SDL2 to run joystick polling and HID device-detection on a dedicated
background thread, rather than processing them inline inside SDL_PollEvent
on the main thread.
Without this hint, every WM_DEVICECHANGE broadcast (which Windows sends when
*any* HID device wakes, sleeps, or pulses the USB bus) causes SDL to walk
every HID device class via SetupAPI / cfgmgr32 from inside SDL_PollEvent,
stalling the frame loop for multiple seconds on machines with many HID
peripherals - especially wireless Logitech mice and keyboards that
periodically pulse the bus. Diagnosed via ProcMon stack capture on one
affected user's machine, with the slow frame's call chain ending in
SDL2.dll -> SETUPAPI.dll -> cfgmgr32.dll -> kernel registry queries against
HKLM\System\CurrentControlSet\Enum\HID\*.
With the hint enabled, that work happens on SDL's own thread and the main
thread just dequeues already-collected events.
Ship_info is already an SCP_vector but MAX_SHIP_CLASSES (500) is held in
place by fixed-size structures throughout the engine and editors. This
converts the seven file-format-adjacent arrays whose persistence touches
the .csg campaign save and .plr pilot file formats:
campaign::ships_allowed [MAX_SHIP_CLASSES] -> SCP_vector<ubyte>
campaign::weapons_allowed [MAX_WEAPON_TYPES] -> SCP_vector<ubyte>
loadout_data::ship_pool [MAX_SHIP_CLASSES] -> SCP_vector<int>
loadout_data::weapon_pool [MAX_WEAPON_TYPES] -> SCP_vector<int>
scoring_struct::kills [MAX_SHIP_CLASSES] -> SCP_vector<int>
scoring_struct::m_kills [MAX_SHIP_CLASSES] -> SCP_vector<int>
scoring_struct::m_okKills [MAX_SHIP_CLASSES] -> SCP_vector<int>
The CSG and PLR file formats already store explicit counts and key by
ship/weapon names, so no on-disk format change is needed. Existing
read/write loops already iterated by ship_info_size() / weapon_info_size()
and just compile through against the new vector types.
Vectors are sized to ship_info_size() / weapon_info_size() in
scoring_struct::init(), mission_campaign_clear(), player_loadout_init(),
and the campaign-pool reset paths in csg.cpp and multi_campaign.cpp.
All of these run after weapon_init() / ship_init(), so the sizing
invariant holds. scoring_struct globals constructed at static-init time
start with empty vectors; first index access is always post-table-parse.
Multiplayer stats sync (multimsgs.cpp) now derives offsets and counts
from the vector size; added USHRT_MAX assertions on the sender side
since the wire protocol packs offset/count as USHORT. The FSTracker
sync (multi_fstracker.cpp) clamps vmt->num_ships down to the local
mod's kills.size() before transmission and guards the receive-side
write so a tracker payload with more ship slots than this mod has won't
overrun the vector.
The MAX_SHIP_CLASSES cap itself stays in place at ship.cpp:2327; this
is one prerequisite toward lifting it. The other ~25 fixed-size
ship-class-indexed structures (team_data, Ss_pool_teams, Wl_ships,
FRED2 editor arrays, qtFRED Editor::_ship_usage, etc.) remain to be
addressed in follow-up PRs.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* change to new fog system
* Fix fog conversion issues
* remove unused old neb values
* Update scripting API
* temporary old-value round trip
* Rewrite nebula fog with four explicit parameters
Replace the legacy `+Fog Near Mult` / `+Fog Far Mult` model — which
depended on fixed engine constants — with four parameters that map
directly to renderer behavior:
+Fog 1000m Visibility fraction of light surviving 1000m of fog
+Fog Near Distance meters from camera where fog begins
+Fog Skybox Clip Distance max render distance for the skybox in fog
+Fog Clip Distance max render distance for the scene in fog
The deferred-lighting fog shader, material system, model renderer,
object sort, and the Lua mission API all consume the new parameters
directly. The legacy `Neb2_fog_near_mult` / `Neb2_fog_far_mult`
globals are removed.
Mission parsing accepts either the legacy keys or the modern keys.
Legacy values are converted to the modern set at parse time, and a
per-mission flag (`Neb2_fog_use_legacy_values`) records which keys to
write back on save. The flag is cleared only when something actually
changes, so opening and OK'ing an unmodified legacy mission preserves
its on-disk format. Saving uses `optional_string_fred` to preserve
user comments through edit cycles.
FRED2 and QtFRED background editors both expose the four parameters
in place of the old multipliers, with friendly labels and tooltips.
Both editors validate input (visibility clamped to [0, 1]; near
distance must be > 0; skybox and scene clip distances may be 0 to
disable fog at that range) and use a snapshot-and-compare at close
time so that a no-op open-then-OK never spuriously rewrites a legacy
mission in the modern format.
FRED2's background dialog is also reorganized so that "Display bg
bitmaps in nebula", "Override nebula fog palette", the RGB row, and
the four fog parameters all sit inside the Nebula group box; the
"Old Nebula" group box is restored below it with its Pattern, Color,
Pitch, Bank, and Heading controls back inside the frame. The dialog
now overrides PreTranslateMessage so that the new fog tooltips —
and the previously broken "Save sun/bitmap angles in correct format"
tooltip — actually fire.
QtFRED's BackgroundEditor.ui adds four QDoubleSpinBox controls in
the existing nebula form layout, with per-field decimals chosen to
avoid scientific notation, and per-field min/max declaring the
validation rules. The QtFRED help page is updated to describe the
new fields.
* fix tooltips
* restore forward-renderer fog
* Clang Tidy
* address feedback
* Refine nebula fog rewrite
- Rename Neb2_fog_use_legacy_values to Neb2_fog_save_legacy_values
to reflect that the flag governs save format, not runtime
behavior.
- Decide both the save flag and the legacy-to-modern conversion
purely from whether the file contains modern fog keys, dropping
the prior heuristic based on required_fso_version. A mission
without modern keys (legacy- or retail-format) converts on load
and saves back in legacy format; missions with modern keys are
saved as modern.
- Snapshot the four fog values as floats at editor open and use
fl_equal for the no-change comparison in both FRED2 and QtFRED,
replacing the FRED2 CString comparison and the QtFRED strict
inequality.
- Document the on-disk invariant in missionsave: when not saving
legacy keys, the four modern keys must always be written (never
gated on "only if non-default"), since the parser uses their
presence to decide whether to run the conversion on next load.
---------
Co-authored-by: Goober5000 <[email protected]>
* Initial KTX1/ETC2 support
* Conditional glad include
* remove unused function
* define glenum for non opengl build
* remove unused param
* fix qtbuild
* change ktx format to enum
* use nullptr
* ktx: support the same etc2 formats available in amd compressonator
* add comments and missing include
* correct flag type
* clarify variable name for clang
* cleanup
* update glad loader to GL4.3
A few visual improvements requested on Discord:
1. Use a configurable LOD to draw the outline wireframe, defaulting to LOD 1
2. Draw subsystem names with a dark outline to make them more visible
3. Draw the subsystem boundary boxes with thicker lines
* initial changes
* add GLAD_ES loader
* Implement basic es compatibility header
* re-add accidentally deleted break
* Add GLES BC7 extension to glad and improve extension support report
* fix some enum mappings
* Use the ARB name for geo shader check
* Add es espand shader includes
* Fix glbufferstorage mapping
* fix some gl errors on opengl es
* Enable GL_CLIP_DISTANCE
* Add format conversions
* add bgba 8888 to rgba 8888 converter
* disable GLAD_GL_ARB_timer_query
* Properly handle wgl + opengl es on windows
* initial enable imgui gles
* add GL_BGR to GL_RGBA conversion
* inform opengl es on menu
* small corrections to the es header
* small refactor of glTexSubImage3D
* remove expandincludes, existing code already did that better
* change default graphic values for opengl es
* compile imgui with opengl es 3 on linux
* allow qtfred to run on opengl es
* improve es compatibility header and remove shader precision quantification
* add compiler hints
* remove unused structs
* Fix imgui crashing on windows with gles, use angle lib
* Do not use MSAA under OpenGL ES, at least for now
MSAA will need an alternative path for GL ES using GL_EXT_multisampled_render_to_texture and GL_EXT_multisampled_render_to_texture2
* add missing profile handler
* cleanup
* revert color_attachment_4/5 fbo workarounds
* Adjustments to log output and enable GL_BLEND
* Implement glGetQueryObjectui64v on es layer
* Fix deferred and decals support
Also added glGetTexImage(), glQueryCounter() and some additional comments
* Revert changes to default values of graphics options
* Minor improvements to glTexSubImage3D()
This will download the appimagetool utility as part of the install step so
that the newest version of both the tool and the runtime is always used. Moving
it out of the build image allows us to take advantage of newer capabilities,
such as no longer having an external dependency on libfuse2.
* add wing display names
Adds display name capability for wings, matching the pattern and infrastructure of display names for ships. As in #7234, wing display names take precedence over ship display names, if both are provided; because if ship display names took precedence, a ship would have the same display name in every wave.
All the relevant display locations are handled, including the HUD, escort list, message box, and mission log. Lua API support is provided as well.
Adds full support for both FRED and QtFRED, including the always-save-display-names setting.
Addresses #7189 and the last request from #1730.
* add help text from #7234
Follow-up to #7251, which added `set-guard-range`
This PR exposes that value to scripting, so scripters do not have to use the more expensive `runSEXP` to use it.
The value is initialized as -1 (`max_guard_radius = -1.0f;` line 7913 in ship.cpp), hence the default value for the script is -1.
* Release Build Safety
* Move to using standard models.
* Avoid using .indexes() to fix heap coruption
* More work on selection function
* major cleanup and refactor
* enable drag and drop
* multi edit support
* cleanup
* fix build issue on linux
* revert non-weapons dialog changes
* clang
* clang
* update help doc
* better model/dialog code split
* further cleanup
* static
* keep primary and secondary banks aligned
---------
Co-authored-by: The Force <[email protected]>
1. more robust handling of missing fireball graphics
2. fix handling of error dialogs on Linux so that the engine doesn't silently continue on an error!
Fixes#6793.
If you set AA level to None, save, then close the game, then re-enter the game and switch the AA mode to an MSAA mode, then the screen will just be black until the game is restarted. This does not happen when switching from None to FXAA because FXAA works because its post-pass uses `Scene_luminance_texture` and `Scene_ldr_texture`, which are always created as part of standard scene setup.
There are two ways to fix this, either require AA mode to require a game restart (though that may complicate the lab) or allow resource allocation for SMAA always.
Honestly I like the idea of keeping the lower-end machines optimized and not allocating for SMAA but simply running it always but for this PR have just allowed it always run.
Happy to discuss whichever option folks think is best!
* add imgui speech options
* adapt existing windows sapi speech implementation
* adapt existing mac speech integration
* add speech linux stubs
* add speech support in linux
* Add array checks
* Use dlopen for speech-dispatcher
* corrrect lib name
* missing includes and static cast
* do not change mac file type
* fix clang tidy warnings 1
* set tts rate
* set localization ids
* fix clang tidy warnings 2
* correct symbol name
* Remove voice cache and fix win enumerate_voices overriding voice selection
* fix mac rate
Done by notimaginative
* requested changes
* re-add voice cache for linux
* Open connection for linux get flags
* fix missing }
* change voice option combobox to std::pair
* delete duplicated voice id sanitizer on windows set voice
* Use pairs for speech_enumerate_voices() and adapt linux speech
* use reference
* actually free vector memory
* Clear voice cache when ingame options closes
* Use extern to call fsspeech_options_cleanup()
* update localization ids
* Fixing some linux and window speech oversights
* Apply volume and rate after a voice change, correct voice, volume and rate apply order
Fix#4089, part 2:
- properly link special-point subsystems with -destroyed submodels, if such a relationship exists and a game_settings.tbl flag is set
- add some helper functions for -destroyed variants of submodels (and now subsystems)
Fix#4089, part 1:
- give the `my_replacement` and `i_replace` fields clearer names
- for submodels with the `Is_damaged` flag (representing -destroyed variants or debris), initialize them to blown-off (the true fix for #3078, fixing a regression introduced in the model instance refactor)
- roll back the de-parenting of live debris from #3089 (726ce953c7), because it was a wrong fix to the initialization bug and introduced its own subtle bug when positioning live debris
- roll back the `Can_move` flag skipping from #4138 (063d7afcfe), because it was another wrong fix to the initialization bug
- add some clarifying comments
Fix a few items flagged by Coverity and Claude:
- properly check for an unassigned ship node, rather than just Asserting, since this could be affected by mission data
- properly check for null containers for the same reason
- rename `ai_goal_find_empty_slot` to `ai_goal_allocate_slot` and edit comments to reflect its not-quite-side-effect-free role
When a streaming OpenAL source plays through all queued buffers it
transitions to AL_STOPPED. Per the spec, queueing more buffers after
that does not auto-resume playback -- alSourcePlay must be called
again. This is the likely cause of music and briefing voices cutting
out.
To fix this, check for underrun and call alSourcePlay if needed. Also
double MAX_STREAM_BUFFERS from 4 to 8, bumping the margin to ~2s
of queued audio.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Some code refactoring to allow mission titles to be strings of any length. Titles that are too long to actually display (based on string width) will be visibly truncated using `font::force_fit_string`, but the underlying title will not be affected. Multiplayer is still subject to the 31-character length limit, so titles sent over the network will still have characters truncated.
Also removes some redundant calls to `gr_get_string_size`, since `font::force_fit_string` returns the fitted string width.
* new qtfred error checker
* fix some issues
* clang
* more clang
* clean up and fixes
* missed a comment
* add help documentation
* surface auto corrected issues more clearly
* some cleanup
FastDebug FSO compiled with /MDd (debug CRT) but imported Qt's Release
libraries via CMAKE_MAP_IMPORTED_CONFIG_FASTDEBUG = Release Debug. Qt
Release ships /MD, so any allocation crossing the qtfred <-> Qt boundary
went into one heap and came back out of the other, tripping
_CrtIsValidHeapPointer on a perfectly-valid std::string dtor. Latent for
ages because it only surfaces when an allocation actually crosses;
opening a mission file is one such path.
To paper over the resulting STL layout difference, FastDebug also forced
_ITERATOR_DEBUG_LEVEL=0 so qtfred's std::string matched Release Qt's.
Not needed once we link Debug Qt, and keeping it would introduce a fresh
mismatch (qtfred IDL=0 vs Debug Qt IDL=2).
Fix:
- Map FastDebug imports to "Debug Release \"\"" in qtfred/CMakeLists.
Debug picks Qt's debug libs; Release is a defensive fallback; the
empty entry falls back to plain IMPORTED_LOCATION, required because
Qt's host tools (uic/moc/rcc/qhelpgenerator) ship a single variant
with no IMPORTED_LOCATION_<CONFIG>. Must precede find_package(Qt5):
CMake snapshots the variable into each target's MAP_IMPORTED_CONFIG
property at creation time. (Also why the prior "Release Debug" was
silently a no-op -- set after find_package, ignored; CMake fell
back to Release on its own.)
- Extend the qwindows/qsqlite plugin POST_BUILD copies' "d"-suffix
generator expression to match FastDebug as well as Debug, so the
Debug Qt runtime finds qwindowsd.dll / qsqlited.dll alongside.
- Drop the FastDebug-only _ITERATOR_DEBUG_LEVEL=0 from the MSVC
toolchain file. Qt was the sole consumer; pure-C deps don't care.
Cost: FastDebug STL containers pick up MSVC's debug-iterator overhead.
Reasonable trade for a config named "Debug with optimizations".
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Curve input follow-up to #6926 and #6889, in that it adds two new curve input Nebula and Particle Detail Levels for use within the particle effects table. These new inputs will allow modders to develop effects that can properly be optimized per varying particle and nebula detail levels.
PR #7334 caused an unintended side effect when building both FRED and QtFRED. With QtFRED enabled, FRED2 sources were compiled with _AFXDLL defined while still linking against static MFC, causing a crash on startup. To fix this, keep the conditionals in sync between cmake/toolchain-msvc.cmake and fred2/CMakeLists.txt.
Also, do not explicitly add static MFC libraries if we are using dynamic linking.
* use std::move() for local variables that are copied but not reused
Addresses ~140 Coverity "Variable copied when it could be moved"
defects across 74 files. Every std::move() targets a local variable
whose value is consumed by push_back, emplace, assignment, lambda
capture, or a function call and is never read again afterward.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* clang: use std::make_shared
* clang: use std::make_unique
* address feedback
---------
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Per Claude:
> The `IF` opens with `(MSVC_USE_RUNTIME_DLL OR FSO_BUILD_QTFRED)` but the `ELSE` and `ENDIF` only reference `(MSVC_USE_RUNTIME_DLL)`. CMake requires the argument in `ELSE`/`ENDIF` to match the `IF` exactly (or be omitted).
* help dialog and documentation
* compile help in headless mode
* scene browser help file
* attempt to get CI working for linux
* debug attempt
* Fix split method to use QString::SkipEmptyParts
* Revert "debug attempt"
This reverts commit cb046e1b3305577ff50e95d5b748f6d1dbf025fb.
* clang
* update help
* correct name
* Inject sexps.html into help and add find in page controls
* update help based on recent commits
* better tutorial asset loading
* no const
* update help again
* Build using /MD flag if building QTFred and on windows
Fixes Multiple QTFred heap crashes due to mismatched runtime types.
* Actually Change Right value
Three out-of-bounds/UB fixes for issue #6793:
- asteroid_create_all: skip field_debris_type[idx] == -1 entries when
building the DG_DEBRIS odds table and loading models; iterate only
over valid table slots during spawn. Matches the guard already present
in asteroid_frame.
- missionparse: bounds-check subtype before indexing colors[] in the
obsolete +Field Debris Type: parsing path.
- verify_asteroid_list: guard the asteroid_list[0] fallback access
against an empty list.
- asteroid_init: emit an mprintf when no asteroids are defined instead
of returning silently.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Per Claude:
The key things the new comments add that the old ones were missing:
1. Palette RGB colors are completely ignored — only the index value is used as alpha. This is the non-obvious invariant that @notimaginative described.
2. Exact mapping table — makes the * 18 / * 17 math immediately readable, and clarifies the ANI vs PCX difference (> 15 clamps to opaque in ANI but transparent in PCX).
3. The broken-palette consequence — explicitly states that a reversed palette causes a white square, linking to #4148 so future readers understand the context.
* fix hotkey not saving/loading
* fix docking setup flow
* fix all/none in flags list not updating ui
* fix tri-state flag issues with multi selection
* fix initial status checkboxes
* fix no warp effect
* more fixes
* fix flag hiding
* allow any flag to be skipped for player starts
* another fix for no warp effect
* smarter context menu
* fixes for object orient editor
Turns out 7360 causes cockpits to not render. That PR had updated `GL_DEPTH_ATTACHMENT` to `GL_DEPTH_STENCIL_ATTACHMENT` but missed two spots. This PR fixes that and tests show cockpits now work. (Root cause was the save/restore zbuffer swap using the old GL_DEPTH_ATTACHMENT point — once the scene texture became a combined depth-stencil, re-binding just the depth slot left stencil dangling and made the FBO incomplete.)
* color variable or container rows based on type
* add props and jump nodes to layer filters
* make goals dialog dynamic and fix bugs
* cleanup
* missed these
Fix issue with our Linux build image where libfontconfig1 isn't installed, but
is needed by some Qt5 libs. Since aqt is used to install a more up-to-date
Qt5 version than what's provided by the distro we don't have the usual
dependency resolution needed to prevent this.
This is a stop-gap measure to fix testing of pull requests for QtFred, and
only applies to that specifc workflow. The arm64 Linux image also has a broken
Qt install so this workaround is useless with normal workflows. A proper fix
will require updating the Linux build image to fix the Qt dependency problem
and related issues.
* fix mission stats message count
* fix texture replace for retail textures
* fix heap issue in ship alt class
* fix props menu item
* some ui clarity
* unify up/down buttons to use our painted icons
* fixup ship and wing cues toggles
* rename and move Object Orientation menu item
* menu seperator styling for dark mode
* qtfred dockable objects list
* fix jumpnode rendering
* more ouline panel features
* fix for wings
* remember list expansions
* clean up wing selection and layer handling
* disable top and bottom docking
* give scene outliner some padding
* replace old selection dialog with the scene browser
* fix some minor issues
* right click for wings and waypoint paths
* clang
* clang again
* fix status bar message
* 25 1 checks
* clang
* more clang
* address feedback
* draft set-target-player-sexp
* Missed a few entries and duplicates
* Missed another entry
* Yet another missed entry
* Fix subsystem not showing up being targeted
* Fix subsystem targeting in set-player-target SEXP
* remove reduntant return
* change sexp category to better suit feature
Fixes the long-standing intermittent bug where the GTD Orion#Repulse in
Silent Threat: Reborn's "Forced Hand" mission spawns with all subsystems
unlinked, leaving the ship untargetable and undisableable. The same root
cause has been reported since at least 2015 (HLP topic 89403) and was
provisionally closed in #3147 as fixed by #3858, but #3858 was an unrelated
parse_ship_values memory leak fix and never actually addressed this
behavior. Recently the underlying check at ship.cpp ~8043 was promoted
from Warning to Error (#5591), which is why Release players are now
hitting a hard error dialog instead of just seeing missing subsystems.
Root cause
----------
model_unload() walks Ship_info and resets si.model_num = -1 on every
ship_info that referenced the model, but does not touch
si.subsystems[k].model_num. Subsystem entries are left pointing at the
freed model id. When a subsequent mission reloads the same pof under a
new id, ship variants that share the model rely on
ship_copy_subsystem_fixup() to re-link their subsystem arrays, but the
fixup matches by name via model_copy_subsystems() and any unmatched
destination subsystem stays at -1. The mismatch case in
model_copy_subsystems() was guarded only by Int3(), which is a no-op in
Release builds, so the failure was completely silent until subsys_set()
errored out much later with no useful context.
The bug is intermittent because it depends on three independent ordering
factors: which prior mission was last played, which Orion variant that
mission used, and the iteration order of Ship_info during the next
mission's ship_page_in().
Changes
-------
* model_unload(): when clearing si.model_num for an unloaded model, also
clear every si.subsystems[k].model_num that pointed at the same id.
This is the structural fix and eliminates the entire class of stale
subsystem pointers surviving across mission boundaries.
* model_copy_subsystems(): replace the silent Int3() in the name-mismatch
branch with Error(LOCATION, ...) naming the unmatched subsystem. This
surfaces a failure mode that has been invisible in Release builds for
over a decade and gives modders an actionable diagnostic when sibling
ship classes that share a model have inconsistent subsystem names.
* ship.cpp: introduce verify_ship_subsystems_linked() helper that checks
every model_subsystem on a ship_info is linked into the same model the
ship is using, and fails with Error(LOCATION, ...) naming both
polymodels if not. This is the canonical post-condition for both
ship_copy_subsystem_fixup() and model_load() (which is supposed to
link subsystems via do_new_subsystem()).
* ship_create(): call verify_ship_subsystems_linked() after
ship_copy_subsystem_fixup() so that any failure to link a subsystem
is surfaced with full context (ship name, subsystem name, both model
filenames) instead of propagating to a generic error in subsys_set()
much later. This closes a long-standing asymmetry where ship_page_in()
had a guard (added by zookeeper in 2015) but ship_create() did not.
* ship_page_in(): three post-fixup verifications were gated by
#ifndef NDEBUG with Warning() or Assertion() calls, both of which are
no-ops in Release builds. Replace each with a verify_ship_subsystems_linked()
call so they fire in Release as well.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
playerGet() indexed Ship_info with ship_class without bounds checking.
Before ship selection, ship_class is -1, which as an unsigned index
causes an out-of-bounds access. Add bounds check using ship_info_size(),
matching the pattern used elsewhere in the codebase. Also update the
Windows standalone GUI to use ship_info_size() for consistency.
Fixes#7366
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Clean up the syntax checker, using clearer variable names for each check, and most importantly unique variable names. Fixes several bugs where syntax checking failed because the same variable was overwritten with incompatible type information.
Also fixes a bug in `check_operator_argument_count` where the count check never ran due to a mixup of `op_index` and `op_const`.
* Implement Photo Mode
* fix gr string errors
* return raw char array
* control conflict groups and better photo param defines
* better param identification in real time
* make photo mode hude dynamically sized
* fix xstrs after all changes
* missed a few
* use modern loop
Net_player[idx] (pointer arithmetic from current player) was used instead
of Net_players[idx] (global array index), causing the status display to
read from wrong offsets. This coincidentally worked for the host at index 0
but showed incorrect status for all other players — most visibly on
standalone servers where no client is at index 0.
Fixes#7358
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
* rename misleading variable check_again to never_check_again
The first element of collision_result means "never check again" per the
typedef comment, but was destructured as check_again (opposite meaning).
Rename to never_check_again to match the actual semantics and prevent
future confusion.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix data races in ship-weapon collision threading
Two thread-safety bugs in ship_weapon_check_collision, which runs on
worker threads:
1. update_danger_weapon() wrote to Ai_info[] (danger_weapon_objnum,
danger_weapon_signature) without synchronization. Multiple weapons
targeting the same ship would race on the same Ai_info entry.
2. Homing missile detonation logic wrote wp->lifeleft and
wp->weapon_flags directly on the Weapons[] global array.
Fix: defer both writes to the main-thread post-processing phase via
new flags in ship_weapon_collision_data. Also convert the collision
data from a 6-element tuple to a named struct for readability.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix data race in ship-ship collision submodel checking
ship_ship_check_collision() toggled pmi->submodel[].collision_checked
flags on the heavy ship's polymodel_instance to selectively enable/
disable submodel collision checks. When two collision pairs shared the
same heavy ship, worker threads would race on the same pmi entries.
Fix: add a collision_checked_override pointer to mc_info that lets
callers provide a thread-local array of collision_checked values.
model_collide() uses the override when set, falling back to the
pmi->submodel[] field otherwise. ship_ship_check_collision() now
builds a local SCP_vector<char> and passes it via the override,
completely avoiding writes to shared polymodel_instance state.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* Ensure threads have spun down before continuing non-threaded execution
* address review feedback for ship-weapon collision threading
- postproc flag now accumulates incrementally instead of being OR'd
at the final return, ensuring all return paths respect it
- early return for predictive collisions now preserves the
should_update_danger_weapon flag in the collision data
- moved nprintf detonation debug print to the main-thread process
pass for thread safety
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* move collision_checked from pmi into mc_info for thread safety
collision_checked flags were transient per-collision-pass state that
didn't belong in the shared polymodel_instance. Now mc_info owns an
SCP_vector<char> that model_collide auto-initializes from pmi when
empty. All collision callers (ship-ship, asteroid, debris, prop)
updated to manipulate mc.collision_checked instead of pmi->submodel[].
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* Convert to CV and spinup counter
* Update comment
---------
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: BMagnu <[email protected]>
Collection of fixes for multiple issues with the multi code found by Claude AI (by way of Goober5000), plus additional issues noted by myself while checking the code. These fixes are primarily focused on the interpolation code.
These changes should not be breaking and are largely exclusive to server-side handling, but still need to be tested thoroughly before being merged. Any tests must be done with at least the server (master) using the fixes.
* set line edit fields to max length in code
* fix some dialog window titles
* remove unused context help button on Windows
* address some easy todo items
* static access
* Fix multiplayer standalone crash: client stats race + host accept code
Fixes a crash in multiplayer PXO/tracker games hosted on a standalone
server where clients crash at debrief close after scoring a kill:
pilotfile.cpp:295: Ship kills of '<ship class>' not found,
should have been added by pilotfile::update_stats
Two independent root causes were found, both of which must be fixed for
correct behavior:
--- Root cause 1: race condition in multi_sexp_end_mission() (sexp.cpp) ---
The previous code called send_debrief_event() before
multi_handle_end_mission_request() as a "hack" to skip the warp-out
sequence when an end-mission SEXP fires. On standalone servers this is
a race condition: scoring_eval_kill only runs on the master, and the
master hasn't broadcast m_okKills to clients yet at the point
multi_sexp_end_mission() is called. Entering debrief this early causes
scoring_level_close() to run with zeroed m_okKills, so
Pilot.update_stats() creates no kill entries for that session.
When debrief_close() later calls scoring_backout_accept() it cannot
find those entries and hits the UNREACHABLE.
Fix: Remove the send_debrief_event() call entirely. The normal flow
via multi_handle_end_mission_request() has the server broadcast stats
first and then send MISSION_END, which causes the client to enter
debrief with correct kill data already populated. The master enters
debrief through sexp_end_mission() -> send_debrief_event() as before.
The behavioral side-effect of removing this hack: clients that go
through the normal warp-out sequence will no longer skip it on
end-mission. Clients in a state where they cannot warp still receive
immediate debrief via multi_handle_sudden_mission_end().
--- Root cause 2: host accept code never set on PXO standalone (multiui.cpp) ---
In multi_debrief_accept_hit() and multi_debrief_esc_hit(), when the
game is a PXO/tracker game and the local player is the game host
(NETINFO_FLAG_GAME_HOST), the code calls send_store_stats_packet() to
tell clients to record their stats. It then sets
Multi_debrief_stats_accept_code = 1 via the per-client response path
inside the NETINFO_FLAG_AM_MASTER block.
On a standalone server the game host is NOT the master
(NETINFO_FLAG_AM_MASTER is false for the client-side host). The
NETINFO_FLAG_AM_MASTER block is skipped entirely, and
send_store_stats_packet() uses multi_io_send_to_all_reliable() which
skips the local player — so the host never receives its own packet.
Multi_debrief_stats_accept_code stays at -1 (unset).
When debrief_close() checks this value and sees it is not 1, it
assumes stats were tossed or the window was closed without accepting,
and runs scoring_backout_accept() unconditionally. With fix 1 in place
this no longer crashes (entries exist), but silently strips all session
kill credit from the host's pilot record.
Fix: After the send_store_stats_packet() block, call
multi_debrief_stats_accept() unconditionally for the game host so the
accept code is set locally regardless of whether the host is also the
standalone master.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* Preserve end-mission warp-out skip via deferred debrief entry
The previous fix removed send_debrief_event() from
multi_sexp_end_mission() entirely, which was correct for the stats
race condition but had a side effect: clients would no longer skip the
warp-out sequence when an end-mission SEXP fires. The warp-out skip
was an intentional feature — process_endgame_packet() checks whether
the client is already in debrief state and, if so, bypasses
multi_warpout_all_players().
Restore the original behavior by deferring the send_debrief_event()
call to process_endgame_packet() rather than eliminating it.
multi_sexp_end_mission() now sets Multi_sexp_end_mission_pending=true
before calling multi_handle_end_mission_request(). When the client
receives the MISSION_END packet, process_endgame_packet() checks the
flag, calls send_debrief_event() there, then falls through to the
debrief-state check which skips the warp-out exactly as before.
This is safe because send_endgame_packet() calls multi_broadcast_stats()
before sending MISSION_END. Both use reliable delivery, so stats are
guaranteed to be received and applied before MISSION_END is processed,
meaning scoring_level_close() now sees correct kill data when
send_debrief_event() fires.
Alt-J-initiated mission ends are unaffected: the flag is never set,
so the warp-out proceeds normally for those paths.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* Revert multiui.cpp accept code change — tracker master owns stats
The previous change added multi_debrief_stats_accept() calls for the
game host in multi_debrief_accept_hit() and multi_debrief_esc_hit() to
work around Multi_debrief_stats_accept_code staying -1 on a standalone
server. This was based on incorrect analysis.
In PXO tracker games the standalone master is intentionally the sole
authority for stat storage (via multi_fs_std_tracker_store_stats() in
multi_standalone_postgame_close()). The host and clients must not save
stats to their local pilot files independently. Multi_debrief_stats_
accept_code remaining -1 and triggering scoring_backout_accept() on the
host is correct behavior: kills are backed out of the local pilot file
because the tracker holds the authoritative record, not the local file.
The race condition fix (deferred send_debrief_event()) is sufficient to
prevent the crash: Pilot.update_stats() now creates kill entries with
correct m_okKills data, so scoring_backout_accept() can find and remove
them cleanly rather than hitting the UNREACHABLE.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* Move Multi_sexp_end_mission_pending from multiutil to multi and reset in multi_vars_init()
Addresses review feedback: the flag has no relation to multiutil, and
resetting it in multi_vars_init() ensures it is always cleared between
missions regardless of which code path was taken.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
---------
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
When a waypoint is deleted from a list, the remaining waypoints after it shift down (e.g. Path:3 becomes Path:2). SEXP and AI goal references were properly invalidated for the deleted waypoint, but were not updated for any subsequent waypoint to reflect the new numbering.
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
* add head animation picker dialog for event messages
* get animations working
all previewing all head anis
cleanup
* reorganize files
* make these static
* no const
* more static
* updated var name
* missed one
Adds multi.cfg options to allow easy tweaking of standalone servers to better handle mods
with faster ships and/or weapons that don't behave reliably with rollback or lower fps.
Put ships getting whacked by weapons or other objects into simulation mode to avoid odd
position changes when client-side whacks get overridden by server interoplation updates.
Fixes timing bug that used the wrong timestamp for primary and secondary weapon shots on
clients. This resulted in a discrepancy between client and server timing which caused weapon
shots to bypass the rollback system and become unreliable.
Add safety checks for signal updates to avoid array boundary issues. And be sure to reasses
packet indexes when a new packet arrives instead of waiting a frame for index updates.
Afterburn hack is to fix trails and model animations getting triggered so that clients and hosts
see them. The hack needs to be reset before multi_oo_unpack_client_data() though, not after.
Fixes behavior that was broken in #2752
mg_start() calls InitializeCriticalSection(&global_log_file_lock) on
every invocation, but mg_stop() never calls DeleteCriticalSection.
Re-initializing an already-initialized critical section is undefined
behavior on Windows and corrupts the heap, causing the next allocation
to throw an exception.
Make the Win32 initialization (WSAStartup + InitializeCriticalSection)
one-shot via a static flag, and remove the asymmetric WSACleanup from
mg_stop so resources remain valid across mg_start/mg_stop cycles.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
When a player enters the mission loop screen from the main hall, there was no code to handle the stopping of main hall music and ambient sound. Add code to handle this specific case.
Also fix `Loop_sound` not being initialized to -1 `in loop_brief_init()`, which caused an assert when closing the loop brief screen if no branch brief sound was defined for the mission.
Fixes#7330.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The waypoint class stored its position in m_position separately from the game object's pos field, requiring callers to manually keep both in sync. Now get_pos() and set_pos() delegate to the object position when the game object exists, falling back to the parsed position only if the object does not exist.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* Fix `targest nearest attacking ship` in multiplayer
Pressing 'Target Nearest Attacker` in multiplayer does not work when a ship has spontaneously targeted another ship. This is because within, `multi_oo_pack_data` `goals[0].target_name` only covers explicitly ordered goal targets and is empty for spontaneous IFF-based engagements, which means `target_signature` does not return the proper value. This PR adds an extra check for that to pefer the live target_objnum so clients know who is actually being attacked.
Tested and works as expected.
* comment cleanup
* comment cleanup
* Add lab panning controls and align to pof tools
* pan based on camera view coords not world coords
* reset view option
* change scrolling to use mouse wheel
* Better ui for controls reference
* clang
* Tune ups for standalones
Fixes two warnings from building in standalone and also provide, also adds needed function to actually tell if game is in standalone mode.
* better fix for armor flags
Add coverity[GLOBAL_INIT_ORDER] annotations to ~50 global variables
across 27 files. These were all analyzed and confirmed safe:
- ~48 OptionBuilder::finish() globals use a Meyers singleton
(OptionsManager::instance()), which guarantees safe init order.
Destruction is also safe due to shared_ptr ref-counting.
- 6 default-constructed container globals (vectors, maps) have no
cross-TU dependencies at construction or destruction time.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Convert `debriefing_editor_dlg` from a modal stack-allocated dialog to a modeless heap-allocated dialog, matching the pattern of the briefing editor. Update FRED infrastructure accordingly.
Add `focus_sexp(int node)` to `debriefing_editor_dlg`, mirroring the existing method in `briefing_editor_dlg`. Fix both `focus_sexp()` implementations to search all team debriefings/briefings instead of only the currently selected team, so nodes in non-zero teams are found correctly in TVT missions.
Fix `debriefing set_modified()` calls to only set the flag if the debriefing data actually changes, rather than every time the editor was opened.
Since bitmaps, suns, and skyboxes store their coordinates as floating-point numbers, we can allow mission designers to specify floating-point numbers in the FRED UI. This PR modifies the dialogs in FRED and QtFRED to allow two decimal places for pitch, bank, and heading.
Implements #7170.
1. Change `ai_profile_lookup` and `multi_xfer_lookup` to use `const char *`, since all the other lookup functions do
2. Remove several unneeded `const_cast`s, some of which are now made possible by the non-const `data()` overload in C++17
3. Change `campaign_link` to use `const char*`
4. Use better string management in `test::FSTestFixture::init_cmdline()`
1. Add optional `start_index` and `num_items` parameters to the find/count functions in utility.h.
2. Fix an accidental recursion bug.
3. Change appropriate parameters to `size_t` and cast appropriately.
4. Add two forms of `SCP_vector_contains_lcase`.
5. Enhance `sprintf` and add `sprintf_concat` for `SCP_string`.
The scripted `gr.drawOffscreenIndicator` was missing a critical `resetClip();` which meant it was using whatever the previous stack's clipping distance was, and thus not draw in the actual correct location.
This 1 line PR fixes that and the fix works as intended.
1. When loading and saving lighting profiles, treat an empty string as equivalent to the default name
2. Remove unused fields from the mission struct
3. Properly guard union initialization in `add_message`
If the graphics system fails to fully init for some reason then it's possible
for the imgui backend and/or renderer to not be initialized. Those subsystems
*must* be initialized before being shut down so we need to check for that to
avoid hitting assertions inside of imgui.
Also add a safety check for making sure that an imgui context exists before
attempting to initialize the backend/renderer. A simple assertion should work
for this as it would take a coder messing something up in order to trip it.
1. Properly initialize campaign links and elements so that stale values don't stick around from previously loaded campaigns.
2. Clear internal flag bits from campaign missions to prevent invalid state from being loaded from a campaign file.
3. Properly check the main hall when saving flags in retail format.
4. Clean up parsing and saving of mission loop data, which had been broken ever since retail. Add compatibility checks for the old format.
Not using the return value from `optional_string_fred` triggers Coverity warnings, but it turns out those "consume token" blocks aren't actually needed.
While we're at it, make the token parsing a little more robust in campaignsave.cpp and clean up the newline behavior.
- generate appimage for qtfred if it's available
- separate fso and qtfred install roots
- move fso appimage files out of global space
- fix qtfred appimage launch script
- prefer X11 Qt backend for qtfred
FRED can get into a weird state if a warning appears while a ship is being created, e.g. if the ship has a null moment of inertia. So, prevent FRED from rendering a ship if it hasn't been fully initialized yet.
1. Modify `ship_get_subsys_for_submodel` to use the subsystem indexer. This changes the operation from O(n) to O(1) and also allows the function to work with turret gun barrels.
2. Add an `isValid` check to `ParticleSource::finishCreation` to prevent unknown state from being accessed if the source is not valid.
3. Tweak `EffectHostTurret` and make sure it works for fighter beams.
4. Prevent `createOnTurret` from running on submodels that are not turrets.
Testing in FotG exposed a bug that dates back to retail. During mission parsing, arrival and departure anchors were represented by indexes into `Parse_names`. After parsing, they were converted to ship indexes -- but only in FRED. Since some functions are shared between FRED and FS2, this can produce inconsistent results, which can be hard to detect since parse indexes and ship indexes are usually the same.
This refactors arrival and departure anchors to be represented by ship registry indexes in all cases. It also adds conversion functions for the benefit of FRED and QtFRED since those dialogs were designed with ship indexes in mind.
String processing enhancement prerequisites for the upcoming `split_str_once` PR.
1. Add overloads of some string processing functions with a length parameter, to allow processing of substrings of C-strings
2. Add overloads of gr_printf that work with string lengths
3. Add constructors to `HUD_message_data` and `line_node`
4. Rename "size" to "len" in `vm_strndup` for clarity
5. Fill in some string attribute annotations
6. Make the rest of the HUD render functions `const`
7. Removed unneeded circular #includes in code/globalincs/memory/
1. The `waypoint_stuff_name` function used the wrong length when building the waypoint name, causing the number to be written past the end of the string in most cases. Not sure how this escaped testing.
2. Change two Assertions, which had no effect due to the comma operator, to Errors, which match their counterparts in their respective functions.
3. Make `internal_error` consistent between the campaign editor, the mission editor, and qtFRED, and prune an unnecessary string copy.
Follow-up to #7104. Fixes#7254.
An upstream bug in libpcpnatpmp caused it to not pass along ping failure
messages in the internal state which then triggered multiple issues with
both the library itself and FSO. This fixes the bug in the pcp library
and takes care of the portfwd log spam issues in FSO as well.
This one would be good for the upcoming point release, as on Stable 25.0, if your threat gauge is flashing during a mission and then you quit the mission and go to the HUD Config screen, then the gauge remains flashing.
This PR fixes that by simply not flashing the gauge while in configure mode. Tested and fixes the bug as expected.
The existing `cannot-perform-scan` flag prevents the cargo from being shown on the HUD, but some modders would like to see the cargo while still preventing a ship from being able to perform a scan. So, this renames the existing flag to `cannot-perform-scan-hide-cargo` and adds a new `cannot-perform-scan-show-cargo` flag. Compatibility code in both mission parsing and flag evaluation ensures that missions using the old flag will still work.
Note that if both `cannot-perform-scan-hide-cargo` and `cannot-perform-scan-show-cargo` are set, the former will take precedence.
Add a useful function for getting a ship_info pointer from a ship registry entry. Also rename `ship_has_dock_bay` to `ship_has_hangar_bay` for clarity, since docking bays and docking points are not the same thing. Finally, add a `model_has_hangar_bay` function.
Make sure that missions without props will still be compatible with earlier mission file formats. If props are included, bump the mission file version. Also, fix some newline behavior in the save code.
Fix a crash caused in part by some missing UI calls in FRED2 and in part by subtle object life cycle issues. Depending on whether FRED receives the focus during mission load (which can happen if the autosave dialog appears) it could access props that were in the process of being cleaned up but were still referenced. This isn't specifically a props issue; it could happen to any FSO object stored in a SCP_vector, since the vector can be cleared.
The quick mission init is to prevent a whole bunch of unnecessary and risky processing during a transient loading state, but it has the nice side effect of making mission list loading noticeably faster.
* Add curve to control the duration of a particle source
* Also add fractional Life Left curve input for sources
* Actually register new particle curve output
* First draft of prop object type
* Add prop editor dialog in FRED
* prop sexps
* lua table prop support
* lab support
* lua mission access to props
* prop collision support
* use std::optional so the object->instance id is always valid
* allow props to block suns
* minor cleanup and remove arbitrary limit. Still limited to 500 objects.
* Sort props by category
* cleanup
* implement collision hooks
* parse prop flags and further ensure props are inited and closed correctly
* Add Cyborg's multi suggestions
* fix missing header
* add props to empty slots if available
* add multi signature
* fix rebase issues and match collisions to the new multithread style
* appease Clang the Conquerer
* save/parse mission prop classes by name
* Clean up comments and finish TODOs
* fix string errors
* clang wants this to be static now
* address feedback
* address feedback
* Use model num from prop info instead
* merge prop and ship collision group sexps together
* fix rebase bug
* address feedback
* fix name shadowing
* ship heavy submodel
* clang
---------
Co-authored-by: Asteroth <[email protected]>
* Generalize mission save from original FRED
* make qtfred use the new generalized missionsave
* split campaign save into a sister class
* allow unlimited campaign description length to be saved
* have the campaign editor pass the links to save properly
* cleanup
* future todo
* fixes
* more fixes
* cleanup vars
* clang
* add missing guardian threshold and fix var name
* more clang
* conflict resolution error
* update qtfred to use the new campaign save
1. Add default strings for variables and containers, providing something more appropriate than `<new default required!>`.
2. Replace the `Assert` in `add_default_operator` with a check for a valid variable index. This prevents a crash if FRED adds an operator that takes a variable as an argument and there are no variables in the mission.
3. Add the correct variable type to `get_listing_opf_variable_names()` to fix SEXP tree construction in certain circumstances.
Apply the same fixes to QtFRED as well.
These were coded for the `split_str` refactor, but are generally useful elsewhere as well.
1. Use SCP_string in some utility functions where appropriate
2. Avoid copying C-strings in some utility functions where it isn't necessary
3. Add concat functions to `SCP_vector`
4. Change return type `int` to `bool` on some common parselo functions
5. Add `find_white_space` and `find_gray_space` parselo functions
Just as special tokens are replaced in debriefings, replace them in command briefings and briefings as well.
Change `string_replace_tokens_with_keys` to `message_translate_tokens` (since it's the same thing) and add a `replaceContainers` script API function to complement `replaceVariables` and `replaceTokens`.
Also replace every category of token in `sexp_modify_variable` and add comments to places where token replacement might be expected but happens elsewhere.
#6670 added support for custom gauges and also cleaned up the color setting of hud gauges when using 'Select All'. It seems two copy paste bug slipped through the cracks (ie the order of colors was copied from red to blue/green, when really the order should have been updated).
This PR restores the proper order and fixes the bug.
* Revert "Move insignia post-processing to model load"
This reverts commit 665d7145b6.
* Revert "Cleanup of old insignia stuff"
This reverts commit fdf98a1f3a.
* Revert "render insignias as decals"
This reverts commit 24cdeb3c95.
* Isolate reverts to insignias
* Fix oversight
* clang tidy
A timestamp set to 1 means an immediate timestamp, and so the `int` version of `timestamp_elapsed` should account for that, just as it does in the `TIMESTAMP` and `UI_TIMESTAMP` versions. Normally the number comparison means the check will still work, but during mission initialization the timestamp code is not running. This caused destroy-before-mission ships to be added to the arrival list when they shouldn't have been.
Also fix logic in `timestamp_elapsed_safe`, where the `TIMESTAMP` and `UI_TIMESTAMP` versions were correct, but the `int` version had a bug dating back to retail that caused it to return true for uninitialized (zero) timestamps rather than false. Practically speaking, this fix has no effect because the function is only used in multiplayer and none of the instances use integer-0 to indicate uninitialized, but this will at least fix any uses in the future.
Add the ability to configure the `less` operator for `SCP_set`, `SCP_map`, and so forth. Add comparison operators to the type-safe `ID` class so that it can be used with these data structures.
All other display names are `SCP_string`, so make these `SCP_string` as well to be consistent and to allow arbitrary-length display names.
Also fix a few infelicities with German translation and the script API.
* Fix warning of unbound keys for newer controls
Under some circumstances, FSO will warn the player if a key is unbound if that they need to press to complete a training event. This logic though only works for keys with XSTRs from 507-619. Any control that was added with a different XSTR will not be picked up correctly, and thus the message displayed to the player will be incorrect, confusing, and not helpful.
To fix this `missiontraining.cpp` around line 757 needs to account for the newer controls as well.
This PR adds those needed checks, and this fixes the issue. This fix is especially needed for mods that use training missions with newer controls such as FotG. Note, we do ship with a full default controls table with all the needed keys bound, but we have found players will be players and simply change all their controls before even starting the training missions. Thus they unbind key training controls, and with this bug they are unable to correct their controls. With this fix they are properly able to update their controls as needed to complete the training missions.
Fixes#7172.
* var name update
Move the rendering of ships with effects to immediately after rendering of ships. This fixes rendering in several edge cases where, currently, additively-rendered items, among others, are incorrectly obscured by ships with effects. This affects anything that doesn't render to the depth buffer -- nebula poofs, particles, lasers, beams, engine glows, etc.
Forward-rendered objects (due to transparency) still interact incorrectly with full nebula fog, but that's out of scope for this PR.
Rewrite `force_fit_string` to be more robust and to remove the potential for memory access violations. Also audit all of the length parameters in the calling functions - some of them were the buffer size, not the length. This should fix the mysterious crash in the mission log screen.
A ship which has a display name and belongs to a wing will display that name no matter what wave it appears in. Since this should only be done when the mission designer deliberately wants it to be done, omit this case from the cases covered by the "Always save display names" feature. (To always save a display name in this case would require saving one for the wing, but a wing display name feature does not yet exist.)
Fixes#7140. Followup to #6810.
* Add flag to respect detailboxes in model collide checks
* Don't check detailboxes that are invisible for sunglare checks
* Use local coords
* Actualyl also run the check for cockpits & show ship
* Be less stupid
Message Lines were not being rendered to the proper position for certain resolutions per issue #7143.
#6575 seemed to be the commit it broke on, and looking at that commit it showed that code added `x` and `y` to the render string positions, even though `x` and `y` did not exist there before.
This 1-line PR fixes that issue, and it is confirmed to fix the issue by KamiGaAtaeta. Also I checked and on more standard resolutions the message lines still display as expected in both mission and the HUD Config screen.
* Fix haloing in cockpit shadows
Cockpits can use shadows, but the small geometry of cockpits and the current shadow pass methods result in bad looking shadow halos and poor quality. The issue is that small scale geometry, like cockpit struts/pillars, cast overlapping shadows--and these overlapping shadows need to use a different shadowing method then the default larger external shadows.
I made a small edit the to the shadows file to fix it for small scale shadows (external shadows, IE those at longer ranges, remain using their method since that method works better at longer ranges). In FotG we have been using this update for years and it works very well.
KamiGaAtaeta was having these halo issues on the FS Ship Interiors project, and this shader update fixed those issues. Thus, per suggestion from Lafiel, I'm PRing this fix so everyone can easily use it.
* remove dead code
The `$Scannable` field in objecttypes.tbl controls whether a ship can be targeted by the "target unscanned ship" key. This is independent of which ship types can actually be *scanned*, which is not connected to any field in objecttypes.tbl.
So, this PR renames the `$Scannable` field to `$Targetable as unscanned:` to be clearer about what it actually does, and it adds the missing counterpart `$Scannable by default:` flag to specify which ship types can actually be scanned.
Note that this is only relevant for legacy scanning behavior. Mods which use `$Unify scanning behavior:` do not need either of the ship type flags.
The `$Scannable` field in objecttypes.tbl controls whether a ship can be targeted by the "target unscanned ship" key. In retail, these were cargo containers and freighters. This is independent of which ship types can actually be *scanned*, which in retail were cargo containers and *transports*. Since the targetability is meaningless without the ability to scan, this fixes the retail inconsistency by moving the targetability from Freighter to Transport.
Note that this is only relevant for legacy scanning behavior. Mods which use `$Unify scanning behavior:` do not experience the inconsistency.
* Two 1-line fixes for new particle lights
This PR provides 2 semi-fixes for the particle lights with 2 simple conditionals.
------------
First, it fixes#7124. In sum, it fixes the issue that new particle lights not affected by light quality slider. This fix is done by adding a conditional check so that particle lights only render when weapon lights do, at the highest lighting setting. This ensures that lower end machines can properly turn off particle lights to help with performance.
------------
Second, this PR adds an extra conditional to ensure that the system does not attempt to render particle lights if the radii is <= 0.
Light emitters logically do not cast light if the light emit radius is <= 0. In 2015, there are assertations in each of the `light_add` functions that trigger if the radii are <= 0.
With the new particle lights and addition of curves for particle lights, this can make result in light radii <= 0. This approach is useful to allow things like hit effects to only give off light if the hit effect is large enough (IE if it hits a large ship scale the radii to be larger, and if it is too far away or a small ship scale the radii to 0). So, in those situations of <= 0 light radii, the modder would expect that the light point is just not shown and simply not attempted to be rendered. Unfortunately, this is not quite the case, as any light radii <= for particle lights will trigger the assertation within the `light_add` functions.
The fix for this is simply to have early conditional checks for light radii. There is already precent for this in the code in 3 locations--1) within the weapon light code in `object.cpp` line `1365`; 2) within the beam light code in `beam.cpp` at line `2009`; and 3) within the fireball light code in `object.cpp` line `1457`. Note these sections also early out if the light intensity is <= 0 as an optimization step, which also makes sense.
This PR simply follows that precedence for particle lights by adding an early out if the light radii are 0. This allows modders to properly use a range of radii and helps ensure internal consistency with the code mentioned above that already does this early out for weapon and beam lights.
----------
Given the benefits listed above, having this PR in before stable would be fantastic (or a relatively quick point release after stable).
Tested and fixes the issue as expected. Happy to answer any questions and/or discuss!
* comment signpost
The object and ship indexes held by the ship registry do not actually need to be cleared until `ship_cleanup` completes. This will allow the ship to be referenced in any functions (via script hooks or otherwise) that are called during cleanup.
Tweak related script documentation while we're at it.
Follow-up to #7120. Fixes#7122.
The `setAutoScaleBehavior` function call should go after the null check to prevent crashing FSO if the font fails to load.
Also, if a font fails to load, skip over it so that subsequent fonts can be parsed.
The `play-sound-from-file` sexp did not have any way to automatically recycle audio handles, instead relying on other sexps to explicitly close them. It is more modder-friendly to implicitly free any handles of streams that have finished playing, so this PR adds that capability. It also adds a Warning in the event that an unused audio handle cannot be found.
Fixes#7108.
This dates back to commit `300d5fc2c1`. It probably did something at some point, but with various upgrades over the years, it no longer has any effect.
It looks like a lot of the model interp code (e.g. `model_interp_defpoints`, which isn't called anywhere) can be removed as well, but that's a bit more involved.
Addresses a behavior idiosyncrasy encountered by Solaris. If this flag is enabled, explosions with a visual radius of 0 do not have fireballs created, and do not have the fireball lifetime added to the explosion lifetime.
First, fix a crash reported in Discord: prevent FRED or QtFRED from giving a waypoint list a name that is too long.
Also fix the updating of references, including for the constituent points, if a waypoint list is renamed.
At some point the mission log became unable to display entries that wrapped around to subsequent lines. Fix that by keeping track of how many lines each entry occupies and adjusting the display accordingly.
This will correctly display mission log segments on multiple lines, but it uses the current string splitting technique which does not split properly in all cases. The splitting will work properly once the `split_str_once` refactor is merged.
* Allow mods to easily tune 'Target Hostile Bomb or Bomber' control
The `Target Hostile Bomb or Bomber` control targets bombs or bombers, though in mods may want a way to easily set exactly what this control does while still leveraging the utility of the 'bomb' flag for weapons and/or 'bomber' flag for ships (both of which affect AI behavior in various ways).
For example, in Solaris, Darius wants a way a way to allow players to only target bombs, while still allowing ships to be classified as as 'bomber'. In this case, the 'only bombs' option can be used. This PR adds a `$Behavior for pressing 'Target Hostile Bomb or Bomber' control:` to allow mods to set the behavior to `default` `only bombs` or `only bombers`.
For example, in FotG we want to allow players to target just bombers, as bombs themselves are hard to shoot down (critically though we still want the player to be able to manually target a bomb via 'target object in reticle'. This allows players to prioritize and easily target bombers while allowing skilled pilots to retain the option of manually shooting down bombs if they want an extra challenge. In this case the 'only bomber' option can be used.
Tested and works as expected in all cases.
* update using cleaned up function
* extra alt option for default case
* warning cleanup
* update default message
* whitespace clang
* appease clang with brackets
* Adds an optional bool to `mouse_down()` for `must_be_mousewheel` to only process mousewheel events.
* Used within `controlsconfig.cpp::check_control_used()` to handle a special case with the mousewheel to allow using it for `CC_TYPE_TRIGGER` controls.
* Cleanup and fix `hud_target_missile`
The function `hud_target_missile` is what runs when the `Target Hostile Bomb or Bomber` control is pressed. Notably, it does not work if there is only 1 hostile bomber. The issue is that the loop within `hud_target_missile` is designed to search for the "next" target, but when there's only one valid target, the loop logic skips over it. But, `hud_target_missile` correctly will target if there is only 1 bomb though, so the fix is to just update the ship bomber logic similarly. This PR updates the logic of the bomber search so it matches the bombs search, that way the bomber search can target a bomber if there is only 1 present in the mission (just as how the existing bomb search will let you target 1 bomb if there is only 1 bomb in the mission currently).
This PR also takes the opportunity to cleanup the function with more clear variable and function naming, along with two new internal bools which will be very helpful for later planned PRs.
Fixes#7050. Tested and works as expected.
* rework hud_target_hostile_bomb_or_bomber
* appease clang
* additional cleanup and modernization
* more cleanup for select previous
Infamously, in FSO, a wing whose mothership is destroyed will not, itself, be considered destroyed if it has more waves remaining, because wing cleanup and logging typically only happen when the last ship in the last wave exits the mission. Instead, with no mothership to arrive from, waves will simply no longer arrive. Events that check to see if the wing is destroyed or departed will never fire.
This PR fixes that behavior, ensuring that the wing is cleaned up and logged properly, by using the same logic as the enhanced `cancel-future-waves` SEXP operator. This is tied to a new `$cancel future waves of any wing launched from an exited ship:` AI profiles flag which is enabled by default on 25.0+.
When checking for subsystems within range of a hit, more than one subsystem is unusual, and 32 (the original `MAX_SUBSYS_LIST` value) is so unlikely as to be impossible. So bumping it to 200 was not needed here -- DTP might have confused it with one of the other subsystem limits. But rather than reducing the limit again, we can simply make the array into a vector.
If the `cancel-future-waves` sexp is called when a wave is not present, it would previously not handle wing cleanup, such as setting flags and updating the mission log.
* Allow 'No Impact Debris' to also apply to explosions
The ship/subsystem flag `no impact debris` prevents the default debris shards from spawning, which is very valuable especially now that impact effects can be completely customized via the -particles table. Now that particle effects are also an option for ship and subsystems explosions, it is also invaluable to have the ability to turn off the spawning of shards when either of those explosions happen.
This PR uses the same flag of `no impact debris` and simply does not spawn the default shards for ship explosions or subsystem explosions of that flag is enabled. I thought about adding two new flags, but that would add to the flag clutter, and most folks who use these flags to turn off impacts I would estimate also want them off for actual explosions. Also, a new flag called `no explosion debris` would likely be confusing, so if a new flag were to be added it should be called something like `no default explosion debris shards` or something. Overall I've opted with the simpler and cleaner solution to just have it all under the impact flags. If two new flags are desired though I can easily add them.
Tested and works as expected.
* throw clang a bone
* use two different flags
* update flag name
* typo and logic fix
* allow custom generic debris to always work
* update to better methods
* cleanup logic
* clang
`optional_string_either` advances the parser by default, but `required_string_either` does not advance the parser by default. So be sure to advance the parser here.
Followup to #7069.
For type safety, use enum class rather than int.
Also make a few miscellaneous tweaks such as adding a new casting macro and making detail level settings a bit cleaner.
* initial cleanup
* rough in more code by copying from debrief
* make buildable
* prep the briefing data model
* completed data model
* activate the ui
* unused param
* stub this
* cmake list is important
* set max cam transition higher
* static cast
* refactored campaign dialog model
* begin setting up the ui code
* work on available missions list
* available missions filter
* working state
* better available missions list
* add tooltip
* handle the retail file format
* add custom data button
* prep for mission graph
* prep for campaign graph widget
* basic functioning nodes
* Basic edges implementation
* path arrows and names
* graph view upgrades
* fixup mode handling
* clean comments
* add some styling
* drag to connect
* add and remove mission nodes
* minor cleanup
* edge emphasis based on selection
* style tweak
* cleanup some graph and tree interactions
* clean out old code
* add getters for lists
* implement the rest of the detail controls
* custom data
* cleanup
* add branch manipulation controls
* branch move buttons
* set as first command
* linux is soooo sensitive (to case)
* more case
* unused param
* fixes
* more terminator checks
* namespaces are fun for the whole family
* Clang
* Private, you're fired!
* refactor variables/containers model and variables ui
* get containers working
* switch to tab view and add filters
* fix the filters
* fixes
* ooo
* static casts
* more static cast
* unused
* clang
Docked wings are created with a sort of reverse-bootstrapped initialization sequence, since normally wings are created first and the wing creates the ships. Issue #7041 found a hole in this sequence, as the mission log entry was added before the IFF was assigned. Fix this bug, and potential future bugs, by moving the assignment of certain fields to immediately before the docked wing is brought in. AI can't be moved that easily, so fix AI setup by calling a separate function.
Fixes#7041.
It's possible for ships to be designated as arrival or departure anchors when these ships do not actually have hangar bays. This cannot normally happen in the interface but can happen when missions are edited in a text editor, or are imported, or the modpack is changed. So add warnings and checks for this situation.
Missions with invalid anchors would previously cause crashes, so update the anchor code to fail gracefully:
1. Negative anchors (especially -1) could trip up the bitwise-AND in the mission saving code, so check for negative anchors *before* checking the special-anchor flag
2. In the event a mission runs with a negative anchor (which shouldn't happen because even `<error>` is added as a recognized anchor), handle the situation with if()s as well as Asserts
* Add parent / host input curves
* reorder some includes to allow particles access to ship.h
* Allow modular_curves to deal with functions returning optionals
* Add convenience function to return an optional from an objp and an instance type
* Add a bunch of particle curve inputs
* Fix internal linkage warning
* Add hitpoint and shield fraction (albeit limited to ships)
* Switch to using signals/slots rather than connect
* Adds coloured persona box
Adds coloured persona box/ fixes persona loading, and reduces amount of data reset on model change
* Update To new flags widget
Updates To new flags widget this reqires moving several non flag items to other dialogs, which also lead to adding a new feature that lets a custom guardian threshold be set in editor
* Switch to size_t
* Make Mission Spec work with changes to Flaglist
* Remove Duplicate member
* Clang Appeasement
* Make static
* Properly initialise guardian threshold
* Convert Player Orders dialog to Checklist box
Unfortunately also formats Shipeditordialogmodel
* Update Custom warp to modern style
* Update Initial status to modern style
* Missed a file
* Update Ship Flags Closing
* Remove QT Code from model
* Update Ship Goals Closing
* Update Special Stats Closing
* Minor Changes
* Replace Paths Dialog With generic checkbox dialog
* Update Texture Replace to modern style
* Cast to int
* Initialize then append
* Clang Fixes
* Two didn't save
* More Clang
* Tighten NOLINT's
* Remove dead code
* Change to built in buttons
1. Add new SEXP operators for setting and fading poofs that will work with one or more arguments, or no arguments (which will affect all poofs at once).
2. Update SEXP help, including clarification that the three `nebula-change-` operators require a nebula to be active to have any effect.
By default, the player's wing will be issued a form-on-wing order at the beginning of the mission if the wing has no other initial goals. Wings in the "starting wings" list that are not the player's wing will also be issued this goal if they arrive after mission start and have no other initial goals. This PR adds a flag to disable this behavior.
* unify naming and some ui cleanup
* sidetracked by a typo
* another sidetrack
* show team list as dropdown like other dialogs
* This is a mess
* cleanup model init and apply
* tweaks
* clear string vars
* validate variables
* some cleanup
* refactor data model
* finish the model and begin the ui
* start getting the ship list working
* fix multi select issues
* activate all 4 lists
* activate teams, filters, selection stuff
* fixes
* clang
* one more cleanup
From Sept 15 onward in fast debug I hit this error when using weapon create
ASSERTION: "cur_frame < part->nframes" at particle.cpp:371
Assert: "cur_frame < part->nframes"
File: particle.cpp
Line: 371
Thanks to lafiel, `that assert should have an `|| (part->nframes == 0 && cur_frame == 0) appended beaause while we need to stay inbounds for animations, frame 0 for both is valid for static images`
The `$better combat collision avoidance for fightercraft:` flag is incredibly useful in preventing AI from hitting large ships while attacking, and the ability to tune the collision avoidance aggression factor further helps mods tune behavior based on their ship speeds (tuning that value is via `+combat collision avoidance aggression for fightercraft:` ). Nevertheless, the improve collision avoidance still is not performed for that actual fightercraft's actual target, so there can be situations where a fast fighter attacks a large ship with high speed, and then when that fighter break off from the attack they turn directly into the large ship's hull. Allowing the target to be incorporated into the `better_collision_avoidance_triggered` check prevents this from happening. To allow the target to be a part of the checks we just simply need to not pass an 'ignor_ship` argument to `maybe_avoid_big_ship`.
This PR adds that ability via flag. This new flag is tested and works as expected. For example, without the flag a squadron of TIEs in FotG would literally ram themselves to death attacking some of our larger capital ships because they would break off attack too late, but with this flag they no longer accidentally collide at all. In discussion with Asteroth it was decided to make this enhanced behavior behind a flag, too.
This PR also fixes a small oversight from the original #2810 where `next_check_time` was never actually used within the `else` block of `maybe_avoid_big_ship`.
* Make particles aware of the effect that spawned them
* Allow modular curves to call global functions from submember inputs
* Add more in and outputs for particle lifetime curves
* Allow post-curve velocity as a curve input
* fix warning and incorrect assig
* Disable CheckTriviallyCopyableMove
* Clang Tidy
Beams in general, and slash beams most likely, can collide with the edge of a model, which will cause a non-normalized vector assertion when particle effects are created. So comment out the normal assignment until a more comprehensive fix can be coded.
When `$Contrail Speed Threshold:` and `+Volumetric Nebula:` are used in a mission, builds since 23.1 would throw an error, since the fields were loaded in a different order than they were saved. It turned out that the save order was the correct order, so this fixes the load order.
Fix heap corruption with smaller mipmaps due to decompression output
always being a 4x4 block rather than actual mipmap size. It's necessary to
pad the allocated data size to allow for the overflow.
Fix heap corruption with DXT1 due to using improper data offsets for the type.
Fix data offsets not always taking the depth value into account.
Adjust code for slight increase in decode performance.
Update bcdec to 0.98
* Removing block to allow volumetric and background nebulas to render at the same time
* Updating code from feedback on pull request #6853
* What the... did I miss a line?
* Dual fog layering should now work when both nebula types are active
Small and subtle fix: move the CINEMATIC options inside the preceding if() block in the same way that the flare style options are inside their preceding if() block. This prevents the CINEMATIC options from being reset to their default values in subsequent modular table parsing. Followup to #6500.
This fixes two build issues:
- `vk::PFN_DebugReportCallbackEXT` takes `vk::DebugReport*EXT` not C
type `VkDebugReport*EXT` since version 1.3.304.
(KhronosGroup/Vulkan-Hpp@d5a18dc87e)
- `vk::ObjectDestroy` was moved to namespace `vk::detail` in version
1.3.301.
(KhronosGroup/Vulkan-Hpp@6e5489fcd9)
Guard them with version checks, so that compiling with older verions
of Vulkan keeps working.
Closes#6416.
* Expose value of idle circling with 'attack-any'
The attack-any order is extremely useful and utilized order, and there was one aspect that was ripe for exposure to modders: the `CHASE_CIRCLE_DIST` that was used to determine how big of a circle to fly around while the AI waited for new hostiles to arrive. For ships with high speeds, like FotG and others, the default radius of 200 m was a bit on the small side, which lead to ships flying in tight circles. This was was counterproductive to goals of tuning the AI to have a more cinematic style, such as where AI would fly around in large distances while waiting for enemies to arrive. Fortunately, this value is easy to expose and allow modders to tune with just a new ai_profiles value.
Tested and works as expected.
* improve name and use correct distance
* Switch to using signals/slots rather than connect
* Adds coloured persona box
Adds coloured persona box/ fixes persona loading, and reduces amount of data reset on model change
* Update To new flags widget
Updates To new flags widget this reqires moving several non flag items to other dialogs, which also lead to adding a new feature that lets a custom guardian threshold be set in editor
* Switch to size_t
* Make Mission Spec work with changes to Flaglist
* Remove Duplicate member
* Clang Appeasement
* Make static
* Properly initialise guardian threshold
* Match file framework of mission events to the rest
* first pass at splitting up the model and ui layers
* fix up message side of event editor
* fix event selection
* fix lots of event bugs
* Get event annotations working
* type to search for operators
* control annotations
* Add event dragging and fix event deletion
* cleanup
* Event and Msg order manipulation
* implement some remaining message todos
* minor cleanup
* prep for browse ani dialog picker
* basic file browser for now
* cleanup
* unused var
* more unused
* clang
* static member access
* rebase error
* fix rebase error
* address feedback
* missing parenthesis
Any place in FRED that uses XSTR is susceptible to double quotes interfering with the standard XSTR format, not just the expected briefing, debriefing, messages, etc. This PR adds `lcl_fred_replace_stuff()` - which handles not only quotes but semicolons and slashes as well - to the other places where XSTR is used.
(Note that quotes are handled just fine in non-XSTR fields. Semicolons will still truncate non-XSTR fields, but addressing that is beyond the scope of this PR as it would require editing every text field in FRED. Fortunately, errant semicolons merely modify the text as opposed to corrupting the mission file.)
Fixes#7005 in both FRED and qtFRED; tested in both. Caveat aedificator: the briefing editor is not yet implemented in qtFRED, so the relevant fixes to briefing icon labels and closeup labels cannot yet be ported over.
Parse errors that are actually errors should use `error_display(1, ...)`, rather than merely logging them (which doesn't abort parsing) or using `Error` (which omits the line number and file name).
Fixes#7002. Tested with a modified script file that produces the same error.
* Switch to using signals/slots rather than connect
* Adds coloured persona box
Adds coloured persona box/ fixes persona loading, and reduces amount of data reset on model change
* Update To new flags widget
Updates To new flags widget this reqires moving several non flag items to other dialogs, which also lead to adding a new feature that lets a custom guardian threshold be set in editor
* Switch to size_t
* Make Mission Spec work with changes to Flaglist
* Remove Duplicate member
* Clang Appeasement
* Make static
* begin asteroid dialog rewrite
* activate fields
* clean up connections
* clean up and rearrange files for consistency
* use constructor to zero out the field when needed
* fix checks errors
* remove duplicate lines
* add missing z
* wing editor dialog base functionality
* flags and path masks plus some cleanup
* squad logo selection
* custom warp params using the ship editor version
* some cleanup
* some finalization
* cleanup, fixes, and clang
* remove duplicate lines after rebase
* merge namespaces
The `_s` functions throw an exception if the string's length is exceeded. But in an error reporting routine, we are far more interested in the string than the exception, and we'd rather get a partial error message than a crash. Plus this bit of code is already set up to truncate the string anyway.
This should fix build issues on ARM64 Windows.
Note that the project name changed from libpcp to libpcpnatpmp and is in
active development again after a multi-year period of inactivity. There
are currently no versioned releases. This is hash b5fe5e2.
During maintenance of the active games list it's possible for the list to be
cleared before a stale item is removed leading to a access violation. So we
need to confirm the list isn't empty when attemping to erase the stale entry.
This also fixes a bug where the list entry index is incremented even when an
entry is removed which can cause an improper selection index being used.
* Add Files and UI
* Initial Setup of dialog
* Finish Dialog
* Obey Rule of 3(Possibly)
Why Cant the compiler do this?
add const
* Fix use of default keyword
* bit more
* Remove unused Vars
* Missed one
* Clang work
* Remove future proofing as the compiler doesnt like it
* Make static/ Apply de morgans
* Lets try this one
* Revert to inital and supress warning
Also switch to Assertions
Broken in #6948 but the original didn't work properly either due to conversion
to int32_t and the resulting size limit.
Big assist from Goober5000 for noticing the bug and helping to sort out the
wonky values.
UI elements with custom mouse cursors wouldn't show them due to the cursor
being reset at the start of each frame. To fix this we need to be sure that
we only reset when the element is no longer active.
A previous attempt to fix the end-mission sexp in multi such that it wouldn't
trigger the jump out sequence was horribly broken. Notable safety checks, state
changes and server/client syncing was skipped over. This caused, as one
particular bug, a standalone server to stop communicating with the game host.
When this happened stats couldn't be accepted/tossed and you were stuck at the
debrief screen, being forced to disconnect from the standalone in order to
continue.
A proper fix for this is to use multi sexps to tell clients to enter a debrief
state before the standard end mission request is handled. This will allow it
the bypass the actual warp out animation for players while still doing the
normal end of mission handling.
NOTE: This is a breaking, but not fatal, multi change and should be safe
considering the recent version bump in early June. As such an additional
version bump is not required with this for 25.0.
Background:
Many mods, especially Event Horizon, have highlighted how versatile and useful using nebula are for creating a wide variety of immersive effects beyond just nebula, including weather, volcanic ash, specialty debris falling from the sky, and more. In addition volumetric nebula have opened another realm of possibilities for modders to creatively utilize. Furthermore, modders can not leverage the powerful updates to the particle system to create a wide diversity of effects, which can be also utilized within nebula (or any mission) by making weapons with those effects and then spawning those weapons with scripts/sexps. Just one creative example is exploding rock debris from a volcano (like in Event Horizon). The visuals of nebula poof though are of course spawned in density according to the `Nebula Detail Level` graphics slider in the Graphics tab of the Options menu. Thus, what the player sets will affect visuals of the nebula. As a modder creating visuals, this can have the effect where particle effects spawned from weapons used in nebula may look different in less dense fields. Ideally there could be a way for the modder to incorporate this Nebula slider detail into the development of their effects, to ensure that the effect visuals properly reflect and integrate with the nebula density that the player might see. The solution to this problem is luckily not difficult, as PR #6889 shows how it can be dealt with. That PR added a particle curve input `Particle Usage Score` which is incredibly useful to allow particle effects to scale visually according to the `Particle Detail Level` that the player has set in the Graphics tab of the Options menu. As such this utility could also be extended to the Nebula detail level to allow modders to develop weapon spawned effects for nebula missions that properly visually integrate with the nebula detail level.
This PR
This PR follows and extends the relatively simple approach of #6889, in that it adds a new curve input `Nebula Usage Score` for use within the particle effects table. This new input will allow modders to develop effects that can properly mesh with varying nebula detail levels--all with the aim to further expand the visuals and range of nebula utility for environmental effects.
From discussion with VR players, it appears that being able to toggle off the skybox/starfield/planet background is very useful to some players to prevent motion sickness. Currently, FSO has the toggle in the Graphics Options window for `Planets/Backgrounds` but it only turns off planet bitmaps. This PR suggests it should be expanded into an accessibility role for players, and properly turn off all background elements--so planets, plus skybox rendering (especially now since most mods also use skyboxes as backgrounds, whereas in early days this was not primarily the case).
Happy to discuss and/or add as a flag if folks think that would be needed.
This has an interesting history. In the original Volition source release, global damage was set to originate from the shockwave position, which would have avoided the fireball issue fixed by #6882. (Technically, though, this was only done for huge ships which would have still left the problem for smaller ships.) In c2716d4ee8, this code was changed to run in non-HTL mode in an attempt to fix a bug. Then in 70529dbd5a, as part of the removal of non-HTL mode, the code was entirely deleted. So, this restores the code.
The #6882 fix is still valid, both because it works for non-huge ships, and because shockwaves may not necessarily originate from the subobject being destroyed. The #6882 fix also subsumes the effect of the restored code, but it's still good to restore the code in case future development may depend on it.
Multiple issues were discovered to be from improper targeting data in multi
tracing back to the addition of multi-lock. This was due to differences in
how targeting works in single/multi and de-sync of this info between server
and client. Collecting accurate targeting data on the server and making sure
that the client will use that data resolves the tracking and sync issues.
Background:
Currently, skybox models can be set in FRED to have `No Z-Buffer` on or off. It is off by default, which is good because it ensures ships and other game objects cannot be rendered behind a skybox. Critically though, skybox models may have sub-models, especially now that animated sub-models are a feature (thanks to BMagnu!). If a skybox is using sub-models and `No Z-Buffer` is turned off, then there will be no proper model occlusion for the skybox and there will be ugly z fighting. Overall, BMangu stated "we could clear the depth buffer after the skybox with another flag".
Update
This PR fixes that issue by adding a new FRED game settings flag, `$Skybox internal depth consistency:` which when set to yes properly ensures there is internally consistency z-sorting with the skybox and any submodels it may have while at the same time ensuring that if `No Z-Buffer` is set in FRED that the skybox still correctly is always drawn behind mission objects like ships/debris.
Many thanks to @Bmagnu for the discussion and help in identifying and creating a proper fix for this issue that is clean, surgical, and supports all existing uses of `No Z-Buffer`.
Tested and works as expected. Fixes#6913.
Move Ship Files To there own folder for legibility
Set File stucture
Create Layout
Rough outline established
Ship data fully loading
limit multiselection to one type
Add in missing conditon
Add weaponlist loading and move Bank model to its own file
Delete Missed file
Fix Cmake file
Change to size_ts
Fix Arrivals
Partial Drag and drop / better multi-select
Finish drag and drop / add ammo editing
Add Saving
Feature Complete
The socket is a value to be assigned, not an index to be used. As such there
is no safety check to be done here and doing so just breaks things.
Fixes networking on Windows.
* Back in business hopefully
* Refactor
* Resolve CI issue in aigoals.cpp
* Updating order.cpp
* Whoops
* Updated objecttypes.tbl to incorporate attack ship type
* Fix clang-tidy issue
* Forgot one other instance
---------
Co-authored-by: wookieejedi <[email protected]>
* Another particle fix for standalones
Fix more standalone crashes from particles by "allowing the code to create particles, and just silently quit if in standalone. I.e., accept an invalid effect handle if in standalone and that'll just quit out the source on its first frame of processing." Thanks to @Bmagnu for the fix! Putting here to allow taylor and chief to more easily test.
* add needed include
* and another fix
In current master the debris creation logic was really showing some rust, which resulted in inconsistent behavior when using `Lifetime Min` and `Lifetime Max` for debris in the `ships.tbl`. Specifically, by default debris can randomly be set as `DoNotExpire` if the check `(Random::next() < (Random::MAX_VALUE / 6))` is false. This was set *before* the code that set the lifetimes from `Min` and `Max` from the table though, which could randomly result in debris with infinite lifetimes even if a min and max were specified (and the ship was small, since large ships trigger infinite debris by default always).
Also, by default, ships with a radius larger than 50 meters always had infinite debris lifetimes because of `MIN_RADIUS_FOR_PERSISTENT_DEBRIS`. Thus, this PR also allows modders to set that value in the game settings table.
Tested and works as expected.
Fix use of incorrect data macro
Fix packet size safety check
Fix sequence order issue with client data packet (Cyborg)
Cleanup code to address readability and maintence issues
The if statement wouldn't trigger as defined which caused the incorrect data
offsets to be used. This resulted in corrupted textures and invalid memory
reads of uncompressed textures if the hardware texture detail slider was set
to anything other than max.
SDL 1.2 had an issue using SDL_Delay() on Mac where it caused bad stuttering
and freezes. A hack was added to avoid this, but it causes 100% CPU usage when
it should be a sleep state, so it wasn't ideal.
With SDL 2 this issue was resolved with the underlying code being unified for
all *NIX variants and that problematic Mac-specific code was removed. So now
we can remove the hack to offer a little better performance on Macs.
The `+Rotation Factor:` value in the ship collide section of the ships table has been around for many years, but raising that value beyond the default of 0.2 results in ship collisions that can result in the colliding ship spinning at ludicrous rotational velocities that last for over 10 seconds (this is especially evident with long ships with high speeds).
This PR adds a field after `+Rotation Factor:` called `+Rotation Magnitude Maximum:` which serves as a maximum for the resulting rotational velocity from a ship collision in degrees per second. By default this is -1 and thus disabled.
Tested and works as expected, and now properly allows mods to have ships spin out if they have collision while not spinning out at wild speeds that look immersion breaking.
* Fix engine not updating with change-ship
Yet another caveat of the change-ship function was discovered by Darius, who found that that both the 3D assigned engine sounds and the 2D throttle/cockpit engine sounds do not properly updated when a ship type is changed via sexp/script.
This PR fixes this by properly calling the respective clearing functions and it also resets the throttle sound check timestamp to ensure the 2D sounds are indeed updated on the next frame.
Tested and works as expected. Fixes#6892.
* cleanup for safety
Dumbfire missiles are client fired for rollback purposes. However players would see
their missiles fire twice due to the server also sending a fire packet back to the player.
So we need to prevent the player that fired the missile in question from getting that
extra packet.
#6248 added an extra subtraction line to calculating when a bomb can be shot down `extra_buggy_time`, but that value should only be calculated if `Aspect_invulnerability_fix` is off. Specifically, the `else if` checks on lines 79 and 97 of `collideweaponweapon.cpp` were getting hit even when `Aspect_invulnerability_fix` was enabled, so ensure that if that flag is on that it correctly keeps the `extra_buggy_time` at 0.
Fix works as expected, happy to edit or tune however.
#6808 converted all Pspews to use the new particle effects, though that in turn lead to a fun little visual bug. Overall, particles on weapons will only be rendered if they are valid, and the is valid check included a `weapon_state == m_weaponstate` check (IE states had to match between what the weapon object held and what the particle held. When a weapon switches to homing that particle state was never updated, b/c before 6808 it never needed to be. This lead to the particle effects from pspews not rendering when a missile was in homing mode.
This PR fixes that issue by also updating the particle host status whenever the weapon state changes (uses the same logic as when the particle spawns the first time).
Tested and works as expected.
A minor bug in #6077 resulted in a crash loading campaigns on the multi ui.
The bug itself was not fatal, however it triggered a cascade of poor error
handling which led to a crash. A lot of these issues date back to retail.
This fixes the minor bug, and hopefully adds enough error handling to
preemptively squash a repeat of the crash problem.
Small one-line fix that follows up #6849. That PR removed the `!(Viewer_mode & VM_EXTERNAL))` check within a section of `ship_render_player_ship` to optimize insignia rendering, but turns out that check is needed to ensure `show-ship` properly works. This PR restores that check to fix this bug, and ideally the thoughts about slightly optimizing insignias can be considered later.
Tested and works as expected.
* Cleanup of Shield Hitpoint Threshold
Overall cleanup that does a few things:
1) Changes `ship_is_shield_up` from integer to bool.
2) `ship_is_shield_up` was only ever called to look at one quadrant, never for all quadrants, so took the opportunity to update the 'all-quadrant' block to account for ships with a non-standard number of shield quadrants.
3) ` MAX(2.0f, Shield_percent_skips_damage * shield_get_max_quad(ship_objp)` was used many times throughout the code (and will be used at least 2 more times with #6848), so simply consolidated all of those uses into a new function called `ship_shield_hitpoint_threshold`. Happy to edit the name however.
4) Removed un-needed redundant comments from `ship_is_shield_up` definition in `ship.h` since those comments were already present in the actual function within `shield.cpp`, and all the other functions used comments in that file instead.
Again happy to tune or edit with any other choices.
* use proper default arg style
* actually commit the updated files
* appease modern clang
* clang round 2
Found a very interesting edge case bug with `$Preload briefing icon models:.`
Situation: Mission 1 has a briefing which has a ship class A as the class (and thus loads the model), but the ship class A is not actually in that mission so no subsystems are loaded. Then in mission 2, the ship class A is actually in the mission but FSO tries to reuse the slot that was loaded, but realizes no subsystems were loaded and makes an error message. I that is because the preload code for the briefing icons on `missionparse.cpp` line 6664 just calls `model_load` but does not specify the subsystem argument.
I've also attached a retail mod reproducible campaign (2 missions, first is 5 seconds long). When the second mission loads the incorrect subsystem warning appears.
This PR properly loads the subsystems and fixes the bug. Tested and works as expected.
* Allow mods to set threshold at which shield stops taking damage
FSO logic dictates that shields collisions and any related sound or visuals related to shields are skipped if the shields are under 10%. This is rather unintuitive especially for mods, so this PR creates a game setting value that allows mods to set this value.
Also, this PR fixes a bug where the HUD shield gauge would try and incorporate this feature but did not do it correctly. Specifically, the gauge skips shield segment rendering if the raw shield strength was 0.1 not the percent. Incorrectly using the raw value results in HUD shields being rendered (albeit faintly) even if the damage was skipping the shield and directly damaging the hull. In other words, if the shield segment was 8%, the shield segment would show faintly even the shield is skipping damage.
Tested and works as expected. Also happy to discuss or answer any questions!
* update local variable name for clarity
* rename `ship_quadrant_shield_strength`
* cleanup with updated get percent function
* more cleanup
* wording and safety tuning
* use correct default number
This allows the first half of a modular -neb.tbm to be skipped, allowing just poofs to be specified without the need for a preceding empty bitmap section. It's a follow-up to #5128 which allowed just bitmaps to be specified without the need for a subsequent empty poof section.
* Slots for custom post processing effects
Post processing effects such as tint or dithering have their uniforms hardcoded, which means the only want to create new post-process effects for a mod is to overwrite an existing effect.
Requested for DEM2, this PR creates 4 blank slots for mods to create new post processing effects--2 floats and 2 vec3. This approach to create blank slots for modders follows the successful strategy used for Custom_Controls 1-5.
Note, this PR also adds `tint` to the default `post_processing.tbl` which had it missing (even though tint is a valid effect with a valid uniform buffer already).
Happy to discuss more or edit however.
* fix ordering
* get proper number of physical cpu cores on macOS
macOS has an easy way to get the physical cpu count so let's use it. Also with
Apple Silicon there are performance and efficiency cores so we need to make
sure we ignore those low-perf cores when getting the count.
* improve error handling
Since this sexp was implemented, there has been a bug that prevented multiple variable-controlled audio streams from working. One default and one variable-controlled stream could coexist, but any subsequent variable-controlled stream would reuse a previous stream's handle if the variable's current value was a valid handle. This adjusts the code to properly create a new handle for every invocation of the sexp with a variable.
The following cases have been tested and now all work properly:
1. The default handle by itself
2. One variable handle by itself
3. One variable handle with one default handle
4. Multiple variable handles
5. Multiple variable handles with one default handle
Follow-up to #2115.
Some SEXP help did not have newlines separating what should be separate lines of text, or spaces separating what should be separate words. Add newlines or spaces where appropriate. (Regexes are A-1 SUPAR.)
* add new conditions
* don't worry about it
* implement new conditions
* bugfixing
* handle pokethrough differently
* clang for the clang god
* appeasement
* to the last i grapple with thee
* from hell's heart etc
* bugfixing
* support hits while dying
* fix shield math, cleanup
* fix memory error
Ever since retail, when encountering a comment, FRED would add an extra newline and mix `\r` with `\r\n`, often causing other bugs. The reason for this is subtle. C and C++ library functions will automatically convert `\n` to `\r\n` and back again when reading and writing in text mode, but FRED mission files are read in binary mode and written in text mode. Normally the parsing code can accommodate reading raw newlines of any type, but comments are copied verbatim from what is read to what is written. A comment ending in `\r\n` will therefore be written as `\r\r\n` which will add an extra incompatible newline.
At one point (in commit a988f5eab2) a fix was made for this, but it only applied to multiline comments, not all comments. Therefore, this PR moves the fix to a common function and uses it for all comment styles.
Add assertions to the model parsing macros to guard against accessing out-of-bounds memory. Patch the model parsing routines to avoid going out of bounds, even if the out of bounds situations are temporary and benign.
* Make scripting use the full-blown particle system
* Add reverse option
* Add animation reversal as an option to modern particles
* Start implementation of beam particles
* Add multi-emission particle source API for legacy particles
* Attach beam muzzle particles to the correct host
* Reorder code in order to facilitate apparent visual size as modular curve input for particles
* fix lua api
* Typo
* Fix scripting and beam muzzle particles
* Remove muzzleflash code, prepare to replace with particles
* Begin mflash effect conversion
* Pass final parameters to mflashes and fix curve
* Remove deprecated particle function
* Add debris flame particles
* remove weapon_explosion table
* Convert shield explosion particles
* Fix modular curve full inputs and convert particle curve inputs accordingly
* Allow particle volume offset and rotation with curve-based rot around fvec
* Add Ring and Point Volumes
* Convert PSPEW to new system
* Make particle curve timing aware of interp
* Update todos
* get rid of performance waste
* Add last parameter for converted pspews
* Fix pspew bugs
* Fix direction for default pspew
* Fix order for voluem rotation
* particle vel interp
* particle vel interp 2
* Make beam muzzle stay parented to the firing ship, as it's likely the more commonly intended variamnt
* fix scripting particle lifetime
* Allow beam muzzle particle override
* Skip invalid pspews
* remove pspew dcf code
* Fix sparkler stretch
* Correct sparkler bia
* General sparkler weirdness
* Tune distribution of sparklers
* Convert Asteroid particles
* Fix conversion warning
* Fix conversion warning again
* Fix conversion warning again again
* Really clang?
Various cleanup associated with the `toStdString()` function in qtFRED. Now that `lcase_equal` exists, it is no longer necessary to compare the C strings. Additionally, QString has its own `isEmpty()` function.
Fix a qtFRED memory access bug when checking for autosaved files. Passing a temporary variable to a function as a reference, then returning it, led to a dangling reference access. Rewrite the `maybeUseAutosave` function to avoid this.
Add several API features to improve scripting support for subsystems.
1. A `CanonicalName` virtvar to provide a clear way to get subsystem names for indexing and referencing
2. `Submodel` and `SubmodelInstance` virtvars to get the submodel information associated with the subsystem, if it exists
3. A `getSubsystemList()` function to provide a subsystem iterator
Applies a stable sort to the keys of a map container before saving the container to the mission file. The underlying container is not modified. Implements #6803.
(Lists are not sorted because the mission designer might have a particular order in mind for them.)
* Allow Custom Gauges to fully use parent type colors
#6670 allowed for custom coloring of HUD gauges, so this PR follows that up with fixing a few edge cases where mods with custom gauges that are linked to parent gauge types accurately reflect the color of their parent gauge type in both the new saved HUD file and the in-mission HUD.
This ability to link color to parent gauges for custom gauges the player cannot edit is what the behavior has always been, so this PR does not change any expected behavior it simply ensures that the new HUD updates and various combinations of table entries for `Config` are all robustly accounted for. For example, in FotG we have multiple non-configurable custom gauges all tied to the center reticle, so if the player changes the color of the center reticle all the custom gauges set to that type also automatically change color.
Tested and works as expected.
* appease clang
* one more clang
* clang needs to calm down
* instruct clang to be calm
* fix comment typo
* Prevent Potential Memory Problems with squadmsg hook function
Within `hud_squadmsg_run_order_issued_hook` it is possible for the calling code to pass `nullptr` as the target parameter, which would cause memory problems with the several instances of `Objects[target->objnum]`. This PR mitigates that potential while testing of `hud_squadmsg_run_order_issued_hook` still works as expected.
* add more safety
On current master players have the ability to name their control preset `...` which creates issues with Windows. This 1-line PR allows that the only non-alphanumeric characters allowed in the control preset name are `-` or `_`.
Tested and works as expected.
Since `builtin_message` might store strdup'd names, we might need to free them when the struct is destroyed. Add a destructor for this purpose, and add corresponding constructors per the Rule of 5.
(Use `vm_strdup` rather than `strdup` for enhanced memory tracking.)
1. Don't display the selection arrows until the selection is actually moved, to avoid interfering with the standard selection feature
2. Use static variables and the new `TIMESTAMP` data type
3. Minor cleanup
Follow-up to #6736.
* AI Cleanup and Flag Fixes
This PR does 3 things.
1) Cleanup `ship_subsystem_in_sight` so it properly returns a bool, which is the return type of the function. Also update `ai_big_maybe_follow_subsys_path` to be a bool instead of int.
2) Adds `+subsystem attack pathing extra distance:` for use within `"$improved subsystem attack pathing:"`. FotG found, especially with the new strafing values we use, could really use the ability to set at what distance `ai_new_maybe_reposition_attack_subsys()` determines if it wants to pick a new point or not. By default the value was 2000.
3) In FotG we started using the `standard_strafe` mode more now thanks to #6511, but we have now discovered some inherit issues with it, namely that it will prematurely trigger `ai_big_strafe_maybe_retreat` because the distance it uses for determining if a collision is going to occur is `dist_normal_to_target`, which commonly resulted in the AI flying to a point to start a strafe, then thinking it would collide with the target and then retreating from strafe mode, only to realize it was now far enough to re-engage strafe mode, which commonly resulted in AI just flying around not accomplishing much. This PR adds a flag which instead uses the `distance_to_target` and a check to see if the ship is even facing the target.
Overall all are tested and work as expected. Happy to change or tune however requested, especially regarding point 3.
* clang cleanup
* cleanup copy paste name
* remove un-needed exposed float
* Allow Display Name to be used in Kills Stats by Ship Class
Currently, the display that is shown for kills by ship type does not use display name of the ship class, which makes the ship classes look different than the other areas where they are displayed throughout the game. This PR fixes that by using display name when rendering the kill stats. Note, this PR does not edit the pilot file structure at all, it simply just tunes how the names are displayed/rendered.
Importantly though, display names do not have to be unique, while the ship class names do. Thus, this PR also consolidates the number of kills of ship classes with the same display name (For example, FotG uses classes like `X-wing#Red` and `X-wing#Blue`, but both have the same display name of `X-wing`, so this consolidation means FSO will simple display `X-wing` with the sum. Overall, mods not using display name will be unaffected, while mods that do use display name will now have it properly work in the barracks and debrief rendering.
Tested and works as expected.
* remove flag for now
* move assert
* use handy get_display_name
* Per Request add flag for `$Disabled engines are silent:`
Follow-up to #6781 as there are modders who use engine sound as ambient sound. Also cleans up the sound engine disabled logic.
* cleanup name
* update flag name
Currently, the `$better combat collision avoidance for fightercraft:` flag only checks for possible big ship collisions when in normal chase mode (`AIM_CHASE`), but strafing a big ship is a separate AI mode (`AIM_STRAFE`). Per discussion with Asteroth, strafe attacking should also check for better collision avoidance, as the modder likely would expect that to fall under this AI flag. Also took the chance to make the collision avoidance check into a function to improve maintenance and usability.
Several refinements:
1. Make the case labels consistent between the setting and getting of the virtvar, for ease of comparison and troubleshooting.
2. Consolidate CHASE_WING and GUARD_WING for setting, like they already are for getting.
3. Consolidate STAY_STILL for getting, using one simple trick.
4. Remove the KEEP_SAFE_DISTANCE goal, since it has no target. Fixes#6761
5. Fix CHASE_SHIP_CLASS which put the getting case in the setting section, and consequently did not handle setting.
The code for generating spark sounds was incorrectly copied from debris to ships, dating all the way back to retail. The sound should be played once per generation event, not once for every electrical arc active on the ship. This fixes a bug that caused overlapping electrical arc sounds.
* Add method to get a font's font family
* nullptr
* add more safety checks
* pass font data instead of font data members
* return an empty string instead of unknown
The new enum class collection of AI goal modes did not handle the superposition of states that could occur when multiple ships were selected in FRED. Add a special FRED-only state for this purpose.
* Two Sound Updates
On current master, destroyed engines still make noise and the `Engine Minimum Volume` is not used by big ships. This PR makes two new game settings flags which allow mods to mitigate those issues (`$Unify minimum engine sound:` and `$Disabled engines are silent:`).
Tested and works as expected.
I also added both of these to the 25.0 default, but happy to alter however.
* disabled eng snd does not need flag fix
* ensure retail large ships still sound loud
This PR adds two new localization strings, which allow modders to change how the numbers in the comms menu are displayed, and it incorporates styling for the comms selection controls from #6736, too.
Tested and works as expected.
* Added new keybinds, keycontrol handlers, hudsquadmsg methods for alternate communication menu control scheme
* .gitignore update. CMake in VStudio places builds in [Oo]ut/ folder by default
* Added support for menu pages
* Small formatting cleanup
* code cleanup
* removed unecessary variable
* Updates after code review
* Updated comments
* XSTR_SIZE correction
* Allow ship debris pieces hitpoints depend on radius
Currently, ship debris pieces have their hitpoints set via a Max and Min range. This constricts modders by needing all debris pieces to have somewhat the same size, otherwise the uniform random hitpoints assignment will could make small pieces much stronger than big pieces.
This PR adds a new field `+Hitpoints Radius Multiplier:` which is just a value that multiplies the debris radius, this value, and the debris hitpoints to calculate a final hitpoints value for the spawned debris piece.
This multiplier thus allows modders to have debris pieces that are very large have much strong hitpoints then debris pieces that are very small.
* incorporate feedback fix
* match other logical checks
* Actually pr-test fastdbg
* Set embedfile msvc runtime
* Restructure toolchain files so that embedfile is also built accordingly
* Conditional AFXDLL
* Set iterator level globally
* Update nightly build to use windows 2022
* Update build-release.yaml
* Update build-test.yaml
* Update test-pull_request.yaml
* Upgrade to CMake 3.21+
temp commit
* remove cotire due to incompatibilities
* Update dependencies to compile on CMake 4 with no warnings
* Update ANTLR4
* Update GTest
* Fix Windows CI
* Fix case sensitive ANTLR include
* Fix naming issues and disable shared ANTLR+
* Include Mess for MSVC
* fix new windows signed/unsigned compare warning
* FRED2 linking settings
* Don't clang tidy gtest
---------
Co-authored-by: Tyler Blount <[email protected]>
* Fix two small visual-based bugs
PR fixes/cleans up two small visual bugs/clean-up aspects.
1) If a mod uses the autoaim frame feature of the center reticle (IE the center reticle switches to a second bitmap if a target is within the autoaim cone), then there is currently an edge case bug where if the player's target dies while in the autoaim cone, the value tracking whether or not to use the autoaim frame is never reset to false. This results in the autoaim frame remaining even when the target is dead and long destroyed. This PR properly resets the autoaim bool to false if the target is not valid, and overall works now as expected.
2) #6555 moved warp options to tables instead of via in-game options, but there was a line of code that still referenced `WarpFlash`, where that option was forced off in standalones. This PR properly removes that line and instead puts the standalone check as part of the input warp queue function.
* also cleanup techroom subsystem loading
1. Allow "Stay near me" and "Stay near my target" to work even if the teams do not match
2. Allow "Stay near my target" to be issued regardless of team
3. Avoid divide-by-zero errors when running `ai_stay_near()`
FSO doesn't appear to use this any longer. And even when it was enabled the
requirements made it largely useless anyway. Removing to clean up cfile a
bit and so we don't have to keep maintaining it.
We have debug commands for sexps, so here are a few for scripts. These will be very useful for script developers to perform diagnostics and troubleshooting.
Mods like FotG do not use the FS style shield hit effects, and simply disabling the shield rendering and checking is useful with one simple global variable.
Tested and works as expected.
`clang-tidy` doesn't pass in the compilation flags normally provided by cmake,
so add the vulkan flags manually to make sure that everything is checked
as it should be, and thus prevent it from choosing the static dispatcher
and complaining about `.init()` being used.
Because these functions can return statuses that aren't strictly an
error (and thus don't raise an exception), but might have to be handled,
they return a `vk::Result` that's `[[nodiscard]]`. Ideally some of the
result statuses would be handled here, but to get it to compile, cast
the result to void.
In 133b033ea0, SCP_vector was made into a
subclass, so direct assignment from the vulkan-hpp result isn't possible
anymore. Use an intermediate vector.
* One fix and one enhancement to AI shield behavior
This PR adds one fix and one enhancement to AI shield behavior.
1) Fix: Testing, especially in FotG, revealed an edge-case bug with shield management where the AI will not direct shield energy to a quadrant if it was hit when that quadrant was down. In other words, if a shield quadrant is knocked down to 0 and continues to be shot the AI will not realize it needs to direct energy to that quadrant. This is because `quadrant` is set to -1 if a shield segment is down. This ensures that the resulting effects and damage calculations properly ignore that quadrant downstream, but it also results in `aip->last_hit_quadrant` being set to -1. This PR adds a fix to properly record which shield was actually hit, so that the AI knows to direct energy to that quadrant.
2) Enhancement: In combat situations with fire coming from many directions, it is good practice to keep shields equalized, so this PR adds a flag for the AI to always attempt to balance shields, even if it is being fired upon (instead of the current behavior to always direct energy to the hit shield quadrant).
Both flags are tested and work as expected.
* fix copy paste
* rename to avoid previous confusion
* also make as ai class flag
* Fix crash when clicking inside the hud area but not on a gauge
* add dogfight_variant weapon flag for sorting purposes
* fix weapon display for default hud and skip dogfight weapons on auto-select
* cleanup the mouse check function
* it's broken and i don't like it
* it's fixed and i approve
* add multi support maybe
* appease clang
* appease clang ii: electric boogaloo
* const refs
* increment multi version
Add `UINT64_T_ARG` and `INT64_T_ARG` macros for printf arguments, similar to `SIZE_T_ARG` and `PTRDIFF_T_ARG`.
In the process, fix some issues with the toolchain: in certain CI runs the toolchain headers were being #included multiple times, and certain CI runs produced collisions between clang definitions and gcc definitions. Resolve these issues with `#pragma once` and preprocessor guards in the event of both gcc and clang being active.
Also remove toolchain.h from sexp_container.cpp since it is already #included via pstypes.h.
* Mod Specific Visual Culling Size for Lasers
Currently, lasers will not render if the length or both head and tail radii are < `0.0001`. This is very small, and in many mods the smallest visual size is `0.01`, so this PR exposes that culling size value to allow mods to optimize and tune visual culling of lasers, which can be quite useful especially in laser heavy missions.
* update names
* actually push all files
* Extra Visual Indication for `Scramble` Missions
Currently, if a mission is set as scramble then there is no visual way for the player to see that the Ship Selection and Weapon Loadout screens are locked, instead the player has to click on the buttons and hear the fail sounds or assess that the hover states are not triggering. This PR adds a text line right below the words Weapons Loadout that states "Ships/Weapons Locked" (XSTR 749) if the mission is scramble thus the player can easily see this right away and not have to check the buttons on every mission.
Tested and works as expected. Happy to put behind a flag if desired.
* whitespace
* incorporate feedback
* Few Minor Visual Indicator Enhancements to Loadout
This PR adds a few visual indicator tune-ups to the loadout screens.
1.
Currently, if a mission is set as `scramble` then there is no visual way for the player to see that the Ship Selection and Weapon Loadout screens are locked, instead the player has to click on the buttons and hear the fail sounds or assess that the hover states are not triggering.
This PR adds a text line right below the words `Weapons Loadout` that states "Ships/Weapons Locked" (XSTR 749) if the mission is `scramble` thus the player can easily see this right away and not have to check the buttons on every mission.
2.
Currently there is a nice orange coloration of the player ship icon in the Ship Selection wing loadout. This immediately shows the player which ship is theirs, but this usefulness does not translate to the Weapon Loadout screen. The player must select another ship, besides the player ship, to have the player ship show up as orange.
This PR adds a bool `always_highlight_ply` which is specifically for the weapon `draw_wing_block` function when called as as part of the weapon loadout routine.
Both PRs are tested and work as expected. I currently have these PRs on without a flag, but if folks really do not want the PRs or would prefer them to be behind a flag, then I'm happy to do that, too.
* separate PRs
Two updates to the energy transfer system.
1. Previously, for fighters missing a system (e.g. shields), the energy would be treated as if all energy from that system was routed to the other systems. So, for example, a fighter's typical speed would be faster without shields than with shields. A new AI profile flag now treats the other systems as if the energy had not been transferred.
2. At some point in development, Volition intended the `$Power Output` ships.tbl field to affect ETS. A new AI profile flag now treats the power output as a factor of energy applied to energy systems.
1. Add an explicit `mn.createWaypointList` function
2. Allow `mn.createWaypoint` to be used with an empty waypoint list
3. Update documentation of `mn.createWaypoint` to clarify optional arguments
The `continue` statement in these error checks had no effect because the error checks are macros implemented in a `do` ... `while (false)` loop. So, use `goto`. There is precedent with other instances of `OpenAL_ErrorCheck` in the code.
This may fix the issue where sound would occasionally randomly stop, requiring a pause or a screen change to get it back. This would be difficult to verify though.
Thanks to Coverity for flagging this situation!
The Input of `Trigger Radius` for curves within new particle effects was never hooked up for muzzle flashes, so this PR adds in the necessary lines to get it working. This allows modders to make a muzzle effect that can scale to the weapon radius through curves, and thus modders can simply make one curve scaled muzzle flash and avoid making a many muzzle flashes for each sized weapon that uses the same base effect.
Tested and works as expected.
If a ship changes class, the dockpoints on the new model may not match the dockpoints on the old model. This is most likely to happen when changing a docked ship in FRED to an incompatible ship class, but it can also happen when using the `change-ship-class` SEXP. So check the dockpoints, update them if they should be updated, and undock them if they can't.
* Allow defining separate player and target shield icons for config
* rename define to prevent confusion with a similar define in shield.cpp
* address some feedback
* Fix some issues preventing various secondary types from firing in the lab
* Add ability to fire turrets from the lab
* const char*, mjn please
* more cleanup
* range-based for loop
* Update comment
Most of the functions in ship.cpp that operate on submodel animations are mirrored in animation_handle.cpp, but `setAnimationSpeed` was overlooked. Add this function so it can be called from a submodel animation handle.
PR #6598 caused eyepoint normals to be used for viewing direction, whereas previously the host object's orientation was used for viewing direction. Since this could cause compatibility issues, return to the previous behavior and make the new behavior depend on a flag that is set in post-25.0 builds. (This only applies to eyepoint normals; eyepoint *positions* were respected both before and after #6598).
The `println` function is a semi-recent addition to zLoadFirst-sct.tbm, while the `Globals` table should have the vector and orientation values. The `string.starts` and `string.ends` functions were in the original version of zLoadFirst-sct.tbm but were not included in #6545, and `string.ends` is required by cfile_include.lua.
* Wingmen and Squad Message QoL Updates
This PR adds a few assorted HUD updates/quality of life enhancements. FotG will be using these, though they relatively general and are likely useful to most other mods, too.
1) Adds a 'Ship Name Max Width:' to the Squad Message Gauge (following the same logic as the Escort Gauge). The Escort Gauge will truncate display names of ships if they are too long, that way all the text fits in the gauge without spilling over. It would also be very useful to do this with the Squad Message Gauge, as long display names can overflow out of the gauge's boundaries currently.
2) Adds `Wingname Align Mode:` to the Wingmen Gauge, which allows modders to set how the wingnames are aligned. Currently they are centered on the calculated x-position, though this PR also adds right and left justification options (which is useful especially if displaying the full wing names).
All options are tested and work as expected.
* appease clang
* whitespace
* more safety and error checking
* and extra error helpfulness
* use safer str copy
Some QoL improvements:
1. Update `$fvec` and `$uvec` parsing to also allow parsing `$rvec` and to allow only `$fvec` to be specified; also make parsing more robust against failure
2. Allow `$fvec` and `$uvec` to specify the "facing" direction if `$look_at_offset` is not specified
3. Add a few additional warnings for incomplete or invalid POF data
* Allow mods to hide main Rearm/Repair items in Message Gauge
Adds a game_settings option to hide/disable the Rearm/Repair commands in the Squad Message Gauge. FotG does not use repair ships, so it is somewhat confusing to players to always see the `Rearm/Repair` order options (IE 5. Rearm/Repair Subsys and 6. Abort Rearm) and never be able to use them.
I wanted to make this PR as surgical as possible, while still giving some degree of generality, thus I went with the solution to use `active` as a true integer instead of simply an old int in the bool style. Now -1 is hidden, 0 is greyed out, and 1 is bright.
Tested and works as expected.
* update comment
* update with better name
* add another clarifying comment
Github runners for Linux arm64 are now in public beta with the same
free limits as normal github runners. Our Linux build images already
have arm64 support so this finally enables it as part of the official
workflow.
This was discovered thanks to the new assertions from #6596. For particles with 0 velocity, the code would attempt to normalize a 0,0,0 vector with predictably undesirable results. So, pick the global `z` vector in these cases, while normalizing in the usual case.
Linux iconv does not support "UCS-2-INTERNAL" and conversion will fail if SDL
is compiled with native iconv support. SDL version 2.32.2 fixed this by
changing the macro to use "UCS-2" instead. Unfortunately in my tests this
worked perfectly in Linux but was broken on Mac in the rocket_ui code. However
simply using proper endianess appears to work on all test platforms.
Additionally this fixes a bad memory leak as SDL_iconv_string() allocates it's
return string and this was never free'd before. So every character of text
input resulted in a memory leak of 6+ bytes.
Update haptic code with changes from icculus.org tree which optimizes
effect loading to better support low-memory devices and no longer
requires full support of every haptic effect type. Additionally...
- avoids attempting FF init for non-haptic devices
- avoids attempting FF init for gamepads
- properly resets FF when device is hot-plugged
- better start/stop/update of effects
- avoid stopping effects unless really needed
- use timestamp for dir effect restarts instead of sys calls
- avoid playing FF effects when window is in background
- general code cleanup
Return the current supernova stage. This sexp, in conjunction with mission cutscene editor, makes it possible to reproduce the FreeSpace 2 end-of-campaign cutscene behavior purely in FRED. The resulting cutscene section looks like this:
```
$Campaign End Cutscene: endpart1.mve
+formula: ( true )
$Campaign End Cutscene: endprt2a.mve
+formula: ( < ( get-supernova-stage ) 3 )
$Campaign End Cutscene: endprt2b.mve
+formula: ( >= ( get-supernova-stage ) 3 )
```
Also add a new status subcategory and fix newline behavior when saving the cutscene section.
Fixes#6657.
* lua access to the comm board menu
* On Order Issued Lua Hook
* Some cleanup and safety checks
* Add mn.sendBuiltinMessage and perform more cleanup
* Send the correct ship to the hook for Sender
* clang cleanup
* address feedback
* fix build errors introduced from upstream
* basic hook conditions
* properly link the condition and the oswpt struct
* some requested cleanup
* allow for sending custom built-in messages
* address more feedback
* more prefix
Previously, FSO did not show normal, AO, or misc maps at LODs 3 or higher. This was a relic from original retail days, so this PR allows players to see those textures if the model detail level is at 3 or 4. I put this under the model slider because it is related to LODs, and b/c changing the model slider is something folks actually use compared to the other hardware tex slider which really makes things look ancient if turned to anything other than the max.
In-game options may be removed/inaccessible, such as VR mode removing the Window, but still valid for listing in the `default_settings.tbl` table.
In other words, we don't want error messages displaying if a player is playing in VR mode (which will remove the Window option for that instance) but the window option is listed in the table.
Thus, downgrade the error to a debug print for options within the `default_settings.tbl`. As MJN stated, the table itself controls the parser here, so downgrading the warning is the best choice.
* Make VR mode more seamless
Works to make the `-vr` command flag more seamlessly work (which means the new KNet button, `Play in VR` will also now actually work). Fixes#6430.
First, creates a new in-game option called VR Resolution and have the default be 2500x2500, with a range that goes from 1000x1000 to 6000x6000.
Second, if `-vr` flag is used, then it auto sets flags of `-capture_mouse` `-stretch_menu` and `-window_res 1000x1000` (or anything that's for sure smaller than the screen but not too small, to maintain mouse precision).
It also overrides settings of `-vysnc` and `-window` to off, by ignoring the in-game values (and does not show these options in menu while in VR mode).
Finally, it reads the in-game value of `VR Resolution` instead of `Resolution`. It also shows the `VR Resolution` in-game option in the menu, while hiding the options of `Resolution`, `Windowed Mode` and `Vsync`.
If the game is run in standard mode then FSO does what it current does, including using the `Resolution` value for screen resolution. It also does not display the new in-game option for `VR Resolution`.
* actually use the vr_enumerator
* use emplace_back instead
* update res vr importance
* Fixes for VR one-button mode
* try reordering removes for clang
* fix string ids
* test to see if clang is being weird
* revert clang test
* strings index update
* cleanup options manager
---------
Co-authored-by: Birk Magnussen <[email protected]>
Ships that red-alerted, but that departed before red-alert was triggered, would have 0 weapons on the subsequent mission. Since exited ships do not store weapon information, that information was never saved in the red-alert status, and so `num_primary_banks` and `num_secondary_banks` would inadvertently be set to 0. This bug has been around since the pilotfile upgrade in 2013, and apparently was common knowledge among several players, but was never reported. :-/ The fix is easy enough: skip setting weapon information if that information is not saved in red-alert status. (We should also skip setting subsystem information in the same circumstances, although that did not cause any subsystem misbehavior.)
Although normalized vectors in FSO are supposed to stay normalized, occasionally small floating point errors can pop up. In most cases these do not cause a problem, but in certain cases these errors can rapidly accumulate and corrupt an otherwise well-behaved matrix. This can most easily be seen with daisy-chained dock sequences or docked ships with angled dockpoints.
This PR audits the usage of `vm_vector_2_matrix_norm` to re-normalize vectors in cases where floating point errors could accumulate. There are also a few new Assertions for extra vigilance.
Follow-up to #6596. Fixes#6634.
The official 1.2.1 release of humbletim/setup-vulkan-sdk was recently published. Update the repo version and, incidentally, also the vulkan version. See https://github.com/humbletim/setup-vulkan-sdk
Follow-up to #6582.
Improve skipmemymissionyo in several ways, based on RedMageJoe's recent experience:
1. Allow spaces to be accepted in the mission prompt
2. If the requested mission can't be found, just abort rather than restarting the entire campaign
3. Clarify that the prompt needs a filename and add a message if the mission can't be found
4. Improve handling of the .fs2 extension
5. Fix a bounds check in `popup_input`
* Fix/cleanup using `intrinsic no shields` and ship loadout switching
The flag `intrinsic no shields` is used to allow switching between both shielded and unshielded craft in loadout. There is one edge case that was not accounted for though, which is that if a ship has no shields, and is switched to a ship with shields, the mission will start with that ship having a current shield strength of 0 and only slow get it's shield strength up via shield recharge.
This is not expected behavior, so this PR adds the extra conditional check that if that flag is on, then treat shield percent as full instead of empty. This ensures that switching to a ship with shields in loadout will begin the mission with full shield strength (instead of 0 and waiting for a full recharge).
Tested and works as expected. If desired I can put this behind a game settings flag, but I figured this was the expected behavior (and I'm not even sure how many mods besides FotG uses `intrinsic no shields`.
* also fix initial ets setting with intrinsic no shields
* format consistency
Fixes a bug where the fire-point and flight cursor position components of the center reticle were improperly calculated. Also fixes bug where the fire-point component was missing an argument for `renderCircle`.
Tested and fixes work as expected.
* base working version
* localization and minor tweaks
* add retail UI controls
* Add way to hide gauges from Config view
* convert hud config from index matching to id matching
* clang
For every move and move-assignment constructor, do the following:
1. Make it default if possible
2. Add or delete where appropriate
3. Check for move-onto-self
4. Apply `std::move` where needed
Also fix problematic moves in `player_h`
Copy existing code from change-ship-alt-name into new sexp
change-ship-display-name and likewise from OP_SHIP_CHANGE_ALT_NAME to
new OP_SHIP_CHANGE_DISPLAY_NAME. Create new blank function
"sexp_ship_change_alt_name_or_callsign" and a function for multi too.
When an orientation matrix is constructed using one or more vectors, all such vectors must be normalized. Previously, the code did not enforce this for matrices parsed from a mission or table file. Although FRED will use correct matrices, it also truncates floating point values to six decimal places, so non-normalized vectors might be written to the mission file as happened in #6632. And there is always the possibility that someone could manually edit the mission file to corrupt the matrices.
While we're at it, per suggestions from Asteroth and qazwsxal, make sure the matrix is orthogonal as well. The `vm_fix_matrix` function handles all relevant calculations.
Fixes#6632. Follow-up to #6596.
Coverity hasn't run since September 27. A close look at the log shows that the workflow makes it almost all the way through but fails on the "Upload to Coverity" step:
`fatal: detected dubious ownership in repository at '/__w/fs2open.github.com/fs2open.github.com'`
There are various questionable ways that people have tried to fix this, but it might be possible to completely avoid the issue by not using `git` in that step. So let's try to get the commit hash from GitHub context rather than by running `git rev-parse HEAD`.
Currently if you try to set a subsystem's hit points via scripting it only sets the value to 0 b/c of what was likely a copy paste bug. This 1 line PR fixes that. Tested and fix works as expected.
Remove the `n_quadrants` field because it is entirely redundant to the size of `shield_quadrant`. Also, be more rigorous about the difference between `shield_get_quad(i)` (which can fluctuate) and `shield_quadrant[i]` (which gives the exact quadrant strength). Finally add some C++ casts and move some checks to better places.
* Fix asteroids spawning outside active fields
Found an interesting edge case bug with active asteroid fields that has been present since retail: if a large ship is just outside an active asteroid field, that field will end up spawning asteroids outside the field bounds. This is because the game thinks that the large ship is within the asteroid field when it is actually not. Specifically, the check `asteroid_is_ship_inside_field` does not properly account for the ship the addition of the ship's diameter to the bounding box check.
This PR adds a flag to fix that bounding box check and fix the bug of spawing asteroids outside the asteroid field bounds. Note, `asteroid_is_ship_inside_field` is used twice in the code, once within `set_asteroid_throw_objnum` and once following that call within `maybe_throw_asteroid`. Also note, `asteroid_in_inner_bound` uses a delta of 0 in all cases except when being called within `asteroid_is_ship_inside_field`.
Tested and this fixes the bug while still having asteroid fields work as expected. (Also took this chance to rename a local variable for newly create asteroids to more descriptive name).
* enable by default for 25.0
Use `std::unique_ptr` rather than `vm_malloc` and `vm_free` to handle optional strings in ship classes. This makes the code more robust and increases memory safety. This also allows several string variables to be consolidated in the ship class and weapon class script APIs.
Also add new `stuff_string()` overloads and a new `F_TRIMMED` string parsing type to handle the new fields and the string trimming done inside `stuff_malloc_string()`.
1. Use `const char *flag_desc` because constructing a SCP_string for each flag description is not needed
2. Make `VALID_FNAME` check for nullptr
3. Modify the signature of `coalesce()` to allow capturing of mixed `const` and non-`const` arguments
4. Use `std::for_each` (via `SCP_tolower`) rather than `std::transform` to fix compilation warnings
Most places in the code that use `vm_vector_2_matrix` do so on already-normalized vectors. Changing these to `vm_vector_2_matrix_norm` avoids redundant normalization.
Currently, the cursor does not revert correctly after visiting F3 options screen or lab due to IMGUI unsetting the FSO cursor image.
This PR reloads the FSO cursor image when those screens end. Fixes#6436.
Tested and works as expected.
Upgrade `parse_get_line` to detect all three EOL types: CR, LF, and CRLF. The function is now more robust against line ending mismatches and will now also warn the modder if a file contains mixed line endings.
Fixes#6395.
There were rather prominent strings shown for joysticks that were never localized. This PR localizes them to allow for proper translation support.
Tested and works as expected.
Original issue post #6509. This flag controls if set-camera-host sexp uses the model's eyepoint for the camera position and orientation when no submodel is specified.
Without the flag, the camera will use the model's origin position and orientation.
1. Trim trailing whitespace on any property values, just as leading whitespace is trimmed. All places where `get_user_prop_value()` is used implicitly or explicitly require this.
2. Warn the user if an invalid `$special` value is parsed. This would have caught #1, and will now catch related errors, such as misspellings, in the future.
3. Enhance `string_lookup()` with the ability to print the list being searched, if desired. Remove an unused version of `string_lookup()`.
4. Check for lower-detail submodels being recognized as subsystems.
There were two rather prominent strings shown in popup windows related to the more modern control presets that were never localized. This PR localizes them to allow for proper translation support.
Tested and works as expected.
* Create scripting hook: 'On Options Menu Closed'
Complements #6591. This PR creates a hook, 'On Options Menu Closed' that provides a hook variable of `hv.OptionsAccepted` which is true if the options are accepted/saved, false if the options are discarded and not accepted/saved.
When searching to see if there is an extension mismatch for a soundtrack audio file, go ahead and substitute the mismatched extension if found. Matching extensions is important, so continue to display a Warning; but for the benefit of players and out-of-maintenance mods, it is more friendly to play the mismatched file even if the audio data is inaccurate.
1. Allow `ship_get_eye` to be used for any objects, not just ships
2. Remove the unused `from_origin` parameter and add `local_pos` and `local_orient` instead
3. Simplify the implementation and take advantage of upgrades to `model_instance_local_to_global_*` functions
4. Consolidate `ship_get_eye_local` into `ship_get_eye`
1. Refactor `num_hits` to `num_sparks` and `MAX_SHIP_HITS` to `MAX_SHIP_SPARKS` to be consistent with their current (since FS1 pre-release) usage.
2. Remove the unused `HP_SCALE`.
3. Always initialize at least one spark pair. If `choose_next_spark()` was entered when `num_sparks` was 1, `num_spark_pairs` would be 0 and none of the spark pairs would be initialized. Consequently, accessing the pair at index 0 would return garbage data.
4. Iterate through `num_spark_pairs` when counting the indexes, rather than the hardcoded (and incorrect) magic number 6.
Fixes a crash discovered by Dawnesya that can only occur when a ship has both the "fighter" and "cruiser" flags. Normally, fighters never enter the `choose_next_spark()` function and 'big' ships always have at least 3 sparks.
With the old style, `LBS_MULTIPLESEL`, clicking once allows the user to select/deselect a poof, and multiple selection/deselection is done by clicking multiple times. With the new style, `LBS_EXTENDEDSEL`, clicking once changes to a new single selection, but clicking and dragging, or clicking with Shift or Ctrl, creates or modifies a multiple selection. This should be a more user-friendly selection style for lists with large numbers of poofs.
* Option to unify setting options with easy flag
Most modern UIs, including KNet 1.3, have options that are always set and do not require the user to click save, or on the few cases where options will not be saved automatically, the program shows a popup telling the user the changes are not saved. In addition, the user experience of setting many options then forgetting to press save is far more common and annoying then the opposite. As a last example, even the F3 in-game options menu presents Escape as the leave and save button, not the leave and discard button.
Currently, there are two screens where FSO allows users to press escape after setting options and leave without warning. The main options screen and the HUD screen. As it turns out, half of the options in the main options screen get saved even if the player presses escape (all the detail slider options along with the joystick and mouse sensitivity and dead zone settings), so current behavior is inconsistent to users.
This PR, aimed to be strategic and efficient, creates a game settings table option that allows mods to set so that the escape key for the HUD and Options screen does the same thing as pressing Ctrl-Enter/Accept. This optional setting unifies behavior, so that setting an option sets it whenever the user leaves that screen (whether it is pressing Escape, Ctrl-Enter, or the Accept button). The other screen that involves options and an escape is the control config menu, but that already methods in place to deal with escape in a consistent way.
Tested and everything works as expected.
* fix oversight of saving when going to F3 menu
* update to enum for future additions
* cleanup with better naming
* update warning message
* one more warning cleanup
* Make Cockpit Deferred an In-game Option
After testing and consideration, this PR adds the Cockpit Deferred setting to the in-game options. Also adds a parser to the new default_settings.tbl.
* cleanup comments
* Create scripting hook: 'On Options Menu Tab Changed'
It would be very useful to know which options tab is active (IE Options, Multi, Detail) but it's all under one single Game State `GS_STATE_OPTIONS_MENU`.
This PR creates a hook, 'On Options Menu Tab Changed' that returns the value of the newly switched to options tab. Lafiel and I both discussed making this an ENUM, but the ENUM list is already quite bloated and this integer value seems like the cleanest solution.
Tested and works as expected.
* fix description typo
* Unify AI Usage of Shield Manage Delay
`$AI Shield Manage Delay:` can be set in the AI profiles, but also set for AI specific classes. Currently, The values set for the specific AI class are only used `if (iff_x_attacks_y(Player_ship->team, Ships[objp->instance].team))`, otherwise the values in the AI profile are used.
Being able to have the shield delay work in a unified way according to the AI class values is very useful, especially for friendly wingmen that you want have different shield manage delays.
This PR adds a AI profiles flag to unify Shield Manage Delay behavior, so that it always works in the same way regardless of AI team conditions.
* cleanup unifying behavior along with CM firing chance
* restore what sushi had for now
* Allow modders to always show first game tip at start
This PR adds a simple boolean that allows mods the ability to always show the game tips in the same order, starting with the first entry. This is particularly useful if the mod is introducing something to new players.
The current behavior is to pick a random starting location, so this PR just always starts at tip index 0.
Tested and works as expected.
* add comment clarification
* make into integer instead of bool
* better tips index setting method
* spelling and static cast
* one more static cast
* make actual warning
* clang and consistent order
* Allow mods to Always Show Directive Value Count
Previously, directive counts were not shown if the value was <= 1.
This PR adds a flag to always show the value, and tests work as expected. It also fullfills a longstanding statement from Mage
```
given that, aside from directive-value, all the code involving Directive_count seems to be volition:-original, it really is past time for a flag skipping this > 1 check
```
* cleanup
As discovered by PDFCommand and tracked down by Asteroth, there was another "missed target" check in `ship_weapon_check_collision()`, in addition to the more comprehensive check in `weapon_home()`. Since the check is redundant and there is an existing `$Fixed Missile Detonation:`, skip the check if the flag is active.
Allow `stringcost()` to use a specified function to check equality, and provide both case-sensitive and case-insensitive sample functions. Use case-insensitive checks for sexp operator lookup.
* Fix incorrect ship legacy particle curve assignment
* Setup trigger radius
* Properly attach particle sources to objects and subobjects
* Add trigger velocity for weapon impacts
* Onetime particle source timing fix
* Warnings
* Allow global_to_local to work with no submodel
* Allow global_to_local to work with no submodel, again
* Add scaling for vfnts and scale multipler to gr_string
* nullptr
* Add scaling to a couple other string operations
* Add scaling features to additional bitmap drawing methods
* Implement framework for rendering hud gauges in config mode
* fix merge error
* address feedback
Make `SCP_vector`, `SCP_list`, `SCP_set`, and `SCP_multiset` subclasses of their STL counterparts. This allows helper functions to be added to each, including the `contains()` function which is not available until C++20. (This has minor effects on other parts of the codebase that treated `SCP_` and `std::` as synonyms.) Since there is now a nontrivial amount of code that needs to be in a .cpp file, create vmallocator.cpp.
Note that `SCP_string` truncation has been refactored to use length rather than C-string size to be consistent with other `std::basic_string` functions.
Also, remove some enum class hashing code which is no longer necessary now that the codebase is at C++17.
Allow waypoint orders to target a specific waypoint and go in reverse. Add script access to waypoints and waypoint lists belonging to orders.
Fix assignment of targets and goal start times. Assign targets when they are different (and thus need to be assigned), not when they are the same.
* allow VFNTs to auto scale and disallow auto scaling in FRED
* fix shadowing
* Update FSFont.cpp
* don't code from your phone, mjn
* refactor to use one central method
Add "goal" as a type recognized by scripted sexps. Also add `mn.Goals` as a collection to complement `mn.Events` and move the goal type to goal.cpp and goal.h to match event.cpp and event.h. The new `mn.Goals` collection contains the same data as the existing `Objectives` collection in the briefing UI library, so the latter could be deprecated.
Several changes related to the volumetrics model fix:
1. Update the `model_load()` prototype with better parameter names, including a new `ErrorType` enum defined in pstypes.h
2. Update the `MIN`, `MAX`, and `CLAMP` macros, all of which were susceptible to performance issues because they duplicated their tokens. This could cause functions or calculations to be re-run unnecessarily. Since the codebase is now on C++17, `std::clamp()` can be used.
3. Update the rest of the codebase to fix any associated issues.
This type for subsystems is analogous to the shipname type for ships. Sometimes it is useful to refer to a subsystem even if its parent ship is not present. Whereas the subsystem object would be invalid, the subsystemname string still contains the string that the mission designer specified.
Relatedly, upgrade the parsing of `+Parent Parameter Index:` to be checked on both parented and non-parented parameters. This will help both modders who put the field in the wrong place and programmers who may want to add a parented parameter in the future.
This function call checked the acceleration of the targeted object, rather than the active object as it should have. Fix it to check the active object. For mods that use `$Random Sidethrust Percent:` (such as Inferno), this fixes a bug that could cause an invalid memory access in situations where the targeted object is -1.
Occasionally a link endpoint could be -1, such as with End of Campaign links, but there were no checks in the `add_link` and `remove_link` functions to protect against array accesses with a -1 index. Add checks in several places for this.
* Made lens flare size proportional to model size.
* Updated fireball_wormhole_intensity function to be smooth and unbreakable
* Added variable frame frate warp and new lens flare animation.
* Last animation changes made since I stopped coding.
* Made cinematic animation, warp-size ratio, and flare-size-ratio parameters configurable by table. New exp_to_line function to be more consistent and to fix a bug.
* Made everything configurable by table.
* Updated default values for cinematic warp animation.
* Fixed the usage of MAX() so that it assigns to the variable.
* Fixed obvious freakin' double to float casting warnings.
* Made requested changes. Flare animation can now be specified with an enum and default else statements will not override earlier entries.
* Changed warp table parameters to Warp flare style and Warp model style.
* Added defaults to switch statements, and made this backwards compatible with older mediavps.
* Removed commented code.
* Opened up flare flickering for table editing.
* Restored cinematic warp flare ratio default.
There were 2 popup dialogs that were missing an `Affirmative` flag, which mean the button was not in the right position and thus showed a visual misalignment. This PR fixes that and in tests works as expected.
`On Dialog Start` (used in SCPUI and within `popup_init`) reads popup options by affirmative or negative flags, and the popup for exiting the Mainhall did not set these flags. Notably, most popups that use `POPUP_NO` or `POPUP_YES` already, so this PR sets those flags for this popup. Now `On Dialog Start` within `popup_init` has access to the correct flags.
PR tested and works as expected, both in retail UI and SCPUI
Any NaN encountered in the evaluation of functional-if-then-else should be isolated to the branch on which it occurs. Fixes#6536.
Also improve some help text for clarity.
Looking through all places in the scripting API where `l_Object.Set()` is called, here is one where we might want to know about the object's breed.
(Normally we would return the result of `ade_set_object_with_breed()`, but the `testLineOfSight_internal()` function has multiple return arguments.)
The `query_modified()` function in FRED did not correctly check whether messages were modified, although interestingly, it did so in qtFRED. Even in qtFRED, there were a few minor omissions. Overall, this fixes FRED and syncs up the FRED and qtFRED versions.
Fixes#6528.
At some point between 2002 and 2006, the Update_window code was removed, but since we don't have FRED history from that period, we don't know the exact rationale. However, since FRED appears to have no difficulty rendering every frame, and since there may be parts of FRED that don't set Update_window when they need to (for example, the background editor), let's keep this disabled.
Follow-up to #6435. Fixes the background not updating when a bitmap is moved in the background editor.
Kamikaze ships entering broadside mode (`ai_cruiser_chase()`) would always point toward the center of the ship. With this fix, they will point toward a subsystem if attacking one. (In practice this situation had not been encountered before, since by default the ai-destroy-subsystem order is only available to fighters and bombers, which do not use broadside mode.)
Make these convenient functions even more convenient:
1. Change `object_get_model()` to `object_get_model_num()` and `object_get_model_instance()` to `object_get_model_instance_num()` to more accurately reflect what they do
2. Add new `object_get_model()` and `object_get_model_instance()` functions to return `polymodel*` and `polymodel_instance*` values.
* Fixes Debris not inheriting parent ship texture replacements
Debris chunks that use the same texture as the actual hull model are not updated when `texture-replace` methods are used. For example, a clean grey base textures that has texture replace via table or FRED is changed to red/brown. But when the ship is destroyed the debris objects are using the original lighter texture instead of the newer darker one.
#6154 provided the groundwork to fix this, but one step fell through the cracks; setting the debris hull textures to what the parent ship used.
This PR sets the debris texture replacements when debris is created to fix this (and fixes#2462).
Fix is tested and works as expected.
* cleanup setting shared
* get pmi correctly
Inferno reported a bug where the unavailability of weapon A could result in weapon B being assigned to a particular weapon bank, even if weapon B was disallowed for that bank. Add a per-bank restriction check to fix this.
* Add Mod Option to Limit 'Show Ship' when Toggling Cockpits
FotG uses cockpits and 'show ship', and also provides a way for players to toggle off cockpits. Unfortunately, if the player disables cockpits, 'show ship' still appears and looks very odd (since it appears the player is flying a ship with a hole in the center where the cockpit would be). Other mods have made entire ships with their cockpits, but FotG needs to use 'show ship' to match team colors and moving external ship animations.
This PR adds a game_settings option that allows mods to set to only use 'show ship' if cockpits are enabled.
Tested and works as expected.
* simplify logic
* fix typo
This has been broken ever since commit 6c17ef09ab in 2005. Since `get_hull_pct()` did not return negative values, `percent_killed` was always 0. Allow negative values in this case.
There is a rather large design flaw in FreeSpace debriefings... debriefing SEXPs can refer to in-mission ship data, while all ships (and all objects) are deleted as soon as the mission completes. Specifically, `obj_delete()` is called which sets all objects to `OBJ_NONE` and marks them as freed, although the data still exists in the various arrays. This is the use-after-free problem, but applied to the in-game object system, rather than memory accessed by pointers.
It's probably best to defer fixes to an as-needed basis. As for hitpoint SEXPs, this change updates them to use the object and ship references from the ship registry, since the ship registry is not cleared by the time the debriefing is loaded. (Using `objp->instance` and `shipp->objnum` at this point would be problematic.) Since subsystems are also cleared at this point, this also updates the warning messages in those functions.
Fixes an Assert seen in debug mode in Inferno.
* initial version of default_settings.tbl
* Add a way to change player detail level defaults and implement a couple more options to detail_settings.tbl
* support the rest of 2d.cpp options
* Allow enforcing options to a specific value
* modernize detail defaults, levels, and values
* Fix parsing issue and remove lambda capture by reference
* fix print
* clang
* More efficient +Enforce parsing
* cleanup
* typo
* don't negate this
* error_display
* clarify language between presets, levels, and values
* add default case
* small fix
* use a map to minimize string lookups
* Allow Modders to Tune Strafing
Many mods change ship velocities and damp values, but this commonly leads to poor behaviors attacking large ships within strafe mode (which is the main method for attacking big ships in a sustained way). As an example, FotG has damp and velocity values that are higher than base FS, thus the defined strafe values result in behavior where fighters never can complete a sustained firing pass against a large ship unless they are sitting and parking (which does not fit our goals to match the movie).
The values for dictating how strafe behavior occurs are easily editable by changing some key values, which this PR exposes to modders. Furthermore, mods may give large ships very long range weapons, so being able to set how far away a ship should do a strafe run begins is very valuable.
In testing it was very easy to get desired behavior of having AI do long sustained strafing runs. I estimate other mods will likely be able to leverage these values to tune strafing behavior.
I did numerous tests and evaluations finding the best balance of values to expose. I would be happy to discuss these changes in detail too, as I know this exposes a number of values.
* clang
* incorporate feedback
Now that `snd_do_frame()` has been tightened up to specifically only adjust audio for the adjust-audio-volume sexp, the redundancy-avoiding code in `snd_set_volume()` is obsolete. So, set the sound volume immediately, even if it is a looping sound.
This is a two-for-one fix; the proper setting of volume fixes both #6504 and #6507.
Change `currentlyLoopingSoundInfos` and `currentlyLooping3dSoundInfos` from lists to maps. The data structure should keep track of the volumes currently, as opposed to historically, associated with each sound handle.
Since the map requires `util::ID` and its derivatives to be hashable, add `util::ID_Hash`.
If the volumetrics model cannot be loaded, fail gracefully by warning and not generating volumetrics. This prevents a hard exit in the event of a model problem, particularly when a mission is being edited in FRED.
In the In-game options for `mouse_mode` the XSTR index for "Mouse" was set to 1774, which is already used for "Glide When Pressed". Luckily "Mouse" XSTR already exists with Index 1373, so this PR changes it to that.
The deprecation warning that required changes:
* CMP0054: Only interpret if() arguments as variables/keywords when unquoted.
The deprecation warnings that did NOT require changes as those
features were not used:
* CMP0026
* CMP0042
* CMP0045
* CMP0059
Follow-up to #6371 (and replaces #5960 since the goal of that PR was already taken care of with #6371 adding the procedural translation).
Overall tagging this as 25.0 since multiple folks have asking about bumping the limit
* Fixes Joystick Hat Labeling
Fixes mislabeling of joystick hat names that appeared in #6371. Tested and confirms this fixes the issue.
* fix ordering oversight
When a mission is loaded in FRED the "immobile" flag is migrated to "don't-change-position" and "don't-change-orientation". So, notify the FREDder that this is happening, and add checks to the "potential issues" checker to guard against mixing the old and new flags.
Follow-up to #6304. Resolves#6489.
Make some modifications to the adjust-audio-volume infrastructure:
1. Add an `aav_volume` array for ease of access to all three volume variables. Refactor `snd_adjust_audio_volume()` to use this array to avoid duplicating code.
2. Move `update_looping_sound_volumes()` to be handled in parallel with `audiostream_set_volume_all()`, and for the same reason: avoid setting the sound volume for every looping sound on every frame if the volume has not changed.
3. If the volume is to be adjusted immediately, apply the relevant changes without waiting for `snd_do_frame()` to be called on the next frame. Resolves#6291.
4. Fix some edge cases in `adjust_volume_on_frame()`.
As discovered by WouterSmits, campaigns with periods in their filenames caused issues with FSO's campaign handling. Specifically, in The Babylon Project, the EA-Minbari war v1.0.fc2 campaign would not save progress because FSO expected EA-Minbari war v1.fc2 in certain places. This is because the `_splitpath()` function attempted to remove an extension from a filename that already had it removed. For most campaigns this did not matter, but WouterSmits found a campaign where it did.
To solve this, there is now a new `util::get_file_part()` function to remove the path without removing the extension. This replaces `_splitpath()` for campaign files, as well as the similar `clean_filename()` and `GetFilePart()` functions in other places. All code paths were inspected for any chance of inadvertent extension adding, and Assertions were added to verify future code. The only potential problem area was `player:loadCampaignSavefile()` which now pre-removes the campaign extension if needed.
There were several bugs and design issues in the Vasudan headz cheat, probably due to being coded in a hurry right before release:
1. Although the cheat activated on the main hall, it was not immediately apparent, requiring the player to switch screens and come back
2. The detection of whether the main hall is Vasudan did not work after the cheat was activated, due to the background filename changing (this one is actually not Volition's fault)
3. The implementation of the cheat was actually in the wrong section of code, resulting in some confusion
These are now fixed. The cheat can be enabled or disabled from one function, the graphics are reloaded properly, and the main hall detection includes the cheat-active version of the main hall. Also, the door sounds have been slightly refactored to use a `std::pair` rather than a vector, since there are exactly two sounds, an open and a close.
This allows the current campaign to be set on FSO launch so that the
player isn't interrupted by the "The currently active campaign cannot
be found" dialog when changing mods.
Example usage:
fs2_open -campaign freespace -mod fsport
* fix some usages of std::transform
* change parse_string_flag_list to use a reference
* add a variant of parse_string_flag_list that can use a SCP_set, and make a templated version of flag_def_list
An idiosyncrasy of the original implementation of `timestamp_until()` is that "immediate" timestamps that expired would be negative. Only one remaining spot in the codebase relied on this: engine wash. When #6258 fixed `timestamp_until()` to return 0 for immediate timestamps, engine wash broke. Changing the comparison from `<` to `<=` fixes it. I searched the code and there are no similar uses of `timestamp_until()` or `timestamp_since()`.
In the process of searching, though, I found two uses of `timestamp_since()` that were converted from `timestamp_until()` in PR #4286. These particular conversions more properly include the 0 rather than exclude it, so I changed these as well.
Due to broken node iteration, the `sexp_ship_deal_with_subsystem_flag()` function incorrectly treated the first sexp node as a subsystem, but previous versions of the function would fail silently and ignore it, and subsequent nodes would work as expected. With the new `process_ship_subsystems()` function, this error is properly flagged (and the incorrect node is again bypassed). So, fix the error by fixing the node iteration.
Follow-up to #6221.
1. Allow the goal priority to be an evaluated number, not just a literal number. This allows the goal priority to be obtained from operators or calculations.
2. Since the priority can now be evaluated, it can be NaN. In that case, default to the max priority.
3. Consolidate `CDR(CDR(...))` to `CDDR()` in the aigoal implementation
4. Clarify that `remove-goal` removes the first goal of a given type and priority, not necessarily the first fully matching goal.
5. Enhance `remove-goal` to remove all goals matching the constraints, not just the first goal.
6. Allow `remove-goal` to disregard priority when checking for matching goals.
* Partially builds weapon curves.
* Further curve implementation
* Implementation of more output types.
* Cleanup
* Adjusts warning.
* Appeases clang.
* further appeasement
* Appeasement and time-traveling review changes
* change the enum branch too that'd be good
* More requested changes
* Basic abstraction for generic modular curves
* Make curve list by output statically sized
* Make instance-randomization consistent and mapless
* Add parsing
* Add derived modular curve sets
* Fix incorrect unpack
* Split modular curve set and definition, properly comment struct usage
* Split off specific type-traits into own file
* Fix modular curves for multi-derive case
* Implement some basic weapon curves, as well as the damage multiplier hit curve
* Merges in generified system built by Lafiel.
* Fills out beam curvesets.
* Renames curvesets.
* Removes launch curves for now.
* Testing, bugfixing.
* Various cleanup
* Returns extern do_subobj_hit_stuff
* Fixes compile errors
* Beam flag checking
* Rearranges beam flag checking.
---------
Co-authored-by: BMagnu <[email protected]>
A connection speed of "None" is really just the default used by launchers if the user hasn't explicitly set the speed yet. Additionally, `CONNECTION_SPEED_NONE` isn't really used by the engine except for error checking. So, fall back to the default connection speed even when the speed has been set to "None".
Follow-up to #6402.
Many SEXP operators that work on subsystems use very similar code. This new function allows the operator implementations to be streamlined and makes future modifications easier. For example, the `change-ai-class` operator now works with names such as `<all turrets>` as well as specific subsystems.
As described in #6445, the `warpIn()` script function did not work correctly for docked ships because the dock leader flag was not set. So, set the flag, but make sure to set it only for the first ship for which `warpIn()` is called. And make sure the flag is removed after the ship finishes arriving.
Also remove an `Int3()` in `shipfx_warpin_start()`. (This Int3() was not actually in the original Volition source code release.)
Fixes#6445.
* Add option to set a font size multiplier for ttf fonts
* remove the option if we have no scaling fonts
* Clang the conquerer strikes again
* Update XSTRs
* clang
* Clarify comments
Having a missing bolt texture is not fatal; TBP uses it for `b_invisible`. Modify the bolt checks to display a non-fatal warning if the bolt texture is explicitly specified but not found.
Many beams are lumped into the #Primary Weapons section of weapons.tbl, which will mark them as WP_LASER. Fix the few instances of code that are intended for beams that may have omitted most beams by mistake.
Randomization of weapon impact particle radius is also affected, but since this affects existing visual effects, it was not changed.
A recent-ish FSO feature, `$Turret Name:`, allows turrets to be displayed differently on the HUD depending on the weapon they carry. It is useful for scripts to be aware of this, so this PR adds a `TurretName` virtvar for weapon classes, as well as a `NameOnHUD` virtvar for subsystems. The `NameOnHUD` virtvar shares exactly the same code as the HUD uses, so any future HUD modifications will be reflected in scripting as well. This required a small amount of refactoring: changing `get_turret_subsys_name()` to return a value rather than stuffing a string, renaming it to `ship_subsys_get_name_on_hud()`, and moving it to ship.cpp.
This refactors FontManager to improve it in several ways:
1. Change all the dynamic memory management to use `new`, rather than mixing `new` and `vm_malloc`
2. Change the current font to use an index rather than a pointer
3. Take advantage of more C++11 features to avoid redundant lookups
4. Use case-insensitive name comparison
5. Avoid overflowing the `fnt->filename` field
6. Use `Warning` rather than `Error` in a non-critical error situation
1. Don't set the `can_use_for_bank` flag to FALSE if the bank is primary but the weapon is secondary, or vice versa
2. Make sure to only restrict the weapons by bank if the ship has per-bank restrictions
In support of this, add `is_primary()` and `is_secondary()` helper functions to `weapon_info` and use them in logical places.
Follow-up to #6434. Fixes a few subtle bugs from that PR.
When clicking on a weapon bank, mark the weapons as enabled or disabled according to their compatibility for that bank. Do not actually prevent the weapons from being selected and dragged, as they may be dropped on a bank that isn't selected.
Also add a new `TriStateBool` for situations where the value is true, false, or unknown.
Fixes#6398.
FRED has code to keep track of whether the main window should be rerendered on each frame. It looks like this was accidentally removed at some point.
(Discovered by comparing FRED source files while investigating #5568.)
A few addenda to PR #6364:
1. Use `std::swap` in the move constructor, since the fields are specifically being moved, not assigned
2. Fix off-by-one error when parsing firing patterns, and make the pattern count non-fatal
3. Standardize the setting of fire points since it's done in three different places, and in the case of `ship_set_default_weapons()`, `primary_firepoint_next_to_fire_index` was not reset to 0. It might be useful to refactor this code into its own function.
4. Make the setting of `primary_firepoint_next_to_fire_index` consistent between forward and reverse cycling
5. Remove a couple redundant `.clear()` calls and fix a typo
Any DDV (Dialog Data Validation) routine must appear immediately after the field it validates in order for the enforcement to work in real-time. If the DDV_ routine is not linked to the field, it will perform validation after-the-fact by displaying a dialog box and returning an error. This is an alternate way of handling validation, but in order for the dialog box not to generate an endless loop, it would be necessary to check the return value of every `UpdateData(TRUE)` call in the FRED codebase (or at least the first `UpdateData(TRUE)` in a pair of them) and then, if the return value is `FALSE`, doing an early return from the enclosing function.
Fixes#6427 as well as all similar cases in FRED.
The recent cycle expansion PR (#6364) causes a CTD when change-ship-type is used. This PR fixes that crash by using `pm->n_guns` instead of 'MAX_SHIP_PRIMARY_BANKS' and clarifies the definition comment for the `pm->n_guns` to help avoid this kind of quandary in the furture.
Tested and works as expected.
Adds a new `+Ambient Sound:` field to mainhall.tbl, allowing any interface sound (or even no interface sound) to be used for the main hall ambient sound. The default ambient sound, as well as the sound played on the pilot select screen, is interface sound 12.
Implements #6421.
If the mission is edited in a text editor, and a ship is given too many weapon banks, this can cause issues in the weapon firing code. Protect against this by checking the number of banks when the ship is created.
* Adds different firing patterns for weapons.
* cleanup
* further cleanup
* appeasement
* appeasement^3
* Requested changes.
* Deals with targeting flag issue.
* Resolves merge conflicts.
* blood for the blood god, tidy for the tidy throne
* Increments XSTR again.
Related to the previous two commits, the medals screen should use the actual all-time stats from the pilot file instead of the active campaign stats. This required tweaking the DCF "medals" debug command to work with the exported stats. Also, some C casts were changed to C++ and an obsolete variable was removed.
Related to the previous commit, the debriefing should use the actual all-time stats from the pilot file instead of the active campaign stats. In multi, however, use the active campaign stats; because the debriefing can display stats for different players, and all-time stats are only available for the local player.
Also, clean up and slightly refactor `show_stats_label()` and `show_stats_numbers()`. Duplicate code has been removed, string output has been streamlined, and a few bugs with percentages (especially divide-by-zero checks) have been fixed.
The FreeSpace AI includes behavior to run away from shockwaves to try to avoid explosion damage. This is implemented for both ships and missiles, although the missile implementation has been buggy ever since retail. There are several issues:
1. The AI attempts to evade a weapon immediately upon launch. Many missiles have a period of free flight before they start homing on their target. During the free flight period, the homing position is not set. Consequently, the AI will not know the position to avoid and will make assumptions.
2. The AI assumes the shockwave-producing weapon will detonate at the center of the ship it is targeting, although missiles detonate on the surface. A capital ship is likely to be significantly larger than the weapon's blast radius, leading the AI to believe the detonation will be much farther away than it actually is.
3. When avoiding ship shockwaves, the `shockwave_object` field is not cleared when avoiding is complete. This can result in stale references (though not crashes, due to object type checks), causing AI to not avoid future explosions in certain cases.
4. When avoiding ship shockwaves, the code does not check the correct ship for the amount of damage caused by the shockwave.
All of these issues are now fixed. Since this is a change in AI behavior, these fixes are tied to a new AI profiles flag.
The barracks should use the actual all-time/multi stats from the pilot file instead of the active campaign stats. Export the all-time stats from the pilot file in order to populate the barracks.
Follow-up to #6238.
```
code/menuui/barracks.cpp:188:8: error: type ‘struct barracks_buttons’ violates the C++ One Definition Rule [-Werror=odr]
188 | struct barracks_buttons {
| ^
code/menuui/playermenu.cpp:82:8: note: a different type is defined in another translation unit
82 | struct barracks_buttons {
| ^
code/osapi/osregistry.cpp:478: error: type ‘struct Section’ violates the C++ One Definition Rule [-Werror=odr]
478 | typedef struct Section
code/pilotfile/FileHandler.h:18: note: a different type is defined in another translation unit
18 | enum class Section {
```
This adds a sexp to allow any boolean condition, or series of conditions, to be evaluated not only instantaneously, but also for a period of time. For example, this can be used with `is-facing` to check if a ship has been facing another ship for a specified duration. Previously this had to be done through scripting or through a group of sexps.
Implements #5754.
When a player tries to skip a mission during a campaign, all goals and events are marked true. Thus it's possible for the campaign condition to unexpectedly *not* evaluate to the next mission (e.g. `if is-previous-goal-false` or `is-previous-event-false` is used without the optional argument). So add a failsafe check, with a warning, to handle this case. Also update the documentation to clarify that the optional argument is checked for the mission-skipped case.
Fixes an endless skip-to-the-same-mission loop discovered by ShivanSlayer in Shrouding the Light.
PR #6335 did not update actions/upload-artifact; both upload and download need to use the same major version number.
Also move from v4.1.7 to just v4 because that appears to be the common practice.
1. Use a sensible default for the connection speed
2. Remove the `Psnet_connection` variable which is now obsolete: "its only purpose now is to change the default object update value for a player if it's set to dialup, and that's easily done in-game already"
The "You must define your connection speed" popup will now no longer appear unless it has been explicitly set to an invalid value.
Applies recommendations from, and fixes, #6402.
Hide these SEXP operators to reduce confusion for FREDders. They still work, but using them properly requires a certain amount of knowledge of the inner workings of variables, and the operators can break if new variables are added causing the list to be re-indexed.
Implements half of #6400.
1. Since we already handle `<all engines>` and `<all turrets>`, it's simple to extend this to all generic subsystems of any type
2. Add an `<all subsystems>` case for handling every subsystem on a ship
3. Add some compiler directives to enforce preconditions for subsystem type `#define`s
There are a few places in the Lua script API where a variable could be some type of "object" or something that is not an "object" but is still useful - one example is the return value from oswpt:get(). With this function, scripts will be able to tell what the variable is without risking an exception.
* Fix AVX2 detection
* Also query for proper OS support
* Actually properly set ISA level on all platforms
* Expose level of x86-SIMD instructions to the code.
* Fix handling of forced instruction set
* Fix errors
* Fix MSVC
* Properly deal with linux CI builds
* fix clang
* Add support for RISC-V compile to cmake
* No need to pass -march for gcc in riscv
* -march=native is not supported in Risc-V clang
* fix comment and remove unnecessary newline
* Remove incorrect values while checking CMAKE_SYSTEM_PROCESSOR
* Support 32bit RISCV as well
I dont think this will be ever be needed, but i dont like that compilation will fail due to incorrect compiler flags if you try.
* Set ver to C++17
* remove deprecated shuffle
* Fix std::iterator being deprecated
* Work around codecvt deprecation
* Fix std::result_of deprecation
* Another random_shuffle
* another text conversion replacement
Takes the command-line arguments used to launch FRED and reuses them to launch FSO.
As part of this, slightly refactor the `cmdline_print_cmdline_multi()` function so that it calls a new `cmdline_build_string()` function.
The enhanced controls and flags in #4552 were intended to allow the camera to shudder in all views, not just the cockpit view. And indeed, the shudder does apply in all other views... except for cutscene cameras, due to the `VM_FREECAMERA` check in `game_render_frame()`. So, add a separate check for cutscene cameras when shuddering everywhere. The cutscene camera can be jittered just like the cockpit camera, but the rotation should not be modified or it will produce feedback.
Follow-up to #4552. Also removes an unused variable that was made obsolete in #5656.
This fixes the fighter/bomber type which had been broken ever since the objecttypes.tbl upgrade in 246cfcfa65: the fighter/bomber type is again treated as a union of fighters and bombers, not a unique type of its own. This requires special handling for the `OPF_SHIP_TYPE` SEXP argument type, and all four SEXPs that use `OPF_SHIP_TYPE` have been modified to check for the special case. The explicit fighter/bomber type has again been removed from the built-in objecttypes.tbl.
The requirements for "fighter/bomber" to be valid are 1) there is no explicit "fighter/bomber" type in the mod; 2) a "fighter" type exists; 3) a "bomber" type exists. If any of these conditions is not met, the special case behavior is not enabled.
Follow-up to #6390. Properly fixes#6388.
A few missions used the fighter/bomber ship type, so this adds the type back to make those missions work again.
Temporary fix for #6388. A more proper fix will be applied after the official 24.2 release.
This is already done in `movie::play()` and shouldn't be done again if a script overrides the function. The extra calls were added in 251285cacc and cbccf655fa (the former copied from the latter), originally as an unsuccessful attempt to fix Mantis 61.
Add an `$On Movie About To Play:` hook to match `$On Intro About To Play:`. Also make the two hooks overridable, since that might be useful.
Additionally, change a few (nonexhaustive) `name` parameters to `filename` to make it clearer that the string is a filename.
Augments the voice acting manager to handle non-wingman as well as wingman personas, plus limit operations to a specific persona. This also modifies the editor to only increment the number of modifications when something *is* modified, not merely when something *could be* modified but is currently the expected value.
Resolves#6379.
The XSTR entry 1779 (strings.tbl) is used for two different texts:
"Disabled" in shadows.cpp;
"Toggle Auto Pilot" in controlsconfigcommon.cpp;
"Disabled" is already assigned to XSTR 413. ATM I have this set to shadow's usage (even though 413 is related to Disabled ships). Alternatively I would be happy to use `"Off", 1693`, which is what the other graphic settings use (though the actual value in the code would still remain `Disabled` of course).
This adds several missing initializations of cargo titles for both ships and subsystems. Note that `Subsys_status` initialization needs to happen in `allocate_subsys_status()`, because subsystems can be allocated in red-alert or in the `ship-copy-damage` SEXP, not just parsing.
Follow-up to #6000. Fixes a rather insidious ERANGE error in Inferno.
1. Tweak the API of `error_display` so that an error level of 2 displays a `ReleaseWarning`.
2. Use this error level for the malformed XSTR warnings in the localization code.
Resolves#6374.
* Remove unneeded comment on U and V axis. (Comments there are for original axis XSTR indices)
* Fix UI issue where bound button message did not display which controller it belonged to
* Removed unused extern reference of Joy_button_text
This makes it so that the "3D"/"2D" display is actually respected in the in-game options menu, rather than just having an ambiguous checkbox labelled "Shockwaves".
The "stealth" and "fighter/bomber" ship class flags are not actual ship types, so they should never have been added to objecttypes.tbl. Remove them from the built-in table.
Additionally, if a mod *does* use "stealth" in its own objecttypes.tbl, remove it. This prevents the invalid "stealth" type from overriding a valid existing type, which fixes#6366.
When actions in the Voice Acting Manager modify the mission, set the modified flag so that FRED will prompt to save the mission. And since this requires tracking the number of modifications, enhance the dialog boxes to display this information to the user.
Fixes#6362.
Several locations in the code (notably `ai_info` and `waypoint_h`) previously stored pointers for waypoints and waypoint lists that need to be valid for more than one frame. Since both waypoint lists and waypoint paths may change size, resulting in vector reallocation, the information should be stored as indexes instead.
Fixes#6353.
Apparently virtvars can only return one value. This deprecates the virtvars and adds function equivalents for getting weapon class swarm info and corkscrew info. Fixes a bug reported by Woolie Wool in Discord.
The warning for mismatched names-and-indexes implicitly assumed that retail-style sounds would only be added with numeric indexes. Since adding named sounds in the retail style is, in fact, allowed, update the logic to not warn in that case.
Fixes#6354.
1. a `hud-reset-color` SEXP operator, to complement the existing `hud-set-color` and set a gauge back to its configured color
2. `ConfigType` and `ObjectType` Lua virtvars which are essentially the built-in gauges' equivalents of `Name` for custom gauges
3. `getColor` and `setColor` Lua functions
Since the `OPF_ANY_HUD_GAUGE` type checks for any default or custom HUD gauge in regular SEXP operators, it should do so in scripted SEXP operators as well.
Fix a small oversight from #6112. In the empty/placeholder indexed sound situation, although the sound should not be appended (since it indexed), it should still be treated as a new sound, in order for all the first-parse and first-initialize logic to run properly. Set the right value and add some comments to illuminate the logic.
Fix the inadvertent swapping of the two utility functions for parsing sounds. While we're at it, streamline a few lines, remove a few C-style casts, and remove an unused function prototype.
Follow-up to #6314. Fixes a crash encountered by Inferno on 24.2-RC1.
Per the comment earlier in this function, both -1 and -2 are expected values for sound indexes. Update the sound validity check accordingly. Fixes an assertion in `obj_snd_delete()` encountered by FotG when a sound index was -2.
* upgrade asteroid sexps to match new asteroid field features
* clang is a needy boy
* unify the sexp operators into one since there are minimal changes
* cleanup for readability
* address feedback
* keep from crashing
* Also, bash the number of waves if necessary
* Add Debug warning to modders
* address feedback
* formatting
---------
Co-authored-by: Goober5000 <[email protected]>
The BWO fix in PR #6317 was not quite the correct fix. The `sim_room_lines` array contains the maximum number of scrollable lines, not the maximum number of lines on the screen at one time. This partially reverts commit 20338ff28b and implements a new fix that allows the full `MAX_LINES` but also properly checks the list button limit. Additionally, this adds the list button limit check to other vulnerable code sections.
Fixes the tech room being limited to a single page of missions after #6317. Testing confirms that the BWO crash is still fixed with this update.
This is an error that existed all the way back in retail. Each line in the simulator room (i.e. each mission name in the list) is also a "button" in the sense that clicking on it will highlight the line and set some values. The maximum number of buttons is `LIST_BUTTONS_MAX`, but the maximum number of `sim_room_lines` was a different #define, `MAX_LINES`. This was set to 200, a far higher value than the `LIST_BUTTONS_MAX` value of 42. The code responsibly checked the limit, but the limit was incorrect.
(This had not been seen in previous mods because the number of lines was never high enough to reach 42. BWO happened to use a font that was small enough to fit that many lines in the mission simulator screen. This explains why removing fonts.tbl prevented the bug from occurring.)
Thus when the number of lines reached 42, the sim room started writing to out-of-bounds memory. This didn't cause a crash immediately, but did corrupt the `Static_lights` vector, which in turn caused a crash as soon as a model was lit in-mission or in the ship loadout screen. It's rather strange that this crash only occurred in optimized SSE2 builds though.
The fix is simply to use `LIST_BUTTONS_MAX` as the limit, rather than `MAX_LINES`. This also removes the unused `MAX_DESC_LINES` and `Num_desc_lines` at the same time.
Fixes#6313.
1. Make sure the legacy `timestamp_until()` and `timestamp_since()` functions check for any type of invalid timestamp
2. Add a useful `isFinite()` function
3. A timestamp delta on an immediate timestamp is more properly the actual delta, rather than another immediate timestamp
Add options to the Edit menu to lock and unlock objects. Locked objects cannot be selected or dragged. They can still be edited in the various editors (e.g. Ships, Objects) but not in the main viewing area.
Also add the Selection Lock option to the Edit menu. It was previously available in the toolbar but this provides another way to access it.
When the Show Waypoints option is toggled, the marking was not updated as it was for the other options (Show Ships, Show Starts, Show IFFs). Fix this by calling `correct_marking()`.
* Cleanup variable name in `weapon_do_area_effect` function
Per discussion in #6302, this PR renames `other_obj` to `impacted_obj` to minimize confusion
* update other functions with impacted_obj naming
* nullptr
* appease clang's strange rules
* fighting clang continues
* use !empty check instead of > 0
* remove un-needed no lint comment
Per #4294, this adds two new flag that, together, are equivalent to the legacy "immobile" flag but individually provide more fine-grained control. Since the physics for position and orientation have a bit of overlap, the new flag functionality simply reverts whatever position or orientation changes were done by the physics sim.
In the FRED and qtFRED ship flags dialogs, the "immobile" flag (aka "Does Not Move") is replaced by the two new flags, but in FSO the situation is more complicated. The old and new flags coexist and have overlapping functionality, so the mission designer must be careful to set and unset the appropriate flag (that is, it is possible for both "immobile" and "don't-change-position" to be set at the same time, in which case the ship cannot change position without both flags being unset). The `set-immobile` and `set-mobile` legacy SEXPs ensure that the new flags are removed so as not to conflict with the legacy flag, but the `alter-ship-flag` and `are-ship-flags-set` SEXPs and the `getFlag` and `setFlag` script functions use exactly what the FREDder/scripter specifies and nothing else.
(I attempted to completely replace "immobile" with the two newer flags, but it proved intractable to do this while maintaining reverse compatibility: retrofitting single-flag functions to apply dual flags for one particular situation made the functions harder to understand as well as introducing many edge cases and opportunities for bugs or "gotchas".)
Implements #4294.
* Fixes CTD with new Friendly Fire Feature
On current master I was hitting a CTD when firing a weapon with a shockwave at close range (ie player is within the shockwave zone). The minidump showed `other_obj` was null, so this PR adds some safety checks.
Tested and this fixes the crashes.
* fix obj usage
* one more obj cleanup
Prevent compiler warnings caused by the `value` parameter of the external serializers hiding the `value` member of `std::integral_constant`.
Follow-up to #6276.
* Adds particle effect offset.
* bugfixing
* Switches to a cleaner approach.
* Futureproofing for particle parenting.
* actually let's just bundle parenting into this one
* working on turrets
* grinding toward turret correctness
* still grinding toward correctness
* Gets turrets working correctly.
* Fixes merge artifact
* appeases clang-tidy
* Updates some comments.
* Updates some comments.
* Tiny bit of cleanup.
* Deduplicates comments.
The return value of `lua_tostring()` is NULL if (and only if) the string conversion failed. Many places in the code did not check for this situation, which led to the crash in #6290.
Fixes#6290.
* Adds curves for slash completion and rotation.
* Finalization.
* Fixes pointer comparison.
* Updates table parameter to better match behavior.
* Makes requested changes.
* Changes rotation amount to use raw curve.
* Sets curve-1.0 to be equal to full turn rotation.
As noted on Discord, there was previously no `is-species` operator. Now there is.
As a bonus, this also fixes a bug where the pre-existing `is-iff` operator did not work with wings that had not yet arrived.
This fixes an edge case in the Average and Multiple modes, where secondary lead indicator rendering was skipped by continue statements when the primary weapons were out of range. I also added some comments that help people actually understand what this function does as it is very confusing.
Although sound indexing is now done by name, mods which index by number (sc. a number that is treated as a name) expect the indexes to be in numeric order. When multiple levels of -snd.tbm files add mixed retail-style and new-style sounds, this assumption can be violated due to named sounds being placed into indexes that later files expect to be available.
This PR refines the parsing so that sounds which use a numeric index can pre-empt existing named sounds that have been assigned to that index. Since named sounds can go anywhere, they are just moved to the end of the list. This allows the ranges 192-199 and 202-249 to be available for numeric indexes as expected under the old style. MediaVPs named sounds which were previously parsed into those indexes are bumped to the next available index.
Additionally, this PR doubles the range of numbers that are treated as indexes, to more realistically accommodate additional numbered sounds. (The number/index distinction is rather arbitrary and is primarily used to avoid creating large sections of unused sounds if a mod were to specify a very large number, e.g. 10001, for a sound name.)
Finally, this changes parse warnings to use `error_display()` so that the warning displays the parsed file and line number.
Fix units are denominated in seconds, while timestamp units are denominated in milliseconds. This fixes the directive timing check which, after the timestamp upgrade, would time out after 5 and 7 milliseconds instead of 5 and 7 seconds.
Follow-up to #4633.
* Sets up linear interpolation for object particles.
* Makes interpolation time-based.
* Updates comments to match changes.
* appeases clang-tidy
* Adds interpolation for particle particles.
Model textures that are too long will cause a very unfriendly and hard-to-track down "ERANGE: String" error. The situation can be greatly improved by checking the string length ahead of time, printing a friendly Warning, and truncating the filename. This will alert the modder to the source of the problem while also allowing gameplay to continue.
This would crash because duplicate sounds were not being populated with the original entries. When snd_set_pos was called, the handle to the Sounds array would not be set, making our code think it was not loaded.
This was motivated by the recent Coverity report. Coverity noticed that a few of the copy assignments could be replaced by move assignments, but on further investigation one copy each in `ship_weapon_check_collision()` and `beam_collide_ship()` can be entirely removed, another either/or copy in each can be replaced with an either/or pointer assignment, and a few copies can be done only when needed. Another vec3d copy (`hit_dir`) can be replaced with a vec3d pointer; it is no longer modified locally, so there is no longer a need to keep a local copy.
According to DahBlount:
> Most atan2 implementations for a long time had problems when the inputs were close to machine epsilon or when x was less than or equal to 0
And according to z64555:
> Modern versions of C++ should have an atan2() that works correctly when the inputs are at 0 or near epsilon of the floating point specification, meaning Volition's workaround shouldn't be needed anymore.
So this removes `atan2_safe` and changes all instances to `atan2`. Consequently, the angle range in FRED now shows as [-180, 180] as expected.
Fixes#3730.
The somewhat modern AI flag for `Require_exact_los` is extremely useful in multiple different situations, for example making large capital ship weapons not fire into friendly surrounding ships on accident. When the feature was added, the `check_los` function was provided with a default value of `10.0` meters for minimum radius detection. This PR exposes that value to modders so they can set it to a reasonable value depending on the ship sizes of their specific needs. And as a note, the los value just uses a simple numerical comparison check, so the los detection could be set to a negative value with no consequence (hence why error messages were not added, though if folks would like I can certainly add them).
In retail, the processing of certain keys during a popup, in the `popup_process_keys()` function, was dependent upon the `PF_ALLOW_DEAD_KEYS` flag. This flag was never used in retail, causing the if() block to be marked as dead code. In a4e623db23, the dead code warning was addressed by removing the dependency on `PF_ALLOW_DEAD_KEYS`, which is incorrect. The "dead keys" should only be processed during the "dead popup". Since the "dead popup" was moved to its own de[a]dicated "popupdead" section, the "dead keys" processing can be entirely removed from the "normal popup".
Fixes a bug noticed by @PremiumColt where certain keys, especially the time compression keys, were processed while the ESC popup was active.
This prevents Coverity from running on any forked repository, by default; both because the workflow will fail, and also because the workflow's results would be identical. (Any forked repository can, of course, change this within its own scope.)
In `strings.tbl` the graphics settings localization IDs are as follows:
1160, "Low"
1161, "Medium"
1162, "High"
1163, "Very High"
These values are used throughout the code, but in some cases with SCPUI upgrades, the IDs got off by 1. This PR fixes those incorrect IDs.
Supports newer SDL2 from the prebuilt package on win32/win64
Adds support for Windows ARM64
Adds option to use prebuilt SDL2/OpenAL/Freetype libs on Linux
* coverity - using `std::move` instead of copying, and change some parameters from value to reference
* coverity - fix or mark potential copy-paste mistakes
* coverity - various checking of parameter and return values
* coverity - miscellaneous fixes, and change some 'intentional' markers to 'false positive' markers
In current master, the debug log commonly shows `CSG => Warning: (0x0011) Short read, information may have been lost!`.
Thanks to Taylor for pointing the following issue out:
The function `pilotfile::csg_read_redalert()` returns if `ship_list_size` is zero, but it still needs to check the `wing_list_size` a bit below that. This has likely not caused data loss issues ATM, because it's reasonable to assume that if `ship_list_size` is zero then so is `wing_list_size`. But it's still a bug and should be fixed before it does cause some real data loss.
This PR moves the relevant read sections to within each respective if-block. That way the function is capable of checking both `ship_list_size` and `wing_list_size` on every load (even if `ship_list_size` is zero).
Per @notimaginative, change the `compiler` variable to uppercase to match its usage in the rest of the file. This should allow the coverity task to start running again.
I took a close look at the code involved in parsing particle tables. There is no smoking gun, but there are several ways to polish the code which I have implemented here. The most likely culprits for the slowdown, IMO, are the repeated conversions between SCP_string and C-string, especially in `ParticleManager::getEffectByName()`; followed by the omission of `std::move` in several places.
Adds an optional argument to the `lock-perspective` sexp to allow locking of the 'free look' or 'padlock' view. This prevents the player from looking around which might not be desired in certain forced perspective situations.
When loading a legacy mission that contains a debris field, FSO will try to index into an empty vector, causing an out-of-bounds exception. This can be seen by loading Derelict mission dl1-08, "The Horror in the Deep".
The `// Obsolete and only for backwards compatibility` code added in #6021 properly handles asteroid fields, but not debris fields; so the fix is simply to apply the logic to debris fields as well.
Patches the gamesnd system in several ways to properly fix the bug identified in #6196. Due to the way the new sound system was written, sounds with numeric IDs were not necessarily added in their indexed location, even though the code assumed (even prior to #6112) that this would be the case. The code now uses the proper index for both old *and* new style sounds. This is done by ensuring, in `gamesnd_parse_entry()`, that the vector contains an entry for the specified numeric ID before doing a search for that ID.
Due to the slightly modified population of the gamesnd vectors, the `Snds_iface_handle` vector is now populated after parsing the various sounds.tbl files rather than during parsing.
Separately, this makes consistent the handling of the `sound_entries` vector which could potentially be empty but also treated an empty state as an assertion failure.
#6187 fixed transparency for cockpits, but the positioning for deferred lighting alas fell through the cracks. This PR fixes that and allows deferred lighting in cockpits to once again work as intended.
Tested and fix works as expected.
When a new mission is loaded, clear the parse names vector, in lieu of the old `Num_parse_names = 0;` line. This fixes a bug where FRED will complain about nonexistent ships when loading a different mission. Follow-up to #5937.
* One more follow-up to #6021
Update assertion message and mission saving check since older builds are not going to be able to read fields created with newer builds
* update to use empty
The Unlimited Asteroid/Debris Field Types & Subtypes PR (#6021) updated to using vectors to allow for unlimited asteroid and debris types. That update removed the count field, `num_used_field _debris_types`, which counted both asteroids and debris pieces (even though the name only has debris in it). The counter variable was removed in favor of `.size()` but now both asteroid and debris field sizes needed to be checked, so this PR updates the code to account for that. Allows asteroid fields to properly pass the count check and properly again spawn in mission.
Tested on asteroid fields passive and active along with debris fields (both created from sexps and the asteroid mission editor) and everything now works as expected. Also tested on missions with no fields and those also still work as expected.
Break when you've found a match, instead of just mindlessly comparing the rest.
This is technically just an optimization and safety change, but potentially, before, if the loops had been switched, it would have caused unexpected behavior if two copies of the same flag were listed.
The header length from the tracker is 1 byte larger than the size calculated
by the client due to psnet removing that byte internally. The header length
is adjusted to compensate for this, but only *after* the deserialization
process, so we have to use the received packet size instead.
* Remove old interpolate angles quick
* Remove old interpolate functions
These are no longer used.
* Add linear interpolate vm function
More clearing functions
* Add physics snapshot struct to silo interpolation
Two of these two functions require an object pointer, so they cannot be in physics_state.cpp
With doxygen documentation
* Try to placate Linux
* Address Feedback
* And update declaration, of course
* Attempt to appease linter
* add API for glow point banks
Previously, a model API existed for glow points mounted on thrusters, but not glow points mounted on glow point banks. This adds glow point bank support. Also, this refactors and cleans up the implementation of the model API a bit.
* NULL -> nullptr
Should allow for most games, even those behind CG-NAT, to work without having
to set up port forwarding. This set of changes is only needed for game servers
to work with the new feature. No special handling is required for clients, so
any build from the last few years should work for them.
The new `ai-disable-ship-tactical` and `ai-disarm-ship-tactical` goals were inadvertently omitted from the ship type default table, causing these goals to not be available in the Event Editor drop-down menu or Ship Editor initial orders. Testing did not catch this because testing was done using the HUD squad message system which assigned the new goal (if the flag is enabled) without explicitly checking the validity.
Follow-up to #5512. Fixes#6189.
* make mission log dynamic
Change the mission log from a static array to a dynamic vector. This removes any chance of the mission log running into a limit (as regularly happened with the last mission of Shepherds before the limit bump) and also prevents strange mission bugs caused by culling obsolete entries.
This also unifies the API a bit by renaming the public `message_log_` function prefixes to `mission_log_`, removing the redundant `Num_log_lines` variable, and removing `Log_scrollback_vec` from the header.
Implements #5878.
* feedback
* refactor to reference rather than pointer
* base working version of unlimited debris types
* Proper FRED support
* make qtFRED handle asteroids properly
* fix qtFRED assertion
* further clean out MAX_RETAIL_DEBRIS_TYPES
* These should be sizes not POFs
* Move this to it's own method
* convert asteroid subtypes to a vector
* unlimit asteroid subtypes
* fix some global shadowing
* signed/unsigned mismatch
* Address feedback
Fixes a bug with new unified scanning PR (#6000) and adds a bit of cleanup, including consistent brackets, whitespace cleanup, and removing vestigial function from the original PR.
Tested and works as expected.
* disable popen
* Check file type when opening with io lib
* Compile on Windows
* Windows include
* Properly conserve function environment
* Correctly copy fenv
* Move these functions into OptionsManager for more global use
* Make sure player options are preferred even when using OptionsManager
* persist the newly loaded options to disk
* Actually let's persist these only if the load is successful and also handle the multi option
* Comment this out for now I guess
This refactors the object_h struct to store objects as indexes rather than pointers. This is a prerequisite for making the collection of objects dynamic in the future. See also #6100.
Follow-up to #5800 and #5829.
* Save/Load player options to a mod-specific ini file if possible
* use rfind instead of find to ensure it's the last dash character used for trimming
* cleanup + comments + nullptr
* A more robust way of getting the mod root using lambdas
* prevent infinite loop for non Knossos/Knet mods
* Notify the player if options may need updating and pull settings from fs2_open.ini if we can
* proper localization
* update xstr
Inspired by #6178, this moves the existing `count_items_with_name()` functions into utility.h and adds additional functions for finding specific items with a given `.name` or, more generally, a given field. The `Damage_types` search has been converted to illustrate how these functions can be used.
* Expose Impact Damage Type to Scripting
There's already a sexp that does this, but having the script version for ships is quite useful, too. For example, scripters can set impact damage types for just the player at various difficulties.
Tested and works as expected.
* always set damage type
* Exposes the New Flight Cursor Mode to Scripting
Thanks to #6136, FSO supports switching between two methods of flying. This PR exposes those settings and values to scripters. Tested and works as expected.
* fix aiming setting
* add reset position function
* cleanup setting pitch and heading
* one more cleanup
* update to enum support
* remove older version
* one more fix for setting flight mode
* Clean unneeded properties
* properly queue-ify keys
* Refactor key checking to use functions instead of globals
* Update hooks and cache checked-against key
* Documentation and Naming
* match tilde
* only remove control not debug
* Move replacement textures from ship to modelinstance
* Actually set pmi
* Fix texture replace in fred as well
* Fix bad indent
* incorporate feedback
When game sounds were changed to allow named entries, it became possible for named entries to unexpectedly replace numbered entries. This was noticed most obviously in the ballistic rearm sound effect, which started using explosions rather than the standard rearm sound effects. This occurred because MV_Tiny and MV_Small were added into indexes 200 and 201.
To restore the original behavior, the code now prevents sound effects added via TBM from being placed into reserved indexes. The reserved indexes are instead assigned placeholders, which can subsequently be updated or left alone as the modder prefers.
This also makes the code a bit more robust including patching some sound validity checks in `gamesnd_game_sound_try_load` and `snd_load`.
Considering that we have `ba.createRandomVector()`, we should have `ba.createRandomOrientation()` too. This is based on an algorithm devised by @Baezon.
When messages are distorted due to EMP effects, the voice volume should be controlled by the voice setting, not the effects setting. Fixes a bug noticed by @skdKitsune, a portion of which dates back to the original public source release.
Also, when volume is adjusted in `snd_set_volume`, make sure the correct voice volumes are used. Fixes a copy-paste bug from #5694.
The three functions `physics_apply_whack`, `physics_apply_shock`, and `physics_collide_whack` limited speed after the physics had been applied, but they limited absolute speed, not the speed due to the physics. This modifies the process to limit the change in speed. It also adds an AI profiles flag to disable the limit if desired.
This also tweaks the three functions (by editing comments and moving lines) to be more consistent, since all three are doing very similar calculations near the end.
* Expose Collision Rotation Factor to Players
Previously, there were hardcoded checks in place to make players have 0 rotational effects when colliding with another ship. This PR adds a new value, "+Player Multiplier for Rotation Factor:" that allows modders to have players experience rotational effects from collisions. Also performed some cleanup of the light and heavy collisional rotational calculations by removing older if-blocks following useful recommendation from Asteroth.
Tested and works as expected.
* make rot_fac_multiplier_ply_collisions into global value
* update name to better match with ships table
* restore repeated comments to help with separation
Follow-up to #6047. This method better accounts for matching the guardee ship orientation when using the new AI flag.
Tested and works as expected. Thanks @BMagnu!
1. Add the "Override #Command in event messages" checkbox to qtFRED
2. Add the "Preload Subspace Tunnel" checkbox to the proper button group in qtFRED
3. Reorder lines in fred.rc so the declarations match the order they appear in the dialog
4. Use the correct name when reporting fireball index errors for ship classes
This provides a command-line argument to restrict the time compression range to the classic 1x - 4x. Implements #6075.
I'm not entirely satisfied with `-orig_speedx_range` but it's the best I came up with that fit into the 19-character limit. I'd be open to other suggestions.
Rework `hud_support_find_closest()` slightly to do a quick out if the player is no longer a valid object. Fixes an assertion noticed by Darius that occurs if the player dies when a rearm is imminent.
Make the initialization sequence consistent so that FSO, FRED, and qtFRED call their initialization functions in the same order. Most of the changes involve bringing FRED and qtFRED into sync with FSO. This fixes fireball prerequisites for the ship types table, applies the script initialization fixes from #5946 to FRED, and generally removes the possibility of any surprises due to FRED differing from FSO.
Also remove the empty `brief_init_colors()` function.
1. fix a bug where blips expired immediately every frame; they now track their expiration by object
3. store object numbers rather than object pointers
3. clamp both the high bound and the low bound of alpha values
Convert `sweep_duration` from seconds to milliseconds to work correctly with the timestamp system. Also clarify use of `game_get_overall_frametime()`, especially with `ba.getFrametimeOverall()`; and add `ba.getSecondsOverall()` to do what `ba.getFrametimeOverall()` allegedly did.
The button should now say restore when the item has already been deleted. Also, this expands how well we warn about deletions and will dynamically decide if we need to warn about deletion.
Allow the resize mode to be specified to `gr_set_clip()` without changing the active graphics-wide resize mode. Along with `drawStringResized`, this provides a shorthand to allow text to be drawn at different sizes, with the appropriate clipping regions, without requiring access to the `CurrentResizeMode` virtvar.
It turns out that an empty string is not the only possible desired value if the filtered string is "-". "-0" should return "0", but would return "" before this.
As requested by Event Horizon, this removes the limit on fireball types. The fixed array has been replaced with a vector and the relevant code updated accordingly. There is also a new version of `stuff_int_list()` to parse ints into a vector.
This also adds bounds checking for explosion animations that are parsed for ship classes, ship types, and asteroids, since previously there was no guarantee that the indexes would be in range.
This is a follow-up to #2942. That PR solved most of the short-circuiting issues with nested conditionals under when-argument, but it was still possible for the code to incorrectly short-circuit on a nested conditional that had `<argument>` in an action operator but not a condition operator. The cleanest way to fix this is to not short-circuit on *any* nodes that are part of a when-argument tree.
First step in the process of working Windows ARM64 support. This adds the most
basic support needed, but by itself will not succesfully build. However these
changes should not interfere with builds for other architectures or platforms,
and should still allow for x86/x64 builds on ARM64 Windows.
Remarkable that we're still finding bugs in fighter beams after 20 years...
Since field-of-fire angles are specified in degrees, and `cosf` accepts radians, the angle needs to be converted (and then halved, per usage elsewhere). Although this is a bugfix, this should technically not affect fighter beam behavior because fighter beams always fire down their normals.
As a follow-up to #5523, some mods use callsigns for their ships but prefer not to display the callsigns in the escort list. In lieu of a more flexible way to configure escort lists, a simple flag is sufficient to implement the desired behavior.
To enforce type safety for arrival and departure locations, this converts them to enum classes. Various casts are added when appropriate to convert between the indexed and enum values.
Allows ships and wings to arrive behind a ship, to complement 'In front of ship'. In fact, the arrival code is nearly identical, with just a small tweak to distinguish ahead from behind.
Since the new arrival location represents a change in mission format, this also adds code to detect for its usage and set the mission format to 24.1. Most missions can continue to be saved as version 23.1.
* Improve Mainhall Button Responsiveness
Previously, there was a 175 millisecond delay when hovering over a mainhall animation before it triggered. This PR makes that value settable via the mainhall table.
Tested and works as expected. Now custom mainhalls have much more of a spring int their step.
* cleanup num res location
Indexes are a more robust way than pointers to manage model and submodel handles, and in the event that models are made dynamic in the future, indexes will be necessary anyway.
Set the bad node to the ship node, so that the FREDder can see which ship is receiving the invalid order. Without this change, the bad node would point to the last value parsed, which is typically the goal priority.
Fixes a misleading error dialog reported in Discord.
When attempting to add a chat message which is all whitespace the split_str()
function will produce no lines. The strcpy() that follows will then crash
due to an attempt to copy a nullptr.
Adds bcdec lib to convert compressed DDS textures to RGBA based on what the
system supports. BC7 if BPTC extension not supported, DXT? if S3TC extension
not supported.
Should support cubemaps and volume textures but those were not tested.
Addtional changes:
- remove indexed DDS support since it had bugs but didn't work anyway
(R8 should be used instead)
- fix issues with volume textures (nothing to test with)
- remove old compression support flags as they are now obsolete
Fixes#4920
Follow-up to #6034. This slightly changes the function signature of `AddElectricArc` but it should be fine since it hasn't appeared in a stable release yet.
* multi host settings ui initial setup
(cherry picked from commit bcb31c327653329e62e4430815fe1e981751f9dc)
* Finish the rest of the API
* include enums
* set these
* Close game needed
* Handle accepting the host setup
* Don't need to be master to set these and add ways to check master and self
* add client ui to this PR because
* Allow getting the player state string
* Multi sync api methods
* unused variables
* Fix state checking
(cherry picked from commit fcde973cdf)
* typo
* address feedback
(cherry picked from commit ecb33e7cc6)
The ai_profiles.tbl options can already be read in any order, so it is modder-friendly to extend this capability to game_settings.tbl as well. This also updates the "unrecognized parameter" log statement to indicate the filename.
Note that this commit should be viewed while ignoring whitespace changes.
Add a routine to the sexp syntax checker that also checks for potential issues. These are not definitive errors, but situations that might trip up mission designers. Currently there is one issue checked: the destruction of a wing that has multiple waves and arrives from a docking bay.
This does two things:
1. Fix a bug in `mission_bring_in_support_ship` that assigns an incorrect parse object index to the support ship's ship registry entry. Since `Arriving_support_ship` is not an item of `Parse_objects`, it should not have an index.
2. Adjust the in-game join checks at the bottom of `parse_create_object_sub` to more scrupulously account for index mismatches and bounds errors, with a specific exception for the arriving support ship.
Thanks to @notimaginative's detective work, nearly all of the FRED stalling when saving a mission can be avoided by simply not calling `model_free_all()`. By checking a flag in `clear_mission()`, multiple situations can avoid this slowdown, including reload-after-save and import-FSM.
The model was not updating its sending to front end list when getting new info from user input. It would save it in the model, but not where it was sending information back to the dialog (UI).
The logic to handle the `$Fixed Missile Detonation:` flag missed an important case: subsystems with concave hull geometry but without destroyable submodels. The original flag was tested on a bowl-shaped turret, which could be destroyed. However the bowl-shaped engine on the SSG Rahu was susceptible to the same detonation problem. By changing the check to always use the radius, whether obtained from a submodel or from the subsystem, the flag fixes the detonation in both cases.
With the `$Damage Impacted Subsystem First:` game_settings flag, weapons will damage submodels over subsystems, even if the subsystem is closer. Yet occasionally this is not the correct behavior (e.g. for the Rahu's engines). The new subsystem flag allows this behavior to be selectively overridden.
Fix a minor oversight from #6014; in the ship lab, there are sometimes no suns at all, so remove the assertion. The lighting check is only needed for supernovas anyway, so make that clear.
Additionally, add further clarification for the distinction between suns, lights, and variables used only for the supernova. Finally fix one more sun/light discrepancy that escaped notice from #6014.
Fixes an assertion in the ship lab. Follow-up to #6014.
* add cockpit fov to in-game options and use a define for the default fov value for both fov options
* Add a controlling toggle option
* constexpr
* localization
This adds the special SEXP return values (SEXP_KNOWN_TRUE, SEXP_NAN, and so forth) as enums, and adds code to intercept these enums if they are returned where the code would normally expect a boolean or number. If an enum is found, it is converted to its special return value equivalent.
With this change, a script can end a function with `return SEXP_KNOWN_TRUE` or similar. No other API changes are needed; in particular, no special `$Return Type:`s are needed.
Implements #5959.
In #5894, in the `add_dynamic_sexp` function in sexp_lookup.cpp, a call to `sexp->getHelpText()` was moved to the bottom of the function. Normally this would be fine, except that this occasion caused the `sexp` variable to be accessed after a `std::move`. The crash can be avoided by moving the last access of the `sexp` variable just a little bit earlier.
This allows the skybox orientation and alpha to be accessed and changed through Lua virtvars, and also adds a sexp to change the alpha.
Unfortunately, changing the alpha has no perceptible effect on the skybox. This will need the attention of a graphics coder to figure out what might need updating.
When waypoint start index and direction were added in #5698 / 42fc989 et seq., the `Fix_ai_path_order_bug` flag needed to be updated to account for those new options. This fixes that.
Fixes#6052.
Since the On Ship Collision hook can potentially be called twice, with the ships reversed, it is necessary for both parameters to have submodels specified. Otherwise +Override would not be able to handle both cases.
Followup to #6035.
* Add AI Flag to `align to target when guarding stationary ship`
When a ship is ordered to guard another ship that is stationary and not incredibly large, the AI will fly to a position then turn and face away from the targeted ship. This behavior is not ideal in various scenarios, including both blockade style formations and overall visuals.
The PR adds a flag that tells the AI to align to the target ship it is guarding once the AI has reached it's guarding position in this situation, which allows all the guarding ships to have the same orientation and look much better and work better for directional defenses.
Tested and works as expected. Also changed some `NULL` to `nullptr` in this function for cleanup.
* remove duplicate brackets
* convert multi team chat to use a struct/list setup
* use the correct array size define
* cleanup local vars & Asserts
* address feedback
* remove uncessary if
* multi pxo api
(cherry picked from commit 9af26da728a19b9d6c890968a314e8e56ecc1ddf)
* multi pxo help api
(cherry picked from commit f4df704576ddb648e9c486907b07ae172c859feb)
* minor fixes
* not extern
* break out chat message data into a table
* address some feedback
* return empty strings if not in multi
* use GetChannelByUser() instead
* once more with feeling
* correct documentation
Kind of surprised this SEXP operator hasn't been added before now. It complements the existing percent-X operators in the Objectives category.
Also, this fixes and clarifies the help documentation for the various percent-X operators.
Turn `Parse_names` into a vector and add SCP_string overloads of ship registry functions. Refactor calling code to use registry as appropriate. Remove an unused overload of `mission_parse_get_parse_object`.
* Add the submodel that was hit to the On Ship Collision scripting hook. (This will only be non-nil if the ship was the "heavy object".)
* Add a `getModel()` function to the scripted submodel object.
* Fix some incorrect documentation in `OnShipCollision`.
* Expose NoCollide and NoCollideThisOnly as virtual variables for submodels
* Allow submodels to be optionally specified in object:checkRayCollision
* Be sure to calculate ship-to-ship hit position before the override collision hook is called, in case the hook needs this value. (The other collision hooks already calculate the hit position before the override hook.)
- Set app name properly per Apple docs
- Use correct "FreeSpace Open" name
- Set version properly per Apple docs
- Add bundle identifier
- Update copyright date
- Remove localized strings since they are all English already
A design choice very early in FSO's scripting development established that invalid results return invalid objects. By using a game_settings.tbl flag, this allows invalid results to return nil instead.
* Fix CTD with HUD Preset Switching
After #5302 it was discoved that pressing the `Next` button in the HUD presets would cause a CTD.
Thanks for Lafiel for figuring this out
`If HC_current_file is HC_preset_filenames.size() - 1, then it'll oob on a vector access.`
Testing this PR fixes that crash.
* use static cast
* add extra ways to modify background elements in missions
This adds Lua API methods for getting suns and bitaps by index, as well as modifying their scale and position. This removes the need to completely add and remove a background element that only needs to be modified.
* big pruning of (int) casts
* Add control_info driver sources
* Properly deal with cockpits and their 'objnum's
* Add driven animation sets to weapons and cockpits
* enumify objnums
Several handle types in the scripting API used inheritance where composition would be more appropriate. This refactors those types, as well as removing the various handle types that were just aliases for `model_h`. These are just the C++-side types; all the Lua types remain as-is.
This also refactors `sound_h` to move the previous `isSoundValid` to `isValid` so that `ade_set_args` will work properly for sounds with the `Lua_API_returns_nil_instead_of_invalid_object` flag. The subclassing from `sound_entry_h` was removed and the "full validity check" was moved to `isValidWithEntry`. The Lua side remains unaffected, but additional documentation was added to clarify the usage.
Follow-up to #6009 and prerequisite to #6006 due to the `isValid` refactor for `sound_h`.
There was confusion in the lighting code between light indexes and sun indexes. These are usually the same, but not always. This makes several changes to fix light/sun handling.
1. Clarify the distinction between lights and suns and add a `sun_index` field
2. Add a flags field and assign the `dual_cone` boolean to it, as well as a new glare flag
3. Determine light glare by checking the light flag, not the sun (which never worked in the first place as the `stars_sun_has_glare` function checked bitmaps rather than suns)
* Create the ingame options game state
* Base working version of in-game options
* Cleanup + Optimization
* Localization pass
* more cleanup + documentation
* tooltips on option hover
* documentation and better inbounds check
* match case
* format strings instead of direct strings
* unused parameter
* address feedback
* localization id conflict with master
* Add this line back in
* pass the new option flags as well
* resolve xstr id conflict
There was an extra check during ship class parsing that prevented a ship class's type from being set if it had been set already. This dates back to commit 5f3a6ec7 and was added as a parsing safeguard rather than as part of any modular table checks. Since the parsing has changed, this extra check is no longer applicable. Removing the check allows a ship class with a different type to be created using an existing ship class as a template.
This rather insidious FRED bug was all down to an improper check for the current ship. It is possible for multiple objects of different types to be selected at the same time. If, for example, a waypoint and ship are selected, and the waypoint was selected first, the waypoint will be what `cur_object_index` refers to. Since the ship is the one and only ship selected, it will be what `single_ship` refers to. Therefore, to avoid flagging its own ship name as a duplicate, the loop should exclude the single ship, not the current object.
The bug can be reliably triggered by selecting a waypoint, then adding a ship to the selection, then switching the focus to another application and back to FRED. This finally squashes the bug.
This improves the ability of Lua to check for ship arrival status:
1. Deprecates the `isWarpingIn` function, which can be misleading, and replaces it with the equivalent `isWarpingStage1`
2. Adds an `isWarpingStage2` function to fill a gap in functionality
3. Adds an `isArrivingWarp` function (complementing the existing `isDepartingWarp` function) to cover both stage 1 and stage 2
In #2464, a somewhat hard-to-understand equation involving taking the modulo of a random number was replaced with a function that would do those calculations instead. The problem is that the function performed the *entire* formula, while the code it replaced was only operating on the *difference* between the two numbers. Fortunately, this is as easy to fix as changing a `+=` into just an `=`.
There were a few instances of `Random::next()` being called without ensuring its arguments couldn't trip an assertion. This should hopefully catch them all.
Before this commit, `IFF_COLOR_SELECTION`, `IFF_COLOR_MESSAGE`, and `IFF_COLOR_TAGGED` were hardcoded indices into the `Iff_colors` vector. This could cause problems if any of these three colors were set to the same RGB values (since `iff_init_color()` doesn't create a new entry if the color already exists in the vector), and if a modular table tried to change any of these colors nothing would happen (since it would just create a new entry in `Iff_colors` without doing anything to the hardcoded indices).
This commit instead changes the `#define`s into `extern int`s, and assigns the return value of `iff_init_color()` to those global variables upon parsing the special color values, meaning that any combination of the three can be set to the same color without causing issues, and modular tables can actually modify them.
Potential clutter from unused values in the `Iff_colors` vector is basically unchanged (technically slightly worse if a modular table overrides any of these special colors with a color that doesn't already exist in the vector), but should maybe be looked at in the future.
The general expectation is that model filenames can be specified as 'none' or '<none>' for no model, but as discovered by no tea, this was not consistent across the code base. For example, `$Model File: none` was handled as expected but `$External Model File: none` was not. This PR makes the handling consistent for all ship, weapon, and shockwave POF files, and also adds some extra checks when models are loaded.
1. Fix the item ID indexing on the popup submenus and make sure they correspond with the ship dropdown menu
2. Remove the "player start" popup menu option as it has very limited utility and was already removed in qtFRED
3. Reduce a bunch of casts by using more appropriate popup menu types
4. Actually place an object in the mission when one is chosen from the popup menu
Also:
1. Remove the `Default_player_model` variable as its use is redundant
2. Remove unused arguments of `create_player()`
The result of this special parsing should produce a mod string identical
to the string passed on the command line with the following exceptions:
directory name case, directory separators
Should address the following:
- no fundamental difference in modlist compared to Windows
- no errors or warnings that are not produced on Windows
- do not remove mods from list if missing
- verify mod directory is accessible and actually a directory
- do minimum amount of work to see if mod directory is valid
- fix bug with trainling slashes
Old Volition bug where the original directory is pushed onto a stack
before the chdir() call. If that call fails then the stack is left with
a used entry that won't be removed until restart and can cause the stack
to fill up. Now it's added only if the chdir() call succeeds.
Also take the opportunity to make Cfile_stack dynamic.
Change the casts used in the convenience #defines in floating.h. Since these #defines are used pretty widely, this should reduce the count of C-style casts in the codebase by quite a bit.
Also change the casts in floating.cpp while we're at it, and remove some obsolete or unused code.
Make sure all medal fields are properly assigned. In particular, if a modular -mdl.tbm is parsed, don't overwrite information from the base medals.tbl. Fixes a bug reported in Discord.
This fixes command briefing data apparently disappearing. The ui was not being properly initialized because model_changed was being called before the ui was initialized, leading to default values.
This also fixes a few other minor issues.
In #5649 / b6c0e8b, the ship registry was updated to take ship death rolls into account. There was one small wrinkle that it did not account for, however: SEXP operators that return numeric values had previously (i.e. before the introduction of the ship registry) checked the mission log for ship destruction, but after #5649 the EXITED status was not set until after the ship had completely exploded, resulting in certain SEXPs having their conditions slightly modified. The equivalent of checking the mission log for ship destruction is now checking the ship status for DEATH_ROLL, so it is necessary to make that change for the numeric SEXPs to behave as they did before.
The motivating result for all this is to fix SEXPs like `hits-left` firing after a ship has been destroyed but before it has finished exploding. This can be seen by loading the first non-training mission of FSPort and comparing the messages that are sent if you use cheats to kill Alpha 2.
SEXP helps should let the FREDder know whether a given ship argument
needs to be already in-mission for the SEXPression to operate. Update
the helps to include (ship needs to be in-mission) or (ship does not
need to be in-mission) or other relevant helpful information.
Check the filenames used to initialize HUD gauges and mark the gauge as hi-res if the filename starts with 2_. Also add a script method to return this value.
Additionally, make accessor methods `const`.
Since its creation, the `is-in-mission` sexp operator has only checked for ships. But mission designers might assume this also works for wings, leading to a situation where the sexp always returns false because no ship can have the same name as a wing. Fortunately wing functionality can be added to this sexp without affecting ship functionality.
This fixes a few items that were revealed in the course of Dark Visor's SEXP documentation PR. The EXITED status should return NAN_FOREVER, not just NAN. The CANT_EVAL value is never returned from the sexp on account of ship status, due to the preceding check, and is not an appropriate return value anyway; so that is removed. Finally, for a ship that can't move, the NAN return value is better than CANT_EVAL, since it represents the numeric situation more accurately and can also be checked by `is-nan`.
This adds a new field to particle effects so that particle rotation can be configured on a per-type basis, not just on a blanket basis. Implements #5941.
As reported by Trivial Psychic, if the number of subsystems exceeds the max as the result of a modular table, the error message was very misleading. This fixes the error message and also makes it report the correct number of parsed subsystems.
`ai_get_weapon` is not guaranteed to return a valid `wip`, so check for that here. This should now cover all uses of `ai_get_weapon` in the codebase.
Fixes an Event Horizon crash reported in Discord. Follow-up to #5842, commit 8dbe0e7.
Apple Silicon Macs require that all code is signed in order to run. Our builds
are partially signed due to the SDL framework already being signed, so it is
seen as broken. To fix that we need to codesign all the rest of the necessary
files with an ad-hoc signature in order to allow the builds to work properly.
This is a new method of ensuring that OPF_POSITIVE numbers are positive. It works for all numeric arguments, including variables and literals, and caches the status of the node to avoid lookups for every negative number on every frame. Tested on both operator and non-operator cases.
Follow-up to #5915.
Operators that specify OPF_POSITIVE should be guaranteed to get positive numbers. This code was previously disabled for performance reasons, but following the contract of the SEXP system is more important. A future PR will improve the performance of the functions used here.
Also, the `num-players` operator takes no arguments, so fix that.
In consultation with @BMagnu, code that validates data in the POF file itself should happen in `read_model_file_no_subsys`, as virtual POFs rely on their source files having correct data. I've added comments and slightly rearranged things to make this clearer, and also moved the new code from `read_and_process_model_file`. Additionally, I fixed two bugs by changing `parent > pm->n_models` to `parent >= pm->n_models` and adding a newline to the `nprintf`.
After getting the main state from the Lua registry, this function had
two Lua thread values on its Lua stack but we only removed one which
lead to a value being left on the stack.
Why did this not blow up before? Because undefined behavior.
The only place where this was called was when creating a Lua reference
value where luaL_ref is called in the same expression (see
UniqueLuaReference::create). The evaluation order of the parameters for
the make_shared call is not defined by the standard and for some reason
all major compilers (except clang) choose to execute the luaL_ref call
before the getMainThread call.
For those compilers, everything is fine. We have some extra values on
the Lua stack but that gets cleaned up after the API function finishes.
However, clang first evaluates the getMainThread which leaves an extra
Lua thread on the Lua stack. The luaL_ref call then references this
thread value instead of the intended value. In the concrete case, this
meant that LuaFunction saw that the reference points to a thread and
rightfully threw an exception.
This fixes#5904.
Use a single canonical `frametime` value for all HUD rendering, in both `hud_render_preprocess` and `hud_render_all`. Previously, certain functions called through `hud_render_preprocess` were using the full frametime, rather than the half frametime needed for VR when the HUD is rendered twice.
Fixes#5882.
Use a simpler, more robust, and more correct method of sharing the fire direction among beams: replicate the actual beam vector for all firing points. This further cleans up and simplifies the beam firing code and also clarifies some vector math.
1. make `check_ok_to_fire` return a boolean (like `check_los`)
2. make `check_ok_to_fire` and `check_los` both use a position argument since we don't need the whole turret
3. remove the redundant position prediction code from `ship_get_global_turret_gun_info` (since that needs to be a "pure" function) while making sure "share fire direction" still works
4. skip calculation of the vector in `ship_get_global_turret_gun_info` if we don't need it
5. move the position prediction code out of `aifft_rotate_turret` and into its own function
6. prune some gun position calculation calls since in most cases one will suffice
7. fix position "jitter" with weapon subsystem damage in missions that use gravity
8. `model_rotate_gun` now uses a nullptr position for a reset instead of an extra boolean argument
9. use a more efficient method to calculate gun barrel length
10. a couple variable name changes for clarity
1. Allow a `+` to appear in front of numbers, just as with `-`
2. Check for `.` and `,` within numbers to give a less misleading error message than "not a number"
3. The old number hack inadvertently skipped numeric literals, so specifically check for those
There are several SEXP argument types that themselves encompass multiple argument types: for example, ships and wings. This could be misleading when there is an error message displayed. So, this updates the error codes to explicitly cover all of the possibilities.
By using app image and switching to Checkout V1.
Also removes Vulkan SDK install, since it seems to be taken care of by the app image or is disabled. I can't figure it out from the app images.
This limit has not been bumped since the original public source release. The final mission in Shepherds has been experiencing mysterious bugs which were finally tracked down to the mission log overflowing its limit and discarding log entries. Ideally the mission log should be made dynamic and the pruning mechanisms removed, but for the 24.0 release, it suffices to bump the limit.
Volition used a bit of juggling when deleting the briefing editor pointer. Turns out this actually prevents a crash in certain situations, so let's put it back.
Follow-up to #5866.
This refactors the ship registry and the OSWPT struct to store data as indexes rather than pointers. This is a prerequisite for making these collections dynamic in the future. See also #5800.
* Reorganized opengl deferred light mesh drawing to submit all data before,
beginning to submit draws, and also to reduce total bind calls needed.
* Leftover unused variable cleanup
* CI didn't like my loops, maybe it'll like these.
* unused variable cleanup.
FRED has an autosave feature but it wasn't invoked in too many places. This adds autosaving whenever a major dialog is closed, unless it was closed by hitting Cancel. NB: Autosave is not yet implemented in qtFRED.
Also, `addvariabledlg` incorrectly referred to `OnOk` instead of `OnOK` and `CMessageEditorDlg` incorrectly referred to `OnOK` instead of `OnOk`, so this fixes those and distinguishes `OnOk` by renaming it `OnButtonOk` to be consistent with the event editor and other dialogs.
Calling `query_node_argument_type()` on a node with no parent is a valid use case, so return the proper argument type. Fixes a crash discovered by Applemush.
Ever since retail, the code has assumed that a soundtrack would always have arrival music. This removes that requirement. If arrival music is missing, it will just be skipped.
These variables are only ever used in the scope of `os_get_legacy_user_dir()`, so they can be scoped rather than global. This should fix a Coverity issue on the `DCF(low_mem` debug console function.
Adds a SEXP that specifically checks for whether a player has skipped a mission. This can be used to set tech room entries, allowed ships/weapons, and other campaign data that would otherwise break if a player skipped a mission.
This only applies to the the failed-five-times popup. For this to work with the `skipmemymissionyo` cheat, it would be necessary to load every intervening mission and check the events. That being said, `skipmemymissionyo` already automatically allows all ships and weapons, so there is much less, if any, need for this SEXP in that case.
An arm64 mac can run unittests on a x86_64 build, but not the other way
around. So if the target arch doesn't match the build host arch then
just skip the tests. Saves us from a far more complicated fix that would
only produce the same test results anyway.
Back in 2008 (in commit 2c45dbbb5f), some retail code incrementing `Player->failures_this_session` was removed, seemingly by accident. A month later, a bug related to this was fixed (in commit 28a408deee) in a different way. Since this fix is rendered redundant by the restoration of the original behavior, I've removed it and put back in the old behavior. This is only "mostly-retail" because the retail code didn't check `Game_mode & GM_CAMPAIGN_MODE`.
Qt has been added to the build image which eliminates the need to
dynamically install it which removed a possible point of failure.
At the moment this is only enabled for pull request builds and should
not affect nightly or release builds.
The previous version of the image accidentally removed the /tmp
directory which broke things in the GitHub actions.
Initially, an update for the upload/download actions was tried which had
no effect but keeping these updated is probably a good idea.
These new SEXP operators clear all status information from an event or goal, making it as if the event or goal had never been evaluated.
Implements feature discussed in #4184.
The requirement for delayed event status checks to be strictly greater than the event fired timestamp (see commit eed50619ca / PR #5267) means that `is-event-true-delay 0` will not work in debriefings if the event becomes true and the debriefing SEXPs are evaluated on the exact same timestamp. Normally this is not a problem, but one important exception is the `end-mission` operator which instantly sends the player to debriefing.
This timestamp behavior is working as designed and should be consistent as long as the `end-mission` operator has been around (I've verified it as far back as 3.7.4). But it does lead to inconvenient situations where the event that called `end-mission` cannot be evaluated by the debriefing. This makes it slightly more complicated to plan debriefing stages based on these events.
Therefore, it makes sense to add an exception to the event status function to ignore the delay if the evaluation is not in-mission. This is consistent with evaluating events that *never* fired and also satisfies the principle of least astonishment for mission designers.
This also adds relevant documentation to the event and goal status operators.
* SCPUI in-game language selector
* xstr support
* proper debug print format
* minor fixes
* Save the language as json data rather than an index into the languages array
* ext instead of id for clarity
* Do this more formally
* unused param
This advances the versions for Clang to 16 and GCC to 13 along with
fixing any warnings these new versions are detecting now.
The new image versions also include Vulkan so the additional workflow
step for installing that is not necessary anymore.
The overlapping checkboxes problem described in #5494 is the result of the checkbox list item height being slightly too small. A fix for this, which requires a subclass of `CCheckListBox`, is described in the following StackOverflow article:
https://stackoverflow.com/questions/3147958/mfc-cchecklistbox-items-overlap
It turns out there is already a subclass of `CCheckListBox` in the codebase: `ShipCheckListBox`, a class that was apparently left on the cutting room floor when DaveB refactored the team loadout dialog on 2/23/99. It allows an entire selected range of items to be toggled by pressing the spacebar. I've augmented it with the StackOverflow fix, and I've added it to the team loadout dialog as well as some other places that could benefit from it.
Fixes the other half of #5494.
We need to call `UpdateData()` in the `OnOK()` function and in several other places so that the member variables are populated with the most recent input from the UI. This prevents certain input (such as Player Entry Delay changes) from being lost by being overwritten with stale stored values.
This fixes a bug reported by Kitsune where the Player Entry Delay box did not work properly. It also fixes the random checkbox issue from #5494.
One of the features requested in #5378 (specifically the one requested in #5274), this adds a new "$Contrails use absolute speed:" option to game_settings.tbl, which makes the `ct_below_limit()` function check `objp->phys_info.speed` instead of `objp->phys_info.fspeed`. This allows contrails to appear when moving in a direction other than forwards.
This option was misleadingly named when originally introduced, so give it a more sensible name. The old name is still accepted for backwards compatibility.
* Allow Modders to Set Rotational Scaling Multiplier for Asteroids/Debris
Previously, there was no way to limit the velocity at which asteroids/debris randomly rotated. There was a way to set maximum speed, thus this PR follows that convention and adds a way to cap the rotational velocity scaling. This PR allows modders to set caps per type, including setting the value to 0 for no rotation.
A single scaling value was used b/c it was the most straightforward value to se via table and it was the employed the least code changes. Asteroids pick a random normalized vector for their rotation when spawning, and then that value is scaled by a random multiplier.
* use full multiplier instead
Convert additional timestamps to use the new timestamp system. This covers all timestamps referred to in freespace.cpp. For purposes of organization, the fade-in/fade-out timestamps have been moved to light.h|cpp and the training timestamps have been moved to missiontraining.h|cpp.
There are also several related code enhancements:
1. `FadeType` has been converted from `enum` to `enum class`
2. Initialization of the various training variables has been added to `training_mission_init` (previously they had never been reset between missions)
3. Validity checks have been added to the relevant locations for these timestamps
1. Use the `optional_string_fred`/`fout` pattern so the FRED comment parser can follow along with the mission file
2. Since the #Custom Data section is optional and requires a version bump, don't output the section header if the section is empty
* Add global to local for matrices
* Add lua integration
* Get Submodel from Submodel instance
* Add submodel functions
* Add model instance from submodel instance
* Fix index
* Fix copy paste error
Here's some low-hanging fruit for reducing the memory footprint of `ship_info`. This turns the maneuvering thrusters array into a vector, refactors the names a bit, fixes thruster activation when `-nosound` is active, reduces the number of calls to `ship_get_thruster_status`, adds some const-correctness, and converts the timestamps to the new system.
Previously (since 2012!) a waypoint would store its parent list as a pointer. However, this pointer can become invalidated if the waypoint list vector is resized. To prevent this, store the parent list as an index.
This also renames the waypoint's `objnum` field to `m_objnum` to match the naming of the other fields.
1. use `SIZE_T_ARG` instead of `"%lu"`; should fix format warning in #5780
2. since `HeapAllocator::checkRangesMerged()` has no effect unless running in debug, `#ifdef` out the function; should fix CI warning in #5778
Some patches for mission imports:
1. Check that the path isn't empty (the user didn't select "This PC") before continuing
2. Count successful imports
3. Avoid treating an import as a newly saved single mission unless the import was successful
In many calls to `ship_get_subsystem_strength`, the caller doesn't care about the actual number, just whether the subsystem type is destroyed. So this adds an optimization to check specifically for that. In the case of `SUBSYSTEM_ENGINE`, this avoids an iteration over every subsystem on the ship which, for a ship with many turrets, can be significant.
Some of the `frand_range` calls were used for integer calculations, so we can use `Random::next` now.
This also reduces the number of C-style casts in the codebase.
Add `const` to the `eval_enemy_obj_struct` struct so its values aren't inadvertently overwritten. Handle a bit of const-correctness propagation. Also add default member initialization to the struct.
One of the Voice Acting Manager dialog's strings is now too long for the .rc file and is truncated at 256 characters. Fortunately this can be worked around by setting it at runtime.
Add `const` to the `mc_info` struct so its values aren't inadvertently overwritten. Tweak some of the collision code to prevent overwrites.
Also remove the `flak_muzzle_flash` declaration since that function no longer exists.
1. Update soundtrack message to make it easier for modders to track down missing files
2. Update sexp help for ai-stay-near-ship to show the right argument count
In a few places where the game checks for the command sender, it should check for #Command as well, as long as the mission flag to override #Command is present.
Additionally, while the mission's command sender was originally intended to be a ship, it has been used to specify an alternative to #Command as well. But this caused problems when the "override #Command" mission flag was active, as it transformed a hashed source into a non-hashed source. So this commit adds a check to treat the source as hashed, if necessary, if a replacement has occurred.
Fixes#5749.
There is an implicit assumption in the code that the `MEF_DIRECTIVE_SPECIAL` flag could not be set on an event until after the `MEF_CURRENT` flag was also set. This change makes that assumption explicit, and also adds a check in `mission_process_event` to be sure the flag setting doesn't happen out of order. This situation is very rare, but can happen if the following conditions are true:
1. there is an event directive checking for the destruction of a wing
2. the wing has multiple waves
3. the directive uses the older `is-event-true-delay` technique to control when it is displayed
4. the directive becomes temporarily true before it can be displayed and while there are still waves remaining
This previously caused the "directive special" logic to occur before the "event current" logic occurred, skipping the proper setting of `born_on_date`.
Fixes Github #5725 and Mantis 930.
* Make sure we handle unknown location types
Avoids edge-case gargabe pointer 1522974
* Make sure local vectors are at least set to zero
For coverity 1522985
* Make sure from_table is initialized
When creating a replacement texture object, for coverity 1522989
* Change to Unreachable to help Linters
This was a false positive uninitialized scalar, Coverity 1523726. Hopefully, changing to UNREACHABLE() will help linters avoid this false positive in the future.
* Initialize xyw on this struct instantiation
For coverity 1523730
* Add early return for ade_set_args if error
For coverity 1523732
1. The player can target other object types besides ships, so when creating an `object_ship_wing_point_team`, make sure it is a ship
2. A few recent mission features require a version bump, but not all missions use these features; so do a "soft bump" where the mission version is updated only if necessary
3. Remove an unneeded #include by adding a `struct team_data` declaration (see #5599)
This is an actual edge case bug. If no countermeasure was set, and then one was set, there might be a garbage timestamp set that would give an incorrect countermeasure delay on next use.
For coverity 1093612, this function *should* never return zero, but it is no catastrophic if it does. Allowing it to return a negative value in some unknown edge case would allow it to clobber some other global data.
So now add a check for negative values and take no action if those negative values are reached. Assert on debug.
A mission in Mantle caused an invalid vector access when checking whether to vaporize a ship whose ship type was -1. Turns out having "no type" is actually allowed, so I audited all `class_type` accesses throughout the code for potential -1 accesses. Most were properly checked but a few were not. A few others needed to be tweaked.
(I suspect this is something that would be on the Coverity list if it isn't already.)
Yes. I know, I know, we're not going to use this code anymore. But just in case, I don't want this memory leak to have the possibility to exist in the future.
* Add Game Option to refresh selected weapon in loadout
This PR adds an option to always ensure the viewed weapon is one that can actually be on the selected ship when first clicking on the weapon loadout.
If you go to the loadout in the briefing and view the weapons on your ship, then go and change your ship class and go back to the weapon loadout screen, you will see that the weapon shown in the window on the right side is from your very first viewing before you changed your ship class. Displaying a weapon not allowed on a ship by default can be confusing to players, especially on mods like FotG where most ships have unique weapons.
The player can still of course click on a non-allowed weapon to view it, but with this PR the player will be initially shown a selected weapon that is allowed on the ship when opening the loadout editor.
Tested and works as expected.
* update order to be near weapon bools
The code has always checked a per-weapon-class value called `lock_fov` when comparing the dot product of a ship to its target to see if it can lock on to it, however the weapon table hasn't ever included a way to set this value; it's always the default value of 0.85. This just adds "+Lock FOV:" entries to aspect/javelin homing missile parsing after "+Seeker Strength:", which will set `lock_fov` as long as the supplied input is between 0 and 360 degrees.
These functions have not been called from what I can tell since the source code was released. But they did happen to trigger a clang warning, so it's time to get rid of them.
* Add stage notes feature for mission messages
* don't keep notes outside the mission editor
* use F_MULTITEXT and do lcl_replacements
* this should be multitext too
The fix in #5578 assumed that a previously playing soundtrack would properly set the timestamp, but if no soundtrack was previously played at all, this wouldn't happen. So if we deliberately don't play a soundtrack, be sure to set the timestamp as if `event_music_do_frame()` had been called.
Fixes#5705.
Occasionally, FRED can save a mission with a wing's ships out of order; this can happen if ships are deleted and FRED finds a free index in the middle of the ship list. This can cause benign but confusing mismatches in the ship registry, the hotkey list, and other places -- and it's also possible some mismatches may not be so benign, e.g. in multiplayer. Anyway, it's better for the ships to appear in the order the wing expects them, so this adds a routine to swap them around if necessary.
* nebula-fade-poofs
* Move this up because order of operations is important.
* Add some documentation
* Respect time compression
* Fix sexp description
* Make sure faded poofs do not flicker
* optimize
Fixes#3098. The `shipfx_eye_in_shadow` function did a collision check for cockpits, bit did not previously take into account of the viewpoint had a non-forward orientation (ie the player was using free look). This PR sets the collide check to take that into account with a 1 line fix. Tested with multiple FotG cockpits and fixes the issue.
* Add a divide by zero check
For coverity 1107324. Keeps framecount from dividing by zero in very rare circumstances.
* Add a clarifying comment
This marks isNaturalNumberFactor() so that we know it is the best way to get whether a number is a natural number.
Modulo division is slower and gives the same results.
* Spoiled by Rust
Before this change if the wrong endianness was used, the c style cast that was used here would lead to the argument being passed to getsockopt to lack the actual information.
Fixes coverity 1093482
(Directly cast to socklen_t)
Add "tactical" versions of disable and disarm goals which only perform the specific task without implying anything else. The target ship is not protected and attack goals are not cleared from other ships.
There is also a new AI profiles flag to make this the default hud squad message command instead of the classic disable/disarm.
The ai-fly-to-ship goal was added early in FSO's development but never worked right. Until recently it could crash; and even aside from the crash the AI would try to reach the target's exact position, causing repeated collisions. This folds ai-fly-to-ship into ai-stay-near-ship, since the behaviors are conceptually the same except for fly-to being satisfied as soon as the target is in range.
This also adds a new "escort" mode usable by both behaviors. The default Volition behavior is to swoop toward the target in a long, graceful arc; the new mode generates a goal point and flies directly to that point. These can be toggled via an optional sexp parameter.
There is also some minor cleanup and a new vec3d operator for convenience.
Needed for Scroll; depends on #5667.
If a ship is in the process of dying, it shouldn't be killed or self-destructed again. This fixes a bug noticed by RedMageJoe during the Derelict playthrough.
(This situation is distinct from a ship being hit while in the middle of its death roll. That shortens the death roll but does not try to kill the ship again.)
* Fixup HUD for slewing
* Fix Training Message box
* Lead indicator slew
* Fix HUD Message Head
* Correctly render messages
* Fix HUD offset handling
* HUD offset never makes any sense
* Cleanup offset code
* Remove unused parameter
* Fix Talking Head in RTT mode
Remove a whole bunch of ad-hoc code piled on top of the retail weapon cycling behavior, then replace it with a robust algorithm that takes all relevant attributes into account.
Fixes#5529.
Subsystem hitpoints are calculated as a percentage of the ship's hull strength as they are parsed. If a modular table modifies the ship's hull strength, the subsystems are not modified at the same time. This can lead to unreasonably large or small subsystem hitpoint values, as recently seen in the 1.3.0 version of Cardinal Spear.
This PR adds an option to defer hitpoint calculation until after parsing so that the subsystem is a percentage of the correct hull strength. Since this may affect the balance of existing mods, it is off by default unless the build targets 24.0 or later.
This also removes the long-unused `hull_percentage_of_hits` check and adds several log statements for significant options in game_settings.tbl.
Update the Lua enums to be consistent with the new ShipStatus enums.
Separately, add an extra ship registry check in the event a ship doesn't exist in the ship registry.
Use the same method for texture replacement in briefing popups that is already used in the tech room.
Also don't render shadows when the jump node is displayed, since it's not being lit anyway.
Normally the disabled/disarmed flags are only set if the destroyed subsystem is actually an engine or turret. This should be done for cheats as well, otherwise, for example, destroying any subsystem on a non-engined ship will cause it to become disabled.
There is a bit of code in missionparse that sets the parse object because in-game joining needs it. This is unrelated to ship status, so the status shouldn't be changed. This fixes the bug and adds a comment to clarify the situation, as well as some warnings to help track down incorrect joining states.
Fixes#5661. Follow-up to #5658 (where the regression was introduced) and #4836 (which fixed in-game joining).
The Star Fox barrel roll effect is achieved using a script which spawns a new ship. The script sets no-collide on this spawned ship, but it also tries to set the ship flag for all future ships -- and future ships require a parse object, which doesn't exist for a created ship. This patches the FALLTHROUGH in the sexp code to account for that possibility.
Separately, there are other ways a parse object pointer could become null through unusual code states, so this adds an INVALID status and several additional checks to defend against this crash in other circumstances.
The retail warp range multiplier can yield ridiculous results, like an Elysium warp being audible over 9000 meters away. So allow the multiplier to be set via ship type.
Adds a `DEATH_ROLL` status to specifically cover the state after ships have been destroyed but before they exit. I've also audited all code that interacts with the ship registry to use the correct state with this new state taken into consideration.
This fixes access to exploding ships that was broken when the ship registry framework was introduced. In particular, the `when destroyed X beam-lock-all X` QoL feature now works again.
CMake's copy_directory functions follow symlinks recursively as opposed to
preserving them. For mac frameworks, which make use of symlinks for versioning,
this causes the files to be duplicated multiple times in the copied framework.
Using rsync instead, just for frameworks, will properly duplicate the framework
while still avoiding the "file exists" error from cp.
Use GNU tar instead of the default bsdtar. This works around some weird
corruption bug triggered by the combination of the GitHub runner-VM, the llvm
linker, and bsdtar.
Adjust intermediate filenames such that they don't get uploaded to
indiegames by mistake.
Unpack builds as a single step instead of two.
If consecutive red-alert missions have different numbers of ships in a wing, then calculating the number of waves will not be correct. This necessitates the addition of wing status to the stored data for red-alert sequences.
Not only must wing data be stored in `Red_alert_wing_status`, but also in the CSG file. This necessitates a version bump. Fortunately, the current design of CSG files allows extra data to be added to a section without breaking old builds, since the CSG loader will just skip over the unrecognized data.
This also renames `red_alert_wingman_status` to `red_alert_ship_status` since it's not limited to wingmen, as well as fixing the omission of exited ships if they are in the player's wing but don't have the red-alert-carry flag.
Fixes#5637. Follow-up to #4457 and #5609.
Add some extra logic implied by the `Begun_detonation` flag. Missiles that are homing can have their targets, headings, speeds, and lifetimes changed for various reasons. If a missile has begun detonation, particularly if it is in "detonation limbo" because it is flying across a bowl-shaped turret, we don't want to change any of that. The "detonation limbo" weapon lifetime is only accurate if all of those values remain constant.
Follow up to #4006.
In #5477, I made the escort list respect hidden names by copying the behavior from `message_queue_process()`, which already checked those flags; however, this resulted in some dramatic behavioral changes for mods using callsigns for escort ships, and while making the behavior optional was a possibility, feedback suggested everyone would rather it just behaved like the target box and displayed both. So I replaced the code with similar logic from hudtargetbox.cpp, except with the "replace hidden name with ship class" code taking priority.
- handle double archiving of macOS builds so they'll work properly with Knossos
- fix issue where only a single configuration was included in the package
(Release or FastDebug, not both)
Statically link to libstdc++ for CI/CD builds in an attempt
to avoid compatibility issues without relying on a crippled
docker build image.
Should properly fix#5571
1. Allow setting the homing subsystem if the homing object has already been set
2. Use the `weapon_set_tracking_info` function if setting both object and subsystem, as it handles several important homing things
The `collides` and `no_collide` flags are equivalent, but opposite. So when sexps or scripts get or set those flags, allow each to be used as an anti-synonym (not exactly an antonym) for the other.
Two fixes for red alert missions:
1. Since any ship in the wing can be stored, not just the wing leader, the "prospective name" check should check for all possible names in each wave
2. If a wing wasn't actually stored, the red alert code should not reset the wing's wave number to 0
Follow-up to #4457.
Since `gr_string` can accept a length parameter, there's no need to copy each line before it is drawn.
Related to #5495 but not one of the two options mentioned.
The `Random::next(low, high)` function returns a value in [low, high]. This location should use the single-argument version, `Random::next(int modulus)`, which returns a value in [0, modulus-1].
As reported by Colt, there was a crash in the in-mission jump sequence in Shepherds where the mission previously worked. The proximate cause was a handwritten SEXP called via script that omitted whitespace before an opening parenthesis. This was incorrectly recognized by the upgraded SEXP parser as an invalid SEXP. Unfortunately, a separate bug in `get_line_num()` caused a crash when the parser tried to display a warning, because the function tried to calculate the line number of a SEXP that did not come from a parsed file.
This commit fixes the parser to recognize opening parentheses even when no whitespace precedes them, moves the output to the 'unexpected end of sexp' warnings will they will now be seen, and fixes `get_line_num()` to work when there is no parsed text.
Follow-up to #5520.
For certain calculations involving armor, the `GetDamage` function needs to know if the damage is being applied by a beam so it can apply the calculations with the proper frametime. The parameter was not provided in all cases, so this fixes that.
Follow-up to #1609.
1. Add a `vanish()` function for beam objects, to be consistent with other object types
2. Add a `BeamFree` virtvar, analogous to `TurretLocked`
3. Add timestamp variants of TurretLocked and BeamFree to be consistent with sexps
4. Add `BeamLife`, `BeamWarmup`, and `BeamWarmdown` virtvars so scripts can access table properties
5. Add "On Beam Death", "On Beam Warmup", and "On Beam Warmdown" hooks
6. Clarify some existing documentation and patch a couple things
The firing point gauge did not work as advertised; this fixes it. Unselected weapons are dimmed, selected weapons are normal, and firing weapons are bright.
This adds several fixes to make the event and menu music more robust:
1. The game will now run with zero soundtracks. All accesses into a potentially empty vector should now have checks.
2. Soundtracks and menu music are now checked for validity before being played (not just when importing a FSM mission).
3. The parsing validity checks and the in-game event music now check for skippable patterns using the same function.
4. Zero measures and zero samples-per-measure now cause the game to skip a pattern. Negative values now trigger a warning.
5. Omitting some or all of the `$Name:` lines for a soundtrack will not cause an assert.
Fixes#5576. Follow-up to #5572.
There is a built-in delay for the event music to start playing, but this delay gets stepped on if `change-soundtrack` is called when the mission first starts. So don't set the delay unless it has already elapsed at least once before.
When a non-looping persistent sound expires, `obj_snd_stop()` actually does need to be called. Even though the sound is no longer playing, the `Num_obj_sounds_playing` tally needs to be decremented, otherwise it will eventually exceed its limit and prevent any additional persistent sounds from playing. And it turns out `obj_snd_stop()` returns gracefully for sounds that aren't playing.
Follow-up to #3510. Fixes a bug that appears to have been around since retail.
The `mn.createWeapon()` function takes an optional group ID for weapons that share lighting, but the internal `weapon_create_group_id()` function was never exposed to the API. This adds that.
Since event music soundtracks use the exact file extension specified (see #5567), the validity check should also use the exact file extension specified.
Also, move the validity check to after parsing has completed because extensions may be overridden.
Currently, menu music will trim the extension and look for both OGG and WAV files, but event music will use the exact extension specified. This is intended but could lead to unexpected results in mods, so display a warning for the modder.
The crash in #5514 appears to be caused by some of the graphics code not being in the expected state for the synchronization. Looking at the code in `render_frame()`, a `gr_flip()` happens after one frame ends and before the next frame begins. That implies that this `gr_flip()` should not be here, as it is in the middle of a frame. For additional evidence, `gr_flip()` modifies the "uniform buffer manager" state, and that is part of the stack trace preceding the crash. Removing this `gr_flip()` fixes the crash.
The strange thing is that this code *doesn't run at all* while the campaign editor is active. I verified this by adding a MessageBox in place of `gr_flip()`; the MessageBox doesn't display until the campaign editor is exited. And yet, FRED crashes with `gr_flip()` present and doesn't crash with it removed. This calls for a new category of bug; I propose "spookybug", from spooky action-at-a-distance.
Fixes#5514.
The default movie subtitle font is font01.vf, but mods with custom font tables might not use this font. So this changes the handling slightly so that the movie player will use whatever the first available font is.
Follow-up to #1523. Fixes a sometimes spurious warning in mod initialization.
Supercaps use a physics flag on warpin that makes them slow down faster than they would under the normal physics code. This adds that flag as an option for custom warp parameters.
Since flags are not yet parsed when warp parameters are parsed, the code needs to skip ahead and peek at the flags in the same way as the weapon override.
1. Fall back to the FREDzone help docs if the local files cannot be found
2. Tweak url_launch error message and add a return value
This consequently removes the ReleaseWarning which wasn't the friendliest or clearest way to tell the user about a missing help file.
Since other functions in the scripting API remove extensions before loading the files, and since the internal functions expect them to be removed, the streaming anim API should handle that too.
As reported by Woutersmits, the GTT Nova did not dock with the GTD Hall in the first mission of Black Horizon. Attempting to run a debug build caused a CTD. Investigation showed that there was an invalid dockpoint triggering an Int3(). The dockpoint has been fixed, but to aid troubleshooting in the future, the Int3()'s in this function have been changed to more appropriate functions.
When weapon flags are parsed in a modular table and override the previous set of flags, certain flags must be kept to preserve the behavior of the weapon. The previous `preset_wi_flags` technique only worked if all such flags (homing, has-display-name, even whether the weapon turns) were set in the same modular table. If a modular table overrode the flags but didn't specify those lines over again, mysterious and subtle bugs would occur.
This modifies the flag parsing to explicitly preserve all appropriate flags from the existing weapon entry, which fixes the bug. It also allows all of the flags to be specified in one place, rather than scattering `preset_wi_flags` assignments throughout `parse_weapon`. And this also adds quite a few flags to the flag list that were not handled at all under the previous design.
Finally this fixes a few incorrect assignments of default values to fields that should only happen the first time a weapon entry is parsed.
Three fixes:
1. In commit fa0878b6b3 for PR #5338, the optional distance parameter was inadvertently changed to a bool. This fixes the parameter.
2. The distance parameter was previously parsed using `atoi` which works for number literals, so change to `eval_num` to allow sexp return values.
3. Make `eval_num` consistent with `eval_sexp` in the sense that evaluating an empty list is valid and returns false or 0.
Also takes advantage of the fact that `is_sexp_true` works for empty lists to streamline optional arguments in `ai_add_goal_sub_sexp`.
Copying a file with cp on top of another one is not allowed by default
so switching the command to use the CMake provided one will fix the
issue and will also unify the commands for all platforms.
The directory support is necessary for Mac where the SDL library is
actually a directory.
For mods which want primary weapons to 'detonate', setting the detonation range is not reliable because, due to rounding imprecision, either the range (which detonates) or the lifetime (which does not) may happen first. So this adds a flag to always detonate a weapon when its lifetime expires. Secondary weapons have this flag by default, but primary weapons can add this flag in the $Flags list. Additionally, if the detonation range and the predicted range due to lifetime are equal, the flag is added automatically.
Resolves#5521.
In #4702 this log line was changed to the 'Model' category, which made it hidden by default. This was missed in review but should be restored as it is a fairly important line.
Fixes#5507.
The hud-set-coords SEXP has always used exact pixels, without regard for the current screen resolution. This adds a similar scaling mechanism as is used for show-subtitle.
Fixes#5525.
When using the mission importer, missions were being corrupted for very subtle reasons: due to some code reordering in prior commits, `raw_ptr` would be initialized to `Parse_text_raw` before `Parse_text_raw` itself was initialized. This assignment was done in the `CFred_mission_save` constructor and the ordering dependency is not obvious. Since this is a highly fragile situation and has the potential to affect any use of `parse_comments()` in FRED, it's better to explicitly assign `raw_ptr` when it is needed, and just initialize it to nullptr in the constructor.
This also sets the version number to the legacy version (0.10) when the mission is saved in the retail format.
Modelread.cpp supports POF versions as low as 1900, but early model versions were not loaded properly because they relied on preprocessor directives rather than version checks. This changes the POF loading to correctly check version numbers and chunk IDs.
Fixes crashes when attempting to load a FS1 model.
1. When saving a campaign, the save directory should be the one that the campaign was just loaded from. If prompting the user, this should be the default save directory. This fixes a bug where campaigns were saved to %APPDATA% instead of where the FREDder might expect. This has been a bug ever since the migration of the game files from FreeSpace2 to %APPDATA%.
2. When saving a campaign, save only the external mission flags, not the working flags that are maintained during gameplay but have no meaning in the saved file.
* In fillValues(), Check the size values returned by SDL to assert they are non-negative. If they are negative, abort vector resize and mprintf the SDL Error.
See title. There were some cascade effects, but the changes are mostly contained to the model code. The calls to `gr_render_model` and `g3_render_primitives` use `const_cast` because constifying that API would require a whole other PR.
- key: 'performance-move-const-arg.CheckTriviallyCopyableMove' # This isn't actually performance relevant, but using move on trivially copyable types can well indicate that the variable should not be used anymore, such as when passing a builder type to the finialization function
message(STATUS"Using ccache for C compilation: ${CCACHE_PROGRAM}")
SET(CMAKE_C_COMPILER_LAUNCHER${CCACHE_PROGRAM})
endif()
if(NOTCMAKE_CXX_COMPILER_LAUNCHER)
message(STATUS"Using ccache for C++ compilation: ${CCACHE_PROGRAM}")
SET(CMAKE_CXX_COMPILER_LAUNCHER${CCACHE_PROGRAM})
endif()
if(ANDROID)
message(STATUS"Building for Android (NDK)")
set(FSO_BUILD_INCLUDED_LIBSONCACHEBOOL""FORCE)
set(USING_PREBUILT_LIBSONCACHEBOOL""FORCE)
set(SDL3_USE_PRECOMPILEDONCACHEBOOL""FORCE)
set(OPENAL_USE_PRECOMPILEDONCACHEBOOL""FORCE)
set(USING_PREBUILT_VULKANONCACHEBOOL""FORCE)
endif()
IF(CMAKE_CROSSCOMPILING)
SET(IMPORT_EXE_DIR"IMPORT_EXE_DIR-NOTFOUND"CACHEFILEPATH"Required for a cross compiling build, point to binary directory of a cmake build for the real OS")
@@ -107,10 +118,8 @@ OPTION(FSO_BUILD_TESTS "Build unit tests" OFF)
OPTION(FSO_DEVELOPMENT_MODE"Generate binaries in development mode, only use if you know what you're doing!"OFF)
OPTION(FSO_BUILD_QTFRED"Build qtFRED2 binary"OFF)
IF(WIN32ORAPPLE)
# On windows and mac the default should be to always build the included libraries
IF(WIN32ORAPPLEORANDROID)
# On windows, mac and android the default should be to always build the included libraries
SET(FSO_BUILD_INCLUDED_LIBS_DEFAULTON)
ELSE()
SET(FSO_BUILD_INCLUDED_LIBS_DEFAULTOFF)
@@ -124,22 +133,52 @@ OPTION(FSO_USE_OPENALSOFT "Download and build OpenAL Soft instead of using the s
OPTION(FSO_FATAL_WARNINGS"Determines if warnings in the build are considered fatal errors, primarily used for CI"OFF)
SET(FSO_FREESPACE_PATH"${CMAKE_INSTALL_PREFIX}"CACHEFILEPATH"The path of the FreeSpace directory you want to use. Please note that you will have to change CMAKE_INSTALL_PREFIX if you change this at some point.")
SET(FSO_FREESPACE_PATH"${CMAKE_INSTALL_PREFIX}"CACHEPATH"The path of the FreeSpace directory you want to use. Please note that you will have to change CMAKE_INSTALL_PREFIX if you change this at some point.")
SET(FSO_RUN_ARGUMENTS""CACHESTRING"Additional arguments passed to a generated executable when run with the generated build files.")
option(FSO_INSTALL_DEBUG_FILES"Install some debug files (currently only PDB files on windows)"OFF)
option(ENABLE_COTIRE"Enable cotire for faster compilation. Enabled by default."ON)
option(FSO_RELEASE_LOGGING"Enable logging output for release builds"OFF)
OPTION(FSO_BUILD_WITH_FFMPEG"Enable the usage of FFmpeg for sound and custscenes"ON)
OPTION(FSO_BUILD_WITH_DISCORD"Build with Discord support"ON)
OPTION(FSO_BUILD_WITH_OPENGL"Enable compilation of the OpenGL renderer"ON)
OPTION(FSO_BUILD_WITH_OPENGL_DEBUG"Enables debug option for OpenGL"OFF)
OPTION(FSO_BUILD_WITH_OPENGL_ES"When building OpenGL, use OpenGL ES compatibility layer"OFF)
OPTION(FSO_BUILD_WITH_VULKAN"Enable compilation of the Vulkan renderer"OFF)
OPTION(FSO_BUILD_WITH_VULKAN"Enable compilation of the Vulkan renderer"ON)
Deprecations are a mechanism in FSO where a certain feature or aspect of the engine has changed or is no longer supported. Since this would normally break existing mods we have the mod table feature "[tt]$Target Version:[/tt]" with which a mod can specify what version of FSO it was developed with. The features listed above will be removed or changed when the target version of a mod is at least the version released in this post.
Deprecations are a mechanism in FSO where a certain feature or aspect of the engine has changed or is no longer supported. Since this would normally break existing mods, we have the mod table feature "[tt]$Target Version:[/tt]" with which a mod can specify what version of FSO it was developed with. Any features listed under Deprecations will be removed or changed when the target version of a mod is at least the version released in this post.
[b]All platforms: [/b] For every day use, we recommend [url=https://www.hard-light.net/forums/index.php?topic=94068.0]Knossos[/url], an integrated solution for downloading and launching mods.
[b]All platforms: [/b] For every day use, we recommend [url=https://knossosnet.github.io/Knossos-Release-Page/]Knossos.NET[/url], an integrated solution for downloading and launching mods.
[hidden=Alternative Launchers]
Cross-platform: [url=https://www.hard-light.net/forums/index.php?topic=89162]wxLauncher 0.12.x Test Build[/url] (ongoing project for a unified launcher, you should upgrade to the latest RC/test build if you have not yet)
Cross-platform: [url=https://www.hard-light.net/forums/index.php?topic=89162]wxLauncher 0.12.x Test Build[/url] (legacy project for a unified launcher)
[b]Important:[/b] For best compatibility with FSO 3.8 and later you should use at least wxLauncher 0.12.
Windows: [url=http://scp.fsmods.net/builds/Launcher55g.zip]Launcher 5.5g[/url] ([url=http://scp.indiegames.us/builds/Launcher55g.zip]Mirror[/url]) ([url=https://www.mediafire.com/?wdvzn7hhhzh418m]Mirror[/url]) Not compatible with Windows 8+, use wxLauncher above
Windows: [url=http://scp.fsmods.net/builds/Launcher55g.zip]Launcher 5.5g[/url] ([url=https://scp.indiegames.us/builds/Launcher55g.zip]Mirror[/url]) ([url=https://www.mediafire.com/?wdvzn7hhhzh418m]Mirror[/url]) Not compatible with Windows 8+, use wxLauncher above
OS X: Soulstorm's [url=https://www.hard-light.net/forums/index.php/topic,51391.0.html]OS X Launcher 3.0[/url]
Linux: [url=https://www.hard-light.net/forums/index.php/topic,53206.0.html]YAL[/url] or [url=https://www.hard-light.net/wiki/index.php/Fs2_open_on_Linux/Graphics_Settings]by hand[/url] or whatever you can figure out.[/hidden]
[b]What are those SSE, SSE2 and AVX builds I keep seeing everywhere?[/b]
[url=https://www.hard-light.net/forums/index.php?topic=65628.0]Your answer is in this topic.[/url]
Don't want to deal with that? Use [url=https://www.hard-light.net/forums/index.php?topic=94068.0]Knossos[/url] and it will download the best build specifically for your PC!
Don't want to deal with that? Use [url=https://knossosnet.github.io/Knossos-Release-Page/]Knossos.NET[/url] and it will download the best build specifically for your PC!
These builds use a mechanism called [url=https://appimage.org/]AppImage[/url] which should allow these builds to run on most Linux distributions. However, we recommend that you compile your own builds which will result in less issues.
Alternatively, if there is a package in your software repository then you should use that. If you are the maintainer of such a package for a distribution then let us know and we will include that here.
[b][color=red]Not available[/color][/b] We recently lost access to our Mac CI environment which we usually used for compiling these builds so for the time being, there will be no builds for this OS.
These builds are not signed and so by default will fail to launch. To run them simply right-click on the app, click open, then click open again on the security confirmation dialog. You should only have to do this once for each app.
If running the game through Knossos or Knossos.NET this step should not be necessary.
[size=8pt][color=red][b]NOTE:[/b][/color] macOS builds currently have limited support and may exhibit issues not present on other platforms.[/size]
[hidden=TrackIR Users]
[size=12pt]Important!![/size]
An external DLL is required for FSO to use TrackIR functions. The following DLL is simply unpacked in to your main FreeSpace2 root dir.
# Since the Travis CI people are not capable of enabling SSH/SCP support for their libcurl we need to build that manually...
# These commands are based on the tutorial from here: http://zeroset.mnim.org/2013/03/14/sftp-support-for-curl-in-ubuntu-12-10-quantal-quetzal-and-later/
SET(MSVC_SIMD_INSTRUCTIONS"${MSVC_DETECTED_SIMD_INSTRUCTIONS}"CACHEFILEPATH"The SIMD instructions which will be used, possible values are ${POSSIBLE_INSTUCTION_SETS}")
set(FORCED_NATIVE_SIMD_INSTRUCTIONSONCACHEBOOL"Override instruction set detection and compile with the maximum possible instructions for the current system.")
#define DOA_APPROACH 1 // Approach the current point on the path (aip->path_cur)
@@ -56,12 +57,6 @@ extern const int Num_ai_flag_names;
#define AIDO_DOCK_NOW 2 // Immediately move into dock position. For ships that start mission docked.
#define AIDO_UNDOCK 3 // Set goal of undocking with object.
// Submodes for seeking safety.
#define AISS_1 41 // Pick a spot to fly to.
#define AISS_2 42 // Flying to spot.
#define AISS_3 43 // Gotten near spot, fly about there.
#define AISS_1a 44 // Pick a new nearby spot because we are endangered, then go to AISS_2
// Flags to ai_turn_towards_vector().
#define AITTV_FAST (1<<0) // Turn fast, not slowed down based on skill level.
#define AITTV_VIA_SEXP (1<<1) // Goober5000 - via sexp
@@ -93,7 +88,7 @@ extern const int Num_ai_flag_names;
#define AIM_BAY_DEPART 18 // Departing to a fighter bay, following path to do so
#define AIM_SENTRYGUN 19 // AI mode for sentry guns only (floating turrets)
#define AIM_WARP_OUT 20 // Commence warp out sequence. Point in legal direction. Then call John's code.
#define AIM_FLY_TO_SHIP 21 // [Kazan] Fly to a ship, doesn't matter if it's hostile or friendly -- for Autopilot usage
#define AIM_FLY_TO_SHIP 21 // Rendezvous with a ship. Like stay-near, but non-perpetual.
#define AIM_LUA 22 // Generic Lua-based AI mode
#define MAX_AI_BEHAVIORS 23 // Number of AIM_xxxx types
@@ -102,6 +97,7 @@ extern const int Num_ai_flag_names;
#define MAX_ENEMY_DISTANCE 2500.0f // Maximum distance from which a ship will pursue an enemy.
#define MAX_AI_GOALS 5
#define AI_ACTIVE_GOAL_NONE -1
#define AI_ACTIVE_GOAL_DYNAMIC 999
typedefstructai_class{
@@ -186,6 +182,12 @@ typedef struct ai_class {
#define AIS_UNDOCK_3 33
#define AIS_UNDOCK_4 34
// Submodes for seeking safety.
#define AISS_1 41 // Pick a spot to fly to.
#define AISS_2 42 // Flying to spot.
#define AISS_3 43 // Gotten near spot, fly about there.
#define AISS_1a 44 // Pick a new nearby spot because we are endangered, then go to AISS_2. (Not implemented.)
// Submodes for Guard behavior
#define AIS_GUARD_PATROL 101
#define AIS_GUARD_ATTACK 102
@@ -240,7 +242,6 @@ typedef struct ai_info {
flagset<AI::AI_Flags>ai_flags;// Special flags for AI behavior.
intshipnum;// Ship using this slot, -1 means none.
intbehavior;// AI behavior; vestigial field from early development of FS1
intmode;
intprevious_mode;
intmode_time;// timestamp at which current mode elapses.
@@ -277,8 +278,8 @@ typedef struct ai_info {
intai_class;// Class. Might be override of default.
// Probably become obsolete, to be replaced by path_start, path_cur, etc.
waypoint_list*wp_list;// waypoint list being followed
size_twp_index;// waypoint index in list
intwp_list_index;// index of waypoint list being followed
intwp_index;// index of waypoint in list
intwp_flags;// waypoint flags, see WPF_xxxx
intwaypoint_speed_cap;// -1 no cap, otherwise cap - changed to int by Goober5000
@@ -294,6 +295,7 @@ typedef struct ai_info {
vec3dpath_create_pos;// Object's position at time of global path creation.
matrixpath_create_orient;// Object's orientation at time of global path creation.
intmp_index;// Model path index. Index in polymodel:model_paths
intmp_randomized_vert;// Vertex of the model path that was given a random offset, or -1
fixpath_next_check_time;// Last time checked to see if would collide with model.
intpath_goal_dist;// minimum distance to first path point to consider path reached
intpath_subsystem_next_check;// timestamp to next check if subsystem is still visible
@@ -308,6 +310,7 @@ typedef struct ai_info {
fixsubmode_start_time;// time at which we entered the current submode
intsubmode_parm0;// parameter specific to current submode
intsubmode_parm1;// SUSHI: Another optional parameter
floatsubmode_float0;// Goober5000: a float parameter
fixnext_predict_pos_time;// Next time to predict position.
intnext_dynamic_path_check_time;//ETP: Time of next path check in ai_new_maybe_reposition_attack_subsys
@@ -317,7 +320,7 @@ typedef struct ai_info {
//Unlike the predicted position stuff, also takes into account velocity
//Only used against small ships
fixnext_aim_pos_time;
vec3dlast_aim_enemy_pos;
vec3dlast_aim_enemy_pos;// Normally this is the position of the enemy a turret is targeting but in the F3 Lab, this is used to pass raw target coordinates to the turret firing methods.
vec3dlast_aim_enemy_vel;
ai_goalgoals[MAX_AI_GOALS];
@@ -329,7 +332,7 @@ typedef struct ai_info {
floattime_enemy_near;// SUSHI: amount of time enemy continuously "near" the player
fixlast_attack_time;// Missiontime of last time this ship attacked its enemy.
fixlast_hit_time;// Missiontime of last time this ship was hit by anyone.
intlast_hit_quadrant;// Shield section of last hit.
intdanger_shield_quadrant;// Shield section AI will prefer to prioritize for recharging, it if possible.
fixlast_hit_target_time;// Missiontime of last time this ship successfully hit target.
inthitter_objnum;// Object index of ship that hit this ship last time.
inthitter_signature;// Signature of hitter. Prevents stupidity if hitter gets killed.
@@ -373,11 +376,6 @@ typedef struct ai_info {
floatai_turret_max_aim_update_delay;
flagset<AI::Profile_Flags>ai_profile_flags;//Holds AI_Profiles flags (possibly overriden by AI class) that actually apply to AI
union{
floatstay_near_distance;// Distance to stay within for AIM_STAY_NEAR mode.
};
ship_subsys*targeted_subsys;// Targeted subobject on current target. NULL if none;
ship_subsys*last_subsys_target;// last known subsystem target
inttargeted_subsys_parent;// Parent objnum of subobject, not necessarily targeted
@@ -489,7 +487,7 @@ typedef struct {
#define SUBSYS_PATH_DIST 500.0f
// Friendly damage defines
#define MAX_BURST_DAMAGE 20 // max damage that can be done in BURST_DURATION
#define MAX_BURST_DAMAGE 20.0f// max damage that can be done in BURST_DURATION
#define BURST_DURATION 500 // decay time over which Player->damage_this_burst falls from MAX_BURST_DAMAGE to 0
externintMission_all_attack;// !0 means all teams attack all teams.
@@ -497,8 +495,8 @@ extern int Mission_all_attack; // !0 means all teams attack all teams.
externai_infoAi_info[];
externai_info*Player_ai;
externai_class*Ai_classes;
externchar**Ai_class_names;
externSCP_vector<ai_class>Ai_classes;
externSCP_vector<constchar*>Ai_class_names;
externintNum_ai_classes;
externintAi_firing_enabled;
@@ -528,21 +526,21 @@ void ai_object_init(object * obj, int ai_index);
Unload_primaries,// Fire primaries as fast as possible!
Trying_unsuccessfully_to_warp,// Trying to warp, but can't warp at the moment
Free_afterburner_use,// Use afterburners while following waypoints or flying towards objects
Waypoints_no_formation,// wont get into formation when running waypoints as part of a wing
NUM_VALUES
};
@@ -41,12 +43,16 @@ namespace AI {
Dockee_index_valid,// when set, index field for dockee is valid
Goal_on_hold,// when set, this goal cannot currently be satisfied, although it could be in the future
Subsys_needs_fixup,// when set, the subsystem index (for a destroy subsystem goal) is invalid and must be gotten from the subsys name stored in docker.name field!!
Goal_override,// paired with AIG_TYPE_DYNAMIC to mean this goal overrides any other goal
Goal_override,// paired with ai_goal_type::DYNAMIC to mean this goal overrides any other goal
Want_override,// a goal should set this flag if Goal_override should be assigned when the goal is achievable
Purge,// purge this goal next time we process
Goals_purged,// this goal has already caused other goals to get purged
Purge_when_new_goal_added,// this goal is perpetual until any other goal is added, at which time it sets its own Purge flag
Goals_purged,// this goal has already caused other goals to get purged (because it is something like ai-disarm that renders other goals invalid)
Depart_sound_played,// Goober5000 - replacement for AL's hack ;)
Target_own_team,// this attack goal is allowed to target friendlies
Afterburn_hard,// afterburn as hard as possible to the goal
Waypoints_in_reverse,// decrement instead of increment
Clear_all_goals_first,// this goal wipes all goals (including itself) before it runs (handled separately, and in a different place, from purging invalid goals)
NUM_VALUES
};
@@ -98,6 +104,10 @@ namespace AI {
Fix_heat_seeker_stealth_bug,
Fix_linked_primary_bug,
Fix_ramming_stationary_targets_bug,
Fix_avoid_shockwave_bugs,// a) waiting until a homing weapon actually homes before evading;
// b) picking the correct expected impact position for capships;
// c) not clearing shockwave_object for ships;
// d) checking the explosion damage of the correct ship
Force_beam_turret_fov,
Free_afterburner_use,
Glide_decay_requires_thrust,
@@ -122,7 +132,8 @@ namespace AI {
Smart_shield_management,
Smart_subsystem_targeting_for_turrets,
Strict_turret_tagged_only_targeting,
Support_dont_add_primaries,//Prevents support ship from equipping new primary as requested in http://scp.indiegames.us/mantis/view.php?id=3198
Ships_intercept_mines,// all AI-controlled ships autonomously engage hostile mines within mine_targetable_range of themselves
Support_dont_add_primaries,//Prevents support ship from equipping new primary as requested in https://scp.indiegames.us/mantis/view.php?id=3198
Turrets_ignore_target_radius,
Use_actual_primary_range,
Use_subsystem_path_point_radii,
@@ -134,10 +145,12 @@ namespace AI {
All_nonshielded_ships_can_manage_ets,
Fightercraft_nonshielded_ships_can_manage_ets,
Ships_playing_dead_dont_manage_ets,
Better_collision_avoidance,
Better_combat_collision_avoidance,
Better_combat_collision_avoid_includes_target,
Better_guard_collision_avoidance,
Require_exact_los,
Improved_missile_avoidance,
Friendlies_use_countermeasure_firechance,
Unify_usage_countermeasure_firechance,
Improved_subsystem_attack_pathing,
Fixed_ship_weapon_collision,
No_shield_damage_from_ship_collisions,
@@ -156,6 +169,45 @@ namespace AI {
Whackable_debris,
Whackable_asteroids,
Dynamic_goals_afterburn_hard,
Player_orders_afterburn_hard,
Hudsquadmsg_tactical_disarm_disable,
Align_to_target_when_guarding_still,
Debris_respects_big_damage,
Dont_limit_change_in_speed_due_to_physics_whack,
Guards_ignore_protected_attackers,
Fix_standard_strafe,
Fix_ai_target_recovery,// a) strafing ships that lose their target re-process their orders, like chasing ships already do
// b) ships parked in AIM_NONE while holding a standing chase order (attack-any etc.) re-process their orders;
// c) target selection for pursuit (chasing, guard reactions, retaliation) skips ships outside the attacker's
// actively-pursues list; targets held while not chasing are unaffected, and explicitly ordered targets are
// still assigned but not chased or strafed;
// d) enemy_wing is reset when a new order takes over (shared with Fix_stale_ai_order_state)
Fix_big_ship_waypoint_completion,// a) big ships complete a waypoint within their radius rather than sqrt(radius);
// b) completion no longer requires moving 0.1m in a single frame (framerate-dependent)
Fix_shockwave_expire_before_do_damage,// shockwaves whose lifetime is shorter than one frame apply their area damage at least once before expiring
Fix_small_ai_recover_after_engines_repaired,// ensure small ship AI can switch back to useful AI modes if engines get repaired
Fix_model_path_refresh_randomization,// a subsystem path keeps its randomized point when the path is refreshed because the target moved
Fix_bay_speed_ramp,// the fighterbay speed ramp covers only the bay path itself, not points that route a departing ship around the carrier, and never exceeds max speed
Fix_stale_ai_order_state,// a) enemy_wing, guard_*, previous_mode, resume_goal_time, and the targeted subsystem (with its path) are reset when a new order takes over (enemy_wing is also reset under Fix_ai_target_recovery);
// b) a dynamic chase saves previous_mode/previous_submode; it and strafe entry leave them alone during an ongoing dynamic goal (evading a weapon still overwrites them, which is harmless since the evade resume re-processes orders);
// c) resuming guard duty discards any subsystem target and path left over from the interruption;
// d) a ship ordered to guard itself, or to guard a wing it leads (including one that becomes leader mid-mission), treats that goal as unachievable instead of holding it forever
mprintf(("Warning: $default form-on-wing priority: should be > 0 (read %d). Value will not be used.\n",priority));
}
}
set_flag(profile,"$do not clear goals when running form-on-wing:",AI::Profile_Flags::Do_not_clear_goals_when_running_form_on_wing);
set_flag(profile,"$do not clear goals when running stay-still:",AI::Profile_Flags::Do_not_clear_goals_when_running_stay_still);
set_flag(profile,"$do not set override when assigning form-on-wing:",AI::Profile_Flags::Do_not_set_override_when_assigning_form_on_wing);
set_flag(profile,"$purge player-issued form-on-wing after subsequent order:",AI::Profile_Flags::Purge_player_issued_form_on_wing_after_subsequent_order);
set_flag(profile,"$cancel future waves of any wing launched from an exited ship:",AI::Profile_Flags::Cancel_future_waves_of_any_wing_launched_from_an_exited_ship);
//The following raycast tends to make up 10%(!) of total AI-frametime for basically no benefit, especially in the common case for turrets where the normal isn't even queried.
if(!(En_objp->flags[Object::Object_Flags::Protected])||((aip->goals[0].ai_mode&(AI_GOAL_DISABLE_SHIP|AI_GOAL_DISARM_SHIP))&&swip->wi_flags[Weapon::Info_Flags::Puncture])){//override lockdown on protected ships when using anti subsystem weapons - Valathil
if(!(En_objp->flags[Object::Object_Flags::Protected])||(ai_goal_is_disable_or_disarm(aip->goals[0].ai_mode)&&swip->wi_flags[Weapon::Info_Flags::Puncture])){//override lockdown on protected ships when using anti subsystem weapons - Valathil
// If ship is protected and very low on hits, don't fire missiles.
Assertion(false, "The goal objnum does not match the target objnum in ai_big_strafe(), please report to the SCP!"); // what is going on here? - Get Alan
AI_GOAL_PLAY_DEAD_PERSISTENT,// Disables subsystem rotation/translation among other things but there is a carveout for that in the lab in ship_move_subsystems() and ai_process_subobjects()
AI_GOAL_LUA,
AI_GOAL_DISARM_SHIP_TACTICAL,
AI_GOAL_DISABLE_SHIP_TACTICAL,
// Goober5000: added AI_GOAL_STAY_NEAR_SHIP and AI_GOAL_KEEP_SAFE_DISTANCE as valid for fighters
Loaded 100 of 3045 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.