Add the Escape menu and a Direct3D 11 colony viewport
This commit is contained in:
1 parent
5cb3b9cec2
commit
1e5a1a6316
7 files changed
+715
-77
No files matched your search
+3
-1
@@ -36,10 +36,12 @@ target_link_libraries(settlement_colony_benchmark PRIVATE settlement_core)
|
||||
|
||||
if(WIN32)
|
||||
add_executable(settlement_viewer WIN32
|
||||
app/d3d_scene_win32.cpp
|
||||
app/viewer_win32.cpp
|
||||
app/lan_session_win32.cpp
|
||||
)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_core user32 gdi32 comctl32 comdlg32 ws2_32 bcrypt iphlpapi)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_core user32 gdi32 comctl32 comdlg32 ws2_32 bcrypt iphlpapi
|
||||
d3d11 d3dcompiler)
|
||||
if(NOT MSVC)
|
||||
target_link_options(settlement_viewer PRIVATE -municode)
|
||||
target_compile_options(settlement_viewer PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
|
||||
@@ -49,7 +49,9 @@
|
||||
- [x] Камера с перемещением и масштабированием относительно курсора.
|
||||
- [x] Нижняя панель с жителями, добычей, участками и строительством.
|
||||
- [x] Главное меню перед игрой со списком сохранений, продолжением партии и подключением к другу.
|
||||
- [ ] Настоящий графический 3D-рендерер и объёмные модели.
|
||||
- [x] Меню Esc с паузой, сохранениями, графикой и сетевыми действиями.
|
||||
- [x] Игровая карта на Direct3D 11 с глубиной и базовыми объёмными моделями.
|
||||
- [ ] Расширение набора 3D-моделей и освещения.
|
||||
- [x] Постановка чертежа домика мышью в Windows-клиенте.
|
||||
- [ ] Интерфейс для остальных типов работ и зданий.
|
||||
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
#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 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, ©))) 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);
|
||||
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
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
struct SceneView {
|
||||
int width;
|
||||
int height;
|
||||
float origin_x;
|
||||
float origin_y;
|
||||
float scale;
|
||||
float tile_half_width;
|
||||
float tile_half_height;
|
||||
std::optional<GridPosition> cursor;
|
||||
bool valid_cursor;
|
||||
std::optional<GridPosition> move_source;
|
||||
std::optional<AgentId> selected;
|
||||
};
|
||||
|
||||
class D3DScene {
|
||||
public:
|
||||
D3DScene();
|
||||
~D3DScene();
|
||||
bool initialize(HWND target, bool software = false);
|
||||
[[nodiscard]] bool ready() const noexcept;
|
||||
bool render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture = nullptr);
|
||||
void reset() noexcept;
|
||||
|
||||
private:
|
||||
struct Backend;
|
||||
std::unique_ptr<Backend> backend_;
|
||||
};
|
||||
|
||||
} // namespace settlement::viewer
|
||||
+245
-65
@@ -6,6 +6,7 @@
|
||||
#include <commdlg.h>
|
||||
#include <windowsx.h>
|
||||
|
||||
#include "d3d_scene_win32.hpp"
|
||||
#include "isometric_camera.hpp"
|
||||
#include "lan_session.hpp"
|
||||
#include "title_screen_win32.hpp"
|
||||
@@ -34,6 +35,7 @@ namespace {
|
||||
|
||||
constexpr wchar_t window_class[] = L"SettlementIsometricViewer";
|
||||
constexpr wchar_t resident_window_class[] = L"SettlementResidentRoster";
|
||||
constexpr wchar_t scene_window_class[] = L"SettlementD3DViewport";
|
||||
constexpr int title_menu_id = 1002;
|
||||
constexpr int status_label_id = 1003;
|
||||
constexpr int cabin_button_id = 1004;
|
||||
@@ -66,6 +68,9 @@ constexpr int first_work_choice_id = 1050;
|
||||
constexpr int resident_list_id = 1060;
|
||||
constexpr int first_role_id = 1070;
|
||||
constexpr int first_dock_section_id = 1080;
|
||||
constexpr int work_list_button_id = 1083;
|
||||
constexpr int graphics_menu_id = 1120;
|
||||
constexpr int exit_menu_id = 1121;
|
||||
constexpr int timer_id = 1;
|
||||
constexpr int map_size = settlement::first_colony_map_size;
|
||||
constexpr int tile_width = 24;
|
||||
@@ -87,7 +92,7 @@ HWND production_label = nullptr;
|
||||
HWND wood_bed_button = nullptr;
|
||||
HWND stone_bed_button = nullptr;
|
||||
HWND priority_button = nullptr;
|
||||
HWND pause_button = nullptr;
|
||||
HWND work_list_button = nullptr;
|
||||
HWND residents_button = nullptr;
|
||||
std::array<HWND, 3> dock_section_buttons{};
|
||||
std::unique_ptr<settlement::World> world;
|
||||
@@ -95,7 +100,10 @@ namespace title = settlement::viewer;
|
||||
title::TitleScreen title_screen;
|
||||
bool showing_title = true;
|
||||
bool has_session = false;
|
||||
HMENU play_menu = nullptr;
|
||||
bool pause_menu_open = false;
|
||||
HWND scene_window = nullptr;
|
||||
settlement::viewer::D3DScene graphics;
|
||||
bool prefer_direct3d = true;
|
||||
using settlement::viewer::LanState;
|
||||
settlement::viewer::LanSession lan;
|
||||
LanState displayed_lan_state = LanState::Offline;
|
||||
@@ -333,6 +341,21 @@ void invalidate_scene(HWND window) {
|
||||
GetClientRect(window, &scene);
|
||||
scene.top = map_top;
|
||||
if (scene.bottom > scene.top) InvalidateRect(window, &scene, FALSE);
|
||||
if (!showing_title && prefer_direct3d && graphics.ready() && scene_window) {
|
||||
InvalidateRect(scene_window, nullptr, FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
void layout_scene(HWND window) {
|
||||
if (!scene_window) return;
|
||||
if (showing_title || !prefer_direct3d || !graphics.ready()) {
|
||||
ShowWindow(scene_window, SW_HIDE);
|
||||
return;
|
||||
}
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
SetWindowPos(scene_window, HWND_BOTTOM, 0, map_top, client.right,
|
||||
std::max(0, static_cast<int>(client.bottom) - map_top - map_footer), SWP_NOACTIVATE | SWP_SHOWWINDOW);
|
||||
}
|
||||
|
||||
void update_camera_drag(POINT point) {
|
||||
@@ -735,6 +758,7 @@ bool draw_toolbar_button(const DRAWITEMSTRUCT& item) {
|
||||
case wood_bed_button_id: draw_icon_button(item, WorkIcon::Wood, selected_bed_base == settlement::BedBase::Wood, true); return true;
|
||||
case stone_bed_button_id: draw_icon_button(item, WorkIcon::Stone, selected_bed_base == settlement::BedBase::Stone, true); return true;
|
||||
case residents_button_id: draw_icon_button(item, WorkIcon::Resident, roster.window != nullptr, true); return true;
|
||||
case work_list_button_id: draw_icon_button(item, WorkIcon::Hammer, false); return true;
|
||||
}
|
||||
if (id >= first_dock_section_id && static_cast<std::size_t>(id - first_dock_section_id) < dock_sections.size()) {
|
||||
const auto& section = dock_sections[static_cast<std::size_t>(id - first_dock_section_id)];
|
||||
@@ -846,12 +870,11 @@ void update_status() {
|
||||
}
|
||||
for (const HWND button : dock_section_buttons) EnableWindow(button, can_play);
|
||||
EnableWindow(priority_button, scenario && can_play);
|
||||
EnableWindow(pause_button, scenario && !lan.is_guest());
|
||||
EnableWindow(work_list_button, can_play);
|
||||
const wchar_t* priority = L"Равный приоритет";
|
||||
if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда";
|
||||
else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка";
|
||||
SetWindowTextW(priority_button, priority);
|
||||
SetWindowTextW(pause_button, world->paused() ? L"Продолжить" : L"Пауза");
|
||||
if (scenario && production_label != nullptr) {
|
||||
const auto progress = world->scenario_progress();
|
||||
const auto sleeping = std::count_if(world->agents().begin(), world->agents().end(),
|
||||
@@ -924,19 +947,21 @@ void show_title_screen(HWND window, bool visible) {
|
||||
title_screen.update(has_session, lan.state() == LanState::Connecting);
|
||||
} else {
|
||||
has_session = true;
|
||||
if (prefer_direct3d && !graphics.ready() && (!scene_window || !graphics.initialize(scene_window))) {
|
||||
prefer_direct3d = false;
|
||||
}
|
||||
}
|
||||
const int flags = visible ? SW_HIDE : SW_SHOWNA;
|
||||
for (const auto control : {status_label, production_label, priority_button, pause_button, residents_button}) {
|
||||
for (const auto control : {status_label, production_label, priority_button, work_list_button, residents_button}) {
|
||||
ShowWindow(control, flags);
|
||||
}
|
||||
for (const auto control : dock_section_buttons) ShowWindow(control, flags);
|
||||
title_screen.show(visible);
|
||||
SetMenu(window, visible ? nullptr : play_menu);
|
||||
DrawMenuBar(window);
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
title_screen.layout(client.right, client.bottom);
|
||||
layout_command_dock(window);
|
||||
layout_scene(window);
|
||||
SetFocus(window);
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
}
|
||||
@@ -1134,27 +1159,14 @@ void show_lan_info(HWND window) {
|
||||
(addresses.empty() ? std::wstring(L"см. ipconfig") : widen_ascii(addresses)) +
|
||||
L"\nКод партии: " + widen_ascii(lan.join_code()) +
|
||||
L"\nПорт TCP: " + std::to_wstring(lan.port()) +
|
||||
L"\n\nДруг в той же сети выбирает «Кооператив → Подключиться…».";
|
||||
L"\n\nДруг в той же сети выбирает «Подключиться к другу…» в главном меню.";
|
||||
MessageBoxW(window, text.c_str(), L"Кооператив по локальной сети", MB_OK | MB_ICONINFORMATION);
|
||||
}
|
||||
|
||||
void refresh_lan_controls(HWND window) {
|
||||
const auto state = lan.state();
|
||||
displayed_lan_state = state;
|
||||
const bool offline = state == LanState::Offline;
|
||||
const bool hosting = state == LanState::Hosting || state == LanState::HostConnected;
|
||||
const bool disconnected = state == LanState::GuestDisconnected;
|
||||
const auto enable = [&](UINT command, bool enabled) {
|
||||
if (play_menu) EnableMenuItem(play_menu, command, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
|
||||
};
|
||||
enable(lan_host_id, offline);
|
||||
enable(lan_join_id, offline || disconnected);
|
||||
enable(lan_info_id, hosting);
|
||||
enable(lan_reconnect_id, disconnected);
|
||||
enable(lan_leave_id, !offline);
|
||||
enable(title_menu_id, offline);
|
||||
enable(save_menu_id, !lan.is_guest());
|
||||
enable(load_menu_id, offline);
|
||||
const wchar_t* suffix = L"";
|
||||
switch (state) {
|
||||
case LanState::Offline: break;
|
||||
@@ -1169,11 +1181,10 @@ void refresh_lan_controls(HWND window) {
|
||||
if (disconnected) {
|
||||
set_placement_mode(window, PlacementMode::None);
|
||||
placement_message = showing_title ? L"Не удалось подключиться. Проверьте адрес и код." :
|
||||
L"Связь прервана. «Кооператив → Подключиться снова». " + widen_ascii(lan.detail());
|
||||
L"Связь прервана. «Esc → Подключиться снова». " + widen_ascii(lan.detail());
|
||||
} else if (state == LanState::GuestConnected) {
|
||||
placement_message = L"Подключено к колонии хозяина.";
|
||||
}
|
||||
DrawMenuBar(window);
|
||||
if (roster.window) update_roster_details();
|
||||
update_status();
|
||||
if (showing_title) {
|
||||
@@ -1717,7 +1728,7 @@ void draw_world(HDC dc, int width, int height) {
|
||||
DeleteObject(background);
|
||||
if (!world) return;
|
||||
|
||||
if (height > map_top + map_footer) {
|
||||
if ((!prefer_direct3d || !graphics.ready()) && height > map_top + map_footer) {
|
||||
const int saved = SaveDC(dc);
|
||||
if (saved != 0) {
|
||||
IntersectClipRect(dc, 0, map_top, width, height - map_footer);
|
||||
@@ -1743,11 +1754,11 @@ void draw_world(HDC dc, int width, int height) {
|
||||
SetBkMode(dc, TRANSPARENT);
|
||||
SetTextColor(dc, color(231, 227, 205));
|
||||
const wchar_t* hint = world->scenario_active() ?
|
||||
L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план" :
|
||||
L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план Esc — меню" :
|
||||
L"Голубой — очередь Бирюзовый — доставка Янтарный — строительство";
|
||||
if (!placement_message.empty()) hint = placement_message.c_str();
|
||||
else if (placement_mode == PlacementMode::Foraging) {
|
||||
hint = L"Щёлкните по ягодному кусту, чтобы включить или выключить сбор. Esc — отмена.";
|
||||
hint = L"Щёлкните по ягодному кусту, чтобы включить или выключить сбор. Правая кнопка — отмена.";
|
||||
} else if (placement_mode == PlacementMode::BerryField) {
|
||||
hint = L"Поле ягод. Выберите свободную клетку. Фермер засеет поле и соберёт урожай.";
|
||||
} else if (placement_mode == PlacementMode::FlaxField) {
|
||||
@@ -1764,16 +1775,16 @@ void draw_world(HDC dc, int width, int height) {
|
||||
hint = move_source ? L"Выберите свободную клетку для переноса." :
|
||||
L"Выберите кровать, склад, станок или посаженный участок.";
|
||||
} else if (placement_mode == PlacementMode::Demolish) {
|
||||
hint = L"Щёлкните по объекту, чтобы снести его. Esc отменяет режим.";
|
||||
hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена.";
|
||||
} else if (placement_mode == PlacementMode::Building) {
|
||||
if (world->staged_beds()) {
|
||||
hint = selected_bed_base
|
||||
? L"Щёлкайте по свободным клеткам. Основу можно сменить под кнопкой «Спальное место»."
|
||||
: L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место».";
|
||||
} else if (world->scenario_active()) {
|
||||
hint = L"Щёлкайте по свободным клеткам. Одно место требует доску. Esc — выход.";
|
||||
hint = L"Щёлкайте по свободным клеткам. Одно место требует доску. Правая кнопка — отмена.";
|
||||
} else {
|
||||
hint = L"Выберите свободную клетку. Домик стоит три доски и два блока. Esc — отмена.";
|
||||
hint = L"Выберите свободную клетку. Домик стоит три доски и два блока. Правая кнопка — отмена.";
|
||||
}
|
||||
}
|
||||
RECT legend{24, height - 159, width - 24, height - 136};
|
||||
@@ -1784,6 +1795,166 @@ void draw_world(HDC dc, int width, int height) {
|
||||
DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
|
||||
}
|
||||
|
||||
settlement::viewer::SceneView scene_view(int width, int height) {
|
||||
const auto pan = camera.offset();
|
||||
const auto scale = camera.scale();
|
||||
const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt;
|
||||
return {width, height, static_cast<float>(width / 2 * scale + pan.x),
|
||||
static_cast<float>(map_origin_y * scale + pan.y - map_top),
|
||||
static_cast<float>(scale), tile_width / 2.f, tile_height / 2.f,
|
||||
cursor, cursor && valid_edit_cell(*cursor), move_source, selected_resident};
|
||||
}
|
||||
|
||||
LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
if (message == WM_NCHITTEST) return HTTRANSPARENT;
|
||||
if (message == WM_ERASEBKGND) return 1;
|
||||
if (message == WM_PAINT) {
|
||||
PAINTSTRUCT paint{};
|
||||
BeginPaint(window, &paint);
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
const bool drawn = !world || !graphics.ready() || !prefer_direct3d ||
|
||||
client.right <= 0 || client.bottom <= 0 ||
|
||||
graphics.render(*world, scene_view(client.right, client.bottom));
|
||||
EndPaint(window, &paint);
|
||||
if (!drawn) {
|
||||
graphics.reset();
|
||||
prefer_direct3d = false;
|
||||
const auto parent = GetParent(window);
|
||||
layout_scene(parent);
|
||||
invalidate_scene(parent);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcW(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
void toggle_graphics(HWND window) {
|
||||
if (prefer_direct3d && graphics.ready()) {
|
||||
prefer_direct3d = false;
|
||||
placement_message = L"Режим графики — изометрия GDI.";
|
||||
} else {
|
||||
prefer_direct3d = graphics.ready() || (scene_window && graphics.initialize(scene_window));
|
||||
placement_message = prefer_direct3d ? L"Режим графики — Direct3D 11." :
|
||||
L"Direct3D 11 недоступен. Включена изометрия GDI.";
|
||||
}
|
||||
layout_scene(window);
|
||||
invalidate_scene(window);
|
||||
}
|
||||
|
||||
struct PauseMenu {
|
||||
LanState lan_state;
|
||||
bool paused;
|
||||
bool scenario;
|
||||
bool direct3d;
|
||||
HBRUSH background;
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK pause_menu_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
switch (message) {
|
||||
case WM_INITDIALOG: {
|
||||
const auto& menu = *reinterpret_cast<const PauseMenu*>(lparam);
|
||||
SetWindowLongPtrW(dialog, DWLP_USER, lparam);
|
||||
const bool offline = menu.lan_state == LanState::Offline;
|
||||
const bool host = menu.lan_state == LanState::Hosting || menu.lan_state == LanState::HostConnected;
|
||||
const bool disconnected = menu.lan_state == LanState::GuestDisconnected;
|
||||
SetWindowTextW(dialog, offline ? L"Меню паузы" : L"Меню игры");
|
||||
const auto control = [&](const wchar_t* type, const wchar_t* label, int id, DWORD flags, RECT rectangle) {
|
||||
MapDialogRect(dialog, &rectangle);
|
||||
const auto child = CreateWindowExW(0, type, label, WS_CHILD | WS_VISIBLE | flags,
|
||||
rectangle.left, rectangle.top, rectangle.right - rectangle.left, rectangle.bottom - rectangle.top,
|
||||
dialog, reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)), GetModuleHandleW(nullptr), nullptr);
|
||||
SendMessageW(child, WM_SETFONT, reinterpret_cast<WPARAM>(GetStockObject(DEFAULT_GUI_FONT)), TRUE);
|
||||
return child;
|
||||
};
|
||||
const auto button = [&](int id, const wchar_t* label, int column, int row, bool enabled = true) {
|
||||
const int x = column == 0 ? 13 : 184;
|
||||
const int y = 27 + row * 25;
|
||||
const auto child = control(L"BUTTON", label, id, WS_TABSTOP | BS_OWNERDRAW,
|
||||
{x, y, x + 155, y + 20});
|
||||
EnableWindow(child, enabled);
|
||||
};
|
||||
control(L"STATIC", L"Поселение", -1, 0, {13, 9, 167, 23});
|
||||
control(L"STATIC", L"Кооператив", -1, 0, {184, 9, 339, 23});
|
||||
button(IDOK, L"Продолжить", 0, 0);
|
||||
button(save_menu_id, L"Сохранить поселение…", 0, 1, offline || host);
|
||||
button(load_menu_id, L"Загрузить поселение…", 0, 2, offline);
|
||||
button(title_menu_id, L"Главное меню", 0, 3, offline);
|
||||
button(graphics_menu_id, menu.direct3d ? L"Графика · Direct3D 11" : L"Графика · Изометрия GDI", 0, 4);
|
||||
button(exit_menu_id, L"Выйти из игры", 0, 5);
|
||||
if (offline) {
|
||||
button(lan_host_id, L"Открыть для друга…", 1, 0, menu.scenario);
|
||||
button(lan_join_id, L"Подключиться к другу…", 1, 1);
|
||||
} else if (host) {
|
||||
button(lan_info_id, L"Адрес и код партии…", 1, 0);
|
||||
button(pause_button_id, menu.paused ? L"Продолжить для всех" : L"Пауза для всех", 1, 1);
|
||||
button(lan_leave_id, L"Закрыть сетевую игру", 1, 2);
|
||||
} else {
|
||||
if (disconnected) button(lan_reconnect_id, L"Подключиться снова", 1, 0);
|
||||
button(lan_leave_id, L"Выйти из сетевой игры", 1, 1);
|
||||
}
|
||||
SetFocus(GetDlgItem(dialog, IDOK));
|
||||
return FALSE;
|
||||
}
|
||||
case WM_CTLCOLORDLG:
|
||||
case WM_CTLCOLORSTATIC:
|
||||
if (const auto* menu = reinterpret_cast<const PauseMenu*>(GetWindowLongPtrW(dialog, DWLP_USER))) {
|
||||
const auto dc = reinterpret_cast<HDC>(wparam);
|
||||
SetTextColor(dc, color(236, 230, 205));
|
||||
SetBkMode(dc, TRANSPARENT);
|
||||
return reinterpret_cast<INT_PTR>(menu->background);
|
||||
}
|
||||
break;
|
||||
case WM_DRAWITEM:
|
||||
if (const auto* item = reinterpret_cast<const DRAWITEMSTRUCT*>(lparam); item && item->CtlType == ODT_BUTTON) {
|
||||
WorkIcon icon = WorkIcon::Resident;
|
||||
if (item->CtlID == graphics_menu_id) icon = WorkIcon::Stone;
|
||||
else if (item->CtlID == save_menu_id || item->CtlID == load_menu_id) icon = WorkIcon::Crate;
|
||||
draw_icon_button(*item, icon, item->CtlID == IDOK, true);
|
||||
return TRUE;
|
||||
}
|
||||
break;
|
||||
case WM_COMMAND:
|
||||
if (HIWORD(wparam) == BN_CLICKED) {
|
||||
EndDialog(dialog, LOWORD(wparam));
|
||||
return TRUE;
|
||||
}
|
||||
break;
|
||||
case WM_CLOSE:
|
||||
EndDialog(dialog, IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void open_pause_menu(HWND window) {
|
||||
if (!world || showing_title || pause_menu_open) return;
|
||||
camera_drag.reset();
|
||||
if (GetCapture() == window) ReleaseCapture();
|
||||
struct alignas(DWORD) EmptyDialog {
|
||||
DLGTEMPLATE header{};
|
||||
WORD menu = 0, window_class = 0, title = 0;
|
||||
} layout;
|
||||
layout.header.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER;
|
||||
layout.header.cx = 352;
|
||||
layout.header.cy = 184;
|
||||
PauseMenu menu{lan.state(), world->paused(), world->scenario_active(), prefer_direct3d && graphics.ready(),
|
||||
CreateSolidBrush(color(34, 46, 40))};
|
||||
pause_menu_open = true;
|
||||
const auto action = DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &layout.header, window,
|
||||
pause_menu_proc, reinterpret_cast<LPARAM>(&menu));
|
||||
if (action == IDOK) {
|
||||
if (lan.state() == LanState::Offline && world->paused()) {
|
||||
static_cast<void>(send_command(settlement::CommandKind::SetPaused));
|
||||
}
|
||||
} else if (action != IDCANCEL && action != -1) {
|
||||
SendMessageW(window, WM_COMMAND, static_cast<WPARAM>(action), 0);
|
||||
}
|
||||
pause_menu_open = false;
|
||||
DeleteObject(menu.background);
|
||||
if (IsWindow(window)) SetFocus(window);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
switch (message) {
|
||||
case WM_GETMINMAXINFO: {
|
||||
@@ -1793,7 +1964,16 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
return 0;
|
||||
}
|
||||
case WM_CREATE: {
|
||||
play_menu = GetMenu(window);
|
||||
const auto instance = GetModuleHandleW(nullptr);
|
||||
WNDCLASSW viewport{};
|
||||
viewport.lpfnWndProc = scene_window_proc;
|
||||
viewport.hInstance = instance;
|
||||
viewport.lpszClassName = scene_window_class;
|
||||
viewport.hCursor = LoadCursorW(nullptr, IDC_ARROW);
|
||||
if (RegisterClassW(&viewport) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) {
|
||||
scene_window = CreateWindowExW(0, scene_window_class, L"", WS_CHILD,
|
||||
0, map_top, 1, 1, window, nullptr, instance, nullptr);
|
||||
}
|
||||
status_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE,
|
||||
18, 14, 735, 24, window,
|
||||
reinterpret_cast<HMENU>(static_cast<INT_PTR>(status_label_id)),
|
||||
@@ -1808,7 +1988,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
GetModuleHandleW(nullptr), nullptr);
|
||||
};
|
||||
priority_button = button(priority_button_id, 18, 142, L"Равный приоритет");
|
||||
pause_button = button(pause_button_id, 168, 96, L"Пауза");
|
||||
work_list_button = button(work_list_button_id, 168, 108, L"Работы", BS_OWNERDRAW);
|
||||
residents_button = button(residents_button_id, 0, 112, L"Жители", BS_OWNERDRAW, 0);
|
||||
for (std::size_t index = 0; index < dock_sections.size(); ++index) {
|
||||
dock_section_buttons[index] = button(first_dock_section_id + static_cast<int>(index), 0, 112,
|
||||
@@ -1838,6 +2018,25 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
if (const auto brush = title_screen.paint_list_background(reinterpret_cast<HWND>(lparam),
|
||||
reinterpret_cast<HDC>(wparam))) return reinterpret_cast<LRESULT>(brush);
|
||||
}
|
||||
if (LOWORD(wparam) == exit_menu_id && pause_menu_open) {
|
||||
DestroyWindow(window);
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) == graphics_menu_id && pause_menu_open) {
|
||||
toggle_graphics(window);
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) == work_list_button_id && HIWORD(wparam) == BN_CLICKED && can_give_orders()) {
|
||||
if (const auto menu = create_work_menu()) {
|
||||
RECT bounds{};
|
||||
GetWindowRect(work_list_button, &bounds);
|
||||
TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
|
||||
bounds.left, bounds.bottom, 0, window, nullptr);
|
||||
DestroyMenu(menu);
|
||||
}
|
||||
SetFocus(window);
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case WM_COMMAND:
|
||||
if (showing_title) {
|
||||
@@ -1934,7 +2133,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
update_status();
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) == pause_button_id) {
|
||||
if (LOWORD(wparam) == pause_button_id && pause_menu_open && !lan.is_guest()) {
|
||||
static_cast<void>(send_command(settlement::CommandKind::SetPaused, {},
|
||||
static_cast<std::uint8_t>(!world->paused())));
|
||||
update_status();
|
||||
@@ -2105,16 +2304,16 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
SendMessageW(window, WM_COMMAND, reset_camera_id, 0);
|
||||
return 0;
|
||||
}
|
||||
if (wparam == VK_ESCAPE && (placement_mode != PlacementMode::None || work_panel != WorkPanel::None)) {
|
||||
set_placement_mode(window, PlacementMode::None);
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
if (wparam == VK_ESCAPE) {
|
||||
if ((lparam & (1L << 30)) == 0) open_pause_menu(window);
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case WM_TIMER:
|
||||
if (wparam == timer_id && world) {
|
||||
if (showing_title && lan.state() != LanState::Connecting) return 0;
|
||||
if (!showing_title && !file_dialog_active && !lan.is_guest()) world->step();
|
||||
if (!showing_title && !file_dialog_active && !lan.is_guest() &&
|
||||
(!pause_menu_open || lan.state() != LanState::Offline)) world->step();
|
||||
if (auto snapshot = lan.poll(*world)) {
|
||||
world = std::move(snapshot);
|
||||
if (showing_title) show_title_screen(window, false);
|
||||
@@ -2140,6 +2339,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
title_screen.layout(client.right, client.bottom);
|
||||
} else {
|
||||
layout_command_dock(window);
|
||||
layout_scene(window);
|
||||
}
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
break;
|
||||
@@ -2167,8 +2367,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
case WM_DESTROY:
|
||||
KillTimer(window, timer_id);
|
||||
lan.leave();
|
||||
if (play_menu && GetMenu(window) != play_menu) DestroyMenu(play_menu);
|
||||
play_menu = nullptr;
|
||||
graphics.reset();
|
||||
scene_window = nullptr;
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
}
|
||||
@@ -2189,35 +2389,10 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
|
||||
window_class_info.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
|
||||
RegisterClassExW(&window_class_info);
|
||||
|
||||
HMENU menu_bar = CreateMenu();
|
||||
HMENU file_menu = CreatePopupMenu();
|
||||
HMENU view_menu = CreatePopupMenu();
|
||||
HMENU coop_menu = CreatePopupMenu();
|
||||
HMENU work_menu = create_work_menu();
|
||||
AppendMenuW(file_menu, MF_STRING, save_menu_id, L"Сохранить поселение…");
|
||||
AppendMenuW(file_menu, MF_STRING, load_menu_id, L"Загрузить поселение…");
|
||||
AppendMenuW(file_menu, MF_SEPARATOR, 0, nullptr);
|
||||
AppendMenuW(file_menu, MF_STRING, title_menu_id, L"Главное меню");
|
||||
AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast<UINT_PTR>(file_menu), L"Поселение");
|
||||
AppendMenuW(view_menu, MF_STRING, reset_camera_id, L"Общий план\tHome");
|
||||
AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast<UINT_PTR>(view_menu), L"Вид");
|
||||
if (work_menu != nullptr) {
|
||||
AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast<UINT_PTR>(work_menu), L"Работы");
|
||||
}
|
||||
AppendMenuW(coop_menu, MF_STRING, lan_host_id, L"Открыть колонию для друга…");
|
||||
AppendMenuW(coop_menu, MF_STRING, lan_join_id, L"Подключиться…");
|
||||
AppendMenuW(coop_menu, MF_STRING, lan_info_id, L"Адрес и код партии…");
|
||||
AppendMenuW(coop_menu, MF_STRING, lan_reconnect_id, L"Подключиться снова");
|
||||
AppendMenuW(coop_menu, MF_SEPARATOR, 0, nullptr);
|
||||
AppendMenuW(coop_menu, MF_STRING, lan_leave_id, L"Выйти из сетевой игры");
|
||||
AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast<UINT_PTR>(coop_menu), L"Кооператив");
|
||||
HWND window = CreateWindowExW(0, window_class, L"Settlement",
|
||||
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 1120, 752,
|
||||
nullptr, menu_bar, instance, nullptr);
|
||||
if (!window) {
|
||||
DestroyMenu(menu_bar);
|
||||
return 1;
|
||||
}
|
||||
nullptr, nullptr, instance, nullptr);
|
||||
if (!window) return 1;
|
||||
ShowWindow(window, show_command);
|
||||
UpdateWindow(window);
|
||||
|
||||
@@ -2225,6 +2400,11 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
|
||||
while (GetMessageW(&message, nullptr, 0, 0) > 0) {
|
||||
if (roster.window && IsDialogMessageW(roster.window, &message)) continue;
|
||||
if (showing_title && IsDialogMessageW(window, &message)) continue;
|
||||
if (!showing_title && message.message == WM_KEYDOWN && message.wParam == VK_ESCAPE &&
|
||||
(message.hwnd == window || IsChild(window, message.hwnd))) {
|
||||
SendMessageW(window, message.message, message.wParam, message.lParam);
|
||||
continue;
|
||||
}
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@
|
||||
- Производительность ядра измерена на колониях с 50–500 жителями, полями, складами и ремеслом. Результаты и команда запуска описаны в [отчёте](../benchmarks/colony-performance.md).
|
||||
- Основные команды собраны в нижней панели «Жители», «Добыча», «Участки» и «Строительство». Меню «Работы» открывает те же команды по профессиям.
|
||||
- Главное меню открывается при запуске. В нём можно начать новую колонию, выбрать сохранение или подключиться к другу.
|
||||
- Esc открывает меню паузы, сохранений, сетевых действий и графики.
|
||||
- Direct3D 11 рисует карту, жителей и постройки как объёмную геометрию с глубиной. Изометрия GDI доступна через меню Esc.
|
||||
- Поиск ресурсных работ отбирает подходящие поручения по профессиям. Повторные запросы путей используют кэш.
|
||||
- Движение, прогресс работ жителей и поиск маршрутов для общих заданий выполняются в пуле из двух и более потоков. Тесты проверяют игровые результаты, сохранения и команды кооператива.
|
||||
|
||||
@@ -36,7 +38,7 @@
|
||||
|
||||
## Ограничения прототипа
|
||||
|
||||
- Графика изометрическая и рисуется Win32/GDI; полноценного 3D-рендера пока нет.
|
||||
- Камера показывает карту в изометрической проекции. Direct3D использует базовые модели и затенение граней.
|
||||
- Каждый поход добытчика доставляет одну единицу сырья. Строитель везёт весь комплект для одного домика за рейс с остановками у нужных складов. Мастерские пока используют складское сырьё напрямую.
|
||||
- Свободный житель сначала ищет еду, если проголодался. Если порции нет, он может снова взять работу. При голоде здоровье пока остаётся прежним.
|
||||
- Завершённое спальное место назначается одному жителю. Сейчас жители идут спать по усталости.
|
||||
|
||||
+11
-9
@@ -12,15 +12,17 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
|
||||
|
||||
При запуске без явного параметра командная версия выбирает от двух до восьми потоков с учётом числа логических процессоров. Для ручного выбора используйте `settlement_sim.exe --workers N`, где N от 2 до 32.
|
||||
|
||||
Колесо мыши приближает и отдаляет карту относительно курсора. Чтобы сдвинуть карту, перетащите её с зажатой левой или средней кнопкой мыши. Короткий щелчок левой кнопкой выбирает жителя или ставит чертёж. Home или «Вид → Общий план» возвращает исходный вид.
|
||||
Колесо мыши приближает и отдаляет карту относительно курсора. Чтобы сдвинуть карту, перетащите её с зажатой левой или средней кнопкой мыши. Короткий щелчок левой кнопкой выбирает жителя или ставит чертёж. Home возвращает исходный вид.
|
||||
|
||||
В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу, затем щёлкайте по свободным клеткам. Выбранная основа применяется к следующим кроватям до выхода из режима или смены основы. Повторное нажатие «Спальное место», Esc или правый щелчок завершает размещение.
|
||||
Игра пробует включить Direct3D 11 при входе в колонию. Рендерер рисует объёмную карту с глубиной, постройки и жителей в изометрической проекции. Кнопка «Графика» в меню Esc переключает Direct3D и изометрию GDI. При ошибке устройства карта открывается в GDI.
|
||||
|
||||
В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу, затем щёлкайте по свободным клеткам. Выбранная основа применяется к следующим кроватям до выхода из режима или смены основы. Повторное нажатие «Спальное место» или правый щелчок завершает размещение.
|
||||
|
||||
Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту.
|
||||
|
||||
Уставшие жители работают медленнее и после поручения идут к закреплённой кровати. На земле они отдыхают только при сильной усталости и восстанавливают меньше сил. Щелчок по жителю показывает усталость и состояние сна.
|
||||
|
||||
На нижней панели «Добыча» (H) открывает сбор с кустов и шахту. «Участки» (Z) открывают поля, посадки, склад и кладовую. «Строительство» (B) открывает спальное место, станок, перенос и снос. Выбор раздела показывает его инструменты над панелью. Те же действия сгруппированы по профессиям в верхнем меню «Работы». Разнорабочий берёт работу любой профессии.
|
||||
На нижней панели «Добыча» (H) открывает сбор с кустов и шахту. «Участки» (Z) открывают поля, посадки, склад и кладовую. «Строительство» (B) открывает спальное место, станок, перенос и снос. Выбор раздела показывает его инструменты над панелью. Кнопка «Работы» открывает те же действия по профессиям. Разнорабочий берёт работу любой профессии.
|
||||
|
||||
Откройте «Жители…» (клавиша C), выберите поселенца в списке, нажмите на нужную роль и подтвердите кнопкой «Назначить профессию». В списке видна текущая роль каждого жителя, а число рядом с названием профессии показывает, сколько жителей уже ею занимаются. Можно последовательно назначать роли всему поселению в одном окне. При смене профессии житель заканчивает текущее поручение.
|
||||
|
||||
@@ -30,18 +32,18 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
|
||||
|
||||
Для переноса выберите «Строительство → Перенести», щёлкните по кровати, складу, станку или посаженному участку и выберите новую клетку. Кровать сохраняет владельца, склад — содержимое. Там же находится «Снести». Снос склада с запасами требует подтверждения. Дождитесь освобождения занятого объекта перед переносом или сносом.
|
||||
|
||||
Нажмите «Добыча → Сбор ягод» и щёлкните по кусту, чтобы включить или отключить его сбор. Правый щелчок или Esc закрывает режим выбора. Кнопка приоритета переключает режимы «Равный приоритет», «Сначала еда» и «Сначала стройка». В паузе можно менять задания. Цель выполнена, когда каждому назначено место и в кладовой есть шесть свободных порций.
|
||||
Нажмите «Добыча → Сбор ягод» и щёлкните по кусту, чтобы включить или отключить его сбор. Правый щелчок закрывает режим выбора. Кнопка приоритета переключает режимы «Равный приоритет», «Сначала еда» и «Сначала стройка». Цель выполнена, когда каждому назначено место и в кладовой есть шесть свободных порций.
|
||||
|
||||
Кусты дают ягоды, которые жители несут в кладовую с розовой крышкой. Розовый маршрут ведёт к еде. Чтобы увидеть голод жителя и его груз, щёлкните по фигурке вне режима размещения чертежа.
|
||||
|
||||
В меню «Поселение» выберите «Сохранить поселение…» или «Загрузить поселение…». Время останавливается на время выбора файла. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. Если файл повреждён или его версия не подходит, окно показывает ошибку и продолжает текущую партию.
|
||||
Esc открывает меню игры из любого режима строительства и выбора. В одиночной партии симуляция останавливается, пока меню открыто. «Продолжить» или Esc закрывает меню. Выбранный на карте инструмент можно использовать дальше. В этом меню доступны сохранение, загрузка, главное меню и выход. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При ошибке загрузки текущая колония остаётся открытой.
|
||||
|
||||
В одиночной игре «Поселение → Главное меню» останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки.
|
||||
В одиночной игре «Esc → Главное меню» возвращает на стартовый экран и останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки.
|
||||
|
||||
## Кооператив по локальной сети
|
||||
|
||||
1. Запустите одинаковую версию игры на двух компьютерах в одной локальной сети.
|
||||
2. Хозяин открывает свою колонию через «Кооператив → Открыть колонию для друга…» и передаёт гостю IPv4 и код партии. Порт игры — TCP 41727.
|
||||
3. Гость выбирает «Подключиться к другу…» в главном меню или «Кооператив → Подключиться…» в игре и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой.
|
||||
2. Хозяин открывает свою колонию через «Esc → Открыть для друга…» и передаёт гостю IPv4 и код партии. Порт игры — TCP 41727.
|
||||
3. Гость выбирает «Подключиться к другу…» в главном меню или в меню Esc и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой.
|
||||
|
||||
Оба игрока строят и меняют задания в общей колонии. Хозяин ставит симуляцию на паузу и сохраняет игру. После выхода гостя хозяин может продолжить партию.
|
||||
Оба игрока строят и меняют задания в общей колонии. Меню Esc доступно каждому. Хозяин сохраняет игру и останавливает симуляцию кнопкой «Пауза для всех». После выхода гостя хозяин может продолжить партию.
|
||||
Reference in new issue
Block a user