-
Notifications
You must be signed in to change notification settings - Fork 1
/
Common.cs
1792 lines (1556 loc) · 53.4 KB
/
Common.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
/// <copyright>
///
/// Rewritten in C# by Yury Kiselev, 2010.
///
/// Copyright (C) 1996-1997 Id Software, Inc.
///
/// This program is free software; you can redistribute it and/or
/// modify it under the terms of the GNU General Public License
/// as published by the Free Software Foundation; either version 2
/// of the License, or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
///
/// See the GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
/// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Net;
using System.Net.Sockets;
using OpenTK;
//
// Source: common.h + common.c
//
// All of Quake's data access is through a hierchal file system, but the contents of the file system can be transparently merged from several sources.
//
// The "base directory" is the path to the directory holding the quake.exe and all game directories. The sys_* files pass this to host_init in quakeparms_t->basedir. This can be overridden with the "-basedir" command line parm to allow code debugging in a different directory. The base directory is
// only used during filesystem initialization.
//
// The "game directory" is the first tree on the search path and directory that all generated files (savegames, screenshots, demos, config files) will be saved to. This can be overridden with the "-game" command line parameter. The game directory can never be changed while quake is executing. This is a precacution against having a malicious server instruct clients to write files over areas they shouldn't.
//
// The "cache directory" is only used during development to save network bandwidth, especially over ISDN / T1 lines. If there is a cache directory
// specified, when a file is found by the normal search path, it will be mirrored
// into the cache directory, then opened there.
//
//
//
// FIXME:
// The file "parms.txt" will be read out of the game directory and appended to the current command line arguments to allow different games to initialize startup parms differently. This could be used to add a "-sspeed 22050" for the high quality sound edition. Because they are added at the end, they will not override an explicit setting on the original command line.
namespace Quarp
{
static class Common
{
// this graphic needs to be in the pak file to use registered features
static ushort[] _Pop = new ushort[]
{
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000
,0x0000,0x0000,0x6600,0x0000,0x0000,0x0000,0x6600,0x0000
,0x0000,0x0066,0x0000,0x0000,0x0000,0x0000,0x0067,0x0000
,0x0000,0x6665,0x0000,0x0000,0x0000,0x0000,0x0065,0x6600
,0x0063,0x6561,0x0000,0x0000,0x0000,0x0000,0x0061,0x6563
,0x0064,0x6561,0x0000,0x0000,0x0000,0x0000,0x0061,0x6564
,0x0064,0x6564,0x0000,0x6469,0x6969,0x6400,0x0064,0x6564
,0x0063,0x6568,0x6200,0x0064,0x6864,0x0000,0x6268,0x6563
,0x0000,0x6567,0x6963,0x0064,0x6764,0x0063,0x6967,0x6500
,0x0000,0x6266,0x6769,0x6a68,0x6768,0x6a69,0x6766,0x6200
,0x0000,0x0062,0x6566,0x6666,0x6666,0x6666,0x6562,0x0000
,0x0000,0x0000,0x0062,0x6364,0x6664,0x6362,0x0000,0x0000
,0x0000,0x0000,0x0000,0x0062,0x6662,0x0000,0x0000,0x0000
,0x0000,0x0000,0x0000,0x0061,0x6661,0x0000,0x0000,0x0000
,0x0000,0x0000,0x0000,0x0000,0x6500,0x0000,0x0000,0x0000
,0x0000,0x0000,0x0000,0x0000,0x6400,0x0000,0x0000,0x0000
};
public const int MAX_FILES_IN_PACK = 2048;
// if a packfile directory differs from this, it is assumed to be hacked
public const int PAK0_COUNT = 339;
public const int PAK0_CRC = 32981;
public static Vector3 ZeroVector = Vector3.Zero; // for passing as reference
public static v3f ZeroVector3f = default(v3f);// for passing as reference
static readonly byte[] ZeroBytes = new byte[4096];
static string[] safeargvs = new string[]
{
"-stdvid", "-nolan", "-nosound", "-nocdaudio", "-nojoy", "-nomouse", "-dibonly"
};
static IByteOrderConverter _Converter;
static Cvar _Registered;
static Cvar _CmdLine;
static string _CacheDir; // com_cachedir[MAX_OSPATH];
static string _GameDir; // com_gamedir[MAX_OSPATH];
static List<searchpath_t> _SearchPaths; // searchpath_t *com_searchpaths;
static string[] _Argv;
static string _Args; // com_cmdline
static GameKind _GameKind; // qboolean standard_quake = true, rogue, hipnotic;
static bool _IsModified; // com_modified
static bool _StaticRegistered; // static_registered
static char[] _Slashes = new char[] { '/', '\\' };
static string _Token; // com_token
public static bool IsBigEndian
{
get { return !BitConverter.IsLittleEndian; }
}
public static string GameDir
{
get { return _GameDir; }
}
public static GameKind GameKind
{
get { return _GameKind; }
}
public static int Argc
{
get { return _Argv.Length; }
}
public static string[] Args
{
get { return _Argv; }
set
{
_Argv = new string[value.Length];
value.CopyTo(_Argv, 0);
_Args = String.Join(" ", value);
}
}
public static string Token
{
get { return _Token; }
}
public static bool IsRegistered
{
get { return _Registered.Value != 0; }
}
static Common()
{
// set the byte swapping variables in a portable manner
if (BitConverter.IsLittleEndian)
{
_Converter = new LittleEndianConverter();
}
else
{
_Converter = new BigEndianConverter();
}
_SearchPaths = new List<searchpath_t>();
}
public static string Argv(int index)
{
return _Argv[index];
}
// int COM_CheckParm (char *parm)
// Returns the position (1 to argc-1) in the program's argument list
// where the given parameter apears, or 0 if not present
public static int CheckParm(string parm)
{
for (int i = 1; i < _Argv.Length; i++)
{
if (_Argv[i].Equals(parm))
return i;
}
return 0;
}
public static bool HasParam(string parm)
{
return (CheckParm(parm) > 0);
}
// void COM_Init (char *path)
public static void Init(string path, string[] argv)
{
_Argv = argv;
_Registered = new Cvar("registered", "0");
_CmdLine = new Cvar("cmdline", "0", false, true);
Cmd.Add("path", Path_f);
InitFileSystem();
CheckRegistered();
}
// void COM_InitArgv (int argc, char **argv)
public static void InitArgv(string[] argv)
{
// reconstitute the command line for the cmdline externally visible cvar
_Args = String.Join(" ", argv);
_Argv = new string[argv.Length];
argv.CopyTo(_Argv, 0);
bool safe = false;
foreach (string arg in _Argv)
{
if (arg == "-safe")
{
safe = true;
break;
}
}
if (safe)
{
// force all the safe-mode switches. Note that we reserved extra space in
// case we need to add these, so we don't need an overflow check
string[] largv = new string[_Argv.Length + safeargvs.Length];
_Argv.CopyTo(largv, 0);
safeargvs.CopyTo(largv, _Argv.Length);
_Argv = largv;
}
_GameKind = GameKind.StandardQuake;
if (HasParam("-rogue"))
_GameKind = GameKind.Rogue;
if (HasParam("-hipnotic"))
_GameKind = GameKind.Hipnotic;
}
/// <summary>
/// COM_Parse
/// Parse a token out of a string
/// </summary>
public static string Parse(string data)
{
_Token = String.Empty;
if (String.IsNullOrEmpty(data))
return null;
// skip whitespace
int i = 0;
while (i < data.Length)
{
while (i < data.Length)
{
if (data[i] > ' ')
break;
i++;
}
if (i >= data.Length)
return null;
// skip // comments
if ((data[i] == '/') && (i + 1 < data.Length) && (data[i + 1] == '/'))
{
while (i < data.Length && data[i] != '\n')
i++;
}
else
break;
}
if (i >= data.Length)
return null;
int i0 = i;
// handle quoted strings specially
if (data[i] == '\"')
{
i++;
i0 = i;
while (i < data.Length && data[i] != '\"')
i++;
if (i == data.Length)
{
_Token = data.Substring(i0, i - i0);
return null;
}
else
{
_Token = data.Substring(i0, i - i0);
return (i + 1 < data.Length ? data.Substring(i + 1) : null);
}
}
// parse single characters
char c = data[i];
if (c == '{' || c == '}' || c == ')' || c == '(' || c == '\'' || c == ':')
{
_Token = data.Substring(i, 1);
return (i + 1 < data.Length ? data.Substring(i + 1) : null);
}
// parse a regular word
while (i < data.Length)
{
c = data[i];
if (c <= 32 || c == '{' || c == '}' || c == ')' || c == '(' || c == '\'' || c == ':')
{
i--;
break;
}
i++;
}
if (i == data.Length)
{
_Token = data.Substring(i0, i - i0);
return null;
}
_Token = data.Substring(i0, i - i0 + 1);
return (i + 1 < data.Length ? data.Substring(i + 1) : null);
}
/// <summary>
/// COM_LoadFile
/// </summary>
public static byte[] LoadFile(string path)
{
// look for it in the filesystem or pack files
DisposableWrapper<BinaryReader> file;
int length = OpenFile(path, out file);
if (file == null)
return null;
byte[] result = new byte[length];
using (file)
{
Drawer.BeginDisc();
int left = length;
while (left > 0)
{
int count = file.Object.Read(result, length - left, left);
if (count == 0)
Sys.Error("COM_LoadFile: reading failed!");
left -= count;
}
Drawer.EndDisc();
}
return result;
}
/// <summary>
/// COM_LoadPackFile
/// Takes an explicit (not game tree related) path to a pak file.
/// Loads the header and directory, adding the files at the beginning
/// of the list so they override previous pack files.
/// </summary>
public static pack_t LoadPackFile(string packfile)
{
FileStream file = Sys.FileOpenRead(packfile);
if (file == null)
return null;
dpackheader_t header = Sys.ReadStructure<dpackheader_t>(file);
string id = Encoding.ASCII.GetString(header.id);
if (id != "PACK")
Sys.Error("{0} is not a packfile", packfile);
header.dirofs = LittleLong(header.dirofs);
header.dirlen = LittleLong(header.dirlen);
int numpackfiles = header.dirlen / Marshal.SizeOf(typeof(dpackfile_t));
if (numpackfiles > MAX_FILES_IN_PACK)
Sys.Error("{0} has {1} files", packfile, numpackfiles);
//if (numpackfiles != PAK0_COUNT)
// _IsModified = true; // not the original file
file.Seek(header.dirofs, SeekOrigin.Begin);
byte[] buf = new byte[header.dirlen];
if (file.Read(buf, 0, buf.Length) != buf.Length)
{
Sys.Error("{0} buffering failed!", packfile);
}
List<dpackfile_t> info = new List<dpackfile_t>(MAX_FILES_IN_PACK);
GCHandle handle = GCHandle.Alloc(buf, GCHandleType.Pinned);
try
{
IntPtr ptr = handle.AddrOfPinnedObject();
int count = 0, structSize = Marshal.SizeOf(typeof(dpackfile_t));
while (count < header.dirlen)
{
dpackfile_t tmp = (dpackfile_t)Marshal.PtrToStructure(ptr, typeof(dpackfile_t));
info.Add(tmp);
ptr = new IntPtr(ptr.ToInt64() + structSize);
count += structSize;
}
if (numpackfiles != info.Count)
{
Sys.Error("{0} directory reading failed!", packfile);
}
}
finally
{
handle.Free();
}
// crc the directory to check for modifications
//ushort crc;
//CRC.Init(out crc);
//for (int i = 0; i < buf.Length; i++)
// CRC.ProcessByte(ref crc, buf[i]);
//if (crc != PAK0_CRC)
// _IsModified = true;
buf = null;
// parse the directory
packfile_t[] newfiles = new packfile_t[numpackfiles];
for (int i = 0; i < numpackfiles; i++)
{
packfile_t pf = new packfile_t();
pf.name = Common.GetString(info[i].name);
pf.filepos = LittleLong(info[i].filepos);
pf.filelen = LittleLong(info[i].filelen);
newfiles[i] = pf;
}
pack_t pack = new pack_t(packfile, new BinaryReader(file, Encoding.ASCII), newfiles);
Con.Print("Added packfile {0} ({1} files)\n", packfile, numpackfiles);
return pack;
}
// COM_CopyFile
//
// Copies a file over from the net to the local cache, creating any directories
// needed. This is for the convenience of developers using ISDN from home.
static void CopyFile(string netpath, string cachepath)
{
using(Stream src = Sys.FileOpenRead(netpath), dest = Sys.FileOpenWrite(cachepath))
{
if (src == null)
{
Sys.Error("CopyFile: cannot open file {0}\n", netpath);
}
long remaining = src.Length;
string dirName = Path.GetDirectoryName(cachepath);
if (!Directory.Exists(dirName))
Directory.CreateDirectory(dirName);
byte[] buf = new byte[4096];
while (remaining > 0)
{
int count = buf.Length;
if (remaining < count)
count = (int)remaining;
src.Read(buf, 0, count);
dest.Write(buf, 0, count);
remaining -= count;
}
}
}
/// <summary>
/// COM_FindFile
/// Finds the file in the search path.
/// </summary>
static int FindFile(string filename, out DisposableWrapper<BinaryReader> file, bool duplicateStream)
{
file = null;
string cachepath = String.Empty;
//
// search through the path, one element at a time
//
foreach (searchpath_t sp in _SearchPaths)
{
// is the element a pak file?
if (sp.pack != null)
{
// look through all the pak file elements
pack_t pak = sp.pack;
foreach (packfile_t pfile in pak.files)
{
if (pfile.name.Equals(filename))
{
// found it!
Con.DPrint ("PackFile: {0} : {1}\n", sp.pack.filename, filename);
if (duplicateStream)
{
FileStream pfs = (FileStream)pak.stream.BaseStream;
FileStream fs = new FileStream(pfs.Name, FileMode.Open, FileAccess.Read, FileShare.Read);
file = new DisposableWrapper<BinaryReader>(new BinaryReader(fs, Encoding.ASCII), true);
}
else
{
file = new DisposableWrapper<BinaryReader>(pak.stream, false);
}
file.Object.BaseStream.Seek(pfile.filepos, SeekOrigin.Begin);
return pfile.filelen;
}
}
}
else
{
// check a file in the directory tree
if (!_StaticRegistered)
{
// if not a registered version, don't ever go beyond base
if (filename.IndexOfAny(_Slashes) != -1) // strchr (filename, '/') || strchr (filename,'\\'))
continue;
}
string netpath = sp.filename + "/" + filename; //sprintf (netpath, "%s/%s",search->filename, filename);
DateTime findtime = Sys.GetFileTime(netpath);
if (findtime == DateTime.MinValue)
continue;
// see if the file needs to be updated in the cache
if (String.IsNullOrEmpty(_CacheDir))// !com_cachedir[0])
{
cachepath = netpath; // strcpy(cachepath, netpath);
}
else
{
if (Sys.IsWindows)
{
if (netpath.Length < 2 || netpath[1] != ':')
cachepath = _CacheDir + netpath;
else
cachepath = _CacheDir + netpath.Substring(2);
}
else
{
cachepath = _CacheDir + netpath;
}
DateTime cachetime = Sys.GetFileTime(cachepath);
if (cachetime < findtime)
CopyFile(netpath, cachepath);
netpath = cachepath;
}
Con.DPrint("FindFile: {0}\n", netpath);
FileStream fs = Sys.FileOpenRead(netpath);
if (fs == null)
{
file = null;
return -1;
}
file = new DisposableWrapper<BinaryReader>(new BinaryReader(fs, Encoding.ASCII), true);
return (int)fs.Length;
}
}
Con.DPrint ("FindFile: can't find {0}\n", filename);
return -1;
}
// COM_OpenFile(char* filename, int* hndl)
// filename never has a leading slash, but may contain directory walks
// returns a handle and a length
// it may actually be inside a pak file
static int OpenFile(string filename, out DisposableWrapper<BinaryReader> file)
{
return FindFile(filename, out file, false);
}
// COM_FOpenFile(char* filename, FILE** file)
// If the requested file is inside a packfile, a new FILE * will be opened
// into the file.
public static int FOpenFile(string filename, out DisposableWrapper<BinaryReader> file)
{
return FindFile(filename, out file, true);
}
// COM_Path_f
static void Path_f()
{
Con.Print("Current search path:\n");
foreach (searchpath_t sp in _SearchPaths)
{
if (sp.pack != null)
{
Con.Print("{0} ({1} files)\n", sp.pack.filename, sp.pack.files.Length);
}
else
{
Con.Print("{0}\n", sp.filename);
}
}
}
// COM_CheckRegistered
//
// Looks for the pop.txt file and verifies it.
// Sets the "registered" cvar.
// Immediately exits out if an alternate game was attempted to be started without
// being registered.
static void CheckRegistered()
{
_StaticRegistered = false;
byte[] buf = LoadFile("gfx/pop.lmp");
if (buf == null || buf.Length < 256)
{
Con.Print("Playing shareware version.\n");
if (_IsModified)
Sys.Error("You must have the registered version to use modified games");
return;
}
ushort[] check = new ushort[buf.Length / 2];
Buffer.BlockCopy(buf, 0, check, 0, buf.Length);
for (int i = 0; i < 128; i++)
{
if (_Pop[i] != (ushort)_Converter.BigShort((short)check[i]))
Sys.Error ("Corrupted data file.");
}
Cvar.Set("cmdline", _Args);
Cvar.Set("registered", "1");
_StaticRegistered = true;
Con.Print("Playing registered version.\n");
}
// COM_InitFilesystem
static void InitFileSystem()
{
//
// -basedir <path>
// Overrides the system supplied base directory (under GAMENAME)
//
string basedir = String.Empty;
int i = CheckParm("-basedir");
if ((i > 0) && (i < _Argv.Length - 1))
{
basedir = _Argv[i + 1];
}
else
{
basedir = Host.Params.basedir;
}
if (!String.IsNullOrEmpty(basedir))
{
basedir.TrimEnd('\\', '/');
}
//
// -cachedir <path>
// Overrides the system supplied cache directory (NULL or /qcache)
// -cachedir - will disable caching.
//
i = CheckParm ("-cachedir");
if ((i > 0) && (i < _Argv.Length - 1))
{
if (_Argv[i + 1][0] == '-')
_CacheDir = String.Empty;
else
_CacheDir = _Argv[i + 1];
}
else if (!String.IsNullOrEmpty(Host.Params.cachedir))
{
_CacheDir = Host.Params.cachedir;
}
else
{
_CacheDir = String.Empty;
}
//
// start up with GAMENAME by default (id1)
//
AddGameDirectory(basedir + "/" + QDef.GAMENAME);
if (HasParam("-rogue"))
AddGameDirectory(basedir + "/rogue");
if (HasParam("-hipnotic"))
AddGameDirectory (basedir + "/hipnotic");
//
// -game <gamedir>
// Adds basedir/gamedir as an override game
//
i = CheckParm ("-game");
if ((i > 0) && (i < _Argv.Length - 1))
{
_IsModified = true;
AddGameDirectory (basedir + "/" + _Argv[i + 1]);
}
//
// -path <dir or packfile> [<dir or packfile>] ...
// Fully specifies the exact serach path, overriding the generated one
//
i = CheckParm ("-path");
if (i > 0)
{
_IsModified = true;
_SearchPaths.Clear();
while (++i < _Argv.Length)
{
if (String.IsNullOrEmpty(_Argv[i]) || _Argv[i][0] == '+' || _Argv[i][0] == '-')
break;
_SearchPaths.Insert(0, new searchpath_t(_Argv[i]));
}
}
}
// COM_AddGameDirectory
//
// Sets com_gamedir, adds the directory to the head of the path,
// then loads and adds pak1.pak pak2.pak ...
static void AddGameDirectory(string dir)
{
_GameDir = dir;
//
// add the directory to the search path
//
_SearchPaths.Insert(0, new searchpath_t(dir));
//
// add any pak files in the format pak0.pak pak1.pak, ...
//
for (int i = 0; ; i++)
{
string pakfile = String.Format("{0}/pak{1}.pak", dir, i);
pack_t pak = LoadPackFile(pakfile);
if (pak == null)
break;
_SearchPaths.Insert(0, new searchpath_t(pak));
}
}
public static int atoi(string s)
{
if (String.IsNullOrEmpty(s))
return 0;
int sign = 1;
int result = 0;
int offset = 0;
if (s.StartsWith("-"))
{
sign = -1;
offset++;
}
int i = -1;
if (s.Length > 2)
{
i = s.IndexOf("0x", offset, 2);
if (i == -1)
{
i = s.IndexOf("0X", offset, 2);
}
}
if (i == offset)
{
int.TryParse(s.Substring(offset + 2), System.Globalization.NumberStyles.HexNumber, null, out result);
}
else
{
i = s.IndexOf('\'', offset, 1);
if (i != -1)
{
result = (byte)s[i + 1];
}
else
int.TryParse(s.Substring(offset), out result);
}
return sign * result;
}
public static float atof(string s)
{
float v;
float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out v);
return v;
}
public static bool SameText(string a, string b)
{
return (String.Compare(a, b, true) == 0);
}
public static bool SameText(string a, string b, int count)
{
return (String.Compare(a, 0, b, 0, count, true) == 0);
}
public static short BigShort(short l)
{
return _Converter.BigShort(l);
}
public static short LittleShort(short l)
{
return _Converter.LittleShort(l);
}
public static int BigLong(int l)
{
return _Converter.BigLong(l);
}
public static int LittleLong(int l)
{
return _Converter.LittleLong(l);
}
public static float BigFloat(float l)
{
return _Converter.BigFloat(l);
}
public static float LittleFloat(float l)
{
return _Converter.LittleFloat(l);
}
public static Vector3 LittleVector(Vector3 src)
{
return new Vector3(_Converter.LittleFloat(src.X),
_Converter.LittleFloat(src.Y), _Converter.LittleFloat(src.Z));
}
public static Vector3 LittleVector3(float[] src)
{
return new Vector3(_Converter.LittleFloat(src[0]),
_Converter.LittleFloat(src[1]), _Converter.LittleFloat(src[2]));
}
public static Vector4 LittleVector4(float[] src, int offset)
{
return new Vector4(_Converter.LittleFloat(src[offset + 0]),
_Converter.LittleFloat(src[offset + 1]),
_Converter.LittleFloat(src[offset + 2]),
_Converter.LittleFloat(src[offset + 3]));
}
public static void FillArray<T>(T[] dest, T value)
{
int elementSizeInBytes = Marshal.SizeOf(typeof(T));
int blockSize = Math.Min(dest.Length, 4096 / elementSizeInBytes);
for (int i = 0; i < blockSize; i++)
dest[i] = value;
int blockSizeInBytes = blockSize * elementSizeInBytes;
int offset = blockSizeInBytes;
int lengthInBytes = Buffer.ByteLength(dest);
while (true)// offset + blockSize <= lengthInBytes)
{
int left = lengthInBytes - offset;
if (left < blockSizeInBytes)
blockSizeInBytes = left;
if (blockSizeInBytes <= 0)
break;
Buffer.BlockCopy(dest, 0, dest, offset, blockSizeInBytes);
offset += blockSizeInBytes;
}
}
public static void ZeroArray<T>(T[] dest, int startIndex, int length)
{
int elementBytes = Marshal.SizeOf(typeof(T));
int offset = startIndex * elementBytes;
int sizeInBytes = dest.Length * elementBytes - offset;
while (true)
{
int blockSize = sizeInBytes - offset;
if (blockSize > ZeroBytes.Length)
blockSize = ZeroBytes.Length;
if (blockSize <= 0)
break;
Buffer.BlockCopy(ZeroBytes, 0, dest, offset, blockSize);
offset += blockSize;
}
}
public static string Copy(string src, int maxLength)
{
if (src == null)
return null;
return (src.Length > maxLength ? src.Substring(1, maxLength) : src);
}
public static void Copy(float[] src, out Vector3 dest)
{
dest.X = src[0];
dest.Y = src[1];
dest.Z = src[2];
}
public static void Copy(ref Vector3 src, float[] dest)
{
dest[0] = src.X;
dest[1] = src.Y;
dest[2] = src.Z;
}
public static string GetString(byte[] src)
{
int count = 0;
while(count < src.Length && src[count] != 0)
count++;
return (count > 0 ? Encoding.ASCII.GetString(src, 0, count) : String.Empty);
}
public static Vector3 ToVector(ref v3f v)
{
return new Vector3(v.x, v.y, v.z);
}
public static void WriteInt(byte[] dest, int offset, int value)
{
Union4b u = Union4b.Empty;
u.i0 = value;
dest[offset + 0] = u.b0;
dest[offset + 1] = u.b1;
dest[offset + 2] = u.b2;
dest[offset + 3] = u.b3;
}
}
enum GameKind
{
StandardQuake, Rogue, Hipnotic
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
class link_t
{
link_t _Prev, _Next;
object _Owner;
public link_t Prev
{
get { return _Prev; }
}
public link_t Next
{
get { return _Next; }
}
public object Owner
{
get { return _Owner; }
}
public link_t(object owner)
{
_Owner = owner;
}
public void Clear()
{
_Prev = _Next = this;
}
public void ClearToNulls()
{
_Prev = _Next = null;
}
public void Remove()
{
_Next._Prev = _Prev;
_Prev._Next = _Next;
_Next = null;
_Prev = null;
}
public void InsertBefore(link_t before)
{
_Next = before;
_Prev = before._Prev;
_Prev._Next = this;
_Next._Prev = this;
}
public void InsertAfter(link_t after)
{