Source

quake3 / code / macosx / macosx_sys.m

Full commit
  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
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.

This file is part of Quake III Arena source code.

Quake III Arena source code 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.

Quake III Arena source code 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 Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
===========================================================================
*/
#import "../client/client.h"
#import "macosx_local.h"

#import "dlfcn.h"
#import "Q3Controller.h"

#import <AppKit/AppKit.h>
#import <IOKit/IOKitLib.h>
#import <IOKit/IOBSD.h>
#import <IOKit/storage/IOCDMedia.h>
#import <mach/mach_error.h>

#import <sys/types.h>
#import <unistd.h>
#import <sys/param.h>
#import <sys/mount.h>
#import <sys/sysctl.h>

#ifdef OMNI_TIMER
#import "macosx_timers.h"
#endif

qboolean stdin_active = qfalse;

//===========================================================================

int main(int argc, const char *argv[]) {
#ifdef DEDICATED
    Q3Controller *controller;
    
    stdin_active = qtrue;
    controller = [[Q3Controller alloc] init];
    [controller quakeMain];
    return 0;
#else
    return NSApplicationMain(argc, argv);
#endif
}

//===========================================================================

/*
=================
Sys_UnloadDll

=================
*/
void Sys_UnloadDll( void *dllHandle ) {
	if ( !dllHandle ) {
		return;
	}
	dlclose( dllHandle );
}

/*
=================
Sys_LoadDll

Used to load a development dll instead of a virtual machine
=================
*/
extern char		*FS_BuildOSPath( const char *base, const char *game, const char *qpath );

void	* QDECL Sys_LoadDll( const char *name, char *fqpath , int (QDECL **entryPoint)(int, ...),
				  int (QDECL *systemcalls)(int, ...) ) {
    void *libHandle;
    void	(*dllEntry)( int (*syscallptr)(int, ...) );
    NSString *bundlePath, *libraryPath;
    const char *path;
    
	// TTimo
	// I don't understand the search strategy here. How can the Quake3 bundle know about the location
	// of the other bundles? is that configured somewhere in XCode?
	/*
    bundlePath = [[NSBundle mainBundle] pathForResource: [NSString stringWithCString: name] ofType: @"bundle"];
    libraryPath = [NSString stringWithFormat: @"%@/Contents/MacOS/%s", bundlePath, name];
	*/	
	libraryPath = [NSString stringWithFormat: @"%s.bundle/Contents/MacOS/%s", name, name];
    if (!libraryPath)
        return NULL;
    
    path = [libraryPath cString];
    Com_Printf("Loading '%s'.\n", path);
    libHandle = dlopen( [libraryPath cString], RTLD_LAZY );
    if (!libHandle) {
        libHandle = dlopen( name, RTLD_LAZY );
        if (!libHandle) {
            Com_Printf("Error loading dll: %s\n", dlerror());
            return NULL;
        }
    }

    dllEntry = dlsym( libHandle, "_dllEntry" );
    if (!dllEntry) {
        Com_Printf("Error loading dll:  No dllEntry symbol.\n");
        dlclose(libHandle);
        return NULL;
    }
    
    *entryPoint = dlsym( libHandle, "_vmMain" );
    if (!*entryPoint) {
        Com_Printf("Error loading dll:  No vmMain symbol.\n");
        dlclose(libHandle);
        return NULL;
    }
    
    dllEntry(systemcalls);
    return libHandle;
}

//===========================================================================

char *Sys_GetClipboardData(void) // FIXME
{
    NSPasteboard *pasteboard;
    NSArray *pasteboardTypes;

    pasteboard = [NSPasteboard generalPasteboard];
    pasteboardTypes = [pasteboard types];
    if ([pasteboardTypes containsObject:NSStringPboardType]) {
        NSString *clipboardString;

        clipboardString = [pasteboard stringForType:NSStringPboardType];
        if (clipboardString && [clipboardString length] > 0) {
            return strdup([clipboardString cString]);
        }
    }
    return NULL;
}

char *Sys_GetWholeClipboard ( void )
{
    return NULL;
}

void Sys_SetClipboard (const char *contents)
{
}


/*
==================
Sys_FunctionCheckSum
==================
*/
int Sys_FunctionCheckSum(void *f1) {
	return 0;
}

/*
==================
Sys_MonkeyShouldBeSpanked
==================
*/
int Sys_MonkeyShouldBeSpanked( void ) {
	return 0;
}

//===========================================================================

void Sys_BeginProfiling(void)
{
}

void Sys_EndProfiling(void)
{
}

//===========================================================================

/*
================
Sys_Init

The cvar and file system has been setup, so configurations are loaded
================
*/
void Sys_Init(void)
{
#ifdef OMNI_TIMER
    InitializeTimers();
    OTStackPushRoot(rootNode);
#endif

    NET_Init();
    Sys_InitInput();	
}

/*
=================
Sys_Shutdown
=================
*/
void Sys_Shutdown(void)
{
    Com_Printf( "----- Sys_Shutdown -----\n" );
    Sys_EndProfiling();
    Sys_ShutdownInput();	
    Com_Printf( "------------------------\n" );
}

