Handmade Hero»Forums»Code
Dana Fortier
25 posts
Playing Square in DirectSound,SOLVED
Edited by Dana Fortier on Reason: figured it out
I am currently into Day 9, but I wanted to pause and check with you guys about the fact that I'm getting a buzzing sound ONLY on the left channel(I tested this through my highend audio interface and the computer's built in sound card which I set to 44.1 48khz as well as 24bit 96khz, same sound for all cases). However it does seem to respect the amplitude of the square wave (VolumeAmount).

I don't know if it matters but I tested it using VS's compiler as well as the cl compiler with the same results in debug each time.

These are the relevant bits of code, please let me know if you need anymore info to help. Thanks!


  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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
#include <windows.h>
#include <stdint.h> 
#include <xinput.h>
#include <winuser.h>
#include <dsound.h>



#define internal static
#define local_persist static
#define global_variable static



typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;

typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;

typedef int32 bool32;

// *TODO: This is all global...for now...
global_variable bool GlobalRunning;
global_variable LPDIRECTSOUNDBUFFER GlobalSecondarySoundBuffer;


struct win32_window_dimension
{
	int Width;
	int Height;
};

struct win32_offscreen_buffer 
{
	//NOTE: Always assumes bytesperpixel is 4 (32 bit), memory order: BB GG RR XX -> in mem: 0x xx RR GG BB
	BITMAPINFO Info;
	void *Memory;
	int Width, Height;
	//int BytesPerPixel;
	int Pitch;
};
global_variable win32_offscreen_buffer GlobalBackBuffer;
// We've created a macro stub function and turned it into a type
// we then create a global var pointing to the type of the function stub
// we then redefine the function stub pointer so it assumes the name 
// of the function we want to steal out of the original lib we don't want to load

// XInputGetState
//create the macro using define, so name will now assume the function signature

#define X_INPUT_GET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_STATE *pState)
typedef X_INPUT_GET_STATE(x_input_get_state); // this is actually a macro'd stub function named: x_input_get_state(DWORD dwUserIndex, XINPUT_STATE *pState);

// this is the stub function's definition
X_INPUT_GET_STATE(XInputGetStateStub)
{
	return(ERROR_DEVICE_NOT_CONNECTED);
}

// this is a global pointer pointing to: x_input_get_state(DWORD dwUserIndex, XINPUT_STATE *pState); now we use XInputGetState as the stub function
global_variable x_input_get_state *XInputGetState_ = XInputGetStateStub;
#define XInputGetState XInputGetState_

// XInputeSetSTATE
#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_


#define DIRECT_SOUND_CREATE(name) HRESULT WINAPI name( LPCGUID pcGuidDevice,  LPDIRECTSOUND *ppDS,  LPUNKNOWN pUnkOuter)
typedef DIRECT_SOUND_CREATE(direct_sound_create);

//DIRECT_SOUND_CREATE(DirectSoundCreate)
//{
//	return(DSERR_NODRIVER);
//}



internal void Win32LoadXInput(void)
{
	//we're going to do the steps the window loader does when it loads our program
	HMODULE XInputLibrary = LoadLibrary("xinput1_4");
	if (!XInputLibrary)
	{
		// *TODO : Create diagnostics
		HMODULE XInputLibrary = LoadLibrary("xinput1_3");
	}

	
	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; }
		// *TODO : Create diagnostics

	}
	else
	{
		// *TODO : Create diagnostics
		OutputDebugString("Module load failed!");
	}
}


internal win32_window_dimension Win32GetWindowDimension(HWND Window)
{
	win32_window_dimension Result;
	RECT ClientRect;
	GetClientRect(Window, &ClientRect);
	Result.Height = ClientRect.bottom - ClientRect.top;
	Result.Width = ClientRect.right - ClientRect.left;

	return(Result);
}


