Files
fs2open.github.com/code/graphics/material.cpp
T
b26b9cf743 Add Vulkan rendering backend, with HDR10 output and raytraced shadows (#7554)
* 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]>
2026-07-21 16:58:21 +00:00

939 lines
22 KiB
C++

#include "globalincs/pstypes.h"
#include "graphics/grinternal.h"
#include "graphics/2d.h"
#include "graphics/material.h"
#include "graphics/shadows.h"
#include "globalincs/systemvars.h"
#include "cmdline/cmdline.h"
#define MODEL_SDR_FLAG_MODE_CPP
#include "def_files/data/effects/model_shader_flags.h"
gr_alpha_blend material_determine_blend_mode(int base_bitmap, bool blending)
{
if ( blending ) {
if ( base_bitmap >= 0 && bm_has_alpha_channel(base_bitmap) ) {
return ALPHA_BLEND_ALPHA_BLEND_ALPHA;
}
return ALPHA_BLEND_ADDITIVE;
}
return ALPHA_BLEND_ALPHA_BLEND_ALPHA;
}
gr_zbuffer_type material_determine_depth_mode(bool depth_testing, bool blending)
{
if ( depth_testing ) {
if ( blending ) {
return ZBUFFER_TYPE_READ;
}
return ZBUFFER_TYPE_FULL;
}
return ZBUFFER_TYPE_NONE;
}
void material_set_unlit(material* mat_info, int texture, float alpha, bool blending, bool depth_testing)
{
mat_info->set_texture_map(TM_BASE_TYPE, texture);
gr_alpha_blend blend_mode = material_determine_blend_mode(texture, blending);
gr_zbuffer_type depth_mode = material_determine_depth_mode(depth_testing, blending);
mat_info->set_blend_mode(blend_mode);
mat_info->set_depth_mode(depth_mode);
mat_info->set_cull_mode(false);
if ( blend_mode == ALPHA_BLEND_ADDITIVE ) {
mat_info->set_color(alpha, alpha, alpha, 1.0f);
} else {
mat_info->set_color(1.0f, 1.0f, 1.0f, alpha);
}
if ( texture >= 0 && bm_has_alpha_channel(texture) ) {
mat_info->set_texture_type(material::TEX_TYPE_XPARENT);
}
}
void material_set_unlit_opaque(material* mat_info, int texture, bool depth_testing)
{
mat_info->set_texture_map(TM_BASE_TYPE, texture);
gr_alpha_blend blend_mode = ALPHA_BLEND_NONE;
gr_zbuffer_type depth_mode = material_determine_depth_mode(depth_testing, false);
mat_info->set_blend_mode(blend_mode);
mat_info->set_depth_mode(depth_mode);
mat_info->set_cull_mode(false);
mat_info->set_color(1.0f, 1.0f, 1.0f, 1.0f);
if ( texture >= 0 && bm_has_alpha_channel(texture) ) {
mat_info->set_texture_type(material::TEX_TYPE_XPARENT);
}
}
void material_set_unlit_emissive(material* mat_info, int texture, float alpha, float color_scale)
{
material_set_unlit(mat_info, texture, alpha, true, true);
mat_info->set_color_scale(color_scale);
}
void material_set_unlit_color(material* mat_info, int texture, color *clr, bool blending, bool depth_testing)
{
mat_info->set_texture_map(TM_BASE_TYPE, texture);
gr_alpha_blend blend_mode = material_determine_blend_mode(texture, blending);
gr_zbuffer_type depth_mode = material_determine_depth_mode(depth_testing, blending);
mat_info->set_blend_mode(blend_mode);
mat_info->set_depth_mode(depth_mode);
mat_info->set_cull_mode(false);
mat_info->set_color(*clr);
}
void material_set_unlit_color(material* mat_info, int texture, color *clr, float alpha, bool blending, bool depth_testing)
{
color clr_with_alpha;
gr_init_alphacolor(&clr_with_alpha, clr->red, clr->green, clr->blue, fl2i(alpha * 255.0f));
material_set_unlit_color(mat_info, texture, &clr_with_alpha, blending, depth_testing);
}
void material_set_interface(material* mat_info, int texture, bool blended, float alpha)
{
mat_info->set_texture_map(TM_BASE_TYPE, texture);
mat_info->set_texture_type(material::TEX_TYPE_INTERFACE);
gr_alpha_blend blend_mode = material_determine_blend_mode(texture, blended);
mat_info->set_blend_mode(blend_mode);
mat_info->set_depth_mode(ZBUFFER_TYPE_NONE);
mat_info->set_cull_mode(false);
if ( blend_mode == ALPHA_BLEND_ADDITIVE ) {
mat_info->set_color(alpha, alpha, alpha, 1.0f);
} else {
mat_info->set_color(1.0f, 1.0f, 1.0f, alpha);
}
}
void material_set_unlit_volume(particle_material* mat_info, int texture, bool point_sprites)
{
mat_info->set_point_sprite_mode(point_sprites);
mat_info->set_depth_mode(ZBUFFER_TYPE_NONE);
mat_info->set_blend_mode(material_determine_blend_mode(texture, true));
mat_info->set_texture_map(TM_BASE_TYPE, texture);
mat_info->set_cull_mode(false);
mat_info->set_color(1.0f, 1.0f, 1.0f, 1.0f);
}
void material_set_distortion(distortion_material *mat_info, int texture, bool thruster)
{
mat_info->set_thruster_rendering(thruster);
mat_info->set_depth_mode(ZBUFFER_TYPE_READ);
mat_info->set_blend_mode(ALPHA_BLEND_ALPHA_BLEND_ALPHA);
mat_info->set_texture_map(TM_BASE_TYPE, texture);
mat_info->set_cull_mode(false);
mat_info->set_color(1.0f, 1.0f, 1.0f, 1.0f);
}
void material_set_rocket_interface(interface_material* mat_info,
int texture,
const vec2d& offset,
float horizontal_swipe)
{
mat_info->set_texture_map(TM_BASE_TYPE, texture);
mat_info->set_offset(offset);
mat_info->set_horizontal_swipe(horizontal_swipe);
mat_info->set_cull_mode(false);
mat_info->set_color(1.0f, 1.0f, 1.0f, 1.0f);
mat_info->set_depth_mode(ZBUFFER_TYPE_NONE);
mat_info->set_blend_mode(ALPHA_BLEND_ALPHA_BLEND_ALPHA);
mat_info->set_texture_type(material::TEX_TYPE_INTERFACE);
}
void material_set_movie(movie_material* mat_info, int y_bm, int u_bm, int v_bm, float alpha) {
mat_info->set_depth_mode(ZBUFFER_TYPE_NONE);
mat_info->set_blend_mode(ALPHA_BLEND_ALPHA_BLEND_ALPHA);
mat_info->set_cull_mode(false);
mat_info->set_color(1.0f, 1.0f, 1.0f, alpha);
mat_info->setYtex(y_bm);
mat_info->setUtex(u_bm);
mat_info->setVtex(v_bm);
mat_info->set_texture_type(material::TEX_TYPE_AABITMAP);
}
void material_set_batched_bitmap(batched_bitmap_material* mat_info, int base_tex, float alpha, float color_scale) {
material_set_unlit(mat_info, base_tex, alpha, true, true);
mat_info->set_color_scale(color_scale);
}
void material_set_batched_opaque_bitmap(batched_bitmap_material* mat_info, int base_tex, float color_scale) {
material_set_unlit_opaque(mat_info, base_tex, true);
mat_info->set_color_scale(color_scale);
}
void material_set_nanovg(nanovg_material* mat_info, int base_tex) {
material_set_unlit(mat_info, base_tex, 1.0f, true, false);
mat_info->set_cull_mode(false);
mat_info->set_color_mask(true, true, true, true);
mat_info->set_blend_mode(ALPHA_BLEND_PREMULTIPLIED);
mat_info->set_stencil_mask(0xFFFFFFFF);
mat_info->set_stencil_func(ComparisionFunction::Always, 0, 0xFFFFFFFF);
mat_info->set_front_stencil_op(StencilOperation::Keep, StencilOperation::Keep, StencilOperation::Keep);
mat_info->set_back_stencil_op(StencilOperation::Keep, StencilOperation::Keep, StencilOperation::Keep);
}
void material_set_decal(material* mat_info, int diffuse_tex, int glow_tex, int normal_tex) {
mat_info->set_depth_mode(ZBUFFER_TYPE_READ);
mat_info->set_blend_mode(0, material_determine_blend_mode(diffuse_tex, true));
mat_info->set_blend_mode(1, ALPHA_BLEND_ADDITIVE); // Normal blending must always be additive
mat_info->set_blend_mode(2, material_determine_blend_mode(glow_tex, true));
mat_info->set_texture_map(TM_BASE_TYPE, diffuse_tex);
mat_info->set_texture_map(TM_GLOW_TYPE, glow_tex);
mat_info->set_texture_map(TM_NORMAL_TYPE, normal_tex);
mat_info->set_cull_mode(false);
// Done't write the alpha channel in any case since that will cause changes to other material properties
// TODO: If decals should be able to change more than just the material diffuse color then a solution with separate
// blending equations must be used
mat_info->set_color_mask(true, true, true, false);
}
material::material():
Sdr_type(SDR_TYPE_DEFAULT_MATERIAL),
Tex_type(TEX_TYPE_NORMAL),
Texture_addressing(TMAP_ADDRESS_WRAP),
Depth_mode(ZBUFFER_TYPE_NONE),
Blend_mode(ALPHA_BLEND_ALPHA_BLEND_ALPHA),
Cull_mode(true),
Fill_mode(GR_FILL_MODE_SOLID),
Clr_scale(1.0f),
Depth_bias(0)
{
Clr.xyzw.x = 1.0f;
Clr.xyzw.y = 1.0f;
Clr.xyzw.z = 1.0f;
Clr.xyzw.w = 1.0f;
Texture_maps[TM_BASE_TYPE] = -1;
Texture_maps[TM_GLOW_TYPE] = -1;
Texture_maps[TM_SPECULAR_TYPE] = -1;
Texture_maps[TM_NORMAL_TYPE] = -1;
Texture_maps[TM_HEIGHT_TYPE] = -1;
Texture_maps[TM_MISC_TYPE] = -1;
Texture_maps[TM_SPEC_GLOSS_TYPE] = -1;
Texture_maps[TM_AMBIENT_TYPE] = -1;
Clip_params.enabled = false;
Color_mask.x = true;
Color_mask.y = true;
Color_mask.z = true;
Color_mask.w = true;
Buffer_blend_mode.fill(Blend_mode);
};
void material::set_shader_type(shader_type init_sdr_type)
{
Sdr_type = init_sdr_type;
}
uint material::get_shader_flags() const
{
return 0;
}
int material::get_shader_handle() const
{
return gr_maybe_create_shader(Sdr_type, get_shader_flags());
}
void material::set_texture_map(int tex_type, int texture_num)
{
Assert(tex_type > -1 && tex_type < TM_NUM_TYPES);
Texture_maps[tex_type] = texture_num;
}
int material::get_texture_map(int tex_type) const
{
Assert(tex_type > -1 && tex_type < TM_NUM_TYPES);
return Texture_maps[tex_type];
}
bool material::is_textured() const
{
return
Texture_maps[TM_BASE_TYPE] > -1 ||
Texture_maps[TM_GLOW_TYPE] > -1 ||
Texture_maps[TM_SPECULAR_TYPE] > -1 ||
Texture_maps[TM_NORMAL_TYPE] > -1 ||
Texture_maps[TM_HEIGHT_TYPE] > -1 ||
Texture_maps[TM_AMBIENT_TYPE] > -1 ||
Texture_maps[TM_MISC_TYPE] > -1;
}
void material::set_texture_type(texture_type t_type)
{
Tex_type = t_type;
}
int material::get_texture_type() const
{
switch ( Tex_type ) {
default:
case TEX_TYPE_NORMAL:
return TCACHE_TYPE_NORMAL;
case TEX_TYPE_XPARENT:
return TCACHE_TYPE_XPARENT;
case TEX_TYPE_INTERFACE:
return TCACHE_TYPE_INTERFACE;
case TEX_TYPE_AABITMAP:
return TCACHE_TYPE_AABITMAP;
}
}
bool material::is_clipped() const
{
return Clip_params.enabled;
}
void material::set_clip_plane(const vec3d &normal, const vec3d &position)
{
Clip_params.enabled = true;
Clip_params.normal = normal;
Clip_params.position = position;
}
void material::set_clip_plane()
{
Clip_params.enabled = false;
}
const material::clip_plane& material::get_clip_plane() const
{
return Clip_params;
}
void material::set_texture_addressing(int addressing)
{
Texture_addressing = addressing;
}
int material::get_texture_addressing() const
{
return Texture_addressing;
}
void material::set_depth_mode(gr_zbuffer_type mode)
{
Depth_mode = mode;
}
gr_zbuffer_type material::get_depth_mode() const
{
return Depth_mode;
}
void material::set_cull_mode(bool mode)
{
Cull_mode = mode;
}
bool material::get_cull_mode() const
{
return Cull_mode;
}
void material::set_fill_mode(int mode)
{
Fill_mode = mode;
}
int material::get_fill_mode() const
{
return Fill_mode;
}
void material::set_blend_mode(gr_alpha_blend mode)
{
Blend_mode = mode;
Has_buffer_blends = false;
Buffer_blend_mode.fill(mode);
}
void material::set_blend_mode(int buffer, gr_alpha_blend mode)
{
Assertion(buffer >= 0 && buffer < (int) Buffer_blend_mode.size(), "Invalid buffer index %d found!", buffer);
Has_buffer_blends = true;
Buffer_blend_mode[buffer] = mode;
}
bool material::has_buffer_blend_modes() const {
return Has_buffer_blends;
}
gr_alpha_blend material::get_blend_mode(int buffer) const
{
if (!Has_buffer_blends) {
return Blend_mode;
}
Assertion(buffer >= 0 && buffer < (int) Buffer_blend_mode.size(), "Invalid buffer index %d found!", buffer);
return Buffer_blend_mode[buffer];
}
void material::set_depth_bias(int bias)
{
Depth_bias = bias;
}
int material::get_depth_bias() const
{
return Depth_bias;
}
void material::set_color(float red, float green, float blue, float alpha)
{
Clr.xyzw.x = red;
Clr.xyzw.y = green;
Clr.xyzw.z = blue;
Clr.xyzw.w = alpha;
}
void material::set_color(int r, int g, int b, int a)
{
CLAMP(r, 0, 255);
CLAMP(b, 0, 255);
CLAMP(g, 0, 255);
CLAMP(a, 0, 255);
Clr.xyzw.x = i2fl(r) / 255.0f;
Clr.xyzw.y = i2fl(g) / 255.0f;
Clr.xyzw.z = i2fl(b) / 255.0f;
Clr.xyzw.w = i2fl(a) / 255.0f;
}
void material::set_color(const color &clr_in)
{
if ( clr_in.is_alphacolor ) {
Clr.xyzw.x = i2fl(clr_in.red) / 255.0f;
Clr.xyzw.y = i2fl(clr_in.green) / 255.0f;
Clr.xyzw.z = i2fl(clr_in.blue) / 255.0f;
Clr.xyzw.w = i2fl(clr_in.alpha) / 255.0f;
} else {
Clr.xyzw.x = i2fl(clr_in.red) / 255.0f;
Clr.xyzw.y = i2fl(clr_in.green) / 255.0f;
Clr.xyzw.z = i2fl(clr_in.blue) / 255.0f;
Clr.xyzw.w = 1.0f;
}
}
const vec4& material::get_color() const
{
return Clr;
}
void material::set_color_scale(float scale)
{
Clr_scale = scale;
}
float material::get_color_scale() const
{
return Clr_scale;
}
void material::set_stencil_test(bool stencil) {
Stencil_test = stencil;
}
bool material::is_stencil_enabled() const {
return Stencil_test;
}
void material::set_stencil_mask(uint32_t mask) {
Stencil_mask = mask;
}
uint32_t material::get_stencil_mask() const {
return Stencil_mask;
}
void material::set_stencil_func(ComparisionFunction compare, int ref, uint32_t mask) {
Stencil_func.compare = compare;
Stencil_func.ref = ref;
Stencil_func.mask = mask;
}
const material::StencilFunc& material::get_stencil_func() const {
return Stencil_func;
}
void material::set_stencil_op(StencilOperation stencilFailOperation,
StencilOperation depthFailOperation,
StencilOperation successOperation) {
set_front_stencil_op(stencilFailOperation, depthFailOperation, successOperation);
set_back_stencil_op(stencilFailOperation, depthFailOperation, successOperation);
}
void material::set_front_stencil_op(StencilOperation stencilFailOperation,
StencilOperation depthFailOperation,
StencilOperation successOperation) {
Front_stencil_op.stencilFailOperation = stencilFailOperation;
Front_stencil_op.depthFailOperation = depthFailOperation;
Front_stencil_op.successOperation = successOperation;
}
const material::StencilOp& material::get_front_stencil_op() const {
return Front_stencil_op;
}
void material::set_back_stencil_op(StencilOperation stencilFailOperation,
StencilOperation depthFailOperation,
StencilOperation successOperation) {
Back_stencil_op.stencilFailOperation = stencilFailOperation;
Back_stencil_op.depthFailOperation = depthFailOperation;
Back_stencil_op.successOperation = successOperation;
}
const material::StencilOp& material::get_back_stencil_op() const {
return Back_stencil_op;
}
void material::set_color_mask(bool red, bool green, bool blue, bool alpha) {
Color_mask.x = red;
Color_mask.y = green;
Color_mask.z = blue;
Color_mask.w = alpha;
}
const bvec4& material::get_color_mask() const {
return Color_mask;
}
model_material::model_material() : material() {
set_shader_type(SDR_TYPE_MODEL);
}
void model_material::set_desaturation(bool enabled)
{
Desaturate = enabled;
}
bool model_material::is_desaturated() const
{
return Desaturate;
}
void model_material::set_shadow_casting(bool enabled)
{
Shadow_casting = enabled;
}
bool model_material::is_shadow_casting() const {
return Shadow_casting;
}
void model_material::set_shadow_receiving(bool enabled) {
Shadow_receiving = enabled;
}
bool model_material::is_shadow_receiving() const {
return Shadow_receiving && !Shadow_override;
}
void model_material::set_light_factor(float factor)
{
Light_factor = factor;
}
float model_material::get_light_factor() const
{
return Light_factor;
}
void model_material::set_lighting(bool mode)
{
lighting = mode;
}
bool model_material::is_lit() const
{
return lighting;
}
void model_material::set_deferred_lighting(bool enabled)
{
Deferred = enabled;
}
bool model_material::is_deferred() const
{
return Deferred;
}
void model_material::set_high_dynamic_range(bool enabled)
{
HDR = enabled;
}
bool model_material::is_hdr() const
{
return HDR;
}
void model_material::set_center_alpha(int c_alpha)
{
Center_alpha = c_alpha;
}
int model_material::get_center_alpha() const
{
return Center_alpha;
}
void model_material::set_thrust_scale(float scale)
{
Thrust_scale = scale;
}
float model_material::get_thrust_scale() const
{
return Thrust_scale;
}
void model_material::set_team_color(const team_color &team_clr)
{
Team_color_set = true;
Tm_color = team_clr;
}
void model_material::set_team_color()
{
Team_color_set = false;
}
bool model_material::is_team_color_set() const
{
return Team_color_set;
}
const team_color& model_material::get_team_color() const
{
return Tm_color;
}
void model_material::set_animated_effect(int effect, float time)
{
Animated_effect = effect;
Animated_timer = time;
}
void model_material::set_animated_effect()
{
Animated_effect = 0;
Animated_timer = 0.0f;
}
int model_material::get_animated_effect() const
{
return Animated_effect;
}
float model_material::get_animated_effect_time() const
{
return Animated_timer;
}
void model_material::set_batching(bool enabled)
{
Batched = enabled;
}
bool model_material::is_batched() const
{
return Batched;
}
void model_material::set_fog(int r, int g, int b)
{
Fog_params.enabled = true;
Fog_params.r = r;
Fog_params.g = g;
Fog_params.b = b;
}
void model_material::set_fog()
{
Fog_params.enabled = false;
}
bool model_material::is_fogged() const
{
return Fog_params.enabled;
}
const model_material::fog& model_material::get_fog() const
{
return Fog_params;
}
void model_material::set_outline_thickness(float thickness) {
Outline_thickness = thickness;
}
float model_material::get_outline_thickness() const {
return Outline_thickness;
}
bool model_material::uses_thick_outlines() const {
return Outline_thickness > 0.0f;
}
float model_material::get_alpha_mult() const {
return Alpha_mult;
}
bool model_material::is_alpha_mult_active() const {
return Use_alpha_mult;
}
void model_material::set_alpha_mult(float alpha) {
Use_alpha_mult = true;
Alpha_mult = alpha;
}
void model_material::reset_alpha_mult() {
Use_alpha_mult = false;
Alpha_mult = 1.0f;
}
uint model_material::get_shader_flags() const
{
uint Shader_flags = 0;
if (!gr_is_capable(gr_capability::CAPABILITY_LARGE_SHADER)) {
Shader_flags |= get_shader_runtime_early_flags();
}
if (Shadow_casting) {
// Shadow map generation now uses a dedicated shader (SDR_TYPE_MODEL_SHADOW_MAP)
return Shader_flags;
}
if (uses_thick_outlines() && gr_is_capable(gr_capability::CAPABILITY_THICK_OUTLINE)) {
Shader_flags |= MODEL_SDR_FLAG_THICK_OUTLINES;
}
// Must stay a genuine compile-time flag (like SHADOW_MAP/THICK_OUTLINES above),
// not one gated only via the runtime `flags` uniform below -- see the comment
// on MODEL_SDR_FLAG_RT_SHADOWS in model_shader_flags.h.
if (is_shadow_receiving() && shadows_use_raytracing()) {
Shader_flags |= MODEL_SDR_FLAG_RT_SHADOWS;
}
if (!gr_is_capable(gr_capability::CAPABILITY_LARGE_SHADER)) {
Shader_flags |= get_shader_runtime_flags();
}
return Shader_flags;
}
int model_material::get_shader_runtime_early_flags() const {
int flags = 0;
if (is_batched())
flags |= MODEL_SDR_FLAG_TRANSFORM;
return flags;
}
int model_material::get_shader_runtime_flags() const {
int flags = 0;
if (is_lit())
flags |= MODEL_SDR_FLAG_LIGHT;
if (is_deferred())
flags |= MODEL_SDR_FLAG_DEFERRED;
if (is_hdr())
flags |= MODEL_SDR_FLAG_HDR;
if (get_texture_map(TM_BASE_TYPE) >= 0)
flags |= MODEL_SDR_FLAG_DIFFUSE;
if (get_texture_map(TM_GLOW_TYPE) >= 0)
flags |= MODEL_SDR_FLAG_GLOW;
if (get_texture_map(TM_SPECULAR_TYPE) >= 0 || get_texture_map(TM_SPEC_GLOSS_TYPE) >= 0)
flags |= MODEL_SDR_FLAG_SPEC;
if (get_texture_map(TM_NORMAL_TYPE) >= 0)
flags |= MODEL_SDR_FLAG_NORMAL;
if (get_texture_map(TM_AMBIENT_TYPE) >= 0)
flags |= MODEL_SDR_FLAG_AMBIENT;
if (get_texture_map(TM_MISC_TYPE) >= 0)
flags |= MODEL_SDR_FLAG_MISC;
if (get_texture_map(TM_MISC_TYPE) >= 0 && is_team_color_set())
flags |= MODEL_SDR_FLAG_TEAMCOLOR;
if (is_fogged())
flags |= MODEL_SDR_FLAG_FOG;
if (is_shadow_receiving())
flags |= MODEL_SDR_FLAG_SHADOWS;
if (get_thrust_scale() > 0.0f)
flags |= MODEL_SDR_FLAG_THRUSTER;
if (is_alpha_mult_active())
flags |= MODEL_SDR_FLAG_ALPHA_MULT;
return flags;
}
particle_material::particle_material():
material()
{
set_shader_type(SDR_TYPE_EFFECT_PARTICLE);
}
void particle_material::set_point_sprite_mode(bool enabled)
{
Point_sprite = enabled;
}
bool particle_material::get_point_sprite_mode()
{
return Point_sprite;
}
uint particle_material::get_shader_flags() const
{
uint flags = 0;
if ( Point_sprite ) {
flags |= SDR_FLAG_PARTICLE_POINT_GEN;
}
return flags;
}
distortion_material::distortion_material():
material()
{
set_shader_type(SDR_TYPE_EFFECT_DISTORTION);
}
void distortion_material::set_thruster_rendering(bool enabled)
{
Thruster_render = enabled;
}
bool distortion_material::get_thruster_rendering()
{
return Thruster_render;
}
shield_material::shield_material() :
material()
{
set_shader_type(SDR_TYPE_SHIELD_DECAL);
vm_set_identity(&Impact_orient);
Impact_pos.xyz.x = 0.0f;
Impact_pos.xyz.y = 0.0f;
Impact_pos.xyz.z = 0.0f;
Impact_radius = 1.0f;
}
void shield_material::set_impact_transform(matrix &orient, vec3d &pos)
{
Impact_orient = orient;
Impact_pos = pos;
}
void shield_material::set_impact_radius(float radius)
{
Impact_radius = radius;
}
const matrix& shield_material::get_impact_orient()
{
return Impact_orient;
}
const vec3d& shield_material::get_impact_pos()
{
return Impact_pos;
}
float shield_material::get_impact_radius()
{
return Impact_radius;
}
movie_material::movie_material() : material() {
set_shader_type(SDR_TYPE_VIDEO_PROCESS);
}
int movie_material::getYtex() const {
return Ytex;
}
int movie_material::getUtex() const {
return Utex;
}
int movie_material::getVtex() const {
return Vtex;
}
void movie_material::setYtex(int _Ytex) {
this->Ytex = _Ytex;
}
void movie_material::setUtex(int _Utex) {
this->Utex = _Utex;
}
void movie_material::setVtex(int _Vtex) {
movie_material::Vtex = _Vtex;
}
batched_bitmap_material::batched_bitmap_material() {
set_shader_type(SDR_TYPE_BATCHED_BITMAP);
}
nanovg_material::nanovg_material() {
set_shader_type(SDR_TYPE_NANOVG);
}
decal_material::decal_material() {
set_shader_type(SDR_TYPE_DECAL);
}
uint decal_material::get_shader_flags() const {
uint flags = 0;
if (get_texture_map(TM_NORMAL_TYPE) == -1) {
// If we don't write to the normal map then we can use the existing normal map for better normal accuracy
flags |= SDR_FLAG_DECAL_USE_NORMAL_MAP;
}
return flags;
}
interface_material::interface_material()
{
set_shader_type(SDR_TYPE_ROCKET_UI);
offset.x = 0;
offset.y = 0;
}
void interface_material::set_offset(const vec2d& new_offset) { this->offset = new_offset; }
vec2d interface_material::get_offset() const { return offset; }
void interface_material::set_horizontal_swipe(float hor_offset) { this->horizontalSwipeOff = hor_offset; }
float interface_material::get_horizontal_swipe() const { return this->horizontalSwipeOff; }