code:
// SPDX-FileCopyrightText: 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later

#pragma once

#include <array>
#include <atomic>
#include <condition_variable>
#include <functional>
#include <list>
#include <mutex>

#include "common/common_types.h"

namespace Tegra {

namespace Host1x {

class SyncpointManager {
public:
    u32 GetGuestSyncpointValue(u32 id) const {
        return syncpoints_guest[id].load(std::memory_order_acquire);
    }

    u32 GetHostSyncpointValue(u32 id) const {
        return syncpoints_host[id].load(std::memory_order_acquire);
    }

    struct RegisteredAction {
        explicit RegisteredAction(u32 expected_value_, std::function<void()>&& action_)
            : expected_value{expected_value_}, action{std::move(action_)} {}
        u32 expected_value;
        std::function<void()> action;
    };
    using ActionHandle = std::list<RegisteredAction>::iterator;

    template <typename Func>
    ActionHandle RegisterGuestAction(u32 syncpoint_id, u32 expected_value, Func&& action) {
        return RegisterAction(syncpoints_guest[syncpoint_id], guest_action_storage[syncpoint_id],
                              expected_value, std::move(action));
    }

    template <typename Func>
    ActionHandle RegisterHostAction(u32 syncpoint_id, u32 expected_value, Func&& action) {
        return RegisterAction(syncpoints_host[syncpoint_id], host_action_storage[syncpoint_id],
                              expected_value, std::move(action));
    }

    void DeregisterGuestAction(u32 syncpoint_id, const ActionHandle& handle);

    void DeregisterHostAction(u32 syncpoint_id, const ActionHandle& handle);

    void IncrementGuest(u32 syncpoint_id);

    void IncrementHost(u32 syncpoint_id);

    void WaitGuest(u32 syncpoint_id, u32 expected_value);

    void WaitHost(u32 syncpoint_id, u32 expected_value);

    bool IsReadyGuest(u32 syncpoint_id, u32 expected_value) const {
        return syncpoints_guest[syncpoint_id].load(std::memory_order_acquire) >= expected_value;
    }

    bool IsReadyHost(u32 syncpoint_id, u32 expected_value) const {
        return syncpoints_host[syncpoint_id].load(std::memory_order_acquire) >= expected_value;
    }

private:
    void Increment(std::atomic<u32>& syncpoint, std::condition_variable& wait_cv,
                   std::list<RegisteredAction>& action_storage);

    ActionHandle RegisterAction(std::atomic<u32>& syncpoint,
                                std::list<RegisteredAction>& action_storage, u32 expected_value,
                                std::function<void()>&& action);

    void DeregisterAction(std::list<RegisteredAction>& action_storage, const ActionHandle& handle);

    void Wait(std::atomic<u32>& syncpoint, std::condition_variable& wait_cv, u32 expected_value);

    static constexpr size_t NUM_MAX_SYNCPOINTS = 192;

    std::array<std::atomic<u32>, NUM_MAX_SYNCPOINTS> syncpoints_guest{};
    std::array<std::atomic<u32>, NUM_MAX_SYNCPOINTS> syncpoints_host{};

    std::array<std::list<RegisteredAction>, NUM_MAX_SYNCPOINTS> guest_action_storage;
    std::array<std::list<RegisteredAction>, NUM_MAX_SYNCPOINTS> host_action_storage;

    std::mutex guard;
    std::condition_variable wait_guest_cv;
    std::condition_variable wait_host_cv;
};

} // namespace Host1x

} // namespace Tegra


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <array>

extern "C" {
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#endif
#include <libswscale/swscale.h>
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
}

#include "common/assert.h"
#include "common/bit_field.h"
#include "common/logging/log.h"

#include "video_core/engines/maxwell_3d.h"
#include "video_core/host1x/host1x.h"
#include "video_core/host1x/nvdec.h"
#include "video_core/host1x/vic.h"
#include "video_core/memory_manager.h"
#include "video_core/textures/decoders.h"

namespace Tegra {

namespace Host1x {

namespace {
enum class VideoPixelFormat : u64_le {
    RGBA8 = 0x1f,
    BGRA8 = 0x20,
    RGBX8 = 0x23,
    YUV420 = 0x44,
};
} // Anonymous namespace

union VicConfig {
    u64_le raw{};
    BitField<0, 7, VideoPixelFormat> pixel_format;
    BitField<7, 2, u64_le> chroma_loc_horiz;
    BitField<9, 2, u64_le> chroma_loc_vert;
    BitField<11, 4, u64_le> block_linear_kind;
    BitField<15, 4, u64_le> block_linear_height_log2;
    BitField<32, 14, u64_le> surface_width_minus1;
    BitField<46, 14, u64_le> surface_height_minus1;
};

Vic::Vic(Host1x& host1x_, std::shared_ptr<Nvdec> nvdec_processor_)
    : host1x(host1x_),
      nvdec_processor(std::move(nvdec_processor_)), converted_frame_buffer{nullptr, av_free} {}

Vic::~Vic() = default;

void Vic::ProcessMethod(Method method, u32 argument) {
    LOG_DEBUG(HW_GPU, "Vic method 0x{:X}", static_cast<u32>(method));
    const u64 arg = static_cast<u64>(argument) << 8;
    switch (method) {
    case Method::Execute:
        Execute();
        break;
    case Method::SetConfigStructOffset:
        config_struct_address = arg;
        break;
    case Method::SetOutputSurfaceLumaOffset:
        output_surface_luma_address = arg;
        break;
    case Method::SetOutputSurfaceChromaOffset:
        output_surface_chroma_address = arg;
        break;
    default:
        break;
    }
}

void Vic::Execute() {
    if (output_surface_luma_address == 0) {
        LOG_ERROR(Service_NVDRV, "VIC Luma address not set.");
        return;
    }
    const VicConfig config{host1x.GMMU().Read<u64>(config_struct_address + 0x20)};
    auto frame = nvdec_processor->GetFrame();
    if (!frame) {
        return;
    }
    const u64 surface_width = config.surface_width_minus1 + 1;
    const u64 surface_height = config.surface_height_minus1 + 1;
    if (static_cast<u64>(frame->GetWidth()) != surface_width ||
        static_cast<u64>(frame->GetHeight()) != surface_height) {
        // TODO: Properly support multiple video streams with differing frame dimensions
        LOG_WARNING(Service_NVDRV, "Frame dimensions {}x{} don't match surface dimensions {}x{}",
                    frame->GetWidth(), frame->GetHeight(), surface_width, surface_height);
    }
    switch (config.pixel_format) {
    case VideoPixelFormat::RGBA8:
    case VideoPixelFormat::BGRA8:
    case VideoPixelFormat::RGBX8:
        WriteRGBFrame(std::move(frame), config);
        break;
    case VideoPixelFormat::YUV420:
        WriteYUVFrame(std::move(frame), config);
        break;
    default:
        UNIMPLEMENTED_MSG("Unknown video pixel format {:X}", config.pixel_format.Value());
        break;
    }
}

void Vic::WriteRGBFrame(std::unique_ptr<FFmpeg::Frame> frame, const VicConfig& config) {
    LOG_TRACE(Service_NVDRV, "Writing RGB Frame");

    const auto frame_width = frame->GetWidth();
    const auto frame_height = frame->GetHeight();
    const auto frame_format = frame->GetPixelFormat();

    if (!scaler_ctx || frame_width != scaler_width || frame_height != scaler_height) {
        const AVPixelFormat target_format = [pixel_format = config.pixel_format]() {
            switch (pixel_format) {
            case VideoPixelFormat::RGBA8:
                return AV_PIX_FMT_RGBA;
            case VideoPixelFormat::BGRA8:
                return AV_PIX_FMT_BGRA;
            case VideoPixelFormat::RGBX8:
                return AV_PIX_FMT_RGB0;
            default:
                return AV_PIX_FMT_RGBA;
            }
        }();

        sws_freeContext(scaler_ctx);
        // Frames are decoded into either YUV420 or NV12 formats. Convert to desired RGB format
        scaler_ctx = sws_getContext(frame_width, frame_height, frame_format, frame_width,
                                    frame_height, target_format, 0, nullptr, nullptr, nullptr);
        scaler_width = frame_width;
        scaler_height = frame_height;
        converted_frame_buffer.reset();
    }
    if (!converted_frame_buffer) {
        const size_t frame_size = frame_width * frame_height * 4;
        converted_frame_buffer = AVMallocPtr{static_cast<u8*>(av_malloc(frame_size)), av_free};
    }
    const std::array<int, 4> converted_stride{frame_width * 4, frame_height * 4, 0, 0};
    u8* const converted_frame_buf_addr{converted_frame_buffer.get()};
    sws_scale(scaler_ctx, frame->GetPlanes(), frame->GetStrides(), 0, frame_height,
              &converted_frame_buf_addr, converted_stride.data());

    // Use the minimum of surface/frame dimensions to avoid buffer overflow.
    const u32 surface_width = static_cast<u32>(config.surface_width_minus1) + 1;
    const u32 surface_height = static_cast<u32>(config.surface_height_minus1) + 1;
    const u32 width = std::min(surface_width, static_cast<u32>(frame_width));
    const u32 height = std::min(surface_height, static_cast<u32>(frame_height));
    const u32 blk_kind = static_cast<u32>(config.block_linear_kind);
    if (blk_kind != 0) {
        // swizzle pitch linear to block linear
        const u32 block_height = static_cast<u32>(config.block_linear_height_log2);
        const auto size = Texture::CalculateSize(true, 4, width, height, 1, block_height, 0);
        luma_buffer.resize_destructive(size);
        std::span<const u8> frame_buff(converted_frame_buf_addr, 4 * width * height);
        Texture::SwizzleSubrect(luma_buffer, frame_buff, 4, width, height, 1, 0, 0, width, height,
                                block_height, 0, width * 4);

        host1x.GMMU().WriteBlock(output_surface_luma_address, luma_buffer.data(), size);
    } else {
        // send pitch linear frame
        const size_t linear_size = width * height * 4;
        host1x.GMMU().WriteBlock(output_surface_luma_address, converted_frame_buf_addr,
                                 linear_size);
    }
}

void Vic::WriteYUVFrame(std::unique_ptr<FFmpeg::Frame> frame, const VicConfig& config) {
    LOG_TRACE(Service_NVDRV, "Writing YUV420 Frame");

    const std::size_t surface_width = config.surface_width_minus1 + 1;
    const std::size_t surface_height = config.surface_height_minus1 + 1;
    const std::size_t aligned_width = (surface_width + 0xff) & ~0xffUL;
    // Use the minimum of surface/frame dimensions to avoid buffer overflow.
    const auto frame_width = std::min(surface_width, static_cast<size_t>(frame->GetWidth()));
    const auto frame_height = std::min(surface_height, static_cast<size_t>(frame->GetHeight()));

    const auto stride = static_cast<size_t>(frame->GetStride(0));

    luma_buffer.resize_destructive(aligned_width * surface_height);
    chroma_buffer.resize_destructive(aligned_width * surface_height / 2);

    // Populate luma buffer
    const u8* luma_src = frame->GetData(0);
    for (std::size_t y = 0; y < frame_height; ++y) {
        const std::size_t src = y * stride;
        const std::size_t dst = y * aligned_width;
        std::memcpy(luma_buffer.data() + dst, luma_src + src, frame_width);
    }
    host1x.GMMU().WriteBlock(output_surface_luma_address, luma_buffer.data(), luma_buffer.size());

    // Chroma
    const std::size_t half_height = frame_height / 2;
    const auto half_stride = static_cast<size_t>(frame->GetStride(1));

    switch (frame->GetPixelFormat()) {
    case AV_PIX_FMT_YUV420P: {
        // Frame from FFmpeg software
        // Populate chroma buffer from both channels with interleaving.
        const std::size_t half_width = frame_width / 2;
        u8* chroma_buffer_data = chroma_buffer.data();
        const u8* chroma_b_src = frame->GetData(1);
        const u8* chroma_r_src = frame->GetData(2);
        for (std::size_t y = 0; y < half_height; ++y) {
            const std::size_t src = y * half_stride;
            const std::size_t dst = y * aligned_width;
            for (std::size_t x = 0; x < half_width; ++x) {
                chroma_buffer_data[dst + x * 2] = chroma_b_src[src + x];
                chroma_buffer_data[dst + x * 2 + 1] = chroma_r_src[src + x];
            }
        }
        break;
    }
    case AV_PIX_FMT_NV12: {
        // Frame from VA-API hardware
        // This is already interleaved so just copy
        const u8* chroma_src = frame->GetData(1);
        for (std::size_t y = 0; y < half_height; ++y) {
            const std::size_t src = y * stride;
            const std::size_t dst = y * aligned_width;
            std::memcpy(chroma_buffer.data() + dst, chroma_src + src, frame_width);
        }
        break;
    }
    default:
        ASSERT(false);
        break;
    }
    host1x.GMMU().WriteBlock(output_surface_chroma_address, chroma_buffer.data(),
                             chroma_buffer.size());
}

} // namespace Host1x

} // namespace Tegra

repo_name: litucks/torzu

license: mit


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <memory>

#include "common/common_types.h"
#include "common/scratch_buffer.h"

struct SwsContext;