internal void Win32DisplayBufferInWindow(win32_offscreen_buffer *Buffer, HDC BitmapDeviceContext, int WindowWidth, int WindowHeight)
{
	//*TODO: aspect ratio maintain
	//*TODO: Stretch modes
	
	StretchDIBits(
		BitmapDeviceContext, 0, 0, // this is the start of the destination fill upper left corner (0,0)
		WindowWidth, WindowHeight, // size of destination buffer
		0, 0, // start of buffer upper left
		Buffer->Width, Buffer->Height, // buffer width, buffer height
		Buffer->Memory, // memory contents pointer to image in buffer
		&Buffer->Info,  // info about image
		DIB_RGB_COLORS, // what colour 'space'
		SRCCOPY); //rasterizing operation
}


internal void Win32ResizeDIBSection(win32_offscreen_buffer *Buffer, int Width, int Height)
{
	//*TODO: Bulletproof this
	// may don't free first, free after, but if that fails free first

	if (Buffer->Memory)
	{
		VirtualFree(Buffer->Memory, 0, MEM_RELEASE);
	}
		
	Buffer->Height = Height;
	Buffer->Width = Width;
	//BITMAPINFO info = Buffer.Info;
	int BytesPerPixel = 4;
	Buffer->Info.bmiHeader.biSize = sizeof(Buffer->Info.bmiHeader);
	Buffer->Info.bmiHeader.biWidth = Buffer->Width;/*Width; */
	Buffer->Info.bmiHeader.biHeight = -Buffer->Height /*Height;*/;  //the negative makes it a top-down DIB so it draws from top-left
	Buffer->Info.bmiHeader.biPlanes = 1;
	Buffer->Info.bmiHeader.biBitCount = 32;
	Buffer->Info.bmiHeader.biCompression = BI_RGB;
	Buffer->Info.bmiHeader.biSizeImage = 0;
	Buffer->Info.bmiHeader.biXPelsPerMeter = 0;
	Buffer->Info.bmiHeader.biYPelsPerMeter = 0;
	Buffer->Info.bmiHeader.biClrUsed = 0;
	Buffer->Info.bmiHeader.biClrImportant = 0;
	
	

	//int BitmapMemorySize = (Width * Height) * BytesPerPixel;
	int BitmapMemorySize = (Buffer->Width * Buffer->Height) * BytesPerPixel;
	Buffer->Memory = VirtualAlloc(0, BitmapMemorySize, MEM_RESERVE| MEM_COMMIT, PAGE_READWRITE);

	//*TODO: probably want to initialize to black
	Buffer->Pitch = Width*BytesPerPixel;
}

