It almost works

This commit is contained in:
John Hunter
2023-03-27 18:58:56 +01:00
parent 3df909a6e8
commit 79fac10880
26 changed files with 2226 additions and 65803 deletions
Generated
+37
View File
@@ -720,6 +720,7 @@ dependencies = [
"egui",
"egui_winit_vulkano",
"obj",
"rand",
"rayon",
"rodio",
"serde",
@@ -1618,6 +1619,12 @@ dependencies = [
"miniz_oxide",
]
[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "proc-macro-crate"
version = "1.2.1"
@@ -1647,6 +1654,36 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "raw-window-handle"
version = "0.4.3"
+2
View File
@@ -40,6 +40,8 @@ utf-8 = "*"
rayon = "*"
rand = "0.8.5"
# using latest gits
[patch.crates-io]
vulkano = { path = "../vulkano/vulkano" }
-251
View File
@@ -1,251 +0,0 @@
// Modifications Copyright © 2021. Advanced Micro Devices, Inc. All Rights Reserved.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016, Intel Corporation
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File changes (yyyy-mm-dd)
// 2016-09-07: filip.strugar@intel.com: first commit
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \file */
#pragma once
#include <stdint.h>
typedef uint8_t FFX_CACAO_Bool;
static const FFX_CACAO_Bool FFX_CACAO_TRUE = 1;
static const FFX_CACAO_Bool FFX_CACAO_FALSE = 0;
/**
The quality levels that FidelityFX CACAO can generate SSAO at. This affects the number of samples taken for generating SSAO.
*/
typedef enum FFX_CACAO_Quality {
FFX_CACAO_QUALITY_LOWEST = 0,
FFX_CACAO_QUALITY_LOW = 1,
FFX_CACAO_QUALITY_MEDIUM = 2,
FFX_CACAO_QUALITY_HIGH = 3,
FFX_CACAO_QUALITY_HIGHEST = 4,
} FFX_CACAO_Quality;
/**
A structure representing a 4x4 matrix of floats. The matrix is stored in row major order in memory.
*/
typedef struct FFX_CACAO_Matrix4x4 {
float elements[4][4];
} FFX_CACAO_Matrix4x4;
/**
A structure for the settings used by FidelityFX CACAO. These settings may be updated with each draw call.
*/
typedef struct FFX_CACAO_Settings {
float radius; ///< [0.0, ~ ] World (view) space size of the occlusion sphere.
float shadowMultiplier; ///< [0.0, 5.0] Effect strength linear multiplier.
float shadowPower; ///< [0.5, 5.0] Effect strength pow modifier.
float shadowClamp; ///< [0.0, 1.0] Effect max limit (applied after multiplier but before blur).
float horizonAngleThreshold; ///< [0.0, 0.2] Limits self-shadowing (makes the sampling area less of a hemisphere, more of a spherical cone, to avoid self-shadowing and various artifacts due to low tessellation and depth buffer imprecision, etc.).
float fadeOutFrom; ///< [0.0, ~ ] Distance to start fading out the effect.
float fadeOutTo; ///< [0.0, ~ ] Distance at which the effect is faded out.
FFX_CACAO_Quality qualityLevel; ///< Effect quality, affects number of taps etc.
float adaptiveQualityLimit; ///< [0.0, 1.0] (only for quality level FFX_CACAO_QUALITY_HIGHEST).
uint32_t blurPassCount; ///< [ 0, 8] Number of edge-sensitive smart blur passes to apply.
float sharpness; ///< [0.0, 1.0] (How much to bleed over edges; 1: not at all, 0.5: half-half; 0.0: completely ignore edges).
float temporalSupersamplingAngleOffset; ///< [0.0, PI] Used to rotate sampling kernel; If using temporal AA / supersampling, suggested to rotate by ( (frame%3)/3.0*PI ) or similar. Kernel is already symmetrical, which is why we use PI and not 2*PI.
float temporalSupersamplingRadiusOffset; ///< [0.0, 2.0] Used to scale sampling kernel; If using temporal AA / supersampling, suggested to scale by ( 1.0f + (((frame%3)-1.0)/3.0)*0.1 ) or similar.
float detailShadowStrength; ///< [0.0, 5.0] Used for high-res detail AO using neighboring depth pixels: adds a lot of detail but also reduces temporal stability (adds aliasing).
FFX_CACAO_Bool generateNormals; ///< This option should be set to FFX_CACAO_TRUE if FidelityFX-CACAO should reconstruct a normal buffer from the depth buffer. It is required to be FFX_CACAO_TRUE if no normal buffer is provided.
float bilateralSigmaSquared; ///< [0.0, ~ ] Sigma squared value for use in bilateral upsampler giving Gaussian blur term. Should be greater than 0.0.
float bilateralSimilarityDistanceSigma; ///< [0.0, ~ ] Sigma squared value for use in bilateral upsampler giving similarity weighting for neighbouring pixels. Should be greater than 0.0.
} FFX_CACAO_Settings;
static const FFX_CACAO_Settings FFX_CACAO_DEFAULT_SETTINGS = {
/* radius */ 1.2f,
/* shadowMultiplier */ 1.0f,
/* shadowPower */ 1.50f,
/* shadowClamp */ 0.98f,
/* horizonAngleThreshold */ 0.06f,
/* fadeOutFrom */ 50.0f,
/* fadeOutTo */ 300.0f,
/* qualityLevel */ FFX_CACAO_QUALITY_HIGHEST,
/* adaptiveQualityLimit */ 0.45f,
/* blurPassCount */ 2,
/* sharpness */ 0.98f,
/* temporalSupersamplingAngleOffset */ 0.0f,
/* temporalSupersamplingRadiusOffset */ 0.0f,
/* detailShadowStrength */ 0.5f,
/* generateNormals */ FFX_CACAO_FALSE,
/* bilateralSigmaSquared */ 5.0f,
/* bilateralSimilarityDistanceSigma */ 0.01f,
};
/**
A C++ structure for the constant buffer used by FidelityFX CACAO.
*/
typedef struct FFX_CACAO_Constants {
float DepthUnpackConsts[2];
float CameraTanHalfFOV[2];
float NDCToViewMul[2];
float NDCToViewAdd[2];
float DepthBufferUVToViewMul[2];
float DepthBufferUVToViewAdd[2];
float EffectRadius;
float EffectShadowStrength;
float EffectShadowPow;
float EffectShadowClamp;
float EffectFadeOutMul;
float EffectFadeOutAdd;
float EffectHorizonAngleThreshold;
float EffectSamplingRadiusNearLimitRec;
float DepthPrecisionOffsetMod;
float NegRecEffectRadius;
float LoadCounterAvgDiv;
float AdaptiveSampleCountLimit;
float InvSharpness;
int PassIndex;
float BilateralSigmaSquared;
float BilateralSimilarityDistanceSigma;
float PatternRotScaleMatrices[5][4];
float NormalsUnpackMul;
float NormalsUnpackAdd;
float DetailAOStrength;
float Dummy0;
float SSAOBufferDimensions[2];
float SSAOBufferInverseDimensions[2];
float DepthBufferDimensions[2];
float DepthBufferInverseDimensions[2];
int DepthBufferOffset[2];
float PerPassFullResUVOffset[2];
float InputOutputBufferDimensions[2];
float InputOutputBufferInverseDimensions[2];
float ImportanceMapDimensions[2];
float ImportanceMapInverseDimensions[2];
float DeinterleavedDepthBufferDimensions[2];
float DeinterleavedDepthBufferInverseDimensions[2];
float DeinterleavedDepthBufferOffset[2];
float DeinterleavedDepthBufferNormalisedOffset[2];
FFX_CACAO_Matrix4x4 NormalsWorldToViewspaceMatrix;
} FFX_CACAO_Constants;
/**
A structure containing sizes of each of the buffers used by FidelityFX CACAO.
*/
typedef struct FFX_CACAO_BufferSizeInfo {
uint32_t inputOutputBufferWidth;
uint32_t inputOutputBufferHeight;
uint32_t ssaoBufferWidth;
uint32_t ssaoBufferHeight;
uint32_t depthBufferXOffset;
uint32_t depthBufferYOffset;
uint32_t depthBufferWidth;
uint32_t depthBufferHeight;
uint32_t deinterleavedDepthBufferXOffset;
uint32_t deinterleavedDepthBufferYOffset;
uint32_t deinterleavedDepthBufferWidth;
uint32_t deinterleavedDepthBufferHeight;
uint32_t importanceMapWidth;
uint32_t importanceMapHeight;
uint32_t downsampledSsaoBufferWidth;
uint32_t downsampledSsaoBufferHeight;
} FFX_CACAO_BufferSizeInfo;
#ifdef __cplusplus
extern "C"
{
#endif
/**
Update buffer size info for resolution width x height.
\code{.cpp}
FFX_CACAO_BufferSizeInfo bufferSizeInfo = {};
FFX_CACAO_UpdateBufferSizeInfo(width, height, useDownsampledSsao, &bufferSizeInfo);
\endcode
\param width Screen width.
\param height Screen height.
\param useDownsampledSsao Whether FFX CACAO should use downsampling.
*/
void FFX_CACAO_UpdateBufferSizeInfo(uint32_t width, uint32_t height, FFX_CACAO_Bool useDownsampledSsao, FFX_CACAO_BufferSizeInfo* bsi);
/**
Update the contents of the FFX CACAO constant buffer (an FFX_CACAO_Constants struct). Note, this function does not update
per pass constants.
\code{.cpp}
FFX_CACAO_Matrix4x4 proj = ...; // projection matrix for the frame
FFX_CACAO_Matrix4x4 normalsToView = ...; // normals world space to view space matrix for the frame
FFX_CACAO_Settings settings = ...; // settings
FFX_CACAO_BufferSizeInfo bufferSizeInfo = ...; // buffer size info
FFX_CACAO_Constants constants = {};
FFX_CACAO_UpdateConstants(&constants, &settings, &bufferSizeInfo, &proj, &normalsToView);
\endcode
\param consts FFX_CACAO_Constants constant buffer.
\param settings FFX_CACAO_Settings settings.
\param bufferSizeInfo FFX_CACAO_BufferSizeInfo buffer size info.
\param proj Projection matrix for the frame.
\param normalsToView Normals world space to view space matrix for the frame.
*/
void FFX_CACAO_UpdateConstants(FFX_CACAO_Constants* consts, const FFX_CACAO_Settings* settings, const FFX_CACAO_BufferSizeInfo* bufferSizeInfo, const FFX_CACAO_Matrix4x4* proj, const FFX_CACAO_Matrix4x4* normalsToView);
/**
Update the contents of the FFX CACAO constant buffer (an FFX_CACAO_Constants struct) with per pass constants.
FFX CACAO runs 4 passes which use different constants. It is recommended to have four separate FFX_CACAO_Constants structs
each filled with constants for each of the 4 passes.
\code{.cpp}
FFX_CACAO_Settings settings = ...; // settings
FFX_CACAO_BufferSizeInfo bufferSizeInfo = ...; // buffer size info
FFX_CACAO_Constants perPassConstants[4] = {};
for (int i = 0; i < 4; ++i) {
FFX_CACAO_UpdatePerPassConstants(&perPassConstants[i], &settings, &bufferSizeInfo, i);
}
\endcode
\param consts FFX_CACAO_Constants constants buffer.
\param settings FFX_CACAO_Settings settings.
\param bufferSizeInfo FFX_CACAO_BufferSizeInfo buffer size info.
\param pass pass number.
*/
void FFX_CACAO_UpdatePerPassConstants(FFX_CACAO_Constants* consts, const FFX_CACAO_Settings* settings, const FFX_CACAO_BufferSizeInfo* bufferSizeInfo, int pass);
#ifdef __cplusplus
}
#endif
-312
View File
@@ -1,312 +0,0 @@
// Modifications Copyright © 2021. Advanced Micro Devices, Inc. All Rights Reserved.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016, Intel Corporation
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File changes (yyyy-mm-dd)
// 2016-09-07: filip.strugar@intel.com: first commit
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \file */
#pragma once
#include "ffx_cacao.h"
// #define FFX_CACAO_ENABLE_PROFILING
// #define FFX_CACAO_ENABLE_D3D12
// #define FFX_CACAO_ENABLE_VULKAN
#ifdef FFX_CACAO_ENABLE_D3D12
#include <d3d12.h>
#endif
#ifdef FFX_CACAO_ENABLE_VULKAN
#include <vulkan/vulkan.h>
#endif
/**
The return codes for the API functions.
*/
typedef enum FFX_CACAO_Status {
FFX_CACAO_STATUS_OK = 0,
FFX_CACAO_STATUS_INVALID_ARGUMENT = -1,
FFX_CACAO_STATUS_INVALID_POINTER = -2,
FFX_CACAO_STATUS_OUT_OF_MEMORY = -3,
FFX_CACAO_STATUS_FAILED = -4,
} FFX_CACAO_Status;
#ifdef FFX_CACAO_ENABLE_D3D12
/**
A struct containing all of the data used by FidelityFX-CACAO.
A context corresponds to an ID3D12Device.
*/
typedef struct FFX_CACAO_D3D12Context FFX_CACAO_D3D12Context;
/**
The parameters for creating a context.
*/
typedef struct FFX_CACAO_D3D12ScreenSizeInfo {
uint32_t width; ///< width of the input/output buffers
uint32_t height; ///< height of the input/output buffers
ID3D12Resource *depthBufferResource; ///< pointer to depth buffer ID3D12Resource
D3D12_SHADER_RESOURCE_VIEW_DESC depthBufferSrvDesc; ///< depth buffer D3D12_SHADER_RESOURCE_VIEW_DESC
ID3D12Resource *normalBufferResource; ///< optional pointer to normal buffer ID3D12Resource (leave as NULL if none is provided)
D3D12_SHADER_RESOURCE_VIEW_DESC normalBufferSrvDesc; ///< normal buffer D3D12_SHADER_RESOURCE_VIEW_DESC
ID3D12Resource *outputResource; ///< pointer to output buffer ID3D12Resource
D3D12_UNORDERED_ACCESS_VIEW_DESC outputUavDesc; ///< output buffer D3D12_UNORDERED_ACCESS_VIEW_DESC
FFX_CACAO_Bool useDownsampledSsao; ///< Whether SSAO should be generated at native resolution or half resolution. It is recommended to enable this setting for improved performance.
} FFX_CACAO_D3D12ScreenSizeInfo;
#endif
#ifdef FFX_CACAO_ENABLE_VULKAN
/**
A struct containing all of the data used by FidelityFX-CACAO.
A context corresponds to a VkDevice.
*/
typedef struct FFX_CACAO_VkContext FFX_CACAO_VkContext;
/**
Miscellaneous flags for used for Vulkan context creation by FidelityFX-CACAO
*/
typedef enum FFX_CACAO_VkCreateFlagsBits {
FFX_CACAO_VK_CREATE_USE_16_BIT = 0x00000001, ///< Flag controlling whether 16-bit optimisations are enabled in shaders.
FFX_CACAO_VK_CREATE_USE_DEBUG_MARKERS = 0x00000002, ///< Flag controlling whether debug markers should be used.
FFX_CACAO_VK_CREATE_NAME_OBJECTS = 0x00000004, ///< Flag controlling whether Vulkan objects should be named.
} FFX_CACAO_VkCreateFlagsBits;
typedef uint32_t FFX_CACAO_VkCreateFlags;
/**
The parameters for creating a context.
*/
typedef struct FFX_CACAO_VkCreateInfo {
VkPhysicalDevice physicalDevice; ///< The VkPhysicalDevice corresponding to the VkDevice in use
VkDevice device; ///< The VkDevice to use FFX CACAO with
FFX_CACAO_VkCreateFlags flags; ///< Miscellaneous flags for context creation
} FFX_CACAO_VkCreateInfo;
/**
The parameters necessary when changing the screen size of FidelityFX CACAO.
*/
typedef struct FFX_CACAO_VkScreenSizeInfo {
uint32_t width; ///< width of the input/output buffers
uint32_t height; ///< height of the input/output buffers
VkImageView depthView; ///< An image view for the depth buffer, should be in layout VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL when used with FFX CACAO
VkImageView normalsView; ///< An optional image view for the normal buffer (may be VK_NULL_HANDLE). Should be in layout VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL when used with FFX CACAO
VkImage output; ///< An image for writing output from FFX CACAO, must have the same dimensions as the input
VkImageView outputView; ///< An image view corresponding to the output image.
FFX_CACAO_Bool useDownsampledSsao; ///< Whether SSAO should be generated at native resolution or half resolution. It is recommended to enable this setting for improved performance.
} FFX_CACAO_VkScreenSizeInfo;
#endif
#ifdef FFX_CACAO_ENABLE_PROFILING
/**
A timestamp. The label gives the name of the stage of the effect, and the ticks is the number of GPU ticks spent on that stage.
*/
typedef struct FFX_CACAO_Timestamp {
const char *label; ///< name of timestamp stage
uint64_t ticks; ///< number of GPU ticks taken for stage
} FFX_CACAO_Timestamp;
/**
An array of timestamps for detailed profiling information. The array timestamps contains numTimestamps entries.
Entry 0 of the timestamps array is guaranteed to be the total time taken by the effect.
*/
typedef struct FFX_CACAO_DetailedTiming {
uint32_t numTimestamps; ///< number of timetstamps in the array timestamps
FFX_CACAO_Timestamp timestamps[32]; ///< array of timestamps for each FFX CACAO stage
} FFX_CACAO_DetailedTiming;
#endif
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef FFX_CACAO_ENABLE_D3D12
/**
Gets the size in bytes required by a context. This is to be used to allocate space for the context.
For example:
\code{.cpp}
size_t FFX_CACAO_D3D12ContextSize = ffxCacaoD3D12GetContextSize();
FFX_CACAO_D3D12Context *context = (FFX_CACAO_D3D12Context*)malloc(FFX_CACAO_D3D12GetContextSize);
// ...
FFX_CACAO_D3D12DestroyContext(context);
free(context);
\endcode
\return The size in bytes of an FFX_CACAO_D3D12Context.
*/
size_t FFX_CACAO_D3D12GetContextSize();
/**
Initialises an FFX_CACAO_D3D12Context.
\param context A pointer to the context to initialise.
\param device A pointer to the D3D12 device.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_D3D12InitContext(FFX_CACAO_D3D12Context* context, ID3D12Device* device);
/**
Destroys an FFX_CACAO_D3D12Context.
\param context A pointer to the context to be destroyed.
\return The corresponding error code.
\note This function does not destroy screen size dependent resources, and must be called after FFX_CACAO_D3D12DestroyScreenSizeDependentResources.
*/
FFX_CACAO_Status FFX_CACAO_D3D12DestroyContext(FFX_CACAO_D3D12Context* context);
/**
Initialises screen size dependent resources for the FFX_CACAO_D3D12Context.
\param context A pointer to the FFX_CACAO_D3D12Context.
\param info A pointer to an FFX_CACAO_D3D12ScreenSizeInfo struct containing screen size info.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_D3D12InitScreenSizeDependentResources(FFX_CACAO_D3D12Context* context, const FFX_CACAO_D3D12ScreenSizeInfo* info);
/**
Destroys screen size dependent resources for the FFX_CACAO_D3D12Context.
\param context A pointer to the FFX_CACAO_D3D12Context.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_D3D12DestroyScreenSizeDependentResources(FFX_CACAO_D3D12Context* context);
/**
Update the settings of the FFX_CACAO_D3D12Context to those stored in the FFX_CACAO_Settings struct.
\param context A pointer to the FFX_CACAO_D3D12Context to update.
\param settings A pointer to the FFX_CACAO_Settings struct containing the new settings.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_D3D12UpdateSettings(FFX_CACAO_D3D12Context* context, const FFX_CACAO_Settings* settings);
/**
Append commands for drawing FFX CACAO to the provided ID3D12GraphicsCommandList.
\param context A pointer to the FFX_CACAO_D3D12Context.
\param commandList A pointer to the ID3D12GraphicsCommandList to append commands to.
\param proj A pointer to the projection matrix.
\param normalsToView An optional pointer to a matrix for transforming normals to in the normal buffer to viewspace.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_D3D12Draw(FFX_CACAO_D3D12Context* context, ID3D12GraphicsCommandList* commandList, const FFX_CACAO_Matrix4x4* proj, const FFX_CACAO_Matrix4x4* normalsToView);
#if FFX_CACAO_ENABLE_PROFILING
/**
Get detailed performance timings from the previous frame.
\param context A pointer to the FFX_CACAO_D3D12Context.
\param timings A pointer to an FFX_CACAO_DetailedTiming struct to fill in with detailed timings.
\result The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_D3D12GetDetailedTimings(FFX_CACAO_D3D12Context* context, FFX_CACAO_DetailedTiming* timings);
#endif
#endif
#ifdef FFX_CACAO_ENABLE_VULKAN
/**
Gets the size in bytes required by a Vulkan context. This is to be used to allocate space for the context.
For example:
\code{.cpp}
size_t FFX_CACAO_VkContextSize = ffxCacaoVkGetContextSize();
FFX_CACAO_VkContext *context = (FFX_CACAO_VkContext*)malloc(FFX_CACAO_VkGetContextSize);
// ...
FFX_CACAO_VkDestroyContext(context);
free(context);
\endcode
\return The size in bytes of an FFX_CACAO_VkContext.
*/
size_t FFX_CACAO_VkGetContextSize();
/**
Initialises an FFX_CACAO_VkContext.
\param context A pointer to the context to initialise.
\param info A pointer to an FFX_CACAO_VkCreateInfo struct with parameters such as the vulkan device.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_VkInitContext(FFX_CACAO_VkContext* context, const FFX_CACAO_VkCreateInfo *info);
/**
Destroys an FFX_CACAO_VkContext.
\param context A pointer to the context to be destroyed.
\return The corresponding error code.
\note This function does not destroy screen size dependent resources, and must be called after FFX_CACAO_VkDestroyScreenSizeDependentResources.
*/
FFX_CACAO_Status FFX_CACAO_VkDestroyContext(FFX_CACAO_VkContext* context);
/**
Initialises screen size dependent resources for the FFX_CACAO_VkContext.
\param context A pointer to the FFX_CACAO_VkContext.
\param info A pointer to an FFX_CACAO_VkScreenSizeInfo struct containing screen size info.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_VkInitScreenSizeDependentResources(FFX_CACAO_VkContext* context, const FFX_CACAO_VkScreenSizeInfo* info);
/**
Destroys screen size dependent resources for the FFX_CACAO_VkContext.
\param context A pointer to the FFX_CACAO_VkContext.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_VkDestroyScreenSizeDependentResources(FFX_CACAO_VkContext* context);
/**
Update the settings of the FFX_CACAO_VkContext to those stored in the FFX_CACAO_Settings struct.
\param context A pointer to the FFX_CACAO_VkContext to update.
\param settings A pointer to the FFX_CACAO_Settings struct containing the new settings.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_VkUpdateSettings(FFX_CACAO_VkContext* context, const FFX_CACAO_Settings* settings);
/**
Append commands for drawing FFX CACAO to the provided VkCommandBuffer.
\param context A pointer to the FFX_CACAO_VkContext.
\param commandList The VkCommandBuffer to append commands to.
\param proj A pointer to the projection matrix.
\param normalsToView An optional pointer to a matrix for transforming normals to in the normal buffer to viewspace.
\return The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_VkDraw(FFX_CACAO_VkContext* context, VkCommandBuffer commandList, const FFX_CACAO_Matrix4x4* proj, const FFX_CACAO_Matrix4x4* normalsToView);
#ifdef FFX_CACAO_ENABLE_PROFILING
/**
Get detailed performance timings from the previous frame.
\param context A pointer to the FFX_CACAO_VkContext.
\param timings A pointer to an FFX_CACAO_DetailedTiming struct to fill in with detailed timings.
\result The corresponding error code.
*/
FFX_CACAO_Status FFX_CACAO_VkGetDetailedTimings(FFX_CACAO_VkContext* context, FFX_CACAO_DetailedTiming* timings);
#endif
#endif
#ifdef __cplusplus
}
#endif
-196
View File
@@ -1,196 +0,0 @@
# FidelityFX CACAO
The **FidelityFX CACAO** library implements screen space ambient occlusion for use in real time applications. A full sample can be found on the [FidelityFX CACAO Github page](https://github.com/GPUOpen-Effects/FidelityFX-CACAO).
# Project Integration
FidelityFX CACAO comes with two main header files, `ffx-cacao/inc/ffx_cacao.h` and `ffx-cacao/inc/ffx_cacao_impl.h`. The file `ffx-cacao/inc/ffx_cacao.h` contains reusable C++ functions and struct definitions for integration of FidelityFX CACAO into custom engines. The functions declared in this header file are defined in `ffx-cacao/src/ffx_cacao.cpp`. The header file `ffx-cacao/inc/ffx_cacao_impl.h` is for use in quick integration of FidelityFX CACAO into DX12 and Vulkan engines. The functions declared in this file are defined in `ffx-cacao/src/ffx_cacao_impl.cpp`, which serves as a reference implementation of FidelityFX CACAO.
# Reusable Functions and Structs
The reusable functions and structs provided in `ffx-cacao/src/ffx_cacao.h` are documented via doxygen comments in the header file itself. The functions and structs are used to initialise the constant buffers used by FidelityFX CACAO from a user friendly settings struct `FFX_CACAO_Settings`.
# Reference Implementation
The reference implementation of FidelityFX CACAO supports three compile time options. These are:
```C++
FFX_CACAO_ENABLE_D3D12
FFX_CACAO_ENABLE_VK
FFX_CACAO_ENABLE_PROFILING
```
For use with D3D12 or Vulkan, the symbols `FFX_CACAO_ENABLE_D3D12` or `FFX_CACAO_ENABLE_VK` must be defined. If you wish to get detailed timings from FFX CACAO the symbol `FFX_CACAO_ENABLE_PROFILING` must be defined. These symbols can either be defined in the header `ffx-cacao/inc/ffx_cacao_impl.h` itself by uncommenting the respective definitions, or they can defined in compiler flags. The provided sample of FFX CACAO defines these symbols using compiler flags.
# Context Initialisation and Shutdown
First the FFX CACAO header must be included. This can be found at `ffx-cacao/inc/ffx_cacao_impl.h`. Then a context must be created. This is usually done only once per device. To create a context you must first query for the size of a context, allocate space for a context, then inintialise the context.
For D3D12 the initialisation and shutdown processes are as follows:
```C++
// initialisation
size_t ffxCacaoContextSize = ffxCacaoD3D12GetContextSize();
FfxCacaoD3D12Context *context = (FfxCacaoD3D12Context*)malloc(ffxCacaoContextSize);
assert(context);
FfxCacaoStatus status = ffxCacaoD3D12InitContext(context, d3d12Device);
assert(status == FFX_CACAO_STATUS_OK);
...
// finalisation
status = ffxCacaoD3D12DestroyContext(context);
assert(status == FFX_CACAO_STATUS_OK);
free(context);
```
The only argument required for initialisation of a D3D12 context is an `ID3D12Device*` for the D3D12 device.
For Vulkan the initialisation and shutdown processes are as follows:
```C++
// initialisation
size_t ffxCacaoContextSize = ffxCacaoVkGetContextSize();
FfxCacaoVkContext *context = (FfxCacaoVkContext*)malloc(ffxCacaoContextSize);
assert(context);
FfxCacaoVkCreateInfo info = {};
info.physicalDevice = vkPhysicalDevice;
info.device = vkDevice;
info.flags = FFX_CACAO_VK_CREATE_USE_16_BIT | FFX_CACAO_VK_CREATE_USE_DEBUG_MARKERS | FFX_CACAO_VK_CREATE_NAME_OBJECTS;
FfxCacaoStatus status = ffxCacaoVkInitContext(context, &info);
assert(status == FFX_CACAO_STATUS_OK);
...
// finalisation
status = ffxCacaoVkDestroyContext(context);
assert(status == FFX_CACAO_STATUS_OK);
free(context);
```
To initialise the FFX CACAO context in Vulkan, the parameters of the `FfxCacaoVkCreateInfo` struct must be filled in. These are the Vulkan physical device and Vulkan device, and a field of flags. The flags is a bitwise combination of the following options. The option `FFX_CACAO_VK_CREATE_USE_16_BIT` enables 16 bit optimisations, and requires a Vulkan device created using 16 bit extensions. This option is strongly recommended for compatible devices. The options `FFX_CACAO_VK_CREATE_USE_DEBUG_MARKERS` and `FFX_CACAO_VK_CREATE_NAME_OBJECTS` will add debug markers and name objects (e.g. textures, shaders) to aid inspection of FFX CACAO with a frame debugger.
# Screen Size Dependent Resource Initialisation
Once the context is initialised, it will need to have screen size dependent resources initialised each time the screen size is changed. To do this, an `FfxCacaoD3D12ScreenSizeInfo` struct must be filled out. The FFX CACAO effect is computed using a depth buffer and optional normal buffer. FFX CACAO writes its output to a user provided output buffer. The depth buffer, normal buffer and output buffer provided to FFX CACAO must all be the same size.
For FFX CACAO D3D12, the process is as follows:
```C++
// initialisation
FfxCacaoD3D12ScreenSizeInfo screenSizeInfo = {};
screenSizeInfo.width = /* width of the input/output buffers */;
screenSizeInfo.height = /* height of the input/output buffers */;
screenSizeInfo.depthBufferResource = /* ID3D12Resource* for the depth input buffer */;
screenSizeInfo.depthBufferSrvDesc = /* D3D12_SHADER_RESOURCE_VIEW_DESC for the depth input buffer */;
screenSizeInfo.normalBufferResource = /* ID3D12Resource* for the normal input buffer - or NULL if none shall be provided */;
screenSizeInfo.normalBufferSrvDesc = /* D3D12_SHADER_RESOURCE_VIEW_DESC for the normal input buffer */;
screenSizeInfo.outputResource = /* ID3D12Resource* for the output buffer */;
screenSizeInfo.depthBufferSrvDesc = /* D3D12_SHADER_RESOURCE_VIEW_DESC for the depth output */;
status = ffxCacaoD3D12InitScreenSizeDependentResources(context, &screenSizeInfo);
assert(status == FFX_CACAO_STATUS_OK);
...
// finalisation
status = ffxCacaoD3D12DestroyScreenSizeDependentResources(context);
assert(status == FFX_CACAO_STATUS_OK);
```
For FFX CACAO Vulkan, the process is as follows:
```C++
// Initialisation
FfxCacaoVkScreenSizeInfo screenSizeInfo = {};
screenSizeInfo.width = /* width of the input/output buffers */;
screenSizeInfo.height = /* height of the input/output buffers */;
screenSizeInfo.depthView = /* a VkImageView for the depth buffer, should be in layout VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL */;
screenSizeInfo.normalsView = /* an optional VkImageView for the normal buffer (VK_NULL_HANDLE if not provided), should be in layout VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL */;
screenSizeInfo.output = /* a VkImage for writing the output of FFX CACAO */;
screenSizeInfo.outputView = /* a VkImageView corresponding to the VkImage for writing the output of FFX CACAO */;
status = ffxCacaoVkInitScreenSizeDependentResources(context, &screenSizeInfo);
assert(status == FFX_CACAO_STATUS_OK);
...
// finalisation
status = ffxCacaoVkDestroyScreenSizeDependentResources(context);
assert(status == FFX_CACAO_STATUS_OK);
```
# Initialising/Updating FFX CACAO Settings
The settings for the FFX CACAO effect may be changed via the `FfxCacaoSettings` struct and the `ffxCacaoD3D12UpdateSettings` or `ffxCacaoVkUpdateSettings` functions as follows.
```C++
FfxCacaoSettings settings = {};
settings.radius = /* world view radius of the occlusion sphere */;
settings.shadowMultiplier = /* effect strength linear multiplier */;
settings.shadowPower = /* effect strength power multiplier */;
settings.shadowClamp = /* effect max limit */;
settings.horizonAngleThreshold = /* minimum horizon angle for contributions to occlusion to limit self shadowing */
settings.fadeOutFrom = /* effect fade out from world space distance */;
settings.fadeOutTo = /* effect fade out to world space distance */;
settings.qualityLevel = /* the quality of the effect, ranging from lowest to highest (adaptive). This affects the number of samples taken to generate SSAO. */;
settings.adaptiveQualityLimit = /* quality limit for adaptive quality */;
settings.blurPassCount = /* a number of edge sensitive blurs from 1 to 8 to perform after SSAO generation */;
settings.sharpness = /* how much to bleed over edges - 0 = ignore edges, 1 = don't bleed over edges */;
settings.temporalSupersamplingAngleOffset = /* sampling angle offset for temporal super sampling */;
settings.temporalSupersamplingRaidusOffset = /* sampling effect radius offset for temporal super sampling */;
settings.detailShadowStrength = /* used to generate details in high res AO */;
settings.generateNormals = /* should the effect generate normals from the depth buffer or use a provided normal buffer */;
settings.bilateralSigmaSquared = /* a parameter for use in bilateral upsampling. Higher values create more blur to help reduce noise */;
settings.bilateralSimilarityDistanceSigma = /* a parameter for use in bilateral upsampling. Lower values create reduce bluring across edge boundaries */;
```
These settings can be set to sensible defaults from the constant `FFX_CACAO_DEFAULT_SETTINGS` and updated using the function `ffxCacaoD3D12UpdateSettings` or `ffxCacaoVkUpdateSettings` as follows.
```C++
FfxCacaoSettings settings = FFX_CACAO_DEFAULT_SETTINGS;
status = ffxCacaoD3D12UpdateSettings(context, &settings);
assert(status == FFX_CACAO_STATUS_OK);
```
Note that the `FFX_CACAO_DEFAULT_SETTINGS` provides a sensible quick start for high quality settings. The parameters `radius`, `fadeOutFrom` and `fadeOutTo` should
be changed to match the world space of the target scene, and the parameter `blurPassCount` is recommended to be increased for lower quality settings. A more complete
set of sensible defaults may be found in the FFX CACAO sample in the file `sample/src/Common/FFX_CACAO_Common.h`, where multiple parameters have been varied to move
from high to low quality presets.
# Drawing
In D3D12, FFX CACAO can be called to add commands to a `ID3D12GraphicsCommandList` using the `ffxCacaoD3D12Draw` function as follows:
```C++
FfxCacaoMatrix4x4 proj = /* row major projection matrix */;
FfxCacaoMatrix4x4 normalsToView = /* row major matrix to convert normals to viewspace */
status = ffxCacaoD3D12Draw(context, commandList, &proj, &normalsToView);
assert(status == FFX_CACAO_STATUS_OK);
```
In Vulkan, FFX CACAO can add commands to a `VkCommandBuffer` using the `ffxCacaoVkDraw` function as follows:
```C++
FfxCacaoMatrix4x4 proj = /* row major projection matrix */;
FfxCacaoMatrix4x4 normalsToView = /* row major matrix to convert normals to viewspace */
status = ffxCacaoVkDraw(context, commandBuffer, &proj, &normalsToView);
assert(status == FFX_CACAO_STATUS_OK);
```
The matrix `proj` is the projection matrix used from viewspace to normalised device coordinates. The matrix `normalsToView` is a matrix to convert the normals provided in the normal buffer to viewspace.
# Profiling
Finally, if the preprocessor symbol `FFX_CACAO_ENABLE_PROFILING` is defined, then detailed timings can be read from FFX CACAO using the functions `ffxCacaoD3D12GetDetailedTimings` and `ffxCacaoVkGetDetailedTimings` for D3D12 and Vulkan respectively. These functions should be called as follows:
```C++
FfxCacaoDetailedTiming timings = {};
uint64_t gpuTicksPerMicrosecond;
FfxCacaoStatus status = ffxCacaoD3D12GetDetailedTimings(context, &timings, &gpuTicksPerMicrosecond);
assert(status == FFX_CACAO_STATUS_OK);
```
The timings returned are in GPU ticks. These can be converted into seconds using the value returned in the `gpuTicksPerMicrosecond` parameter above.
Or in Vulkan:
```C++
FfxCacaoDetailedTiming timings = {};
FfxCacaoStatus status = ffxCacaoD3D12GetDetailedTimings(context, &timings);
assert(status == FFX_CACAO_STATUS_OK);
```
The timings returned are measured in GPU ticks, and will need to be converted using th GPU ticks per microsecond parameter available from `vkGetPhysicalDeviceLimits`.
-55
View File
@@ -1,55 +0,0 @@
%echo off
pushd %~dp0
set cauldron_dxc=..\..\sample\libs\cauldron\libs\DXC\bin\dxc.exe -T cs_6_2
if not exist "PrecompiledShadersDXIL" mkdir "PrecompiledShadersDXIL"
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOClearLoadCounter.h -Vn CSClearLoadCounterDXIL -E FFX_CACAO_ClearLoadCounter ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareDownsampledDepths.h -Vn CSPrepareDownsampledDepthsDXIL -E FFX_CACAO_PrepareDownsampledDepths ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareNativeDepths.h -Vn CSPrepareNativeDepthsDXIL -E FFX_CACAO_PrepareNativeDepths ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareDownsampledDepthsAndMips.h -Vn CSPrepareDownsampledDepthsAndMipsDXIL -E FFX_CACAO_PrepareDownsampledDepthsAndMips ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareNativeDepthsAndMips.h -Vn CSPrepareNativeDepthsAndMipsDXIL -E FFX_CACAO_PrepareNativeDepthsAndMips ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareDownsampledNormals.h -Vn CSPrepareDownsampledNormalsDXIL -E FFX_CACAO_PrepareDownsampledNormals ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareNativeNormals.h -Vn CSPrepareNativeNormalsDXIL -E FFX_CACAO_PrepareNativeNormals ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareDownsampledNormalsFromInputNormals.h -Vn CSPrepareDownsampledNormalsFromInputNormalsDXIL -E FFX_CACAO_PrepareDownsampledNormalsFromInputNormals ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareNativeNormalsFromInputNormals.h -Vn CSPrepareNativeNormalsFromInputNormalsDXIL -E FFX_CACAO_PrepareNativeNormalsFromInputNormals ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareDownsampledDepthsHalf.h -Vn CSPrepareDownsampledDepthsHalfDXIL -E FFX_CACAO_PrepareDownsampledDepthsHalf ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPrepareNativeDepthsHalf.h -Vn CSPrepareNativeDepthsHalfDXIL -E FFX_CACAO_PrepareNativeDepthsHalf ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOGenerateQ0.h -Vn CSGenerateQ0DXIL -E FFX_CACAO_GenerateQ0 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOGenerateQ1.h -Vn CSGenerateQ1DXIL -E FFX_CACAO_GenerateQ1 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOGenerateQ2.h -Vn CSGenerateQ2DXIL -E FFX_CACAO_GenerateQ2 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOGenerateQ3.h -Vn CSGenerateQ3DXIL -E FFX_CACAO_GenerateQ3 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOGenerateQ3Base.h -Vn CSGenerateQ3BaseDXIL -E FFX_CACAO_GenerateQ3Base ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOGenerateImportanceMap.h -Vn CSGenerateImportanceMapDXIL -E FFX_CACAO_GenerateImportanceMap ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPostprocessImportanceMapA.h -Vn CSPostprocessImportanceMapADXIL -E FFX_CACAO_PostprocessImportanceMapA ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOPostprocessImportanceMapB.h -Vn CSPostprocessImportanceMapBDXIL -E FFX_CACAO_PostprocessImportanceMapB ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOEdgeSensitiveBlur1.h -Vn CSEdgeSensitiveBlur1DXIL -E FFX_CACAO_EdgeSensitiveBlur1 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOEdgeSensitiveBlur2.h -Vn CSEdgeSensitiveBlur2DXIL -E FFX_CACAO_EdgeSensitiveBlur2 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOEdgeSensitiveBlur3.h -Vn CSEdgeSensitiveBlur3DXIL -E FFX_CACAO_EdgeSensitiveBlur3 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOEdgeSensitiveBlur4.h -Vn CSEdgeSensitiveBlur4DXIL -E FFX_CACAO_EdgeSensitiveBlur4 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOEdgeSensitiveBlur5.h -Vn CSEdgeSensitiveBlur5DXIL -E FFX_CACAO_EdgeSensitiveBlur5 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOEdgeSensitiveBlur6.h -Vn CSEdgeSensitiveBlur6DXIL -E FFX_CACAO_EdgeSensitiveBlur6 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOEdgeSensitiveBlur7.h -Vn CSEdgeSensitiveBlur7DXIL -E FFX_CACAO_EdgeSensitiveBlur7 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOEdgeSensitiveBlur8.h -Vn CSEdgeSensitiveBlur8DXIL -E FFX_CACAO_EdgeSensitiveBlur8 ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOApply.h -Vn CSApplyDXIL -E FFX_CACAO_Apply ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAONonSmartApply.h -Vn CSNonSmartApplyDXIL -E FFX_CACAO_NonSmartApply ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAONonSmartHalfApply.h -Vn CSNonSmartHalfApplyDXIL -E FFX_CACAO_NonSmartHalfApply ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOUpscaleBilateral5x5NonSmart.h -Vn CSUpscaleBilateral5x5NonSmartDXIL -E FFX_CACAO_UpscaleBilateral5x5NonSmart ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOUpscaleBilateral5x5Smart.h -Vn CSUpscaleBilateral5x5SmartDXIL -E FFX_CACAO_UpscaleBilateral5x5Smart ffx_cacao.hlsl
%cauldron_dxc% -Fh PrecompiledShadersDXIL/CACAOUpscaleBilateral5x5Half.h -Vn CSUpscaleBilateral5x5HalfDXIL -E FFX_CACAO_UpscaleBilateral5x5Half ffx_cacao.hlsl
popd
-103
View File
@@ -1,103 +0,0 @@
%echo off
pushd %~dp0
set cauldron_dxc_16=glslc -Wno-conversion -spirv -T cs_6_2 -enable-16bit-types -fspv-target-env=vulkan1.1 -fvk-s-shift 0 0 -fvk-b-shift 10 0 -fvk-t-shift 20 0 -fvk-u-shift 30 0
set cauldron_dxc_32=glslc -Wno-conversion -spirv -T cs_6_2 -fspv-target-env=vulkan1.1 -fvk-s-shift 0 0 -fvk-b-shift 10 0 -fvk-t-shift 20 0 -fvk-u-shift 30 0
if not exist "PrecompiledShadersSPIRV" mkdir "PrecompiledShadersSPIRV"
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOClearLoadCounter_16.h -Vn CSClearLoadCounterSPIRV16 -E FFX_CACAO_ClearLoadCounter ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledDepths_16.h -Vn CSPrepareDownsampledDepthsSPIRV16 -E FFX_CACAO_PrepareDownsampledDepths ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeDepths_16.h -Vn CSPrepareNativeDepthsSPIRV16 -E FFX_CACAO_PrepareNativeDepths ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledDepthsAndMips_16.h -Vn CSPrepareDownsampledDepthsAndMipsSPIRV16 -E FFX_CACAO_PrepareDownsampledDepthsAndMips ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeDepthsAndMips_16.h -Vn CSPrepareNativeDepthsAndMipsSPIRV16 -E FFX_CACAO_PrepareNativeDepthsAndMips ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledNormals_16.h -Vn CSPrepareDownsampledNormalsSPIRV16 -E FFX_CACAO_PrepareDownsampledNormals ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeNormals_16.h -Vn CSPrepareNativeNormalsSPIRV16 -E FFX_CACAO_PrepareNativeNormals ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledNormalsFromInputNormals_16.h -Vn CSPrepareDownsampledNormalsFromInputNormalsSPIRV16 -E FFX_CACAO_PrepareDownsampledNormalsFromInputNormals ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeNormalsFromInputNormals_16.h -Vn CSPrepareNativeNormalsFromInputNormalsSPIRV16 -E FFX_CACAO_PrepareNativeNormalsFromInputNormals ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledDepthsHalf_16.h -Vn CSPrepareDownsampledDepthsHalfSPIRV16 -E FFX_CACAO_PrepareDownsampledDepthsHalf ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeDepthsHalf_16.h -Vn CSPrepareNativeDepthsHalfSPIRV16 -E FFX_CACAO_PrepareNativeDepthsHalf ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ0_16.h -Vn CSGenerateQ0SPIRV16 -E FFX_CACAO_GenerateQ0 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ1_16.h -Vn CSGenerateQ1SPIRV16 -E FFX_CACAO_GenerateQ1 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ2_16.h -Vn CSGenerateQ2SPIRV16 -E FFX_CACAO_GenerateQ2 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ3_16.h -Vn CSGenerateQ3SPIRV16 -E FFX_CACAO_GenerateQ3 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ3Base_16.h -Vn CSGenerateQ3BaseSPIRV16 -E FFX_CACAO_GenerateQ3Base ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOGenerateImportanceMap_16.h -Vn CSGenerateImportanceMapSPIRV16 -E FFX_CACAO_GenerateImportanceMap ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPostprocessImportanceMapA_16.h -Vn CSPostprocessImportanceMapASPIRV16 -E FFX_CACAO_PostprocessImportanceMapA ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOPostprocessImportanceMapB_16.h -Vn CSPostprocessImportanceMapBSPIRV16 -E FFX_CACAO_PostprocessImportanceMapB ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur1_16.h -Vn CSEdgeSensitiveBlur1SPIRV16 -E FFX_CACAO_EdgeSensitiveBlur1 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur2_16.h -Vn CSEdgeSensitiveBlur2SPIRV16 -E FFX_CACAO_EdgeSensitiveBlur2 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur3_16.h -Vn CSEdgeSensitiveBlur3SPIRV16 -E FFX_CACAO_EdgeSensitiveBlur3 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur4_16.h -Vn CSEdgeSensitiveBlur4SPIRV16 -E FFX_CACAO_EdgeSensitiveBlur4 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur5_16.h -Vn CSEdgeSensitiveBlur5SPIRV16 -E FFX_CACAO_EdgeSensitiveBlur5 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur6_16.h -Vn CSEdgeSensitiveBlur6SPIRV16 -E FFX_CACAO_EdgeSensitiveBlur6 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur7_16.h -Vn CSEdgeSensitiveBlur7SPIRV16 -E FFX_CACAO_EdgeSensitiveBlur7 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur8_16.h -Vn CSEdgeSensitiveBlur8SPIRV16 -E FFX_CACAO_EdgeSensitiveBlur8 ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOApply_16.h -Vn CSApplySPIRV16 -E FFX_CACAO_Apply ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAONonSmartApply_16.h -Vn CSNonSmartApplySPIRV16 -E FFX_CACAO_NonSmartApply ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAONonSmartHalfApply_16.h -Vn CSNonSmartHalfApplySPIRV16 -E FFX_CACAO_NonSmartHalfApply ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOUpscaleBilateral5x5Smart_16.h -Vn CSUpscaleBilateral5x5SmartSPIRV16 -E FFX_CACAO_UpscaleBilateral5x5Smart ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOUpscaleBilateral5x5NonSmart_16.h -Vn CSUpscaleBilateral5x5NonSmartSPIRV16 -E FFX_CACAO_UpscaleBilateral5x5NonSmart ffx_cacao.hlsl
%cauldron_dxc_16% -Fh PrecompiledShadersSPIRV/CACAOUpscaleBilateral5x5Half_16.h -Vn CSUpscaleBilateral5x5HalfSPIRV16 -E FFX_CACAO_UpscaleBilateral5x5Half ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOClearLoadCounter_32.h -Vn CSClearLoadCounterSPIRV32 -E FFX_CACAO_ClearLoadCounter ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledDepths_32.h -Vn CSPrepareDownsampledDepthsSPIRV32 -E FFX_CACAO_PrepareDownsampledDepths ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeDepths_32.h -Vn CSPrepareNativeDepthsSPIRV32 -E FFX_CACAO_PrepareNativeDepths ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledDepthsAndMips_32.h -Vn CSPrepareDownsampledDepthsAndMipsSPIRV32 -E FFX_CACAO_PrepareDownsampledDepthsAndMips ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeDepthsAndMips_32.h -Vn CSPrepareNativeDepthsAndMipsSPIRV32 -E FFX_CACAO_PrepareNativeDepthsAndMips ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledNormals_32.h -Vn CSPrepareDownsampledNormalsSPIRV32 -E FFX_CACAO_PrepareDownsampledNormals ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeNormals_32.h -Vn CSPrepareNativeNormalsSPIRV32 -E FFX_CACAO_PrepareNativeNormals ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledNormalsFromInputNormals_32.h -Vn CSPrepareDownsampledNormalsFromInputNormalsSPIRV32 -E FFX_CACAO_PrepareDownsampledNormalsFromInputNormals ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeNormalsFromInputNormals_32.h -Vn CSPrepareNativeNormalsFromInputNormalsSPIRV32 -E FFX_CACAO_PrepareNativeNormalsFromInputNormals ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareDownsampledDepthsHalf_32.h -Vn CSPrepareDownsampledDepthsHalfSPIRV32 -E FFX_CACAO_PrepareDownsampledDepthsHalf ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPrepareNativeDepthsHalf_32.h -Vn CSPrepareNativeDepthsHalfSPIRV32 -E FFX_CACAO_PrepareNativeDepthsHalf ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ0_32.h -Vn CSGenerateQ0SPIRV32 -E FFX_CACAO_GenerateQ0 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ1_32.h -Vn CSGenerateQ1SPIRV32 -E FFX_CACAO_GenerateQ1 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ2_32.h -Vn CSGenerateQ2SPIRV32 -E FFX_CACAO_GenerateQ2 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ3_32.h -Vn CSGenerateQ3SPIRV32 -E FFX_CACAO_GenerateQ3 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOGenerateQ3Base_32.h -Vn CSGenerateQ3BaseSPIRV32 -E FFX_CACAO_GenerateQ3Base ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOGenerateImportanceMap_32.h -Vn CSGenerateImportanceMapSPIRV32 -E FFX_CACAO_GenerateImportanceMap ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPostprocessImportanceMapA_32.h -Vn CSPostprocessImportanceMapASPIRV32 -E FFX_CACAO_PostprocessImportanceMapA ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOPostprocessImportanceMapB_32.h -Vn CSPostprocessImportanceMapBSPIRV32 -E FFX_CACAO_PostprocessImportanceMapB ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur1_32.h -Vn CSEdgeSensitiveBlur1SPIRV32 -E FFX_CACAO_EdgeSensitiveBlur1 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur2_32.h -Vn CSEdgeSensitiveBlur2SPIRV32 -E FFX_CACAO_EdgeSensitiveBlur2 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur3_32.h -Vn CSEdgeSensitiveBlur3SPIRV32 -E FFX_CACAO_EdgeSensitiveBlur3 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur4_32.h -Vn CSEdgeSensitiveBlur4SPIRV32 -E FFX_CACAO_EdgeSensitiveBlur4 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur5_32.h -Vn CSEdgeSensitiveBlur5SPIRV32 -E FFX_CACAO_EdgeSensitiveBlur5 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur6_32.h -Vn CSEdgeSensitiveBlur6SPIRV32 -E FFX_CACAO_EdgeSensitiveBlur6 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur7_32.h -Vn CSEdgeSensitiveBlur7SPIRV32 -E FFX_CACAO_EdgeSensitiveBlur7 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOEdgeSensitiveBlur8_32.h -Vn CSEdgeSensitiveBlur8SPIRV32 -E FFX_CACAO_EdgeSensitiveBlur8 ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOApply_32.h -Vn CSApplySPIRV32 -E FFX_CACAO_Apply ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAONonSmartApply_32.h -Vn CSNonSmartApplySPIRV32 -E FFX_CACAO_NonSmartApply ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAONonSmartHalfApply_32.h -Vn CSNonSmartHalfApplySPIRV32 -E FFX_CACAO_NonSmartHalfApply ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOUpscaleBilateral5x5Smart_32.h -Vn CSUpscaleBilateral5x5SmartSPIRV32 -E FFX_CACAO_UpscaleBilateral5x5Smart ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOUpscaleBilateral5x5NonSmart_32.h -Vn CSUpscaleBilateral5x5NonSmartSPIRV32 -E FFX_CACAO_UpscaleBilateral5x5NonSmart ffx_cacao.hlsl
%cauldron_dxc_32% -Fh PrecompiledShadersSPIRV/CACAOUpscaleBilateral5x5Half_32.h -Vn CSUpscaleBilateral5x5HalfSPIRV32 -E FFX_CACAO_UpscaleBilateral5x5Half ffx_cacao.hlsl
popd
-263
View File
@@ -1,263 +0,0 @@
// Modifications Copyright © 2021. Advanced Micro Devices, Inc. All Rights Reserved.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016, Intel Corporation
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File changes (yyyy-mm-dd)
// 2016-09-07: filip.strugar@intel.com: first commit
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "ffx_cacao.h"
#include <assert.h>
#include <math.h> // cos, sin
#include <string.h> // memcpy
#include <stdio.h> // snprintf
// Define symbol to enable DirectX debug markers created using Cauldron
#define FFX_CACAO_ENABLE_CAULDRON_DEBUG
#define FFX_CACAO_ASSERT(exp) assert(exp)
#define FFX_CACAO_ARRAY_SIZE(xs) (sizeof(xs)/sizeof(xs[0]))
#define FFX_CACAO_COS(x) cosf(x)
#define FFX_CACAO_SIN(x) sinf(x)
#define FFX_CACAO_MIN(x, y) (((x) < (y)) ? (x) : (y))
#define FFX_CACAO_MAX(x, y) (((x) > (y)) ? (x) : (y))
#define FFX_CACAO_CLAMP(value, lower, upper) FFX_CACAO_MIN(FFX_CACAO_MAX(value, lower), upper)
#define FFX_CACAO_OFFSET_OF(T, member) (size_t)(&(((T*)0)->member))
#define MATRIX_ROW_MAJOR_ORDER 1
static const FFX_CACAO_Matrix4x4 FFX_CACAO_IDENTITY_MATRIX = {
{ { 1.0f, 0.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f } }
};
void FFX_CACAO_UpdateBufferSizeInfo(uint32_t width, uint32_t height, FFX_CACAO_Bool useDownsampledSsao, FFX_CACAO_BufferSizeInfo* bsi)
{
uint32_t halfWidth = (width + 1) / 2;
uint32_t halfHeight = (height + 1) / 2;
uint32_t quarterWidth = (halfWidth + 1) / 2;
uint32_t quarterHeight = (halfHeight + 1) / 2;
uint32_t eighthWidth = (quarterWidth + 1) / 2;
uint32_t eighthHeight = (quarterHeight + 1) / 2;
uint32_t depthBufferWidth = width;
uint32_t depthBufferHeight = height;
uint32_t depthBufferHalfWidth = halfWidth;
uint32_t depthBufferHalfHeight = halfHeight;
uint32_t depthBufferQuarterWidth = quarterWidth;
uint32_t depthBufferQuarterHeight = quarterHeight;
uint32_t depthBufferXOffset = 0;
uint32_t depthBufferYOffset = 0;
uint32_t depthBufferHalfXOffset = 0;
uint32_t depthBufferHalfYOffset = 0;
uint32_t depthBufferQuarterXOffset = 0;
uint32_t depthBufferQuarterYOffset = 0;
bsi->inputOutputBufferWidth = width;
bsi->inputOutputBufferHeight = height;
bsi->depthBufferXOffset = depthBufferXOffset;
bsi->depthBufferYOffset = depthBufferYOffset;
bsi->depthBufferWidth = depthBufferWidth;
bsi->depthBufferHeight = depthBufferHeight;
if (useDownsampledSsao)
{
bsi->ssaoBufferWidth = quarterWidth;
bsi->ssaoBufferHeight = quarterHeight;
bsi->deinterleavedDepthBufferXOffset = depthBufferQuarterXOffset;
bsi->deinterleavedDepthBufferYOffset = depthBufferQuarterYOffset;
bsi->deinterleavedDepthBufferWidth = depthBufferQuarterWidth;
bsi->deinterleavedDepthBufferHeight = depthBufferQuarterHeight;
bsi->importanceMapWidth = eighthWidth;
bsi->importanceMapHeight = eighthHeight;
bsi->downsampledSsaoBufferWidth = halfWidth;
bsi->downsampledSsaoBufferHeight = halfHeight;
}
else
{
bsi->ssaoBufferWidth = halfWidth;
bsi->ssaoBufferHeight = halfHeight;
bsi->deinterleavedDepthBufferXOffset = depthBufferHalfXOffset;
bsi->deinterleavedDepthBufferYOffset = depthBufferHalfYOffset;
bsi->deinterleavedDepthBufferWidth = depthBufferHalfWidth;
bsi->deinterleavedDepthBufferHeight = depthBufferHalfHeight;
bsi->importanceMapWidth = quarterWidth;
bsi->importanceMapHeight = quarterHeight;
bsi->downsampledSsaoBufferWidth = 1;
bsi->downsampledSsaoBufferHeight = 1;
}
}
void FFX_CACAO_UpdateConstants(FFX_CACAO_Constants* consts, const FFX_CACAO_Settings* settings, const FFX_CACAO_BufferSizeInfo* bufferSizeInfo, const FFX_CACAO_Matrix4x4* proj, const FFX_CACAO_Matrix4x4* normalsToView)
{
consts->BilateralSigmaSquared = settings->bilateralSigmaSquared;
consts->BilateralSimilarityDistanceSigma = settings->bilateralSimilarityDistanceSigma;
if (settings->generateNormals)
{
consts->NormalsWorldToViewspaceMatrix = FFX_CACAO_IDENTITY_MATRIX;
}
else
{
consts->NormalsWorldToViewspaceMatrix = *normalsToView;
}
// used to get average load per pixel; 9.0 is there to compensate for only doing every 9th InterlockedAdd in PSPostprocessImportanceMapB for performance reasons
consts->LoadCounterAvgDiv = 9.0f / (float)(bufferSizeInfo->importanceMapWidth * bufferSizeInfo->importanceMapHeight * 255.0);
float depthLinearizeMul = (MATRIX_ROW_MAJOR_ORDER) ? (-proj->elements[3][2]) : (-proj->elements[2][3]); // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
float depthLinearizeAdd = (MATRIX_ROW_MAJOR_ORDER) ? (proj->elements[2][2]) : (proj->elements[2][2]); // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
// correct the handedness issue. need to make sure this below is correct, but I think it is.
if (depthLinearizeMul * depthLinearizeAdd < 0)
depthLinearizeAdd = -depthLinearizeAdd;
consts->DepthUnpackConsts[0] = depthLinearizeMul;
consts->DepthUnpackConsts[1] = depthLinearizeAdd;
float tanHalfFOVY = 1.0f / proj->elements[1][1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
float tanHalfFOVX = 1.0F / proj->elements[0][0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
consts->CameraTanHalfFOV[0] = tanHalfFOVX;
consts->CameraTanHalfFOV[1] = tanHalfFOVY;
consts->NDCToViewMul[0] = consts->CameraTanHalfFOV[0] * 2.0f;
consts->NDCToViewMul[1] = consts->CameraTanHalfFOV[1] * -2.0f;
consts->NDCToViewAdd[0] = consts->CameraTanHalfFOV[0] * -1.0f;
consts->NDCToViewAdd[1] = consts->CameraTanHalfFOV[1] * 1.0f;
float ratio = ((float)bufferSizeInfo->inputOutputBufferWidth) / ((float)bufferSizeInfo->depthBufferWidth);
float border = (1.0f - ratio) / 2.0f;
for (int i = 0; i < 2; ++i)
{
consts->DepthBufferUVToViewMul[i] = consts->NDCToViewMul[i] / ratio;
consts->DepthBufferUVToViewAdd[i] = consts->NDCToViewAdd[i] - consts->NDCToViewMul[i] * border / ratio;
}
consts->EffectRadius = FFX_CACAO_CLAMP(settings->radius, 0.0f, 100000.0f);
consts->EffectShadowStrength = FFX_CACAO_CLAMP(settings->shadowMultiplier * 4.3f, 0.0f, 10.0f);
consts->EffectShadowPow = FFX_CACAO_CLAMP(settings->shadowPower, 0.0f, 10.0f);
consts->EffectShadowClamp = FFX_CACAO_CLAMP(settings->shadowClamp, 0.0f, 1.0f);
consts->EffectFadeOutMul = -1.0f / (settings->fadeOutTo - settings->fadeOutFrom);
consts->EffectFadeOutAdd = settings->fadeOutFrom / (settings->fadeOutTo - settings->fadeOutFrom) + 1.0f;
consts->EffectHorizonAngleThreshold = FFX_CACAO_CLAMP(settings->horizonAngleThreshold, 0.0f, 1.0f);
// 1.2 seems to be around the best trade off - 1.0 means on-screen radius will stop/slow growing when the camera is at 1.0 distance, so, depending on FOV, basically filling up most of the screen
// This setting is viewspace-dependent and not screen size dependent intentionally, so that when you change FOV the effect stays (relatively) similar.
float effectSamplingRadiusNearLimit = (settings->radius * 1.2f);
// if the depth precision is switched to 32bit float, this can be set to something closer to 1 (0.9999 is fine)
consts->DepthPrecisionOffsetMod = 0.9992f;
// Special settings for lowest quality level - just nerf the effect a tiny bit
if (settings->qualityLevel <= FFX_CACAO_QUALITY_LOW)
{
//consts.EffectShadowStrength *= 0.9f;
effectSamplingRadiusNearLimit *= 1.50f;
if (settings->qualityLevel == FFX_CACAO_QUALITY_LOWEST)
consts->EffectRadius *= 0.8f;
}
effectSamplingRadiusNearLimit /= tanHalfFOVY; // to keep the effect same regardless of FOV
consts->EffectSamplingRadiusNearLimitRec = 1.0f / effectSamplingRadiusNearLimit;
consts->AdaptiveSampleCountLimit = settings->adaptiveQualityLimit;
consts->NegRecEffectRadius = -1.0f / consts->EffectRadius;
consts->InvSharpness = FFX_CACAO_CLAMP(1.0f - settings->sharpness, 0.0f, 1.0f);
consts->DetailAOStrength = settings->detailShadowStrength;
// set buffer size constants.
consts->SSAOBufferDimensions[0] = (float)bufferSizeInfo->ssaoBufferWidth;
consts->SSAOBufferDimensions[1] = (float)bufferSizeInfo->ssaoBufferHeight;
consts->SSAOBufferInverseDimensions[0] = 1.0f / ((float)bufferSizeInfo->ssaoBufferWidth);
consts->SSAOBufferInverseDimensions[1] = 1.0f / ((float)bufferSizeInfo->ssaoBufferHeight);
consts->DepthBufferDimensions[0] = (float)bufferSizeInfo->depthBufferWidth;
consts->DepthBufferDimensions[1] = (float)bufferSizeInfo->depthBufferHeight;
consts->DepthBufferInverseDimensions[0] = 1.0f / ((float)bufferSizeInfo->depthBufferWidth);
consts->DepthBufferInverseDimensions[1] = 1.0f / ((float)bufferSizeInfo->depthBufferHeight);
consts->DepthBufferOffset[0] = bufferSizeInfo->depthBufferXOffset;
consts->DepthBufferOffset[1] = bufferSizeInfo->depthBufferYOffset;
consts->InputOutputBufferDimensions[0] = (float)bufferSizeInfo->inputOutputBufferWidth;
consts->InputOutputBufferDimensions[1] = (float)bufferSizeInfo->inputOutputBufferHeight;
consts->InputOutputBufferInverseDimensions[0] = 1.0f / ((float)bufferSizeInfo->inputOutputBufferWidth);
consts->InputOutputBufferInverseDimensions[1] = 1.0f / ((float)bufferSizeInfo->inputOutputBufferHeight);
consts->ImportanceMapDimensions[0] = (float)bufferSizeInfo->importanceMapWidth;
consts->ImportanceMapDimensions[1] = (float)bufferSizeInfo->importanceMapHeight;
consts->ImportanceMapInverseDimensions[0] = 1.0f / ((float)bufferSizeInfo->importanceMapWidth);
consts->ImportanceMapInverseDimensions[1] = 1.0f / ((float)bufferSizeInfo->importanceMapHeight);
consts->DeinterleavedDepthBufferDimensions[0] = (float)bufferSizeInfo->deinterleavedDepthBufferWidth;
consts->DeinterleavedDepthBufferDimensions[1] = (float)bufferSizeInfo->deinterleavedDepthBufferHeight;
consts->DeinterleavedDepthBufferInverseDimensions[0] = 1.0f / ((float)bufferSizeInfo->deinterleavedDepthBufferWidth);
consts->DeinterleavedDepthBufferInverseDimensions[1] = 1.0f / ((float)bufferSizeInfo->deinterleavedDepthBufferHeight);
consts->DeinterleavedDepthBufferOffset[0] = (float)bufferSizeInfo->deinterleavedDepthBufferXOffset;
consts->DeinterleavedDepthBufferOffset[1] = (float)bufferSizeInfo->deinterleavedDepthBufferYOffset;
consts->DeinterleavedDepthBufferNormalisedOffset[0] = ((float)bufferSizeInfo->deinterleavedDepthBufferXOffset) / ((float)bufferSizeInfo->deinterleavedDepthBufferWidth);
consts->DeinterleavedDepthBufferNormalisedOffset[1] = ((float)bufferSizeInfo->deinterleavedDepthBufferYOffset) / ((float)bufferSizeInfo->deinterleavedDepthBufferHeight);
if (!settings->generateNormals)
{
consts->NormalsUnpackMul = 2.0f; // inputs->NormalsUnpackMul;
consts->NormalsUnpackAdd = -1.0f; // inputs->NormalsUnpackAdd;
}
else
{
consts->NormalsUnpackMul = 2.0f;
consts->NormalsUnpackAdd = -1.0f;
}
}
void FFX_CACAO_UpdatePerPassConstants(FFX_CACAO_Constants* consts, const FFX_CACAO_Settings* settings, const FFX_CACAO_BufferSizeInfo* bufferSizeInfo, int pass)
{
consts->PerPassFullResUVOffset[0] = ((float)(pass % 2)) / (float)bufferSizeInfo->ssaoBufferWidth;
consts->PerPassFullResUVOffset[1] = ((float)(pass / 2)) / (float)bufferSizeInfo->ssaoBufferHeight;
consts->PassIndex = pass;
float additionalAngleOffset = settings->temporalSupersamplingAngleOffset; // if using temporal supersampling approach (like "Progressive Rendering Using Multi-frame Sampling" from GPU Pro 7, etc.)
float additionalRadiusScale = settings->temporalSupersamplingRadiusOffset; // if using temporal supersampling approach (like "Progressive Rendering Using Multi-frame Sampling" from GPU Pro 7, etc.)
const int subPassCount = 5;
for (int subPass = 0; subPass < subPassCount; subPass++)
{
int a = pass;
int b = subPass;
int spmap[5]{ 0, 1, 4, 3, 2 };
b = spmap[subPass];
float ca, sa;
float angle0 = ((float)a + (float)b / (float)subPassCount) * (3.1415926535897932384626433832795f) * 0.5f;
ca = FFX_CACAO_COS(angle0);
sa = FFX_CACAO_SIN(angle0);
float scale = 1.0f + (a - 1.5f + (b - (subPassCount - 1.0f) * 0.5f) / (float)subPassCount) * 0.07f;
consts->PatternRotScaleMatrices[subPass][0] = scale * ca;
consts->PatternRotScaleMatrices[subPass][1] = scale * -sa;
consts->PatternRotScaleMatrices[subPass][2] = -scale * sa;
consts->PatternRotScaleMatrices[subPass][3] = -scale * ca;
}
}
File diff suppressed because it is too large Load Diff
-367
View File
@@ -1,367 +0,0 @@
// Modifications Copyright © 2021. Advanced Micro Devices, Inc. All Rights Reserved.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016, Intel Corporation
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File changes (yyyy-mm-dd)
// 2016-09-07: filip.strugar@intel.com: first commit
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef FFX_CACAO_BINDINGS_HLSL
#define FFX_CACAO_BINDINGS_HLSL
// =============================================================================
// Constants
struct FFX_CACAO_Constants
{
float2 DepthUnpackConsts;
float2 CameraTanHalfFOV;
float2 NDCToViewMul;
float2 NDCToViewAdd;
float2 DepthBufferUVToViewMul;
float2 DepthBufferUVToViewAdd;
float EffectRadius; // world (viewspace) maximum size of the shadow
float EffectShadowStrength; // global strength of the effect (0 - 5)
float EffectShadowPow;
float EffectShadowClamp;
float EffectFadeOutMul; // effect fade out from distance (ex. 25)
float EffectFadeOutAdd; // effect fade out to distance (ex. 100)
float EffectHorizonAngleThreshold; // limit errors on slopes and caused by insufficient geometry tessellation (0.05 to 0.5)
float EffectSamplingRadiusNearLimitRec; // if viewspace pixel closer than this, don't enlarge shadow sampling radius anymore (makes no sense to grow beyond some distance, not enough samples to cover everything, so just limit the shadow growth; could be SSAOSettingsFadeOutFrom * 0.1 or less)
float DepthPrecisionOffsetMod;
float NegRecEffectRadius; // -1.0 / EffectRadius
float LoadCounterAvgDiv; // 1.0 / ( halfDepthMip[SSAO_DEPTH_MIP_LEVELS-1].sizeX * halfDepthMip[SSAO_DEPTH_MIP_LEVELS-1].sizeY )
float AdaptiveSampleCountLimit;
float InvSharpness;
int PassIndex;
float BilateralSigmaSquared;
float BilateralSimilarityDistanceSigma;
float4 PatternRotScaleMatrices[5];
float NormalsUnpackMul;
float NormalsUnpackAdd;
float DetailAOStrength;
float Dummy0;
float2 SSAOBufferDimensions;
float2 SSAOBufferInverseDimensions;
float2 DepthBufferDimensions;
float2 DepthBufferInverseDimensions;
int2 DepthBufferOffset;
float2 PerPassFullResUVOffset;
float2 OutputBufferDimensions;
float2 OutputBufferInverseDimensions;
float2 ImportanceMapDimensions;
float2 ImportanceMapInverseDimensions;
float2 DeinterleavedDepthBufferDimensions;
float2 DeinterleavedDepthBufferInverseDimensions;
float2 DeinterleavedDepthBufferOffset;
float2 DeinterleavedDepthBufferNormalisedOffset;
float4x4 NormalsWorldToViewspaceMatrix;
};
cbuffer SSAOConstantsBuffer : register(b0)
{
FFX_CACAO_Constants g_FFX_CACAO_Consts;
}
// =============================================================================
// Samplers
SamplerState g_PointClampSampler : register(s0);
SamplerState g_PointMirrorSampler : register(s1);
SamplerState g_LinearClampSampler : register(s2);
SamplerState g_ViewspaceDepthTapSampler : register(s3);
SamplerState g_RealPointClampSampler : register(s4);
// =============================================================================
// Clear Load Counter
RWTexture1D<uint> g_ClearLoadCounter_LoadCounter : register(u0);
void FFX_CACAO_ClearLoadCounter_SetLoadCounter(uint val)
{
g_ClearLoadCounter_LoadCounter[0] = val;
}
// =============================================================================
// Edge Sensitive Blur
Texture2DArray<float2> g_EdgeSensitiveBlur_Input : register(t0);
RWTexture2DArray<float2> g_EdgeSensitiveBlur_Output : register(u0);
float2 FFX_CACAO_EdgeSensitiveBlur_SampleInputOffset(float2 uv, int2 offset)
{
return g_EdgeSensitiveBlur_Input.SampleLevel(g_PointMirrorSampler, float3(uv, 0.0f), 0.0f, offset);
}
float2 FFX_CACAO_EdgeSensitiveBlur_SampleInput(float2 uv)
{
return g_EdgeSensitiveBlur_Input.SampleLevel(g_PointMirrorSampler, float3(uv, 0.0f), 0.0f);
}
void FFX_CACAO_EdgeSensitiveBlur_StoreOutput(int2 coord, float2 value)
{
g_EdgeSensitiveBlur_Output[int3(coord, 0)] = value;
}
// =============================================================================
// SSAO Generation
Texture2DArray<float> g_ViewspaceDepthSource : register(t0);
Texture2DArray<float4> g_DeinterleavedNormals : register(t1);
Texture1D<uint> g_LoadCounter : register(t2);
Texture2D<float> g_ImportanceMap : register(t3);
Texture2DArray<float2> g_FinalSSAO : register(t4);
RWTexture2DArray<float2> g_SSAOOutput : register(u0);
float FFX_CACAO_SSAOGeneration_SampleViewspaceDepthMip(float2 uv, float mip)
{
return g_ViewspaceDepthSource.SampleLevel(g_ViewspaceDepthTapSampler, float3(uv, 0.0f), mip);
}
float4 FFX_CACAO_SSAOGeneration_GatherViewspaceDepthOffset(float2 uv, int2 offset)
{
return g_ViewspaceDepthSource.GatherRed(g_PointMirrorSampler, float3(uv, 0.0f), offset);
}
uint FFX_CACAO_SSAOGeneration_GetLoadCounter()
{
return g_LoadCounter[0];
}
float FFX_CACAO_SSAOGeneration_SampleImportance(float2 uv)
{
return g_ImportanceMap.SampleLevel(g_LinearClampSampler, uv, 0.0f);
}
float2 FFX_CACAO_SSAOGeneration_LoadBasePassSSAOPass(int2 coord, int pass)
{
return g_FinalSSAO.Load(int4(coord, pass, 0)).xy;
}
float3 FFX_CACAO_SSAOGeneration_GetNormalPass(int2 coord, int pass)
{
return g_DeinterleavedNormals[int3(coord, pass)].xyz;
}
void FFX_CACAO_SSAOGeneration_StoreOutput(int2 coord, float2 val)
{
g_SSAOOutput[int3(coord, 0)] = val;
}
// ============================================================================
// Apply
Texture2DArray<float2> g_ApplyFinalSSAO : register(t0);
RWTexture2D<float> g_ApplyOutput : register(u0);
float FFX_CACAO_Apply_SampleSSAOUVPass(float2 uv, int pass)
{
return g_ApplyFinalSSAO.SampleLevel(g_LinearClampSampler, float3(uv, pass), 0.0f).x;
}
float2 FFX_CACAO_Apply_LoadSSAOPass(int2 coord, int pass)
{
return g_ApplyFinalSSAO.Load(int4(coord, pass, 0));
}
void FFX_CACAO_Apply_StoreOutput(int2 coord, float val)
{
g_ApplyOutput[coord] = val;
}
// =============================================================================
// Prepare
Texture2D<float> g_DepthIn : register(t0);
Texture2D<float4> g_PrepareNormalsFromNormalsInput : register(t0);
RWTexture2DArray<float> g_PrepareDepthsAndMips_OutMip0 : register(u0);
RWTexture2DArray<float> g_PrepareDepthsAndMips_OutMip1 : register(u1);
RWTexture2DArray<float> g_PrepareDepthsAndMips_OutMip2 : register(u2);
RWTexture2DArray<float> g_PrepareDepthsAndMips_OutMip3 : register(u3);
RWTexture2DArray<float> g_PrepareDepthsOut : register(u0);
RWTexture2DArray<float4> g_PrepareNormals_NormalOut : register(u0);
float FFX_CACAO_Prepare_SampleDepthOffset(float2 uv, int2 offset)
{
return g_DepthIn.SampleLevel(g_PointClampSampler, uv, 0.0f, offset);
}
float4 FFX_CACAO_Prepare_GatherDepth(float2 uv)
{
return g_DepthIn.GatherRed(g_PointClampSampler, uv);
}
float FFX_CACAO_Prepare_LoadDepth(int2 coord)
{
return g_DepthIn.Load(int3(coord, 0));
}
float FFX_CACAO_Prepare_LoadDepthOffset(int2 coord, int2 offset)
{
return g_DepthIn.Load(int3(coord, 0), offset);
}
float4 FFX_CACAO_Prepare_GatherDepthOffset(float2 uv, int2 offset)
{
return g_DepthIn.GatherRed(g_PointClampSampler, uv, offset);
}
float3 FFX_CACAO_Prepare_LoadNormal(int2 coord)
{
float3 normal = g_PrepareNormalsFromNormalsInput.Load(int3(coord, 0)).xyz;
normal = normal * g_FFX_CACAO_Consts.NormalsUnpackMul.xxx + g_FFX_CACAO_Consts.NormalsUnpackAdd.xxx;
normal = mul(normal, (float3x3)g_FFX_CACAO_Consts.NormalsWorldToViewspaceMatrix).xyz;
// normal = normalize(normal);
return normal;
}
void FFX_CACAO_Prepare_StoreDepthMip0(int2 coord, int index, float val)
{
g_PrepareDepthsAndMips_OutMip0[int3(coord, index)] = val;
}
void FFX_CACAO_Prepare_StoreDepthMip1(int2 coord, int index, float val)
{
g_PrepareDepthsAndMips_OutMip1[int3(coord, index)] = val;
}
void FFX_CACAO_Prepare_StoreDepthMip2(int2 coord, int index, float val)
{
g_PrepareDepthsAndMips_OutMip2[int3(coord, index)] = val;
}
void FFX_CACAO_Prepare_StoreDepthMip3(int2 coord, int index, float val)
{
g_PrepareDepthsAndMips_OutMip3[int3(coord, index)] = val;
}
void FFX_CACAO_Prepare_StoreDepth(int2 coord, int index, float val)
{
g_PrepareDepthsOut[int3(coord, index)] = val;
}
void FFX_CACAO_Prepare_StoreNormal(int2 coord, int index, float3 normal)
{
g_PrepareNormals_NormalOut[int3(coord, index)] = float4(normal, 1.0f);
}
// =============================================================================
// Importance Map
Texture2DArray<float2> g_ImportanceFinalSSAO : register(t0);
RWTexture2D<float> g_ImportanceOut : register(u0);
Texture2D<float> g_ImportanceAIn : register(t0);
RWTexture2D<float> g_ImportanceAOut : register(u0);
Texture2D<float> g_ImportanceBIn : register(t0);
RWTexture2D<float> g_ImportanceBOut : register(u0);
RWTexture1D<uint> g_ImportanceBLoadCounter : register(u1);
float4 FFX_CACAO_Importance_GatherSSAO(float2 uv, int index)
{
return g_ImportanceFinalSSAO.GatherRed(g_PointClampSampler, float3(uv, index));
}
void FFX_CACAO_Importance_StoreImportance(int2 coord, float val)
{
g_ImportanceOut[coord] = val;
}
float FFX_CACAO_Importance_SampleImportanceA(float2 uv)
{
return g_ImportanceAIn.SampleLevel(g_LinearClampSampler, uv, 0.0f);
}
void FFX_CACAO_Importance_StoreImportanceA(int2 coord, float val)
{
g_ImportanceAOut[coord] = val;
}
float FFX_CACAO_Importance_SampleImportanceB(float2 uv)
{
return g_ImportanceBIn.SampleLevel(g_LinearClampSampler, uv, 0.0f);
}
void FFX_CACAO_Importance_StoreImportanceB(int2 coord, float val)
{
g_ImportanceBOut[coord] = val;
}
void FFX_CACAO_Importance_LoadCounterInterlockedAdd(uint val)
{
InterlockedAdd(g_ImportanceBLoadCounter[0], val);
}
// =============================================================================
// Bilateral Upscale
RWTexture2D<float> g_BilateralUpscaleOutput : register(u0);
Texture2DArray<float2> g_BilateralUpscaleInput : register(t0);
Texture2D<float> g_BilateralUpscaleDepth : register(t1);
Texture2DArray<float> g_BilateralUpscaleDownscaledDepth : register(t2);
void FFX_CACAO_BilateralUpscale_StoreOutput(int2 coord, int2 offset, float val)
{
g_BilateralUpscaleOutput[coord + offset] = val;
}
float FFX_CACAO_BilateralUpscale_SampleSSAOLinear(float2 uv, int index)
{
return g_BilateralUpscaleInput.SampleLevel(g_LinearClampSampler, float3(uv, index), 0).x;
}
float FFX_CACAO_BilateralUpscale_SampleSSAOPoint(float2 uv, int index)
{
return g_BilateralUpscaleInput.SampleLevel(g_PointClampSampler, float3(uv, index), 0).x;
}
float2 FFX_CACAO_BilateralUpscale_LoadSSAO(int2 coord, int index)
{
return g_BilateralUpscaleInput.Load(int4(coord, index, 0));
}
float FFX_CACAO_BilateralUpscale_LoadDepth(int2 coord, int2 offset)
{
return g_BilateralUpscaleDepth.Load(int3(coord, 0), offset);
}
float FFX_CACAO_BilateralUpscale_LoadDownscaledDepth(int2 coord, int index)
{
return g_BilateralUpscaleDownscaledDepth.Load(int4(coord, index, 0));
}
#endif
-83
View File
@@ -1,83 +0,0 @@
// Modifications Copyright © 2021. Advanced Micro Devices, Inc. All Rights Reserved.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016, Intel Corporation
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File changes (yyyy-mm-dd)
// 2016-09-07: filip.strugar@intel.com: first commit
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Defines for constants common to both CACAO.cpp and CACAO.hlsl
#ifndef FFX_CACAO_DEFINES_H
#define FFX_CACAO_DEFINES_H
// ============================================================================
// Prepare
#define FFX_CACAO_PREPARE_DEPTHS_AND_MIPS_WIDTH 8
#define FFX_CACAO_PREPARE_DEPTHS_AND_MIPS_HEIGHT 8
#define FFX_CACAO_PREPARE_DEPTHS_WIDTH 8
#define FFX_CACAO_PREPARE_DEPTHS_HEIGHT 8
#define FFX_CACAO_PREPARE_DEPTHS_HALF_WIDTH 8
#define FFX_CACAO_PREPARE_DEPTHS_HALF_HEIGHT 8
#define FFX_CACAO_PREPARE_NORMALS_WIDTH 8
#define FFX_CACAO_PREPARE_NORMALS_HEIGHT 8
#define PREPARE_NORMALS_FROM_INPUT_NORMALS_WIDTH 8
#define PREPARE_NORMALS_FROM_INPUT_NORMALS_HEIGHT 8
// ============================================================================
// SSAO Generation
#define FFX_CACAO_GENERATE_SPARSE_WIDTH 4
#define FFX_CACAO_GENERATE_SPARSE_HEIGHT 16
#define FFX_CACAO_GENERATE_WIDTH 8
#define FFX_CACAO_GENERATE_HEIGHT 8
// ============================================================================
// Importance Map
#define IMPORTANCE_MAP_WIDTH 8
#define IMPORTANCE_MAP_HEIGHT 8
#define IMPORTANCE_MAP_A_WIDTH 8
#define IMPORTANCE_MAP_A_HEIGHT 8
#define IMPORTANCE_MAP_B_WIDTH 8
#define IMPORTANCE_MAP_B_HEIGHT 8
// ============================================================================
// Edge Sensitive Blur
#define FFX_CACAO_BLUR_WIDTH 16
#define FFX_CACAO_BLUR_HEIGHT 16
// ============================================================================
// Apply
#define FFX_CACAO_APPLY_WIDTH 8
#define FFX_CACAO_APPLY_HEIGHT 8
// ============================================================================
// Bilateral Upscale
#define FFX_CACAO_BILATERAL_UPSCALE_WIDTH 8
#define FFX_CACAO_BILATERAL_UPSCALE_HEIGHT 8
#endif
File diff suppressed because it is too large Load Diff
+16 -7
View File
@@ -7,9 +7,12 @@
#ifdef implicit
layout (constant_id = 0) const bool DISABLE_TRACE = false;
layout(location=0)in VertexInput
{
vec4 position;
vec3 globaloffset;
}vertexInput;
#else
@@ -53,9 +56,10 @@ const uint MAX_STEPS=50;
#define FARPLANE length(vec3(10))
#define gl_GlobalInvocationID uvec3(1)
#endif
#define interval_frags
#include "intervals.glsl"
layout(set=0,binding=20)restrict readonly buffer fragmentMasks{
layout(set=0,binding=20, std430)restrict readonly buffer fragmentMasks{
uint8_t masks[][masklen];
}fragmentpassmasks;
@@ -71,6 +75,9 @@ vec3 getNormal(vec3 p,float dens){
vec2 spheretracing(vec3 ori,vec3 dir,out vec3 p){
vec2 td=vec2(NEARPLANE,1.);
p=ori;
td.y=sceneoverride(p,false).x;
td.x+=(td.y)*.9;
p=ori+dir*td.x;
for(int i=0;i<MAX_STEPS&&td.y>EPSILON&&td.x<FARPLANE;i++){
td.y=sceneoverride(p,false).x;
td.x+=(td.y)*.9;
@@ -106,12 +113,14 @@ void main(){
vec3 raypos=vertexInput.position.xyz;
vec3 p;
vec3 raydir=normalize(raypos-(inverse(pc.world)*vec4(camera_uniforms.campos,1)).xyz);
//raypos-=vec3(5);
raypos+=vertexInput.globaloffset;
/*f_color=vec4(raydir,1.);
return;*/
/*f_color=vertexInput.position;
return;*/
//f_color=vec4(raydir,1.);
if (DISABLE_TRACE) {
f_color=vertexInput.position;
return;
}
#ifdef debug
f_color=vec4(sceneoverride(raypos,false),1);
@@ -123,9 +132,9 @@ void main(){
f_color=vec4(td,0,1);
return;
#endif*/
vec3 n=getNormal(p,td.y);
if(td.y<EPSILON)
{
vec3 n=getNormal(p,td.y);
//f_color=vec4(1.);
f_color=vec4(shading(n),1.);
+45
View File
@@ -0,0 +1,45 @@
#version 460
uint DescriptionIndex;
//#include "include.glsl"
#include "intervals.glsl"
struct Results {
float[2] f;
vec2[2] v2;
vec4[2] v3;
vec4[2] v4;
uint8_t[masklen] mask;
};
layout(set=0,binding=30, std430)buffer ResultsArray{
Results r[];
}results;
layout(local_size_x=32,local_size_y=1,local_size_z=1)in;
void main ()
{
DescriptionIndex = gl_LocalInvocationID.x;
default_mask();
float[6]bounds=scene_description.desc[DescriptionIndex+1].bounds;
vec3 bottomleft = vec3(bounds[3],bounds[4],bounds[5]);
vec3 topright = vec3(bounds[0],bounds[1],bounds[2]);
desc = scene_description.desc[(DescriptionIndex)+1];
clear_stacks();
results.r[gl_GlobalInvocationID.x].f = scene(vec3[2](bottomleft, topright), true);
vec3[2] v3 = pull_vec3(false);
results.r[gl_GlobalInvocationID.x].v3[0] = vec4(v3[0],1.);
results.r[gl_GlobalInvocationID.x].v3[1] = vec4(v3[1],1.);
results.r[gl_GlobalInvocationID.x].v2 = pull_vec2(false);
results.r[gl_GlobalInvocationID.x].v4 = pull_vec4(false);
//results.r[gl_GlobalInvocationID.x].f[1] = float(gl_GlobalInvocationID.x);
/*results.r[gl_GlobalInvocationID.x].f = pull_float(true);//scene(vec3[2](bottomleft, topright), false);
vec3[2] v3 = pull_vec3(true);
results.r[gl_GlobalInvocationID.x].v3[0] = vec4(v3[0],1.);
results.r[gl_GlobalInvocationID.x].v3[1] = vec4(v3[1],1.);
results.r[gl_GlobalInvocationID.x].v2 = pull_vec2(true);
results.r[gl_GlobalInvocationID.x].v4 = pull_vec4(true);
results.r[gl_GlobalInvocationID.x].f[1] = float(gl_GlobalInvocationID.x);*/
results.r[gl_GlobalInvocationID.x].mask = mask;
}
+19
View File
@@ -10,6 +10,15 @@ fn sized_text(ui: &mut egui::Ui, text: impl Into<String>, size: f32) {
ui.label(egui::RichText::new(text).size(size));
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct PreviousDebug {
pub bounding_boxes: bool,
pub disable_meshcull: bool,
pub disable_meshscale1: bool,
pub disable_meshscale2: bool,
pub disable_taskcull: bool,
}
#[derive(Debug)]
pub struct GState {
pub cursor_sensitivity: f32,
@@ -20,6 +29,8 @@ pub struct GState {
pub csg: Vec<CSG>,
pub fps: [f64; 128],
pub debug: PreviousDebug,
}
impl Default for GState {
@@ -33,6 +44,8 @@ impl Default for GState {
csg: vec![],
fps: [0.0; 128],
debug: Default::default(),
}
}
}
@@ -87,6 +100,12 @@ pub fn gui_up(gui: &mut Gui, state: &mut GState) {
let line = Line::new(fps);
ui.heading("FPS");
Plot::new("fps").view_aspect(2.0).show(ui, |plot_ui| plot_ui.line(line));
ui.heading("Debug");
ui.toggle_value(&mut state.debug.bounding_boxes, "Render bounding boxes instead");
ui.toggle_value(&mut state.debug.disable_meshcull, "Disable mesh shader culling");
ui.toggle_value(&mut state.debug.disable_meshscale1, "Disable mesh shader scaling part 1");
ui.toggle_value(&mut state.debug.disable_meshscale2, "Disable mesh shader scaling part 2");
ui.toggle_value(&mut state.debug.disable_taskcull, "Disable task shader culling");
});
});
});
+32 -9
View File
@@ -8,12 +8,17 @@ uint DescriptionIndex;
#include "include.glsl"
#include "intervals.glsl"
layout (constant_id = 0) const bool DISABLE_TRACE = false;
layout (constant_id = 1) const bool DISABLE_SCALING_1 = false;
layout (constant_id = 2) const bool DISABLE_SCALING_2 = false;
layout(local_size_x=32,local_size_y=1,local_size_z=1)in;
layout(triangles,max_vertices=256,max_primitives=192)out;
layout(location=0)out VertexOutput
{
vec4 position;
vec3 globaloffset;
}vertexOutput[];
struct MeshMasks
@@ -23,11 +28,11 @@ struct MeshMasks
vec3 bottomleft; //12
vec3 topright; //12
uint globalindex; //4
//uint objectindex; //4
}; //total = 992 bytes
vec3 globaloffset; //12
}; //total = 1000 bytes
taskPayloadSharedEXT MeshMasks meshmasks;
layout(set=0,binding=20)restrict writeonly buffer fragmentMasks{
layout(set=0,binding=20, std430)restrict writeonly buffer fragmentMasks{
uint8_t masks[][masklen];
}fragmentpassmasks;
@@ -40,6 +45,7 @@ void main()
mask = meshmasks.masks[gl_WorkGroupID.x];
vec3 bottomleft = meshmasks.bottomleft;
vec3 topright = meshmasks.topright;
vec3 center = (topright + bottomleft) / 2.;
vec4[8]positions={
vec4(bottomleft,1.),
@@ -61,17 +67,20 @@ void main()
int GlobalInvocationIndex = int((meshmasks.globalindex*32+localindex)*32+gl_LocalInvocationID.x);
//adjust scale and position
if (!DISABLE_SCALING_1) {
for (int i = 0; i<8; i++)
{
positions[i] *= vec4(0.25,0.25,0.5,1.);
positions[i].x += (topright.x-bottomleft.x)*0.25 * (mod(localindex,4.)-1.5);
positions[i].y += (topright.y-bottomleft.y)*0.25 * (mod(floor(localindex/4.),4.)-1.5);
positions[i].x += (topright.x-bottomleft.x)*0.25 * (mod(localindex,4.)-1.5) + (topright.x+bottomleft.x)*0.375;
positions[i].y += (topright.y-bottomleft.y)*0.25 * (mod(floor(localindex/4.),4.)-1.5) + (topright.y+bottomleft.y)*0.375;
positions[i].z += ((topright.z-bottomleft.z)*0.5 * (floor(localindex/16.)-0.5) + (topright.z+bottomleft.z)*0.25);
}
}
vec4 localtopright=positions[0];
vec4 localbottomleft=positions[7];
if (!DISABLE_SCALING_2) {
for (int i = 0; i<8; i++)
{
positions[i] *= vec4(0.25,0.25,0.5,1.);
@@ -79,11 +88,10 @@ void main()
positions[i].y += (localtopright.y-localbottomleft.y)*(0.25) * (mod(floor(gl_LocalInvocationID.x/4.),4.)-1.5) + (localtopright.y+localbottomleft.y)*0.375;
positions[i].z += (localtopright.z-localbottomleft.z)*(0.5) * (floor(gl_LocalInvocationID.x/16.)-0.5) + (localtopright.z+localbottomleft.z)*0.25;
}
}
bvec3 signingvec=greaterThan((inverse(pc.world)*vec4(camera_uniforms.campos,1)).xyz,(positions[0].xyz+positions[7].xyz)/2);
float[2] check = scene(vec3[2](vec3(positions[0].xyz),vec3(positions[7].xyz)), true);
gl_MeshPrimitivesEXT[pindex+0].gl_PrimitiveID=GlobalInvocationIndex;
gl_MeshPrimitivesEXT[pindex+1].gl_PrimitiveID=GlobalInvocationIndex;
gl_MeshPrimitivesEXT[pindex+2].gl_PrimitiveID=GlobalInvocationIndex;
@@ -91,8 +99,15 @@ void main()
gl_MeshPrimitivesEXT[pindex+4].gl_PrimitiveID=GlobalInvocationIndex;
gl_MeshPrimitivesEXT[pindex+5].gl_PrimitiveID=GlobalInvocationIndex;
if ((check[0] < 0) && (check[1] > 0) && (gl_WorkGroupID.x < 32))
//if (true)
bool triangle_fine;
if (!DISABLE_TRACE) {
float[2] check = scene(vec3[2](vec3(positions[0].xyz),vec3(positions[7].xyz)), true);
triangle_fine = (check[0] <= 0) && (check[1] >= 0);
} else {
triangle_fine = true;
}
if (triangle_fine)
{
fragmentpassmasks.masks[GlobalInvocationIndex]=mask;
@@ -112,6 +127,14 @@ void main()
vertexOutput[vindex+5].position=(positions[5]);
vertexOutput[vindex+6].position=(positions[6]);
vertexOutput[vindex+7].position=(positions[7]);
vertexOutput[vindex+0].globaloffset=(meshmasks.globaloffset);
vertexOutput[vindex+1].globaloffset=(meshmasks.globaloffset);
vertexOutput[vindex+2].globaloffset=(meshmasks.globaloffset);
vertexOutput[vindex+3].globaloffset=(meshmasks.globaloffset);
vertexOutput[vindex+4].globaloffset=(meshmasks.globaloffset);
vertexOutput[vindex+5].globaloffset=(meshmasks.globaloffset);
vertexOutput[vindex+6].globaloffset=(meshmasks.globaloffset);
vertexOutput[vindex+7].globaloffset=(meshmasks.globaloffset);
/*vertexOutput[vindex+0].position=vec4(bottomleft,1.);
vertexOutput[vindex+1].position=vec4(bottomleft.x,bottomleft.y,topright.z,1.);
vertexOutput[vindex+2].position=vec4(bottomleft.x,topright.y,bottomleft.z,1.);
+39 -15
View File
@@ -8,6 +8,8 @@
#include "include.glsl"
#include "intervals.glsl"
layout (constant_id = 0) const bool DISABLE_TRACE = false;
layout(local_size_x=32,local_size_y=1,local_size_z=1)in;
struct MeshMasks
@@ -17,8 +19,8 @@ struct MeshMasks
vec3 bottomleft; //12
vec3 topright; //12
uint globalindex; //4
//uint objectindex; //4
}; //total = 992 bytes
vec3 globaloffset; //12
}; //total = 1000 bytes
taskPayloadSharedEXT MeshMasks meshmasks;
shared uint index;
@@ -34,43 +36,62 @@ void main()
index=0;
}
#define CLIPCHECK 65536
//#define CLIPCHECK 65536
float[6]bounds={
/*float[6]bounds={
CLIPCHECK-sceneoverride(vec3(CLIPCHECK,0,0),false),
CLIPCHECK-sceneoverride(vec3(0,CLIPCHECK,0),false),
CLIPCHECK-sceneoverride(vec3(0,0,CLIPCHECK),false),
-CLIPCHECK+sceneoverride(vec3(-CLIPCHECK,0,0),false),
-CLIPCHECK+sceneoverride(vec3(0,-CLIPCHECK,0),false),
-CLIPCHECK+sceneoverride(vec3(0,0,-CLIPCHECK),false),
};
};*/
/*const float[6]bounds={
1,1,1,-1,-1,-1,
};*/
float[6]bounds=scene_description.desc[gl_WorkGroupID.x+1].bounds;
/*bounds[0] += abs(bounds[0] * 0.01);
bounds[1] += abs(bounds[1] * 0.01);
bounds[2] += abs(bounds[2] * 0.01);
bounds[3] -= abs(bounds[3] * 0.01);
bounds[4] -= abs(bounds[4] * 0.01);
bounds[5] -= abs(bounds[5] * 0.01);*/
vec3 bottomleft = vec3(bounds[3],bounds[4],bounds[5]);
vec3 topright = vec3(bounds[0],bounds[1],bounds[2]);
vec3 center = (topright + bottomleft) / 2;
vec3 globaloffset = vec3(0);//(topright+bottomleft)/2.;
#define adjust(var) var -= center;\
#define adjust(var) \
var *= vec3(0.25,0.25,0.25);\
var.x += (bounds[0]-bounds[3]) * 0.25 * (mod(gl_LocalInvocationID.x,4.)-1.5) ;\
var.y += (bounds[1]-bounds[4]) * 0.25 * (mod(floor(gl_LocalInvocationID.x/4.),4.)-1.5) ;\
var.z += (bounds[2]-bounds[5]) * 0.25 * (floor(gl_LocalInvocationID.x/16.)-1.5+gl_WorkGroupID.z*2.) ;\
var += center;
var.x += ((bounds[0]-bounds[3]) * 0.25 * (mod(gl_LocalInvocationID.x,4.)-1.5)) + ((bounds[0]+bounds[3])*0.375) ;\
var.y += ((bounds[1]-bounds[4]) * 0.25 * (mod(floor(gl_LocalInvocationID.x/4.),4.)-1.5)) + ((bounds[1]+bounds[4])*0.375) ;\
var.z += ((bounds[2]-bounds[5]) * 0.25 * (floor(gl_LocalInvocationID.x/16.)-1.5+gl_WorkGroupID.z*2.)) + ((bounds[2]+bounds[5])*0.375) ;\
adjust(bottomleft);
adjust(topright);
barrier();
float[2] check = scene(vec3[2](bottomleft,topright), false);
bool triangle_fine;
if (!DISABLE_TRACE) {
float[2] check = scene(vec3[2](bottomleft+globaloffset,topright+globaloffset), true);
triangle_fine = (check[0] <= 0) && (check[1] >= 0);
} else {
triangle_fine = true;
}
//default_mask();
//float[2] check = scene(vec3[2](bottomleft,topright), false);
//float[2] check = scene(vec3[2](bottomleft-globaloffset,topright-globaloffset), false);
//float[2] check = scene(vec3[2](vec3(bounds[3],bounds[4],bounds[5]),vec3(bounds[0],bounds[1],bounds[2])), false);
if ((check[0] < 0) && (check[1] > 0))
//if (((check[0] <= 0) && (check[1] >= 0)) )//|| ((check[1] <= 0) && ()))
//if ((bottomleft.x >= -1) && (bottomleft.y >= -1) && (bottomleft.z >= -1) && (topright.x <= 1) && (topright.y <= 1) && (topright.z <= 1))
//if ((gl_LocalInvocationID.x == 0) && (bottomleft.x >= 0))
if (triangle_fine)
{
uint localindex = atomicAdd(index, 1);
//if (localindex < 32) {
@@ -84,9 +105,12 @@ void main()
meshmasks.bottomleft = vec3(bounds[3],bounds[4],(bounds[5]*0.5) + ((bounds[2]-bounds[5])*0.5 * (-0.5+gl_WorkGroupID.z)));
meshmasks.topright = vec3(bounds[0],bounds[1],(bounds[2]*0.5) + ((bounds[2]-bounds[5])*0.5 * (-0.5+gl_WorkGroupID.z)));
meshmasks.globalindex = gl_WorkGroupID.x*2+gl_WorkGroupID.z;
//meshmasks.objectindex = DescriptionIndex;
meshmasks.globaloffset = globaloffset/0.25;
}
barrier();
if (gl_LocalInvocationID.x==0)
{
EmitMeshTasksEXT(index,1,1);
}
}
+2
View File
@@ -216,4 +216,6 @@ const uint OPCubeVec3=__LINE__-1; //V3 //V3
const uint OPSquareVec4=__LINE__-1; //V4 //V4
const uint OPCubeVec4=__LINE__-1; //V4 //V4
const uint OPSDFSphere=__LINE__-1; //F V3 //F
const uint OPSDFBox=__LINE__-1; //V3 V3 //F
const uint OPSDFTorus=__LINE__-1; //V2 V3 //F
const uint OPInvalid=__LINE__-1; // //
+1 -1
View File
@@ -6,7 +6,7 @@
#include "instructionset.glsl"
layout(set=0,binding=2)uniform SceneDescription{
layout(set=0,binding=2, std430)uniform SceneDescription{
u32vec4 d[13];//stored packed for space efficiency, 8 per index
}scene_description;
+1557 -2940
View File
File diff suppressed because it is too large Load Diff
+108 -57
View File
@@ -12,48 +12,45 @@ struct Description{
uint scene;
uint floats;
uint vec2s;
uint vec3s;
uint vec4s;
uint mat2s;
uint mat3s;
uint mat4s;
uint mats;
uint dependencies;
float[6] bounds;
};
Description desc;
layout(set=0,binding=2)restrict readonly buffer SceneDescription{
layout(set=0,binding=2, std430)restrict readonly buffer SceneDescription{
Description desc[];
}scene_description;
layout(set=0,binding=3)restrict readonly buffer SceneBuf{
layout(set=0,binding=3, std430)restrict readonly buffer SceneBuf{
u32vec4 opcodes[];
}scenes;
layout(set=0,binding=4)restrict readonly buffer FloatConst{
layout(set=0,binding=4, std430)restrict readonly buffer FloatConst{
float floats[];
}fconst;
layout(set=0,binding=5)restrict readonly buffer Vec2Const{
layout(set=0,binding=5, std430)restrict readonly buffer Vec2Const{
vec2 vec2s[];
}v2const;
layout(set=0,binding=6)restrict readonly buffer Vec3Const{
vec3 vec3s[];
}v3const;
layout(set=0,binding=7)restrict readonly buffer Vec4Const{
layout(set=0,binding=7, std430)restrict readonly buffer Vec4Const{
vec4 vec4s[];
}v4const;
layout(set=0,binding=8)restrict readonly buffer Mat2Const{
layout(set=0,binding=8, std430)restrict readonly buffer Mat2Const{
mat2 mat2s[];
}m2const;
layout(set=0,binding=9)restrict readonly buffer Mat3Const{
layout(set=0,binding=9, std430)restrict readonly buffer Mat3Const{
mat3 mat3s[];
}m3const;
layout(set=0,binding=10)restrict readonly buffer Mat4Const{
layout(set=0,binding=10, std430)restrict readonly buffer Mat4Const{
mat4 mat4s[];
}m4const;
layout(set=0,binding=11)restrict readonly buffer MatConst{
layout(set=0,binding=11, std430)restrict readonly buffer MatConst{
mat4 mats[];
}matconst;
layout(set=0,binding=12)restrict readonly buffer DepInfo{
layout(set=0,binding=12, std430)restrict readonly buffer DepInfo{
uint8_t dependencies[][2];
}depinfo;
@@ -85,13 +82,16 @@ uint mat4_stack_head=0;
uint float_const_head=0;
uint vec2_const_head=0;
uint vec3_const_head=0;
uint vec4_const_head=0;
uint mat2_const_head=0;
uint mat3_const_head=0;
uint mat4_const_head=0;
uint mat_const_head=0;
#define vec3_const_head vec4_const_head
#define v3const v4const
#define vec3s vec4s
void push_float(float f[2]){
float_stack[float_stack_head++]=f;
}
@@ -134,7 +134,7 @@ void push_vec3(vec3 f[2]){
vec3[2]pull_vec3(bool c){
if (c) {
vec3 f = v3const.vec3s[desc.vec3s+vec3_const_head++];
vec3 f = v3const.vec3s[desc.vec3s+vec3_const_head++].xyz;
return vec3[2](f,f);
}
else {
@@ -143,7 +143,7 @@ vec3[2]pull_vec3(bool c){
}
vec3 cpull_vec3(){
return v3const.vec3s[desc.vec3s+vec3_const_head++];
return v3const.vec3s[desc.vec3s+vec3_const_head++].xyz;
}
void push_vec4(vec4 f[2]){
@@ -698,18 +698,18 @@ void pruneself (int pos) {
}
#define minpruning if (prune) { if (all(lessThan(in1[1],in2[0]))) {\
prunesome(OPPos,bool[6](false,true,false,false,false,false));\
prunesome(OPPos,bool[6](true,false,false,false,false,false));\
passthroughself(OPPos);\
} else if (all(lessThan(in2[1],in1[0]))) {\
prunesome(OPPos,bool[6](true,false,false,false,false,false));\
prunesome(OPPos,bool[6](false,true,false,false,false,false));\
passthroughself(OPPos);\
}}
#define maxpruning if (prune) { if (all(greaterThan(in1[0],in2[1]))) {\
prunesome(OPPos,bool[6](false,true,false,false,false,false));\
prunesome(OPPos,bool[6](true,false,false,false,false,false));\
passthroughself(OPPos);\
} else if (all(greaterThan(in2[0],in1[1]))) {\
prunesome(OPPos,bool[6](true,false,false,false,false,false));\
prunesome(OPPos,bool[6](false,true,false,false,false,false));\
passthroughself(OPPos);\
}}
@@ -719,6 +719,13 @@ vec3 scene(vec3 p[2], bool prune)
float[2]scene(vec3 p[2], bool prune)
#endif
{
if (prune)
{
for (int i = 0; i<=(masklen*8); i++)
pruneallchecks[i] = uint8_t(0);
}
//p[0]=p[0].yxz;
//p[1]=p[1].yxz;
uint major_position=0;
uint minor_position=0;
@@ -735,6 +742,12 @@ float[2]scene(vec3 p[2], bool prune)
if(minor_position==0){
get_caches;
}
/*#ifdef implicit
if (mask[major_position] != 255) discard;
if (mask[major_position+1] != 255) discard;
if (mask[major_position+2] != 255) discard;
if (mask[major_position+3] != 255) discard;
#endif*/
#ifdef debug
/*if((minor_integer_cache[minor_position]&1023)==OPStop) {
return vec3(0.,0.,1.);
@@ -1565,11 +1578,12 @@ float[2]scene(vec3 p[2], bool prune)
if (prune) {
if (in1[1] < in2[0])
{
prunesome(OPPos,bool[6](false,true,false,false,false,false));
//return float[2](-1,-1);
prunesome(OPPos,bool[6](true,false,false,false,false,false));
passthroughself(OPPos);
} else if (in2[1] < in1[0])
{
prunesome(OPPos,bool[6](true,false,false,false,false,false));
prunesome(OPPos,bool[6](false,true,false,false,false,false));
passthroughself(OPPos);
}}
float[2]temp;
@@ -1585,11 +1599,11 @@ float[2]scene(vec3 p[2], bool prune)
if (prune) {
if (in1[0] > in2[1])
{
prunesome(OPPos,bool[6](false,true,false,false,false,false));
prunesome(OPPos,bool[6](true,false,false,false,false,false));
passthroughself(OPPos);
} else if (in2[0] > in1[1])
{
prunesome(OPPos,bool[6](true,false,false,false,false,false));
prunesome(OPPos,bool[6](false,true,false,false,false,false));
passthroughself(OPPos);
}}
float[2]temp;
@@ -2803,37 +2817,27 @@ float[2]scene(vec3 p[2], bool prune)
case OPSmoothMinMaterialFloat:
case OPSmoothMinFloat:{
if(maskdefine){
if(ifconst(0)) {float_const_head++;}
if(ifconst(1)) {float_const_head++;}
float_const_head++;
break;
}
float k=cpull_float();
float[2] a=pull_float(ifconst(0));
float[2] b=pull_float(ifconst(1));
float hmin=max(k-abs(a[0]-b[0]),0.);
float hmax=max(k-abs(a[1]-b[1]),0.);
float smin=min(a[0],b[0])-hmin*hmin*.25/k;
float smax=min(a[1],b[1])-hmax*hmax*.25/k;
inputmask3(float_const_head,float_const_head,float_const_head);
float[2] k=pull_float(ifconst(0));
float[2] a=pull_float(ifconst(1));
float[2] b=pull_float(ifconst(2));
float hmin=max(k[0]-abs(a[0]-b[0]),0.);
float hmax=max(k[0]-abs(a[1]-b[1]),0.);
float smin=min(a[0],b[0])-hmin*hmin*.25/k[0];
float smax=min(a[1],b[1])-hmax*hmax*.25/k[0];
push_float(float[2](smin,smax));
}
break;
case OPSmoothMaxMaterialFloat:
case OPSmoothMaxFloat:{
if(maskdefine){
if(ifconst(0)) {float_const_head++;}
if(ifconst(1)) {float_const_head++;}
float_const_head++;
break;
}
float k=cpull_float();
float[2] a=pull_float(ifconst(0));
float[2] b=pull_float(ifconst(1));
float hmin=max(k-abs(a[0]-b[0]),0.);
float hmax=max(k-abs(a[1]-b[1]),0.);
float smin=max(a[0],b[0])+hmin*hmin*.25/k;
float smax=max(a[1],b[1])+hmax*hmax*.25/k;
inputmask3(float_const_head,float_const_head,float_const_head);
float[2] k=pull_float(ifconst(0));
float[2] a=pull_float(ifconst(1));
float[2] b=pull_float(ifconst(2));
float hmin=max(k[0]-abs(a[0]-b[0]),0.);
float hmax=max(k[0]-abs(a[1]-b[1]),0.);
float smin=max(a[0],b[0])+hmin*hmin*.25/k[0];
float smax=max(a[1],b[1])+hmax*hmax*.25/k[0];
push_float(float[2](smin,smax));
}
break;
@@ -3084,13 +3088,13 @@ float[2]scene(vec3 p[2], bool prune)
{
inputmask2(float_const_head,vec3_const_head);
float[2] in2=pull_float(ifconst(0));
#ifdef debug
/*#ifdef debug
if (in2[0] == in2[1] && in2[0] == 0.2)
{return vec3(in2[0],in2[1],0.);
}else{
return vec3(in2[0],in2[1],1.);
}
#endif
#endif*/
vec3[2] in1=pull_vec3(ifconst(1));
/*#ifdef debug
return in1[0];
@@ -3109,11 +3113,57 @@ float[2]scene(vec3 p[2], bool prune)
}
break;
case OPSDFTorus:
{
inputmask2(vec2_const_head,vec3_const_head);
vec2[2] in2=pull_vec2(ifconst(0)); //t
vec3[2] in1=pull_vec3(ifconst(1)); //p
vec2[2] out1;
float[2] out2;
bvec2 mixer=mix(bvec2(false),greaterThan(in1[1].xz,vec2(0)),lessThan(in1[0].xz,vec2(0)));
out1[0].x=length(mix(min(abs(in1[0].xz),abs(in1[1].xz)),vec2(0),mixer))-in2[1].x;
out1[1].x=length(max(abs(in1[0].xz),abs(in1[1].xz)))-in2[0].x;
out1[0].y = p[0].y;
out1[1].y = p[1].y;
mixer=mix(bvec2(false),greaterThan(out1[1],vec2(0)),lessThan(out1[0],vec2(0)));
out2[0]=length(mix(min(abs(out1[0]),abs(out1[1])),vec2(0),mixer))-in2[1].y;
out2[1]=length(max(abs(out1[0]),abs(out1[1])))-in2[0].y;
push_float(out2);
}
break;
//this doesn't work internally but it's probably fiiiine
case OPSDFBox:
{
inputmask2(vec3_const_head,vec3_const_head);
vec3[2] in2=pull_vec3(ifconst(0)); //r
vec3[2] in1=pull_vec3(ifconst(1)); //p
#ifdef debug
return in1[0];
#endif
vec3[2]temp;
bvec3 mixer = bvec3(false);
vec3 zero = vec3(0);
absolute;
subtract;
float out1 = length(max(in1[0],0.0))+min(max(in1[0].x,max(in1[0].y,in1[0].z)),0.0);
float out2 = length(max(in1[1],0.0))+min(max(in1[1].x,max(in1[1].y,in1[1].z)),0.0);
push_float(float[2](min(out1,out2),max(out1,out2)));
}
break;
case OPNop:
break;
case OPStop:
if (prune)
if (prune) {
//return float[2](-1,-1);
pruneall(uint8_t((major_position<<3)|minor_position));
}
#ifdef debug
return vec3(pull_float(ifconst(0))[0]);
#else
@@ -3124,7 +3174,7 @@ float[2]scene(vec3 p[2], bool prune)
#ifdef debug
return vec3(float(minor_integer_cache[minor_position]));
#else
return float[2](0,0);
return float[2](-1,-1);
#endif
}
@@ -3135,8 +3185,9 @@ float[2]scene(vec3 p[2], bool prune)
major_position++;
if(major_position==masklen)
{
if (prune)
pruneall(uint8_t((masklen*8)));
if (prune) {
pruneall(uint8_t(masklen<<3));
}
#ifdef debug
return vec3(pull_float(false)[0]);
#else
+239 -45
View File
@@ -1,7 +1,8 @@
#![feature(variant_count)]
use bytemuck::{Zeroable, Pod};
use cgmath::{
Deg, EuclideanSpace, Euler, Matrix2, Matrix3, Matrix4, Point3, Rad, SquareMatrix, Vector2,
Vector3, Vector4,
Vector3, Vector4, Zero,
};
use instruction_set::InputTypes;
use vulkano::command_buffer::{CopyBufferInfo, PrimaryCommandBufferAbstract};
@@ -66,6 +67,7 @@ use winit::{
mod gui;
use crate::gui::*;
mod objects;
use crate::interpreter::Interpreter;
use crate::objects::*;
mod mcsg_deserialise;
@@ -75,6 +77,8 @@ mod instruction_set {
use crate::instruction_set::InstructionSet;
mod interpreter;
pub type MemoryAllocator = StandardMemoryAllocator;
fn main() {
@@ -300,6 +304,21 @@ fn main() {
}
}
mod cs {
vulkano_shaders::shader!{
ty: "compute",
path: "src/fuzz.comp.glsl",
types_meta: {
use bytemuck::{Pod, Zeroable};
#[derive(Clone, Copy, Zeroable, Pod, Debug)]
},
vulkan_version: "1.2",
spirv_version: "1.5",
}
}
let loaders: Vec<
fn(
::std::sync::Arc<::vulkano::device::Device>,
@@ -343,6 +362,13 @@ fn main() {
::std::sync::Arc<::vulkano::shader::ShaderModule>,
::vulkano::shader::ShaderCreationError,
>),
((cs::load)
as fn(
::std::sync::Arc<::vulkano::device::Device>,
) -> Result<
::std::sync::Arc<::vulkano::shader::ShaderModule>,
::vulkano::shader::ShaderCreationError,
>),
];
let pariter = loaders
@@ -357,8 +383,21 @@ fn main() {
let implicit_ts = pariter[3].clone();
let implicit_fs = pariter[4].clone();
let compute_shader = pariter[5].clone();
drop(pariter);
use vulkano::pipeline::ComputePipeline;
let compute_pipeline = ComputePipeline::new(
device.clone(),
compute_shader.entry_point("main").unwrap(),
&(),
None,
|_| {},
)
.expect("failed to create compute pipeline");
let memory_allocator = Arc::new(MemoryAllocator::new_default(device.clone()));
let render_pass = vulkano::ordered_passes_renderpass!(
@@ -402,6 +441,8 @@ fn main() {
depth_range: 0.0..1.0,
};
let mut gstate = GState::default();
//let [RES_X, RES_Y] = images[0].dimensions().width_height();
let ([mut mesh_pipeline, mut implicit_pipeline], mut framebuffers) =
window_size_dependent_setup(
@@ -414,7 +455,12 @@ fn main() {
&images,
render_pass.clone(),
&mut viewport,
implicit_fs::SpecializationConstants {},
implicit_fs::SpecializationConstants {DISABLE_TRACE:gstate.debug.bounding_boxes as u32},
implicit_ms::SpecializationConstants {DISABLE_TRACE:gstate.debug.disable_meshcull as u32,
DISABLE_SCALING_1:gstate.debug.disable_meshscale1 as u32,
DISABLE_SCALING_2:gstate.debug.disable_meshscale2 as u32},
implicit_ts::SpecializationConstants {DISABLE_TRACE:gstate.debug.disable_taskcull as u32},
);
let command_buffer_allocator =
@@ -442,8 +488,6 @@ fn main() {
Subpass::from(render_pass.clone(), 1).unwrap(),
);
let mut gstate = GState::default();
let mut campos = Point3 {
x: 0f32,
y: 0f32,
@@ -491,7 +535,9 @@ fn main() {
.lights
.push(Light::new([-4., 6., -8.], [8., 4., 1.], 0.05));
let subbuffers = object_size_dependent_setup(memory_allocator.clone(), &gstate, &command_buffer_allocator, transfer_queue.clone());
let subbuffers = object_size_dependent_setup(memory_allocator.clone(), &gstate.csg, &command_buffer_allocator, transfer_queue.clone(), None, false);
let mut prevdub = PreviousDebug::default();
let mut render_start = Instant::now();
@@ -571,6 +617,10 @@ fn main() {
previous_frame_end.as_mut().unwrap().cleanup_finished();
if prevdub != gstate.debug {
recreate_swapchain = true;
}
if recreate_swapchain {
let (new_swapchain, new_images) =
match swapchain.recreate(SwapchainCreateInfo {
@@ -583,7 +633,7 @@ fn main() {
};
swapchain = new_swapchain;
let [RES_X, RES_Y] = images[0].dimensions().width_height();
//let [RES_X, RES_Y] = images[0].dimensions().width_height();
([mesh_pipeline, implicit_pipeline], framebuffers) =
window_size_dependent_setup(
&memory_allocator,
@@ -595,9 +645,14 @@ fn main() {
&new_images,
render_pass.clone(),
&mut viewport,
implicit_fs::SpecializationConstants {},
implicit_fs::SpecializationConstants {DISABLE_TRACE:gstate.debug.bounding_boxes as u32},
implicit_ms::SpecializationConstants {DISABLE_TRACE:gstate.debug.disable_meshcull as u32,
DISABLE_SCALING_1:gstate.debug.disable_meshscale1 as u32,
DISABLE_SCALING_2:gstate.debug.disable_meshscale2 as u32},
implicit_ts::SpecializationConstants {DISABLE_TRACE:gstate.debug.disable_taskcull as u32},
);
recreate_swapchain = false;
prevdub = gstate.debug;
}
let (mut push_constants, cam_set) = {
@@ -718,7 +773,7 @@ fn main() {
WriteDescriptorSet::buffer(3, subbuffers.scene.clone()),
WriteDescriptorSet::buffer(4, subbuffers.floats.clone()),
WriteDescriptorSet::buffer(5, subbuffers.vec2s.clone()),
WriteDescriptorSet::buffer(6, subbuffers.vec3s.clone()),
//WriteDescriptorSet::buffer(6, subbuffers.vec3s.clone()),
WriteDescriptorSet::buffer(7, subbuffers.vec4s.clone()),
//WriteDescriptorSet::buffer(8, subbuffers.mat2s.clone()),
//WriteDescriptorSet::buffer(9, subbuffers.mat3s.clone()),
@@ -730,6 +785,100 @@ fn main() {
)
.unwrap();
const COMPUTE_FUZZING: bool = false;
if COMPUTE_FUZZING {
let mut fake_csg = vec![];
for i in 0..(32)
{
fake_csg.push(
CSG{ name: format!("fuzz_{}",i), parts: vec![
CSGPart::opcode(InstructionSet::OPMulVec3Float, vec![Inputs::Variable, Inputs::Float(0.9)]),
CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]),
CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![Inputs::Variable, Inputs::Vec3([-0.7, (i as f64), -0.7].into())]),
CSGPart::opcode(InstructionSet::OPSDFSphere,vec![Inputs::Float(0.5), Inputs::Variable]),
//CSGPart::opcode(InstructionSet::OPNop,vec![]),
//CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]),
//CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![Inputs::Variable, Inputs::Vec3([-0.2, -0.2, -0.2].into())]),
//CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![Inputs::Variable, Inputs::Vec3([-0.0, -0.0, -0.0].into())]),
CSGPart::opcode(InstructionSet::OPSDFSphere,vec![Inputs::Float(1.2), Inputs::Variable]),
//CSGPart::opcode(InstructionSet::OPSDFBox, vec![Inputs::Variable, Inputs::Vec3([0.7, 0.7, 0.7].into())]),
CSGPart::opcode(InstructionSet::OPMinFloat, vec![Inputs::Variable,Inputs::Variable]),
CSGPart::opcode(InstructionSet::OPDivFloatFloat, vec![Inputs::Variable, Inputs::Float(0.9)]),
CSGPart::opcode(InstructionSet::OPStop, vec![Inputs::Variable]),
], pos: Point3::origin(), rot: Euler { x: Deg(0.), y: Deg(0.), z: Deg(0.) }, scale: Vector3 { x: 1., y: 1., z: 1. } }
)
}
let compute_subbuffers = object_size_dependent_setup(memory_allocator.clone(), &fake_csg, &command_buffer_allocator, transfer_queue.clone(), Some(
[1.,1.,1.,1.,5.,1.]
),true);
let compute_result_buffer:Subbuffer<[cs::ty::Results]> = uniform_buffer.allocate_slice((fake_csg.len()+1) as u64).unwrap();
let compute_layout = compute_pipeline.layout().set_layouts().get(0).unwrap();
let compute_set = PersistentDescriptorSet::new(
&descriptor_set_allocator,
compute_layout.clone(),
[
//WriteDescriptorSet::buffer(0, uniform_buffer_subbuffer.clone()),
//WriteDescriptorSet::buffer(1, cam_set.clone()),
WriteDescriptorSet::buffer(2, compute_subbuffers.desc.clone()),
WriteDescriptorSet::buffer(3, compute_subbuffers.scene.clone()),
WriteDescriptorSet::buffer(4, compute_subbuffers.floats.clone()),
WriteDescriptorSet::buffer(5, compute_subbuffers.vec2s.clone()),
//WriteDescriptorSet::buffer(6, compute_subbuffers.vec3s.clone()),
WriteDescriptorSet::buffer(7, compute_subbuffers.vec4s.clone()),
//WriteDescriptorSet::buffer(8, compute_subbuffers.mat2s.clone()),
//WriteDescriptorSet::buffer(9, compute_subbuffers.mat3s.clone()),
//WriteDescriptorSet::buffer(10, compute_subbuffers.mat4s.clone()),
//WriteDescriptorSet::buffer(11, compute_subbuffers.mats.clone()),
WriteDescriptorSet::buffer(12, compute_subbuffers.deps.clone()),
//WriteDescriptorSet::buffer(20, compute_subbuffers.masks.clone()),
WriteDescriptorSet::buffer(30, compute_result_buffer.clone()),],
)
.unwrap();
let mut builder = AutoCommandBufferBuilder::primary(
&command_buffer_allocator,
queue.queue_family_index(),
CommandBufferUsage::OneTimeSubmit,
)
.unwrap();
builder
.bind_pipeline_compute(compute_pipeline.clone())
.bind_descriptor_sets(
PipelineBindPoint::Compute,
compute_pipeline.layout().clone(),
0, // 0 is the index of our set
compute_set,
)
.dispatch([1, 1, 1])
.unwrap();
let command_buffer = builder.build().unwrap();
let future = sync::now(device.clone())
.then_execute(queue.clone(), command_buffer)
.unwrap()
.then_signal_fence_and_flush()
.unwrap();
future.wait(None).unwrap();
let content = compute_result_buffer.read().unwrap();
for (val,csg) in content.iter().zip(fake_csg.iter()) {
println!("{:?}",val);
let expected = Interpreter::new(csg).scene(Vector3::new(1.,1.,1.)) as f32;
if expected != val.f[0] {
println!("ERROR: expected {}, got {}", expected, val.f[0]);
}
}
}
let (image_index, suboptimal, acquire_future) =
match acquire_next_image(swapchain.clone(), None) {
Ok(r) => r,
@@ -864,7 +1013,7 @@ fn main() {
}
/// This method is called once during initialization, then again whenever the window is resized
fn window_size_dependent_setup<Mms>(
fn window_size_dependent_setup<Fs,Ms,Ts>(
allocator: &StandardMemoryAllocator,
mesh_vs: &ShaderModule,
mesh_fs: &ShaderModule,
@@ -874,10 +1023,14 @@ fn window_size_dependent_setup<Mms>(
images: &[Arc<SwapchainImage>],
render_pass: Arc<RenderPass>,
viewport: &mut Viewport,
specs: Mms,
implicit_fs_specs: Fs,
implicit_ms_specs: Ms,
implicit_ts_specs: Ts,
) -> ([Arc<GraphicsPipeline>; 2], Vec<Arc<Framebuffer>>)
where
Mms: SpecializationConstants + Clone,
Fs: SpecializationConstants + Clone,
Ms: SpecializationConstants + Clone,
Ts: SpecializationConstants + Clone,
{
let dimensions = images[0].dimensions().width_height();
viewport.dimensions = [dimensions[0] as f32, dimensions[1] as f32];
@@ -887,7 +1040,7 @@ where
allocator,
dimensions,
SampleCount::Sample4,
Format::D16_UNORM,
Format::D16_UNORM, // D24_UNORM_S8_UINT
)
.unwrap(),
)
@@ -944,7 +1097,7 @@ where
depth_range: 0.0..1.0,
},
]))
.fragment_shader(mesh_fs.entry_point("main").unwrap(), specs.clone())
.fragment_shader(mesh_fs.entry_point("main").unwrap(), ())
.depth_stencil_state(DepthStencilState::simple_depth_test())
.rasterization_state(RasterizationState {
front_face: Fixed(Clockwise),
@@ -974,9 +1127,9 @@ where
depth_range: 0.0..1.0,
},
]))
.fragment_shader(implicit_fs.entry_point("main").unwrap(), specs)
.task_shader(implicit_ts.entry_point("main").unwrap(), ())
.mesh_shader(implicit_ms.entry_point("main").unwrap(), ())
.fragment_shader(implicit_fs.entry_point("main").unwrap(), implicit_fs_specs.clone())
.task_shader(implicit_ts.entry_point("main").unwrap(), implicit_ts_specs.clone())
.mesh_shader(implicit_ms.entry_point("main").unwrap(), implicit_ms_specs.clone())
.depth_stencil_state(DepthStencilState::simple_depth_test())
.rasterization_state(RasterizationState {
//front_face: Fixed(Clockwise),
@@ -999,11 +1152,19 @@ where
([mesh_pipeline, implicit_pipeline], framebuffers)
}
#[repr(C)]
#[derive(Clone,Copy,Pod,Zeroable, Default, Debug)]
struct Description {
pointers: [u32; 9],
bounds: [f32;6],
}
struct Subbuffers {
masks: Subbuffer<[[u8; 29]]>,
floats: Subbuffer<[f32]>,
vec2s: Subbuffer<[[f32; 2]]>,
vec3s: Subbuffer<[[f32; 3]]>,
//vec3s: Subbuffer<[[f32; 4]]>,
vec4s: Subbuffer<[[f32; 4]]>,
mat2s: Subbuffer<[[[f32; 2]; 2]]>,
mat3s: Subbuffer<[[[f32; 3]; 3]]>,
@@ -1011,7 +1172,7 @@ struct Subbuffers {
mats: Subbuffer<[[[f32; 4]; 4]]>,
scene: Subbuffer<[[u32; 4]]>,
deps: Subbuffer<[[u8; 2]]>,
desc: Subbuffer<[[u32; 10]]>,
desc: Subbuffer<[Description]>,
}
impl PartialEq<InputTypes> for Inputs {
@@ -1076,15 +1237,29 @@ where
buffer
}
fn f64tof32<const A:usize>(input: [[f64;A];A]) -> [[f32;A];A]
{
let mut out = [[0_f32;A];A];
for x in 0..input.len()
{
for y in 0..input.len()
{
out[x][y] = input[x][y] as f32;
}
}
out
}
fn object_size_dependent_setup(
allocator: Arc<StandardMemoryAllocator>,
state: &GState,
state: &Vec<CSG>,
command_allocator: &StandardCommandBufferAllocator,
queue: Arc<Queue>,
set_bound: Option<[f32;6]>,
actual: bool,
) -> Subbuffers {
let mut floats: Vec<f32> = vec![Default::default()];
let mut vec2s: Vec<[f32; 2]> = vec![Default::default()];
let mut vec3s: Vec<[f32; 3]> = vec![Default::default()];
let mut vec4s: Vec<[f32; 4]> = vec![Default::default()];
let mut mat2s: Vec<[[f32; 2]; 2]> = vec![Default::default()];
let mut mat3s: Vec<[[f32; 3]; 3]> = vec![Default::default()];
@@ -1092,16 +1267,15 @@ fn object_size_dependent_setup(
let mut mats: Vec<[[f32; 4]; 4]> = vec![Default::default()];
let mut scene: Vec<[u32; 4]> = vec![Default::default()];
let mut deps: Vec<[u8; 2]> = vec![Default::default()];
let mut desc: Vec<[u32; 10]> = vec![Default::default()];
let mut desc: Vec<Description> = vec![Default::default()];
'nextcsg: for csg in &state.csg {
'nextcsg: for csg in state {
let mut data: Vec<[u32; 4]> = vec![];
let to_push = [
scene.len() as u32,
floats.len() as u32,
vec2s.len() as u32,
vec3s.len() as u32,
vec4s.len() as u32,
mat2s.len() as u32,
mat3s.len() as u32,
@@ -1110,19 +1284,24 @@ fn object_size_dependent_setup(
deps.len() as u32,
];
let parts = vec![
let example = vec![
CSGPart::opcode(InstructionSet::OPMulVec3Float, vec![Inputs::Variable, Inputs::Float(0.9)]),
CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]),
CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![Inputs::Variable, Inputs::Vec3([-0.7, -1.2, -0.7].into())]),
CSGPart::opcode(InstructionSet::OPSDFSphere,vec![Inputs::Float(0.5), Inputs::Variable]),
//CSGPart::opcode(InstructionSet::OPNop,vec![]),
//CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]),
//CSGPart::opcode(InstructionSet::OPSubVec3Vec3, vec![Inputs::Variable, Inputs::Vec3([0., 0.2, 0.].into())]),
CSGPart::opcode(
InstructionSet::OPSDFSphere,
vec![Inputs::Float(1.0), Inputs::Variable],
),
//CSGPart::opcode(InstructionSet::OPAddVec3Vec3, 0b010000),
//CSGPart::opcode(InstructionSet::OPSDFSphere, 0b100000),
//CSGPart::opcode(InstructionSet::OPSmoothMinFloat, 0b000000),
//CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![Inputs::Variable, Inputs::Vec3([-0.2, -0.2, -0.2].into())]),
//CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![Inputs::Variable, Inputs::Vec3([-0.0, -0.0, -0.0].into())]),
//CSGPart::opcode(InstructionSet::OPSDFSphere,vec![Inputs::Float(1.2), Inputs::Variable]),
CSGPart::opcode(InstructionSet::OPSDFTorus, vec![Inputs::Vec2([0.7, 0.4].into()), Inputs::Variable]),
CSGPart::opcode(InstructionSet::OPMinFloat, vec![Inputs::Variable,Inputs::Variable]),
CSGPart::opcode(InstructionSet::OPDivFloatFloat, vec![Inputs::Variable, Inputs::Float(0.9)]),
CSGPart::opcode(InstructionSet::OPStop, vec![Inputs::Variable]),
];
let parts = if actual {&csg.parts} else {&example};
let mut dependencies: Vec<[u8; 2]> = vec![];
for _ in 0..parts.len() {
dependencies.push([u8::MAX, u8::MAX]);
@@ -1244,13 +1423,13 @@ fn object_size_dependent_setup(
}
} else {
match actual {
&Inputs::Float(f) => floats.push(f),
&Inputs::Vec2(f) => vec2s.push(f.into()),
&Inputs::Vec3(f) => vec3s.push(f.into()),
&Inputs::Vec4(f) => vec4s.push(f.into()),
&Inputs::Mat2(f) => mat2s.push(f.into()),
&Inputs::Mat3(f) => mat3s.push(f.into()),
&Inputs::Mat4(f) => mat4s.push(f.into()),
&Inputs::Float(f) => floats.push(f as f32),
&Inputs::Vec2(f) => vec2s.push(f.map(|x| x as f32).into()),
&Inputs::Vec3(f) => vec4s.push(f.map(|x| x as f32).extend(1.).into()),
&Inputs::Vec4(f) => vec4s.push(f.map(|x| x as f32).into()),
&Inputs::Mat2(f) => mat2s.push(f64tof32(f.into())),
&Inputs::Mat3(f) => mat3s.push(f64tof32(f.into())),
&Inputs::Mat4(f) => mat4s.push(f64tof32(f.into())),
&Inputs::Variable => unreachable!(),
}
}
@@ -1273,7 +1452,7 @@ fn object_size_dependent_setup(
let mut minor = 0;
let mut major = 0;
for part in parts {
for part in parts.iter() {
if major == data.len() {
data.push([0; 4]);
}
@@ -1292,7 +1471,23 @@ fn object_size_dependent_setup(
}
}
desc.push(to_push);
let temp_csg = &CSG { name: "test".to_string(), parts: parts.to_vec(), pos: Point3::origin(), rot: Euler::new(Deg(0.), Deg(0.), Deg(0.)), scale: Vector3 { x: 1., y: 1., z: 1. } };
let mut interpreter = interpreter::Interpreter::new( temp_csg);
const CLIPCHECK:Float =65536.;
let bounds = set_bound.unwrap_or([
((CLIPCHECK-interpreter.scene(Vector3::new(CLIPCHECK,0.,0.)))*1.00001) as f32,
((CLIPCHECK-interpreter.scene(Vector3::new(0.,CLIPCHECK,0.)))*1.00001) as f32,
((CLIPCHECK-interpreter.scene(Vector3::new(0.,0.,CLIPCHECK)))*1.00001) as f32,
((-CLIPCHECK+interpreter.scene(Vector3::new(-CLIPCHECK,0.,0.)))*1.00001) as f32,
((-CLIPCHECK+interpreter.scene(Vector3::new(0.,-CLIPCHECK,0.)))*1.00001) as f32,
((-CLIPCHECK+interpreter.scene(Vector3::new(0.,0.,-CLIPCHECK)))*1.00001) as f32,
]);
//println!("bounds: {:?}",bounds);
desc.push(Description {pointers:to_push,bounds});
scene.append(&mut data);
@@ -1303,8 +1498,7 @@ fn object_size_dependent_setup(
println!("floats: {:?}", floats);
println!("vec2s: {:?}", vec2s);
println!("vec3s: {:?}", vec3s);
println!("vec4s: {:?}", vec4s);
println!("vec3/4s: {:?}", vec4s);
println!("mat2s: {:?}", mat2s);
println!("mat3s: {:?}", mat3s);
println!("mat4s: {:?}", mat4s);
@@ -1338,7 +1532,7 @@ fn object_size_dependent_setup(
let csg_desc = gpu_buffer(desc, &allocator, &staging, command_allocator, queue.clone());
let csg_floats = gpu_buffer(floats, &allocator, &staging, command_allocator, queue.clone());
let csg_vec2s = gpu_buffer(vec2s, &allocator, &staging, command_allocator, queue.clone());
let csg_vec3s = gpu_buffer(vec3s, &allocator, &staging, command_allocator, queue.clone());
//let csg_vec3s = gpu_buffer(vec3s, &allocator, &staging, command_allocator, queue.clone());
let csg_vec4s = gpu_buffer(vec4s, &allocator, &staging, command_allocator, queue.clone());
let csg_mat2s = gpu_buffer(mat2s, &allocator, &staging, command_allocator, queue.clone());
let csg_mat3s = gpu_buffer(mat3s, &allocator, &staging, command_allocator, queue.clone());
@@ -1350,7 +1544,7 @@ fn object_size_dependent_setup(
masks: fragment_masks_buffer,
floats: csg_floats,
vec2s: csg_vec2s,
vec3s: csg_vec3s,
//vec3s: csg_vec3s,
vec4s: csg_vec4s,
mat2s: csg_mat2s,
mat3s: csg_mat3s,
+20 -12
View File
@@ -7,8 +7,8 @@ use std::{
use bytemuck::{Pod, Zeroable};
use cgmath::{
Deg, EuclideanSpace, Euler, Matrix2, Matrix3, Matrix4, Point3, SquareMatrix, Vector2, Vector3,
Vector4,
num_traits::float, Deg, EuclideanSpace, Euler, Matrix2, Matrix3, Matrix4, Point3, SquareMatrix,
Vector2, Vector3, Vector4,
};
use obj::{LoadConfig, ObjData, ObjError};
use serde::{Deserialize, Serialize};
@@ -55,17 +55,25 @@ pub struct CSG {
pub scale: Vector3<f32>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub type Float = f64;
pub type Vec2 = Vector2<Float>;
pub type Vec3 = Vector3<Float>;
pub type Vec4 = Vector4<Float>;
pub type Mat2 = Matrix2<Float>;
pub type Mat3 = Matrix3<Float>;
pub type Mat4 = Matrix4<Float>;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Inputs {
#[default]
Variable,
Float(f32),
Vec2(Vector2<f32>),
Vec3(Vector3<f32>),
Vec4(Vector4<f32>),
Mat2(Matrix2<f32>),
Mat3(Matrix3<f32>),
Mat4(Matrix4<f32>),
Float(Float),
Vec2(Vec2),
Vec3(Vec3),
Vec4(Vec4),
Mat2(Mat2),
Mat3(Mat3),
Mat4(Mat4),
}
#[repr(C)]
@@ -74,7 +82,7 @@ pub struct CSGPart {
pub code: u16,
pub opcode: InstructionSet,
pub constants: Vec<Inputs>,
pub material: Option<Matrix4<f32>>,
pub material: Option<Mat4>,
}
impl CSGPart {
@@ -101,7 +109,7 @@ impl CSGPart {
pub fn opcode_with_material(
opcode: InstructionSet,
inputs: Vec<Inputs>,
material: Matrix4<f32>,
material: Mat4,
) -> CSGPart {
let mut c = CSGPart::opcode(opcode, inputs);
c.material = Some(material);
BIN
View File
Binary file not shown.
-56846
View File
File diff suppressed because it is too large Load Diff
-49
View File
@@ -1,49 +0,0 @@
; SPIR-V
; Version: 1.5
; Generator: Google Shaderc over Glslang; 11
; Bound: 127
; Schema: 0
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main" %67 %72
OpExecutionMode %4 OriginUpperLeft
OpDecorate %67 Location 0
OpDecorate %72 Location 0
%void = OpTypeVoid
%3 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%uint = OpTypeInt 32 0
%uint_2 = OpConstant %uint 2
%_arr_v4float_uint_2 = OpTypeArray %v4float %uint_2
%bool = OpTypeBool
%v4bool = OpTypeVector %bool 4
%false = OpConstantFalse %bool
%34 = OpConstantComposite %v4bool %false %false %false %false
%float_0 = OpConstant %float 0
%38 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_0
%_ptr_Input__arr_v4float_uint_2 = OpTypePointer Input %_arr_v4float_uint_2
%67 = OpVariable %_ptr_Input__arr_v4float_uint_2 Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%72 = OpVariable %_ptr_Output_v4float Output
%float_1 = OpConstant %float 1
%4 = OpFunction %void None %3
%5 = OpLabel
%69 = OpLoad %_arr_v4float_uint_2 %67
%125 = OpCompositeExtract %v4float %69 0
%126 = OpCompositeExtract %v4float %69 1
%86 = OpExtInst %v4float %1 FAbs %125
%89 = OpExtInst %v4float %1 FAbs %126
%90 = OpExtInst %v4float %1 FMin %86 %89
%93 = OpFOrdLessThan %v4bool %125 %38
%96 = OpFOrdGreaterThan %v4bool %126 %38
%97 = OpSelect %v4bool %96 %93 %34
%100 = OpSelect %v4float %97 %38 %90
%102 = OpExtInst %float %1 Length %100
%110 = OpExtInst %v4float %1 FMax %86 %89
%111 = OpExtInst %float %1 Length %110
%78 = OpCompositeConstruct %v4float %102 %111 %float_0 %float_1
OpStore %72 %78
OpReturn
OpFunctionEnd