namespace Tegra {

namespace Host1x {

class Host1x;
class Nvdec;
union VicConfig;

class Vic {
public:
    enum class Method : u32 {
        Execute = 0xc0,
        SetControlParams = 0x1c1,
        SetConfigStructOffset = 0x1c2,
        SetOutputSurfaceLumaOffset = 0x1c8,
        SetOutputSurfaceChromaOffset = 0x1c9,
        SetOutputSurfaceChromaUnusedOffset = 0x1ca
    };

    explicit Vic(Host1x& host1x, std::shared_ptr<Nvdec> nvdec_processor);

    ~Vic();

    /// Write to the device state.
    void ProcessMethod(Method method, u32 argument);

private:
    void Execute();

    void WriteRGBFrame(std::unique_ptr<FFmpeg::Frame> frame, const VicConfig& config);

    void WriteYUVFrame(std::unique_ptr<FFmpeg::Frame> frame, const VicConfig& config);

    Host1x& host1x;
    std::shared_ptr<Tegra::Host1x::Nvdec> nvdec_processor;

    /// Avoid reallocation of the following buffers every frame, as their
    /// size does not change during a stream
    using AVMallocPtr = std::unique_ptr<u8, decltype(&av_free)>;
    AVMallocPtr converted_frame_buffer;
    Common::ScratchBuffer<u8> luma_buffer;
    Common::ScratchBuffer<u8> chroma_buffer;

    GPUVAddr config_struct_address{};
    GPUVAddr output_surface_luma_address{};
    GPUVAddr output_surface_chroma_address{};

    SwsContext* scaler_ctx{};
    s32 scaler_width{};
    s32 scaler_height{};
};

} // namespace Host1x

} // namespace Tegra


code:
# SPDX-FileCopyrightText: 2018 yuzu Emulator Project
# SPDX-License-Identifier: GPL-2.0-or-later

set(FIDELITYFX_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/externals/FidelityFX-FSR/ffx-fsr)

set(FIDELITYFX_FILES
    ${FIDELITYFX_INCLUDE_DIR}/ffx_a.h
    ${FIDELITYFX_INCLUDE_DIR}/ffx_fsr1.h
)

set(GLSL_INCLUDES
    fidelityfx_fsr.frag
    ${FIDELITYFX_FILES}
)

set(SHADER_FILES
    astc_decoder.comp
    blit_color_float.frag
    block_linear_unswizzle_2d.comp
    block_linear_unswizzle_3d.comp
    convert_abgr8_to_d24s8.frag
    convert_abgr8_to_d32f.frag
    convert_d32f_to_abgr8.frag
    convert_d24s8_to_abgr8.frag
    convert_depth_to_float.frag
    convert_float_to_depth.frag
    convert_msaa_to_non_msaa.comp
    convert_non_msaa_to_msaa.comp
    convert_s8d24_to_abgr8.frag
    full_screen_triangle.vert
    fxaa.frag
    fxaa.vert
    opengl_convert_s8d24.comp
    opengl_copy_bc4.comp
    opengl_fidelityfx_fsr.frag
    opengl_fidelityfx_fsr_easu.frag
    opengl_fidelityfx_fsr_rcas.frag
    opengl_lmem_warmup.comp
    opengl_present.frag
    opengl_present.vert
    opengl_present_scaleforce.frag
    opengl_smaa.glsl
    pitch_unswizzle.comp
    present_bicubic.frag
    present_gaussian.frag
    queries_prefix_scan_sum.comp
    queries_prefix_scan_sum_nosubgroups.comp
    resolve_conditional_render.comp
    smaa_edge_detection.vert
    smaa_edge_detection.frag
    smaa_blending_weight_calculation.vert
    smaa_blending_weight_calculation.frag
    smaa_neighborhood_blending.vert
    smaa_neighborhood_blending.frag
    vulkan_blit_depth_stencil.frag
    vulkan_color_clear.frag
    vulkan_color_clear.vert
    vulkan_depthstencil_clear.frag
    vulkan_fidelityfx_fsr.vert
    vulkan_fidelityfx_fsr_easu_fp16.frag
    vulkan_fidelityfx_fsr_easu_fp32.frag
    vulkan_fidelityfx_fsr_rcas_fp16.frag
    vulkan_fidelityfx_fsr_rcas_fp32.frag
    vulkan_present.frag
    vulkan_present.vert
    vulkan_present_scaleforce_fp16.frag
    vulkan_present_scaleforce_fp32.frag
    vulkan_quad_indexed.comp
    vulkan_turbo_mode.comp
    vulkan_uint8.comp
)

find_program(GLSLANGVALIDATOR "glslangValidator")
if ("${GLSLANGVALIDATOR}" STREQUAL "GLSLANGVALIDATOR-NOTFOUND")
    message(FATAL_ERROR "Required program `glslangValidator` not found.")
endif()

set(GLSL_FLAGS "")
set(SPIR_V_VERSION "spirv1.3")
set(QUIET_FLAG "--quiet")

set(SHADER_INCLUDE ${CMAKE_CURRENT_BINARY_DIR}/include)
set(SHADER_DIR ${SHADER_INCLUDE}/video_core/host_shaders)
set(HOST_SHADERS_INCLUDE ${SHADER_INCLUDE} PARENT_SCOPE)

set(INPUT_FILE ${CMAKE_CURRENT_SOURCE_DIR}/source_shader.h.in)
set(HEADER_GENERATOR ${CMAKE_CURRENT_SOURCE_DIR}/StringShaderHeader.cmake)

# Check if `--quiet` is available on host's glslangValidator version
# glslangValidator prints to STDERR iff an unrecognized flag is passed to it
execute_process(
    COMMAND
        ${GLSLANGVALIDATOR} ${QUIET_FLAG}
    ERROR_VARIABLE
        GLSLANG_ERROR
    # STDOUT variable defined to silence unnecessary output during CMake configuration
    OUTPUT_VARIABLE
        GLSLANG_OUTPUT
)

if (NOT GLSLANG_ERROR STREQUAL "")
    message(WARNING "Refusing to use unavailable flag `${QUIET_FLAG}` on `${GLSLANGVALIDATOR}`")
    set(QUIET_FLAG "")
endif()

foreach(FILENAME IN ITEMS ${SHADER_FILES})
    string(REPLACE "." "_" SHADER_NAME ${FILENAME})
    set(SOURCE_FILE ${CMAKE_CURRENT_SOURCE_DIR}/${FILENAME})
    # Skip generating source headers on Vulkan exclusive files
    if (NOT ${FILENAME} MATCHES "vulkan.*")
        set(SOURCE_HEADER_FILE ${SHADER_DIR}/${SHADER_NAME}.h)
        add_custom_command(
            OUTPUT
                ${SOURCE_HEADER_FILE}
            COMMAND
                ${CMAKE_COMMAND} -P ${HEADER_GENERATOR} ${SOURCE_FILE} ${SOURCE_HEADER_FILE} ${INPUT_FILE}
            MAIN_DEPENDENCY
                ${SOURCE_FILE}
            DEPENDS
                ${INPUT_FILE}
                # HEADER_GENERATOR should be included here but msbuild seems to assume it's always modified
        )
        set(SHADER_HEADERS ${SHADER_HEADERS} ${SOURCE_HEADER_FILE})
    endif()
    # Skip compiling to SPIR-V OpenGL exclusive files
    if (NOT ${FILENAME} MATCHES "opengl.*")
        string(TOUPPER ${SHADER_NAME}_SPV SPIRV_VARIABLE_NAME)
        set(SPIRV_HEADER_FILE ${SHADER_DIR}/${SHADER_NAME}_spv.h)
        add_custom_command(
            OUTPUT
                ${SPIRV_HEADER_FILE}
            COMMAND
                ${GLSLANGVALIDATOR} -V ${QUIET_FLAG} -I"${FIDELITYFX_INCLUDE_DIR}" ${GLSL_FLAGS} --variable-name ${SPIRV_VARIABLE_NAME} -o ${SPIRV_HEADER_FILE} ${SOURCE_FILE} --target-env ${SPIR_V_VERSION}
            MAIN_DEPENDENCY
                ${SOURCE_FILE}
        )
        set(SHADER_HEADERS ${SHADER_HEADERS} ${SPIRV_HEADER_FILE})
    endif()
endforeach()

foreach(FILEPATH IN ITEMS ${FIDELITYFX_FILES})
    get_filename_component(FILENAME ${FILEPATH} NAME)
    string(REPLACE "." "_" HEADER_NAME ${FILENAME})
    set(SOURCE_FILE ${FILEPATH})
    set(SOURCE_HEADER_FILE ${SHADER_DIR}/${HEADER_NAME}.h)
    add_custom_command(
        OUTPUT
            ${SOURCE_HEADER_FILE}
        COMMAND
            ${CMAKE_COMMAND} -P ${HEADER_GENERATOR} ${SOURCE_FILE} ${SOURCE_HEADER_FILE} ${INPUT_FILE}
        MAIN_DEPENDENCY
            ${SOURCE_FILE}
        DEPENDS
            ${INPUT_FILE}
            # HEADER_GENERATOR should be included here but msbuild seems to assume it's always modified
    )
    set(SHADER_HEADERS ${SHADER_HEADERS} ${SOURCE_HEADER_FILE})
endforeach()

set(SHADER_SOURCES ${SHADER_FILES})
list(APPEND SHADER_SOURCES ${GLSL_INCLUDES})

add_custom_target(host_shaders
    DEPENDS
        ${SHADER_HEADERS}
    SOURCES
        ${SHADER_SOURCES}
)


code:
# SPDX-FileCopyrightText: 2020 yuzu Emulator Project
# SPDX-License-Identifier: GPL-2.0-or-later

set(SOURCE_FILE ${CMAKE_ARGV3})
set(HEADER_FILE ${CMAKE_ARGV4})
set(INPUT_FILE ${CMAKE_ARGV5})

get_filename_component(CONTENTS_NAME ${SOURCE_FILE} NAME)
string(REPLACE "." "_" CONTENTS_NAME ${CONTENTS_NAME})
string(TOUPPER ${CONTENTS_NAME} CONTENTS_NAME)

FILE(READ ${SOURCE_FILE} line_contents)

# CMake separates list elements with semicolons, but semicolons
# are used extensively in the shader code.
# Replace with a temporary marker, to be reverted later.
STRING(REGEX REPLACE ";" "{{SEMICOLON}}" line_contents "${line_contents}")

# Make every line an individual element in the CMake list.
STRING(REGEX REPLACE "\n" ";" line_contents "${line_contents}")

# Build the shader string, wrapping each line in double quotes.
foreach(line IN LISTS line_contents)
    string(CONCAT CONTENTS "${CONTENTS}" "R\"(${line}\n)\" ")
endforeach()

# Revert the original semicolons in the source.
STRING(REGEX REPLACE "{{SEMICOLON}}" ";" CONTENTS "${CONTENTS}")

get_filename_component(OUTPUT_DIR ${HEADER_FILE} DIRECTORY)
make_directory(${OUTPUT_DIR})
configure_file(${INPUT_FILE} ${HEADER_FILE} @ONLY)


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450

#ifdef VULKAN

#define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants {
#define END_PUSH_CONSTANTS };
#define UNIFORM(n)
#define BINDING_INPUT_BUFFER 0
#define BINDING_OUTPUT_IMAGE 1

#else // ^^^ Vulkan ^^^ // vvv OpenGL vvv

#define BEGIN_PUSH_CONSTANTS
#define END_PUSH_CONSTANTS
#define UNIFORM(n) layout(location = n) uniform
#define BINDING_INPUT_BUFFER 0
#define BINDING_OUTPUT_IMAGE 0

#endif

layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;

BEGIN_PUSH_CONSTANTS
UNIFORM(1) uvec2 block_dims;
UNIFORM(2) uint layer_stride;
UNIFORM(3) uint block_size;
UNIFORM(4) uint x_shift;
UNIFORM(5) uint block_height;
UNIFORM(6) uint block_height_mask;
END_PUSH_CONSTANTS

struct EncodingData {
    uint data;
};

layout(binding = BINDING_INPUT_BUFFER, std430) readonly restrict buffer InputBufferU32 {
    uvec4 astc_data[];
};

layout(binding = BINDING_OUTPUT_IMAGE, rgba8) uniform writeonly restrict image2DArray dest_image;

const uint GOB_SIZE_X_SHIFT = 6;
const uint GOB_SIZE_Y_SHIFT = 3;
const uint GOB_SIZE_SHIFT = GOB_SIZE_X_SHIFT + GOB_SIZE_Y_SHIFT;

const uint BYTES_PER_BLOCK_LOG2 = 4;

const uint JUST_BITS = 0u;
const uint QUINT = 1u;
const uint TRIT = 2u;

// ASTC Encodings data, sorted in ascending order based on their BitLength value
// (see GetBitLength() function)
const uint encoding_values[22] = uint[](
    (JUST_BITS), (JUST_BITS | (1u << 8u)), (TRIT), (JUST_BITS | (2u << 8u)),
    (QUINT), (TRIT | (1u << 8u)), (JUST_BITS | (3u << 8u)), (QUINT | (1u << 8u)),
    (TRIT | (2u << 8u)), (JUST_BITS | (4u << 8u)), (QUINT | (2u << 8u)), (TRIT | (3u << 8u)),
    (JUST_BITS | (5u << 8u)), (QUINT | (3u << 8u)), (TRIT | (4u << 8u)), (JUST_BITS | (6u << 8u)),
    (QUINT | (4u << 8u)), (TRIT | (5u << 8u)), (JUST_BITS | (7u << 8u)), (QUINT | (5u << 8u)),
    (TRIT | (6u << 8u)), (JUST_BITS | (8u << 8u)));

