-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhellodirectx.cpp
More file actions
302 lines (251 loc) · 9.65 KB
/
hellodirectx.cpp
File metadata and controls
302 lines (251 loc) · 9.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/**
* @file hellodirectx.cpp
* @author Pratchaya (info@nordickey.se)
* @brief Hello DirectX!
* @version 0.0
* @date 2022-11-10
*
* @copyright Copyright (c) 2022
*/
// Windows standard libraries
#include <Windows.h>
#include <cmath>
#include <unordered_map>
#include <vector>
#include <winerror.h>
#include "fmt/std.h"
#include <DirectXMath.h>
#include "d3x/buffer.hpp"
#include "d3x/graphics.hpp"
#include "d3x/pipeline.hpp"
#include "d3x/texture.hpp"
#include "d3x/types.hpp"
#include "d3x/window.hpp"
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
using namespace d3x::types;
constexpr i32 SCREEN_WIDTH = 1280;
constexpr i32 SCREEN_HEIGHT = 720;
constexpr d3x::buffer_element VERTEX_LAYOUT[] = {
{"POSITION", d3x::type::vec3},
{"NORMAL", d3x::type::vec3},
{"TEXCOORD", d3x::type::vec2},
};
struct Vertex {
float px, py, pz; // position
float nx, ny, nz; // normal
float u, v; // texture coords
};
auto WINAPI WinMain(HINSTANCE hInstance,
[[maybe_unused]]HINSTANCE hPrevInstance,
[[maybe_unused]]LPSTR lpCmdLine, int nCmdShow) -> int {
d3x::window window{{
.title = "Hello, DirectX!",
.width = SCREEN_WIDTH,
.height = SCREEN_HEIGHT,
}};
if (!window.setup(hInstance, nCmdShow)) return 1;
d3x::graphics gfx{{
.hwnd = window.native(),
.width = window.width(),
.height = window.height(),
}};
if (!gfx.setup()) return 1;
d3x::pipeline pipe{};
if (!pipe.create(gfx.device(), {
.vs_path = "./res/shaders/camera.vs.hlsl",
.ps_path = "./res/shaders/main.ps.hlsl",
.layout = VERTEX_LAYOUT,
.rasterizer = {
.cull = d3x::cull_mode::none,
.fill = d3x::fill_mode::solid,
.ccw_front = true,
},
}, gfx.msaa())) return 1;
// Camera
struct CameraBuffer {
DirectX::XMFLOAT4X4 view;
DirectX::XMFLOAT4X4 proj;
};
d3x::uniform<CameraBuffer> camera{};
if (!camera.create(gfx.device())) return 1;
// Object
struct ObjectBuffer {
DirectX::XMFLOAT4X4 model;
};
d3x::uniform<ObjectBuffer> object{};
if (!object.create(gfx.device())) return 1;
// Lighting
struct LightingBuffer {
DirectX::XMFLOAT3 light_dir;
float _pad0;
DirectX::XMFLOAT3 camera_pos;
float _pad1;
DirectX::XMFLOAT3 ambient_color;
float _pad2;
};
d3x::uniform<LightingBuffer> lighting{};
if (!lighting.create(gfx.device())) return 1;
lighting.data().light_dir = {0.5f, 0.5f, -1.0f};
lighting.data().ambient_color = {0.35f, 0.35f, 0.35f};
// Orbit camera state
struct {
f32 yaw = 0.8f; // radians
f32 pitch = 0.6f; // radians
f32 distance = 3.0f;
DirectX::XMFLOAT3 target{0.0f, 0.0f, 0.0f};
f32 sensitivity = 0.005f;
f32 pan_speed = 0.005f;
f32 zoom_speed = 0.3f;
i32 last_mx = 0, last_my = 0;
bool orbiting = false;
bool panning = false;
} orbit;
auto update_camera = [&] {
using namespace DirectX;
f32 cp = std::cos(orbit.pitch), sp = std::sin(orbit.pitch);
f32 cy = std::cos(orbit.yaw), sy = std::sin(orbit.yaw);
XMVECTOR offset = XMVectorSet(
orbit.distance * cp * cy,
orbit.distance * cp * sy,
orbit.distance * sp,
0.0f
);
XMVECTOR target = XMLoadFloat3(&orbit.target);
XMVECTOR eye = XMVectorAdd(target, offset);
XMVECTOR up = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
XMMATRIX view = XMMatrixLookAtLH(eye, target, up);
XMMATRIX proj = XMMatrixPerspectiveFovLH(
XMConvertToRadians(60.0f),
static_cast<float>(window.width()) / static_cast<float>(window.height()),
0.1f, 1000.0f
);
XMStoreFloat4x4(&camera.data().view, XMMatrixTranspose(view));
XMStoreFloat4x4(&camera.data().proj, XMMatrixTranspose(proj));
camera.upload(gfx.ctx());
XMFLOAT3 eye_pos;
XMStoreFloat3(&eye_pos, eye);
lighting.data().camera_pos = eye_pos;
lighting.upload(gfx.ctx());
};
window.on_mouse_button([&](i32 button, bool pressed) {
if (button == 1) orbit.orbiting = pressed;
if (button == 2) orbit.panning = pressed;
});
window.on_mouse_move([&](i32 x, i32 y) {
i32 dx = x - orbit.last_mx;
i32 dy = y - orbit.last_my;
orbit.last_mx = x;
orbit.last_my = y;
if (orbit.orbiting) {
orbit.yaw += static_cast<f32>(dx) * orbit.sensitivity;
orbit.pitch += static_cast<f32>(dy) * orbit.sensitivity;
// Clamp pitch to avoid flipping at poles
constexpr f32 limit = 1.5f;
if (orbit.pitch > limit) orbit.pitch = limit;
if (orbit.pitch < -limit) orbit.pitch = -limit;
}
if (orbit.panning) {
using namespace DirectX;
// Compute camera right and up vectors for panning in screen space
f32 cp = std::cos(orbit.pitch), sp = std::sin(orbit.pitch);
f32 cy = std::cos(orbit.yaw), sy = std::sin(orbit.yaw);
XMVECTOR forward = XMVectorSet(-cp * cy, -cp * sy, -sp, 0.0f);
XMVECTOR world_up = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
XMVECTOR right = XMVector3Normalize(XMVector3Cross(world_up, forward));
XMVECTOR up = XMVector3Cross(forward, right);
XMVECTOR pan = XMVectorScale(right, static_cast<f32>(dx) * orbit.pan_speed * orbit.distance)
+ XMVectorScale(up, static_cast<f32>(dy) * orbit.pan_speed * orbit.distance);
XMVECTOR t = XMLoadFloat3(&orbit.target);
XMStoreFloat3(&orbit.target, XMVectorAdd(t, pan));
}
});
window.on_mouse_scroll([&](f32 delta) {
orbit.distance -= delta * orbit.zoom_speed;
if (orbit.distance < 0.1f) orbit.distance = 0.1f;
});
// Load 3D model
tinyobj::attrib_t attrib{};
std::vector<tinyobj::shape_t> shapes{};
std::vector<tinyobj::material_t> materials{};
std::string warn{};
std::string err{};
// bool const obj_res = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, "./res/models/cat/12221_Cat_v1_l3.obj", "./res/models/cat/");
bool const obj_res = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, "./res/models/viking_room/viking_room.obj", "./res/models/viking_room/");
if (!warn.empty()) fmt::print(stderr, "tinyobj::warn: {}", warn);
if (!err.empty()) fmt::print(stderr, "tinyobj::err: {}", err);
if (!obj_res) return 1;
d3x::vertex_buffer triangles{};
d3x::index_buffer indices{};
// OBJ has separate indices per attribute, so we deduplicate into a unified vertex list.
std::vector<Vertex> mesh_vertices;
std::vector<u32> mesh_indices;
std::unordered_map<u64, u32> index_cache;
for (auto const& shape : shapes) {
for (auto const& idx : shape.mesh.indices) {
// Pack the three OBJ indices into one 64-bit key for deduplication.
u64 key = (u64)(u32)idx.vertex_index
| (u64)(u32)idx.normal_index << 20
| (u64)(u32)idx.texcoord_index << 40;
auto [it, inserted] = index_cache.emplace(key, (u32)mesh_vertices.size());
if (inserted) {
Vertex v{};
v.px = attrib.vertices[3 * idx.vertex_index + 0];
v.py = attrib.vertices[3 * idx.vertex_index + 1];
v.pz = attrib.vertices[3 * idx.vertex_index + 2];
if (idx.normal_index >= 0) {
v.nx = attrib.normals[3 * idx.normal_index + 0];
v.ny = attrib.normals[3 * idx.normal_index + 1];
v.nz = attrib.normals[3 * idx.normal_index + 2];
}
if (idx.texcoord_index >= 0) {
v.u = attrib.texcoords[2 * idx.texcoord_index + 0];
v.v = 1.0f - attrib.texcoords[2 * idx.texcoord_index + 1];
}
mesh_vertices.push_back(v);
}
mesh_indices.push_back(it->second);
}
}
if (!triangles.upload(gfx.device(), std::as_bytes(std::span{mesh_vertices}), sizeof(Vertex)))
return 1;
if (!indices.upload(gfx.device(), mesh_indices))
return 1;
d3x::texture tex{};
if (!tex.load(gfx.device(), "./res/models/viking_room/viking_room.png")) return 1;
// if (!tex.load(gfx.device(), "./res/models/cat/Cat_diffuse.jpg")) return 1;
d3x::sampler samp{};
if (!samp.create(gfx.device())) return 1;
auto render_frame = [&]{
gfx.resize(window.width(), window.height());
update_camera();
gfx.clear(0.0f, 0.0f, 0.0f);
pipe.bind(gfx.ctx());
triangles.bind(gfx.ctx());
indices.bind(gfx.ctx());
camera.bind_vs(gfx.ctx(), 0);
DirectX::XMStoreFloat4x4(&object.data().model, DirectX::XMMatrixTranspose(
DirectX::XMMatrixIdentity()
));
object.upload(gfx.ctx());
object.bind_vs(gfx.ctx(), 1);
lighting.bind_ps(gfx.ctx(), 0);
tex.bind(gfx.ctx(), 0);
samp.bind(gfx.ctx(), 0);
gfx.ctx()->DrawIndexed(indices.count(), 0, 0);
gfx.present();
};
window.on_paint([&] {
render_frame();
});
MSG msg;
while (true) {
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT) break;
}
render_frame();
}
return static_cast<int>(msg.wParam);
}