-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparticles.cpp
More file actions
516 lines (428 loc) · 16.1 KB
/
particles.cpp
File metadata and controls
516 lines (428 loc) · 16.1 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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#define NOMINMAX
#include <windows.h>
#include <d3d11.h>
#include <DirectXMath.h>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <ctime>
#pragma comment(lib, "d3d11.lib")
#include <d3dcompiler.h>
#pragma comment(lib, "D3dcompiler.lib")
#include <algorithm>
#include <wrl/client.h>
using namespace DirectX;
using Microsoft::WRL::ComPtr;
// DirectX Objects
ID3D11Device* g_pd3dDevice = nullptr;
ID3D11DeviceContext* g_pImmediateContext = nullptr;
IDXGISwapChain* g_pSwapChain = nullptr;
ID3D11RenderTargetView* g_mainRenderTargetView = nullptr;
ID3D11InputLayout* g_pInputLayout = nullptr;
ID3D11VertexShader* g_pVertexShader = nullptr;
ID3D11PixelShader* g_pPixelShader = nullptr;
ID3D11Buffer* g_pVertexBuffer = nullptr;
ID3D11Buffer* g_pMatrixBuffer = nullptr;
// Window Size
const int g_width = 1920;
const int g_height = 1080;
// Particle Struct
struct Particle3D
{
XMFLOAT3 pos;
XMFLOAT3 vel;
};
// Particle Settings
std::vector<Particle3D> particles;
const int numParticles = 400;
const float maxDepth = 100.0f;
const float particleSpeed = 40.0f;
const float particleLineDist = 40.0f;
const int maxLines = 3;
// Virtex for Lines
struct Vertex
{
XMFLOAT3 pos;
XMFLOAT4 color;
};
// Boundary Box Virtex Buffer
ID3D11Buffer* g_pBoundaryVB = nullptr;
// Camera Objects
XMMATRIX g_view;
XMMATRIX g_proj;
float g_rotationAngle = 0.0f; // horizontal rotation (around Y)
float g_pitchAngle = 0.0f; // vertical rotation (tilt up/down)
float g_camDistance = 600.0f; // distance from cube center
static float g_radius = 600.0f;
const float g_minRadius = 100.0f;
const float g_maxRadius = 1500.0f;
// Shaders
const char* g_VSCode = R"(
cbuffer MatrixBuffer : register(b0)
{
matrix world;
matrix view;
matrix projection;
};
struct VS_INPUT
{
float3 pos : POSITION;
float4 color : COLOR;
};
struct PS_INPUT
{
float4 pos : SV_POSITION;
float4 color : COLOR;
};
PS_INPUT VS(VS_INPUT input)
{
PS_INPUT output;
float4 worldPos = mul(float4(input.pos,1), world);
float4 viewPos = mul(worldPos, view);
output.pos = mul(viewPos, projection);
output.color = input.color;
return output;
}
)";
const char* g_PSCode = R"(
struct PS_INPUT
{
float4 pos : SV_POSITION;
float4 color : COLOR;
};
float4 PS(PS_INPUT input) : SV_TARGET
{
return input.color;
}
)";
// Compile Shader Helpers
HRESULT CompileShaderFromMemory(const char* src, const char* entry, const char* target, ID3DBlob** blob)
{
return D3DCompile(src, strlen(src), nullptr, nullptr, nullptr, entry, target, 0, 0, blob, nullptr);
}
// Initialize DX
bool InitD3D(HWND hWnd)
{
DXGI_SWAP_CHAIN_DESC sd = {};
sd.BufferCount = 1;
sd.BufferDesc.Width = g_width;
sd.BufferDesc.Height = g_height;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.Windowed = TRUE;
HRESULT hrCreate = D3D11CreateDeviceAndSwapChain(
nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0,
nullptr, 0, D3D11_SDK_VERSION, &sd,
&g_pSwapChain, &g_pd3dDevice, nullptr, &g_pImmediateContext
);
if (FAILED(hrCreate)) return false;
// Initialize and get the back buffer
ComPtr<ID3D11Texture2D> pBackBuffer; // Using ComPtr gets rid of Buffer Could be 0 warning.
HRESULT BackBufferResult = g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
if (FAILED(BackBufferResult))
return false;
BackBufferResult = g_pd3dDevice->CreateRenderTargetView(
pBackBuffer.Get(),
nullptr,
&g_mainRenderTargetView
);
if (FAILED(BackBufferResult))
return false;
// This way works, its from a lot of guides but produces a pBackBuffer could be 0 warning
//g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
//g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &g_mainRenderTargetView);
pBackBuffer->Release();
g_pImmediateContext->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr);
D3D11_VIEWPORT vp = {};
vp.Width = g_width;
vp.Height = g_height;
vp.MaxDepth = 1.0f;
g_pImmediateContext->RSSetViewports(1, &vp);
// Compile shaders
ID3DBlob* vsBlob = nullptr;
ID3DBlob* psBlob = nullptr;
ID3DBlob* errorBlob = nullptr;
HRESULT hr = D3DCompile(g_VSCode, strlen(g_VSCode), nullptr, nullptr, nullptr, "VS", "vs_5_0", 0, 0, &vsBlob, &errorBlob);
if (FAILED(hr))
{
if (errorBlob) OutputDebugStringA((char*)errorBlob->GetBufferPointer());
if (errorBlob) errorBlob->Release();
return false;
}
hr = D3DCompile(g_PSCode, strlen(g_PSCode), nullptr, nullptr, nullptr, "PS", "ps_5_0", 0, 0, &psBlob, &errorBlob);
if (FAILED(hr))
{
if (errorBlob) OutputDebugStringA((char*)errorBlob->GetBufferPointer());
if (errorBlob) errorBlob->Release();
return false;
}
hr = g_pd3dDevice->CreateVertexShader(vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), nullptr, &g_pVertexShader);
if (FAILED(hr)) return false;
hr = g_pd3dDevice->CreatePixelShader(psBlob->GetBufferPointer(), psBlob->GetBufferSize(), nullptr, &g_pPixelShader);
if (FAILED(hr)) return false;
// Input layout
D3D11_INPUT_ELEMENT_DESC layoutDesc[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}
};
g_pd3dDevice->CreateInputLayout(layoutDesc, 2, vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), &g_pInputLayout);
vsBlob->Release();
psBlob->Release();
// Matrix buffer
D3D11_BUFFER_DESC cbd = {};
cbd.ByteWidth = sizeof(XMMATRIX) * 3;
cbd.Usage = D3D11_USAGE_DYNAMIC;
cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
g_pd3dDevice->CreateBuffer(&cbd, nullptr, &g_pMatrixBuffer);
// Projection
g_proj = XMMatrixPerspectiveFovLH(XM_PIDIV4, g_width / (float)g_height, 1.0f, 1000.0f);
return true;
}
// Initialize particles
void InitParticles()
{
particles.resize(numParticles);
for (auto& p : particles)
{
float cubeSize = 200.0f; // Cube Bounds Box
p.pos = XMFLOAT3(
((float)rand() / RAND_MAX - 0.5f) * cubeSize,
((float)rand() / RAND_MAX - 0.5f) * cubeSize,
((float)rand() / RAND_MAX - 0.5f) * cubeSize
);
p.vel = XMFLOAT3(
((float)rand() / RAND_MAX - 0.5f) * particleSpeed,
((float)rand() / RAND_MAX - 0.5f) * particleSpeed,
((float)rand() / RAND_MAX - 0.5f) * particleSpeed
);
}
}
// Update particles
void UpdateParticles(float dt)
{
float halfSize = 150.0f; // Particle bounding Size
for (auto& p : particles)
{
p.pos.x += p.vel.x * dt;
p.pos.y += p.vel.y * dt;
p.pos.z += p.vel.z * dt;
// Reflect/bounce off walls
if (p.pos.x < -halfSize || p.pos.x > halfSize) p.vel.x *= -1;
if (p.pos.y < -halfSize || p.pos.y > halfSize) p.vel.y *= -1;
if (p.pos.z < -halfSize || p.pos.z > halfSize) p.vel.z *= -1;
// Clamp in case velocity overshoots
p.pos.x = std::max(-halfSize, std::min(p.pos.x, halfSize));
p.pos.y = std::max(-halfSize, std::min(p.pos.y, halfSize));
p.pos.z = std::max(-halfSize, std::min(p.pos.z, halfSize));
}
}
void DrawBoundaryBox(
ID3D11Device* device,
ID3D11DeviceContext* context,
float halfSize,
ID3D11Buffer*& lineVB
)
{
XMFLOAT4 color = XMFLOAT4(1, 1, 1, 1);
Vertex verts[] =
{
// Bottom square
{{-halfSize,-halfSize,-halfSize}, color}, {{ halfSize,-halfSize,-halfSize}, color},
{{ halfSize,-halfSize,-halfSize}, color}, {{ halfSize,-halfSize, halfSize}, color},
{{ halfSize,-halfSize, halfSize}, color}, {{-halfSize,-halfSize, halfSize}, color},
{{-halfSize,-halfSize, halfSize}, color}, {{-halfSize,-halfSize,-halfSize}, color},
// Top square
{{-halfSize, halfSize,-halfSize}, color}, {{ halfSize, halfSize,-halfSize}, color},
{{ halfSize, halfSize,-halfSize}, color}, {{ halfSize, halfSize, halfSize}, color},
{{ halfSize, halfSize, halfSize}, color}, {{-halfSize, halfSize, halfSize}, color},
{{-halfSize, halfSize, halfSize}, color}, {{-halfSize, halfSize,-halfSize}, color},
// Vertical edges
{{-halfSize,-halfSize,-halfSize}, color}, {{-halfSize, halfSize,-halfSize}, color},
{{ halfSize,-halfSize,-halfSize}, color}, {{ halfSize, halfSize,-halfSize}, color},
{{ halfSize,-halfSize, halfSize}, color}, {{ halfSize, halfSize, halfSize}, color},
{{-halfSize,-halfSize, halfSize}, color}, {{-halfSize, halfSize, halfSize}, color},
};
if (!lineVB)
{
D3D11_BUFFER_DESC bd = {};
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(verts);
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
device->CreateBuffer(&bd, nullptr, &lineVB);
}
D3D11_MAPPED_SUBRESOURCE mapped;
context->Map(lineVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
memcpy(mapped.pData, verts, sizeof(verts));
context->Unmap(lineVB, 0);
UINT stride = sizeof(Vertex);
UINT offset = 0;
context->IASetVertexBuffers(0, 1, &lineVB, &stride, &offset);
context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
context->Draw(24, 0); //Lines * Verts
}
// Create line vertices
void BuildLineVertices(std::vector<Vertex>& verts)
{
verts.clear();
for (size_t i = 0; i < particles.size(); ++i)
{
for (size_t j = i + 1; j < particles.size(); ++j)
{
XMFLOAT3& a = particles[i].pos;
XMFLOAT3& b = particles[j].pos;
float dx = b.x - a.x;
float dy = b.y - a.y;
float dz = b.z - a.z;
float dist = sqrtf(dx * dx + dy * dy + dz * dz);
if (dist < particleLineDist)
{
float alpha = 1.0f - dist / particleLineDist;
XMFLOAT4 color(1, 1, 1, alpha);
verts.push_back({ a,color });
verts.push_back({ b,color });
}
}
}
}
// Win32 WndProc
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_MOUSEWHEEL:
{
short delta = GET_WHEEL_DELTA_WPARAM(wParam);
g_radius -= delta * 0.25f; // Sensitivity
if (g_radius < g_minRadius) g_radius = g_minRadius;
if (g_radius > g_maxRadius) g_radius = g_maxRadius;
}
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
// Main
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
srand((unsigned int)time(0));
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0,0,
hInstance,nullptr,nullptr,nullptr,nullptr,
L"DXParticles", nullptr };
RegisterClassEx(&wc);
HWND hWnd = CreateWindow(L"DXParticles", L"3D Particle Network",
WS_POPUP, 0, 0, g_width, g_height, nullptr, nullptr, hInstance, nullptr);
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
if (!InitD3D(hWnd)) return 1;
InitParticles();
// Vertex buffer
D3D11_BUFFER_DESC vbd = {};
vbd.Usage = D3D11_USAGE_DYNAMIC;
vbd.ByteWidth = sizeof(Vertex) * numParticles * numParticles * maxLines;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
g_pd3dDevice->CreateBuffer(&vbd, nullptr, &g_pVertexBuffer);
MSG msg = {};
ULONGLONG lastTime = GetTickCount64();
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
ULONGLONG now = GetTickCount64();
float dt = (now - lastTime) / 1000.0f;
lastTime = now;
// Update particles
UpdateParticles(dt);
// Build line vertices
std::vector<Vertex> verts;
BuildLineVertices(verts);
// Update vertex buffer
D3D11_MAPPED_SUBRESOURCE ms;
g_pImmediateContext->Map(g_pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &ms);
memcpy(ms.pData, verts.data(), verts.size() * sizeof(Vertex));
g_pImmediateContext->Unmap(g_pVertexBuffer, 0);
// Clear
float clearColor[4] = { 0,0,0,1 };
g_pImmediateContext->ClearRenderTargetView(g_mainRenderTargetView, clearColor);
// Set pipeline
UINT stride = sizeof(Vertex);
UINT offset = 0;
g_pImmediateContext->IASetInputLayout(g_pInputLayout);
g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &offset);
g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
g_pImmediateContext->VSSetShader(g_pVertexShader, nullptr, 0);
g_pImmediateContext->PSSetShader(g_pPixelShader, nullptr, 0);
// Update matrices
XMMATRIX world = XMMatrixIdentity();
// Convert angles + dist to Cartesian
float camX = sinf(g_rotationAngle) * cosf(g_pitchAngle) * g_radius;
float camY = sinf(g_pitchAngle) * g_radius;
float camZ = cosf(g_rotationAngle) * cosf(g_pitchAngle) * g_radius;
XMVECTOR eye = XMVectorSet(camX, camY, camZ, 0.0f);
XMVECTOR focus = XMVectorZero(); // look at cube center
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMMATRIX view = XMMatrixLookAtLH(eye, focus, up);
// Mouse input for rotation
static POINT lastMouse = {};
POINT currMouse;
GetCursorPos(&currMouse);
if (GetAsyncKeyState(VK_RBUTTON) & 0x8000)
{
float dx = (currMouse.x - lastMouse.x) * 0.005f; // sensitivity
float dy = (currMouse.y - lastMouse.y) * 0.005f;
g_rotationAngle += dx;
g_pitchAngle += dy;
// Clamp pitch
const float pitchLimit = XM_PIDIV2 - 0.01f;
if (g_pitchAngle > pitchLimit) g_pitchAngle = pitchLimit;
if (g_pitchAngle < -pitchLimit) g_pitchAngle = -pitchLimit;
}
lastMouse = currMouse;
D3D11_MAPPED_SUBRESOURCE ms2;
g_pImmediateContext->Map(g_pMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &ms2);
XMMATRIX* m = (XMMATRIX*)ms2.pData;
m[0] = XMMatrixTranspose(world);
m[1] = XMMatrixTranspose(view);
m[2] = XMMatrixTranspose(g_proj);
g_pImmediateContext->Unmap(g_pMatrixBuffer, 0);
g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pMatrixBuffer);
// Draw lines
g_pImmediateContext->Draw(verts.size(), 0);
std::vector<Vertex> pointVerts;
pointVerts.reserve(numParticles);
for (const auto& p : particles)
{
// Depth-based brightness
float depthNorm = (p.pos.z - 50.0f) / 150.0f;
float brightness = 1.0f - depthNorm * 0.6f;
brightness = std::max(brightness, 0.4f);
pointVerts.push_back({ p.pos, XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f) });
}
// Update the same vertex buffer with point data
g_pImmediateContext->Map(g_pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &ms);
memcpy(ms.pData, pointVerts.data(), pointVerts.size() * sizeof(Vertex));
g_pImmediateContext->Unmap(g_pVertexBuffer, 0);
// Switch to drawing points
g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
// Draw the particles
g_pImmediateContext->Draw(numParticles, 0);
// Draw boundary box
DrawBoundaryBox(g_pd3dDevice, g_pImmediateContext, 150.0f, g_pBoundaryVB);
// Present
g_pSwapChain->Present(1, 0);
}
}
return 0;
}