// Input ASTC texture globals
int total_bitsread = 0;
uvec4 local_buff;

// Color data globals
uvec4 color_endpoint_data;
int color_bitsread = 0;

// Global "vector" to be pushed into when decoding
// At most will require BLOCK_WIDTH x BLOCK_HEIGHT in single plane mode
// At most will require BLOCK_WIDTH x BLOCK_HEIGHT x 2 in dual plane mode
// So the maximum would be 144 (12 x 12) elements, x 2 for two planes
#define DIVCEIL(number, divisor) (number + divisor - 1) / divisor
#define ARRAY_NUM_ELEMENTS 144
#define VECTOR_ARRAY_SIZE DIVCEIL(ARRAY_NUM_ELEMENTS * 2, 4)
uint result_vector[ARRAY_NUM_ELEMENTS * 2];

int result_index = 0;
uint result_vector_max_index;
bool result_limit_reached = false;

// EncodingData helpers
uint Encoding(EncodingData val) {
    return bitfieldExtract(val.data, 0, 8);
}
uint NumBits(EncodingData val) {
    return bitfieldExtract(val.data, 8, 8);
}
uint BitValue(EncodingData val) {
    return bitfieldExtract(val.data, 16, 8);
}
uint QuintTritValue(EncodingData val) {
    return bitfieldExtract(val.data, 24, 8);
}

void Encoding(inout EncodingData val, uint v) {
    val.data = bitfieldInsert(val.data, v, 0, 8);
}
void NumBits(inout EncodingData val, uint v) {
    val.data = bitfieldInsert(val.data, v, 8, 8);
}
void BitValue(inout EncodingData val, uint v) {
    val.data = bitfieldInsert(val.data, v, 16, 8);
}
void QuintTritValue(inout EncodingData val, uint v) {
    val.data = bitfieldInsert(val.data, v, 24, 8);
}

EncodingData CreateEncodingData(uint encoding, uint num_bits, uint bit_val, uint quint_trit_val) {
    return EncodingData(((encoding) << 0u) | ((num_bits) << 8u) |
                        ((bit_val) << 16u) | ((quint_trit_val) << 24u));
}

void ResultEmplaceBack(EncodingData val) {
    if (result_index >= result_vector_max_index) {
        // Alert callers to avoid decoding more than needed by this phase
        result_limit_reached = true;
        return;
    }
    result_vector[result_index] = val.data;
    ++result_index;
}

uvec4 ReplicateByteTo16(uvec4 value) {
    return value * 0x101;
}

uint ReplicateBitTo7(uint value) {
    return value * 127;
}

uint ReplicateBitTo9(uint value) {
    return value * 511;
}

uint ReplicateBits(uint value, uint num_bits, uint to_bit) {
    if (value == 0 || num_bits == 0) {
        return 0;
    }
    if (num_bits >= to_bit) {
        return value;
    }
    const uint v = value & uint((1 << num_bits) - 1);
    uint res = v;
    uint reslen = num_bits;
    while (reslen < to_bit) {
        const uint num_dst_bits_to_shift_up = min(num_bits, to_bit - reslen);
        const uint num_src_bits_to_shift_down = num_bits - num_dst_bits_to_shift_up;

        res <<= num_dst_bits_to_shift_up;
        res |= (v >> num_src_bits_to_shift_down);
        reslen += num_bits;
    }
    return res;
}

uint FastReplicateTo8(uint value, uint num_bits) {
    return ReplicateBits(value, num_bits, 8);
}

uint FastReplicateTo6(uint value, uint num_bits) {
    return ReplicateBits(value, num_bits, 6);
}

uint Div3Floor(uint v) {
    return (v * 0x5556) >> 16;
}

uint Div3Ceil(uint v) {
    return Div3Floor(v + 2);
}

uint Div5Floor(uint v) {
    return (v * 0x3334) >> 16;
}

uint Div5Ceil(uint v) {
    return Div5Floor(v + 4);
}

uint Hash52(uint p) {
    p ^= p >> 15;
    p -= p << 17;
    p += p << 7;
    p += p << 4;
    p ^= p >> 5;
    p += p << 16;
    p ^= p >> 7;
    p ^= p >> 3;
    p ^= p << 6;
    p ^= p >> 17;
    return p;
}

uint Select2DPartition(uint seed, uint x, uint y, uint partition_count) {
    if ((block_dims.y * block_dims.x) < 32) {
        x <<= 1;
        y <<= 1;
    }

    seed += (partition_count - 1) * 1024;

    const uint rnum = Hash52(uint(seed));
    uint seed1 = uint(rnum & 0xF);
    uint seed2 = uint((rnum >> 4) & 0xF);
    uint seed3 = uint((rnum >> 8) & 0xF);
    uint seed4 = uint((rnum >> 12) & 0xF);
    uint seed5 = uint((rnum >> 16) & 0xF);
    uint seed6 = uint((rnum >> 20) & 0xF);
    uint seed7 = uint((rnum >> 24) & 0xF);
    uint seed8 = uint((rnum >> 28) & 0xF);

    seed1 = (seed1 * seed1);
    seed2 = (seed2 * seed2);
    seed3 = (seed3 * seed3);
    seed4 = (seed4 * seed4);
    seed5 = (seed5 * seed5);
    seed6 = (seed6 * seed6);
    seed7 = (seed7 * seed7);
    seed8 = (seed8 * seed8);

    uint sh1, sh2;
    if ((seed & 1) > 0) {
        sh1 = (seed & 2) > 0 ? 4 : 5;
        sh2 = (partition_count == 3) ? 6 : 5;
    } else {
        sh1 = (partition_count == 3) ? 6 : 5;
        sh2 = (seed & 2) > 0 ? 4 : 5;
    }
    seed1 >>= sh1;
    seed2 >>= sh2;
    seed3 >>= sh1;
    seed4 >>= sh2;
    seed5 >>= sh1;
    seed6 >>= sh2;
    seed7 >>= sh1;
    seed8 >>= sh2;

    uint a = seed1 * x + seed2 * y + (rnum >> 14);
    uint b = seed3 * x + seed4 * y + (rnum >> 10);
    uint c = seed5 * x + seed6 * y + (rnum >> 6);
    uint d = seed7 * x + seed8 * y + (rnum >> 2);

    a &= 0x3F;
    b &= 0x3F;
    c &= 0x3F;
    d &= 0x3F;

    if (partition_count < 4) {
        d = 0;
    }
    if (partition_count < 3) {
        c = 0;
    }

    if (a >= b && a >= c && a >= d) {
        return 0;
    } else if (b >= c && b >= d) {
        return 1;
    } else if (c >= d) {
        return 2;
    } else {
        return 3;
    }
}

uint ExtractBits(uvec4 payload, int offset, int bits) {
    if (bits <= 0) {
        return 0;
    }
    if (bits > 32) {
        return 0;
    }
    const int last_offset = offset + bits - 1;
    const int shifted_offset = offset >> 5;
    if ((last_offset >> 5) == shifted_offset) {
        return bitfieldExtract(payload[shifted_offset], offset & 31, bits);
    }
    const int first_bits = 32 - (offset & 31);
    const int result_first = int(bitfieldExtract(payload[shifted_offset], offset & 31, first_bits));
    const int result_second = int(bitfieldExtract(payload[shifted_offset + 1], 0, bits - first_bits));
    return result_first | (result_second << first_bits);
}

uint StreamBits(uint num_bits) {
    const int int_bits = int(num_bits);
    const uint ret = ExtractBits(local_buff, total_bitsread, int_bits);
    total_bitsread += int_bits;
    return ret;
}

void SkipBits(uint num_bits) {
    const int int_bits = int(num_bits);
    total_bitsread += int_bits;
}

uint StreamColorBits(uint num_bits) {
    const int int_bits = int(num_bits);
    const uint ret = ExtractBits(color_endpoint_data, color_bitsread, int_bits);
    color_bitsread += int_bits;
    return ret;
}

EncodingData GetEncodingFromVector(uint index) {
    const uint data = result_vector[index];
    return EncodingData(data);
}

// Returns the number of bits required to encode n_vals values.
uint GetBitLength(uint n_vals, uint encoding_index) {
    const EncodingData encoding_value = EncodingData(encoding_values[encoding_index]);
    const uint encoding = Encoding(encoding_value);
    uint total_bits = NumBits(encoding_value) * n_vals;
    if (encoding == TRIT) {
        total_bits += Div5Ceil(n_vals * 8);
    } else if (encoding == QUINT) {
        total_bits += Div3Ceil(n_vals * 7);
    }
    return total_bits;
}

uint GetNumWeightValues(uvec2 size, bool dual_plane) {
    uint n_vals = size.x * size.y;
    if (dual_plane) {
        n_vals *= 2;
    }
    return n_vals;
}

uint GetPackedBitSize(uvec2 size, bool dual_plane, uint max_weight) {
    const uint n_vals = GetNumWeightValues(size, dual_plane);
    return GetBitLength(n_vals, max_weight);
}

uint BitsBracket(uint bits, uint pos) {
    return ((bits >> pos) & 1);
}

uint BitsOp(uint bits, uint start, uint end) {
    const uint mask = (1 << (end - start + 1)) - 1;
    return ((bits >> start) & mask);
}

void DecodeQuintBlock(uint num_bits) {
    uvec3 m;
    uvec4 qQ;
    m[0] = StreamColorBits(num_bits);
    qQ.w = StreamColorBits(3);
    m[1] = StreamColorBits(num_bits);
    qQ.w |= StreamColorBits(2) << 3;
    m[2] = StreamColorBits(num_bits);
    qQ.w |= StreamColorBits(2) << 5;
    if (BitsOp(qQ.w, 1, 2) == 3 && BitsOp(qQ.w, 5, 6) == 0) {
        qQ.x = 4;
        qQ.y = 4;
        qQ.z = (BitsBracket(qQ.w, 0) << 2) | ((BitsBracket(qQ.w, 4) & ~BitsBracket(qQ.w, 0)) << 1) |
              (BitsBracket(qQ.w, 3) & ~BitsBracket(qQ.w, 0));
    } else {
        uint C = 0;
        if (BitsOp(qQ.w, 1, 2) == 3) {
            qQ.z = 4;
            C = (BitsOp(qQ.w, 3, 4) << 3) | ((~BitsOp(qQ.w, 5, 6) & 3) << 1) | BitsBracket(qQ.w, 0);
        } else {
            qQ.z = BitsOp(qQ.w, 5, 6);
            C = BitsOp(qQ.w, 0, 4);
        }
        if (BitsOp(C, 0, 2) == 5) {
            qQ.y = 4;
            qQ.x = BitsOp(C, 3, 4);
        } else {
            qQ.y = BitsOp(C, 3, 4);
            qQ.x = BitsOp(C, 0, 2);
        }
    }
    for (uint i = 0; i < 3; i++) {
        const EncodingData val = CreateEncodingData(QUINT, num_bits, m[i], qQ[i]);
        ResultEmplaceBack(val);
    }
}

void DecodeTritBlock(uint num_bits) {
    uvec4 m;
    uvec4 t;
    uvec3 Tm5t5;
    m[0] = StreamColorBits(num_bits);
    Tm5t5.x = StreamColorBits(2);
    m[1] = StreamColorBits(num_bits);
    Tm5t5.x |= StreamColorBits(2) << 2;
    m[2] = StreamColorBits(num_bits);
    Tm5t5.x |= StreamColorBits(1) << 4;
    m[3] = StreamColorBits(num_bits);
    Tm5t5.x |= StreamColorBits(2) << 5;
    Tm5t5.y = StreamColorBits(num_bits);
    Tm5t5.x |= StreamColorBits(1) << 7;
    uint C = 0;
    if (BitsOp(Tm5t5.x, 2, 4) == 7) {
        C = (BitsOp(Tm5t5.x, 5, 7) << 2) | BitsOp(Tm5t5.x, 0, 1);
        Tm5t5.z = 2;
        t[3] = 2;
    } else {
        C = BitsOp(Tm5t5.x, 0, 4);
        if (BitsOp(Tm5t5.x, 5, 6) == 3) {
            Tm5t5.z = 2;
            t[3] = BitsBracket(Tm5t5.x, 7);
        } else {
            Tm5t5.z = BitsBracket(Tm5t5.x, 7);
            t[3] = BitsOp(Tm5t5.x, 5, 6);
        }
    }
    if (BitsOp(C, 0, 1) == 3) {
        t[2] = 2;
        t[1] = BitsBracket(C, 4);
        t[0] = (BitsBracket(C, 3) << 1) | (BitsBracket(C, 2) & ~BitsBracket(C, 3));
    } else if (BitsOp(C, 2, 3) == 3) {
        t[2] = 2;
        t[1] = 2;
        t[0] = BitsOp(C, 0, 1);
    } else {
        t[2] = BitsBracket(C, 4);
        t[1] = BitsOp(C, 2, 3);
        t[0] = (BitsBracket(C, 1) << 1) | (BitsBracket(C, 0) & ~BitsBracket(C, 1));
    }
    for (uint i = 0; i < 4; i++) {
        const EncodingData val = CreateEncodingData(TRIT, num_bits, m[i], t[i]);
        ResultEmplaceBack(val);
    }
    const EncodingData val = CreateEncodingData(TRIT, num_bits, Tm5t5.y, Tm5t5.z);
    ResultEmplaceBack(val);
}