void Sys_Error(const char *error, ...)
{
    va_list argptr;
    NSString *formattedString;

    Sys_Shutdown();

    va_start(argptr,error);
    formattedString = [[NSString alloc] initWithFormat:[NSString stringWithCString:error] arguments:argptr];
    va_end(argptr);

    NSLog(@"Sys_Error: %@", formattedString);
    NSRunAlertPanel(@"Quake 3 Error", formattedString, nil, nil, nil);

    Sys_Quit();
}

void Sys_Quit(void)
{
    Sys_Shutdown();
    [NSApp terminate:nil];
}

/*
================
Sys_Print

This is called for all console output, even if the game is running
full screen and the dedicated console window is hidden.
================
*/

char *ansiColors[8] =
	{ "\033[30m" ,	/* ANSI Black */
	  "\033[31m" ,	/* ANSI Red */
	  "\033[32m" ,	/* ANSI Green */
	  "\033[33m" ,  /* ANSI Yellow */
	  "\033[34m" ,	/* ANSI Blue */
	  "\033[36m" ,  /* ANSI Cyan */
	  "\033[35m" ,	/* ANSI Magenta */
	  "\033[37m" }; /* ANSI White */
	  
void Sys_Print(const char *text)
{
#if 0
	/* Okay, this is a stupid hack, but what the hell, I was bored. ;) */
	const char *scan = text;
	int index;
	
	/* Make sure terminal mode is reset at the start of the line... */
	fputs("\033[0m", stdout);
	
	while(*scan) {
		/* See if we have a color control code.  If so, snarf the character, 
		print what we have so far, print the ANSI Terminal color code,
		skip over the color control code and continue */
		if(Q_IsColorString(scan)) {
			index = ColorIndex(scan[1]);
			
			/* Flush current message */
			if(scan != text) {
				fwrite(text, scan - text, 1, stdout);
			}
			
			/* Write ANSI color code */
			fputs(ansiColors[index], stdout);
			
			/* Reset search */
			text = scan+2;
			scan = text;
			continue;			
		}
		scan++;
	}

	/* Flush whatever's left */
	fputs(text, stdout);

	/* Make sure terminal mode is reset at the end of the line too... */
	fputs("\033[0m", stdout);

#else
    fputs(text, stdout);
#endif	
}



/*
================
Sys_CheckCD

Return true if the proper CD is in the drive
================
*/

qboolean Sys_ObjectIsCDRomDevice(io_object_t object)
{
    CFStringRef value;
    kern_return_t krc;
    CFDictionaryRef properties;
    qboolean isCDROM = qfalse;
    io_iterator_t parentIterator;
    io_object_t parent;
    
    krc = IORegistryEntryCreateCFProperties(object, &properties, kCFAllocatorDefault, (IOOptionBits)0);
    if (krc != KERN_SUCCESS) {
        fprintf(stderr, "IORegistryEntryCreateCFProperties returned 0x%08x -- %s\n", krc, mach_error_string(krc));
        return qfalse;
    }

    //NSLog(@"properties = %@", properties);
    
    // See if this is a CD-ROM
    value = CFDictionaryGetValue(properties, CFSTR(kIOCDMediaTypeKey));
    if (value && CFStringCompare(value, CFSTR("CD-ROM"), 0) == kCFCompareEqualTo)
        isCDROM = qtrue;
    CFRelease(properties);

    // If it isn't check each of its parents.  It seems that the parent enumerator only returns the immediate parent.  Maybe the plural indicates that an object can have multiple direct parents.  So, we'll call ourselves recursively for each parent.
    if (!isCDROM) {
        krc = IORegistryEntryGetParentIterator(object, kIOServicePlane, &parentIterator);
        if (krc != KERN_SUCCESS) {
            fprintf(stderr, "IOServiceGetMatchingServices returned 0x%08x -- %s\n",
                    krc, mach_error_string(krc));
        } else {
            while (!isCDROM && (parent = IOIteratorNext(parentIterator))) {
                if (Sys_ObjectIsCDRomDevice(parent))
                    isCDROM = qtrue;
                IOObjectRelease(parent);
            }
    
            IOObjectRelease(parentIterator);
        }
    }
    
    //NSLog(@"Sys_ObjectIsCDRomDevice -> %d", isCDROM);
    return isCDROM;
}

