-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZPlatform_Win32.inc
1902 lines (1646 loc) · 56.7 KB
/
ZPlatform_Win32.inc
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{Copyright (c) 2008 Ville Krumlinde
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.}
//This file is INCLUDEd in ZPlatform.pas
{$ifndef minimal}
procedure Platform_DesignerSetDC(DC : longword; HWnd : longword);
procedure Platform_DesignerWindowProc(P : pointer);
{$endif}
{$if defined(zzdc_screensaver) or defined(zzdc_activex)}
//Defined in interface so it can be assigned from activex-form
var
//Screensaver example
//http://www.christiancoders.com/cgi-bin/articles/show_article.pl?f=briant05292003004836.html
PreviewParentHWnd : longword; //HWND;
{$if defined(zzdc_activex)}
ZgeActiveXFinished : boolean;
{$ifend}
{$ifend}
implementation
uses ZOpenGL, ZLog, {$ifdef FPC}Windows{$else}Winapi.Windows{$endif}, ZApplication, AudioPlayer,
Commands
{$ifndef minimal}
,SysUtils
{$endif}
{$IFDEF FPC}
,WinEvent
{$ENDIF}
;
//gl code based on, http://www.sulaco.co.za
var
h_Wnd : HWND; // Global window handle
h_DC : HDC; // Global device context
h_RC : HGLRC; // OpenGL rendering context
Keys : array[0..255] of boolean;
KeyMap : array[AnsiChar] of byte;
LastMouse : TPoint;
procedure UpdateJoysticks; forward;
procedure InitJoysticks; forward;
//Copied from Messages.pas
const
WM_CREATE = $0001;
WM_DESTROY = $0002;
WM_CLOSE = $0010;
WM_KEYDOWN = $0100;
WM_KEYUP = $0101;
WM_MOUSEMOVE = $0200;
WM_LBUTTONDOWN = $0201;
WM_LBUTTONUP = $0202;
WM_RBUTTONDOWN = $0204;
WM_RBUTTONUP = $0205;
WM_MBUTTONDOWN = $0207;
WM_MBUTTONUP = $0208;
WM_QUIT = $0012;
WM_INITDIALOG = $0110;
WM_COMMAND = $0111;
WM_ACTIVATE = $0006;
WM_ACTIVATEAPP = $001C;
WM_NCACTIVATE = $0086;
WM_MOUSEWHEEL = $020A;
WM_LBUTTONDBLCLK = $0203;
BM_SETCHECK = $00F1;
CBN_SELCHANGE = 1;
CB_ADDSTRING = $0143;
CB_SETCURSEL = $014E;
CB_GETCURSEL = $0147;
{$ifdef fpc}
ID_OK = 1;
ID_CANCEL = 2;
{$endif}
type
//From Messages.pas
TWordFiller = record
{$IFDEF CPUX86}
Filler: array[1..2] of Byte; // Pad word make it 4 Bytes (2+2)
{$ENDIF}
{$IFDEF CPUX64}
Filler: array[1..6] of Byte; // Pad word to make it 8 Bytes (2+6)
{$ENDIF}
end;
TDWordFiller = record
{$IFDEF CPUX64}
Filler: array[1..4] of Byte; // Pad DWORD to make it 8 bytes (4+4) [x64 only]
{$ENDIF}
end;
PMessage = ^TMessage;
TMessage = record
Msg: Cardinal;
case Integer of
0: (
WParam: WPARAM;
LParam: LPARAM;
Result: LRESULT);
1: (
WParamLo: Word;
WParamHi: Word;
WParamFiller: TDWordFiller;
LParamLo: Word;
LParamHi: Word;
LParamFiller: TDWordFiller;
ResultLo: Word;
ResultHi: Word;
ResultFiller: TDWordFiller);
end;
{$POINTERMATH ON}
function WndProc(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
ZApp : TZApplication;
begin
Result := 0;
case Msg of
WM_CREATE:
begin
// Insert stuff you want executed when the program starts
{$ifdef minimal}
SetWindowLongPtr(hWnd,GWL_USERDATA, NativeInt(PCreateStruct(lParam).lpCreateParams) );
{$endif}
end;
WM_CLOSE,WM_DESTROY:
begin
//In screensaver mode with ParentWindow: parent window sends destroy to
//all child windows, important to quit otherwise process will keep on living.
{$ifdef minimal}
PostQuitMessage(0);
{$endif}
end;
WM_KEYDOWN: // Set the pressed key (wparam) to equal true so we can check if its pressed
begin
{$ifdef cpux64}
Keys[ PByte(@wParam)[4] ] := True;
{$else}
Keys[Lo(wParam)] := True;
{$endif}
end;
WM_KEYUP: // Set the released key (wparam) to equal false so we can check if its pressed
begin
{$ifdef minimal}
if (wParam=VK_ESCAPE) then
begin
ZApp := TZApplication(GetWindowLongPtr(hWnd,GWL_USERDATA));
if ZApp.EscapeToQuit then
PostMessage(hWnd,WM_QUIT,0,0);
end;
{$endif}
{$ifdef cpux64}
Keys[ PByte(@wParam)[4] ] := False;
{$else}
Keys[Lo(wParam)] := False;
{$endif}
end;
WM_MOUSEMOVE :
begin
LastMouse.X := LoWord(lParam);
LastMouse.Y := HiWord(lParam);
end;
WM_LBUTTONDOWN,WM_LBUTTONUP :
//Use '{' as key for left mouse button
Keys[ Ord('{') ] := Msg=WM_LBUTTONDOWN;
WM_RBUTTONDOWN,WM_RBUTTONUP :
//Use '}' as key for right mouse button
Keys[ Ord('}') ] := Msg=WM_RBUTTONDOWN;
WM_MBUTTONDOWN,WM_MBUTTONUP :
//Use '|' as key for middle mouse button
Keys[ Ord('|') ] := Msg=WM_MBUTTONDOWN;
WM_MOUSEWHEEL :
begin
ZApp := TZApplication(GetWindowLongPtr(hWnd,GWL_USERDATA));
if ZApp<>nil then
ZApp.MouseWheelDelta := shortint(wParam shr 16) div 120;
end;
{$ifdef minimal}
else
Result := DefWindowProc(hWnd, Msg, wParam, lParam); // Default result if nothing happens
{$endif}
end;
{$ifdef zgeviz}
//Always pass on the message to avoid zgeviz stealing keypresses from FL-studio
if (Msg=WM_KEYDOWN) or (Msg=WM_KEYUP) then
Result := DefWindowProc(hWnd, Msg, wParam, lParam);
{$endif}
end;
{$if (not defined(minimal))}
procedure Platform_DesignerWindowProc(P : pointer);
var
M : PMessage;
begin
//Brygga mellan vcl-tmessage och win-api wndproc.
M := PMessage(P);
WndProc(h_Wnd,M.Msg,M.WParam,M.LParam);
UpdateJoysticks;
end;
{$ifend}
procedure KillWnd(Fullscreen : Boolean);
begin
if Fullscreen then // Change back to non fullscreen
begin
{$IFDEF FPC}
ChangeDisplaySettings(nil, 0);
{$ELSE}
ChangeDisplaySettings( devmode(nil^), 0);
{$ENDIF}
ShowCursor(True);
end;
// Makes current rendering context not current, and releases the device
// context that is used by the rendering context.
if (not wglMakeCurrent(h_DC, 0)) then
{$ifdef zdebug}
MessageBox(0, 'Release of DC and RC failed!', 'Error', MB_OK or MB_ICONERROR)
{$endif}
;
// Attempts to delete the rendering context
if (not wglDeleteContext(h_RC)) then
begin
{$ifdef zdebug}
MessageBox(0, 'Release of rendering context failed!', 'Error', MB_OK or MB_ICONERROR);
{$endif}
h_RC := 0;
end;
// Attemps to release the device context
if ((h_DC > 0) and (ReleaseDC(h_Wnd, h_DC) = 0)) then
begin
{$ifdef zdebug}
MessageBox(0, 'Release of device context failed!', 'Error', MB_OK or MB_ICONERROR);
{$endif}
h_DC := 0;
end;
// Attempts to destroy the window
if ((h_Wnd <> 0) and (not DestroyWindow(h_Wnd))) then
begin
{$ifdef zdebug}
MessageBox(0, 'Unable to destroy window!', 'Error', MB_OK or MB_ICONERROR);
{$endif}
h_Wnd := 0;
end;
// Attempts to unregister the window class
if (not UnRegisterClass('OpenGL', hInstance)) then
begin
//Skip errormessage if activex, otherwise it will hang IE
{$ifdef zdebug}
MessageBox(0, 'Unable to unregister window class!', 'Error', MB_OK or MB_ICONERROR);
{$endif}
// hInstance := 0;
end;
end;
var
Fullscreen : Boolean;
procedure Platform_ShutdownScreen;
begin
KillWnd(FullScreen);
end;
function Platform_InitScreen(var Width, Height : integer; UseFullScreen : boolean; Title : PAnsiChar; ZApp : pointer) : integer;
var
wndClass : TWndClassA; // Window class
dwStyle : DWORD; // Window styles
dwExStyle : DWORD; // Extended window styles
dmScreenSettings : DEVMODE; // Screen settings (fullscreen, etc...)
PixelFormat : GLuint; // Settings for the OpenGL rendering
pfd : TPIXELFORMATDESCRIPTOR; // Settings for the OpenGL window
ScreenDC : HDC;
PixelDepth : Integer;
R : TRect;
DesktopSize : TRect;
WinX,WinY,DesktopPixelDepth : integer;
UseFullScreenWindow : boolean;
begin
GetClientRect(GetDesktopWindow,DesktopSize);
FullScreen := UseFullScreen;
//FullscreenWindow means use full desktop size without making a mode-switch
UseFullScreenWindow := Width=-1;
if UseFullScreenWindow then
begin
FullScreen := False;
Width := DesktopSize.Right;
Height := DesktopSize.Bottom;
end;
{$if defined(zzdc_screensaver) or defined(zzdc_activex)}
if PreviewParentHWnd<>0 then
FullScreen := False;
{$ifend}
PixelDepth := 32;
if not Fullscreen then
begin
//If windowed, do not ask for more pixeldepth than supported
//otherwise hw-acceleration will be disabled
ScreenDC := GetDC(0);
DesktopPixelDepth := GetDeviceCaps(ScreenDC, BITSPIXEL);
if PixelDepth>DesktopPixelDepth then
PixelDepth := DesktopPixelDepth;
ReleaseDC(0, ScreenDC);
end;
FillChar(wndClass, SizeOf(wndClass),0); // Clear the window class structure
// Set up the window class
// wndClass.cbSize := SizeOf(wndClass);
wndClass.style := CS_HREDRAW or // Redraws entire window if length changes
CS_VREDRAW or // Redraws entire window if height changes
CS_OWNDC; // Unique device context for the window
//Ignore doubleclicks for now, they steal single clicks
// CS_DBLCLKS; // Receive doubleclick messages
wndClass.lpfnWndProc := @WndProc; // Set the window procedure to our func WndProc
wndClass.hInstance := HInstance; //Delphi rtl gets the hinstance (SysInit.Unit)
wndClass.hCursor := LoadCursor(0, IDC_ARROW);
wndClass.lpszClassName := 'OpenGL';
// wndClass.hIconSm := LoadIcon(0, IDI_APPLICATION);
wndClass.hIcon := LoadIcon(0, IDI_APPLICATION);
//if LoadImageA(HInstance, '1', IMAGE_ICON, 32, 32, 0)=0 then
// zhalt('crash2');
//if LoadIconA(hInstance,'HEJ')=0 then
// zhalt('crash');
if (RegisterClassA(wndClass) = 0) then // Attemp to register the window class
{$if not defined(zzdc_activex)}
ZHalt('Failed to register window class')
{$ifend};
// Change to fullscreen if so desired
if Fullscreen then
begin
FillChar(dmScreenSettings, SizeOf(dmScreenSettings), 0);
with dmScreenSettings do begin // Set parameters for the screen setting
dmSize := SizeOf(dmScreenSettings);
dmPelsWidth := Width; // Window width
dmPelsHeight := Height; // Window height
dmBitsPerPel := PixelDepth; // Window color depth
dmFields := DM_PELSWIDTH or DM_PELSHEIGHT or DM_BITSPERPEL;
end;
// Try to change screen mode to fullscreen
if (ChangeDisplaySettings(dmScreenSettings, CDS_FULLSCREEN) = DISP_CHANGE_FAILED) then
ZHalt('Unable to switch to fullscreen.');
end;
if Fullscreen or UseFullScreenWindow then
begin
dwStyle := WS_POPUP or // Creates a popup window
WS_CLIPCHILDREN // Doesn't draw within child windows
or WS_CLIPSIBLINGS; // Doesn't draw within sibling windows
dwExStyle := WS_EX_APPWINDOW; // Top level window
end
else
begin
dwStyle :=
(WS_OVERLAPPED or WS_CAPTION or WS_SYSMENU) or
//WS_OVERLAPPEDWINDOW or // Creates an overlapping window
WS_CLIPCHILDREN or // Doesn't draw within child windows
WS_CLIPSIBLINGS; // Doesn't draw within sibling windows
dwExStyle := WS_EX_APPWINDOW or // Top level window
WS_EX_WINDOWEDGE; // Border with a raised edge
end;
{$if defined(zzdc_screensaver) or defined(zzdc_activex)}
if PreviewParentHWnd<>0 then
begin
//We are a child window
GetClientRect(PreviewParentHWnd, R);
Height := R.Bottom;
Width := R.Right;
dwStyle := WS_VISIBLE or WS_CHILD;
dwExStyle := 0;
end;
{$ifend}
{$ifndef minimal}
try
{$endif}
R.Top := 0;
R.Left := 0;
R.Bottom := Height;
R.Right := Width;
// ViewportH := Height;
// ViewportW := Width;
if (not Fullscreen) and (not UseFullScreenWindow)
{$if defined(zzdc_screensaver) or defined(zzdc_activex)}
and (PreviewParentHWnd=0)
{$ifend}
then
begin
//Önskad fönsterstorlek måste justeras så att titlebar får plats
AdjustWindowRectEx(R,dwStyle,False,dwExStyle);
WinX := (DesktopSize.Right - R.Right) div 2;
WinY := (DesktopSize.Bottom - R.Bottom) div 2;
end else
begin
WinX := 0;
WinY := 0;
end;
// Attempt to create the actual window
h_Wnd := CreateWindowExA(dwExStyle, // Extended window styles
'OpenGL', // Class name
Title, // Window title (caption)
dwStyle, // Window styles
WinX, WinY, // Window position
R.Right - R.Left, R.Bottom - R.Top, // Size of window
{$if defined(zzdc_screensaver) or defined(zzdc_activex)}
PreviewParentHWnd
{$else}
0
{$ifend}, //Parent window
0, // No menu
hInstance, // Instance
ZApp); // Pass to WM_CREATE
if h_Wnd = 0 then
ZHalt('Unable to create window.');
// Try to get a device context
h_DC := GetDC(h_Wnd);
if (h_DC = 0) then
ZHalt('Unable to get a device context.');
// Settings for the OpenGL window
FillChar(pfd, SizeOf(pfd), 0);
with pfd do
begin
nSize := SizeOf(TPIXELFORMATDESCRIPTOR); // Size Of This Pixel Format Descriptor
nVersion := 1; // The version of this data structure
dwFlags := PFD_DRAW_TO_WINDOW // Buffer supports drawing to window
or PFD_SUPPORT_OPENGL // Buffer supports OpenGL drawing
or PFD_DOUBLEBUFFER; // Supports double buffering
iPixelType := PFD_TYPE_RGBA; // RGBA color format
cColorBits := PixelDepth; // OpenGL color depth
//cRedBits := 8; // Number of red bitplanes
//cRedShift := 0; // Shift count for red bitplanes
//cGreenBits := 8; // Number of green bitplanes
//cGreenShift := 0; // Shift count for green bitplanes
//cBlueBits := 8; // Number of blue bitplanes
//cBlueShift := 0; // Shift count for blue bitplanes
//Only ask for alpha bits in 32 bit mode
//Otherwise hw-acceleration might be disabled
if PixelDepth=32 then
cAlphaBits := 8; // Not supported
//cAlphaShift := 0; // Not supported
//cAccumBits := 0; // No accumulation buffer
//cAccumRedBits := 0; // Number of red bits in a-buffer
//cAccumGreenBits := 0; // Number of green bits in a-buffer
//cAccumBlueBits := 0; // Number of blue bits in a-buffer
//cAccumAlphaBits := 0; // Number of alpha bits in a-buffer
cDepthBits := 16; // Specifies the depth of the depth buffer
//cStencilBits := 0; // Turn off stencil buffer
//cAuxBuffers := 0; // Not supported
iLayerType := PFD_MAIN_PLANE; // Ignored
//bReserved := 0; // Number of overlay and underlay planes
//dwLayerMask := 0; // Ignored
//dwVisibleMask := 0; // Transparent color of underlay plane
//dwDamageMask := 0; // Ignored
end;
// Attempts to find the pixel format supported by a device context that is the best match to a given pixel format specification.
PixelFormat := ChoosePixelFormat(h_DC, {$IFNDEF FPC}@{$ENDIF}pfd);
if (PixelFormat = 0) then
ZHalt('Unable to find a suitable pixel format');
// Sets the specified device context's pixel format to the format specified by the PixelFormat.
if (not SetPixelFormat(h_DC, PixelFormat, @pfd)) then
ZHalt('Unable to set the pixel format');
// Create a OpenGL rendering context
h_RC := wglCreateContext(h_DC);
if (h_RC = 0) then
ZHalt('Unable to create an OpenGL rendering context');
// Makes the specified OpenGL rendering context the calling thread's current rendering context
if (not wglMakeCurrent(h_DC, h_RC)) then
ZHalt('Unable to activate OpenGL rendering context');
{$ifndef minimal}
except
KillWnd(Fullscreen);
raise;
end;
{$endif}
// Settings to ensure that the window is the topmost window
ShowWindow(h_Wnd, SW_SHOW);
SetForegroundWindow(h_Wnd);
SetFocus(h_Wnd);
if FullScreen then
//Try to workaround corrupt font problem in fullscreen
Sleep(500);
// Ensure the OpenGL window is resized properly
// ResizeWndGL(Width, Height);
{$ifdef zzdc_screensaver}
//Must have initial mouseposition in screensaver mode
GetCursorPos(LastMouse);
{$endif}
Result := h_Wnd;
end;
procedure Platform_SetWindowCaption(Title : PAnsiChar);
begin
SetWindowTextA(h_Wnd,Title);
end;
procedure Platform_ShowMouse(Visible : boolean);
begin
//Hide mouse, except in preview mode
{$if defined(zzdc_screensaver) or defined(zzdc_activex)}
if PreviewParentHWnd<>0 then
Exit;
{$ifend}
ShowCursor(Visible);
end;
procedure Platform_SwapBuffers;
begin
SwapBuffers(h_DC);
end;
procedure Platform_Run(Callback : TRunCallback);
//WinMain som behandlar meddelanden och anropar callback
var
Msg : TMsg;
Finished : Boolean;
{$ifdef zzdc_screensaver}
EndTime : single;
{$endif}
begin
Finished := False;
{$ifdef zzdc_screensaver}
if PreviewParentHWnd<>0 then
begin
//The control panel preview window does not show until app is idle
//This half-second wait-loop will make the preview window appear
EndTime := Platform_GetTime + 0.5;
while Platform_GetTime<EndTime do
if (PeekMessage(msg, 0, 0, 0, PM_REMOVE)) then // Check if there is a message for this window
begin
TranslateMessage(msg);
DispatchMessage(msg);
end;
end;
{$endif}
// Main message loop:
while not Finished do
begin
if (PeekMessage(msg, 0, 0, 0, PM_REMOVE)) then // Check if there is a message for this window
begin
{$ifdef zzdc_screensaver}
if PreviewParentHWnd=0 then
case Msg.Message of
WM_MOUSEMOVE :
Finished := (Abs(LOWORD(Msg.lParam) - LastMouse.X) > 5) or
(Abs(HIWORD(Msg.lParam) - LastMouse.Y) > 5);
WM_KEYDOWN,WM_ACTIVATE,WM_ACTIVATEAPP,WM_NCACTIVATE : Finished := True;
end;
{$endif}
if (msg.message = WM_QUIT) then // If WM_QUIT message received then we are done
finished := True
else
begin // Else translate and dispatch the message to this window
TranslateMessage(msg);
DispatchMessage(msg);
end;
end
else
begin
if not (Callback()) then
Finished := True;
UpdateJoysticks;
{$ifdef zzdc_activex}
if ZgeActiveXFinished then
Finished := True;
{$endif}
{$if defined(zzdc_screensaver) or defined(zzdc_activex)}
//Sleep(5); //Avoid using all cpu in screensaver mode
{$ifend}
end;
end;
end;
// Keyboard input
procedure InitKeyMap;
var
I : integer;
begin
for I := 0 to 255 do
KeyMap[AnsiChar(I)] := I;
KeyMap[UpKey] := VK_UP;
KeyMap[DownKey] := VK_DOWN;
KeyMap[LeftKey] := VK_LEFT;
KeyMap[RightKey] := VK_RIGHT;
end;
function Platform_IsKeyPressed(C : AnsiChar) : boolean;
begin
Result := Keys[ KeyMap[C] ];
end;
function Platform_CommandLine(Switch : PAnsiChar) : boolean;
var
P : PAnsiChar;
begin
{$ifdef zzdc_screensaver}
if Switch[0] in ['f','s'] then
begin //screensaver always fullscreen no sound
Result := True;
Exit;
end;
{$endif}
P := GetCommandLineA;
Result := False;
while(P[0]<>#0) do
begin
if (P[0] in ['-','/']) and (P[1]=Switch[0]) then
begin
Result := True;
Break;
end;
Inc(P);
end;
end;
procedure Platform_Error(ErrorMessage : PAnsiChar);
begin
MessageBoxA(H_Wnd, ErrorMessage, 'ZZDC Error', MB_OK);
end;
function Platform_GetMousePos : TZPointi;
begin
if Fullscreen then
Result := TZPointi(LastMouse)
else
begin
//I fönster-läge så behöver muskoord klippas till fönsterstorlek
//Och getcursorpos används pga wm_mousemove enbart skickas till aktuellt fönster
GetCursorPos(TPoint(Result));
ScreenToClient(h_Wnd,TPoint(Result));
end;
end;
procedure Platform_SetMousePos(const X,Y : integer);
var
Tmp : TPoint;
begin
Tmp.X := X;
Tmp.Y := Y;
if not Fullscreen then
ClientToScreen(h_Wnd,Tmp);
SetCursorPos(Tmp.X,Tmp.Y);
end;
function Platform_GetExeFileName : PAnsiChar;
begin
GetMem(Result,256);
GetModuleFileNameA(0, Result, 256)
end;
{$ifndef minimal}
var
DesignerFilePath : AnsiString;
procedure Platform_DesignerSetFilePath(const P : AnsiString);
begin
DesignerFilePath := P;
end;
{$endif}
procedure MakeFullPath(FileName : PAnsiChar; var Buf : array of ansichar);
{$ifdef minimal}
var
I : integer;
{$endif}
begin
{$ifdef minimal}
I := GetModuleFileNameA(0,Buf,255);
while (I>0) and (Buf[I]<>'\') do
Dec(I);
if I>0 then
begin
Buf[I+1]:=#0;
//lstrcat(Buf,FileName);
ZStrCat(PAnsiChar(@Buf),FileName);
end;
{$else}
Assert(Length(DesignerFilePath) + Length(FileName) < Length(Buf));
ZStrCopy(PAnsiChar(@Buf),PAnsiChar(DesignerFilePath));
ZStrCat(PAnsiChar(@Buf),FileName);
{$endif}
end;
procedure Platform_WriteFile(FileName : PAnsiChar; Memory : pointer; Size : integer; Append : Boolean);
var
Handle : THandle;
Dummy : longword;
Buf : array[0..254] of AnsiChar;
OpenFlag : LongWord;
begin
MakeFullPath(FileName,Buf);
FileName := @Buf;
if Append then
OpenFlag := OPEN_ALWAYS
else
OpenFlag := CREATE_ALWAYS;
Handle := CreateFileA(FileName, GENERIC_WRITE,
0, nil, OpenFlag,
FILE_ATTRIBUTE_NORMAL, 0);
if Handle=INVALID_HANDLE_VALUE then
begin
{$ifdef zlog}
ZLog.GetLog('Platform').Write('Could not open file: ' + FileName);
{$endif}
Exit;
end;
SetFilePointer(Handle, 0, nil, FILE_END);
WriteFile(Handle, Memory^, Size, Dummy, nil);
CloseHandle(Handle);
end;
procedure Platform_ReadFile(FileName : PAnsiChar; var Memory : pointer; var Size : integer; IsRelative : Boolean);
var
Handle : THandle;
Dummy : longword;
Buf : array[0..254] of AnsiChar;
begin
//Open file relative to path of exe-file
if IsRelative then
begin
MakeFullPath(FileName,Buf);
FileName := @Buf;
end;
Handle := CreateFileA(FileName, GENERIC_READ,
0, nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
if Handle=INVALID_HANDLE_VALUE then
begin
{$ifdef zlog}
ZLog.GetLog('Platform').Write('File missing: ' + FileName);
{$endif}
Exit;
end;
Size := GetFileSize(Handle,nil);
GetMem(Memory,Size);
ReadFile(Handle, Memory^, Size, Dummy, nil);
CloseHandle(Handle);
end;
function Platform_GenerateFontDisplayLists(Size : integer; FirstChar,LastChar : integer) : integer;
var
Quantity : integer;
Start : integer;
OldFont,Font : HFONT;
Tries : integer;
begin
Quantity := LastChar - FirstChar;
Start := glGenLists(Quantity);
Font := CreateFont( (Size-2), // Height Of Font
Size-2, // Width Of Font
0, // Angle Of Escapement
0, // Orientation Angle
1000, // Font Weight
0, // Italic
0, // Underline
0, // Strikeout
ANSI_CHARSET, // Character Set Identifier
OUT_TT_PRECIS , // Output Precision
CLIP_DEFAULT_PRECIS, // Clipping Precision
ANTIALIASED_QUALITY, // Output Quality
FF_DONTCARE or DEFAULT_PITCH, // Family And Pitch
'Lucida Console'); //'Verdana'); //'Arial Black'); //'Courier New');
oldfont := HFONT(SelectObject(h_DC, font)); // Selects The Font We Want
//In some cases (16 bit color) wglUseFontBitmaps failse the first time
Tries:=2;
while not wglUseFontBitmaps(h_DC,FirstChar,Quantity,Start) and (Tries>0) do
Dec(Tries);
// wglUseFontOutlines(h_DC, FirstChar, Quantity, Start, 0.0, 0.1, WGL_FONT_POLYGONS, nil);
//alt. med getglyphoutline så kan texturer skapas direkt
SelectObject(h_DC, oldfont);
DeleteObject(font);
//todo delete lists on finalization
Result := Start;
end;
var
TimerFreq,TimerStart : int64;
function Platform_GetTime : single;
var
Count : int64;
begin
//http://www.devsource.com/article2/0,1895,2063854,00.asp
QueryPerformanceCounter(Count);
//Om man inte drar ifrån timerstart så blir värdet för högt
//och det blir frameskips.
Count := (Count-TimerStart);
// Count := Count * 1000;
//QueryPerformanceFrequency(TimerFreq);
Result := (Count/TimerFreq);
// Result := Count div TimerFreq;
// Result := GetTickCount;
end;
function Platform_GetSystemTime : integer;
var
T : TSystemTime;
begin
GetLocalTime(T);
Result := T.wHour * 3600 + T.wMinute * 60 + T.wSecond;
end;
procedure Platform_DesignerSetDC(DC : longword; HWnd : longword);
begin
H_DC := DC;
H_Wnd := HWnd;
end;
function Platform_LoadLinkedResource : TZInputStream;
var
HResInfo: THandle;
HGlobal: THandle;
Size : integer;
begin
Result := nil;
HResInfo := FindResource(HInstance,'data_file', RT_RCDATA);
//if HResInfo = 0 then Error;
HGlobal := LoadResource(HInstance, HResInfo);
//if HGlobal = 0 then Error;
Size := SizeOfResource(HInstance, HResInfo);
if Size<=4 then
//Only dummy data present, return nil
Exit;
Result := TZInputStream.CreateFromMemory(LockResource(HGlobal), Size);
end;
////////////////////////////////
// AUDIO
//From mmsystem.pas
type
PWaveFormatEx = ^TWaveFormatEx;
tWAVEFORMATEX = packed record
wFormatTag: Word; { format type }
nChannels: Word; { number of channels (i.e. mono, stereo, etc.) }
nSamplesPerSec: DWORD; { sample rate }
nAvgBytesPerSec: DWORD; { for buffer estimation }
nBlockAlign: Word; { block size of data }
wBitsPerSample: Word; { number of bits per sample of mono data }
cbSize: Word; { the count in bytes of the size of }
end;
MMRESULT = UINT;
const
WAVE_FORMAT_PCM = 1;
WAVE_FORMAT_IEEE_FLOAT = 3;
mmsyst = 'winmm.dll';
function timeBeginPeriod(uPeriod: UINT): MMRESULT; stdcall; external mmsyst;
function timeEndPeriod(uPeriod: UINT): MMRESULT; stdcall; external mmsyst;
function PlaybackThread_Execute(Parameter: Pointer): Integer; stdcall; forward;
type
//DirectSound
//C-style references
PDSBufferDesc = ^TDSBufferDesc;
TDSBufferDesc = packed record
dwSize: DWORD;
dwFlags: DWORD;
dwBufferBytes: DWORD;
dwReserved: DWORD;
lpwfxFormat: PWaveFormatEx;
guid3DAlgorithm: TGUID;
end;
PDSCcaps = ^TDSCcaps;
TDSCcaps = packed record
dwSize: DWORD;
dwFlags: DWORD;
dwFormats: DWORD;
dwChannels: DWORD;
end;
PDSCaps = ^TDSCaps;
TDSCaps = packed record
dwSize : DWORD;
dwFlags : DWORD;
dwMinSecondarySampleRate : DWORD;
dwMaxSecondarySampleRate : DWORD;
dwPrimaryBuffers : DWORD;
dwMaxHwMixingAllBuffers : DWORD;
dwMaxHwMixingStaticBuffers : DWORD;
dwMaxHwMixingStreamingBuffers : DWORD;
dwFreeHwMixingAllBuffers : DWORD;
dwFreeHwMixingStaticBuffers : DWORD;
dwFreeHwMixingStreamingBuffers : DWORD;
dwMaxHw3DAllBuffers : DWORD;
dwMaxHw3DStaticBuffers : DWORD;
dwMaxHw3DStreamingBuffers : DWORD;
dwFreeHw3DAllBuffers : DWORD;
dwFreeHw3DStaticBuffers : DWORD;
dwFreeHw3DStreamingBuffers : DWORD;
dwTotalHwMemBytes : DWORD;
dwFreeHwMemBytes : DWORD;
dwMaxContigFreeHwMemBytes : DWORD;
dwUnlockTransferRateHwBuffers : DWORD;
dwPlayCpuOverheadSwBuffers : DWORD;
dwReserved1 : DWORD;
dwReserved2 : DWORD;
end;
PDSBcaps = ^TDSBcaps;
TDSBcaps = packed record