void DecodeIntegerSequence(uint max_range, uint num_values) {
    EncodingData val = EncodingData(encoding_values[max_range]);
    const uint encoding = Encoding(val);
    const uint num_bits = NumBits(val);
    uint vals_decoded = 0;
    while (vals_decoded < num_values && !result_limit_reached) {
        switch (encoding) {
        case QUINT:
            DecodeQuintBlock(num_bits);
            vals_decoded += 3;
            break;
        case TRIT:
            DecodeTritBlock(num_bits);
            vals_decoded += 5;
            break;
        case JUST_BITS:
            BitValue(val, StreamColorBits(num_bits));
            ResultEmplaceBack(val);
            vals_decoded++;
            break;
        }
    }
}

void DecodeColorValues(uvec4 modes, uint num_partitions, uint color_data_bits, out uint color_values[32]) {
    uint num_values = 0;
    for (uint i = 0; i < num_partitions; i++) {
        num_values += ((modes[i] >> 2) + 1) << 1;
    }
    // Find the largest encoding that's within color_data_bits
    // TODO(ameerj): profile with binary search
    int range = 0;
    while (++range < encoding_values.length()) {
        const uint bit_length = GetBitLength(num_values, range);
        if (bit_length > color_data_bits) {
            break;
        }
    }
    DecodeIntegerSequence(range - 1, num_values);
    uint out_index = 0;
    for (int itr = 0; itr < result_index; ++itr) {
        if (out_index >= num_values) {
            break;
        }
        const EncodingData val = GetEncodingFromVector(itr);
        const uint encoding = Encoding(val);
        const uint bitlen = NumBits(val);
        const uint bitval = BitValue(val);
        uint A = 0, B = 0, C = 0, D = 0;
        A = ReplicateBitTo9((bitval & 1));
        switch (encoding) {
        case JUST_BITS:
            color_values[++out_index] = FastReplicateTo8(bitval, bitlen);
            break;
        case TRIT: {
            D = QuintTritValue(val);
            switch (bitlen) {
            case 1:
                C = 204;
                break;
            case 2: {
                C = 93;
                const uint b = (bitval >> 1) & 1;
                B = (b << 8) | (b << 4) | (b << 2) | (b << 1);
                break;
            }
            case 3: {
                C = 44;
                const uint cb = (bitval >> 1) & 3;
                B = (cb << 7) | (cb << 2) | cb;
                break;
            }
            case 4: {
                C = 22;
                const uint dcb = (bitval >> 1) & 7;
                B = (dcb << 6) | dcb;
                break;
            }
            case 5: {
                C = 11;
                const uint edcb = (bitval >> 1) & 0xF;
                B = (edcb << 5) | (edcb >> 2);
                break;
            }
            case 6: {
                C = 5;
                const uint fedcb = (bitval >> 1) & 0x1F;
                B = (fedcb << 4) | (fedcb >> 4);
                break;
            }
            }
            break;
        }
        case QUINT: {
            D = QuintTritValue(val);
            switch (bitlen) {
            case 1:
                C = 113;
                break;
            case 2: {
                C = 54;
                const uint b = (bitval >> 1) & 1;
                B = (b << 8) | (b << 3) | (b << 2);
                break;
            }
            case 3: {
                C = 26;
                const uint cb = (bitval >> 1) & 3;
                B = (cb << 7) | (cb << 1) | (cb >> 1);
                break;
            }
            case 4: {
                C = 13;
                const uint dcb = (bitval >> 1) & 7;
                B = (dcb << 6) | (dcb >> 1);
                break;
            }
            case 5: {
                C = 6;
                const uint edcb = (bitval >> 1) & 0xF;
                B = (edcb << 5) | (edcb >> 3);
                break;
            }
            }
            break;
        }
        }
        if (encoding != JUST_BITS) {
            uint T = (D * C) + B;
            T ^= A;
            T = (A & 0x80) | (T >> 2);
            color_values[++out_index] = T;
        }
    }
}

ivec2 BitTransferSigned(int a, int b) {
    ivec2 transferred;
    transferred.y = b >> 1;
    transferred.y |= a & 0x80;
    transferred.x = a >> 1;
    transferred.x &= 0x3F;
    if ((transferred.x & 0x20) > 0) {
        transferred.x -= 0x40;
    }
    return transferred;
}

uvec4 ClampByte(ivec4 color) {
    return uvec4(clamp(color, 0, 255));
}

ivec4 BlueContract(int a, int r, int g, int b) {
    return ivec4(a, (r + b) >> 1, (g + b) >> 1, b);
}

void ComputeEndpoints(out uvec4 ep1, out uvec4 ep2, uint color_endpoint_mode, uint color_values[32],
                      inout uint colvals_index) {
#define READ_UINT_VALUES(N)                                                                        \
    uvec4 V[2];                                                                                \
    for (uint i = 0; i < N; i++) {                                                                 \
        V[i / 4][i % 4] = color_values[++colvals_index];                      \
    }
#define READ_INT_VALUES(N)                                                                         \
    ivec4 V[2];                                                                                \
    for (uint i = 0; i < N; i++) {                                                                 \
        V[i / 4][i % 4] = int(color_values[++colvals_index]);                      \
    }

    switch (color_endpoint_mode) {
    case 0: {
        READ_UINT_VALUES(2)
        ep1 = uvec4(0xFF, V[0].x, V[0].x, V[0].x);
        ep2 = uvec4(0xFF, V[0].y, V[0].y, V[0].y);
        break;
    }
    case 1: {
        READ_UINT_VALUES(2)
        const uint L0 = (V[0].x >> 2) | (V[0].y & 0xC0);
        const uint L1 = min(L0 + (V[0].y & 0x3F), 0xFFU);
        ep1 = uvec4(0xFF, L0, L0, L0);
        ep2 = uvec4(0xFF, L1, L1, L1);
        break;
    }
    case 4: {
        READ_UINT_VALUES(4)
        ep1 = uvec4(V[0].z, V[0].x, V[0].x, V[0].x);
        ep2 = uvec4(V[0].w, V[0].y, V[0].y, V[0].y);
        break;
    }
    case 5: {
        READ_INT_VALUES(4)
        ivec2 transferred = BitTransferSigned(V[0].y, V[0].x);
        V[0].y = transferred.x;
        V[0].x = transferred.y;
        transferred = BitTransferSigned(V[0].w, V[0].z);
        V[0].w = transferred.x;
        V[0].z = transferred.y;
        ep1 = ClampByte(ivec4(V[0].z, V[0].x, V[0].x, V[0].x));
        ep2 = ClampByte(ivec4(V[0].z + V[0].w, V[0].x + V[0].y, V[0].x + V[0].y, V[0].x + V[0].y));
        break;
    }
    case 6: {
        READ_UINT_VALUES(4)
        ep1 = uvec4(0xFF, (V[0].x * V[0].w) >> 8, (V[0].y * V[0].w) >> 8, (V[0].z * V[0].w) >> 8);
        ep2 = uvec4(0xFF, V[0].x, V[0].y, V[0].z);
        break;
    }
    case 8: {
        READ_UINT_VALUES(6)
        if ((V[0].y + V[0].w + V[1].y) >= (V[0].x + V[0].z + V[1].x)) {
            ep1 = uvec4(0xFF, V[0].x, V[0].z, V[1].x);
            ep2 = uvec4(0xFF, V[0].y, V[0].w, V[1].y);
        } else {
            ep1 = uvec4(BlueContract(0xFF, int(V[0].y), int(V[0].w), int(V[1].y)));
            ep2 = uvec4(BlueContract(0xFF, int(V[0].x), int(V[0].z), int(V[1].x)));
        }
        break;
    }
    case 9: {
        READ_INT_VALUES(6)
        ivec2 transferred = BitTransferSigned(V[0].y, V[0].x);
        V[0].y = transferred.x;
        V[0].x = transferred.y;
        transferred = BitTransferSigned(V[0].w, V[0].z);
        V[0].w = transferred.x;
        V[0].z = transferred.y;
        transferred = BitTransferSigned(V[1].y, V[1].x);
        V[1].y = transferred.x;
        V[1].x = transferred.y;
        if ((V[0].y + V[0].w + V[1].y) >= 0) {
            ep1 = ClampByte(ivec4(0xFF, V[0].x, V[0].z, V[1].x));
            ep2 = ClampByte(ivec4(0xFF, V[0].x + V[0].y, V[0].z + V[0].w, V[1].x + V[1].y));
        } else {
            ep1 = ClampByte(BlueContract(0xFF, V[0].x + V[0].y, V[0].z + V[0].w, V[1].x + V[1].y));
            ep2 = ClampByte(BlueContract(0xFF, V[0].x, V[0].z, V[1].x));
        }
        break;
    }
    case 10: {
        READ_UINT_VALUES(6)
        ep1 = uvec4(V[1].x, (V[0].x * V[0].w) >> 8, (V[0].y * V[0].w) >> 8, (V[0].z * V[0].w) >> 8);
        ep2 = uvec4(V[1].y, V[0].x, V[0].y, V[0].z);
        break;
    }
    case 12: {
        READ_UINT_VALUES(8)
        if ((V[0].y + V[0].w + V[1].y) >= (V[0].x + V[0].z + V[1].x)) {
            ep1 = uvec4(V[1].z, V[0].x, V[0].z, V[1].x);
            ep2 = uvec4(V[1].w, V[0].y, V[0].w, V[1].y);
        } else {
            ep1 = uvec4(BlueContract(int(V[1].w), int(V[0].y), int(V[0].w), int(V[1].y)));
            ep2 = uvec4(BlueContract(int(V[1].z), int(V[0].x), int(V[0].z), int(V[1].x)));
        }
        break;
    }
    case 13: {
        READ_INT_VALUES(8)
        ivec2 transferred = BitTransferSigned(V[0].y, V[0].x);
        V[0].y = transferred.x;
        V[0].x = transferred.y;
        transferred = BitTransferSigned(V[0].w, V[0].z);
        V[0].w = transferred.x;
        V[0].z = transferred.y;

        transferred = BitTransferSigned(V[1].y, V[1].x);
        V[1].y = transferred.x;
        V[1].x = transferred.y;

        transferred = BitTransferSigned(V[1].w, V[1].z);
        V[1].w = transferred.x;
        V[1].z = transferred.y;

        if ((V[0].y + V[0].w + V[1].y) >= 0) {
            ep1 = ClampByte(ivec4(V[1].z, V[0].x, V[0].z, V[1].x));
            ep2 = ClampByte(ivec4(V[1].w + V[1].z, V[0].x + V[0].y, V[0].z + V[0].w, V[1].x + V[1].y));
        } else {
            ep1 = ClampByte(BlueContract(V[1].z + V[1].w, V[0].x + V[0].y, V[0].z + V[0].w, V[1].x + V[1].y));
            ep2 = ClampByte(BlueContract(V[1].z, V[0].x, V[0].z, V[1].x));
        }
        break;
    }
    default: {
        // HDR mode, or more likely a bug computing the color_endpoint_mode
        ep1 = uvec4(0xFF, 0xFF, 0, 0);
        ep2 = uvec4(0xFF, 0xFF, 0, 0);
        break;
    }
    }
#undef READ_UINT_VALUES
#undef READ_INT_VALUES
}

uint UnquantizeTexelWeight(EncodingData val) {
    const uint encoding = Encoding(val);
    const uint bitlen = NumBits(val);
    const uint bitval = BitValue(val);
    const uint A = ReplicateBitTo7((bitval & 1));
    uint B = 0, C = 0, D = 0;
    uint result = 0;
    const uint bitlen_0_results[5] = {0, 16, 32, 48, 64};
    switch (encoding) {
    case JUST_BITS:
        return FastReplicateTo6(bitval, bitlen);
    case TRIT: {
        D = QuintTritValue(val);
        switch (bitlen) {
        case 0:
            return bitlen_0_results[D * 2];
        case 1: {
            C = 50;
            break;
        }
        case 2: {
            C = 23;
            const uint b = (bitval >> 1) & 1;
            B = (b << 6) | (b << 2) | b;
            break;
        }
        case 3: {
            C = 11;
            const uint cb = (bitval >> 1) & 3;
            B = (cb << 5) | cb;
            break;
        }
        default:
            break;
        }
        break;
    }
    case QUINT: {
        D = QuintTritValue(val);
        switch (bitlen) {
        case 0:
            return bitlen_0_results[D];
        case 1: {
            C = 28;
            break;
        }
        case 2: {
            C = 13;
            const uint b = (bitval >> 1) & 1;
            B = (b << 6) | (b << 1);
            break;
        }
        }
        break;
    }
    }
    if (encoding != JUST_BITS && bitlen > 0) {
        result = D * C + B;
        result ^= A;
        result = (A & 0x20) | (result >> 2);
    }
    if (result > 32) {
        result += 1;
    }
    return result;
}