// define the windows callback messaging responses
LRESULT CALLBACK Win32MainWindowCallback( HWND Window,UINT Message,WPARAM WParam,LPARAM LParam)	
{

	LRESULT Result = 0;
	//win32_offscreen_buffer Buffer;
	
	switch(Message)
	{
	case WM_KEYDOWN:
	
	case WM_KEYUP:

	case WM_SYSKEYDOWN:

	case WM_SYSKEYUP:
	{
		uint32 VKCode = WParam;
		#define KeyWasDownMessageBit (1<<30)
		#define KeyIsDownMessageBit (1<<31)
		#define AltKeyIsDownMessageBit (1<<29)

		bool32 wasKeyDown = ((LParam & KeyWasDownMessageBit) != 0); //use expression since results will be 0 or bit 30, not 1;
		bool32 isKeyDownNow = ((LParam & KeyIsDownMessageBit) == 0);
		
  		if (wasKeyDown != isKeyDownNow)
		{

			if (VKCode == 'W')
			{

			}
			else if (VKCode == 'S')
			{

			}
			else if (VKCode == 'A')
			{

			}
			else if (VKCode == 'D')
			{

			}

			else if (VKCode == 'Q')
			{

			}
			else if (VKCode == 'E')
			{

			}

			else if (VKCode == VK_UP)
			{

			}
			else if (VKCode == VK_DOWN)
			{

			}
			else if (VKCode == VK_LEFT)
			{
				OutputDebugString("LEFT :");
				if (isKeyDownNow)
				{
					OutputDebugString(" IS down!\n");
				}
				if (wasKeyDown)
				{
					OutputDebugString(" WAS down!\n");
				}
			}
			else if (VKCode == VK_RIGHT)
			{

			}
			else if (VKCode == VK_ESCAPE)
			{
				GlobalRunning = false;
			}
			else if (VKCode == VK_SPACE && isKeyDownNow)
			{
				OutputDebugString("Space is down\n");
			}
			else if (VKCode == VK_SPACE && wasKeyDown)
			{
				OutputDebugString("Space is up\n");
			}

		}
		
		bool32 AltKeyWasDown = (LParam & AltKeyIsDownMessageBit);
	

		if ((VKCode == VK_F4) && AltKeyWasDown)
		{
			GlobalRunning = false;
		}
	}break;

		case WM_SETFOCUS:
		{
			
			
		}break;

		case WM_KILLFOCUS:
		{


		}break;

		case WM_PAINT:
		{
			PAINTSTRUCT Paint;
			HDC BitmapDeviceContext = BeginPaint(Window, &Paint);
		
			win32_window_dimension Dimension = Win32GetWindowDimension(Window);
			int X = Paint.rcPaint.left;
			int Y = Paint.rcPaint.top;
			int Height = Paint.rcPaint.bottom - Paint.rcPaint.top;
			int Width = Paint.rcPaint.right - Paint.rcPaint.left;
			Win32DisplayBufferInWindow(&GlobalBackBuffer, BitmapDeviceContext, Dimension.Width, Dimension.Height);
		
			EndPaint(Window, &Paint);
			OutputDebugStringA("WM_SIZE\n");
		}break;

		case WM_DESTROY:
		{
			//*TODO: Handle this as an error - recreate window?
			GlobalRunning = false;
			OutputDebugStringA("PostQuitMessage(0) - WM_DESTROY\n");
		}break;

		case WM_CLOSE:
		{
			//*TODO: Handle this with a message to the user?
			GlobalRunning = false;
			OutputDebugStringA("WM_CLOSE\n");
		}break;

		case WM_ACTIVATEAPP: //let's us know if user has clicked and made the window active
		{
			OutputDebugStringA("WM_ACTIVATEAPP\n");
		}break;

		default:
		{
		//	OutputDebugStringA("Default case!\n");
			//this is the catchall LRESULT return to windows, there's a default Windows way to do this
			Result = DefWindowProc(Window, Message, WParam, LParam);
		}break;
	}

	return(Result);

}


internal void RenderWeirdGrad(win32_offscreen_buffer *Buffer, int XOffset, int YOffset)
{
	//*TODO: Let's see what the optimizer does in regard to using a pointer to win32_offscreen_buffer vs. copying it directly

	uint8 *Row = (uint8 *)Buffer->Memory; // this ensures as we move the pointer it's moving by 1 byte (8bits)

	for (int Y = 0;
		Y < Buffer->Height;
		++Y)
	{
		//uint32 *Pixel = (uint32 *)Row; //cast it so it now jumps by 4 bytes (1 pixel) instead of just 1 as cast above
		uint32 *Pixel = (uint32 *)Row;


		for (int X = 0;
			X < Buffer->Width;
			++X)
		{
			// fractally weirdness
			//YOffset += Y;
			//XOffset += X;
			uint8 Red = (Y + XOffset); // this makes the weird scan line effect
			uint8 Gr = (X + XOffset);
			uint8 Bl = (Y + YOffset);

			//this shifts the green values so it sits after yet before the blue (ie: xx RR GG BB - so green's 8 bits needs to actually sit in the 9-16 area
			*Pixel++ = ((Red << 16) | (Gr << 8) | Bl);
		

		}
		Row += Buffer->Pitch;

	}
}

