-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathProgram.cs
2193 lines (1825 loc) · 89 KB
/
Program.cs
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
using Memory;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Speech.Synthesis;
using System.Numerics;
using AccessibleOutput;
using System.Text;
using Vortice.XInput;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System.Windows.Forms;
using System.Collections.Immutable;
using PvZA11y.Widgets;
using NAudio.Mixer;
/*
[PVZ-A11y Beta 1.17.2]
Blind and motor accessibility mod for Plants Vs Zombies.
Allows input with rebindable keys and controller buttons, rather than requiring a mouse for input.
Includes many features to make the game playable for blind players.
The core goal is to make the game fully accessible for blind gamers, without affecting the game's learning curve.
Being blind shouldn't make a game more challenging to play, it should just be an alternate playstyle.
We're not quite there yet. I often use the freeze functionality as a crutch, because it takes a while to convey the current board state.
To convey information quicker, we could have a unique sound for each type of plant or zombie, but that will bring a much steeper learning curve.
For now, I recommend using NVDA with rate-boosted speech.
Works by using pointerchains to find values in memory.
Sends mouse movement and click events to the game process, to simulate input.
Todo:
Move all pointers/offsets/struct-sizes into pointers.cs
Move all memory interaction operations into memoryIO.cs
General code cleanup (so much dead code, things where they shouldn't be, etc)
Ideas for future updates (Not plans. Other stuff comes first)
Audio descriptions
Zombie sound effects for each almanac entry
Hook the input functions, so we're able to directly control where the game thinks the mouse is, without sending messages to the window.
Manual sun/coin/pickup collection, possible with a sonar-like system
Narration history, so you can see any missed messages.
Discussions:
How should we handle the in-game store? This implements a custom accessible version, but comes with the issue that purchases aren't saved until you enter a game.
Is this enough of an issue to warrant scrapping the accessible version, and instead implement a direct translation of the original menu? (page-shifting delays included)
How can we make it easier for a player to read the game state, without adding a huge learning curve?
We could add a unique audio cue for each plant/zombie, but that will require memorizing 50+ audio cues.
We could offer an option for information brevity. With short nicknames for each plant/zombie (Peashooter > pea, Magnet-Shroom > Mag, Screen Door > Door)
Could disable the delay in the zombie sonar, and just use panning.
Could implement pitch to indicate zombie threat (health/armor, speed, digger, pole-vaulter pre-jump, etc..)
Could have a plant-column checker, to indicate how many empty/plantable tiles are in the current column (useful for detecting if a plant has been eaten, or if you missed a spot)
Could add a screen reader cue when a plant is eaten (eg; "E-4 Peashooter Eaten").
The memory.dll library could use some enhancements, but it's workable for now.
*/
namespace PvZA11y
{
internal class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
/// <summary>
/// Provides keyboard access.
/// </summary>
internal static class NativeKeyboard
{
/// <summary>
/// A positional bit flag indicating the part of a key state denoting
/// key pressed.
/// </summary>
private const int KeyPressed = 0x8000;
/// <summary>
/// Returns a value indicating if a given key is pressed.
/// </summary>
/// <param name="key">The key to check.</param>
/// <returns>
/// <c>true</c> if the key is pressed, otherwise <c>false</c>.
/// </returns>
public static bool IsKeyDown(uint key)
{
return (GetKeyState((int)key) & KeyPressed) != 0;
}
//Fuck C#
public static bool IsKeyDown(int key)
{
return IsKeyDown((uint)key);
}
/// <summary>
/// Gets the key state of a key.
/// </summary>
/// <param name="key">Virtuak-key code for key.</param>
/// <returns>The state of the key.</returns>
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern short GetKeyState(int key);
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
public static int MakeLParam(int x, int y) => (y << 16) | (x & 0xFFFF);
const uint WM_KEYDOWN = 0x0100;
const uint WM_KEYUP = 0x0101;
const uint WM_CHAR = 0x0102;
const int VK_TAB = 0x09;
const int VK_ENTER = 0x0D;
const int VK_UP = 0x26;
const int VK_DOWN = 0x28;
const int VK_RIGHT = 0x27;
const uint WM_LBUTTONDOWN = 0x0201;
const uint WM_LBUTTONUP = 0x0202;
const uint WM_RBUTTONDOWN = 0x0204;
const uint WM_RBUTTONUP = 0x0205;
static bool steamLaunchAttempted = false;
static int GetParentProcessId(Process process)
{
try
{
using (var mo = new System.Management.ManagementObject(string.Format("win32_process.handle='{0}'", process.Id)))
{
mo.Get();
return (int)(uint)mo["ParentProcessId"];
}
}
catch
{
Console.WriteLine("Failed to find parent process");
return -1;
}
}
struct plantInPicker
{
public int posX;
public int posY;
//public int animStartFrame;
//public int animEndFrame;
//public int animStartX;
//public int animStartY;
//public int animEndX;
//public int animEndY;
public SeedType seedType;
public ChosenSeedState seedState;
public int indexInBank;
public bool refreshing;
public int refreshCounter;
public SeedType imitaterType;
public bool crazyDavePicked;
}
static MemoryIO memIO;// = new MemoryIO("PLACEHOLDER", 0, mem);
public static long CurrentEpoch()
{
return DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
struct plantInBoardBank
{
public int refreshCounter;
public int refreshTime;
public int index; //Of what?
public int offsetX;
public int packetType;
public int imitaterType;
public bool isRefreshing;
public float absX;
}
public static Encoding encoding = Encoding.UTF8;
static plantInPicker[] plantPickerState = new plantInPicker[(int)SeedType.NUM_SEED_TYPES];
static byte[] plantPickerBytes = new byte[3180];
static void RefreshPlantPickerState()
{
//Stopwatch sw = new Stopwatch();
//sw.Start();
plantPickerBytes = mem.ReadBytes(memIO.ptr.lawnAppPtr + ",874,bc", 3180); //Can we do this without reallocating the byte array? Might have to fork memory.dll to allow it
//sw.Stop();
//Console.WriteLine("Got bytes in {0}ms", sw.ElapsedMilliseconds);
//If not in plant picker?
if (plantPickerBytes == null)
return;
int index = 0;
for (int i =0; i < (int)SeedType.NUM_SEED_TYPES; i++)
{
plantPickerState[i].posX = BitConverter.ToInt32(plantPickerBytes, index);
index += 4;
plantPickerState[i].posY = BitConverter.ToInt32(plantPickerBytes, index);
index += 28; //Jump to plant id
plantPickerState[i].seedType = (SeedType)BitConverter.ToInt32(plantPickerBytes, index);
index += 4;
plantPickerState[i].seedState = (ChosenSeedState)BitConverter.ToInt32(plantPickerBytes, index);
index += 4;
plantPickerState[i].indexInBank = BitConverter.ToInt32(plantPickerBytes, index);
index += 16;
plantPickerState[i].crazyDavePicked = BitConverter.ToInt32(plantPickerBytes, index) > 0;
index += 4;
}
}
static int CurrentTreeDialogue = -1;
static Mem mem = new Mem();
static nint gameWHnd;
public static int windowWidth;
public static int windowHeight;
public static int drawWidth;
public static int drawHeight;
static int drawStartX;
static long vibrationEnd;
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
private const int CCHDEVICENAME = 0x20;
private const int CCHFORMNAME = 0x20;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public ScreenOrientation dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
[DllImport("user32.dll")]
public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);
static float GetScalingFactor()
{
Screen[] screenList = Screen.AllScreens;
for (int i = 0; i < screenList.Length; i++)
{
DEVMODE dm = new DEVMODE();
dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));
EnumDisplaySettings(screenList[i].DeviceName, -1, ref dm);
var scalingFactor = Math.Round(Decimal.Divide(dm.dmPelsWidth, screenList[i].Bounds.Width), 2);
return (float)scalingFactor;
}
return 1;
}
public static void Click(float downX, float downY, float upX, float upY, bool async = true)
{
if (async)
Task.Run(() => ClickTask(downX, downY, upX, upY));
else
ClickTask(downX, downY, upX, upY);
}
public static void MoveMouse(float x, float y)
{
if (!Config.current.MoveMouseCursor)
return;
float windowScale = GetScalingFactor();
int posX = (int)(((x * drawWidth)/ windowScale) + drawStartX/windowScale);
int posY = (int)((y * drawHeight)/ windowScale);
RECT rect = new RECT();
GetWindowRect(gameWHnd, ref rect);
//Console.WriteLine("Window Pos: {0},{1}", rect.Left, rect.Top);
int cursorX = rect.Left + posX;
int cursorY = rect.Top + posY;
//Move mouse before processing click
for (int attempts = 2; attempts > 0; attempts--)
{
PostMessage(gameWHnd, 0x0200, 1, MakeLParam(posX, posY));
//SendMessage(gameWHnd, 0x0200, 1, MakeLParam(posX, posY));
Task.Delay(10).Wait();
Cursor.Position = new System.Drawing.Point(cursorX, cursorY);
Task.Delay(10).Wait();
}
}
public static void Click(float x, float y, bool rightClick = false, bool async = true, int delayTime = 50, bool moveMouse = false)
{
if (async)
Task.Run(() => ClickTask(x, y, rightClick, delayTime, moveMouse));
else
ClickTask(x, y, rightClick, delayTime, moveMouse);
}
public static void Click(Vector2 clickPos, bool rightClick = false)
{
Click(clickPos.X, clickPos.Y, rightClick);
}
static void ClickTask(float downX, float downY, float upX, float upY)
{
float windowScale = GetScalingFactor();
int clickX = (int)(((downX * drawWidth)/ windowScale) + drawStartX/windowScale);
int clickY = (int)((downY * drawHeight)/windowScale);
int clickUpX = (int)(((upX * drawWidth)/ windowScale) + drawStartX/windowScale);
int clickUpY = (int)((upY * drawHeight)/ windowScale);
PostMessage(gameWHnd, WM_LBUTTONDOWN, 1, MakeLParam(clickX, clickY));
Task.Delay(50).Wait();
PostMessage(gameWHnd, WM_LBUTTONUP, 0, MakeLParam(clickUpX, clickUpY));
}
static void ClickTask(float x, float y, bool rightClick = false, int delayTime = 50, bool moveMouse = false)
{
float windowScale = GetScalingFactor();
int clickX = (int)(((x * drawWidth)/windowScale) + drawStartX/windowScale);
int clickY = (int)((y*drawHeight)/windowScale);
//Console.WriteLine("ClickX: {0} ClickY: {1}", clickX, clickY);
//mem.WriteMemory("PlantsVsZombies.exe+00329670,D9C", "byte", "1"); //Set windowFocus variable to true
uint clickDown = rightClick ? WM_RBUTTONDOWN : WM_LBUTTONDOWN;
uint clickUp = rightClick ? WM_RBUTTONUP : WM_LBUTTONUP;
//Overwrite mouse position in widgetManager
//mem.WriteMemory(lawnAppPtr + ",320,108", "int", clickX.ToString());
//mem.WriteMemory(lawnAppPtr + ",320,10c", "int", clickY.ToString());
if (moveMouse && Config.current.MoveMouseCursor)
{
RECT rect = new RECT();
GetWindowRect(gameWHnd, ref rect);
//Console.WriteLine("Window Pos: {0},{1}", rect.Left, rect.Top);
int cursorX = rect.Left + clickX;
int cursorY = rect.Top + clickY;
Cursor.Position = new System.Drawing.Point(cursorX, cursorY);
//Move mouse before processing click
PostMessage(gameWHnd, 0x0200, 1, MakeLParam(clickX, clickY));
Task.Delay(delayTime).Wait();
}
PostMessage(gameWHnd, clickDown, 1, MakeLParam(clickX, clickY));
Task.Delay(delayTime).Wait();
PostMessage(gameWHnd, clickUp, 0, MakeLParam(clickX, clickY));
}
//static uint addr_tooltip_plantID = 0;
static Process HookProcess()
{
//bool didOpen = mem.OpenProcess("PlantsVsZombies.exe");
Process[] foundProcs = null;
Console.WriteLine("Searching for game process...");
while (foundProcs == null || foundProcs.Length < 1)
{
foundProcs = Process.GetProcessesByName("PlantsVsZombies");
Task.Delay(100).Wait();
if((foundProcs == null || foundProcs.Length < 1) && Config.current.AutoLaunchGame && !steamLaunchAttempted)
{
ProcessStartInfo startInfo = new ProcessStartInfo(Config.current.GameStartPath);
startInfo.WorkingDirectory = Directory.GetParent(Config.current.GameStartPath).FullName;
startInfo.UseShellExecute = true;
if (Config.current.GameStartPath.StartsWith("steam:"))
steamLaunchAttempted = true;
Console.WriteLine("Starting '{0}' in '{1}'", Config.current.GameStartPath, startInfo.WorkingDirectory);
Process.Start(startInfo);
return HookProcess();
}
}
bool isSteam = false;
int parentPid = GetParentProcessId(foundProcs[0]);
if (parentPid != -1)
{
try
{
Process parentProc = Process.GetProcessById(parentPid);
if (parentProc != null)
{
Console.WriteLine("Parent process: Pid: {0}, Name: {1}", parentPid, parentProc.ProcessName);
if (parentProc.ProcessName == "steam")
isSteam = true;
}
}
catch
{
Console.WriteLine("Parent process exited! Assuming non-steam");
}
}
Console.WriteLine("IsSteam: {0}", isSteam);
ProcessModule? mainModule = null;
try
{
mainModule = foundProcs[0].MainModule;
}
catch { }
if(mainModule == null)
return HookProcess(); //Process probably closed/crashed, or hasn't loaded yet. Try again.
string procDir = mainModule.FileName;
procDir = Path.GetDirectoryName(procDir);
appPath = procDir;
Console.WriteLine(procDir);
bool reqpopcapgame1 = false;
while (foundProcs[0].Threads == null || foundProcs[0].Threads.Count < 1)
{
foundProcs = Process.GetProcessesByName("PlantsVsZombies");
Task.Delay(100).Wait();
}
Console.WriteLine("Thread count: " + foundProcs[0].Threads.Count);
//TODO: Less hacky solution to detect launcher vs popcapgames1
//Launcher doesn't use many threads
if (foundProcs[0].Threads.Count < 10)
reqpopcapgame1 = true;
Process? gameProc = null;
//See if we can find popcapgame first
Process[] procs2 = Process.GetProcessesByName("popcapgame1");
if (procs2 != null && procs2.Length > 0)
{
gameProc = procs2[0];
appName = appNamePopcap;
}
else
{
if (reqpopcapgame1)
{
while (procs2 == null || procs2.Length < 1)
{
procs2 = Process.GetProcessesByName("popcapgame1");
//If plantsVsZombies.exe starts more threads, it's not a launcher. So stop searching for popcapagame1
foundProcs = Process.GetProcessesByName("PlantsVsZombies");
if (foundProcs != null && foundProcs.Length > 0 && foundProcs[0].Threads.Count >= 10)
{
reqpopcapgame1 = false;
break;
}
Task.Delay(100).Wait();
}
if (reqpopcapgame1)
{
gameProc = procs2[0];
appName = appNamePopcap;
}
}
if(!reqpopcapgame1)
{
gameProc = foundProcs[0];
appName = appNamePvz;
}
}
bool didOpen = mem.OpenProcess(gameProc.Id);
//TODO: Detect game version
string? versionStr = null;
try
{
versionStr = gameProc.MainModule.FileVersionInfo.ProductVersion;
}
catch { }
//Steam version creates temporary/locked popcapgames1.exe, which will fail to grab version info. If that's the case, grab the verison info from PlantsVsZombies.exe instead.
if (versionStr is null && appName == appNamePopcap && foundProcs != null && foundProcs.Length > 0)
{
try
{
versionStr = foundProcs[0].MainModule.FileVersionInfo.ProductVersion;
}
catch { }
}
if (versionStr == null)
versionStr = "";
versionStr = string.Concat(versionStr.Where(char.IsDigit));
uint versionNum = 0;
if (!uint.TryParse(versionStr, out versionNum))
{
Console.WriteLine("Failed to parse game version!");
Program.Say("Failed to parse game version!");
input.GetKey();
Environment.Exit(1);
}
memIO = new MemoryIO(appName, versionNum, mem);
//memIO = new MemoryIO(appName, 1201073, mem);
gameWHnd = gameProc.MainWindowHandle;
//bool didOpen = mem.OpenProcess(Process.GetProcessesByName("PlantsVsZombies.exe")[0].Id);
Console.WriteLine("DidOpen: " + didOpen);
if (!didOpen)
Environment.Exit(1);
if (isSteam)
Config.current.GameStartPath = "steam://rungameid/3590";
else if (!reqpopcapgame1)
{
try
{
Config.current.GameStartPath = gameProc.MainModule.FileName;
}
catch { }
}
else if (foundProcs != null && foundProcs.Length > 0 && foundProcs[0].MainModule != null)
{
try
{
Config.current.GameStartPath = foundProcs[0].MainModule.FileName;
}
catch { }
}
Config.SaveConfig();
return gameProc;
}
static float GetFrequencyForValue(int key)
{
int keyIndex = (12 * 4) + key;
return (float)Math.Pow(2, (keyIndex - 49) / 12.0) * 440;
}
static float GetFrequencyForValue1(int key)
{
int keyIndex = (12 * 4) + key;
return (float)Math.Pow(2, (keyIndex - 49) / 9.0) * 440;
}
static float GetFrequencyForValue2(int key)
{
int keyIndex = (12 * 4) + key;
return (float)Math.Pow(2, (keyIndex - 49) / 6.0) * 440;
}
static float GetFrequnecyForKey(int octave, int key)
{
int keyIndex = 12 * octave + key;
return (float)Math.Pow(2, (keyIndex - 49) / 12.0) * 440;
}
static string appNamePopcap = "popcapgame1.exe";
static string appNamePvz = "PlantsVsZombies.exe";
static string appName = "";
static string appPath = ""; //Path where data.pak is stored (if popcapgame1.exe, use dir of PlantsVsZombies.exe, not popcapgame1.exe)
//const string lawnAppPtrOffset = "+00329670"; //1.2.0.1073 (cracked goty)
//const string lawnAppPtr = "PlantsVsZombies.exe+00329670"; //1.2.0.1073 (cracked goty)
//const string lawnAppPtr = "PlantsVsZombies.exe+00331C50"; //1.2.0.1096 (latest steam)
//const string dirtyBoardPtrOffset = ",320,18,0,8"; //Not updated properly at main menu
//const string boardPtr = lawnAppPtr + ",868"; //Always accurate. Null if not in game (board)
//const string boardPtrOffset = ",868"; //Always accurate. Null if not in game (board)
//static string lawnAppPtr = appName + lawnAppPtrOffset;
//static string boardPtr = lawnAppPtr + boardPtrOffset;
//static string dirtyBoardPtr = lawnAppPtr + dirtyBoardPtrOffset;
struct Zombie
{
public int zombieType;
public int phase;
public float posX;
public float posY;
public int row; //From GameObject
}
//TODO: Move to board class
public struct PlantOnBoard
{
public int plantType;
public int row;
public int column;
public int state;
public int magItem;
//Only gathered when GetPlantAtCell is called
public bool hasPumpkin;
public bool hasPot;
public bool hasLillypad;
public bool hasLadder;
public bool squished;
public bool sleeping;
public int health;
public int pumpkinHealth;
}
//TODO: Move to board class
public struct GridItem
{
public int type;
public int state;
public int x;
public int y;
//Positions that aren't exact board tiles (stinky uses these)
public float floatX;
public float floatY;
public int vasePlant;
public int vaseZombie;
public int transparent;
}
//TODO: move to memio
public static int GetCursorType()
{
return mem.ReadInt(memIO.ptr.boardChain + ",150,30");
}
//TODO: Move to memio
static int GetCursorPlantID()
{
return mem.ReadInt(memIO.ptr.boardChain + ",150,28");
}
public static void GameplayTutorial(string[] tutorial)
{
foreach (var tut in tutorial)
GameplayTutorial(tut);
}
public static void GameplayTutorial(string tutorial)
{
memIO.SetBoardPaused(true);
input.ClearIntents();
int currentLine = 0;
string[] splitLines = tutorial.Split("\r\n");
int lineCount = splitLines.Length;
Console.WriteLine(tutorial);
Say(tutorial);
InputIntent intent = input.GetCurrentIntent();
while (intent != InputIntent.Confirm)
{
if (intent is InputIntent.Up)
currentLine--;
if (intent is InputIntent.Down)
currentLine++;
if (intent is InputIntent.Up or InputIntent.Down)
{
currentLine = currentLine < 0 ? 0 : currentLine;
currentLine = currentLine >= lineCount ? lineCount - 1 : currentLine;
Console.WriteLine(splitLines[currentLine]);
Say(splitLines[currentLine]);
}
intent = input.GetCurrentIntent();
bool gameClosed = false;
try { gameClosed = memIO.mem.mProc.Process.HasExited; } catch { }
if (gameClosed)
Environment.Exit(0);
}
memIO.SetBoardPaused(false);
}
//TODO: Move to board class
public static List<GridItem> GetGridItems()
{
List<GridItem> gridItems = new List<GridItem>();
int maxCount = mem.ReadInt(memIO.ptr.boardChain + ",138");
for(int i = 0; i < maxCount; i++)
{
int index = i * 236;
bool isActive = mem.ReadByte(memIO.ptr.boardChain + ",134," + (index + 0x20).ToString("X2")) == 0;
if (!isActive)
continue;
GridItem gridItem = new GridItem();
gridItem.type = mem.ReadInt(memIO.ptr.boardChain + ",134," + (index + 0x08).ToString("X2"));
gridItem.state = mem.ReadInt(memIO.ptr.boardChain + ",134," + (index + 0x0c).ToString("X2"));
gridItem.x = mem.ReadInt(memIO.ptr.boardChain + ",134," + (index + 0x10).ToString("X2"));
gridItem.y = mem.ReadInt(memIO.ptr.boardChain + ",134," + (index + 0x14).ToString("X2"));
gridItem.floatX = mem.ReadFloat(memIO.ptr.boardChain + ",134," + (index + 0x24).ToString("X2"));
gridItem.floatY = mem.ReadFloat(memIO.ptr.boardChain + ",134," + (index + 0x28).ToString("X2"));
gridItem.vaseZombie = mem.ReadInt(memIO.ptr.boardChain + ",134," + (index + 0x3c).ToString("X2"));
gridItem.vasePlant = mem.ReadInt(memIO.ptr.boardChain + ",134," + (index + 0x40).ToString("X2"));
gridItem.transparent = mem.ReadInt(memIO.ptr.boardChain + ",134," + (index + 0x4c).ToString("X2"));
gridItems.Add(gridItem);
//Console.WriteLine("Added item at {0} {1}", gridItem.x, gridItem.y);
}
return gridItems;
}
public static void Debug_FinishLevel()
{
mem.WriteMemory(memIO.ptr.boardChain + ",5614", "byte", "1");
}
//TODO: Move to board class
public static PlantOnBoard GetPlantAtCell(int x, int y)
{
var plants = GetPlantsOnBoard();
bool hasPumpkin = false;
int plantID = -1; //None
bool hasPot = false;
bool hasLillypad = false;
bool squished = false;
bool sleeping = false;
int state = 0;
int magItem = 0;
bool rightCobCannon = false;
int health = 0;
int pumpkinHealth = 0;
int lilypadHealth = 0;
int flowerpotHealth = 0;
for(int i =0; i < plants.Count; i++)
{
if (plants[i].column == x - 1 && plants[i].row == y && plants[i].plantType == (int)SeedType.SEED_COBCANNON)
{
state = plants[i].state;
rightCobCannon = true;
}
if (plants[i].column != x)
continue;
if (plants[i].row != y)
continue;
if (plants[i].plantType == (int)SeedType.SEED_PUMPKINSHELL)
{
hasPumpkin = true;
pumpkinHealth = plants[i].health;
}
else if (plants[i].plantType == (int)SeedType.SEED_LILYPAD)
{
hasLillypad = true;
lilypadHealth = plants[i].health;
}
else if (plants[i].plantType == (int)SeedType.SEED_FLOWERPOT)
{
hasPot = true;
flowerpotHealth = plants[i].health;
}
else
{
plantID = plants[i].plantType;
state = plants[i].state;
health = plants[i].health;
}
if (plants[i].magItem != 0)
magItem = plants[i].magItem;
squished |= plants[i].squished;
sleeping |= plants[i].sleeping;
}
bool hasLadder = false;
var gridItems = GetGridItems();
foreach(var gridItem in gridItems)
{
if (gridItem.type == (int)GridItemType.Ladder && gridItem.x == x && gridItem.y == y)
hasLadder = true;
}
if (rightCobCannon)
plantID = (int)SeedType.SEED_COBCANNON;
PlantOnBoard plant;
plant.row = x;
plant.column = y;
plant.hasPumpkin = hasPumpkin;
plant.plantType = plantID;
plant.hasPot = hasPot;
plant.hasLillypad = hasLillypad;
plant.squished = squished;
plant.sleeping = sleeping;
plant.state = state;
plant.magItem = magItem;
plant.hasLadder = hasLadder;
plant.pumpkinHealth = pumpkinHealth;
plant.health = health;
if (plant.hasLillypad && plant.plantType == -1)
{
plant.plantType = (int)SeedType.SEED_LILYPAD;
plant.health = lilypadHealth;
}
if (plant.hasPot && plant.plantType == -1)
{
plant.plantType = (int)SeedType.SEED_FLOWERPOT;
plant.health = flowerpotHealth;
}
if (plant.hasPumpkin && plant.plantType == -1)
{
plant.plantType = (int)SeedType.SEED_PUMPKINSHELL;
plant.health = pumpkinHealth;
}
return plant;
}
//TODO: Move to board class
public static List<PlantOnBoard> GetPlantsOnBoard()
{
List<PlantOnBoard> plants = new List<PlantOnBoard>();
int maxCount = mem.ReadInt(memIO.ptr.boardChain + ",c8");
//int currentCount = mem.ReadInt(boardPtr + ",d4");
for(int i =0; i < maxCount; i++)
{
int index = i * 332;
byte isDead = (byte)mem.ReadByte(memIO.ptr.boardChain + ",c4," + (index + 0x141).ToString("X2"));
byte isSquished = (byte)mem.ReadByte(memIO.ptr.boardChain + ",c4," + (index + 0x142).ToString("X2"));
byte isSleeping = (byte)mem.ReadByte(memIO.ptr.boardChain + ",c4," + (index + 0x143).ToString("X2"));
byte onBoard = (byte)mem.ReadByte(memIO.ptr.boardChain + ",c4," + (index + 0x144).ToString("X2"));
if (onBoard == 1 && isDead == 0)
{
PlantOnBoard p = new PlantOnBoard();
p.squished = isSquished == 1;
p.sleeping = isSleeping == 1;
p.row = mem.ReadInt(memIO.ptr.boardChain + ",c4," + (index + 0x1c).ToString("X2"));
p.plantType = mem.ReadInt(memIO.ptr.boardChain + ",c4," + (index + 0x24).ToString("X2"));
p.column = mem.ReadInt(memIO.ptr.boardChain + ",c4," + (index + 0x28).ToString("X2"));
p.state = mem.ReadInt(memIO.ptr.boardChain + ",c4," + (index + 0x3c).ToString("X2"));
p.health = mem.ReadInt(memIO.ptr.boardChain + ",c4," + (index + 0x40).ToString("X2"));
//magnetItems: c8
for(int mag = 0; mag < 5; mag++)
{
int magIndex = index + 0xc8 + (mag * 0x14) + 0x10;
int magItem = mem.ReadInt(memIO.ptr.boardChain + ",c4," + (magIndex).ToString("X2"));
if (magItem > 0 && (magItem <= 17 || magItem == 21))
p.magItem = magItem;
}
plants.Add(p);
}
}
return plants;
}
//returns amount of sun currently on its way to the sun bank
static int CollectBoardStuff(Widget currentWidget)
{
if (currentWidget is not (Board or ZenGarden))
return 0;
//Make sure we're actually on the board
bool hasBoardPtr = mem.ReadUInt(memIO.ptr.boardChain) != 0;
if (!hasBoardPtr)
return 0;
//And we aren't holding anything with our cursor (plant/shovel)
//Don't care if it's whack-a-zombie, it's fine.
int cursorType = GetCursorType();
if (cursorType > 0 && cursorType != 7)
return 0;
int sunAmount = 0;
//Grab all coins, sunflowers, awards
int maxCount = mem.ReadInt(memIO.ptr.boardChain + ",100");
//List<Vector2> clickables = new List<Vector2>();
for(int i =0; i < maxCount; i++)
{
int index = i * 216;
int coinType = mem.ReadInt(memIO.ptr.boardChain + ",fc," + (index + 0x58).ToString("X2"));
//Skip inactive clickables
if (mem.ReadByte(memIO.ptr.boardChain + ",fc," + (index + 0x38).ToString("X2")) == 1)
continue;
//Skip seed packets
if (coinType == (int)CoinType.UsableSeedPacket)
continue;
//Skip collectables we've already clicked on
if (mem.ReadByte(memIO.ptr.boardChain + ",fc," + (index + 0x50).ToString("X2")) == 1)
{
switch ((CoinType)coinType)
{
case CoinType.Sun:
sunAmount += 25;
break;
case CoinType.Smallsun:
sunAmount += 15;
break;
}
continue;
}
//Get pos, add a couple of pixels to account for rounding errors
Vector2 pos = new Vector2();