void UnquantizeTexelWeights(uvec2 size, bool is_dual_plane) {
    const uint num_planes = is_dual_plane ? 2 : 1;
    const uint area = size.x * size.y;
    const uint loop_count = min(result_index, area * num_planes);
    for (uint itr = 0; itr < loop_count; ++itr) {
        result_vector[itr] =
            UnquantizeTexelWeight(GetEncodingFromVector(itr));
    }
}

uint GetUnquantizedTexelWeight(uint offset_base, uint plane, bool is_dual_plane) {
    const uint offset = is_dual_plane ? 2 * offset_base + plane : offset_base;
    return result_vector[offset];
}

uvec4 GetUnquantizedWeightVector(uint t, uint s, uvec2 size, uint plane_index, bool is_dual_plane) {
    const uint Ds = uint((block_dims.x * 0.5f + 1024) / (block_dims.x - 1));
    const uint Dt = uint((block_dims.y * 0.5f + 1024) / (block_dims.y - 1));
    const uint area = size.x * size.y;

    const uint cs = Ds * s;
    const uint ct = Dt * t;
    const uint gs = (cs * (size.x - 1) + 32) >> 6;
    const uint gt = (ct * (size.y - 1) + 32) >> 6;
    const uint js = gs >> 4;
    const uint fs = gs & 0xF;
    const uint jt = gt >> 4;
    const uint ft = gt & 0x0F;
    const uint w11 = (fs * ft + 8) >> 4;
    const uint w10 = ft - w11;
    const uint w01 = fs - w11;
    const uint w00 = 16 - fs - ft + w11;
    const uvec4 w = uvec4(w00, w01, w10, w11);
    const uint v0 = jt * size.x + js;

    uvec4 p0 = uvec4(0);
    uvec4 p1 = uvec4(0);

    if (v0 < area) {
        const uint offset_base = v0;
        p0.x = GetUnquantizedTexelWeight(offset_base, 0, is_dual_plane);
        p1.x = GetUnquantizedTexelWeight(offset_base, 1, is_dual_plane);
    }
    if ((v0 + 1) < (area)) {
        const uint offset_base = v0 + 1;
        p0.y = GetUnquantizedTexelWeight(offset_base, 0, is_dual_plane);
        p1.y = GetUnquantizedTexelWeight(offset_base, 1, is_dual_plane);
    }
    if ((v0 + size.x) < (area)) {
        const uint offset_base = v0 + size.x;
        p0.z = GetUnquantizedTexelWeight(offset_base, 0, is_dual_plane);
        p1.z = GetUnquantizedTexelWeight(offset_base, 1, is_dual_plane);
    }
    if ((v0 + size.x + 1) < (area)) {
        const uint offset_base = v0 + size.x + 1;
        p0.w = GetUnquantizedTexelWeight(offset_base, 0, is_dual_plane);
        p1.w = GetUnquantizedTexelWeight(offset_base, 1, is_dual_plane);
    }

    const uint primary_weight = (uint(dot(p0, w)) + 8) >> 4;

    uvec4 weight_vec = uvec4(primary_weight);

    if (is_dual_plane) {
        const uint secondary_weight = (uint(dot(p1, w)) + 8) >> 4;
        for (uint c = 0; c < 4; c++) {
            const bool is_secondary = ((plane_index + 1u) & 3u) == c;
            weight_vec[c] = is_secondary ? secondary_weight : primary_weight;
        }
    }
    return weight_vec;
}

int FindLayout(uint mode) {
    if ((mode & 3) != 0) {
        if ((mode & 8) != 0) {
            if ((mode & 4) != 0) {
                if ((mode & 0x100) != 0) {
                    return 4;
                }
                return 3;
            }
            return 2;
        }
        if ((mode & 4) != 0) {
            return 1;
        }
        return 0;
    }
    if ((mode & 0x100) != 0) {
        if ((mode & 0x80) != 0) {
            if ((mode & 0x20) != 0) {
                return 8;
            }
            return 7;
        }
        return 9;
    }
    if ((mode & 0x80) != 0) {
        return 6;
    }
    return 5;
}

void FillError(ivec3 coord) {
    for (uint j = 0; j < block_dims.y; j++) {
        for (uint i = 0; i < block_dims.x; i++) {
            imageStore(dest_image, coord + ivec3(i, j, 0), vec4(0.0, 0.0, 0.0, 0.0));
        }
    }
}

void FillVoidExtentLDR(ivec3 coord) {
    SkipBits(52);
    const uint r_u = StreamBits(16);
    const uint g_u = StreamBits(16);
    const uint b_u = StreamBits(16);
    const uint a_u = StreamBits(16);
    const float a = float(a_u) / 65535.0f;
    const float r = float(r_u) / 65535.0f;
    const float g = float(g_u) / 65535.0f;
    const float b = float(b_u) / 65535.0f;
    for (uint j = 0; j < block_dims.y; j++) {
        for (uint i = 0; i < block_dims.x; i++) {
            imageStore(dest_image, coord + ivec3(i, j, 0), vec4(r, g, b, a));
        }
    }
}

bool IsError(uint mode) {
    if ((mode & 0x1ff) == 0x1fc) {
        if ((mode & 0x200) != 0) {
            // params.void_extent_hdr = true;
            return true;
        }
        if ((mode & 0x400) == 0 || StreamBits(1) == 0) {
            return true;
        }
        return false;
    }
    if ((mode & 0xf) == 0) {
        return true;
    }
    if ((mode & 3) == 0 && (mode & 0x1c0) == 0x1c0) {
        return true;
    }
    return false;
}

uvec2 DecodeBlockSize(uint mode) {
    uint A, B;
    switch (FindLayout(mode)) {
    case 0:
        A = (mode >> 5) & 0x3;
        B = (mode >> 7) & 0x3;
        return uvec2(B + 4, A + 2);
    case 1:
        A = (mode >> 5) & 0x3;
        B = (mode >> 7) & 0x3;
        return uvec2(B + 8, A + 2);
    case 2:
        A = (mode >> 5) & 0x3;
        B = (mode >> 7) & 0x3;
        return uvec2(A + 2, B + 8);
    case 3:
        A = (mode >> 5) & 0x3;
        B = (mode >> 7) & 0x1;
        return uvec2(A + 2, B + 6);
    case 4:
        A = (mode >> 5) & 0x3;
        B = (mode >> 7) & 0x1;
        return uvec2(B + 2, A + 2);
    case 5:
        A = (mode >> 5) & 0x3;
        return uvec2(12, A + 2);
    case 6:
        A = (mode >> 5) & 0x3;
        return uvec2(A + 2, 12);
    case 7:
        return uvec2(6, 10);
    case 8:
        return uvec2(10, 6);
    case 9:
        A = (mode >> 5) & 0x3;
        B = (mode >> 9) & 0x3;
        return uvec2(A + 6, B + 6);
    default:
        return uvec2(0);
    }
}

uint DecodeMaxWeight(uint mode) {
    const uint mode_layout = FindLayout(mode);
    uint weight_index = (mode & 0x10) != 0 ? 1 : 0;
    if (mode_layout < 5) {
        weight_index |= (mode & 0x3) << 1;
    } else {
        weight_index |= (mode & 0xc) >> 1;
    }
    weight_index -= 2;
    if ((mode_layout != 9) && ((mode & 0x200) != 0)) {
        weight_index += 6;
    }
    return weight_index + 1;
}

void DecompressBlock(ivec3 coord) {
    uint mode = StreamBits(11);
    if (IsError(mode)) {
        FillError(coord);
        return;
    }
    if ((mode & 0x1ff) == 0x1fc) {
        // params.void_extent_ldr = true;
        FillVoidExtentLDR(coord);
        return;
    }
    const uvec2 size_params = DecodeBlockSize(mode);
    if ((size_params.x > block_dims.x) || (size_params.y > block_dims.y)) {
        FillError(coord);
        return;
    }
    const uint num_partitions = StreamBits(2) + 1;
    const uint mode_layout = FindLayout(mode);
    const bool dual_plane = (mode_layout != 9) && ((mode & 0x400) != 0);
    if (num_partitions > 4 || (num_partitions == 4 && dual_plane)) {
        FillError(coord);
        return;
    }
    uint partition_index = 1;
    uvec4 color_endpoint_mode = uvec4(0);
    uint ced_pointer = 0;
    uint base_cem = 0;
    if (num_partitions == 1) {
        color_endpoint_mode.x = StreamBits(4);
        partition_index = 0;
    } else {
        partition_index = StreamBits(10);
        base_cem = StreamBits(6);
    }
    const uint base_mode = base_cem & 3;
    const uint max_weight = DecodeMaxWeight(mode);
    const uint weight_bits = GetPackedBitSize(size_params, dual_plane, max_weight);
    uint remaining_bits = 128 - weight_bits - total_bitsread;
    uint extra_cem_bits = 0;
    if (base_mode > 0) {
        switch (num_partitions) {
        case 2:
            extra_cem_bits += 2;
            break;
        case 3:
            extra_cem_bits += 5;
            break;
        case 4:
            extra_cem_bits += 8;
            break;
        default:
            return;
        }
    }
    remaining_bits -= extra_cem_bits;
    const uint plane_selector_bits = dual_plane ? 2 : 0;
    remaining_bits -= plane_selector_bits;
    if (remaining_bits > 128) {
        // Bad data, more remaining bits than 4 bytes
        // return early
        return;
    }
    // Read color data...
    const uint color_data_bits = remaining_bits;
    while (remaining_bits > 0) {
        const int nb = int(min(remaining_bits, 32U));
        const uint b = StreamBits(nb);
        color_endpoint_data[ced_pointer] = uint(bitfieldExtract(b, 0, nb));
        ++ced_pointer;
        remaining_bits -= nb;
    }
    const uint plane_index = uint(StreamBits(plane_selector_bits));
    if (base_mode > 0) {
        const uint extra_cem = StreamBits(extra_cem_bits);
        uint cem = (extra_cem << 6) | base_cem;
        cem >>= 2;
        uvec4 C = uvec4(0);
        for (uint i = 0; i < num_partitions; i++) {
            C[i] = (cem & 1);
            cem >>= 1;
        }
        uvec4 M = uvec4(0);
        for (uint i = 0; i < num_partitions; i++) {
            M[i] = cem & 3;
            cem >>= 2;
        }
        for (uint i = 0; i < num_partitions; i++) {
            color_endpoint_mode[i] = base_mode;
            if (C[i] == 0) {
                --color_endpoint_mode[i];
            }
            color_endpoint_mode[i] <<= 2;
            color_endpoint_mode[i] |= M[i];
        }
    } else if (num_partitions > 1) {
        const uint cem = base_cem >> 2;
        for (uint i = 0; i < num_partitions; i++) {
            color_endpoint_mode[i] = cem;
        }
    }

    uvec4 endpoints0[4];
    uvec4 endpoints1[4];
    {
        // This decode phase should at most push 32 elements into the vector
        result_vector_max_index = 32;
        uint color_values[32];
        uint colvals_index = 0;
        DecodeColorValues(color_endpoint_mode, num_partitions, color_data_bits, color_values);
        for (uint i = 0; i < num_partitions; i++) {
            ComputeEndpoints(endpoints0[i], endpoints1[i], color_endpoint_mode[i], color_values,
                             colvals_index);
        }
    }
    color_endpoint_data = local_buff;
    color_endpoint_data = bitfieldReverse(color_endpoint_data).wzyx;
    const uint clear_byte_start = (weight_bits >> 3) + 1;

    const uint byte_insert = ExtractBits(color_endpoint_data, int(clear_byte_start - 1) * 8, 8) &
                             uint(((1 << (weight_bits % 8)) - 1));
    const uint vec_index = (clear_byte_start - 1) >> 2;
    color_endpoint_data[vec_index] = bitfieldInsert(color_endpoint_data[vec_index], byte_insert,
                                                    int((clear_byte_start - 1) % 4) * 8, 8);
    for (uint i = clear_byte_start; i < 16; ++i) {
        const uint idx = i >> 2;
        color_endpoint_data[idx] = bitfieldInsert(color_endpoint_data[idx], 0, int(i % 4) * 8, 8);
    }

    // Re-init vector variables for next decode phase
    result_index = 0;
    color_bitsread = 0;
    result_limit_reached = false;

    // The limit for the Unquantize phase, avoids decoding more data than needed.
    result_vector_max_index = size_params.x * size_params.y;
    if (dual_plane) {
        result_vector_max_index *= 2;
    }
    DecodeIntegerSequence(max_weight, GetNumWeightValues(size_params, dual_plane));

    UnquantizeTexelWeights(size_params, dual_plane);
    for (uint j = 0; j < block_dims.y; j++) {
        for (uint i = 0; i < block_dims.x; i++) {
            uint local_partition = 0;
            if (num_partitions > 1) {
                local_partition = Select2DPartition(partition_index, i, j, num_partitions);
            }
            const uvec4 C0 = ReplicateByteTo16(endpoints0[local_partition]);
            const uvec4 C1 = ReplicateByteTo16(endpoints1[local_partition]);
            const uvec4 weight_vec = GetUnquantizedWeightVector(j, i, size_params, plane_index, dual_plane);
            const vec4 Cf =
                vec4((C0 * (uvec4(64) - weight_vec) + C1 * weight_vec + uvec4(32)) / 64);
            const vec4 p = (Cf / 65535.0f);
            imageStore(dest_image, coord + ivec3(i, j, 0), p.gbar);
        }
    }
}