qboolean Sys_IsCDROMDevice(const char *deviceName)
{
    kern_return_t krc;
    io_iterator_t deviceIterator;
    mach_port_t masterPort;
    io_object_t object;
    qboolean isCDROM = qfalse;
    
    krc = IOMasterPort(bootstrap_port, &masterPort);
    if (krc != KERN_SUCCESS) {
        fprintf(stderr, "IOMasterPort returned 0x%08x -- %s\n", krc, mach_error_string(krc));
        return qfalse;
    }

    // Get an iterator for this BSD device.  If it is a CD, it will likely only be one partition of the larger CD-ROM device.
    krc = IOServiceGetMatchingServices(masterPort,
                                       IOBSDNameMatching(masterPort, 0, deviceName),
                                       &deviceIterator);
    if (krc != KERN_SUCCESS) {
        fprintf(stderr, "IOServiceGetMatchingServices returned 0x%08x -- %s\n",
                krc, mach_error_string(krc));
        return qfalse;
    }

    while (!isCDROM && (object = IOIteratorNext(deviceIterator))) {
        if (Sys_ObjectIsCDRomDevice(object)) {
            isCDROM = qtrue;
        }
        IOObjectRelease(object);
    }
    
    IOObjectRelease(deviceIterator);

    //NSLog(@"Sys_IsCDROMDevice -> %d", isCDROM);
    return isCDROM;
}

qboolean        Sys_CheckCD( void )
{
    // DO NOT just return success here if we have a library directory.
    // Actually look for the CD.

    // We'll look through the actual mount points rather than just looking
    // for a particular directory since (a) the mount point may change
    // between OS version (/foo in Public Beta, /Volumes/foo after Public Beta)
    // and (b) this way someone can't just create a directory and warez the files.
    
    unsigned int mountCount;
    struct statfs  *mounts;
    
    mountCount = getmntinfo(&mounts, MNT_NOWAIT);
    if (mountCount <= 0) {
        perror("getmntinfo");
#if 1 // Q3:TA doesn't need a CD, but we still need to locate it to allow for partial installs
        return qtrue;
#else
        return qfalse;
#endif
    }
    
    while (mountCount--) {
        const char *lastComponent;
        
        if ((mounts[mountCount].f_flags & MNT_RDONLY) != MNT_RDONLY) {
            // Should have been a read only CD... this isn't it
            continue;
        }
        
        if ((mounts[mountCount].f_flags & MNT_LOCAL) != MNT_LOCAL) {
            // Should have been a local filesystem
            continue;
        }
        
        lastComponent = strrchr(mounts[mountCount].f_mntonname, '/');
        if (!lastComponent) {
            // No slash in the mount point!  How is that possible?
            continue;
        }
        
        // Skip the slash and look for the game name
        lastComponent++;
        if ((strcasecmp(lastComponent, "Quake3") != 0)) {
            continue;
        }

            
#if 0
        fprintf(stderr, "f_bsize: %d\n", mounts[mountCount].f_bsize);
        fprintf(stderr, "f_blocks: %d\n", mounts[mountCount].f_blocks);
        fprintf(stderr, "type: %d\n", mounts[mountCount].f_type);
        fprintf(stderr, "flags: %d\n", mounts[mountCount].f_flags);
        fprintf(stderr, "fstype: %s\n", mounts[mountCount].f_fstypename);
        fprintf(stderr, "f_mntonname: %s\n", mounts[mountCount].f_mntonname);
        fprintf(stderr, "f_mntfromname: %s\n", mounts[mountCount].f_mntfromname);
        fprintf(stderr, "\n\n");
#endif

        lastComponent = strrchr(mounts[mountCount].f_mntfromname, '/');
        if (!lastComponent) {
            // No slash in the device name!  How is that possible?
            continue;
        }
        lastComponent++;
        if (!Sys_IsCDROMDevice(lastComponent))
            continue;

        // This looks good
        Sys_SetDefaultCDPath(mounts[mountCount].f_mntonname);
        return qtrue;
    }
    
#if 1 // Q3:TA doesn't need a CD, but we still need to locate it to allow for partial installs
    return qtrue;
#else
    return qfalse;
#endif
}


//===================================================================

void Sys_BeginStreamedFile( fileHandle_t f, int readAhead ) {
}

void Sys_EndStreamedFile( fileHandle_t f ) {
}

int Sys_StreamedRead( void *buffer, int size, int count, fileHandle_t f ) {
	return FS_Read( buffer, size * count, f );
}

void Sys_StreamSeek( fileHandle_t f, int offset, int origin ) {
	FS_Seek( f, offset, origin );
}


void OutputDebugString(char * s)
{
#ifdef DEBUG
    fprintf(stderr, "%s", s);
#endif
}

/*
==================
Sys_LowPhysicalMemory()
==================
*/
#define MEM_THRESHOLD 96*1024*1024

qboolean Sys_LowPhysicalMemory()
{
    return NSRealMemoryAvailable() <= MEM_THRESHOLD;
}

static unsigned int _Sys_ProcessorCount = 0;

unsigned int Sys_ProcessorCount()
{
    if (!_Sys_ProcessorCount) {
        int name[] = {CTL_HW, HW_NCPU};
        size_t size;
    
        size = sizeof(_Sys_ProcessorCount);
        if (sysctl(name, 2, &_Sys_ProcessorCount, &size, NULL, 0) < 0) {
            perror("sysctl");
            _Sys_ProcessorCount = 1;
        } else {
            Com_Printf("System processor count is %d\n", _Sys_ProcessorCount);
        }
    }
    
    return _Sys_ProcessorCount;
}