-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
346 lines (296 loc) · 12 KB
/
main.cpp
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Based and inspired by https://github.com/cwoffenden/hello-webgpu
// and https://github.com/emscripten-core/emscripten/blob/main/test/webgpu_basic_rendering.cpp
#include <webgpu/webgpu_cpp.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <emscripten.h>
#include <emscripten/html5.h>
#include <emscripten/html5_webgpu.h>
struct Vertex
{
float pos[2] = { 0.0f, 0.0f };
float color[3] = { 0.0f, 0.0f, 0.0f };
};
struct UbObject
{
float pos[2] = { 0.0f, 0.0f };
float padding[2]; // 構造体サイズが16byteの倍数になるように調整
};
const char shaderCode[] = R"(
struct VSIn {
@location(0) Pos : vec2<f32>,
@location(1) Color : vec3<f32>,
};
struct VSOut {
@builtin(position) Pos: vec4<f32>,
@location(0) Color: vec3<f32>,
};
struct UbObject
{
Pos : vec2<f32>,
Padding : vec2<f32>,
};
@group(0) @binding(0) var<uniform> ubObject : UbObject;
@vertex
fn main_v(In: VSIn) -> VSOut {
var out: VSOut;
out.Pos = vec4<f32>(In.Pos + ubObject.Pos, 0.0, 1.0);
out.Color = In.Color;
return out;
}
@fragment
fn main_f(In : VSOut) -> @location(0) vec4<f32> {
return vec4<f32>(In.Color, 1.0f);
}
)";
wgpu::Instance instance;
wgpu::Device device;
wgpu::Queue queue;
wgpu::Buffer readbackBuffer;
wgpu::RenderPipeline pipeline;
wgpu::Surface surface;
wgpu::SwapChain swapChain;
wgpu::TextureView canvasDepthStencilView;
const uint32_t kWidth = 1280;
const uint32_t kHeight = 720;
wgpu::Buffer vertexBuffer; // vertex buffer
wgpu::Buffer indexBuffer; // index buffer
wgpu::Buffer uniformBuffer; // uniform buffer
wgpu::BindGroup bindGroup;
UbObject ubObject;
wgpu::Buffer createBuffer(const void* data, size_t size, wgpu::BufferUsage usage) {
wgpu::BufferDescriptor desc = {};
desc.usage = wgpu::BufferUsage::CopyDst | usage;
desc.size = size;
wgpu::Buffer buffer = device.CreateBuffer(&desc);
queue.WriteBuffer(buffer, 0, data, size);
return buffer;
}
void initRenderPipelineAndBuffers() {
//---------------------------------------
// Shaderのコンパイル、ShaderModule作成
//---------------------------------------
wgpu::ShaderModule shaderModule{};
wgpu::ShaderModuleWGSLDescriptor wgslDesc{};
wgslDesc.code = shaderCode;
wgpu::ShaderModuleDescriptor smDesc{};
smDesc.nextInChain = &wgslDesc;
shaderModule = device.CreateShaderModule(&smDesc);
//---------------------------------------
// bufferの作成
//---------------------------------------
// 頂点情報(座標と頂点色)
// 座標系はDirectXと同じY-Up
Vertex const vertData[] = {
{ 0.8f, -0.8f, 0.0f, 1.0f, 0.0f }, // 右下
{ -0.8f, -0.8f, 0.0f, 0.0f, 1.0f }, // 左下
{ -0.0f, 0.8f, 1.0f, 0.0f, 0.0f }, // 上
};
// 頂点インデックス情報
uint16_t const indxData[] = {
0, 1, 2
, 0 // padding。各バッファのサイズは4byteの倍数である必要がある。
};
// vertex buffer
vertexBuffer = createBuffer(vertData, sizeof(vertData), wgpu::BufferUsage::Vertex);
// index buffer
indexBuffer = createBuffer(indxData, sizeof(indxData), wgpu::BufferUsage::Index);
// Uniform buffer
uniformBuffer = createBuffer(&ubObject, sizeof(ubObject), wgpu::BufferUsage::Uniform);
//---------------------------------------
// uniformBufferについての
// group layoutとbind group
//---------------------------------------
// bind group layout
// bind groupの抽象的な情報。render pipelineに覚えてもらうために、ここで作成&登録する。
wgpu::BufferBindingLayout buf = {};
buf.type = wgpu::BufferBindingType::Uniform;
wgpu::BindGroupLayoutEntry bglEntry = {};
bglEntry.binding = 0; // シェーダーソース上の「@binding(0)」に割り当てられる。
bglEntry.visibility = wgpu::ShaderStage::Vertex | wgpu::ShaderStage::Fragment;
bglEntry.buffer = buf;
wgpu::BindGroupLayoutDescriptor bglDesc{};
bglDesc.entryCount = 1;
bglDesc.entries = &bglEntry;
wgpu::BindGroupLayout bgl = device.CreateBindGroupLayout(&bglDesc);
// bind group
wgpu::BindGroupEntry bgEntry = {};
bgEntry.binding = 0;
bgEntry.buffer = uniformBuffer;
bgEntry.offset = 0;
bgEntry.size = sizeof(ubObject);
wgpu::BindGroupDescriptor bgDesc;
bgDesc.layout = bgl;
bgDesc.entryCount = 1;
bgDesc.entries = &bgEntry;
bindGroup = device.CreateBindGroup(&bgDesc);
//---------------------------------------
// render pipelineの作成
//---------------------------------------
// vertex
wgpu::VertexAttribute vertAttrs[2] = {};
vertAttrs[0].format = wgpu::VertexFormat::Float32x2;
vertAttrs[0].offset = 0;
vertAttrs[0].shaderLocation = 0;
vertAttrs[1].format = wgpu::VertexFormat::Float32x3;
vertAttrs[1].offset = 2 * sizeof(float);
vertAttrs[1].shaderLocation = 1;
wgpu::VertexBufferLayout vertexBufferLayout = {};
vertexBufferLayout.arrayStride = 5 * sizeof(float);
vertexBufferLayout.attributeCount = 2;
vertexBufferLayout.attributes = vertAttrs;
wgpu::VertexState vertexState = {};
vertexState.module = shaderModule;
vertexState.entryPoint = "main_v";
vertexState.bufferCount = 1;
vertexState.buffers = &vertexBufferLayout;
// fragment and blendState
wgpu::BlendState blend = {};
blend.color.operation = wgpu::BlendOperation::Add;
blend.color.srcFactor = wgpu::BlendFactor::SrcAlpha;
blend.color.dstFactor = wgpu::BlendFactor::OneMinusDstAlpha;
blend.alpha.operation = wgpu::BlendOperation::Add;
blend.alpha.srcFactor = wgpu::BlendFactor::One;
blend.alpha.dstFactor = wgpu::BlendFactor::OneMinusDstAlpha;
wgpu::ColorTargetState colorTargetState{};
colorTargetState.format = wgpu::TextureFormat::BGRA8Unorm;
colorTargetState.blend = &blend;
wgpu::FragmentState fragmentState{};
fragmentState.module = shaderModule;
fragmentState.entryPoint = "main_f";
fragmentState.targetCount = 1;
fragmentState.targets = &colorTargetState;
// DepthStencilState
wgpu::DepthStencilState depthStencilState{};
depthStencilState.format = wgpu::TextureFormat::Depth24PlusStencil8;
depthStencilState.depthWriteEnabled = true;
depthStencilState.depthCompare = wgpu::CompareFunction::Less;
// render pipelineの作成
wgpu::PipelineLayoutDescriptor pllDesc{}; // bindGroupLayoutをまとめたもの
pllDesc.bindGroupLayoutCount = 1;
pllDesc.bindGroupLayouts = &bgl;
wgpu::RenderPipelineDescriptor descriptor{};
descriptor.layout = device.CreatePipelineLayout(&pllDesc);
descriptor.vertex = vertexState;
descriptor.fragment = &fragmentState;
descriptor.primitive.frontFace = wgpu::FrontFace::CW; // 表面とするときの頂点の並び順。
// デフォルトはCCW(反時計回り)
descriptor.primitive.cullMode = wgpu::CullMode::Back; // カリングする面(表裏)
descriptor.primitive.topology = wgpu::PrimitiveTopology::TriangleList;
descriptor.primitive.stripIndexFormat = wgpu::IndexFormat::Undefined;
descriptor.depthStencil = &depthStencilState;
pipeline = device.CreateRenderPipeline(&descriptor);
}
void initSwapChain() {
// HTMLページ内の、Canvas要素からSurfaceを作成
wgpu::SurfaceDescriptorFromCanvasHTMLSelector canvasDesc{};
canvasDesc.selector = "#canvas";
wgpu::SurfaceDescriptor surfDesc{};
surfDesc.nextInChain = &canvasDesc;
surface = instance.CreateSurface(&surfDesc);
// SwapChain作成
wgpu::SwapChainDescriptor scDesc{};
scDesc.usage = wgpu::TextureUsage::RenderAttachment;
scDesc.format = wgpu::TextureFormat::BGRA8Unorm;
scDesc.width = kWidth;
scDesc.height = kHeight;
scDesc.presentMode = wgpu::PresentMode::Fifo;
swapChain = device.CreateSwapChain(surface, &scDesc);
}
void initDepthStencil() {
// DepthStencil作成
wgpu::TextureDescriptor descriptor{};
descriptor.usage = wgpu::TextureUsage::RenderAttachment;
descriptor.size = {kWidth, kHeight, 1};
descriptor.format = wgpu::TextureFormat::Depth24PlusStencil8;
canvasDepthStencilView = device.CreateTexture(&descriptor).CreateView();
}
void frame() {
// バックバッファとDepthStencilのクリア
wgpu::TextureView backbuffer = swapChain.GetCurrentTextureView();
wgpu::RenderPassColorAttachment attachment{};
attachment.view = backbuffer;
attachment.loadOp = wgpu::LoadOp::Clear;
attachment.storeOp = wgpu::StoreOp::Store;
attachment.clearValue = {0, 0, 0, 1};
wgpu::RenderPassDescriptor renderpass{};
renderpass.colorAttachmentCount = 1;
renderpass.colorAttachments = &attachment;
wgpu::RenderPassDepthStencilAttachment depthStencilAttachment = {};
depthStencilAttachment.view = canvasDepthStencilView;
depthStencilAttachment.depthClearValue = 1.0f;
depthStencilAttachment.depthLoadOp = wgpu::LoadOp::Clear;
depthStencilAttachment.depthStoreOp = wgpu::StoreOp::Store;
depthStencilAttachment.stencilClearValue = 0;
depthStencilAttachment.stencilLoadOp = wgpu::LoadOp::Clear;
depthStencilAttachment.stencilStoreOp = wgpu::StoreOp::Store;
renderpass.depthStencilAttachment = &depthStencilAttachment;
wgpu::CommandBuffer commands;
{
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
{
wgpu::RenderPassEncoder pass = encoder.BeginRenderPass(&renderpass);
// uniform buffer更新&書き込み
static float speed = 0.015f;
ubObject.pos[0] += speed;
if (ubObject.pos[0] > (1.0f - 0.8f) || ubObject.pos[0] < -(1.0f - 0.8f))
{
speed = -speed;
}
queue.WriteBuffer(uniformBuffer, 0, &ubObject, sizeof(ubObject));
pass.SetPipeline(pipeline);
pass.SetBindGroup(0, bindGroup, 0, 0);
pass.SetVertexBuffer(0, vertexBuffer, 0, WGPU_WHOLE_SIZE);
pass.SetIndexBuffer(indexBuffer, wgpu::IndexFormat::Uint16, 0, WGPU_WHOLE_SIZE);
pass.DrawIndexed(3, 1, 0, 0, 0);
pass.End();
}
commands = encoder.Finish();
}
queue.Submit(1, &commands);
}
void run() {
device.SetUncapturedErrorCallback(
[](WGPUErrorType errorType, const char* message, void*) {
printf("%d: %s\n", errorType, message);
}, nullptr);
queue = device.GetQueue();
initRenderPipelineAndBuffers();
initSwapChain();
initDepthStencil();
// メインループ設定
emscripten_set_main_loop(frame, 0, false);
}
void getDevice(void (*callback)(wgpu::Device)) {
// instanceの作成
WGPUInstance wgpuInstance = wgpuCreateInstance(nullptr);
instance = wgpu::Instance::Acquire(wgpuInstance);
wgpuInstanceRequestAdapter(wgpuInstance, nullptr, [](WGPURequestAdapterStatus status, WGPUAdapter adapter, const char* message, void* userdata) {
if (message) {
printf("wgpuInstanceRequestAdapter: %s\n", message);
}
if (status == WGPURequestAdapterStatus_Unavailable) {
printf("WebGPU unavailable; exiting cleanly\n");
exit(0);
}
assert(status == WGPURequestAdapterStatus_Success);
wgpuAdapterRequestDevice(adapter, nullptr, [](WGPURequestDeviceStatus status, WGPUDevice dev, const char* message, void* userdata) {
if (message) {
printf("wgpuAdapterRequestDevice: %s\n", message);
}
assert(status == WGPURequestDeviceStatus_Success);
wgpu::Device device = wgpu::Device::Acquire(dev);
reinterpret_cast<void (*)(wgpu::Device)>(userdata)(device);
}, userdata);
}, reinterpret_cast<void*>(callback));
}
int main() {
// GetDeviceのあとに残りの処理を行いたいので、コールバックしてもらう必要がある
getDevice([](wgpu::Device dev) {
device = dev;
run();
});
return 0;
}