uint SwizzleOffset(uvec2 pos) {
    const uint x = pos.x;
    const uint y = pos.y;
    return ((x % 64) / 32) * 256 + ((y % 8) / 2) * 64 +
            ((x % 32) / 16) * 32 + (y % 2) * 16 + (x % 16);
}

void main() {
    uvec3 pos = gl_GlobalInvocationID;
    pos.x <<= BYTES_PER_BLOCK_LOG2;
    const uint swizzle = SwizzleOffset(pos.xy);
    const uint block_y = pos.y >> GOB_SIZE_Y_SHIFT;

    uint offset = 0;
    offset += pos.z * layer_stride;
    offset += (block_y >> block_height) * block_size;
    offset += (block_y & block_height_mask) << GOB_SIZE_SHIFT;
    offset += (pos.x >> GOB_SIZE_X_SHIFT) << x_shift;
    offset += swizzle;

    const ivec3 coord = ivec3(gl_GlobalInvocationID * uvec3(block_dims, 1));
    if (any(greaterThanEqual(coord, imageSize(dest_image)))) {
        return;
    }
    local_buff = astc_data[offset / 16];
    DecompressBlock(coord);
}


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450

layout(binding = 0) uniform sampler2D tex;

layout(location = 0) in vec2 texcoord;
layout(location = 0) out vec4 color;

void main() {
    color = textureLod(tex, texcoord, 0);
}


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 430

#ifdef VULKAN

#extension GL_EXT_shader_16bit_storage : require
#extension GL_EXT_shader_8bit_storage : require
#define HAS_EXTENDED_TYPES 1
#define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants {
#define END_PUSH_CONSTANTS };
#define UNIFORM(n)
#define BINDING_SWIZZLE_BUFFER 0
#define BINDING_INPUT_BUFFER 1
#define BINDING_OUTPUT_IMAGE 2

#else // ^^^ Vulkan ^^^ // vvv OpenGL vvv

#extension GL_NV_gpu_shader5 : enable
#ifdef GL_NV_gpu_shader5
#define HAS_EXTENDED_TYPES 1
#else
#define HAS_EXTENDED_TYPES 0
#endif
#define BEGIN_PUSH_CONSTANTS
#define END_PUSH_CONSTANTS
#define UNIFORM(n) layout (location = n) uniform
#define BINDING_SWIZZLE_BUFFER 0
#define BINDING_INPUT_BUFFER 1
#define BINDING_OUTPUT_IMAGE 0

#endif

BEGIN_PUSH_CONSTANTS
UNIFORM(0) uvec3 origin;
UNIFORM(1) ivec3 destination;
UNIFORM(2) uint bytes_per_block_log2;
UNIFORM(3) uint layer_stride;
UNIFORM(4) uint block_size;
UNIFORM(5) uint x_shift;
UNIFORM(6) uint block_height;
UNIFORM(7) uint block_height_mask;
END_PUSH_CONSTANTS

layout(binding = BINDING_SWIZZLE_BUFFER, std430) readonly buffer SwizzleTable {
    uint swizzle_table[];
};

#if HAS_EXTENDED_TYPES
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU8 { uint8_t u8data[]; };
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU16 { uint16_t u16data[]; };
#endif
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU32 { uint u32data[]; };
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU64 { uvec2 u64data[]; };
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU128 { uvec4 u128data[]; };

layout(binding = BINDING_OUTPUT_IMAGE) uniform writeonly uimage2DArray output_image;

layout(local_size_x = 32, local_size_y = 32, local_size_z = 1) in;

const uint GOB_SIZE_X = 64;
const uint GOB_SIZE_Y = 8;
const uint GOB_SIZE_Z = 1;
const uint GOB_SIZE = GOB_SIZE_X * GOB_SIZE_Y * GOB_SIZE_Z;

const uint GOB_SIZE_X_SHIFT = 6;
const uint GOB_SIZE_Y_SHIFT = 3;
const uint GOB_SIZE_Z_SHIFT = 0;
const uint GOB_SIZE_SHIFT = GOB_SIZE_X_SHIFT + GOB_SIZE_Y_SHIFT + GOB_SIZE_Z_SHIFT;

const uvec2 SWIZZLE_MASK = uvec2(GOB_SIZE_X - 1, GOB_SIZE_Y - 1);

uint SwizzleOffset(uvec2 pos) {
    pos = pos & SWIZZLE_MASK;
    return swizzle_table[pos.y * 64 + pos.x];
}

uvec4 ReadTexel(uint offset) {
    switch (bytes_per_block_log2) {
#if HAS_EXTENDED_TYPES
    case 0:
        return uvec4(u8data[offset], 0, 0, 0);
    case 1:
        return uvec4(u16data[offset / 2], 0, 0, 0);
#else
    case 0:
        return uvec4(bitfieldExtract(u32data[offset / 4], int((offset * 8) & 24), 8), 0, 0, 0);
    case 1:
        return uvec4(bitfieldExtract(u32data[offset / 4], int((offset * 8) & 16), 16), 0, 0, 0);
#endif
    case 2:
        return uvec4(u32data[offset / 4], 0, 0, 0);
    case 3:
        return uvec4(u64data[offset / 8], 0, 0);
    case 4:
        return u128data[offset / 16];
    }
    return uvec4(0);
}

void main() {
    uvec3 pos = gl_GlobalInvocationID + origin;
    pos.x <<= bytes_per_block_log2;

    // Read as soon as possible due to its latency
    const uint swizzle = SwizzleOffset(pos.xy);

    const uint block_y = pos.y >> GOB_SIZE_Y_SHIFT;

    uint offset = 0;
    offset += pos.z * layer_stride;
    offset += (block_y >> block_height) * block_size;
    offset += (block_y & block_height_mask) << GOB_SIZE_SHIFT;
    offset += (pos.x >> GOB_SIZE_X_SHIFT) << x_shift;
    offset += swizzle;

    const uvec4 texel = ReadTexel(offset);
    const ivec3 coord = ivec3(gl_GlobalInvocationID) + destination;
    imageStore(output_image, coord, texel);
}


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 430

#ifdef VULKAN

#extension GL_EXT_shader_16bit_storage : require
#extension GL_EXT_shader_8bit_storage : require
#define HAS_EXTENDED_TYPES 1
#define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants {
#define END_PUSH_CONSTANTS };
#define UNIFORM(n)
#define BINDING_SWIZZLE_BUFFER 0
#define BINDING_INPUT_BUFFER 1
#define BINDING_OUTPUT_IMAGE 2

#else // ^^^ Vulkan ^^^ // vvv OpenGL vvv

#extension GL_NV_gpu_shader5 : enable
#ifdef GL_NV_gpu_shader5
#define HAS_EXTENDED_TYPES 1
#else
#define HAS_EXTENDED_TYPES 0
#endif
#define BEGIN_PUSH_CONSTANTS
#define END_PUSH_CONSTANTS
#define UNIFORM(n) layout (location = n) uniform
#define BINDING_SWIZZLE_BUFFER 0
#define BINDING_INPUT_BUFFER 1
#define BINDING_OUTPUT_IMAGE 0

#endif

BEGIN_PUSH_CONSTANTS
UNIFORM(0) uvec3 origin;
UNIFORM(1) ivec3 destination;
UNIFORM(2) uint bytes_per_block_log2;
UNIFORM(3) uint slice_size;
UNIFORM(4) uint block_size;
UNIFORM(5) uint x_shift;
UNIFORM(6) uint block_height;
UNIFORM(7) uint block_height_mask;
UNIFORM(8) uint block_depth;
UNIFORM(9) uint block_depth_mask;
END_PUSH_CONSTANTS

layout(binding = BINDING_SWIZZLE_BUFFER, std430) readonly buffer SwizzleTable {
    uint swizzle_table[];
};

#if HAS_EXTENDED_TYPES
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU8 { uint8_t u8data[]; };
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU16 { uint16_t u16data[]; };
#endif
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU32 { uint u32data[]; };
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU64 { uvec2 u64data[]; };
layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU128 { uvec4 u128data[]; };

layout(binding = BINDING_OUTPUT_IMAGE) uniform writeonly uimage3D output_image;

layout(local_size_x = 16, local_size_y = 8, local_size_z = 8) in;

const uint GOB_SIZE_X = 64;
const uint GOB_SIZE_Y = 8;
const uint GOB_SIZE_Z = 1;
const uint GOB_SIZE = GOB_SIZE_X * GOB_SIZE_Y * GOB_SIZE_Z;

const uint GOB_SIZE_X_SHIFT = 6;
const uint GOB_SIZE_Y_SHIFT = 3;
const uint GOB_SIZE_Z_SHIFT = 0;
const uint GOB_SIZE_SHIFT = GOB_SIZE_X_SHIFT + GOB_SIZE_Y_SHIFT + GOB_SIZE_Z_SHIFT;

const uvec2 SWIZZLE_MASK = uvec2(GOB_SIZE_X - 1, GOB_SIZE_Y - 1);

uint SwizzleOffset(uvec2 pos) {
    pos = pos & SWIZZLE_MASK;
    return swizzle_table[pos.y * 64 + pos.x];
}

uvec4 ReadTexel(uint offset) {
    switch (bytes_per_block_log2) {
#if HAS_EXTENDED_TYPES
    case 0:
        return uvec4(u8data[offset], 0, 0, 0);
    case 1:
        return uvec4(u16data[offset / 2], 0, 0, 0);
#else
    case 0:
        return uvec4(bitfieldExtract(u32data[offset / 4], int((offset * 8) & 24), 8), 0, 0, 0);
    case 1:
        return uvec4(bitfieldExtract(u32data[offset / 4], int((offset * 8) & 16), 16), 0, 0, 0);
#endif
    case 2:
        return uvec4(u32data[offset / 4], 0, 0, 0);
    case 3:
        return uvec4(u64data[offset / 8], 0, 0);
    case 4:
        return u128data[offset / 16];
    }
    return uvec4(0);
}

void main() {
    uvec3 pos = gl_GlobalInvocationID + origin;
    pos.x <<= bytes_per_block_log2;

    // Read as soon as possible due to its latency
    const uint swizzle = SwizzleOffset(pos.xy);

    const uint block_y = pos.y >> GOB_SIZE_Y_SHIFT;

    uint offset = 0;
    offset += (pos.z >> block_depth) * slice_size;
    offset += (pos.z & block_depth_mask) << (GOB_SIZE_SHIFT + block_height);
    offset += (block_y >> block_height) * block_size;
    offset += (block_y & block_height_mask) << GOB_SIZE_SHIFT;
    offset += (pos.x >> GOB_SIZE_X_SHIFT) << x_shift;
    offset += swizzle;

    const uvec4 texel = ReadTexel(offset);
    const ivec3 coord = ivec3(gl_GlobalInvocationID) + destination;
    imageStore(output_image, coord, texel);
}


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450
#extension GL_ARB_shader_stencil_export : require

layout(binding = 0) uniform sampler2D color_texture;

void main() {
    ivec2 coord = ivec2(gl_FragCoord.xy);
    uvec4 color = uvec4(texelFetch(color_texture, coord, 0).abgr * (exp2(8) - 1.0f));
    uvec4 bytes = color << uvec4(24, 16, 8, 0);
    uint depth_stencil_unorm = bytes.x | bytes.y | bytes.z | bytes.w;

    gl_FragDepth = float(depth_stencil_unorm & 0x00FFFFFFu) / (exp2(24.0) - 1.0f);
    gl_FragStencilRefARB = int(depth_stencil_unorm >> 24);
}


code:
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450

layout(binding = 0) uniform sampler2D color_texture;

void main() {
    ivec2 coord = ivec2(gl_FragCoord.xy);
    vec4 color = texelFetch(color_texture, coord, 0).abgr;

    float value = color.a * (color.r + color.g + color.b) / 3.0f;

    gl_FragDepth = value;
}


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450

precision mediump int;
precision highp float;

layout(binding = 0) uniform sampler2D depth_tex;
layout(binding = 1) uniform usampler2D stencil_tex;

layout(location = 0) out vec4 color;

void main() {
    ivec2 coord = ivec2(gl_FragCoord.xy);
    highp uint depth_val =
        uint(textureLod(depth_tex, coord, 0).r * (exp2(32.0) - 1.0));
    lowp uint stencil_val = textureLod(stencil_tex, coord, 0).r;
    highp uvec4 components =
        uvec4(stencil_val, (uvec3(depth_val) >> uvec3(24u, 16u, 8u)) & 0x000000FFu);
    color.abgr = vec4(components) / (exp2(8.0) - 1.0);
}


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450

layout(binding = 0) uniform sampler2D depth_tex;

layout(location = 0) out vec4 color;

void main() {
    ivec2 coord = ivec2(gl_FragCoord.xy);
    float depth = texelFetch(depth_tex, coord, 0).r;
    color = vec4(depth, depth, depth, 1.0);
}


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450