internal void Win32InitDSound(HWND Window, int32 BufferSize, int32 SamplesPerSecond)
{
	//we're going to do the steps the window loader does when it loads our program
	HMODULE DSoundLibrary = LoadLibrary("dsound.dll");

	if (DSoundLibrary)
	{
		direct_sound_create *DirectSoundCreate = (direct_sound_create *)GetProcAddress(DSoundLibrary, "DirectSoundCreate");

		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)))
			{
				// *TODO: look into DSBCAPS_GETCURRENTPOSITION2
				DSBUFFERDESC BufferDescription = {};
				BufferDescription.dwSize = sizeof(BufferDescription); // primary buffer must be set to 0
				BufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;

				//create primary buffer - THIS IS NOT ACTUALLY A BUFFER IT IS A HANDLE TO THE PRIMARY SOUND DEVICE THAT PUTS THE SOUNDCARD
				// INTO A MODE TO PLAY THE FORMAT! - HELLO WINDOWS PLEASE PLAY THIS FORMAT ON THE SOUNDCARD 
				LPDIRECTSOUNDBUFFER PrimaryBuffer;

				if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &PrimaryBuffer, 0)))
				{

					HRESULT Error = PrimaryBuffer->SetFormat(&Waveformat);

					OutputDebugString("Primary buffer created!\n\n");
					//if (SUCCEEDED(PrimaryBuffer->SetFormat(&Waveformat)))
					if (SUCCEEDED(Error))
					{
						// format is set!
						OutputDebugString("Primary sound buffer set format succeeded!\n\n");
					}
					else
					{
						// *TODO: DIAGNOSTIC
					}
				}
				else
				{
					//*TODO: Create Diagnostic
				}
			}
			else
			{
				// *TODO: DIAGNOSTIC
			}
				DSBUFFERDESC BufferDescription = {};

				BufferDescription.dwSize = sizeof(BufferDescription); 
				BufferDescription.dwFlags = 0;
				BufferDescription.dwBufferBytes = BufferSize;
				BufferDescription.lpwfxFormat = &Waveformat;

				
				if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &GlobalSecondarySoundBuffer, 0)))
				{
					OutputDebugString("Secondary sound buffer creation succeeded!\n\n");

				}
				else // DirectSoundCreate failed!
				{
					// *TODO: Create diagnostic
				}


		}
		else // No direct sound library found!
		{
			// *TODO: Create diagnostic
		}


	}
}



// **** MAIN MAIN MAIN MAIN ****
// **** MAIN MAIN MAIN MAIN ****
// **** MAIN MAIN MAIN MAIN ****

