I've just noticed that I'm getting sound clicks on Window move/resize after completing Day 12 but going back to my code, I think I've had this problem since the end of Day 9. Is there a way to fix this? I'm on Windows 10 with the motherboard sound. Here is my code at the end of Day 9:
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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 | #include <windows.h> #include <stdint.h> #include <xinput.h> #include <dsound.h> // TODO(remy): Implement sine ourselves #include <math.h> #define internal static #define local_persist static #define global_variable static #define Pi32 3.141592653589793f typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; typedef int32 bool32; typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; typedef float real32; typedef double real64; struct win32_offscreen_buffer { // NOTE(remy): Pixels are always 32 bits wide, Little Endian BITMAPINFO Info; void *Memory; int Width; int Height; int Pitch; }; struct win32_window_dimension { int Width; int Height; }; // TODO(remy): This is a global for now global_variable bool32 GlobalRunning; global_variable win32_offscreen_buffer GlobalBackbuffer; global_variable LPDIRECTSOUNDBUFFER GlobalSecondaryBuffer; // NOTE(remy): XInputGetState #define X_INPUT_GET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_STATE *pState) typedef X_INPUT_GET_STATE(x_input_get_state); X_INPUT_GET_STATE(XInputGetStateStub) { return(ERROR_DEVICE_NOT_CONNECTED); } global_variable x_input_get_state *XInputGetState_ = XInputGetStateStub; #define XInputGetState XInputGetState_ // NOTE(remy): XInputSetState #define X_INPUT_SET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration) typedef X_INPUT_SET_STATE(x_input_set_state); X_INPUT_SET_STATE(XInputSetStateStub) { return(ERROR_DEVICE_NOT_CONNECTED); } global_variable x_input_set_state *XInputSetState_ = XInputSetStateStub; #define XInputSetState XInputSetState_ // NOTE(remy): DirectSoundCreate #define DIRECT_SOUND_CREATE(name) HRESULT WINAPI name(LPCGUID pcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter) typedef DIRECT_SOUND_CREATE(direct_sound_create); internal void Win32LoadXInput(void) { // TODO(remy): Test this on Windows 8 HMODULE XInputLibrary = LoadLibraryA("xinput1_4.dll"); if(!XInputLibrary) { // TODO(remy): Diagnostic XInputLibrary = LoadLibraryA("xinput9_1_0.dll"); } if(!XInputLibrary) { // TODO(remy): Diagnostic XInputLibrary = LoadLibraryA("xinput1_3.dll"); } if(XInputLibrary) { XInputGetState = (x_input_get_state *)GetProcAddress(XInputLibrary, "XInputGetState"); if(!XInputGetState) {XInputGetState = XInputGetStateStub;} XInputSetState = (x_input_set_state *)GetProcAddress(XInputLibrary, "XInputSetState"); if(!XInputSetState) {XInputSetState = XInputSetStateStub;} } else { // TODO(remy): Diagnostic } } internal void Win32InitDSound(HWND Window, int32 SamplesPerSecond, int32 BufferSize) { // NOTE(remy): Load the library HMODULE DSoundLibrary = LoadLibraryA("dsound.dll"); if (DSoundLibrary) { // NOTE(remy): Get a DirectSound object! - cooperative direct_sound_create *DirectSoundCreate = (direct_sound_create *) GetProcAddress(DSoundLibrary, "DirectSoundCreate"); // TODO(remy): Double-check that this works on XP LPDIRECTSOUND DirectSound; if(DirectSoundCreate && SUCCEEDED(DirectSoundCreate(0, &DirectSound, 0))) { WAVEFORMATEX WaveFormat = {}; WaveFormat.wFormatTag = WAVE_FORMAT_PCM; WaveFormat.nChannels = 2; WaveFormat.nSamplesPerSec = SamplesPerSecond; WaveFormat.wBitsPerSample = 16; WaveFormat.nBlockAlign = (WaveFormat.nChannels*WaveFormat.wBitsPerSample) / 8; WaveFormat.nAvgBytesPerSec = WaveFormat.nSamplesPerSec*WaveFormat.nBlockAlign; WaveFormat.cbSize = 0; if(SUCCEEDED(DirectSound->SetCooperativeLevel(Window, DSSCL_PRIORITY))) { DSBUFFERDESC BufferDescription = {}; BufferDescription.dwSize = sizeof(BufferDescription); BufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER; // TODO(remy): Check if we need DSBCAPS_GLOBALFOCUS? // NOTE(remy): "Create" a primary buffer LPDIRECTSOUNDBUFFER PrimaryBuffer; if(SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &PrimaryBuffer, 0))) { if(SUCCEEDED(PrimaryBuffer->SetFormat(&WaveFormat))) { // NOTE(remy): Now we have finally set the format! OutputDebugStringA("Primary Buffer format was set.\n"); } else { // TODO(remy): Diagnostic } } else { // TODO(remy): Diagnostic } } else { // TODO(remy): Diagnostic } DSBUFFERDESC BufferDescription = {}; BufferDescription.dwSize = sizeof(BufferDescription); // TODO(remy): Check if we need DSBCAPS_GLOBALFOCUS or DSBCAPS_GETCURRENTPOSITION2? BufferDescription.dwBufferBytes = BufferSize; BufferDescription.lpwfxFormat = &WaveFormat; // NOTE(remy): "Create" a secondary buffer if(SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &GlobalSecondaryBuffer, 0))) { OutputDebugStringA("Secondary Buffer created successfully.\n"); } else { // TODO(remy): Diagnostic } } else { // TODO(remy): Diagnostic } } } internal win32_window_dimension Win32GetWindowDimension(HWND Window) { win32_window_dimension Result; RECT ClientRect; GetClientRect(Window, &ClientRect); Result.Width = ClientRect.right - ClientRect.left; Result.Height = ClientRect.bottom - ClientRect.top; return(Result); } internal void RenderWeirdGradient(win32_offscreen_buffer *Buffer, int BlueOffset, int GreenOffset) { // TODO(remy): Let's see what the optimizer does for Buffer by value uint8 *Row = (uint8 *)Buffer->Memory; for(int Y = 0; Y < Buffer->Height; ++Y) { uint32 *Pixel = (uint32 *)Row; for(int X = 0; X < Buffer->Width; ++X) { /* 0 1 2 3 Pixel in memory: BB GG RR xx Little Endian Architecture 0x00RRGGBB */ uint8 Blue = (uint8)(X + BlueOffset); uint8 Green = (uint8)(Y + GreenOffset); *Pixel++ = ((Green << 8) | Blue); } Row += Buffer->Pitch; } } internal void Win32ResizeDIBSection(win32_offscreen_buffer *Buffer, int Width, int Height) { // TODO(remy): Bulletproof this. Maybe don't free first, free after, then free first if that fails. if(Buffer->Memory) { VirtualFree(Buffer->Memory, 0, MEM_RELEASE); } Buffer->Width = Width; Buffer->Height = Height; int BytesPerPixel = 4; Buffer->Info.bmiHeader.biSize = sizeof(Buffer->Info.bmiHeader); Buffer->Info.bmiHeader.biWidth = Buffer->Width; Buffer->Info.bmiHeader.biHeight = -Buffer->Height; Buffer->Info.bmiHeader.biPlanes = 1; Buffer->Info.bmiHeader.biBitCount = 32; Buffer->Info.bmiHeader.biCompression = BI_RGB; // NOTE(remy): Thank you to Chris Hecker of Spy Party fame for clarifying the deal // with StrechDIBits and BitBlt! No more DC for us. int BitmapMemorySize = (Buffer->Width*Buffer->Height)*BytesPerPixel; Buffer->Memory = VirtualAlloc(0, BitmapMemorySize, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); Buffer->Pitch = Width*BytesPerPixel; // TODO(remy): Probably want to clear this to black } internal void Win32DisplayBufferInWindow(win32_offscreen_buffer *Buffer, HDC DeviceContext, int WindowWidth, int WindowHeight) { // TODO(remy): Aspect ratio correction // TODO(remy): We can play with stretch modes StretchDIBits(DeviceContext, /* X, Y, Width, Height, X, Y, Width, Height, */ 0, 0, WindowWidth, WindowHeight, 0, 0, Buffer->Width, Buffer->Height, Buffer->Memory, &Buffer->Info, DIB_RGB_COLORS, SRCCOPY); } internal LRESULT CALLBACK Win32MainWindowCallback(HWND Window, UINT Message, WPARAM WParam, LPARAM LParam) { LRESULT Result = 0; switch(Message) { case WM_SIZE: { } break; case WM_CLOSE: { // TODO(remy): Handle this with a message to the user? GlobalRunning = false; } break; case WM_ACTIVATEAPP: { OutputDebugStringA("WM_ACTIVATEAPP\n"); } break; case WM_DESTROY: { // TODO(remy): Handle this as an error - recreate window? GlobalRunning = false; } break; case WM_SYSKEYDOWN: case WM_SYSKEYUP: case WM_KEYDOWN: case WM_KEYUP: { uint32 VKCode = WParam; bool32 WasDown = ((LParam & (1 << 30)) != 0); bool32 IsDown = ((LParam & (1 << 31)) == 0); if(WasDown != IsDown) { if(VKCode == 'W') { } else if(VKCode == 'A') { } else if(VKCode == 'S') { } else if(VKCode == 'D') { } else if(VKCode == 'Q') { } else if(VKCode == 'E') { } else if(VKCode == VK_UP) { } else if(VKCode == VK_LEFT) { } else if(VKCode == VK_DOWN) { } else if(VKCode == VK_RIGHT) { } else if(VKCode == VK_ESCAPE) { OutputDebugStringA("Escape : "); if(IsDown) { OutputDebugStringA("IsDown "); } if(WasDown) { OutputDebugStringA("WasDown"); } OutputDebugStringA("\n"); } else if(VKCode == VK_SPACE) { } } bool32 AltKeyWasDown = (LParam & (1 << 29)); if((VKCode == VK_F4) && AltKeyWasDown) { GlobalRunning = false; } } break; case WM_PAINT: { PAINTSTRUCT Paint; HDC DeviceContext = BeginPaint(Window, &Paint); win32_window_dimension Dimension = Win32GetWindowDimension(Window); Win32DisplayBufferInWindow(&GlobalBackbuffer, DeviceContext, Dimension.Width, Dimension.Height); EndPaint(Window, &Paint); } break; default: { Result = DefWindowProcA(Window, Message, WParam, LParam); } break; } return(Result); } struct win32_sound_output { int SamplesPerSeconds; int ToneHz; int ToneVolume; uint32 RunningSampleIndex; int WavePeriod; int BytesPerSample; int SecondaryBufferSize; real32 tSine; int LatencySampleCount; }; internal void Win32FillSoundBuffer(win32_sound_output *SoundOutput, DWORD ByteToLock, DWORD BytesToWrite) { // TODO(remy): More strenuous test! VOID *Region1; DWORD Region1Size; VOID *Region2; DWORD Region2Size; if(SUCCEEDED(GlobalSecondaryBuffer->Lock(ByteToLock, BytesToWrite, &Region1, &Region1Size, &Region2, &Region2Size, 0))) { // TODO(remy): assert that Region1Size/Region2Size is valid // TODO(remy): Collapse these two loops DWORD Region1SampleCount = Region1Size/SoundOutput->BytesPerSample; int16 *SampleOut = (int16 *)Region1; for(DWORD SampleIndex = 0; SampleIndex < Region1SampleCount; ++SampleIndex) { // TODO(remy): Draw this out for people real32 SineValue = sinf(SoundOutput->tSine); int16 SampleValue = (int16)(SineValue * SoundOutput->ToneVolume); *SampleOut++ = SampleValue; *SampleOut++ = SampleValue; SoundOutput->tSine += 2.0f*Pi32*1.0f / (real32)SoundOutput->WavePeriod; ++SoundOutput->RunningSampleIndex; } DWORD Region2SampleCount = Region2Size/SoundOutput->BytesPerSample; SampleOut = (int16 *)Region2; for(DWORD SampleIndex = 0; SampleIndex < Region2SampleCount; ++SampleIndex) { real32 SineValue = sinf(SoundOutput->tSine); int16 SampleValue = (int16)(SineValue * SoundOutput->ToneVolume); *SampleOut++ = SampleValue; *SampleOut++ = SampleValue; SoundOutput->tSine += 2.0f*Pi32*1.0f / (real32)SoundOutput->WavePeriod; ++SoundOutput->RunningSampleIndex; } GlobalSecondaryBuffer->Unlock(Region1, Region1Size, Region2, Region2Size); } } int CALLBACK WinMain(HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCode) { Win32LoadXInput(); WNDCLASSA WindowClass = {}; Win32ResizeDIBSection(&GlobalBackbuffer, 1280, 720); WindowClass.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC; WindowClass.lpfnWndProc = Win32MainWindowCallback; WindowClass.hInstance = Instance; // TODO(remy): Add game icon // WindowClass.hIcon; WindowClass.lpszClassName = "HandmadeHeroWindowClass"; if(RegisterClassA(&WindowClass)) { HWND Window = CreateWindowExA( 0, WindowClass.lpszClassName, "Handmade Hero", WS_OVERLAPPEDWINDOW|WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, Instance, 0); if(Window) { // NOTE(remy): Since we are using CS_OWNDC, we can just get one device context // and use it foreever. HDC DeviceContext = GetDC(Window); // NOTE(remy): Graphics test int XOffset = 0; int YOffset = 0; win32_sound_output SoundOutput = {}; // TODO(remy): Make this like sixty seconds? SoundOutput.SamplesPerSeconds = 48000; SoundOutput.ToneHz = 256; SoundOutput.ToneVolume = 2000; SoundOutput.WavePeriod = SoundOutput.SamplesPerSeconds/SoundOutput.ToneHz; SoundOutput.BytesPerSample = sizeof(int16)*2; SoundOutput.SecondaryBufferSize = SoundOutput.SamplesPerSeconds*SoundOutput.BytesPerSample; SoundOutput.LatencySampleCount = SoundOutput.SamplesPerSeconds / 15; Win32InitDSound(Window, SoundOutput.SamplesPerSeconds, SoundOutput.SecondaryBufferSize); Win32FillSoundBuffer(&SoundOutput, 0, SoundOutput.LatencySampleCount*SoundOutput.BytesPerSample); GlobalSecondaryBuffer->Play(0, 0, DSBPLAY_LOOPING); GlobalRunning = true; while(GlobalRunning) { MSG Message; while(PeekMessageA(&Message, 0, 0, 0, PM_REMOVE)) { if(Message.message == WM_QUIT) { GlobalRunning = false; } TranslateMessage(&Message); DispatchMessage(&Message); } // TODO(casey): Should we poll this more frequently? for (DWORD ControllerIndex = 0; ControllerIndex < XUSER_MAX_COUNT; ControllerIndex++) { XINPUT_STATE ControllerState; if(XInputGetState(ControllerIndex, &ControllerState) == ERROR_SUCCESS) { // NOTE(remy): This controller is plugged in // TODO(remy): See if ControllerState.dwPacketNumber increment too rapidly XINPUT_GAMEPAD *Pad = &ControllerState.Gamepad; bool32 Up = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_UP); bool32 Down = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_DOWN); bool32 Left = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_LEFT); bool32 Right = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT); bool32 Start = (Pad->wButtons & XINPUT_GAMEPAD_START); bool32 Back = (Pad->wButtons & XINPUT_GAMEPAD_BACK); bool32 LeftShoulder = (Pad->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER); bool32 RightShoulder = (Pad->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER); bool32 AButton = (Pad->wButtons & XINPUT_GAMEPAD_A); bool32 BButton = (Pad->wButtons & XINPUT_GAMEPAD_B); bool32 XButton = (Pad->wButtons & XINPUT_GAMEPAD_X); bool32 YButton = (Pad->wButtons & XINPUT_GAMEPAD_Y); int16 StickX = Pad->sThumbLX; int16 StickY = Pad->sThumbLY; // NOTE(remy): Animate with gamepad control // TODO(remy): We will do dead zone handling properly using XINPUT consts XOffset += StickX / 4096; YOffset += StickY / 4096; SoundOutput.ToneHz = 512 + (int)(256.0f*((real32)StickY / 30000.0f)); SoundOutput.WavePeriod = SoundOutput.SamplesPerSeconds/SoundOutput.ToneHz; } else { // NOTE(remy): This controller is not available } } RenderWeirdGradient(&GlobalBackbuffer, XOffset, YOffset); // NOTE(remy): DirectSound output test DWORD PlayCursor; DWORD WriteCursor; if(SUCCEEDED(GlobalSecondaryBuffer->GetCurrentPosition(&PlayCursor, &WriteCursor))) { DWORD ByteToLock = ((SoundOutput.RunningSampleIndex*SoundOutput.BytesPerSample) % SoundOutput.SecondaryBufferSize); DWORD TargetCursor = ((PlayCursor + (SoundOutput.LatencySampleCount*SoundOutput.BytesPerSample)) % SoundOutput.SecondaryBufferSize); DWORD BytesToWrite; if(ByteToLock > TargetCursor) { BytesToWrite = SoundOutput.SecondaryBufferSize - ByteToLock; BytesToWrite += TargetCursor; } else { BytesToWrite = TargetCursor - ByteToLock; } Win32FillSoundBuffer(&SoundOutput, ByteToLock, BytesToWrite); } win32_window_dimension Dimension = Win32GetWindowDimension(Window); Win32DisplayBufferInWindow(&GlobalBackbuffer, DeviceContext, Dimension.Width, Dimension.Height); // NOTE(remy): Animate without gamepad /*XOffset++; YOffset++;*/ } } else { // TODO(remy): Logging } } else { // TODO(remy): Logging } return(0); } |