layout(binding = 0) uniform sampler2D depth_texture;
layout(location = 0) out float output_color;

void main() {
    ivec2 coord = ivec2(gl_FragCoord.xy);
    output_color = texelFetch(depth_texture, coord, 0).r;
}


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450

layout(binding = 0) uniform sampler2D color_texture;

void main() {
    ivec2 coord = ivec2(gl_FragCoord.xy);
    float color = texelFetch(color_texture, coord, 0).r;
    gl_FragDepth = color;
}


code:
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450 core
layout (local_size_x = 8, local_size_y = 8, local_size_z = 1) in;

layout (binding = 0, rgba8) uniform readonly restrict image2DMSArray msaa_in;
layout (binding = 1, rgba8) uniform writeonly restrict image2DArray output_img;

void main() {
    const ivec3 coords = ivec3(gl_GlobalInvocationID);
    if (any(greaterThanEqual(coords, imageSize(msaa_in)))) {
        return;
    }

    // TODO: Specialization constants for num_samples?
    const int num_samples = imageSamples(msaa_in);
    const ivec3 msaa_size = imageSize(msaa_in);
    const ivec3 out_size = imageSize(output_img);
    const ivec3 scale = out_size / msaa_size;
    for (int curr_sample = 0; curr_sample < num_samples; ++curr_sample) {
        const vec4 pixel = imageLoad(msaa_in, coords, curr_sample);

        const int single_sample_x = scale.x * coords.x + (curr_sample & 1);
        const int single_sample_y = scale.y * coords.y + ((curr_sample / 2) & 1);
        const ivec3 dest_coords = ivec3(single_sample_x, single_sample_y, coords.z);

        if (any(greaterThanEqual(dest_coords, imageSize(output_img)))) {
            continue;
        }
        imageStore(output_img, dest_coords, pixel);
    }
}


code:
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450 core
layout (local_size_x = 8, local_size_y = 8, local_size_z = 1) in;

layout (binding = 0, rgba8) uniform readonly restrict image2DArray img_in;
layout (binding = 1, rgba8) uniform writeonly restrict image2DMSArray output_msaa;

void main() {
    const ivec3 coords = ivec3(gl_GlobalInvocationID);
    if (any(greaterThanEqual(coords, imageSize(output_msaa)))) {
        return;
    }

    // TODO: Specialization constants for num_samples?
    const int num_samples = imageSamples(output_msaa);
    const ivec3 msaa_size = imageSize(output_msaa);
    const ivec3 out_size = imageSize(img_in);
    const ivec3 scale = out_size / msaa_size;
    for (int curr_sample = 0; curr_sample < num_samples; ++curr_sample) {
        const int single_sample_x = scale.x * coords.x + (curr_sample & 1);
        const int single_sample_y = scale.y * coords.y + ((curr_sample / 2) & 1);
        const ivec3 single_coords = ivec3(single_sample_x, single_sample_y, coords.z);

        if (any(greaterThanEqual(single_coords, imageSize(img_in)))) {
            continue;
        }
        const vec4 pixel = imageLoad(img_in, single_coords);
        imageStore(output_msaa, coords, curr_sample, pixel);
    }
}


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450

precision mediump int;
precision highp float;

layout(binding = 0) uniform sampler2D depth_tex;
layout(binding = 1) uniform usampler2D stencil_tex;

layout(location = 0) out vec4 color;

void main() {
    ivec2 coord = ivec2(gl_FragCoord.xy);
    highp uint depth_val =
        uint(textureLod(depth_tex, coord, 0).r * (exp2(32.0) - 1.0));
    lowp uint stencil_val = textureLod(stencil_tex, coord, 0).r;
    highp uvec4 components =
        uvec4((uvec3(depth_val) >> uvec3(24u, 16u, 8u)) & 0x000000FFu, stencil_val);
    color.rgba = vec4(components) / (exp2(8.0) - 1.0);
}


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

//!#version 460 core
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable
#extension GL_GOOGLE_include_directive : enable
#extension GL_EXT_shader_explicit_arithmetic_types : require

// FidelityFX Super Resolution Sample
//
// Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
// 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.

layout( push_constant ) uniform constants {
    uvec4 Const0;
    uvec4 Const1;
    uvec4 Const2;
    uvec4 Const3;
};

layout(set=0,binding=0) uniform sampler2D InputTexture;

#define A_GPU 1
#define A_GLSL 1
#define FSR_RCAS_PASSTHROUGH_ALPHA 1

#ifndef YUZU_USE_FP16
    #include "ffx_a.h"

    #if USE_EASU
        #define FSR_EASU_F 1
        AF4 FsrEasuRF(AF2 p) { AF4 res = textureGather(InputTexture, p, 0); return res; }
        AF4 FsrEasuGF(AF2 p) { AF4 res = textureGather(InputTexture, p, 1); return res; }
        AF4 FsrEasuBF(AF2 p) { AF4 res = textureGather(InputTexture, p, 2); return res; }
    #endif
    #if USE_RCAS
        #define FSR_RCAS_F 1
        AF4 FsrRcasLoadF(ASU2 p) { return texelFetch(InputTexture, ASU2(p), 0); }
        void FsrRcasInputF(inout AF1 r, inout AF1 g, inout AF1 b) {}
    #endif
#else
    #define A_HALF
    #include "ffx_a.h"

    #if USE_EASU
        #define FSR_EASU_H 1
        AH4 FsrEasuRH(AF2 p) { AH4 res = AH4(textureGather(InputTexture, p, 0)); return res; }
        AH4 FsrEasuGH(AF2 p) { AH4 res = AH4(textureGather(InputTexture, p, 1)); return res; }
        AH4 FsrEasuBH(AF2 p) { AH4 res = AH4(textureGather(InputTexture, p, 2)); return res; }
    #endif
    #if USE_RCAS
        #define FSR_RCAS_H 1
        AH4 FsrRcasLoadH(ASW2 p) { return AH4(texelFetch(InputTexture, ASU2(p), 0)); }
        void FsrRcasInputH(inout AH1 r,inout AH1 g,inout AH1 b){}
    #endif
#endif

#include "ffx_fsr1.h"

layout (location = 0) in vec2 frag_texcoord;
layout (location = 0) out vec4 frag_color;

void CurrFilter(AU2 pos) {
#if USE_EASU
    #ifndef YUZU_USE_FP16
        AF3 c;
        FsrEasuF(c, pos, Const0, Const1, Const2, Const3);
        frag_color = AF4(c, texture(InputTexture, frag_texcoord).a);
    #else
        AH3 c;
        FsrEasuH(c, pos, Const0, Const1, Const2, Const3);
        frag_color = AH4(c, texture(InputTexture, frag_texcoord).a);
    #endif
#endif
#if USE_RCAS
    #ifndef YUZU_USE_FP16
        AF4 c;
        FsrRcasF(c.r, c.g, c.b, c.a, pos, Const0);
        frag_color = c;
    #else
        AH4 c;
        FsrRcasH(c.r, c.g, c.b, c.a, pos, Const0);
        frag_color = c;
    #endif
#endif
}

void main() {
#if USE_RCAS
    CurrFilter(AU2(frag_texcoord * vec2(textureSize(InputTexture, 0))));
#else
    CurrFilter(AU2(gl_FragCoord.xy));
#endif
}


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 450

#ifdef VULKAN
#define VERTEX_ID gl_VertexIndex
#define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants {
#define END_PUSH_CONSTANTS };
#define UNIFORM(n)
#define FLIPY 1
#else // ^^^ Vulkan ^^^ // vvv OpenGL vvv
#define VERTEX_ID gl_VertexID
#define BEGIN_PUSH_CONSTANTS
#define END_PUSH_CONSTANTS
#define FLIPY -1
#define UNIFORM(n) layout (location = n) uniform
out gl_PerVertex {
    vec4 gl_Position;
};
#endif

BEGIN_PUSH_CONSTANTS
UNIFORM(0) vec2 tex_scale;
UNIFORM(1) vec2 tex_offset;
END_PUSH_CONSTANTS

layout(location = 0) out vec2 texcoord;

void main() {
    float x = float((VERTEX_ID & 1) << 2);
    float y = float((VERTEX_ID & 2) << 1);
    gl_Position = vec4(x - 1.0, FLIPY * (y - 1.0), 0.0, 1.0);
    texcoord = fma(vec2(x, y) / 2.0, tex_scale, tex_offset);
}


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

// Source code is adapted from
// https://www.geeks3d.com/20110405/fxaa-fast-approximate-anti-aliasing-demo-glsl-opengl-test-radeon-geforce/3/

#version 460

#ifdef VULKAN

#define BINDING_COLOR_TEXTURE 1

#else // ^^^ Vulkan ^^^ // vvv OpenGL vvv

#define BINDING_COLOR_TEXTURE 0

#endif

layout (location = 0) in vec4 posPos;

layout (location = 0) out vec4 frag_color;

layout (binding = BINDING_COLOR_TEXTURE) uniform sampler2D input_texture;

const float FXAA_SPAN_MAX = 8.0;
const float FXAA_REDUCE_MUL = 1.0 / 8.0;
const float FXAA_REDUCE_MIN = 1.0 / 128.0;

#define FxaaTexLod0(t, p) textureLod(t, p, 0.0)
#define FxaaTexOff(t, p, o) textureLodOffset(t, p, 0.0, o)

vec3 FxaaPixelShader(vec4 posPos, sampler2D tex) {

    vec3 rgbNW = FxaaTexLod0(tex, posPos.zw).xyz;
    vec3 rgbNE = FxaaTexOff(tex, posPos.zw, ivec2(1,0)).xyz;
    vec3 rgbSW = FxaaTexOff(tex, posPos.zw, ivec2(0,1)).xyz;
    vec3 rgbSE = FxaaTexOff(tex, posPos.zw, ivec2(1,1)).xyz;
    vec3 rgbM  = FxaaTexLod0(tex, posPos.xy).xyz;
/*---------------------------------------------------------*/
    vec3 luma = vec3(0.299, 0.587, 0.114);
    float lumaNW = dot(rgbNW, luma);
    float lumaNE = dot(rgbNE, luma);
    float lumaSW = dot(rgbSW, luma);
    float lumaSE = dot(rgbSE, luma);
    float lumaM  = dot(rgbM,  luma);
/*---------------------------------------------------------*/
    float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
    float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
/*---------------------------------------------------------*/
    vec2 dir;
    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
    dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));
/*---------------------------------------------------------*/
    float dirReduce = max(
        (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),
        FXAA_REDUCE_MIN);
    float rcpDirMin = 1.0/(min(abs(dir.x), abs(dir.y)) + dirReduce);
    dir = min(vec2( FXAA_SPAN_MAX,  FXAA_SPAN_MAX),
          max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),
          dir * rcpDirMin)) / textureSize(tex, 0);
/*--------------------------------------------------------*/
    vec3 rgbA = (1.0 / 2.0) * (
        FxaaTexLod0(tex, posPos.xy + dir * (1.0 / 3.0 - 0.5)).xyz +
        FxaaTexLod0(tex, posPos.xy + dir * (2.0 / 3.0 - 0.5)).xyz);
    vec3 rgbB = rgbA * (1.0 / 2.0) + (1.0 / 4.0) * (
        FxaaTexLod0(tex, posPos.xy + dir * (0.0 / 3.0 - 0.5)).xyz +
        FxaaTexLod0(tex, posPos.xy + dir * (3.0 / 3.0 - 0.5)).xyz);
    float lumaB = dot(rgbB, luma);
    if((lumaB < lumaMin) || (lumaB > lumaMax)) return rgbA;
    return rgbB;
}

void main() {
  frag_color = vec4(FxaaPixelShader(posPos, input_texture), texture(input_texture, posPos.xy).a);
}


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 460

out gl_PerVertex {
    vec4 gl_Position;
};

const vec2 vertices[3] =
    vec2[3](vec2(-1,-1), vec2(3,-1), vec2(-1, 3));

layout (location = 0) out vec4 posPos;

#ifdef VULKAN

#define BINDING_COLOR_TEXTURE 0
#define VERTEX_ID gl_VertexIndex

#else // ^^^ Vulkan ^^^ // vvv OpenGL vvv

#define BINDING_COLOR_TEXTURE 0
#define VERTEX_ID gl_VertexID

#endif

layout (binding = BINDING_COLOR_TEXTURE) uniform sampler2D input_texture;

const float FXAA_SUBPIX_SHIFT = 0;

void main() {
  vec2 vertex = vertices[VERTEX_ID];
  gl_Position = vec4(vertex, 0.0, 1.0);
  vec2 vert_tex_coord = (vertex + 1.0) / 2.0;
  posPos.xy = vert_tex_coord;
  posPos.zw = vert_tex_coord - (0.5 + FXAA_SUBPIX_SHIFT) / textureSize(input_texture, 0);
}


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 430 core

layout(local_size_x = 16, local_size_y = 8) in;

layout(binding = 0, rgba8ui) restrict uniform uimage2D destination;
layout(location = 0) uniform uvec3 size;

void main() {
    if (any(greaterThanEqual(gl_GlobalInvocationID, size))) {
        return;
    }
    uvec4 components = imageLoad(destination, ivec2(gl_GlobalInvocationID.xy));
    imageStore(destination, ivec2(gl_GlobalInvocationID.xy), components.wxyz);
}


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 430 core
#extension GL_ARB_gpu_shader_int64 : require

