Files
stoneheart_at_home/app/d3d_scene_win32.cpp
T

436 lines
21 KiB
C++

#define NOMINMAX
#include "d3d_scene_win32.hpp"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <wrl/client.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iterator>
#include <limits>
#include <utility>
namespace settlement::viewer {
namespace {
using Microsoft::WRL::ComPtr;
struct Point { float x, y, z; };
struct Color { float r, g, b; };
struct Vertex { Point position; Color color; };
constexpr Color rgb(int r, int g, int b) {
return {static_cast<float>(r) / 255.f, static_cast<float>(g) / 255.f, static_cast<float>(b) / 255.f};
}
constexpr Color shade(Color color, float amount) {
return {color.r * amount, color.g * amount, color.b * amount};
}
class Mesh {
public:
std::vector<Vertex> vertices;
void quad(Point a, Point b, Point c, Point d, Color color) {
vertices.insert(vertices.end(), {{a, color}, {b, color}, {c, color}, {a, color}, {c, color}, {d, color}});
}
void flat(float a, float b, float c, float d, float z, Color color) {
quad({a, b, z}, {c, b, z}, {c, d, z}, {a, d, z}, color);
}
void box(float x, float y, float z, float w, float d, float h, Color color) {
const float a = x - w / 2, b = y - d / 2, c = x + w / 2, e = y + d / 2, top = z + h;
flat(a, b, c, e, top, color);
quad({c, b, z}, {c, e, z}, {c, e, top}, {c, b, top}, shade(color, .76f));
quad({a, e, z}, {c, e, z}, {c, e, top}, {a, e, top}, shade(color, .62f));
}
void track(GridPosition from, GridPosition to, Color color) {
const float x = static_cast<float>(from.x), y = static_cast<float>(from.y);
const float end_x = static_cast<float>(to.x), end_y = static_cast<float>(to.y);
constexpr float half = .035f;
flat(std::min(x, end_x) - half, std::min(y, end_y) - half,
std::max(x, end_x) + half, std::max(y, end_y) + half, .016f, color);
}
};
void terrain(Mesh& mesh, const World& world, const SceneView& view) {
mesh.box(static_cast<float>(world.width() - 1) / 2.f, static_cast<float>(world.height() - 1) / 2.f, -.65f,
static_cast<float>(world.width()), static_cast<float>(world.height()), .64f, rgb(133, 107, 71));
for (int y = 0; y < world.height(); ++y) {
for (int x = 0; x < world.width(); ++x) {
const GridPosition cell{x, y};
const float px = static_cast<float>(x), py = static_cast<float>(y);
const int variation = (x * 17 + y * 29 + x * y * 5) % 12;
const bool walkable = world.is_walkable(cell);
auto surface = walkable ? rgb(123 + variation, 157 + variation, 104 + variation) : rgb(103, 118, 106);
if (view.move_source == cell) surface = rgb(219, 189, 113);
if (view.cursor == cell) surface = view.valid_cursor ? rgb(150, 205, 219) : rgb(223, 139, 124);
mesh.flat(px - .50f, py - .50f, px + .50f, py + .50f, 0, shade(surface, .90f));
mesh.flat(px - .48f, py - .48f, px + .48f, py + .48f, .004f, surface);
if (walkable) continue;
const float height = .50f + static_cast<float>(variation % 4) * .10f;
mesh.box(px, py, .004f, .75f, .76f, height * .45f, rgb(114, 131, 119));
mesh.box(px - .06f, py - .04f, height * .45f, .55f, .59f, height * .55f, rgb(146, 157, 143));
}
}
}
void resources(Mesh& mesh, const World& world) {
for (const auto& node : world.resource_nodes()) {
const float x = static_cast<float>(node.position.x), y = static_cast<float>(node.position.y);
if (node.site != ResourceSite::Natural) {
mesh.flat(x - .43f, y - .43f, x + .43f, y + .43f, .025f, rgb(133, 103, 70));
}
if (node.site == ResourceSite::Mine) {
mesh.box(x, y, .025f, .74f, .76f, .09f, rgb(62, 67, 63));
mesh.box(x - .28f, y, .05f, .12f, .65f, .46f, rgb(140, 102, 67));
mesh.box(x + .28f, y, .05f, .12f, .65f, .46f, rgb(140, 102, 67));
mesh.box(x, y, .51f, .76f, .65f, .11f, rgb(181, 141, 90));
} else if (node.quantity == 0) {
if (node.growth_at != 0 || node.reserved_workers != 0) {
mesh.box(x, y, .025f, .16f, .14f, .15f, rgb(100, 150, 85));
}
} else if (node.type == ItemType::Wood) {
mesh.box(x, y, .02f, .19f, .19f, .75f, rgb(117, 83, 57));
mesh.box(x, y, .58f, .72f, .73f, .36f, rgb(67, 112, 72));
mesh.box(x - .07f, y - .07f, .94f, .49f, .49f, .29f, rgb(91, 143, 85));
} else if (node.type == ItemType::Berries || node.type == ItemType::Flax) {
const bool flax = node.type == ItemType::Flax;
if (node.type == ItemType::Berries && node.foraging_enabled) {
mesh.flat(x - .39f, y - .39f, x + .39f, y + .39f, .028f, rgb(159, 187, 102));
}
for (int i = 0; i < 3; ++i) {
const float shift = static_cast<float>(i - 1) * .19f;
mesh.box(x + shift, y - shift * .56f, .03f, flax ? .12f : .30f, flax ? .13f : .33f,
flax ? .34f : .24f, flax ? rgb(98, 143, 80) : rgb(78, 133, 75));
mesh.box(x + shift, y - shift * .56f, flax ? .37f : .27f, .13f, .15f, .08f,
flax ? rgb(147, 175, 229) : rgb(207, 105, 135));
}
} else {
mesh.box(x, y, .03f, .51f, .53f, .32f, rgb(151, 159, 150));
}
}
}
void construction(Mesh& mesh, const World& world) {
for (const auto& storage : world.storages()) {
const float x = static_cast<float>(storage.position.x), y = static_cast<float>(storage.position.y);
mesh.box(x, y, .02f, .66f, .62f, .44f, rgb(160, 110, 65));
mesh.box(x, y, .46f, .72f, .67f, .10f, storage.kind == StorageKind::Pantry ?
rgb(187, 120, 148) : rgb(202, 155, 91));
mesh.box(x + .34f, y, .30f, .052f, .13f, .13f, rgb(229, 195, 124));
}
for (const auto& order : world.production_orders()) {
const float x = static_cast<float>(order.position.x), y = static_cast<float>(order.position.y);
if (!is_construction(order.recipe)) {
mesh.box(x, y, .025f, .71f, .58f, .34f, rgb(150, 110, 73));
mesh.box(x, y, .37f, .77f, .62f, .10f, rgb(199, 156, 100));
if (order.recipe == RecipeId::WeaveCloth) {
mesh.box(x, y - .12f, .46f, .62f, .12f, .37f, rgb(167, 124, 79));
mesh.box(x, y - .15f, .79f, .48f, .15f, .10f, rgb(235, 225, 193));
}
continue;
}
if (order.state != JobState::Completed) {
const auto marked = order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99);
mesh.flat(x - .44f, y - .44f, x + .44f, y + .44f, .03f, marked);
}
if (order.recipe == RecipeId::BuildBed &&
(order.state == JobState::Completed || order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)) {
mesh.box(x, y, .045f, .77f, .43f, .18f,
order.bed_base == BedBase::Stone ? rgb(145, 155, 151) : rgb(156, 107, 66));
if (order.bed_stage == BedStage::Pillow || order.state == JobState::Completed) {
mesh.box(x, y, .225f, .69f, .38f, .12f, rgb(115, 159, 185));
}
if (order.state == JobState::Completed) {
mesh.box(x - .23f, y, .345f, .2f, .32f, .07f, rgb(243, 230, 194));
}
} else if (order.recipe == RecipeId::BuildCabin && order.state == JobState::Completed) {
mesh.box(x, y, .03f, .83f, .82f, .65f, rgb(194, 151, 103));
mesh.quad({x - .46f, y + .46f, .64f}, {x + .46f, y + .46f, .64f},
{x + .46f, y, 1.03f}, {x - .46f, y, 1.03f}, rgb(158, 83, 62));
mesh.quad({x - .46f, y, 1.03f}, {x + .46f, y, 1.03f},
{x + .46f, y - .46f, .64f}, {x - .46f, y - .46f, .64f}, rgb(193, 113, 79));
mesh.quad({x + .42f, y - .42f, .67f}, {x + .42f, y + .42f, .67f},
{x + .42f, y, 1.01f}, {x + .42f, y, 1.01f}, rgb(174, 126, 80));
}
}
for (const auto& job : world.jobs()) {
if (job.state == JobState::Completed) continue;
const float x = static_cast<float>(job.position.x), y = static_cast<float>(job.position.y);
mesh.box(x, y, .015f, .20f, .20f, .10f,
job.state == JobState::Available ? rgb(76, 134, 90) : rgb(208, 159, 77));
}
}
void draw_blueprint(Mesh& mesh, const BlueprintPart& part, bool preview) {
const float x = static_cast<float>(part.cell.x), y = static_cast<float>(part.cell.y);
const auto ink = preview ? rgb(168, 232, 243) : rgb(90, 189, 236);
const auto frame = part.recipe == RecipeId::BuildBed && part.base == BedBase::Stone
? shade(ink, .70f) : ink;
constexpr float beam = .055f;
const auto outline = [&](float width, float depth, float z, Color color) {
for (float side : {-1.f, 1.f}) {
mesh.box(x, y + side * depth / 2, z, width + beam, beam, beam, color);
mesh.box(x + side * width / 2, y, z, beam, depth, beam, color);
}
};
outline(.88f, .88f, .035f, ink);
const float width = part.recipe == RecipeId::BuildBed ? .72f : .70f;
const float depth = part.recipe == RecipeId::BuildBed ? .41f : .62f;
const float top = part.recipe == RecipeId::BuildBed ? .34f : .68f;
outline(width, depth, top, frame);
for (float side_x : {-1.f, 1.f}) {
for (float side_y : {-1.f, 1.f}) {
mesh.box(x + side_x * width / 2, y + side_y * depth / 2, .04f, beam, beam, top - .04f, frame);
}
}
if (part.recipe == RecipeId::WeaveCloth) mesh.box(x, y, .30f, width, beam, beam, ink);
}
void residents(Mesh& mesh, const World& world, const SceneView& view) {
for (const auto& agent : world.agents()) {
using enum AgentState;
if (agent.state != Sleeping) {
auto position = agent.position;
const auto trail = agent.state == Hauling ? rgb(104, 164, 159) : rgb(137, 126, 167);
for (std::size_t i = agent.route_cursor; i < agent.route.size(); ++i) {
mesh.track(position, agent.route[i], trail);
position = agent.route[i];
}
}
const float shift = static_cast<float>(static_cast<int>(agent.id % 5) - 2) / 12.f;
const float x = static_cast<float>(agent.position.x) + shift;
const float y = static_cast<float>(agent.position.y) - shift;
const auto clothes = agent.state == Working ? rgb(195, 98, 74) :
agent.state == Gathering ? rgb(196, 152, 74) :
agent.state == Hauling ? rgb(67, 146, 138) : rgb(89, 126, 172);
if (view.selected == agent.id) {
mesh.flat(x - .28f, y - .26f, x + .28f, y + .26f, .042f, rgb(247, 207, 114));
}
if (agent.state == Sleeping) {
const float bed_height = agent.resting_on_ground ? .035f : .36f;
mesh.box(x, y, bed_height, .54f, .25f, .14f, clothes);
mesh.box(x - .23f, y, bed_height + .01f, .16f, .20f, .15f, rgb(234, 195, 149));
continue;
}
mesh.box(x, y, .027f, .19f, .22f, .14f, rgb(75, 72, 71));
mesh.box(x, y, .167f, .27f, .22f, .22f, clothes);
mesh.box(x, y, .387f, .25f, .24f, .23f, rgb(232, 191, 144));
mesh.box(x - .025f, y - .02f, .59f, .27f, .25f, .065f, rgb(92, 73, 56));
if (!agent.inventory.empty()) {
mesh.box(x - .11f, y - .12f, .14f, .19f, .18f, .24f, rgb(200, 156, 92));
}
}
}
constexpr char hlsl[] = R"(
cbuffer Camera : register(b0) {
float2 origin;
float2 halfTile;
float2 screen;
float scale;
float padding;
};
struct Input { float3 position : POSITION; float3 color : COLOR; };
struct Pixel { float4 position : SV_Position; float3 color : COLOR; };
Pixel project(Input input) {
float3 p = input.position;
float2 screenPoint = origin + scale * float2((p.x - p.y) * halfTile.x,
(p.x + p.y) * halfTile.y - p.z * 16.0);
Pixel result;
result.position = float4(screenPoint.x * 2.0 / screen.x - 1.0,
1.0 - screenPoint.y * 2.0 / screen.y, 0.96 - (p.x + p.y + p.z * 1.5) * 0.009, 1.0);
result.color = input.color;
return result;
}
float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
)";
} // namespace
struct D3DScene::Backend {
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
ComPtr<IDXGISwapChain> swap_chain;
ComPtr<ID3D11Texture2D> target_texture;
ComPtr<ID3D11RenderTargetView> target_view;
ComPtr<ID3D11DepthStencilView> depth_view;
ComPtr<ID3D11VertexShader> vertex_shader;
ComPtr<ID3D11PixelShader> pixel_shader;
ComPtr<ID3D11InputLayout> layout;
ComPtr<ID3D11RasterizerState> rasterizer;
ComPtr<ID3D11Buffer> camera;
ComPtr<ID3D11Buffer> geometry;
UINT buffer_bytes = 0;
int width = 0, height = 0;
Mesh mesh;
bool resize(int w, int h) {
if (w == width && h == height && target_view && depth_view) return true;
context->OMSetRenderTargets(0, nullptr, nullptr);
target_texture.Reset();
target_view.Reset();
depth_view.Reset();
D3D11_TEXTURE2D_DESC texture{};
texture.Width = static_cast<UINT>(w);
texture.Height = static_cast<UINT>(h);
texture.MipLevels = texture.ArraySize = texture.SampleDesc.Count = 1;
texture.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
texture.BindFlags = D3D11_BIND_RENDER_TARGET;
if (swap_chain) {
if (FAILED(swap_chain->ResizeBuffers(0, texture.Width, texture.Height, DXGI_FORMAT_UNKNOWN, 0)) ||
FAILED(swap_chain->GetBuffer(0, IID_PPV_ARGS(target_texture.GetAddressOf())))) return false;
} else if (FAILED(device->CreateTexture2D(&texture, nullptr, &target_texture))) {
return false;
}
texture.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
texture.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ComPtr<ID3D11Texture2D> depth;
if (FAILED(device->CreateRenderTargetView(target_texture.Get(), nullptr, &target_view)) ||
FAILED(device->CreateTexture2D(&texture, nullptr, &depth)) ||
FAILED(device->CreateDepthStencilView(depth.Get(), nullptr, &depth_view))) return false;
width = w;
height = h;
return true;
}
bool upload_geometry() {
const auto bytes = mesh.vertices.size() * sizeof(Vertex);
if (bytes > std::numeric_limits<UINT>::max()) return false;
if (bytes > buffer_bytes) {
D3D11_BUFFER_DESC desc{};
desc.ByteWidth = static_cast<UINT>(bytes);
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
if (FAILED(device->CreateBuffer(&desc, nullptr, geometry.ReleaseAndGetAddressOf()))) return false;
buffer_bytes = desc.ByteWidth;
}
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(geometry.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
std::memcpy(mapped.pData, mesh.vertices.data(), bytes);
context->Unmap(geometry.Get(), 0);
return true;
}
bool read_frame(std::vector<std::uint32_t>& pixels) {
D3D11_TEXTURE2D_DESC desc{};
target_texture->GetDesc(&desc);
desc.BindFlags = 0;
desc.Usage = D3D11_USAGE_STAGING;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
ComPtr<ID3D11Texture2D> copy;
if (FAILED(device->CreateTexture2D(&desc, nullptr, &copy))) return false;
context->CopyResource(copy.Get(), target_texture.Get());
pixels.resize(static_cast<std::size_t>(width) * static_cast<std::size_t>(height));
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(copy.Get(), 0, D3D11_MAP_READ, 0, &mapped))) return false;
const auto* data = static_cast<const std::byte*>(mapped.pData);
for (int row = 0; row < height; ++row) {
std::memcpy(pixels.data() + static_cast<std::size_t>(row) * static_cast<std::size_t>(width),
data + static_cast<std::size_t>(row) * mapped.RowPitch,
static_cast<std::size_t>(width) * sizeof(std::uint32_t));
}
context->Unmap(copy.Get(), 0);
return true;
}
};
D3DScene::D3DScene() = default;
D3DScene::~D3DScene() = default;
bool D3DScene::initialize(HWND target, bool software) {
auto graphics = std::make_unique<Backend>();
const auto driver = software ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE;
constexpr D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};
constexpr UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
if (target) {
DXGI_SWAP_CHAIN_DESC swap{};
swap.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
swap.SampleDesc.Count = 1;
swap.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swap.BufferCount = 2;
swap.OutputWindow = target;
swap.Windowed = TRUE;
swap.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
if (FAILED(D3D11CreateDeviceAndSwapChain(nullptr, driver, nullptr, flags, levels, std::size(levels),
D3D11_SDK_VERSION, &swap, &graphics->swap_chain, &graphics->device, nullptr, &graphics->context))) return false;
} else if (FAILED(D3D11CreateDevice(nullptr, driver, nullptr, flags, levels, std::size(levels),
D3D11_SDK_VERSION, &graphics->device, nullptr, &graphics->context))) return false;
ComPtr<ID3DBlob> vertex, pixel;
constexpr UINT compile_flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3;
if (FAILED(D3DCompile(hlsl, sizeof(hlsl) - 1, nullptr, nullptr, nullptr, "project", "vs_4_0",
compile_flags, 0, &vertex, nullptr)) ||
FAILED(D3DCompile(hlsl, sizeof(hlsl) - 1, nullptr, nullptr, nullptr, "paint", "ps_4_0",
compile_flags, 0, &pixel, nullptr))) return false;
if (FAILED(graphics->device->CreateVertexShader(vertex->GetBufferPointer(), vertex->GetBufferSize(),
nullptr, &graphics->vertex_shader)) ||
FAILED(graphics->device->CreatePixelShader(pixel->GetBufferPointer(), pixel->GetBufferSize(),
nullptr, &graphics->pixel_shader))) return false;
constexpr D3D11_INPUT_ELEMENT_DESC elements[] = {
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(Point), D3D11_INPUT_PER_VERTEX_DATA, 0}
};
D3D11_RASTERIZER_DESC raster{};
raster.FillMode = D3D11_FILL_SOLID;
raster.CullMode = D3D11_CULL_NONE;
raster.DepthClipEnable = TRUE;
D3D11_BUFFER_DESC constants{};
constants.ByteWidth = 32;
constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
if (FAILED(graphics->device->CreateInputLayout(elements, std::size(elements), vertex->GetBufferPointer(),
vertex->GetBufferSize(), &graphics->layout)) ||
FAILED(graphics->device->CreateRasterizerState(&raster, &graphics->rasterizer)) ||
FAILED(graphics->device->CreateBuffer(&constants, nullptr, &graphics->camera))) return false;
backend_ = std::move(graphics);
return true;
}
bool D3DScene::ready() const noexcept { return backend_ != nullptr; }
void D3DScene::reset() noexcept { backend_.reset(); }
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
auto& graphics = *backend_;
if (!graphics.resize(view.width, view.height)) return false;
graphics.mesh.vertices.clear();
terrain(graphics.mesh, world, view);
resources(graphics.mesh, world);
construction(graphics.mesh, world);
for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false);
if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true);
residents(graphics.mesh, world, view);
if (!graphics.upload_geometry()) return false;
auto* ctx = graphics.context.Get();
constexpr float clear[] = {.83f, .87f, .79f, 1.f};
ctx->ClearRenderTargetView(graphics.target_view.Get(), clear);
ctx->ClearDepthStencilView(graphics.depth_view.Get(), D3D11_CLEAR_DEPTH, 1.f, 0);
ctx->OMSetRenderTargets(1, graphics.target_view.GetAddressOf(), graphics.depth_view.Get());
const D3D11_VIEWPORT viewport{0, 0, static_cast<float>(view.width), static_cast<float>(view.height), 0, 1};
ctx->RSSetViewports(1, &viewport);
ctx->RSSetState(graphics.rasterizer.Get());
const float constants[] = {view.origin_x, view.origin_y, view.tile_half_width, view.tile_half_height,
viewport.Width, viewport.Height, view.scale, 0};
ctx->UpdateSubresource(graphics.camera.Get(), 0, nullptr, constants, 0, 0);
constexpr UINT stride = sizeof(Vertex);
constexpr UINT offset = 0;
ctx->IASetInputLayout(graphics.layout.Get());
ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
ctx->IASetVertexBuffers(0, 1, graphics.geometry.GetAddressOf(), &stride, &offset);
ctx->VSSetShader(graphics.vertex_shader.Get(), nullptr, 0);
ctx->VSSetConstantBuffers(0, 1, graphics.camera.GetAddressOf());
ctx->PSSetShader(graphics.pixel_shader.Get(), nullptr, 0);
ctx->Draw(static_cast<UINT>(graphics.mesh.vertices.size()), 0);
if (capture && !graphics.read_frame(*capture)) return false;
return !graphics.swap_chain || SUCCEEDED(graphics.swap_chain->Present(0, 0));
}
} // namespace settlement::viewer