int CALLBACK WinMain(
	HINSTANCE Instance,
	HINSTANCE PrevInstance,
	LPSTR     CmdLine,
	int       CmdShow
	)
{
	
	Win32LoadXInput();
	// create instance of windowclass and initialize to 0/null
	WNDCLASS WindowClass = {};
	
	// buffer stretch into window (or shrink)
	Win32ResizeDIBSection(&GlobalBackBuffer, 1280, 720);
	
	//create copy of xinputvibration struct for use later
	_XINPUT_VIBRATION InputVibration;
	
	//define the window class fields
	WindowClass.style = CS_HREDRAW|CS_VREDRAW;
	WindowClass.lpfnWndProc = Win32MainWindowCallback; //how window responds to events by passing in a function via pointer, defined above
	WindowClass.hInstance = Instance; // get the windowhandle instance
	//HICON     hIcon; //may be used later
	WindowClass.lpszClassName = "HandMadeHeroWindowClass";

	//MessageBox(0, "This is handmade hero!", "handmade caption", MB_OK | MB_ICONINFORMATION);

	//REGISTERING THE WINDOW CLASS
	
	if (RegisterClass(&WindowClass))
	{
		HWND Window = CreateWindowExA(
			0, // extended style, no thanks
			WindowClass.lpszClassName,
			"Handmadehero!",
			WS_VISIBLE | WS_OVERLAPPEDWINDOW,
			CW_USEDEFAULT,
			CW_USEDEFAULT,
			CW_USEDEFAULT,
			CW_USEDEFAULT,
			0,
			0,
			Instance,
			0);
		
		if (Window)
		{
			GlobalRunning = true;
			// since we used CS_OWNDC we have this device context forever since we are not sharing it with anyone
			/*HDC DeviceContext = GetDC(Window);*/

			// For Graphics Test
			int XOffset = 0;
			int YOffset = 0;
			
			// For sound test
			int SamplesPerSecond = 48000;
			int BytesPerSample = sizeof(int16) * 2; //how many bytes needed for one LEFT ch/RIGHT ch pair
			int Hz = 4000; //random test tone
			uint32 RunningSampleIndex = 0;
			int SecondaryBufferSize = (SamplesPerSecond * BytesPerSample);
			int SquareWavePeriod = SamplesPerSecond/Hz;
			int HalfSquareWavePeriod = SquareWavePeriod / 2;
			int16 VolumeAmount = 14000;
			bool32 isBufferFilled = false;
				
			
			Win32InitDSound(Window, SecondaryBufferSize, SamplesPerSecond);
			
			
			
			while (GlobalRunning)
			{
				MSG Message;
				
				while (PeekMessage(&Message, 0, 0, 0, PM_REMOVE))
				{
					
					if (Message.message == WM_QUIT)
					{
						GlobalRunning = false;
					}
					TranslateMessage(&Message);
					DispatchMessage(&Message);
				}
				//NOTE: Should we poll this more frequently?
				for (DWORD ControllerIndex = 0;
					ControllerIndex < XUSER_MAX_COUNT;
					++ControllerIndex)
				{
					XINPUT_STATE ControllerState;
					if (XInputGetState(ControllerIndex, &ControllerState) == ERROR_SUCCESS )
					{
						// Controller connected!
						//*TODO: Look at ControllerState.dwPacketNumber increments too rapidly
						XINPUT_GAMEPAD *Pad = &ControllerState.Gamepad;

						
						Pad->bLeftTrigger;
						Pad->bRightTrigger;
						Pad->sThumbLX;
						Pad->sThumbLY;
						Pad->sThumbRX;
						Pad->sThumbRY;
						bool32 DPadUp = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_UP);			//	0x0001
						bool32 DPadDown = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_DOWN);		//  0x0002
						bool32 DPadLeft = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_LEFT);		//  0x0004
						bool32 DPadRight = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT);	//  0x0008
						
						bool32 DPadButtonA = (Pad->wButtons & XINPUT_GAMEPAD_A);			//	0x1000
						bool32 DPadButtonB = (Pad->wButtons & XINPUT_GAMEPAD_B);			//	0x2000
						bool32 DPadButtonX = (Pad->wButtons & XINPUT_GAMEPAD_X);			//	0x4000
						bool32 DPadButtonY = (Pad->wButtons & XINPUT_GAMEPAD_Y);			//	0x8000
						
						bool32 DPadStart = (Pad->wButtons & XINPUT_GAMEPAD_START);			//	0x0010
						bool32 DPadBack = (Pad->wButtons & XINPUT_GAMEPAD_BACK);			//	0x0020
						
						bool32 DPadLeftThumbSButton = (Pad->wButtons & XINPUT_GAMEPAD_LEFT_THUMB);			//	0x0040
						bool32 DPadRightThumbSButton = (Pad->wButtons & XINPUT_GAMEPAD_RIGHT_THUMB);			//	0x0080
						
						bool32 DPadLBumper = (Pad->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);			//	0x0100
						bool32 DPadRBumper = (Pad->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);			//	0x0200
					
						uint8 DPadLTrigger = Pad->bLeftTrigger;
						uint8 DPadRTrigger = Pad->bRightTrigger;

						int16 DPadLXAxis = Pad->sThumbLX;
						int16 DPadLYAxis = Pad->sThumbLY;
						int16 DPadRXAxis = Pad->sThumbRX;
						int16 DPadRYAxis = Pad->sThumbRY;

						XOffset += -DPadLXAxis >> 12;
						YOffset += -DPadLYAxis >> 12;
						if (DPadButtonA)
						{
							YOffset += 2;
							
							InputVibration.wLeftMotorSpeed = 10000;
							InputVibration.wRightMotorSpeed = 10000;
						}
						else
						{
							// No controller detected!
							InputVibration.wLeftMotorSpeed = 0;
							InputVibration.wRightMotorSpeed = 0;
						}

					}
					else
					{
						
					}
				}

				HDC DeviceContext = GetDC(Window);
				XInputSetState(0, &InputVibration);
				
				//prepare the backbuffer
				RenderWeirdGrad(&GlobalBackBuffer, XOffset, YOffset);
				// DirectSound output test right here
				//lock the buffer
				
				// Begin Sound Testing
				DWORD CurrentPlayCursor;
				DWORD CurrentWriteCursor;
							
				if (SUCCEEDED(GlobalSecondarySoundBuffer->GetCurrentPosition(
					&CurrentPlayCursor,
					&CurrentWriteCursor
					)))
				{
					DWORD BytesToWrite;
					DWORD ByteToLock = (RunningSampleIndex*BytesPerSample) % (SecondaryBufferSize);
				
					//*TODO: This is pretty dangerous as we could end up overwriting the buffer before 
					// the original contents are played, must find a better way to do this
					if (ByteToLock == CurrentPlayCursor)
					{
						BytesToWrite = SecondaryBufferSize;
					}
					else if (ByteToLock > CurrentPlayCursor)
					{ 
						// add the two chunks of the buffer together [--ChunkA---Play-----Write---ByteToLock---ChunkB---]
						BytesToWrite =  SecondaryBufferSize - ByteToLock; //From end to ByteToLock ChunkB
						BytesToWrite += CurrentPlayCursor; // from 0 to PlayCursor ChunkA
					}
					else
					{
						BytesToWrite = CurrentPlayCursor - ByteToLock;
					}
					
					//DWORD WritePointer = GlobalSecondarySoundBuffer->GetCurrentPosition(0,&WritePointer);
				
					VOID *FirstLock;
					VOID *SecondLock;
					DWORD BytesInFirstLock;
					DWORD BytesInSecondLock;
				

					if (SUCCEEDED(GlobalSecondarySoundBuffer->Lock(ByteToLock, BytesToWrite,
						&FirstLock, &BytesInFirstLock,
						&SecondLock, &BytesInSecondLock,
						0)))
					{
					DWORD FirstLockSampleCount = BytesInFirstLock / BytesPerSample;
					
						//OutputDebugString("Locking of secondary buffer success!\n\n");
						
						//*TODO: assert if BytesInXLock does not return int16*2 size!
						int16 *SampleOut = (int16*)FirstLock;
						for (DWORD SampleIndex = 0;
							SampleIndex < FirstLockSampleCount;
							++SampleIndex)
						{
							
							int16 SampleValue = ((++RunningSampleIndex / HalfSquareWavePeriod) % 2) ? VolumeAmount : -VolumeAmount;

							++*SampleOut = SampleValue; // increment pointer, write samplevalue
							++*SampleOut = SampleValue;
							
						}
						
						DWORD SecondLockSampleCount = BytesInSecondLock / BytesPerSample;
						SampleOut = (int16 *)SecondLock;
						for (DWORD SampleIndex = 0;
							SampleIndex < SecondLockSampleCount;
							++SampleIndex)
						{
								
							int16 SampleValue = ((++RunningSampleIndex / HalfSquareWavePeriod) % 2) ? VolumeAmount : -VolumeAmount;

							++*SampleOut = SampleValue;
							++*SampleOut = SampleValue;
							

						}
						GlobalSecondarySoundBuffer->Unlock(FirstLock, BytesInFirstLock,SecondLock, BytesInSecondLock); // we're done writing to buffer
						if (!isBufferFilled)
						{
							GlobalSecondarySoundBuffer->Play(0, 0, DSBPLAY_LOOPING);
							isBufferFilled = true;
						}

						
					}
					else
					{
						OutputDebugString("Locking failed!\n\n");
					}

				} // end of success check to see if play and write pointers exist
				else
				{
					OutputDebugString("Play and write pointers may not exist!\n\n");
				}

				
				//paint the buffer
				win32_window_dimension Dimension = Win32GetWindowDimension(Window);
				Win32DisplayBufferInWindow(&GlobalBackBuffer, DeviceContext, Dimension.Width, Dimension.Height);
				ReleaseDC(Window, DeviceContext);
				++XOffset;
			
			}

		}
		else 
		{
			//*TODO: Window non-existent Log it!
			OutputDebugStringA("Window non-existent ");
		}
	}
	
	else 
	{
		//*TODO: RegisterClass(&WindowClass) is bad Log it!
		OutputDebugStringA("RegisterClass(&WindowClass) is bad ");
	}
	
	return(0);
}

	
Dana Fortier
25 posts
Playing Square in DirectSound,SOLVED
Caught it, the increments in the buffer filling were on the WRONG SIDE. Owls of Shame are apparently nesting inside my PC.