layout (local_size_x = 4, local_size_y = 4) in;

layout(binding = 0, rg32ui) readonly uniform uimage3D bc4_input;
layout(binding = 1, rgba8ui) writeonly uniform uimage3D bc4_output;

layout(location = 0) uniform uvec3 src_offset;
layout(location = 1) uniform uvec3 dst_offset;

// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_compression_rgtc.txt
uint DecompressBlock(uint64_t bits, uvec2 coord) {
    const uint code_offset = 16 + 3 * (4 * coord.y + coord.x);
    const uint code = uint(bits >> code_offset) & 7;
    const uint red0 = uint(bits >> 0) & 0xff;
    const uint red1 = uint(bits >> 8) & 0xff;
    if (red0 > red1) {
        switch (code) {
        case 0:
            return red0;
        case 1:
            return red1;
        case 2:
            return (6 * red0 + 1 * red1) / 7;
        case 3:
            return (5 * red0 + 2 * red1) / 7;
        case 4:
            return (4 * red0 + 3 * red1) / 7;
        case 5:
            return (3 * red0 + 4 * red1) / 7;
        case 6:
            return (2 * red0 + 5 * red1) / 7;
        case 7:
            return (1 * red0 + 6 * red1) / 7;
        }
    } else {
        switch (code) {
        case 0:
            return red0;
        case 1:
            return red1;
        case 2:
            return (4 * red0 + 1 * red1) / 5;
        case 3:
            return (3 * red0 + 2 * red1) / 5;
        case 4:
            return (2 * red0 + 3 * red1) / 5;
        case 5:
            return (1 * red0 + 4 * red1) / 5;
        case 6:
            return 0;
        case 7:
            return 0xff;
        }
    }
    return 0;
}

void main() {
    uvec2 packed_bits = imageLoad(bc4_input, ivec3(gl_WorkGroupID + src_offset)).rg;
    uint64_t bits = packUint2x32(packed_bits);
    uint red = DecompressBlock(bits, gl_LocalInvocationID.xy);
    uvec4 color = uvec4(red & 0xff, 0, 0, 0xff);
    imageStore(bc4_output, ivec3(gl_GlobalInvocationID + dst_offset), color);
}


code:
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

//!#version 460 core
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable

#extension GL_AMD_gpu_shader_half_float : enable
#extension GL_NV_gpu_shader5 : enable

// FidelityFX Super Resolution Sample
//
// Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
// 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.

layout (location = 0) uniform uvec4 constants[4];

#define A_GPU 1
#define A_GLSL 1
#define FSR_RCAS_PASSTHROUGH_ALPHA 1

#ifdef YUZU_USE_FP16
    #define A_HALF
#endif
#include "ffx_a.h"

#ifndef YUZU_USE_FP16
    layout (binding=0) uniform sampler2D InputTexture;
    #if USE_EASU
        #define FSR_EASU_F 1
        AF4 FsrEasuRF(AF2 p) { AF4 res = textureGather(InputTexture, p, 0); return res; }
        AF4 FsrEasuGF(AF2 p) { AF4 res = textureGather(InputTexture, p, 1); return res; }
        AF4 FsrEasuBF(AF2 p) { AF4 res = textureGather(InputTexture, p, 2); return res; }
    #endif
    #if USE_RCAS
        #define FSR_RCAS_F
        AF4 FsrRcasLoadF(ASU2 p) { return texelFetch(InputTexture, ASU2(p), 0); }
        void FsrRcasInputF(inout AF1 r, inout AF1 g, inout AF1 b) {}
    #endif
#else
    layout (binding=0) uniform sampler2D InputTexture;
    #if USE_EASU
        #define FSR_EASU_H 1
        AH4 FsrEasuRH(AF2 p) { AH4 res = AH4(textureGather(InputTexture, p, 0)); return res; }
        AH4 FsrEasuGH(AF2 p) { AH4 res = AH4(textureGather(InputTexture, p, 1)); return res; }
        AH4 FsrEasuBH(AF2 p) { AH4 res = AH4(textureGather(InputTexture, p, 2)); return res; }
    #endif
    #if USE_RCAS
        #define FSR_RCAS_H
        AH4 FsrRcasLoadH(ASW2 p) { return AH4(texelFetch(InputTexture, ASU2(p), 0)); }
        void FsrRcasInputH(inout AH1 r,inout AH1 g,inout AH1 b){}
    #endif
#endif

#include "ffx_fsr1.h"

layout (location = 0) in vec2 frag_texcoord;
layout (location = 0) out vec4 frag_color;

void CurrFilter(AU2 pos)
{
#if USE_EASU
    #ifndef YUZU_USE_FP16
        AF3 c;
        FsrEasuF(c, pos, constants[0], constants[1], constants[2], constants[3]);
        frag_color = AF4(c, texture(InputTexture, frag_texcoord).a);
    #else
        AH3 c;
        FsrEasuH(c, pos, constants[0], constants[1], constants[2], constants[3]);
        frag_color = AH4(c, texture(InputTexture, frag_texcoord).a);
    #endif
#endif
#if USE_RCAS
    #ifndef YUZU_USE_FP16
        AF4 c;
        FsrRcasF(c.r, c.g, c.b, c.a, pos, constants[0]);
        frag_color = c;
    #else
        AH3 c;
        FsrRcasH(c.r, c.g, c.b, c.a, pos, constants[0]);
        frag_color = c;
    #endif
#endif
}

void main()
{
#if USE_RCAS
    CurrFilter(AU2(frag_texcoord * vec2(textureSize(InputTexture, 0))));
#else
    CurrFilter(AU2(gl_FragCoord.xy));
#endif
}


code:
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 460 core
#extension GL_GOOGLE_include_directive : enable

#define USE_EASU 1

#include "opengl_fidelityfx_fsr.frag"


code:
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 460 core
#extension GL_GOOGLE_include_directive : enable

#define USE_RCAS 1

#include "opengl_fidelityfx_fsr.frag"


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

// This shader is a workaround for a quirk in NVIDIA OpenGL drivers
// Shaders using local memory see a great performance benefit if a shader that was dispatched
// before it had more local memory allocated.
// This shader allocates the maximum local memory allowed on NVIDIA drivers to ensure that
// subsequent shaders see the performance boost.

// NOTE: This shader does no actual meaningful work and returns immediately,
// it is simply a means to have the driver expect a shader using lots of local memory.

#version 450

layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;

layout(location = 0) uniform uint uniform_data;

layout(binding = 0, rgba8) uniform writeonly restrict image2DArray dest_image;

#define MAX_LMEM_SIZE 4080 // Size chosen to avoid errors in Nvidia's GLSL compiler
#define NUM_LMEM_CONSTANTS 1
#define ARRAY_SIZE MAX_LMEM_SIZE - NUM_LMEM_CONSTANTS

uint lmem_0[ARRAY_SIZE];
const uvec4 constant_values[NUM_LMEM_CONSTANTS] = uvec4[](uvec4(0));

void main() {
    const uint global_id = gl_GlobalInvocationID.x;
    if (global_id <= 128) {
        // Since the shader is called with a dispatch of 1x1x1
        // This should always be the case, and this shader will not actually execute
        return;
    }
    for (uint t = 0; t < uniform_data; t++) {
        const uint offset = (t * uniform_data);
        lmem_0[offset] = t;
    }
    const uint offset = (gl_GlobalInvocationID.y * uniform_data + gl_GlobalInvocationID.x);
    const uint value = lmem_0[offset];
    const uint const_value = constant_values[offset / 4][offset % 4];
    const uvec4 color = uvec4(value + const_value);

    // A "side-effect" is needed so the variables don't get optimized out,
    // but this should never execute so there should be no clobbering of previously bound state.
    imageStore(dest_image, ivec3(gl_GlobalInvocationID), color);
}


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 430 core

layout (location = 0) in vec2 frag_tex_coord;
layout (location = 0) out vec4 color;

layout (binding = 0) uniform sampler2D color_texture;

void main() {
    color = vec4(texture(color_texture, frag_tex_coord));
}


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#version 430 core

out gl_PerVertex {
    vec4 gl_Position;
};

layout (location = 0) in vec2 vert_position;
layout (location = 1) in vec2 vert_tex_coord;
layout (location = 0) out vec2 frag_tex_coord;

// This is a truncated 3x3 matrix for 2D transformations:
// The upper-left 2x2 submatrix performs scaling/rotation/mirroring.
// The third column performs translation.
// The third row could be used for projection, which we don't need in 2D. It hence is assumed to
// implicitly be [0, 0, 1]
layout (location = 0) uniform mat3x2 modelview_matrix;

void main() {
    // Multiply input position by the rotscale part of the matrix and then manually translate by
    // the last column. This is equivalent to using a full 3x3 matrix and expanding the vector
    // to `vec3(vert_position.xy, 1.0)`
    gl_Position = vec4(mat2(modelview_matrix) * vert_position + modelview_matrix[2], 0.0, 1.0);
    frag_tex_coord = vert_tex_coord;
}


code:
// SPDX-FileCopyrightText: 2020 BreadFish64
// SPDX-License-Identifier: MIT

// Adapted from https://github.com/BreadFish64/ScaleFish/tree/master/scaleforce

//! #version 460

#extension GL_ARB_separate_shader_objects : enable

#ifdef YUZU_USE_FP16

#extension GL_AMD_gpu_shader_half_float : enable
#extension GL_NV_gpu_shader5 : enable

#define lfloat float16_t
#define lvec2 f16vec2
#define lvec3 f16vec3
#define lvec4 f16vec4

#else

#define lfloat float
#define lvec2 vec2
#define lvec3 vec3
#define lvec4 vec4

#endif

layout (location = 0) in vec2 tex_coord;

layout (location = 0) out vec4 frag_color;

layout (binding = 0) uniform sampler2D input_texture;

const bool ignore_alpha = true;

lfloat ColorDist1(lvec4 a, lvec4 b) {
    // https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.2020_conversion
    const lvec3 K = lvec3(0.2627, 0.6780, 0.0593);
    const lfloat scaleB = lfloat(0.5) / (lfloat(1.0) - K.b);
    const lfloat scaleR = lfloat(0.5) / (lfloat(1.0) - K.r);
    lvec4 diff = a - b;
    lfloat Y = dot(diff.rgb, K);
    lfloat Cb = scaleB * (diff.b - Y);
    lfloat Cr = scaleR * (diff.r - Y);
    lvec3 YCbCr = lvec3(Y, Cb, Cr);
    lfloat d = length(YCbCr);
    if (ignore_alpha) {
        return d;
    }
    return sqrt(a.a * b.a * d * d + diff.a * diff.a);
}

lvec4 ColorDist(lvec4 ref, lvec4 A, lvec4 B, lvec4 C, lvec4 D) {
    return lvec4(
            ColorDist1(ref, A),
            ColorDist1(ref, B),
            ColorDist1(ref, C),
            ColorDist1(ref, D)
        );
}

vec4 Scaleforce(sampler2D tex, vec2 tex_coord) {
    lvec4 bl = lvec4(textureOffset(tex, tex_coord, ivec2(-1, -1)));
    lvec4 bc = lvec4(textureOffset(tex, tex_coord, ivec2(0, -1)));
    lvec4 br = lvec4(textureOffset(tex, tex_coord, ivec2(1, -1)));
    lvec4 cl = lvec4(textureOffset(tex, tex_coord, ivec2(-1, 0)));
    lvec4 cc = lvec4(texture(tex, tex_coord));
    lvec4 cr = lvec4(textureOffset(tex, tex_coord, ivec2(1, 0)));
    lvec4 tl = lvec4(textureOffset(tex, tex_coord, ivec2(-1, 1)));
    lvec4 tc = lvec4(textureOffset(tex, tex_coord, ivec2(0, 1)));
    lvec4 tr = lvec4(textureOffset(tex, tex_coord, ivec2(1, 1)));

    lvec4 offset_tl = ColorDist(cc, tl, tc, tr, cr);
    lvec4 offset_br = ColorDist(cc, br, bc, bl, cl);

    // Calculate how different cc is from the texels around it
    const lfloat plus_weight = lfloat(1.5);
    const lfloat cross_weight = lfloat(1.5);
    lfloat total_dist = dot(offset_tl + offset_br, lvec4(cross_weight, plus_weight, cross_weight, plus_weight));

    if (total_dist == lfloat(0.0)) {
        return cc;
    } else {
        // Add together all the distances with direction taken into account
        lvec4 tmp = offset_tl - offset_br;
        lvec2 total_offset = tmp.wy * plus_weight + (tmp.zz + lvec2(-tmp.x, tmp.x)) * cross_weight;

        // When the image has thin points, they tend to split apart.
        // This is because the texels all around are different and total_offset reaches into clear areas.
        // This works pretty well to keep the offset in bounds for these cases.
        lfloat clamp_val = length(total_offset) / total_dist;
        vec2 final_offset = vec2(clamp(total_offset, -clamp_val, clamp_val)) / textureSize(tex, 0);

        return texture(tex, tex_coord - final_offset);
    }
}

void main() {
    frag_color = Scaleforce(input_texture, tex_coord);
}