diff --git a/.gitignore b/.gitignore index 8974296db..b2e11ecb3 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ *.la *.lo *.obj +*.a *.o *~ autom4te.cache/ @@ -12,6 +13,7 @@ autom4te.cache/ ChangeLog Makefile Makefile.in +core # / /aclocal.m4 @@ -108,6 +110,7 @@ Makefile.in # /libs/ # /libs/audio/ +/libs/audio/testsound # /libs/audio/cd/ @@ -185,7 +188,6 @@ Makefile.in /nq/include/stamp-h # /nq/source/ -/nq/source/*.a /nq/source/*.d /nq/source/fbset_modes_l.c /nq/source/fbset_modes_y.c @@ -212,7 +214,6 @@ Makefile.in /qtv/include/config.h # /qtv/source/ -/qtv/source/*.a /qtv/source/*.d /qtv/source/*.i /qtv/source/*.s @@ -227,7 +228,6 @@ Makefile.in /qw/include/config.h # /qw/source/ -/qw/source/*.a /qw/source/*.d /qw/source/*.i /qw/source/*.s @@ -316,6 +316,7 @@ Makefile.in /tools/Forge/Bundles/MapEdit/shared_profile_obj /tools/Forge/Bundles/MapEdit/obj /tools/Forge/Bundles/MapEdit/*.forgeb +/tools/Forge/Bundles/MapEdit/*.app # /tools/bsp2img/ /tools/bsp2img/bsp2img diff --git a/include/QF/script.h b/include/QF/script.h index 6f9ae5a96..ee69894f8 100644 --- a/include/QF/script.h +++ b/include/QF/script.h @@ -88,6 +88,11 @@ qboolean Script_GetToken (script_t *script, qboolean crossline); */ void Script_UngetToken (script_t *script); +/** Return a pointer to the current token. + \param script The script_t object being parsed +*/ +const char *Script_Token (script_t *token); + //@} #endif//__QF_script_h diff --git a/include/QF/wadfile.h b/include/QF/wadfile.h index 8d37859a0..db690e1f6 100644 --- a/include/QF/wadfile.h +++ b/include/QF/wadfile.h @@ -56,20 +56,20 @@ #define TYP_MIPTEX 68 typedef struct qpic_s { - int width, height; + int32_t width, height; byte data[]; // variably sized } qpic_t; typedef struct wadinfo_s { char id[4]; // should be WAD2 or 2DAW - int numlumps; - int infotableofs; + int32_t numlumps; + int32_t infotableofs; } wadinfo_t; typedef struct lumpinfo_s { - int filepos; - int disksize; - int size; // uncompressed + int32_t filepos; + int32_t disksize; + int32_t size; // uncompressed byte type; byte compression; byte pad1, pad2; diff --git a/libs/util/script.c b/libs/util/script.c index 4513f1cd1..6f8a65f57 100644 --- a/libs/util/script.c +++ b/libs/util/script.c @@ -157,9 +157,16 @@ Script_GetToken (script_t *script, qboolean crossline) dstring_copysubstr (script->token, token_p, script->p - token_p); script->p++; } else { + const char *single = "{}()':"; + token_p = script->p; - while (*script->p && !isspace ((unsigned char) *script->p)) + if (strchr (single, *script->p)) { script->p++; + } else { + while (*script->p && !isspace ((unsigned char) *script->p) + && !strchr (single, *script->p)) + script->p++; + } dstring_copysubstr (script->token, token_p, script->p - token_p); } @@ -171,3 +178,9 @@ Script_UngetToken (script_t *script) { script->unget = true; } + +VISIBLE const char * +Script_Token (script_t *script) +{ + return script->token->str; +} diff --git a/libs/util/wadfile.c b/libs/util/wadfile.c index 0599e5abc..c63106c62 100644 --- a/libs/util/wadfile.c +++ b/libs/util/wadfile.c @@ -61,19 +61,20 @@ static __attribute__ ((used)) const char rcsid[] = static uintptr_t wad_get_hash (void *l, void *unused) { - char name[16]; + char name[17]; int i; for (i = 0; i < 16; i++) name[i] = tolower (((lumpinfo_t *) l)->name[i]); + name[16] = 0; return Hash_String (name); } static int wad_compare (void *la, void *lb, void *unused) { - return strcasecmp (((lumpinfo_t *) la)->name, - ((lumpinfo_t *) lb)->name) == 0; + return strncasecmp (((lumpinfo_t *) la)->name, + ((lumpinfo_t *) lb)->name, 16) == 0; } VISIBLE wad_t * diff --git a/tools/Forge/Bundles/MainPrefs/MainPrefs.m b/tools/Forge/Bundles/MainPrefs/MainPrefs.m index e488b2cb7..feb794a81 100644 --- a/tools/Forge/Bundles/MainPrefs/MainPrefs.m +++ b/tools/Forge/Bundles/MainPrefs/MainPrefs.m @@ -38,6 +38,7 @@ static const char rcsid[] = #include #include #include +#include #include #include diff --git a/tools/Forge/Bundles/MapEdit/Brush.h b/tools/Forge/Bundles/MapEdit/Brush.h deleted file mode 100644 index e1dff67ec..000000000 --- a/tools/Forge/Bundles/MapEdit/Brush.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef Brush_h -#define Brush_h - -#include -#include "SetBrush.h" -#include "EditWindow.h" - -extern id brush_i; - -extern BOOL brushdraw; // YES when drawing cutbrushes and ents - -@interface Brush : SetBrush -{ - id cutbrushes_i; - id cutentities_i; - boolean updatemask[MAXBRUSHVERTEX]; - BOOL dontdraw; // for modal instance loops - BOOL deleted; // when not visible at all -} - -- init; - -- initFromSetBrush: br; - -- deselect; -- (BOOL)isSelected; - -- (BOOL)XYmouseDown: (NSPoint *)pt; // return YES if brush handled -- (BOOL)ZmouseDown: (NSPoint *)pt; // return YES if brush handled - -- _keyDown:(NSEvent *)theEvent; - -- (NSPoint)centerPoint; // for camera flyby mode - -- InstanceSize; -- XYDrawSelf; -- ZDrawSelf; -- CameraDrawSelf; - -- flipHorizontal: sender; -- flipVertical: sender; -- rotate90: sender; - -- makeTall: sender; -- makeShort: sender; -- makeWide: sender; -- makeNarrow: sender; - -- placeEntity: sender; - -- cut: sender; -- copy: sender; - -- addBrush; - -@end - -#define Brush_h diff --git a/tools/Forge/Bundles/MapEdit/CameraView.h b/tools/Forge/Bundles/MapEdit/CameraView.h index a8ac5dd65..015e8d849 100644 --- a/tools/Forge/Bundles/MapEdit/CameraView.h +++ b/tools/Forge/Bundles/MapEdit/CameraView.h @@ -1,61 +1,76 @@ +#ifndef CameraView_h +#define CameraView_h + #include -#include "mathlib.h" + +#include "QF/mathlib.h" + #include "SetBrush.h" -extern id cameraview_i; +#include "render.h" -extern byte renderlist[1024*1024*4]; +extern id cameraview_i; -void CameraMoveto(vec3_t p); -void CameraLineto(vec3_t p); +extern byte renderlist[1024 * 1024 * 4]; -extern BOOL timedrawing; +void CameraMoveto (vec3_t p); +void CameraLineto (vec3_t p); -@interface CameraView : NSView +extern BOOL timedrawing; + +@interface CameraView: NSView { - float xa, ya, za; - float move; - - float *zbuffer; - unsigned *imagebuffer; - - BOOL angleChange; // JR 6.8.95 - - vec3_t origin; - vec3_t matrix[3]; - - NSPoint dragspot; - - drawmode_t drawmode; - + float xa, ya, za; + float move; + + float *zbuffer; + unsigned *imagebuffer; + + BOOL angleChange; // JR 6.8.95 + + vec3_t origin; + vec3_t matrix[3]; + + NSPoint dragspot; + + drawmode_t drawmode; + + NSBezierPath *xycamera; + NSBezierPath *xycamera_aim; + NSBezierPath *zcamera; + // UI links - id mode_radio_i; - + id mode_radio_i; } -- setXYOrigin: (NSPoint *)pt; -- setZOrigin: (float)pt; +- (id) setXYOrigin: (NSPoint *)pt; +- (id) setZOrigin: (float)pt; -- setOrigin: (vec3_t)org angle: (float)angle; -- getOrigin: (vec3_t)org; +- (id) setOrigin: (vec3_t)org + angle: (float)angle; -- (float)yawAngle; +- (id) getOrigin: (vec3_t)org; -- matrixFromAngles; -- _keyDown: (NSEvent *)theEvent; +- (float) yawAngle; -- drawMode: sender; -- setDrawMode: (drawmode_t)mode; +- (id) matrixFromAngles; +- (id) _keyDown: (NSEvent *)theEvent; -- homeView: sender; +- (id) drawMode: sender; +- (id) setDrawMode: (drawmode_t)mode; -- XYDrawSelf; // for drawing viewpoint in XY view -- ZDrawSelf; // for drawing viewpoint in XY view -- (BOOL)XYmouseDown: (NSPoint *)pt flags:(int)flags; // return YES if brush handled -- (BOOL)ZmouseDown: (NSPoint *)pt flags:(int)flags; // return YES if brush handled +- (id) homeView: sender; -- upFloor:sender; -- downFloor: sender; +- (void) XYDrawSelf; // for drawing viewpoint in XY view +- (void) ZDrawSelf; // for drawing viewpoint in XY view +- (BOOL) XYmouseDown: (NSPoint *)pt // return YES if brush handled + flags: (int)flags; + +- (BOOL) ZmouseDown: (NSPoint *)pt // return YES if brush handled + flags: (int)flags; + +- (id) upFloor: sender; +- (id) downFloor: sender; @end - +#endif // CameraView_h diff --git a/tools/Forge/Bundles/MapEdit/CameraView.m b/tools/Forge/Bundles/MapEdit/CameraView.m index 48d29a840..05f807d53 100644 --- a/tools/Forge/Bundles/MapEdit/CameraView.m +++ b/tools/Forge/Bundles/MapEdit/CameraView.m @@ -1,55 +1,103 @@ -#include "qedefs.h" +#include "QF/sys.h" -id cameraview_i; +#import +#include "CameraView.h" +#include "Map.h" +#include "QuakeEd.h" +#include "XYView.h" +#include "ZView.h" -BOOL timedrawing = 0; +id cameraview_i; +extern NSBezierPath *path; + +BOOL timedrawing = 0; @implementation CameraView - /* ================== initWithFrame: ================== */ -- initWithFrame:(NSRect)frameRect +- (id) initWithFrame: (NSRect)frameRect { - int size; - + int size; + [super initWithFrame: frameRect]; - + cameraview_i = self; - + xa = ya = za = 0; - + [self matrixFromAngles]; - + origin[0] = 64; origin[1] = 64; origin[2] = 48; - + move = 16; - + size = _bounds.size.width * _bounds.size.height; - zbuffer = malloc (size*4); - imagebuffer = malloc (size*4); - + zbuffer = malloc (size * 4); + imagebuffer = malloc (size * 4); + return self; } -- setXYOrigin: (NSPoint *)pt +- (BOOL) isOpaque +{ + return YES; +} + +- (void) awakeFromNib +{ + NSBezierPath *path; + + path = zcamera = [NSBezierPath new]; + [path setLineWidth: 0.3]; + [path moveToPoint: NSMakePoint (-16, 0)]; + [path relativeLineToPoint: NSMakePoint (16, 8)]; + [path relativeLineToPoint: NSMakePoint (16, -8)]; + [path relativeLineToPoint: NSMakePoint (-16, -8)]; + [path relativeLineToPoint: NSMakePoint (-16, 8)]; + [path relativeLineToPoint: NSMakePoint (32, 0)]; + [path moveToPoint: NSMakePoint (-15, -47)]; + [path relativeLineToPoint: NSMakePoint (29, 0)]; + [path relativeLineToPoint: NSMakePoint (0, 54)]; + [path relativeLineToPoint: NSMakePoint (-29, 0)]; + [path relativeLineToPoint: NSMakePoint (0, -54)]; + + path = xycamera = [NSBezierPath new]; + [path setLineWidth: 0.3]; + [path moveToPoint: NSMakePoint (-16, 0)]; + [path relativeLineToPoint: NSMakePoint (16, 8)]; + [path relativeLineToPoint: NSMakePoint (16, -8)]; + [path relativeLineToPoint: NSMakePoint (-16, -8)]; + [path relativeLineToPoint: NSMakePoint (-16, 8)]; + [path relativeLineToPoint: NSMakePoint (32, 0)]; + + path = xycamera_aim = [NSBezierPath new]; + [path setLineWidth: 0.3]; + [path moveToPoint: NSMakePoint (0, 0)]; + [path relativeLineToPoint: NSMakePoint (45, 45)]; + [path moveToPoint: NSMakePoint (0, 0)]; + [path relativeLineToPoint: NSMakePoint (45, -45)]; +} + +- (id) setXYOrigin: (NSPoint *)pt { origin[0] = pt->x; origin[1] = pt->y; return self; } -- setZOrigin: (float)pt +- (id) setZOrigin: (float)pt { origin[2] = pt; return self; } -- setOrigin: (vec3_t)org angle: (float)angle +- (id) setOrigin: (vec3_t)org + angle: (float)angle { VectorCopy (org, origin); ya = angle; @@ -57,44 +105,42 @@ initWithFrame: return self; } -- getOrigin: (vec3_t)org +- (id) getOrigin: (vec3_t)org { VectorCopy (origin, org); return self; } -- (float)yawAngle +- (float) yawAngle { return ya; } -- upFloor:sender +- (id) upFloor: sender { sb_floor_dir = 1; sb_floor_dist = 99999; - [map_i makeAllPerform: @selector(feetToFloor)]; - if (sb_floor_dist == 99999) - { - qprintf ("already on top floor"); + [map_i makeAllPerform: @selector (feetToFloor)]; + if (sb_floor_dist == 99999) { + Sys_Printf ("already on top floor\n"); return self; } - qprintf ("up floor"); + Sys_Printf ("up floor\n"); origin[2] += sb_floor_dist; [quakeed_i updateCamera]; return self; } -- downFloor: sender +- (id) downFloor: sender { sb_floor_dir = -1; sb_floor_dist = -99999; - [map_i makeAllPerform: @selector(feetToFloor)]; - if (sb_floor_dist == -99999) - { - qprintf ("already on bottom floor"); + [map_i makeAllPerform: @selector (feetToFloor)]; + if (sb_floor_dist == -99999) { + Sys_Printf ("already on bottom floor\n"); return self; } - qprintf ("down floor"); + Sys_Printf ("down floor\n"); origin[2] += sb_floor_dist; [quakeed_i updateCamera]; return self; @@ -113,30 +159,30 @@ UI TARGETS homeView ============ */ -- homeView: sender +- (id) homeView: sender { xa = za = 0; - + [self matrixFromAngles]; [quakeed_i updateAll]; - qprintf ("homed view angle"); - + Sys_Printf ("homed view angle\n"); + return self; } -- drawMode: sender +- (id) drawMode: sender { drawmode = [sender selectedColumn]; [quakeed_i updateCamera]; return self; } -- setDrawMode: (drawmode_t)mode +- (id) setDrawMode: (drawmode_t)mode { drawmode = mode; - //XXX[mode_radio_i selectCellAt:0: mode]; + [mode_radio_i selectCellAtRow: 0 column: mode]; [quakeed_i updateCamera]; return self; } @@ -149,95 +195,95 @@ TRANSFORMATION METHODS =============================================================================== */ -- matrixFromAngles +- (id) matrixFromAngles { - if (xa > M_PI*0.4) - xa = M_PI*0.4; - if (xa < -M_PI*0.4) - xa = -M_PI*0.4; - -// vpn - matrix[2][0] = cos(xa)*cos(ya); - matrix[2][1] = cos(xa)*sin(ya); - matrix[2][2] = sin(xa); + if (xa > M_PI * 0.4) + xa = M_PI * 0.4; + if (xa < -M_PI * 0.4) + xa = -M_PI * 0.4; -// vup - matrix[1][0] = cos(xa+M_PI/2)*cos(ya); - matrix[1][1] = cos(xa+M_PI/2)*sin(ya); - matrix[1][2] = sin(xa+M_PI/2); + // vpn + matrix[2][0] = cos (xa) * cos (ya); + matrix[2][1] = cos (xa) * sin (ya); + matrix[2][2] = sin (xa); -// vright + // vup + matrix[1][0] = cos (xa + M_PI / 2) * cos (ya); + matrix[1][1] = cos (xa + M_PI / 2) * sin (ya); + matrix[1][2] = sin (xa + M_PI / 2); + + // vright CrossProduct (matrix[2], matrix[1], matrix[0]); return self; } - -- inverseTransform: (vec_t *)invec to:(vec_t *)outvec +- (id) inverseTransform: (vec_t *)invec + to: (vec_t *)outvec { - vec3_t inverse[3]; - vec3_t temp; - int i,j; - - for (i=0 ; i<3 ; i++) - for (j=0 ; j<3 ; j++) + vec3_t inverse[3]; + vec3_t temp; + int i, j; + + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) inverse[i][j] = matrix[j][i]; - - temp[0] = DotProduct(invec, inverse[0]); - temp[1] = DotProduct(invec, inverse[1]); - temp[2] = DotProduct(invec, inverse[2]); + } + + temp[0] = DotProduct (invec, inverse[0]); + temp[1] = DotProduct (invec, inverse[1]); + temp[2] = DotProduct (invec, inverse[2]); VectorAdd (temp, origin, outvec); return self; } - - /* =============================================================================== - DRAWING METHODS + DRAWING METHODS =============================================================================== */ -typedef struct -{ - vec3_t trans; - int clipflags; - vec3_t screen; // valid only if clipflags == 0 +typedef struct { + vec3_t trans; + int clipflags; + vec3_t screen; // valid only if clipflags == 0 } campt_t; -#define CLIP_RIGHT 1 -#define CLIP_LEFT 2 -#define CLIP_TOP 4 -#define CLIP_BOTTOM 8 -#define CLIP_FRONT 16 -int cam_cur; -campt_t campts[2]; +#define CLIP_RIGHT 1 +#define CLIP_LEFT 2 +#define CLIP_TOP 4 +#define CLIP_BOTTOM 8 +#define CLIP_FRONT 16 -vec3_t r_matrix[3]; -vec3_t r_origin; -float mid_x, mid_y; -float topscale = (240.0/3)/160; -float bottomscale = (240.0*2/3)/160; +int cam_cur; +campt_t campts[2]; -extern plane_t frustum[5]; +vec3_t r_matrix[3]; +vec3_t r_origin; +float mid_x, mid_y; +float topscale = (240.0 / 3) / 160; +float bottomscale = (240.0 * 2 / 3) / 160; -void MakeCampt (vec3_t in, campt_t *pt) +extern plane_t rfrustum[5]; + +void +MakeCampt (vec3_t in, campt_t * pt) { - vec3_t temp; - float scale; - -// transform the points - VectorSubtract (in, r_origin, temp); - - pt->trans[0] = DotProduct(temp, r_matrix[0]); - pt->trans[1] = DotProduct(temp, r_matrix[1]); - pt->trans[2] = DotProduct(temp, r_matrix[2]); + vec3_t temp; + float scale; -// check clip flags + // transform the points + VectorSubtract (in, r_origin, temp); + + pt->trans[0] = DotProduct (temp, r_matrix[0]); + pt->trans[1] = DotProduct (temp, r_matrix[1]); + pt->trans[2] = DotProduct (temp, r_matrix[2]); + + // check clip flags if (pt->trans[2] < 1) pt->clipflags = CLIP_FRONT; else @@ -247,189 +293,166 @@ void MakeCampt (vec3_t in, campt_t *pt) pt->clipflags |= CLIP_RIGHT; else if (-pt->trans[0] > pt->trans[2]) pt->clipflags |= CLIP_LEFT; - - if (pt->trans[1] > pt->trans[2]*topscale ) + + if (pt->trans[1] > pt->trans[2] * topscale) pt->clipflags |= CLIP_TOP; - else if (-pt->trans[1] > pt->trans[2]*bottomscale ) + else if (-pt->trans[1] > pt->trans[2] * bottomscale) pt->clipflags |= CLIP_BOTTOM; - + if (pt->clipflags) return; - -// project - scale = mid_x/pt->trans[2]; - pt->screen[0] = mid_x + pt->trans[0]*scale; - pt->screen[1] = mid_y + pt->trans[1]*scale; + + // project + scale = mid_x / pt->trans[2]; + pt->screen[0] = mid_x + pt->trans[0] * scale; + pt->screen[1] = mid_y + pt->trans[1] * scale; } - -void CameraMoveto(vec3_t p) +void +CameraMoveto (vec3_t p) { - campt_t *pt; - - if (upath->numberOfPoints > 2048) + campt_t *pt; + + if ([path elementCount] > 2048) lineflush (); - + pt = &campts[cam_cur]; cam_cur ^= 1; - MakeCampt (p,pt); - if (!pt->clipflags) - { // onscreen, so move there immediately - UPmoveto (upath, pt->screen[0], pt->screen[1]); + MakeCampt (p, pt); + if (!pt->clipflags) { // onscreen, so move there immediately + NSPoint point = {pt->screen[0], pt->screen[1]}; + [path moveToPoint: point]; } } -void ClipLine (vec3_t p1, vec3_t p2, int planenum) +void +ClipLine (vec3_t p1, vec3_t p2, int planenum) { - float d, d2, frac; - vec3_t new; - plane_t *pl; - float scale; - - if (planenum == 5) - { // draw it! - scale = mid_x/p1[2]; - new[0] = mid_x + p1[0]*scale; - new[1] = mid_y + p1[1]*scale; - UPmoveto (upath, new[0], new[1]); - - scale = mid_x/p2[2]; - new[0] = mid_x + p2[0]*scale; - new[1] = mid_y + p2[1]*scale; - UPlineto (upath, new[0], new[1]); + float d, d2, frac; + vec3_t new; + plane_t *pl; + float scale; + NSPoint point; + + if (planenum == 5) { // draw it! + scale = mid_x / p1[2]; + point.x = mid_x + p1[0] * scale; + point.y = mid_y + p1[1] * scale; + [path moveToPoint: point]; + + scale = mid_x / p2[2]; + point.x = mid_x + p2[0] * scale; + point.y = mid_y + p2[1] * scale; + [path lineToPoint: point]; return; } - pl = &frustum[planenum]; - - d = DotProduct (p1, pl->normal) - pl->dist; + pl = &rfrustum[planenum]; + + d = DotProduct (p1, pl->normal) - pl->dist; d2 = DotProduct (p2, pl->normal) - pl->dist; - if (d <= ON_EPSILON && d2 <= ON_EPSILON) - { // off screen + if (d <= ON_EPSILON && d2 <= ON_EPSILON) // off screen + return; + + if (d >= 0 && d2 >= 0) { // on front + ClipLine (p1, p2, planenum + 1); return; } - - if (d >= 0 && d2 >= 0) - { // on front - ClipLine (p1, p2, planenum+1); - return; - } - - frac = d/(d-d2); - new[0] = p1[0] + frac*(p2[0]-p1[0]); - new[1] = p1[1] + frac*(p2[1]-p1[1]); - new[2] = p1[2] + frac*(p2[2]-p1[2]); - + + frac = d / (d - d2); + new[0] = p1[0] + frac * (p2[0] - p1[0]); + new[1] = p1[1] + frac * (p2[1] - p1[1]); + new[2] = p1[2] + frac * (p2[2] - p1[2]); + if (d > 0) - ClipLine (p1, new, planenum+1); + ClipLine (p1, new, planenum + 1); else - ClipLine (new, p2, planenum+1); + ClipLine (new, p2, planenum + 1); } -int c_off, c_on, c_clip; +int c_off, c_on, c_clip; -void CameraLineto(vec3_t p) +void +CameraLineto (vec3_t p) { - campt_t *p1, *p2; - int bits; - + campt_t *p1, *p2; + int bits; + p2 = &campts[cam_cur]; cam_cur ^= 1; p1 = &campts[cam_cur]; MakeCampt (p, p2); - if (p1->clipflags & p2->clipflags) - { + if (p1->clipflags & p2->clipflags) { // entirely off screen c_off++; - return; // entirely off screen + return; } - + bits = p1->clipflags | p2->clipflags; - - if (! bits ) - { + if (!bits) { // entirely on screen + NSPoint point1 = {p1->screen[0], p1->screen[1]}; + NSPoint point2 = {p2->screen[0], p2->screen[1]}; + c_on++; - UPmoveto (upath, p1->screen[0], p1->screen[1]); - UPlineto (upath, p2->screen[0], p2->screen[1]); - return; // entirely on screen + [path moveToPoint: point1]; + [path lineToPoint: point2]; + return; } - -// needs to be clipped + + // needs to be clipped c_clip++; ClipLine (p1->trans, p2->trans, 0); } - /* ============= drawSolid ============= */ -- drawSolid +- (id) drawSolid { - unsigned char *planes[5]; - -// -// draw it -// + unsigned char *planes[5]; + + // draw it VectorCopy (origin, r_origin); VectorCopy (matrix[0], r_matrix[0]); VectorCopy (matrix[1], r_matrix[1]); VectorCopy (matrix[2], r_matrix[2]); - + r_width = _bounds.size.width; r_height = _bounds.size.height; r_picbuffer = imagebuffer; r_zbuffer = zbuffer; r_drawflat = (drawmode == dr_flat); - + REN_BeginCamera (); REN_ClearBuffers (); -// -// render the setbrushes -// - [map_i makeAllPerform: @selector(CameraRenderSelf)]; + // render the setbrushes + [map_i makeAllPerform: @selector (CameraRenderSelf)]; -// -// display the output -// - [[self window] setBackingType:NSBackingStoreRetained]; - - planes[0] = (unsigned char *)imagebuffer; - NSDrawBitmap( - _bounds, - r_width, - r_height, - 8, - 3, - 32, - r_width*4, - NO, - NO, - @"RGB", //FIXME what should this be? - (const unsigned char **const)planes - ); + // display the output + [[self window] setBackingType: NSBackingStoreRetained]; + + planes[0] = (unsigned char *) imagebuffer; + NSDrawBitmap (_bounds, r_width, r_height, 8, 3, 32, r_width * 4, NO, NO, + NSCalibratedRGBColorSpace, (const unsigned char **) planes); + + [[self window] setBackingType: NSBackingStoreBuffered]; - //XXX NSPing (); - [[self window] setBackingType:NSBackingStoreBuffered]; - - - return self; } - /* =================== drawWire =================== */ -- drawWire: (NSRect)rect +- (id) drawWire: (NSRect)rect { -// copy current info to globals for the C callbacks + // copy current info to globals for the C callbacks mid_x = _bounds.size.width / 2; mid_y = 2 * _bounds.size.height / 3; @@ -437,20 +460,20 @@ drawWire VectorCopy (matrix[0], r_matrix[0]); VectorCopy (matrix[1], r_matrix[1]); VectorCopy (matrix[2], r_matrix[2]); - + r_width = _bounds.size.width; r_height = _bounds.size.height; r_picbuffer = imagebuffer; r_zbuffer = zbuffer; REN_BeginCamera (); - -// erase window + + // erase window NSEraseRect (rect); - -// draw all entities - linestart (0,0,0); - [map_i makeUnselectedPerform: @selector(CameraDrawSelf)]; + + // draw all entities + linestart (0, 0, 0); + [map_i makeUnselectedPerform: @selector (CameraDrawSelf)]; lineflush (); return self; @@ -461,54 +484,53 @@ drawWire drawSelf =================== */ -- drawSelf:(NSRect)rects :(int)rectCount +- (void) drawRect: (NSRect)rect { - static float drawtime; // static to shut up compiler warning + float drawtime = 0; if (timedrawing) - drawtime = I_FloatTime (); + drawtime = Sys_DoubleTime (); - if (drawmode == dr_texture || drawmode == dr_flat) + if (drawmode == dr_texture || drawmode == dr_flat) { + [quakeed_i cameraNoRestore: _bounds]; [self drawSolid]; - else - [self drawWire: rects]; - - if (timedrawing) - { - //XXX NSPing (); - drawtime = I_FloatTime() - drawtime; - printf ("CameraView drawtime: %5.3f\n", drawtime); + } else { + [quakeed_i cameraNoRestore: rect]; + [self drawWire: rect]; } - return self; + if (timedrawing) { + drawtime = Sys_DoubleTime () - drawtime; + printf ("CameraView drawtime: %5.3f\n", drawtime); + } } - /* ============= XYDrawSelf ============= */ -- XYDrawSelf +- (void) XYDrawSelf { - - PSsetrgbcolor (0,0,1.0); - PSsetlinewidth (0.15); - PSmoveto (origin[0]-16,origin[1]); - PSrlineto (16,8); - PSrlineto (16,-8); - PSrlineto (-16,-8); - PSrlineto (-16,8); - PSrlineto (32,0); - - PSmoveto (origin[0],origin[1]); - PSrlineto (64*cos(ya+M_PI/4), 64*sin(ya+M_PI/4)); - PSmoveto (origin[0],origin[1]); - PSrlineto (64*cos(ya-M_PI/4), 64*sin(ya-M_PI/4)); - - PSstroke (); - - return self; + NSBezierPath *path; + NSAffineTransform *trans; + + [[NSColor blueColor] set]; + + trans = [NSAffineTransform transform]; + [trans translateXBy: origin[0] yBy: origin[1]]; + + path = [xycamera copy]; + [path transformUsingAffineTransform: trans]; + [path stroke]; + [path release]; + + [trans rotateByRadians: ya]; + + path = [xycamera_aim copy]; + [path transformUsingAffineTransform: trans]; + [path stroke]; + [path release]; } /* @@ -516,34 +538,26 @@ XYDrawSelf ZDrawSelf ============= */ -- ZDrawSelf +- (void) ZDrawSelf { - PSsetrgbcolor (0,0,1.0); - PSsetlinewidth (0.15); - - PSmoveto (-16,origin[2]); - PSrlineto (16,8); - PSrlineto (16,-8); - PSrlineto (-16,-8); - PSrlineto (-16,8); - PSrlineto (32,0); - - PSmoveto (-15,origin[2]-47); - PSrlineto (29,0); - PSrlineto (0,54); - PSrlineto (-29,0); - PSrlineto (0,-54); + NSBezierPath *path; + NSAffineTransform *trans; - PSstroke (); + [[NSColor blueColor] set]; - return self; + trans = [NSAffineTransform transform]; + [trans translateXBy: 0 yBy: origin[2]]; + + path = [zcamera copy]; + [path transformUsingAffineTransform: trans]; + [path stroke]; + [path release]; } - /* =============================================================================== - XYZ mouse view methods + XYZ mouse view methods =============================================================================== */ @@ -553,280 +567,247 @@ ZDrawSelf modalMoveLoop ================ */ -- modalMoveLoop: (NSPoint *)basept :(vec3_t)movemod : converter +- (id) modalMoveLoop: (NSPoint *)basept + : (vec3_t)movemod + : converter { - vec3_t originbase; - NSEvent *event = 0; //XXX - NSPoint newpt; -// NSPoint brushpt; - vec3_t delta; -// id ent; - int i; -// vec3_t temp; - - qprintf ("moving camera position"); + vec3_t originbase; + NSEvent *event = 0; + unsigned eventMask = (NSLeftMouseUpMask | NSLeftMouseDraggedMask + | NSRightMouseUpMask | NSRightMouseDraggedMask + | NSApplicationDefinedMask); + NSPoint newpt; + vec3_t delta; + int i; - VectorCopy (origin, originbase); - -// -// modal event loop using instance drawing -// + Sys_Printf ("moving camera position\n"); + + VectorCopy (origin, originbase); + + // modal event loop using instance drawing goto drawentry; - while ([event type] != NSLeftMouseUp && [event type] != NSRightMouseUp) - { - // + while ([event type] != NSLeftMouseUp && [event type] != NSRightMouseUp) { // calculate new point - // newpt = [event locationInWindow]; - newpt = [converter convertPoint:newpt fromView:NULL]; - - delta[0] = newpt.x-basept->x; - delta[1] = newpt.y-basept->y; - delta[2] = delta[1]; // height change - - for (i=0 ; i<3 ; i++) - origin[i] = originbase[i]+movemod[i]*delta[i]; - -#if 0 // FIXME - // + newpt = [converter convertPoint: newpt fromView: NULL]; + + delta[0] = newpt.x - basept->x; + delta[1] = newpt.y - basept->y; + delta[2] = delta[1]; // height change + + for (i = 0; i < 3; i++) + origin[i] = originbase[i] + movemod[i] * delta[i]; + +#if 0 // FIXME // if command is down, look towards brush or entity - // - if (event->flags & NS_SHIFTMASK) - { + if (event->flags & NS_SHIFTMASK) { + NSPoint brushpt; + id ent; + vec3_t temp; + ent = [quakemap_i selectedEntity]; - if (ent) - { + if (ent) { [ent origin: temp]; brushpt.x = temp[0]; brushpt.y = temp[1]; - } - else + } else { brushpt = [brush_i centerPoint]; - ya = atan2 (brushpt.y - newpt.y, brushpt.x - newpt.x); + } ya = atan2 (brushpt.y - newpt.y, brushpt.x - newpt.x); [self matrixFromAngles]; } #endif - -drawentry: - // + + drawentry: // instance draw new frame - // [quakeed_i newinstance]; [self display]; -/*XXX - event = [NSApp nextEventMatchingMask: NSLeftMouseUpMask - | NSLeftMouseDraggedMask | NSRightMouseUpMask - | NSRightMouseDraggedMask | NSApplicationDefinedMask]; -*/ - if ([event type] == NSKeyDown) - { + event = [NSApp nextEventMatchingMask: eventMask + untilDate: [NSDate distantFuture] + inMode: NSEventTrackingRunLoopMode dequeue: + YES]; + if ([event type] == NSKeyDown) { [self _keyDown: event]; [self display]; goto drawentry; } - } return self; } -//============================================================================ +// ============================================================================ /* =============== XYmouseDown =============== */ -- (BOOL)XYmouseDown: (NSPoint *)pt flags:(int)flags // return YES if brush handled -{ - vec3_t movemod; - - if (fabs(pt->x - origin[0]) > 16 - || fabs(pt->y - origin[1]) > 16 ) +- (BOOL) XYmouseDown: (NSPoint *)pt + flags: (int)flags +// return YES if brush handled +{ + vec3_t movemod; + + if (fabs (pt->x - origin[0]) > 16 || fabs (pt->y - origin[1]) > 16) return NO; - -#if 0 - if (flags & NSAlternateKeyMask) - { // up / down drag + +#if 0 + if (flags & NSAlternateKeyMask) { // up / down drag movemod[0] = 0; movemod[1] = 0; movemod[2] = 1; - } - else + } else #endif - { + { movemod[0] = 1; movemod[1] = 1; movemod[2] = 0; } - - [self modalMoveLoop: pt : movemod : xyview_i]; - + + [self modalMoveLoop: pt: movemod: xyview_i]; + return YES; } - /* =============== ZmouseDown =============== */ -- (BOOL)ZmouseDown: (NSPoint *)pt flags:(int)flags // return YES if brush handled -{ - vec3_t movemod; - - if (fabs(pt->y - origin[2]) > 16 - || pt->x < -8 || pt->x > 8 ) +- (BOOL) ZmouseDown: (NSPoint *)pt + flags: (int)flags +// return YES if brush handled +{ + vec3_t movemod; + + if (fabs (pt->y - origin[2]) > 16 || pt->x < -8 || pt->x > 8) return NO; - + movemod[0] = 0; movemod[1] = 0; movemod[2] = 1; - - [self modalMoveLoop: pt : movemod : zview_i]; + + [self modalMoveLoop: pt: movemod: zview_i]; return YES; } - -//============================================================================= +// ============================================================================= /* =================== viewDrag: =================== */ -- viewDrag:(NSPoint *)pt +- (id) viewDrag: (NSPoint *)pt { - float dx,dy; - NSEvent *event = 0; //XXX - NSPoint newpt; - -// -// modal event loop using instance drawing -// + float dx, dy; + NSEvent *event = 0; + NSPoint newpt; + + // modal event loop using instance drawing goto drawentry; - while ([event type] != NSRightMouseUp) - { - // + while ([event type] != NSRightMouseUp) { // calculate new point - // newpt = [event locationInWindow]; - newpt = [self convertPoint:newpt fromView:NULL]; + newpt = [self convertPoint: newpt fromView: NULL]; dx = newpt.x - pt->x; dy = newpt.y - pt->y; *pt = newpt; - - ya -= dx/_bounds.size.width*M_PI/2 * 4; - xa += dy/_bounds.size.width*M_PI/2 * 4; - + + ya -= dx / _bounds.size.width * M_PI / 2 * 4; + xa += dy / _bounds.size.width * M_PI / 2 * 4; + [self matrixFromAngles]; - -drawentry: + + drawentry: [quakeed_i newinstance]; [self display]; -/*XXX - event = [NSApp getNextEvent: - NSKeyDownMask | NSRightMouseUpMask | NSRightMouseDraggedMask]; -*/ - if ([event type] == NSKeyDown) - { + event = [NSApp nextEventMatchingMask: NSRightMouseUpMask + | NSRightMouseDraggedMask + untilDate: [NSDate distantFuture] + inMode: NSEventTrackingRunLoopMode dequeue: + YES]; + if ([event type] == NSKeyDown) { [self _keyDown: event]; [self display]; goto drawentry; } - } return self; } - -//============================================================================= +// ============================================================================= /* =================== mouseDown =================== */ -- (void) mouseDown:(NSEvent *)theEvent +- (void) mouseDown: (NSEvent *)theEvent { - NSPoint pt; - int i; - vec3_t p1, p2; - float forward, right, up; - int flags; - + NSPoint pt; + int i; + vec3_t p1, p2; + float forward, right, up; + int flags; + pt = [theEvent locationInWindow]; - - pt = [self convertPoint:pt fromView:NULL]; + + pt = [self convertPoint: pt fromView: NULL]; VectorCopy (origin, p1); forward = 160; right = pt.x - 160; - up = pt.y - 240*2/3; - for (i=0 ; i<3 ; i++) - p2[i] = forward*matrix[2][i] + up*matrix[1][i] + right*matrix[0][i]; - for (i=0 ; i<3 ; i++) - p2[i] = p1[i] + 100*p2[i]; + up = pt.y - 240 * 2 / 3; + for (i = 0; i < 3; i++) { + p2[i] = + forward * matrix[2][i] + up * matrix[1][i] + right * matrix[0][i]; + } + for (i = 0; i < 3; i++) + p2[i] = p1[i] + 100 * p2[i]; - flags = [theEvent modifierFlags] & (NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask); + flags = + [theEvent modifierFlags] & (NSShiftKeyMask | NSControlKeyMask | + NSAlternateKeyMask | NSCommandKeyMask); -// -// bare click to select a texture -// - if (flags == 0) - { + // bare click to select a texture + if (flags == 0) { [map_i getTextureRay: p1 : p2]; return; } - -// -// shift click to select / deselect a brush from the world -// - if (flags == NSShiftKeyMask) - { + // shift click to select / deselect a brush from the world + if (flags == NSShiftKeyMask) { [map_i selectRay: p1 : p2 : NO]; return; } - -// -// cmd-shift click to set a target/targetname entity connection -// - if (flags == (NSShiftKeyMask|NSCommandKeyMask) ) - { + // cmd-shift click to set a target/targetname entity connection + if (flags == (NSShiftKeyMask | NSCommandKeyMask)) { [map_i entityConnect: p1 : p2]; return; } -// -// alt click = set entire brush texture -// - if (flags == NSAlternateKeyMask) - { - if (drawmode != dr_texture) - { - qprintf ("No texture setting except in texture mode!\n"); + // alt click = set entire brush texture + if (flags == NSAlternateKeyMask) { + if (drawmode != dr_texture) { + Sys_Printf ("No texture setting except in texture mode!\n"); NopSound (); return; - } + } [map_i setTextureRay: p1 : p2 : YES]; [quakeed_i updateAll]; return; } - -// -// ctrl-alt click = set single face texture -// - if (flags == (NSControlKeyMask | NSAlternateKeyMask) ) - { - if (drawmode != dr_texture) - { - qprintf ("No texture setting except in texture mode!\n"); + + // ctrl-alt click = set single face texture + if (flags == (NSControlKeyMask | NSAlternateKeyMask)) { + if (drawmode != dr_texture) { + Sys_Printf ("No texture setting except in texture mode!\n"); NopSound (); return; } @@ -834,11 +815,10 @@ mouseDown [quakeed_i updateAll]; return; } - - qprintf ("bad flags for click"); + Sys_Printf ("bad flags for click %x\n", flags); NopSound (); - + return; } @@ -847,31 +827,29 @@ mouseDown rightMouseDown =================== */ --(void) rightMouseDown:(NSEvent *)theEvent +- (void) rightMouseDown: (NSEvent *)theEvent { - NSPoint pt; - int flags; - + NSPoint pt; + int flags; + pt = [theEvent locationInWindow]; - - [self convertPoint:pt fromView:NULL]; - flags = [theEvent modifierFlags] & (NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask); + [self convertPoint: pt fromView: NULL]; -// -// click = drag camera -// - if (flags == 0) - { - qprintf ("looking"); + flags = [theEvent modifierFlags] + & (NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask + | NSCommandKeyMask); + + // click = drag camera + if (flags == 0) { + Sys_Printf ("looking\n"); [self viewDrag: &pt]; - qprintf (""); return; - } + } - qprintf ("bad flags for click"); + Sys_Printf ("bad flags for click\n"); NopSound (); - + return; } @@ -881,91 +859,79 @@ keyDown =============== */ -#define KEY_RIGHTARROW 0xae -#define KEY_LEFTARROW 0xac -#define KEY_UPARROW 0xad -#define KEY_DOWNARROW 0xaf - - -- _keyDown: (NSEvent *)theEvent +- (id) _keyDown: (NSEvent *)theEvent { - int ch; - - ch = tolower([[theEvent characters] characterAtIndex: 0]); - - switch (ch) - { - case 13: - return self; - - case 'a': - case 'A': - xa += M_PI/8; - [self matrixFromAngles]; - [quakeed_i updateCamera]; - return self; - - case 'z': - case 'Z': - xa -= M_PI/8; - [self matrixFromAngles]; - [quakeed_i updateCamera]; - return self; - - case KEY_RIGHTARROW: - ya -= M_PI*move/(64*2); - [self matrixFromAngles]; - [quakeed_i updateCamera]; - break; - - case KEY_LEFTARROW: - ya += M_PI*move/(64*2); - [self matrixFromAngles]; - [quakeed_i updateCamera]; - break; - - case KEY_UPARROW: - origin[0] += move*cos(ya); - origin[1] += move*sin(ya); - [quakeed_i updateCamera]; - break; - - case KEY_DOWNARROW: - origin[0] -= move*cos(ya); - origin[1] -= move*sin(ya); - [quakeed_i updateCamera]; - break; - - case '.': - origin[0] += move*cos(ya-M_PI_2); - origin[1] += move*sin(ya-M_PI_2); - [quakeed_i updateCamera]; - break; - - case ',': - origin[0] -= move*cos(ya-M_PI_2); - origin[1] -= move*sin(ya-M_PI_2); - [quakeed_i updateCamera]; - break; - - case 'd': - case 'D': - origin[2] += move; - [quakeed_i updateCamera]; - break; - - case 'c': - case 'C': - origin[2] -= move; - [quakeed_i updateCamera]; - break; - - } + NSString *chars = [theEvent characters]; + unichar c = ([chars length] == 1) ? [chars characterAtIndex: 0] : '\0'; - - return self; + switch (c) { + case 13: + return self; + + case 'a': + case 'A': + xa += M_PI / 8; + [self matrixFromAngles]; + [quakeed_i updateCamera]; + return self; + + case 'z': + case 'Z': + xa -= M_PI / 8; + [self matrixFromAngles]; + [quakeed_i updateCamera]; + return self; + + case NSRightArrowFunctionKey: + ya -= M_PI * move / (64 * 2); + [self matrixFromAngles]; + [quakeed_i updateCamera]; + break; + + case NSLeftArrowFunctionKey: + ya += M_PI * move / (64 * 2); + [self matrixFromAngles]; + [quakeed_i updateCamera]; + break; + + case NSUpArrowFunctionKey: + origin[0] += move * cos (ya); + origin[1] += move * sin (ya); + [quakeed_i updateCamera]; + break; + + case NSDownArrowFunctionKey: + origin[0] -= move * cos (ya); + origin[1] -= move * sin (ya); + [quakeed_i updateCamera]; + break; + + case '.': + origin[0] += move * cos (ya - M_PI_2); + origin[1] += move * sin (ya - M_PI_2); + [quakeed_i updateCamera]; + break; + + case ',': + origin[0] -= move * cos (ya - M_PI_2); + origin[1] -= move * sin (ya - M_PI_2); + [quakeed_i updateCamera]; + break; + + case 'd': + case 'D': + origin[2] += move; + [quakeed_i updateCamera]; + break; + + case 'c': + case 'C': + origin[2] -= move; + [quakeed_i updateCamera]; + break; + } /* switch */ + + return self; } - @end - diff --git a/tools/Forge/Bundles/MapEdit/Clipper.h b/tools/Forge/Bundles/MapEdit/Clipper.h index 5fec08642..3e4dde5dc 100644 --- a/tools/Forge/Bundles/MapEdit/Clipper.h +++ b/tools/Forge/Bundles/MapEdit/Clipper.h @@ -1,24 +1,32 @@ +#ifndef Clipper_h +#define Clipper_h -extern id clipper_i; +#include -@interface Clipper : Object +#include "QF/mathlib.h" + +#include "SetBrush.h" + +extern id clipper_i; + +@interface Clipper: NSObject { - int num; - vec3_t pos[3]; - plane_t plane; + int num; + vec3_t pos[3]; + plane_t plane; } -- (BOOL)hide; -- XYClick: (NSPoint)pt; -- (BOOL)XYDrag: (NSPoint *)pt; -- ZClick: (NSPoint)pt; -- carve; -- flipNormal; -- (BOOL)getFace: (face_t *)pl; +- (BOOL) hide; +- (id) XYClick: (NSPoint)pt; +- (BOOL) XYDrag: (NSPoint *)pt; +- (id) ZClick: (NSPoint)pt; +- (id) carve; +- (void) flipNormal; +- (BOOL) getFace: (face_t *)pl; -- cameraDrawSelf; -- XYDrawSelf; -- ZDrawSelf; +- (void) cameraDrawSelf; +- (void) XYDrawSelf; +- (void) ZDrawSelf; @end - +#endif // Clipper_h diff --git a/tools/Forge/Bundles/MapEdit/Clipper.m b/tools/Forge/Bundles/MapEdit/Clipper.m index 201e17837..aba58c2d1 100644 --- a/tools/Forge/Bundles/MapEdit/Clipper.m +++ b/tools/Forge/Bundles/MapEdit/Clipper.m @@ -1,81 +1,77 @@ +#include "QF/sys.h" -#include "qedefs.h" +#include "Clipper.h" +#include "Map.h" +#include "XYView.h" +#include "ZView.h" +#include "CameraView.h" +#include "QuakeEd.h" -#include -#include - -id clipper_i; +id clipper_i; +extern NSBezierPath *path; @implementation Clipper -- init +- (id) init { [super init]; clipper_i = self; - return self; + return self; } -- (BOOL)hide +- (BOOL) hide { - int oldnum; - + int oldnum; + oldnum = num; num = 0; return (oldnum > 0); } -- flipNormal +- (void) flipNormal { - vec3_t temp; - - if (num == 2) - { + vec3_t temp; + + if (num == 2) { VectorCopy (pos[0], temp); VectorCopy (pos[1], pos[0]); VectorCopy (temp, pos[1]); - } - else if (num == 3) - { + } else if (num == 3) { VectorCopy (pos[0], temp); VectorCopy (pos[2], pos[0]); VectorCopy (temp, pos[2]); - } - else - { - qprintf ("no clipplane"); + } else { + Sys_Printf ("no clipplane\n"); NSBeep (); } - - return self; } -- (BOOL)getFace: (face_t *)f +- (BOOL) getFace: (face_t *)f { - vec3_t v1, v2, norm; - int i; - + vec3_t v1, v2, norm; + int i; + VectorCopy (vec3_origin, plane.normal); plane.dist = 0; if (num < 2) return NO; - if (num == 2) - { + if (num == 2) { VectorCopy (pos[0], pos[2]); pos[2][2] += 16; } - - for (i=0 ; i<3 ; i++) + + for (i = 0; i < 3; i++) VectorCopy (pos[i], f->planepts[i]); - + VectorSubtract (pos[2], pos[0], v1); VectorSubtract (pos[1], pos[0], v2); - + CrossProduct (v1, v2, norm); VectorNormalize (norm); - - if ( !norm[0] && !norm[1] && !norm[2] ) + + if (!norm[0] && !norm[1] && !norm[2]) return NO; - + [texturepalette_i getTextureDef: &f->texture]; return YES; @@ -86,20 +82,18 @@ id clipper_i; XYClick ================ */ -- XYClick: (NSPoint)pt +- (id) XYClick: (NSPoint)pt { - int i; - vec3_t new; - + int i; + vec3_t new; + new[0] = [xyview_i snapToGrid: pt.x]; new[1] = [xyview_i snapToGrid: pt.y]; new[2] = [map_i currentMinZ]; -// see if a point is allready there - for (i=0 ; ix - pos[i][0] > 10) || fabs(pt->y - pos[i][1] > 10) ) - continue; - // drag this point - + int i; + + for (i = 0; i < 3; i++) { + if (fabs (pt->x - pos[i][0] > 10) || fabs (pt->y - pos[i][1] > 10)) + continue; // drag this point } - + return NO; } -- ZClick: (NSPoint)pt +- (id) ZClick: (NSPoint)pt { return self; } -//============================================================================= +// ============================================================================= -- carve +- (id) carve { - [map_i makeSelectedPerform: @selector(carveByClipper)]; + [map_i makeSelectedPerform: @selector (carveByClipper)]; num = 0; return self; } - -- cameraDrawSelf +- (void) cameraDrawSelf { - vec3_t mid; - int i; - - linecolor (1,0.5,0); + vec3_t mid; + int i; - for (i=0 ; i -typedef struct -{ - char *key; - char *value; -} dict_t; +#include "Storage.h" -@interface Dict:Storage +struct script_s; + +@interface Dict: NSObject { + struct plitem_s *plist; } -- initFromFile:(FILE *)fp; +- (id) initFromFile: (FILE *)fp; -- (id) parseMultipleFrom:(char *)value; -- (int) getValueUnits:(char *)key; -- delString:(char *)string fromValue:(char *)key; -- addString:(char *)string toValue:(char *)key; -- (char *)convertListToString:(id)list; -- (char *)getStringFor:(char *)name; -- removeKeyword:(char *)key; -- (unsigned int)getValueFor:(char *)name; -- changeStringFor:(char *)key to:(char *)value; -- (dict_t *) findKeyword:(char *)key; +- (int) getValueUnits: (const char *)key; -- writeBlockTo:(FILE *)fp; -- writeFile:(char *)path; +- (struct plitem_s *) getArrayFor: (const char *)name; +- (const char *) getStringFor: (const char *)name; +- (unsigned int) getValueFor: (const char *)name; +- (id) changeStringFor: (const char *)key to: (const char *)value; -// INTERNAL -- init; -- (id) parseBraceBlock:(FILE *)fp; -- setupMultiple:(char *)value; -- (char *)getNextParameter; +- (id) writeBlockTo: (FILE *)fp; +- (id) writeFile: (const char *)path; @end -int GetNextChar(FILE *fp); -void CopyUntilWhitespc(FILE *fp,char *buffer); -void CopyUntilQuote(FILE *fp,char *buffer); -int FindBrace(FILE *fp); -int FindQuote(FILE *fp); -int FindWhitespc(FILE *fp); -int FindNonwhitespc(FILE *fp); +int GetNextChar (FILE * fp); +void CopyUntilWhitespc (FILE * fp, char *buffer); +void CopyUntilQuote (FILE * fp, char *buffer); +int FindBrace (FILE * fp); +int FindQuote (FILE * fp); +int FindWhitespc (FILE * fp); +int FindNonwhitespc (FILE * fp); -char *FindWhitespcInBuffer(char *buffer); -char *FindNonwhitespcInBuffer(char *buffer); +char *FindWhitespcInBuffer (char *buffer); +char *FindNonwhitespcInBuffer (char *buffer); + +#endif // Dict_h diff --git a/tools/Forge/Bundles/MapEdit/Dict.m b/tools/Forge/Bundles/MapEdit/Dict.m index aa126f643..359b5d60e 100644 --- a/tools/Forge/Bundles/MapEdit/Dict.m +++ b/tools/Forge/Bundles/MapEdit/Dict.m @@ -1,29 +1,26 @@ +#include "QF/dstring.h" +#include "QF/qfplist.h" +#include "QF/script.h" +#include "QF/sys.h" +#include "QF/va.h" -#include "qedefs.h" +#include "Dict.h" @implementation Dict -- init +/* +- (id) print { - [super initCount:0 - elementSize:sizeof(dict_t) - description:NULL]; - return self; -} + NSUInteger i; + dict_t *d; -- print -{ - int i; - dict_t *d; - - for (i=0 ; ikey, d->value); + printf ("%s : %s\n", d->key, d->value); } return self; } - +*/ /* =========== copyFromZone @@ -31,553 +28,128 @@ copyFromZone JDC =========== */ -- copyFromZone:(NSZone *)zone +- (id) copy { - id new; - int i; - dict_t *d; - char *old; - - new = [super copyFromZone: zone]; - for (i=0 ; ikey; - d->key = malloc(strlen(old)+1); - strcpy (d->key, old); - - old = d->value; - d->value = malloc(strlen(old)+1); - strcpy (d->value, old); - } - - return new; -} - -- initFromFile:(FILE *)fp -{ - [self init]; - return [self parseBraceBlock:fp]; -} - -//=============================================== -// -// Dictionary pair functions -// -//=============================================== - -// -// Write a { } block out to a FILE* -// -- writeBlockTo:(FILE *)fp -{ - int max; - int i; - dict_t *d; - - fprintf(fp,"{\n"); - max = [super count]; - for (i = 0;i < max;i++) - { - d = [super elementAt:i]; - fprintf(fp,"\t{\"%s\"\t\"%s\"}\n",d->key,d->value); - } - fprintf(fp,"}\n"); - - return self; -} - -// -// Write a single { } block out -// -- writeFile:(char *)path -{ - FILE *fp; - - fp = fopen(path,"w+t"); - if (fp != NULL) - { - printf("Writing dictionary file %s.\n",path); - fprintf(fp,"// QE_Project file %s\n",path); - [self writeBlockTo:fp]; - fclose(fp); - } - else - { - printf("Error writing %s!\n",path); - return NULL; - } - - return self; -} - -//=============================================== -// -// Utility methods -// -//=============================================== - -// -// Find a keyword in storage -// Returns * to dict_t, otherwise NULL -// -- (dict_t *) findKeyword:(char *)key -{ - int max; - int i; - dict_t *d; - - max = [super count]; - for (i = 0;i < max;i++) - { - d = [super elementAt:i]; - if (!strcmp(d->key,key)) - return d; - } - - return NULL; -} - -// -// Change a keyword's string -// -- changeStringFor:(char *)key to:(char *)value -{ - dict_t *d; - dict_t newd; - - d = [self findKeyword:key]; - if (d != NULL) - { - free(d->value); - d->value = malloc(strlen(value)+1); - strcpy(d->value,value); - } - else - { - newd.key = malloc(strlen(key)+1); - strcpy(newd.key,key); - newd.value = malloc(strlen(value)+1); - strcpy(newd.value,value); - [self addElement:&newd]; - } - return self; -} - -// -// Search for keyword, return the string * -// -- (char *)getStringFor:(char *)name -{ - dict_t *d; - - d = [self findKeyword:name]; - if (d != NULL) - return d->value; - - return ""; -} - -// -// Search for keyword, return the value -// -- (unsigned int)getValueFor:(char *)name -{ - dict_t *d; - - d = [self findKeyword:name]; - if (d != NULL) - return atol(d->value); - + Sys_Printf ("Dict copy: not implemented\n"); return 0; } -// -// Return # of units in keyword's value -// -- (int) getValueUnits:(char *)key +- (id) initFromFile: (FILE *)fp { - id temp; - int count; - - temp = [self parseMultipleFrom:key]; - count = [temp count]; - [temp free]; - - return count; -} + dstring_t *text = dstring_newstr (); + char *str; + size_t read; + const size_t readsize = 1024; -// -// Convert List to string -// -- (char *)convertListToString:(id)list -{ - int i; - int max; - char tempstr[4096]; - char *s; - char *newstr; - - max = [list count]; - tempstr[0] = 0; - for (i = 0;i < max;i++) - { - s = [list elementAt:i]; - strcat(tempstr,s); - strcat(tempstr," "); - } - newstr = malloc(strlen(tempstr)+1); - strcpy(newstr,tempstr); - - return newstr; -} + [self init]; -// -// JDC: I wrote this to simplify removing vectors -// -- removeKeyword:(char *)key -{ - dict_t *d; + do { + str = dstring_reservestr (text, readsize); + read = fread (str, 1, readsize, fp); + if (read) + str[read] = 0; + } while (read == readsize); - d = [self findKeyword:key]; - if (d == NULL) - return self; - [self removeElementAt:d - (dict_t*)dataPtr]; + + plist = PL_GetPropertyList (text->str); + dstring_delete (text); + if (!plist) + return 0; return self; } -// -// Delete string from keyword's value -// -- delString:(char *)string fromValue:(char *)key +- (void) dealloc { - id temp; - int count; - int i; - char *s; - dict_t *d; - - d = [self findKeyword:key]; - if (d == NULL) - return NULL; - temp = [self parseMultipleFrom:key]; - count = [temp count]; - for (i = 0;i < count;i++) - { - s = [temp elementAt:i]; - if (!strcmp(s,string)) - { - [temp removeElementAt:i]; - free(d->value); - d->value = [self convertListToString:temp]; - [temp free]; - - break; - } - } + if (plist) + PL_Free (plist); + [super dealloc]; +} + +// =============================================== +// +// Dictionary pair functions +// +// =============================================== + +- (id) writeBlockTo: (FILE *)fp +{ + char *data; + + data = PL_WritePropertyList (plist); + fputs (data, fp); + free (data); + return self; } -// -// Add string to keyword's value -// -- addString:(char *)string toValue:(char *)key +- (id) writeFile: (const char *)path { - char *newstr; - char spacing[] = "\t"; - dict_t *d; - - d = [self findKeyword:key]; - if (d == NULL) + FILE *fp; + + fp = fopen (path, "w+t"); + if (fp != NULL) { + printf ("Writing dictionary file %s.\n", path); + fprintf (fp, "// QE_Project file %s\n", path); + [self writeBlockTo: fp]; + fclose (fp); + } else { + printf ("Error writing %s!\n", path); return NULL; - newstr = malloc(strlen(string) + strlen(d->value) + strlen(spacing) + 1); - strcpy(newstr,d->value); - strcat(newstr,spacing); - strcat(newstr,string); - free(d->value); - d->value = newstr; - + } + return self; } -//=============================================== +// =============================================== // -// Use these for multiple parameters in a keyword value +// Utility methods // -//=============================================== -char *searchStr; -char item[4096]; +// =============================================== -- setupMultiple:(char *)value +// Change a keyword's string +- (id) changeStringFor: (const char *)key to: (const char *)value { - searchStr = value; + PL_D_AddObject (plist, key, PL_NewString (value)); return self; } -- (char *)getNextParameter +- (plitem_t *) getArrayFor: (const char *)name { - char *s; - - if (!searchStr) - return NULL; - strcpy(item,searchStr); - s = FindWhitespcInBuffer(item); - if (!*s) - searchStr = NULL; - else - { - *s = 0; - searchStr = FindNonwhitespcInBuffer(s+1); - } - return item; + plitem_t *item; + item = PL_ObjectForKey (plist, name); + if (item && PL_Type (item) == QFArray) + return item; + return 0; } -// -// Parses a keyvalue string & returns a Storage full of those items -// -- (id) parseMultipleFrom:(char *)key +// Search for keyword, return the string * +- (const char *) getStringFor: (const char *)name { - #define ITEMSIZE 128 - id stuff; - char string[ITEMSIZE]; - char *s; - - s = [self getStringFor:key]; - if (s == NULL) - return NULL; - - stuff = [[Storage alloc] - initCount:0 - elementSize:ITEMSIZE - description:NULL]; - - [self setupMultiple:s]; - while((s = [self getNextParameter])) - { - bzero(string,ITEMSIZE); - strcpy(string,s); - [stuff addElement:string]; - } - - return stuff; + plitem_t *item; + const char *str; + + item = PL_ObjectForKey (plist, name); + if (item && (str = PL_String (item))) + return str; + return ""; } -//=============================================== -// -// Dictionary pair parsing -// -//=============================================== - -// -// parse all keyword/value pairs within { } 's -// -- (id) parseBraceBlock:(FILE *)fp +// Search for keyword, return the value +- (unsigned int) getValueFor: (const char *)name { - int c; - dict_t pair; - char string[1024]; - - c = FindBrace(fp); - if (c == -1) - return NULL; - - while((c = FindBrace(fp)) != '}') - { - if (c == -1) - return NULL; -// c = FindNonwhitespc(fp); -// if (c == -1) -// return NULL; -// CopyUntilWhitespc(fp,string); + return atol ([self getStringFor: name]); +} -// JDC: fixed to allow quoted keys - c = FindNonwhitespc(fp); - if (c == -1) - return NULL; - c = fgetc(fp); - if ( c == '\"') - CopyUntilQuote(fp,string); - else - { - ungetc (c,fp); - CopyUntilWhitespc(fp,string); - } +// Return # of units in keyword's value +- (int) getValueUnits: (const char *)key +{ + plitem_t *item; - pair.key = malloc(strlen(string)+1); - strcpy(pair.key,string); - - c = FindQuote(fp); - CopyUntilQuote(fp,string); - pair.value = malloc(strlen(string)+1); - strcpy(pair.value,string); - - [super addElement:&pair]; - c = FindBrace(fp); - } - - return self; + item = PL_ObjectForKey (plist, key); + if (!item || PL_Type (item) != QFArray) + return 0; + + return PL_A_NumObjects (item); } @end - -//=============================================== -// -// C routines for string parsing -// -//=============================================== -int GetNextChar(FILE *fp) -{ - int c; - int c2; - - c = getc(fp); - if (c == EOF) - return -1; - if (c == '/') // parse comments - { - c2 = getc(fp); - if (c2 == '/') - { - while((c2 = getc(fp)) != '\n'); - c = getc(fp); - } - else - ungetc(c2,fp); - } - return c; -} - -void CopyUntilWhitespc(FILE *fp,char *buffer) -{ - int count = 800; - int c; - - while(count--) - { - c = GetNextChar(fp); - if (c == EOF) - return; - if (c <= ' ') - { - *buffer = 0; - return; - } - *buffer++ = c; - } -} - -void CopyUntilQuote(FILE *fp,char *buffer) -{ - int count = 800; - int c; - - while(count--) - { - c = GetNextChar(fp); - if (c == EOF) - return; - if (c == '\"') - { - *buffer = 0; - return; - } - *buffer++ = c; - } -} - -int FindBrace(FILE *fp) -{ - int count = 800; - int c; - - while(count--) - { - c = GetNextChar(fp); - if (c == EOF) - return -1; - if (c == '{' || - c == '}') - return c; - } - return -1; -} - -int FindQuote(FILE *fp) -{ - int count = 800; - int c; - - while(count--) - { - c = GetNextChar(fp); - if (c == EOF) - return -1; - if (c == '\"') - return c; - } - return -1; -} - -int FindWhitespc(FILE *fp) -{ - int count = 800; - int c; - - while(count--) - { - c = GetNextChar(fp); - if (c == EOF) - return -1; - if (c <= ' ') - { - ungetc(c,fp); - return c; - } - } - return -1; -} - -int FindNonwhitespc(FILE *fp) -{ - int count = 800; - int c; - - while(count--) - { - c = GetNextChar(fp); - if (c == EOF) - return -1; - if (c > ' ') - { - ungetc(c,fp); - return c; - } - } - return -1; -} - -char *FindWhitespcInBuffer(char *buffer) -{ - int count = 1000; - char *b = buffer; - - while(count--) - if (*b <= ' ') - return b; - else - b++; - return NULL; -} - -char *FindNonwhitespcInBuffer(char *buffer) -{ - int count = 1000; - char *b = buffer; - - while(count--) - if (*b > ' ') - return b; - else - b++; - return NULL; -} diff --git a/tools/Forge/Bundles/MapEdit/DictList.h b/tools/Forge/Bundles/MapEdit/DictList.h deleted file mode 100644 index d2878b6cb..000000000 --- a/tools/Forge/Bundles/MapEdit/DictList.h +++ /dev/null @@ -1,12 +0,0 @@ - -#include - -@interface DictList:List -{ -} - -- initListFromFile:(FILE *)fp; -- writeListFile:(char *)filename; -- (id) findDictKeyword:(char *)key; - -@end diff --git a/tools/Forge/Bundles/MapEdit/DictList.m b/tools/Forge/Bundles/MapEdit/DictList.m deleted file mode 100644 index 66f78b4b7..000000000 --- a/tools/Forge/Bundles/MapEdit/DictList.m +++ /dev/null @@ -1,69 +0,0 @@ - -#include "qedefs.h" - -@implementation DictList - -// -// Read in variable # of objects from FILE * -// -- initListFromFile:(FILE *)fp -{ - id d; - - [super init]; - do - { - d = [(Dict *)[Dict alloc] initFromFile:fp]; - if (d != NULL) - [self addObject:d]; - } while(d != NULL); - [d free]; - - return self; -} - -// -// Write out list file -// -- writeListFile:(char *)filename -{ - FILE *fp; - int i; - id obj; - - fp = fopen(filename,"w+t"); - if (fp == NULL) - return NULL; - - fprintf(fp,"// Object List written by QuakeEd\n"); - - for (i = 0;i < maxElements;i++) - { - obj = [self objectAt:i]; - [obj writeBlockTo:fp]; - } - fclose(fp); - - return self; -} - -// -// Find the keyword in all the Dict objects -// -- (id) findDictKeyword:(char *)key -{ - int i; - dict_t *d; - id dict; - - for (i = 0;i < maxElements;i++) - { - dict = [self objectAt:i]; - d = [(Dict *)dict findKeyword:key]; - if (d != NULL) - return dict; - } - return NULL; -} - -@end diff --git a/tools/Forge/Bundles/MapEdit/Entity.h b/tools/Forge/Bundles/MapEdit/Entity.h index d4d5191c4..3a6919442 100644 --- a/tools/Forge/Bundles/MapEdit/Entity.h +++ b/tools/Forge/Bundles/MapEdit/Entity.h @@ -1,40 +1,46 @@ +#ifndef Entity_h +#define Entity_h -#define MAX_KEY 64 -#define MAX_VALUE 128 -typedef struct epair_s -{ - struct epair_s *next; - char key[MAX_KEY]; - char value[MAX_VALUE]; +#include + +#include "QF/mathlib.h" + +typedef struct epair_s { + struct epair_s *next; + char *key; + char *value; } epair_t; // an Entity is a list of brush objects, with additional key / value info -@interface Entity : NSObject +@interface Entity: NSMutableArray { - epair_t *epairs; - BOOL modifiable; + NSMutableArray *array; + epair_t *epairs; + BOOL modifiable; } -- initClass: (char *)classname; -- initFromTokens; +- (Entity *) initClass: (const char *)classname; +- (Entity *) initFromScript: (struct script_s *)script; -- free; +- (oneway void) dealloc; -- (BOOL)modifiable; -- setModifiable: (BOOL)m; +- (BOOL) modifiable; +- (void) setModifiable: (BOOL)m; -- (char *)targetname; +- (const char *) targetname; -- writeToFILE: (FILE *)f region:(BOOL)reg; +- (void) writeToFILE: (FILE *)f region: (BOOL)reg; -- (char *)valueForQKey: (char *)k; -- getVector: (vec3_t)v forKey: (char *)k; -- setKey:(char *)k toValue:(char *)v; -- (int)numPairs; -- (epair_t *)epairs; -- removeKeyPair: (char *)key; +- (const char *) valueForQKey: (const char *)k; +- (void) getVector: (vec3_t)v forKey: (const char *)k; + +- (void) setKey: (const char *)k + toValue: (const char *)v; + +- (int) numPairs; +- (epair_t *) epairs; +- (void) removeKeyPair: (const char *)key; @end - - +#endif // Entity_h diff --git a/tools/Forge/Bundles/MapEdit/Entity.m b/tools/Forge/Bundles/MapEdit/Entity.m index 5e33340e9..4ca3b4d2c 100644 --- a/tools/Forge/Bundles/MapEdit/Entity.m +++ b/tools/Forge/Bundles/MapEdit/Entity.m @@ -1,27 +1,36 @@ +#include "QF/dstring.h" +#include "QF/script.h" +#include "QF/sys.h" +#include "QF/va.h" -#include "qedefs.h" +#include "Entity.h" +#include "EntityClass.h" +#include "TexturePalette.h" +#include "SetBrush.h" +#include "Map.h" +#include "CameraView.h" + +#define THING Entity +#include "THING+NSArray.m" @implementation Entity -vec3_t bad_mins = {-8, -8, -8}; -vec3_t bad_maxs = {8, 8, 8}; +vec3_t bad_mins = {-8, -8, -8}; +vec3_t bad_maxs = {8, 8, 8}; -- createFixedBrush: (vec3_t)org +- (id) createFixedBrush: (vec3_t)org { - vec3_t emins, emaxs; - float *v, *v2, *color; - id new; - texturedef_t td; - -// get class + vec3_t emins, emaxs; + float *v, *v2, *color; + id new; + texturedef_t td; + + // get class new = [entity_classes_i classForName: [self valueForQKey: "classname"]]; - if (new) - { + if (new) { v = [new mins]; v2 = [new maxs]; - } - else - { + } else { v = bad_mins; v2 = bad_maxs; } @@ -29,239 +38,227 @@ vec3_t bad_maxs = {8, 8, 8}; color = [new drawColor]; modifiable = NO; - memset(&td,0,sizeof(td)); - strcpy (td.texture,"entity"); + memset (&td, 0, sizeof (td)); + strcpy (td.texture, "entity"); VectorAdd (org, v, emins); VectorAdd (org, v2, emaxs); - new = [[SetBrush alloc] initOwner: self mins:emins maxs:emaxs - texture: &td]; + new = [[SetBrush alloc] initOwner: self mins: emins maxs: emaxs texture: &td]; [new setEntityColor: color]; [self addObject: new]; - + return self; } -- copyWithZone:(NSZone *)zone +- (id) copyWithZone: (NSZone *) zone { - id new, nb; - epair_t *e; - int i; - - new = [[Entity alloc] init]; + id new, nb; + epair_t *e; + int i, c; + + new = [[Entity allocWithZone: zone] init]; [new setModifiable: modifiable]; - - for (e=epairs ; e ; e=e->next) - { // don't copy target and targetname fields - if (strncmp(e->key,"target",6)) + + for (e = epairs; e; e = e->next) { + // don't copy target and targetname fields + if (strncmp (e->key, "target", 6)) [new setKey: e->key toValue: e->value]; } - for (i=0 ; inext; + free (e->key); + free (e->value); free (e); } - return [super free]; + [array release]; + [super dealloc]; } -- (BOOL)modifiable +- (BOOL) modifiable { return modifiable; } -- setModifiable: (BOOL)m +- (void) setModifiable: (BOOL)m { modifiable = m; - return self; + return; } -- removeObject: o +- (void) removeObject: (id)o { - o = [super removeObject: o]; - if (numElements) - return o; -// the entity is empty, so remove the entire thing - if ( self == [map_i objectAt: 0]) - return o; // never remove the world - + [super removeObject: o]; + if ([self count]) + return; + + // the entity is empty, so remove the entire thing + if (self == [map_i objectAtIndex: 0]) // unless it's the world... + return; + [map_i removeObject: self]; - [self free]; - - return o; + [self release]; } - -- (char *)valueForQKey: (char *)k +- (const char *) valueForQKey: (const char *)k { - epair_t *e; - static char ret[64]; - - for (e=epairs ; e ; e=e->next) - if (!strcmp(k,e->key)) - { - strcpy (ret, e->value); - return ret; - } + epair_t *e; + + for (e = epairs; e; e = e->next) { + if (!strcmp (k, e->key)) + return e->value; + } return ""; } -- getVector: (vec3_t)v forKey: (char *)k +- (void) getVector: (vec3_t)v + forKey: (const char *)k { - char *c; - + const char *c; + c = [self valueForQKey: k]; - v[0] = v[1] = v[2] = 0; - + sscanf (c, "%f %f %f", &v[0], &v[1], &v[2]); +} + +- (id) print +{ + epair_t *e; + + for (e = epairs; e; e = e->next) + printf ("%20s : %20s\n", e->key, e->value); return self; } -- print +- (void) setKey: (const char *)k + toValue: (const char *)v { - epair_t *e; - - for (e=epairs ; e ; e=e->next) - printf ("%20s : %20s\n",e->key, e->value); + epair_t *e; - return self; -} - -- setKey:(char *)k toValue:(char *)v -{ - epair_t *e; - - if (strlen(k) > MAX_KEY) - Error ("setKey: %s > MAX_KEY", k); - if (strlen(v) > MAX_VALUE) - Error ("setKey: %s > MAX_VALUE", v); - while (*k && *k <= ' ') k++; - if (!*k) - return self; // don't set NULL values - - for (e=epairs ; e ; e=e->next) - if (!strcmp(k,e->key)) - { - memset (e->value, 0, sizeof(e->value)); - strcpy (e->value, v); - return self; - } - e = malloc (sizeof(epair_t)); - memset (e, 0, sizeof(epair_t)); - - strcpy (e->key, k); - strcpy (e->value, v); + // don't set NULL values + if (!*k) + return; + + for (e = epairs; e; e = e->next) { + if (!strcmp (k, e->key)) { + if (e->value == v) + return; + free (e->value); + e->value = strdup (v); + return; + } + } + + e = malloc (sizeof (epair_t)); + + e->key = strdup (k); + e->value = strdup (v); e->next = epairs; epairs = e; - - return self; } -- (int)numPairs +- (int) numPairs { - int i; - epair_t *e; - - i=0; - for (e=epairs ; e ; e=e->next) + int i; + epair_t *e; + + i = 0; + for (e = epairs; e; e = e->next) i++; + return i; } -- (epair_t *)epairs +- (epair_t *) epairs { return epairs; } -- removeKeyPair: (char *)key +- (void) removeKeyPair: (char *)key { - epair_t *e, *e2; - + epair_t *e, *e2; + if (!epairs) - return self; + return; + e = epairs; - if (!strcmp(e->key, key)) - { + if (!strcmp (e->key, key)) { epairs = e->next; free (e); - return self; + return; } - - for (; e ; e=e->next) - { - if (e->next && !strcmp(e->next->key, key)) - { + + for ( ; e; e = e->next) { + if (e->next && !strcmp (e->next->key, key)) { e2 = e->next; e->next = e2->next; free (e2); - return self; + return; } } - - printf ("WARNING: removeKeyPair: %s not found\n", key); - return self; -} + printf ("WARNING: removeKeyPair: %s not found\n", key); + return; +} /* ============= @@ -270,37 +267,33 @@ targetname If the entity does not have a "targetname" key, a unique one is generated ============= */ -- (char *)targetname +- (const char *) targetname { - char *t; - int i, count; - id ent; - int tval, maxt; - char name[20]; - + const char *t; + int i, count; + id ent; + int tval, maxt; + t = [self valueForQKey: "targetname"]; if (t && t[0]) return t; - -// make a unique name of the form t + + // make a unique name of the form t count = [map_i count]; maxt = 0; - for (i=1 ; i maxt) maxt = tval; } - - sprintf (name,"t%i",maxt+1); - - [self setKey: "targetname" toValue: name]; - - return [self valueForQKey: "targetname"]; // so it's not on the stack + + [self setKey: "targetname" toValue: va ("t%i", maxt + 1)]; + + return [self valueForQKey: "targetname"]; } /* @@ -311,167 +304,159 @@ FILE METHODS ============================================================================== */ -int nument; +int nument; -- initFromTokens +- (Entity *) initFromScript: (script_t *)script { - char key[MAXTOKEN]; - id eclass, brush; - char *spawn; - vec3_t emins, emaxs; - vec3_t org; - texturedef_t td; - esize_t esize; - int i, c; - float *color; - - [self init]; + char *key; + id eclass, brush; + const char *spawn; + vec3_t emins, emaxs; + vec3_t org; + texturedef_t td; + esize_t esize; + int i, c; + float *color; - if (!GetToken (true)) - { - [self free]; + self = [super init]; + array = [[NSMutableArray alloc] init]; + + if (!Script_GetToken (script, true)) { + [self dealloc]; return nil; } - if (strcmp (token, "{") ) - Error ("initFromFileP: { not found"); - - do - { - if (!GetToken (true)) + if (strcmp (Script_Token (script), "{")) + Sys_Error ("initFromScript: { not found"); + + do { + if (!Script_GetToken (script, true)) break; - if (!strcmp (token, "}") ) + if (!strcmp (Script_Token (script), "}")) break; - if (!strcmp (token, "{") ) - { // read a brush - brush = [[SetBrush alloc] initFromTokens: self]; + if (!strcmp (Script_Token (script), "{")) { + // read a brush + brush = [[SetBrush alloc] initFromScript: script owner: self]; [self addObject: brush]; - } - else - { // read a key / value pair - strcpy (key, token); - GetToken (false); - [self setKey: key toValue:token]; + } else { + // read a key / value pair + key = strdup (Script_Token (script)); + Script_GetToken (script, false); + [self setKey: key toValue: Script_Token (script)]; + free (key); } } while (1); - + nument++; -// get class + // get class spawn = [self valueForQKey: "classname"]; eclass = [entity_classes_i classForName: spawn]; esize = [eclass esize]; [self getVector: org forKey: "origin"]; - - if ([self count] && esize != esize_model) - { - printf ("WARNING:Entity with brushes and wrong model type\n"); - [self empty]; + + if ([self count] && esize != esize_model) { + printf ("WARNING:Entity with brushes and wrong model type\n"); + [self removeAllObjects]; } - - if (![self count] && esize == esize_model) - { - printf ("WARNING:Entity with no brushes and esize_model\n"); + + if (![self count] && esize == esize_model) { + printf ("WARNING:Entity with no brushes and esize_model: %s\n", + [self valueForQKey: "classname"]); [texturepalette_i getTextureDef: &td]; - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { emins[i] = org[i] - 8; emaxs[i] = org[i] + 8; } - brush = [[SetBrush alloc] initOwner: self mins:emins maxs:emaxs - texture: &td]; + brush = + [[SetBrush alloc] initOwner: self mins: emins maxs: emaxs texture: &td]; [self addObject: brush]; } - -// create a brush if needed + + // create a brush if needed if (esize == esize_fixed) [self createFixedBrush: org]; else modifiable = YES; -// set all the brush colors + // set all the brush colors color = [eclass drawColor]; c = [self count]; - for (i=0 ; inext) - fprintf (f,"\"%s\"\t\"%s\"\n", e->key, e->value); - -// fixed size entities don't save out brushes - if ( modifiable ) - { - for (i=0 ; inext) + fprintf (f, "\"%s\"\t\"%s\"\n", e->key, e->value); + + // fixed size entities don't save out brushes + if (modifiable) { + for (i = 0; i < [self count]; i++) + [[self objectAtIndex: i] writeToFILE: f region: reg]; + } + + fprintf (f, "}\n"); + + if (oldang) { + [self setKey: "angle" toValue: oldang]; + free (oldang); + } + + return; } /* diff --git a/tools/Forge/Bundles/MapEdit/EntityClass.h b/tools/Forge/Bundles/MapEdit/EntityClass.h index a58719afc..65d016577 100644 --- a/tools/Forge/Bundles/MapEdit/EntityClass.h +++ b/tools/Forge/Bundles/MapEdit/EntityClass.h @@ -1,42 +1,46 @@ +#ifndef EntityClass_h +#define EntityClass_h + #include -#include "mathlib.h" -typedef enum {esize_model, esize_fixed} esize_t; +#include "QF/mathlib.h" -#define MAX_FLAGS 8 +typedef enum {esize_model, esize_fixed} esize_t; -@interface EntityClass : Object +#define MAX_FLAGS 8 + +@interface EntityClass: NSObject { - char *name; - esize_t esize; - vec3_t mins, maxs; - vec3_t color; - char *comments; - char flagnames[MAX_FLAGS][32]; + char *name; + esize_t esize; + vec3_t mins, maxs; + vec3_t color; + char *comments; + char *flagnames[MAX_FLAGS]; } -- initFromText: (char *)text; -- (char *)classname; -- (esize_t)esize; -- (float *)mins; // only for esize_fixed -- (float *)maxs; // only for esize_fixed -- (float *)drawColor; -- (char *)comments; -- (char *)flagName: (unsigned)flagnum; +- (id) initFromText: (const char *)text source: (const char *)filename; -@end +- (const char *) classname; +- (esize_t) esize; +- (float *) mins; // only for esize_fixed +- (float *) maxs; // only for esize_fixed +- (float *) drawColor; +- (const char *) comments; +- (const char *) flagName: (unsigned)flagnum; -extern id entity_classes_i; +@end extern id entity_classes_i; -@interface EntityClassList : NSMutableArray +@interface EntityClassList: NSMutableArray { - id nullclass; - char *source_path; + NSMutableArray *array; + id nullclass; + char *source_path; } -- initForSourceDirectory: (char *)path; -- (id)classForName: (char *)name; -- (void)scanDirectory; +- (id) initForSourceDirectory: (const char *)path; +- (id) classForName: (const char *)name; +- (void) scanDirectory; @end - +#endif // EntityClass_h diff --git a/tools/Forge/Bundles/MapEdit/EntityClass.m b/tools/Forge/Bundles/MapEdit/EntityClass.m index ed0a881b7..db5ca380e 100644 --- a/tools/Forge/Bundles/MapEdit/EntityClass.m +++ b/tools/Forge/Bundles/MapEdit/EntityClass.m @@ -1,8 +1,33 @@ +#include -#include "qedefs.h" +#include "QF/quakeio.h" +#include "QF/script.h" +#include "QF/sys.h" +#include "QF/va.h" + +#include "EntityClass.h" @implementation EntityClass +static int +parse_vector (script_t * script, vec3_t vec) +{ + int r; + + if (!Script_GetToken (script, 0)) + return 0; + if (strcmp (Script_Token (script), "(")) + return 0; + r = sscanf (script->p, "%f %f %f)", &vec[0], &vec[1], &vec[2]); + if (r != 3) + return 0; + while (strcmp (Script_Token (script), ")")) { + if (!Script_GetToken (script, 0)) + return 0; + } + return 1; +} + // the classname, color triple, and bounding box are parsed out of comments // A ? size means take the exact brush size. // @@ -11,255 +36,235 @@ // // Flag names can follow the size description: // -// /*QUAKED func_door (0 .5 .8) ? START_OPEN STONE_SOUND DOOR_DONT_LINK GOLD_KEY SILVER_KEY +// /*QUAKED func_door (0 .5 .8) ? START_OPEN STONE_SOUND DOOR_DONT_LINK GOLD_KEY +// SILVER_KEY -char *debugname; -- initFromText: (char *)text +- (id) initFromText: (const char *)text source: (const char *)filename { - char *t; - int len; - int r, i; - char parms[256], *p; - + const char *t; + size_t len; + int i; + script_t *script; + [super init]; - - text += strlen("/*QUAKED "); - -// grab the name - text = COM_Parse (text); - name = malloc (strlen(com_token)+1); - strcpy (name, com_token); - debugname = name; - -// grab the color - r = sscanf (text," (%f %f %f)", &color[0], &color[1], &color[2]); - if (r != 3) - return NULL; - - while (*text != ')') - { - if (!*text) - return NULL; - text++; - } - text++; - -// get the size - text = COM_Parse (text); - if (com_token[0] == '(') - { // parse the size as two vectors + + text += strlen ("/*QUAKED "); + + script = Script_New (); + Script_Start (script, filename, text); + + // grab the name + if (!Script_GetToken (script, 0)) + return 0; + if (!strcmp (Script_Token (script), "*/")) + return 0; + name = strdup (Script_Token (script)); + + // grab the color + if (!parse_vector (script, color)) + return 0; + // get the size + if (!Script_GetToken (script, 0)) + return 0; + if (!strcmp (Script_Token (script), "(")) { + Script_UngetToken (script); + if (!parse_vector (script, mins)) + return 0; + if (!parse_vector (script, maxs)) + return 0; esize = esize_fixed; - r = sscanf (text,"%f %f %f) (%f %f %f)", &mins[0], &mins[1], &mins[2], &maxs[0], &maxs[1], &maxs[2]); - if (r != 6) - return NULL; - - for (i=0 ; i<2 ; i++) - { - while (*text != ')') - { - if (!*text) - return NULL; - text++; - } - text++; - } - } - else - { // use the brushes + } else if (!strcmp (Script_Token (script), "?")) { + // use the brushes esize = esize_model; + } else { + return 0; } - -// get the flags - - -// copy to the first /n - p = parms; - while (*text && *text != '\n') - *p++ = *text++; - *p = 0; - text++; - -// any remaining words are parm flags - p = parms; - for (i=0 ; i<8 ; i++) - { - p = COM_Parse (p); - if (!p) + // get the flags + // any remaining words on the line are parm flags + for (i = 0; i < MAX_FLAGS; i++) { + if (!Script_TokenAvailable (script, 0)) break; - strcpy (flagnames[i], com_token); - } + Script_GetToken (script, 0); + flagnames[i] = strdup (Script_Token (script)); + } + while (Script_TokenAvailable (script, 0)) + Script_GetToken (script, 0); -// find the length until close comment - for (t=text ; t[0] && !(t[0]=='*' && t[1]=='/') ; t++) - ; - -// copy the comment block out - len = t-text; - comments = malloc (len+1); + // find the length until close comment + for (t = script->p; t[0] && !(t[0] == '*' && t[1] == '/'); t++) + ; + + // copy the comment block out + len = t - text; + comments = malloc (len + 1); memcpy (comments, text, len); comments[len] = 0; - + return self; } -- (esize_t)esize +- (esize_t) esize { return esize; } -- (char *)classname +- (const char *) classname { return name; } -- (float *)mins +- (float *) mins { return mins; } -- (float *)maxs +- (float *) maxs { return maxs; } -- (float *)drawColor +- (float *) drawColor { return color; } -- (char *)comments +- (const char *) comments { return comments; } - -- (char *)flagName: (unsigned)flagnum +- (const char *) flagName: (unsigned)flagnum { if (flagnum >= MAX_FLAGS) - Error ("EntityClass flagName: bad number"); + Sys_Error ("EntityClass flagName: bad number"); return flagnames[flagnum]; } @end +// =========================================================================== -//=========================================================================== +#define THING EntityClassList +#include "THING+NSArray.m" @implementation EntityClassList - /* ================= insertEC: ================= */ -- (void)insertEC: ec +- (void) insertEC: ec { - char *name; - int i; - + const char *name; + unsigned int i; + name = [ec classname]; - for (i=0 ; i<[self count] ; i++) - { - if (strcasecmp (name, [[self objectAtIndex: i] classname]) < 0) - { - [self insertObject: ec atIndex:i]; + for (i = 0; i < [self count]; i++) { + if (strcasecmp (name, [[self objectAtIndex: i] classname]) < 0) { + [self insertObject: ec atIndex: i]; return; } } [self addObject: ec]; } - /* ================= scanFile ================= */ -- (void)scanFile: (char *)filename +- (void) scanFile: (const char *)filename { - int size; - char *data; - id cl; - int i; - char path[1024]; - - sprintf (path,"%s/%s", source_path, filename); - - size = LoadFile (path, (void *)&data); - - for (i=0 ; id_name); if (len <= 3) continue; - if (!strcmp (ent->d_name+len-3,".qc")) + if (!strcmp (ent->d_name + len - 3, ".qc")) [self scanFile: ent->d_name]; } } +id entity_classes_i; -id entity_classes_i; - - -- initForSourceDirectory: (char *)path +- (id) initForSourceDirectory: (const char *)path { - [super init]; - - source_path = path; + self = [super init]; + array = [[NSMutableArray alloc] init]; + + source_path = strdup (path); // FIXME leak? [self scanDirectory]; - + entity_classes_i = self; - - nullclass = [[EntityClass alloc] initFromText: -"/*QUAKED UNKNOWN_CLASS (0 0.5 0) ?"]; + + nullclass = [[EntityClass alloc] + initFromText: "/*QUAKED UNKNOWN_CLASS (0 0.5 0) ?*/" + source: va ("%s:%d", __FILE__, __LINE__ - 1)]; return self; } -- (id)classForName: (char *)name +- (id) classForName: (const char *)name { - int i; - id o; - - for (i=0 ; i<[self count] ; i++) - { + unsigned int i; + id o; + + for (i = 0; i < [self count]; i++) { o = [self objectAtIndex: i]; - if (!strcmp (name,[o classname]) ) + if (!strcmp (name, [o classname])) return o; } - + return nullclass; } - @end - diff --git a/tools/Forge/Bundles/MapEdit/GNUmakefile b/tools/Forge/Bundles/MapEdit/GNUmakefile index ea70af447..a8db9ca94 100644 --- a/tools/Forge/Bundles/MapEdit/GNUmakefile +++ b/tools/Forge/Bundles/MapEdit/GNUmakefile @@ -1,27 +1,80 @@ +include GNUmakefile.find-makefiles + include $(GNUSTEP_MAKEFILES)/common.make -BUNDLE_NAME= MapEdit -BUNDLE_EXTENSION= .forgeb # -# We don't install this bundle, it goes inside the app. +# Subprojects # -BUNDLE_INSTALL_DIR= none -MapEdit_STANDARD_INSTALL= no +SUBPROJECTS= -MapEdit_RESOURCE_FILES= \ - MapEdit.gorm +# +# Main application +# +PACKAGE_NAME= QuakeEd +APP_NAME= QuakeEd +QuakeEd_PRINCIPAL_CLASS= QuakeEdApp +QuakeEd_APPLICATION_ICON= -MapEdit_OBJC_FILES= \ - CameraView.m Clipper.m EntityClass.m KeypairView.m PopScrollView.m ZView.m misc.m render.m +# +# Additional libraries +# +ADDITIONAL_GUI_LIBS += -MapEdit_HEADERS= \ - EntityClass.h +# +# Resource files +# +QuakeEd_MAIN_MODEL_FILE= MapEdit.gorm +QuakeEd_RESOURCE_FILES= \ + MapEdit.gorm \ + help.txt \ + ../../Images/DownArrow.tiff \ + ../../Images/UpArrow.tiff \ + ../../Images/i_90d.tiff \ + ../../Images/i_add.tiff \ + ../../Images/i_brushes.tiff \ + ../../Images/i_fliph.tiff \ + ../../Images/i_flipv.tiff \ + ../../Images/i_quakeed.tiff \ + ../../Images/i_sub.tiff \ + ../../Images/short.tiff \ + ../../Images/tall.tiff -MapEdit_PRINCIPAL_CLASS= \ - MapEdit +QuakeEd_LOCALIZED_RESOURCE_FILES= + +# Languages we're localized for +QuakeEd_LANGUAGES= \ + English + +# +# Header files +# +QuakeEd_HEADERS= \ + CameraView.h Clipper.h Dict.h Entity.h EntityClass.h \ + InspectorControl.h KeypairView.h Map.h PopScrollView.h Preferences.h \ + Project.h QuakeEd.h SetBrush.h Storage.h TexturePalette.h TextureView.h \ + Things.h XYView.h ZScrollView.h ZView.h render.h \ + \ + THING+NSArray.m + +# +# Class files +# +QuakeEd_OBJC_FILES= \ + CameraView.m Clipper.m Dict.m Entity.m EntityClass.m \ + InspectorControl.m KeypairView.m Map.m PopScrollView.m Preferences.m \ + Project.m QuakeEd.m QuakeEd_main.m SetBrush.m Storage.m TexturePalette.m \ + TextureView.m Things.m XYView.m ZScrollView.m ZView.m render.m + +# +# C files +# +QuakeEd_C_FILES= -include GNUmakefile.preamble +-include GNUmakefile.local -include $(GNUSTEP_MAKEFILES)/bundle.make +include $(GNUSTEP_MAKEFILES)/aggregate.make +include $(GNUSTEP_MAKEFILES)/application.make -include GNUmakefile.postamble + diff --git a/tools/Forge/Bundles/MapEdit/GNUmakefile.bundle b/tools/Forge/Bundles/MapEdit/GNUmakefile.bundle new file mode 100644 index 000000000..96effd62e --- /dev/null +++ b/tools/Forge/Bundles/MapEdit/GNUmakefile.bundle @@ -0,0 +1,29 @@ +include GNUmakefile.find-makefiles + +include $(GNUSTEP_MAKEFILES)/common.make + +BUNDLE_NAME= MapEdit +BUNDLE_EXTENSION= .forgeb +# +# We don't install this bundle, it goes inside the app. +# +BUNDLE_INSTALL_DIR= none +MapEdit_STANDARD_INSTALL= no + +MapEdit_RESOURCE_FILES= \ + MapEdit.gorm + +MapEdit_OBJC_FILES= \ + CameraView.m Clipper.m Dict.m DictList.m Entity.m EntityClass.m InspectorControl.m KeypairView.m Map.m PopScrollView.m Preferences.m Project.m QuakeEd.m QuakeEd_main.m SetBrush.m Storage.m TexturePalette.m TextureView.m Things.m XYView.m ZScrollView.m ZView.m render.m + +MapEdit_HEADERS= \ + EntityClass.h + +MapEdit_PRINCIPAL_CLASS= \ + MapEdit + +-include GNUmakefile.preamble + +include $(GNUSTEP_MAKEFILES)/bundle.make + +-include GNUmakefile.postamble diff --git a/tools/Forge/Bundles/MapEdit/GNUmakefile.find-makefiles b/tools/Forge/Bundles/MapEdit/GNUmakefile.find-makefiles new file mode 100644 index 000000000..3d7f8f4e4 --- /dev/null +++ b/tools/Forge/Bundles/MapEdit/GNUmakefile.find-makefiles @@ -0,0 +1,13 @@ +# Make sure that GNUSTEP_MAKEFILES is set. +# First, try the "gnustep-config" program which should be in the path somewhere. +# If that fails, try sourcing the GNUstep.conf file (which should be a legal Make fragment). +# Finally, just give up and assume the default value. +ifeq ($(GNUSTEP_MAKEFILES),) +GNUSTEP_MAKEFILES=$(shell gnustep-config --variable=GNUSTEP_MAKEFILES) +ifeq ($(GNUSTEP_MAKEFILES),) +-include /etc/GNUstep/GNUstep.conf +ifeq ($(GNUSTEP_MAKEFILES),) +GNUSTEP_MAKEFILES=/usr/GNUstep/Library/Makefiles +endif +endif +endif diff --git a/tools/Forge/Bundles/MapEdit/GNUmakefile.preamble b/tools/Forge/Bundles/MapEdit/GNUmakefile.preamble index f97e93f39..e27d1e102 100644 --- a/tools/Forge/Bundles/MapEdit/GNUmakefile.preamble +++ b/tools/Forge/Bundles/MapEdit/GNUmakefile.preamble @@ -2,16 +2,16 @@ ADDITIONAL_CPPFLAGS += # Additional flags to pass to the Objective-C compiler -ADDITIONAL_OBJCFLAGS += -DUSING_NIBS -Wall -Werror +ADDITIONAL_OBJCFLAGS += -DUSING_NIBS -Wall -Werror -Wsign-compare -Wwrite-strings #-Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations # Additional flags to pass to the C compiler -ADDITIONAL_CFLAGS += -Wall -Werror +ADDITIONAL_CFLAGS += -Wall -Werror -Wsign-compare -Wwrite-strings #-Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations # Additional include directories the compiler should search -ADDITIONAL_INCLUDE_DIRS += -I ../.. +ADDITIONAL_INCLUDE_DIRS += -I ../.. -I ../../../../include # Additional LDFLAGS to pass to the linker -ADDITIONAL_LDFLAGS += +ADDITIONAL_LDFLAGS += -lQFutil # Additional library directories the linker should search ADDITIONAL_LIB_DIRS += diff --git a/tools/Forge/Bundles/MapEdit/InspectorControl.h b/tools/Forge/Bundles/MapEdit/InspectorControl.h index 016afaee9..f9733aea6 100644 --- a/tools/Forge/Bundles/MapEdit/InspectorControl.h +++ b/tools/Forge/Bundles/MapEdit/InspectorControl.h @@ -1,10 +1,11 @@ +#ifndef InspectorControl_h +#define InspectorControl_h #include -#define MINIWINICON "DoomEdIcon" +#define MINIWINICON "DoomEdIcon" -typedef enum -{ +typedef enum { i_project, i_textures, i_things, @@ -13,59 +14,69 @@ typedef enum i_output, i_help, i_end -} insp_e; +} insp_e; -extern id inspcontrol_i; +@class InspectorControl; -@interface InspectorControl:Object +extern InspectorControl *inspcontrol_i; + +@interface InspectorControl: NSObject { - id inspectorView_i; // inspector view - id inspectorSubview_i; // inspector view's current subview (gets replaced) + IBOutlet NSView *inspectorView_i; // inspector view + IBOutlet NSView *inspectorSubview_i; // inspector view's current subview + // (gets replaced) - id contentList; // List of contentviews (corresponds to - // insp_e enum order) - id windowList; // List of Windows (corresponds to - // insp_e enum order) + id contentList; // List of contentviews (corresponds to + // insp_e enum order) - id obj_textures_i; // TexturePalette object (for delegating) - id obj_genkeypair_i; // GenKeyPair object + id windowList; // List of Windows (corresponds to + // insp_e enum order) + + id obj_textures_i; // TexturePalette object (for + // delegating) + id obj_genkeypair_i; // GenKeyPair object + + NSPopUpButton *popUpButton_i; // PopUpList title button + NSMatrix *popUpMatrix_i; // PopUpList matrix + NSMutableArray *itemList; // List of popUp buttons + + IBOutlet NSTextView *helpView; + + insp_e currentInspectorType; // keep track of current inspector - id popUpButton_i; // PopUpList title button - id popUpMatrix_i; // PopUpList matrix - id itemList; // List of popUp buttons - - insp_e currentInspectorType; // keep track of current inspector // - // Add id's here for new inspectors - // **NOTE: Make sure PopUpList has correct TAG value that - // corresponds to the enums above! - + // Add id's here for new inspectors + // **NOTE: Make sure PopUpList has correct TAG value that + // corresponds to the enums above! + // Windows - id win_project_i; // project - id win_textures_i; // textures - id win_things_i; // things - id win_prefs_i; // preferences - id win_settings_i; // project settings - id win_output_i; // bsp output - id win_help_i; // documentation - + IBOutlet NSWindow *win_project_i; // project + IBOutlet NSWindow *win_textures_i; // textures + IBOutlet NSWindow *win_things_i; // things + IBOutlet NSWindow *win_prefs_i; // preferences + IBOutlet NSWindow *win_settings_i; // project settings + IBOutlet NSWindow *win_output_i; // bsp output + IBOutlet NSWindow *win_help_i; // documentation + // PopUpList objs - id itemProject_i; // project - id itemTextures_i; // textures - id itemThings_i; // things - id itemPrefs_i; // preferences - id itemSettings_i; // project settings - id itemOutput_i; // bsp output - id itemHelp_i; // docs + IBOutlet id itemProject_i; // project + IBOutlet id itemTextures_i; // textures + IBOutlet id itemThings_i; // things + IBOutlet id itemPrefs_i; // preferences + IBOutlet id itemSettings_i; // project settings + IBOutlet id itemOutput_i; // bsp output + IBOutlet id itemHelp_i; // docs } -- awakeFromNib; -- changeInspector:sender; -- changeInspectorTo:(insp_e)which; -- (insp_e)getCurrentInspector; +- (IBAction) changeInspector: (id)sender; + +- (void) setCurrentInspector: (insp_e)which; +- (insp_e) currentInspector; @end @protocol InspectorControl -- windowResized; +- (void) windowResized; @end + +#endif // InspectorControl_h diff --git a/tools/Forge/Bundles/MapEdit/InspectorControl.m b/tools/Forge/Bundles/MapEdit/InspectorControl.m index b0dfbe8bd..4c3a158a2 100644 --- a/tools/Forge/Bundles/MapEdit/InspectorControl.m +++ b/tools/Forge/Bundles/MapEdit/InspectorControl.m @@ -1,128 +1,128 @@ +#include "QF/sys.h" -#include "qedefs.h" +#include "InspectorControl.h" // Add .h-files here for new inspectors -#include "Things.h" -#include "TexturePalette.h" -#include "Preferences.h" +#include "Things.h" +#include "TexturePalette.h" +#include "Preferences.h" -id inspcontrol_i; +InspectorControl *inspcontrol_i; + +@interface CustomView: NSView +@end +@implementation CustomView +@end @implementation InspectorControl -- awakeFromNib +- (void) awakeFromNib { + NSBundle *mainBundle = [NSBundle mainBundle]; + NSString *path = [mainBundle pathForResource: @"help" ofType: @"txt" + inDirectory: nil]; + NSString *help = [NSString stringWithContentsOfFile: path]; + + [helpView setString: help]; + inspcontrol_i = self; - + currentInspectorType = -1; - contentList = [[List alloc] init]; - windowList = [[List alloc] init]; - itemList = [[List alloc] init]; + contentList = [[NSMutableArray alloc] init]; + windowList = [[NSMutableArray alloc] init]; + itemList = [[NSMutableArray alloc] init]; // ADD NEW INSPECTORS HERE... - [windowList addObject:win_project_i]; - [contentList addObject:[win_project_i contentView]]; - [itemProject_i setKeyEquivalent:'1']; - [itemList addObject:itemProject_i]; + [windowList addObject: win_project_i]; + [contentList addObject: [win_project_i contentView]]; + [itemProject_i setKeyEquivalent: @"1"]; + [itemList addObject: itemProject_i]; - [windowList addObject:win_textures_i]; - [contentList addObject:[win_textures_i contentView]]; - [itemTextures_i setKeyEquivalent:'2']; - [itemList addObject:itemTextures_i]; + [windowList addObject: win_textures_i]; + [contentList addObject: [win_textures_i contentView]]; + [itemTextures_i setKeyEquivalent: @"2"]; + [itemList addObject: itemTextures_i]; - [windowList addObject:win_things_i]; - [contentList addObject:[win_things_i contentView]]; - [itemThings_i setKeyEquivalent:'3']; - [itemList addObject:itemThings_i]; - - [windowList addObject:win_prefs_i]; - [contentList addObject:[win_prefs_i contentView]]; - [itemPrefs_i setKeyEquivalent:'4']; - [itemList addObject:itemPrefs_i]; + [windowList addObject: win_things_i]; + [contentList addObject: [win_things_i contentView]]; + [itemThings_i setKeyEquivalent: @"3"]; + [itemList addObject: itemThings_i]; - [windowList addObject:win_settings_i]; - [contentList addObject:[win_settings_i contentView]]; - [itemSettings_i setKeyEquivalent:'5']; - [itemList addObject:itemSettings_i]; + [windowList addObject: win_prefs_i]; + [contentList addObject: [win_prefs_i contentView]]; + [itemPrefs_i setKeyEquivalent: @"4"]; + [itemList addObject: itemPrefs_i]; - [windowList addObject:win_output_i]; - [contentList addObject:[win_output_i contentView]]; - [itemOutput_i setKeyEquivalent:'6']; - [itemList addObject:itemOutput_i]; + [windowList addObject: win_settings_i]; + [contentList addObject: [win_settings_i contentView]]; + [itemSettings_i setKeyEquivalent: @"5"]; + [itemList addObject: itemSettings_i]; - [windowList addObject:win_help_i]; - [contentList addObject:[win_help_i contentView]]; - [itemHelp_i setKeyEquivalent:'7']; - [itemList addObject:itemHelp_i]; + [windowList addObject: win_output_i]; + [contentList addObject: [win_output_i contentView]]; + [itemOutput_i setKeyEquivalent: @"6"]; + [itemList addObject: itemOutput_i]; + + [windowList addObject: win_help_i]; + [contentList addObject: [win_help_i contentView]]; + [itemHelp_i setKeyEquivalent: @"7"]; + [itemList addObject: itemHelp_i]; // Setup inspector window with project subview first - [inspectorView_i setAutoresizeSubviews:YES]; + [inspectorView_i setAutoresizesSubviews: YES]; - inspectorSubview_i = [contentList objectAt:i_project]; - [inspectorView_i addSubview:inspectorSubview_i]; + inspectorSubview_i = [contentList objectAtIndex: i_project]; + + [inspectorView_i addSubview: inspectorSubview_i]; currentInspectorType = -1; - [self changeInspectorTo:i_project]; - - return self; + [self setCurrentInspector: i_project]; } - -// -// Sent by the PopUpList in the Inspector -// Each cell in the PopUpList must have the correct tag -// -- changeInspector:sender +// Sent by the PopUpList in the Inspector +// Each cell in the PopUpList must have the correct tag +- (IBAction) changeInspector: sender { - id cell; - - cell = [sender selectedCell]; - [self changeInspectorTo:[cell tag]]; - return self; + [self setCurrentInspector: [sender selectedTag]]; } -// -// Change to specific Inspector -// -- changeInspectorTo:(insp_e)which +// Change to specific Inspector +- (void) setCurrentInspector: (insp_e)which { - id newView; - NSRect r; - id cell; - NSRect f; - + id newView; + NSRect r; + NSRect f; + if (which == currentInspectorType) - return self; - + return; currentInspectorType = which; - newView = [contentList objectAt:which]; - - cell = [itemList objectAt:which]; // set PopUpButton title - [popUpButton_i setTitle:[cell title]]; - - [inspectorView_i replaceSubview:inspectorSubview_i with:newView]; - [inspectorView_i getFrame:&r]; + newView = [contentList objectAtIndex: which]; + + [popUpButton_i selectItemAtIndex: which]; + + [inspectorView_i replaceSubview: inspectorSubview_i with: newView]; + r = [inspectorView_i frame]; inspectorSubview_i = newView; - [inspectorSubview_i setAutosizing:NS_WIDTHSIZABLE | NS_HEIGHTSIZABLE]; - [inspectorSubview_i sizeTo:r.size.width - 4 :r.size.height - 4]; - + [inspectorSubview_i setAutoresizingMask: NSViewWidthSizable | + NSViewHeightSizable]; + r.size.width -= 4; + r.size.height -= 4; + [inspectorSubview_i setFrameSize: r.size]; + [inspectorSubview_i lockFocus]; - [inspectorSubview_i getBounds:&f]; - PSsetgray(NS_LTGRAY); - NSRectFill(&f); + f = [inspectorSubview_i bounds]; + [[NSColor windowBackgroundColor] set]; + NSRectFill (f); [inspectorSubview_i unlockFocus]; - [inspectorView_i display]; - - return self; + [inspectorView_i setNeedsDisplay: YES]; } -- (insp_e)getCurrentInspector +- (insp_e) currentInspector { return currentInspectorType; } - @end diff --git a/tools/Forge/Bundles/MapEdit/KeypairView.h b/tools/Forge/Bundles/MapEdit/KeypairView.h index 3bb3543cd..8afdd1d95 100644 --- a/tools/Forge/Bundles/MapEdit/KeypairView.h +++ b/tools/Forge/Bundles/MapEdit/KeypairView.h @@ -1,16 +1,22 @@ +#ifndef KeypairView_h +#define KeypairView_h -extern id keypairview_i; +#include -@interface KeypairView:NSView +extern id keypairview_i; + +@interface KeypairView: NSView { } -- calcViewSize; +- (id) calcViewSize; -#define SPACING 4 -#define FONTSIZE 12 -#define EXTRASPC 2 +#define SPACING 4 +#define FONTSIZE 12 +#define EXTRASPC 2 -#define LINEHEIGHT 16 +#define LINEHEIGHT 16 @end + +#endif // KeypairView_h diff --git a/tools/Forge/Bundles/MapEdit/KeypairView.m b/tools/Forge/Bundles/MapEdit/KeypairView.m index 7758d119c..a48e2a058 100644 --- a/tools/Forge/Bundles/MapEdit/KeypairView.m +++ b/tools/Forge/Bundles/MapEdit/KeypairView.m @@ -1,92 +1,98 @@ +#include "KeypairView.h" +#include "Map.h" +#include "Entity.h" +#include "Things.h" -#include "qedefs.h" - -id keypairview_i; +id keypairview_i; @implementation KeypairView - /* ================== initWithFrame: ================== */ -- initWithFrame:(NSRect)frameRect +- (id) initWithFrame: (NSRect)frameRect { - [super initWithFrame:frameRect]; + [super initWithFrame: frameRect]; keypairview_i = self; return self; } - -- calcViewSize +- (BOOL) isFlipped { - NSRect b; - NSPoint pt; - int count; - id ent; - + return YES; +} + +- (BOOL) isOpaque +{ + return YES; +} + +- (id) calcViewSize +{ + NSRect b; + NSPoint pt; + int count; + id ent; + ent = [map_i currentEntity]; count = [ent numPairs]; - //XXX[_super_view setFlipped: YES]; - - b = [_super_view bounds]; - b.size.height = LINEHEIGHT*count + SPACING; - [self setBounds: b]; + b = [[self superview] bounds]; + b.size.height = LINEHEIGHT * count + SPACING; + [self setFrameSize: b.size]; pt.x = pt.y = 0; [self scrollPoint: pt]; return self; } -- drawSelf:(const NSRect *)rects :(int)rectCount +- (id) drawRect: (NSRect)rects { - epair_t *pair; - int y; - - //XXX PSsetgray(NSGrayComponent(NS_COLORLTGRAY)); - PSrectfill(0,0,_bounds.size.width,_bounds.size.height); - - //XXX PSselectfont("Helvetica-Bold",FONTSIZE); - PSrotate(0); - PSsetgray(0); - + epair_t *pair; + int y; + NSMutableDictionary *attribs = [NSMutableDictionary dictionary]; + + [[NSColor lightGrayColor] set]; + NSRectFill (NSMakeRect (0, 0, _bounds.size.width, _bounds.size.height)); + + [[NSFont systemFontOfSize: FONTSIZE] set]; + [[NSColor blackColor] set]; + pair = [[map_i currentEntity] epairs]; y = _bounds.size.height - LINEHEIGHT; - for ( ; pair ; pair=pair->next) - { - PSmoveto(SPACING, y); - PSshow(pair->key); - PSmoveto(100, y); - PSshow(pair->value); + for ( ; pair; pair = pair->next) { + NSString *key = [NSString stringWithCString: pair->key]; + NSString *value = [NSString stringWithCString: pair->value]; + + [key drawAtPoint: NSMakePoint (SPACING, y) withAttributes: attribs]; + [value drawAtPoint: NSMakePoint (100, y) withAttributes: attribs]; y -= LINEHEIGHT; } - PSstroke(); - + return self; } -- (void)mouseDown:(NSEvent *)theEvent +- (void) mouseDown: (NSEvent *)theEvent { - NSPoint loc; - int i; - epair_t *p; + NSPoint loc; + int i; + epair_t *p; loc = [theEvent locationInWindow]; - loc = [self convertPoint:loc fromView:NULL]; - + loc = [self convertPoint: loc fromView: NULL]; + i = (_bounds.size.height - loc.y - 4) / LINEHEIGHT; p = [[map_i currentEntity] epairs]; - while ( i ) - { - p=p->next; + while (i) { + p = p->next; if (!p) return; i--; } if (p) [things_i setSelectedKey: p]; - + return; } diff --git a/tools/Forge/Bundles/MapEdit/Map.h b/tools/Forge/Bundles/MapEdit/Map.h index 15c4f581c..8d8347dc3 100644 --- a/tools/Forge/Bundles/MapEdit/Map.h +++ b/tools/Forge/Bundles/MapEdit/Map.h @@ -1,68 +1,77 @@ +#ifndef Map_h +#define Map_h + +#include + +#include "QF/mathlib.h" // Map is a list of Entity objects -extern id map_i; +extern id map_i; -@interface Map : NSMutableArray +@interface Map: NSMutableArray { - id currentEntity; - id oldselection; // temp when loading a new map - float minz, maxz; + NSMutableArray *array; + id currentEntity; + id oldselection; // temp when loading a new map + float minz, maxz; } -- newMap; +- (id) newMap; -- writeStats; +- (id) writeStats; -- readMapFile: (char *)fname; -- writeMapFile: (char *)fname useRegion: (BOOL)reg; +- (id) readMapFile: (const char *)fname; +- (id) writeMapFile: (const char *)fname useRegion: (BOOL)reg; -- entityConnect: (vec3_t)p1 : (vec3_t)p2; +- (id) entityConnect: (vec3_t)p1: (vec3_t)p2; -- selectRay: (vec3_t)p1 : (vec3_t)p2 : (BOOL)ef; -- grabRay: (vec3_t)p1 : (vec3_t)p2; -- setTextureRay: (vec3_t)p1 : (vec3_t)p2 : (BOOL)allsides; -- getTextureRay: (vec3_t)p1 : (vec3_t)p2; +- (id) selectRay: (vec3_t)p1: (vec3_t)p2: (BOOL)ef; +- (id) grabRay: (vec3_t)p1: (vec3_t)p2; +- (id) setTextureRay: (vec3_t)p1: (vec3_t)p2: (BOOL)allsides; +- (id) getTextureRay: (vec3_t)p1: (vec3_t)p2; -- currentEntity; -- setCurrentEntity: ent; +- (id) currentEntity; +- (id) setCurrentEntity: ent; -- (float)currentMinZ; -- setCurrentMinZ: (float)m; -- (float)currentMaxZ; -- setCurrentMaxZ: (float)m; +- (float) currentMinZ; +- (id) setCurrentMinZ: (float)m; +- (float) currentMaxZ; +- (id) setCurrentMaxZ: (float)m; -- (int)numSelected; -- selectedBrush; // returns the first selected brush +- (int) numSelected; +- (id) selectedBrush; // returns the first selected brush // // operations on current selection // -- makeSelectedPerform: (SEL)sel; -- makeUnselectedPerform: (SEL)sel; -- makeAllPerform: (SEL)sel; -- makeGlobalPerform: (SEL)sel; // in and out of region +- (id) makeSelectedPerform: (SEL)sel; +- (id) makeUnselectedPerform: (SEL)sel; +- (id) makeAllPerform: (SEL)sel; +- (id) makeGlobalPerform: (SEL)sel; // in and out of region -- cloneSelection: sender; +- (id) cloneSelection: sender; -- makeEntity: sender; +- (id) makeEntity: sender; -- subtractSelection: sender; +- (id) subtractSelection: sender; -- selectCompletelyInside: sender; -- selectPartiallyInside: sender; +- (id) selectCompletelyInside: sender; +- (id) selectPartiallyInside: sender; -- tallBrush: sender; -- shortBrush: sender; +- (id) tallBrush: sender; +- (id) shortBrush: sender; -- rotate_x: sender; -- rotate_y: sender; -- rotate_z: sender; +- (id) rotate_x: sender; +- (id) rotate_y: sender; +- (id) rotate_z: sender; -- flip_x: sender; -- flip_y: sender; -- flip_z: sender; +- (id) flip_x: sender; +- (id) flip_y: sender; +- (id) flip_z: sender; -- selectCompleteEntity: sender; +- (id) selectCompleteEntity: sender; @end + +#endif // Map_h diff --git a/tools/Forge/Bundles/MapEdit/Map.m b/tools/Forge/Bundles/MapEdit/Map.m index ed7b40bdf..cea093d49 100644 --- a/tools/Forge/Bundles/MapEdit/Map.m +++ b/tools/Forge/Bundles/MapEdit/Map.m @@ -1,14 +1,27 @@ - -#include "qedefs.h" - #include #include +#include "QF/quakeio.h" +#include "QF/script.h" +#include "QF/sys.h" -id map_i; +#include "Map.h" +#include "Entity.h" +#include "TexturePalette.h" +#include "SetBrush.h" +#include "XYView.h" +#include "CameraView.h" +#include "QuakeEd.h" +#include "Things.h" +#include "InspectorControl.h" +#include "Project.h" + +#define THING Map +#include "THING+NSArray.m" + +id map_i; @implementation Map - /* =============================================================================== @@ -16,78 +29,70 @@ FILE METHODS =============================================================================== */ - -- init +- (id) init { - [super init]; + self = [super init]; + array = [[NSMutableArray alloc] init]; map_i = self; minz = 0; maxz = 80; - + oldselection = [[NSMutableArray alloc] init]; - + return self; } -- saveSelected +- (id) saveSelected { - int i, c; - id o, w; - + int i, c; + id o, w; + [oldselection removeAllObjects]; w = [self objectAtIndex: 0]; c = [w count]; sb_newowner = oldselection; - for (i=0 ; i -2048) minz = m; + return self; } -- (float)currentMaxZ +- (float) currentMaxZ { - float grid; - - [self currentMinZ]; // grid align - + float grid; + + [self currentMinZ]; + + // grid align grid = [xyview_i gridsize]; - maxz = grid * rint(maxz/grid); + maxz = grid * rint (maxz / grid); if (maxz <= minz) maxz = minz + grid; + return maxz; } -- setCurrentMaxZ: (float)m +- (id) setCurrentMaxZ: (float)m { if (m < 2048) maxz = m; + return self; } - (void) removeObject: o { [super removeObject: o]; - - if (o == currentEntity) - { // select the world + + if (o == currentEntity) // select the world [self setCurrentEntity: [self objectAtIndex: 0]]; - } return; } -- writeStats +#define FN_DEVLOG "/qcache/devlog" +- (id) writeStats { - FILE *f; - extern int c_updateall; - struct timeval tp; - struct timezone tzp; + FILE *f; + extern int c_updateall; + struct timeval tp; + struct timezone tzp; + + gettimeofday (&tp, &tzp); - gettimeofday(&tp, &tzp); - f = fopen (FN_DEVLOG, "a"); - fprintf (f,"%i %i\n", (int)tp.tv_sec, c_updateall); + fprintf (f, "%i %i\n", (int) tp.tv_sec, c_updateall); c_updateall = 0; fclose (f); return self; } -- (int)numSelected +- (int) numSelected { - int i, c; - int num; - + int i, c; + int num; + num = 0; c = [currentEntity count]; - for (i=0 ; i=0 ; i--) - { + for (i = c - 1; i >= 0; i--) { ent = [self objectAtIndex: i]; c2 = [ent count]; - for (j=0 ; jbesttime) + if (time < 0 || time > besttime) continue; bestent = ent; besttime = time; bestbrush = brush; bestface = face; } - if (i == 1 && ef && bestbrush) - break; // found an entity, so don't check the world + if (i == 1 && ef && bestbrush) // found an entity, don't check the + // world + break; } - - if (besttime == 99999) - { - qprintf ("trace missed"); + + if (besttime == 99999) { + Sys_Printf ("trace missed\n"); return self; } - if ( [bestbrush regioned] ) - { - qprintf ("WANRING: clicked on regioned brush"); + if ([bestbrush regioned]) { + Sys_Printf ("WARNING: clicked on regioned brush\n"); return self; } - - if (bestent != currentEntity) - { - [self makeSelectedPerform: @selector(deselect)]; + + if (bestent != currentEntity) { + [self makeSelectedPerform: @selector (deselect)]; [self setCurrentEntity: bestent]; } - + [quakeed_i disableFlushWindow]; - if ( ![bestbrush selected] ) - { - if ( [map_i numSelected] == 0) - { // don't grab texture if others are selected + if (![bestbrush selected]) { + // don't grab texture if others are selected + if ([map_i numSelected] == 0) { td = [bestbrush texturedefForFace: bestface]; [texturepalette_i setTextureDef: td]; } [bestbrush setSelected: YES]; - qprintf ("selected entity %i brush %i face %i", [self indexOfObject:bestent], [bestent indexOfObject: bestbrush], bestface); - } - else - { + Sys_Printf ("selected entity %i brush %i face %i\n", + (int) [self indexOfObject: bestent], + (int) [bestent indexOfObject: bestbrush], bestface); + } else { [bestbrush setSelected: NO]; - qprintf ("deselected entity %i brush %i face %i", [self indexOfObject:bestent], [bestent indexOfObject: bestbrush], bestface); + Sys_Printf ("deselected entity %i brush %i face %i\n", + (int) [self indexOfObject: bestent], + (int) [bestent indexOfObject: bestbrush], bestface); } [quakeed_i enableFlushWindow]; [quakeed_i updateAll]; - + return self; } @@ -470,38 +477,36 @@ checks only the selected brushes Returns the brush hit, or nil if missed. ================= */ -- grabRay: (vec3_t)p1 : (vec3_t)p2 +- (id) grabRay: (vec3_t)p1 + : (vec3_t)p2 { - int i, j, c, c2; - id ent; - id brush, bestbrush; - int face; - float time, besttime; - + int i, j, c, c2; + id ent; + id brush, bestbrush; + int face; + float time, besttime; + bestbrush = nil; besttime = 99999; - + c = [self count]; - for (i=0 ; ibesttime) + if (time < 0 || time > besttime) continue; besttime = time; bestbrush = brush; } } - + if (besttime == 99999) return nil; - return bestbrush; } @@ -510,31 +515,29 @@ Returns the brush hit, or nil if missed. getTextureRay ================= */ -- getTextureRay: (vec3_t)p1 : (vec3_t)p2 +- (id) getTextureRay: (vec3_t)p1 + : (vec3_t)p2 { - int i, j, c, c2; - id ent, bestent; - id brush, bestbrush; - int face, bestface; - float time, besttime; - texturedef_t *td; - vec3_t mins, maxs; - + int i, j, c, c2; + id ent, bestent; + id brush, bestbrush; + int face, bestface; + float time, besttime; + texturedef_t *td; + vec3_t mins, maxs; bestbrush = nil; bestent = nil; besttime = 99999; bestface = -1; c = [self count]; - for (i=0 ; ibesttime) + if (time < 0 || time > besttime) continue; bestent = ent; bestface = face; @@ -542,26 +545,24 @@ getTextureRay bestbrush = brush; } } - + if (besttime == 99999) return nil; - - if ( ![bestent modifiable]) - { - qprintf ("can't modify spawned entities"); + if (![bestent modifiable]) { + Sys_Printf ("can't modify spawned entities\n"); return self; } - + td = [bestbrush texturedefForFace: bestface]; [texturepalette_i setTextureDef: td]; - - qprintf ("grabbed texturedef and sizes"); - + + Sys_Printf ("grabbed texturedef and sizes\n"); + [bestbrush getMins: mins maxs: maxs]; - + minz = mins[2]; maxz = maxs[2]; - + return bestbrush; } @@ -570,30 +571,30 @@ getTextureRay setTextureRay ================= */ -- setTextureRay: (vec3_t)p1 : (vec3_t)p2 : (BOOL)allsides; +- (id) setTextureRay: (vec3_t)p1 + : (vec3_t)p2 + : (BOOL)allsides; { - int i, j, c, c2; - id ent, bestent; - id brush, bestbrush; - int face, bestface; - float time, besttime; - texturedef_t td; - + int i, j, c, c2; + id ent, bestent; + id brush, bestbrush; + int face, bestface; + float time, besttime; + texturedef_t td; + bestent = nil; bestface = -1; bestbrush = nil; besttime = 99999; - + c = [self count]; - for (i=0 ; ibesttime) + if (time < 0 || time > besttime) continue; bestent = ent; besttime = time; @@ -601,46 +602,44 @@ setTextureRay bestface = face; } } - - if (besttime == 99999) - { - qprintf ("trace missed"); + + if (besttime == 99999) { + Sys_Printf ("trace missed\n"); return self; } - if ( ![bestent modifiable]) - { - qprintf ("can't modify spawned entities"); + if (![bestent modifiable]) { + Sys_Printf ("can't modify spawned entities\n"); return self; } - - if ( [bestbrush regioned] ) - { - qprintf ("WANRING: clicked on regioned brush"); + + if ([bestbrush regioned]) { + Sys_Printf ("WANRING: clicked on regioned brush\n"); return self; } - + [texturepalette_i getTextureDef: &td]; - + [quakeed_i disableFlushWindow]; - if (allsides) - { + if (allsides) { [bestbrush setTexturedef: &td]; - qprintf ("textured entity %i brush %i", [self indexOfObject:bestent], [bestent indexOfObject: bestbrush]); - } - else - { + Sys_Printf ("textured entity %i brush %i\n", + (int) [self indexOfObject: bestent], + (int) [bestent indexOfObject: bestbrush]); + } else { [bestbrush setTexturedef: &td forFace: bestface]; - qprintf ("deselected entity %i brush %i face %i", [self indexOfObject:bestent], [bestent indexOfObject: bestbrush], bestface); + Sys_Printf ("deselected entity %i brush %i face %i\n", + (int) [self indexOfObject: bestent], + (int) [bestent indexOfObject: bestbrush], + bestface); } [quakeed_i enableFlushWindow]; - + [quakeed_i updateAll]; - + return self; } - /* ============================================================================== @@ -649,138 +648,134 @@ OPERATIONS ON SELECTIONS ============================================================================== */ -- makeSelectedPerform: (SEL)sel +- (id) makeSelectedPerform: (SEL)sel { - int i,j, c, c2; - id ent, brush; - int total; - + int i, j, c, c2; + id ent, brush; + int total; + total = 0; c = [self count]; - for (i=c-1 ; i>=0 ; i--) - { + for (i = c - 1; i >= 0; i--) { ent = [self objectAtIndex: i]; c2 = [ent count]; - for (j = c2-1 ; j >=0 ; j--) - { + for (j = c2 - 1; j >= 0; j--) { brush = [ent objectAtIndex: j]; - if (! [brush selected] ) + if (![brush selected]) continue; if ([brush regioned]) continue; total++; - [brush perform:sel]; + [brush performSelector: sel]; } } -// if (!total) -// qprintf ("nothing selected"); - - return self; +// if (!total) +// Sys_Printf ("nothing selected\n"); + + return self; } -- makeUnselectedPerform: (SEL)sel +- (id) makeUnselectedPerform: (SEL)sel { - int i,j, c, c2; - id ent, brush; - + int i, j, c, c2; + id ent, brush; + c = [self count]; - for (i=c-1 ; i>=0 ; i--) - { + for (i = c - 1; i >= 0; i--) { ent = [self objectAtIndex: i]; c2 = [ent count]; - for (j = c2-1 ; j >=0 ; j--) - { + for (j = c2 - 1; j >= 0; j--) { brush = [ent objectAtIndex: j]; - if ( [brush selected] ) + if ([brush selected]) continue; if ([brush regioned]) continue; - [brush perform:sel]; + [brush performSelector: sel]; } } - return self; + return self; } -- makeAllPerform: (SEL)sel +- (id) makeAllPerform: (SEL)sel { - int i,j, c, c2; - id ent, brush; - + int i, j, c, c2; + id ent, brush; + c = [self count]; - for (i=c-1 ; i>=0 ; i--) - { + for (i = c - 1; i >= 0; i--) { ent = [self objectAtIndex: i]; c2 = [ent count]; - for (j = c2-1 ; j >=0 ; j--) - { + for (j = c2 - 1; j >= 0; j--) { brush = [ent objectAtIndex: j]; if ([brush regioned]) continue; - [brush perform:sel]; + [brush performSelector: sel]; } } - return self; + return self; } -- makeGlobalPerform: (SEL)sel // in and out of region +- (id) makeGlobalPerform: (SEL)sel // in and out of region { - int i,j, c, c2; - id ent, brush; - + int i, j, c, c2; + id ent, brush; + c = [self count]; - for (i=c-1 ; i>=0 ; i--) - { + for (i = c - 1; i >= 0; i--) { ent = [self objectAtIndex: i]; c2 = [ent count]; - for (j = c2-1 ; j >=0 ; j--) - { + for (j = c2 - 1; j >= 0; j--) { brush = [ent objectAtIndex: j]; - [brush perform:sel]; + [brush performSelector: sel]; } } - return self; + return self; } - -void sel_identity (void) +void +sel_identity (void) { - sel_x[0]=1; sel_x[1]=0; sel_x[2]=0; - sel_y[0]=0; sel_y[1]=1; sel_y[2]=0; - sel_z[0]=0; sel_z[1]=0; sel_z[2]=1; + sel_x[0] = 1; + sel_x[1] = 0; + sel_x[2] = 0; + sel_y[0] = 0; + sel_y[1] = 1; + sel_y[2] = 0; + sel_z[0] = 0; + sel_z[1] = 0; + sel_z[2] = 1; } -- transformSelection +- (id) transformSelection { - if ( ![currentEntity modifiable]) - { - qprintf ("can't modify spawned entities"); + if (![currentEntity modifiable]) { + Sys_Printf ("can't modify spawned entities\n"); return self; } - -// find an origin to apply the transformation to + // find an origin to apply the transformation to sb_mins[0] = sb_mins[1] = sb_mins[2] = 99999; sb_maxs[0] = sb_maxs[1] = sb_maxs[2] = -99999; - [self makeSelectedPerform: @selector(addToBBox)]; - sel_org[0] = [xyview_i snapToGrid: (sb_mins[0] + sb_maxs[0])/2]; - sel_org[1] = [xyview_i snapToGrid: (sb_mins[1] + sb_maxs[1])/2]; - sel_org[2] = [xyview_i snapToGrid: (sb_mins[2] + sb_maxs[2])/2]; - -// do it! - [self makeSelectedPerform: @selector(transform)]; + [self makeSelectedPerform: @selector (addToBBox)]; + sel_org[0] = [xyview_i snapToGrid: (sb_mins[0] + sb_maxs[0]) / 2]; + sel_org[1] = [xyview_i snapToGrid: (sb_mins[1] + sb_maxs[1]) / 2]; + sel_org[2] = [xyview_i snapToGrid: (sb_mins[2] + sb_maxs[2]) / 2]; + + // do it! + [self makeSelectedPerform: @selector (transform)]; [quakeed_i updateAll]; return self; } - -void swapvectors (vec3_t a, vec3_t b) +void +swapvectors (vec3_t a, vec3_t b) { - vec3_t temp; - + vec3_t temp; + VectorCopy (a, temp); VectorCopy (b, a); VectorSubtract (vec3_origin, temp, b); @@ -794,90 +789,84 @@ UI operations =============================================================================== */ -- rotate_x: sender +- (id) rotate_x: sender { sel_identity (); - swapvectors(sel_y, sel_z); + swapvectors (sel_y, sel_z); [self transformSelection]; return self; } -- rotate_y: sender +- (id) rotate_y: sender { sel_identity (); - swapvectors(sel_x, sel_z); + swapvectors (sel_x, sel_z); [self transformSelection]; return self; } -- rotate_z: sender +- (id) rotate_z: sender { sel_identity (); - swapvectors(sel_x, sel_y); + swapvectors (sel_x, sel_y); [self transformSelection]; return self; } - -- flip_x: sender +- (id) flip_x: sender { sel_identity (); sel_x[0] = -1; [self transformSelection]; - [map_i makeSelectedPerform: @selector(flipNormals)]; + [map_i makeSelectedPerform: @selector (flipNormals)]; return self; } -- flip_y: sender +- (id) flip_y: sender { sel_identity (); sel_y[1] = -1; [self transformSelection]; - [map_i makeSelectedPerform: @selector(flipNormals)]; + [map_i makeSelectedPerform: @selector (flipNormals)]; return self; } - -- flip_z: sender +- (id) flip_z: sender { sel_identity (); sel_z[2] = -1; [self transformSelection]; - [map_i makeSelectedPerform: @selector(flipNormals)]; + [map_i makeSelectedPerform: @selector (flipNormals)]; return self; } - -- cloneSelection: sender +- (id) cloneSelection: sender { - int i,j , c, originalElements; - id o, b; - id new; - + int i, j, c, originalElements; + id o, b; + id new; + sb_translate[0] = sb_translate[1] = [xyview_i gridsize]; sb_translate[2] = 0; -// copy individual brushes in the world entity + // copy individual brushes in the world entity o = [self objectAtIndex: 0]; c = [o count]; - for (i=0 ; i -@interface PopScrollView : NSScrollView +@interface PopScrollView: NSScrollView { - id button1, button2; + id button1, button2; } -- initWithFrame:(NSRect)frameRect button1: b1 button2: b2; -- tile; +- (id) initWithFrame: (NSRect)frameRect + button1: b1 + button2: b2; + +- (id) tile; @end +#endif // PopScrollView_h diff --git a/tools/Forge/Bundles/MapEdit/PopScrollView.m b/tools/Forge/Bundles/MapEdit/PopScrollView.m index 00316157f..199903988 100644 --- a/tools/Forge/Bundles/MapEdit/PopScrollView.m +++ b/tools/Forge/Bundles/MapEdit/PopScrollView.m @@ -1,8 +1,6 @@ - -#include "qedefs.h" +#include "PopScrollView.h" @implementation PopScrollView - /* ==================== initWithFrame: button: @@ -10,10 +8,11 @@ initWithFrame: button: Initizes a scroll view with a button at it's lower right corner ==================== */ - -- initWithFrame:(NSRect)frameRect button1:b1 button2:b2 +- (id) initWithFrame: (NSRect)frameRect + button1: b1 + button2: b2 { - [super initWithFrame: frameRect]; + [super initWithFrame: frameRect]; [self addSubview: b1]; [self addSubview: b2]; @@ -25,10 +24,14 @@ Initizes a scroll view with a button at it's lower right corner [self setHasVerticalScroller: YES]; [self setBorderType: NSBezelBorder]; - + return self; } +- (BOOL) isOpaque +{ + return YES; +} /* ================ @@ -37,20 +40,20 @@ tile Adjust the size for the pop up scale menu ================= */ - -- tile +- (id) tile { - NSRect scrollerframe; - NSRect buttonframe, buttonframe2; - NSRect newframe; - + NSRect scrollerframe; + NSRect buttonframe, buttonframe2; + NSRect newframe; + [super tile]; buttonframe = [button1 frame]; buttonframe2 = [button2 frame]; scrollerframe = [_horizScroller frame]; newframe.origin.y = scrollerframe.origin.y; - newframe.origin.x = scrollerframe.size.width - buttonframe.size.width; + newframe.origin.x = scrollerframe.origin.x + scrollerframe.size.width - + buttonframe.size.width; newframe.size.width = buttonframe.size.width; newframe.size.height = scrollerframe.size.height; scrollerframe.size.width -= newframe.size.width; @@ -66,22 +69,19 @@ Adjust the size for the pop up scale menu } /* -- superviewSizeChanged:(const NSSize *)oldSize +- (id) superviewSizeChanged: (const NSSize *)oldSize { - [super superviewSizeChanged: oldSize]; - - [[self docView] newSuperBounds]; - - return self; + [super superviewSizeChanged: oldSize]; + + [[self docView] newSuperBounds]; + + return self; } */ --(BOOL) acceptsFirstResponder +- (BOOL) acceptsFirstResponder { - return YES; + return YES; } - - @end - diff --git a/tools/Forge/Bundles/MapEdit/Preferences.h b/tools/Forge/Bundles/MapEdit/Preferences.h index a27d81ae2..5c415eef2 100644 --- a/tools/Forge/Bundles/MapEdit/Preferences.h +++ b/tools/Forge/Bundles/MapEdit/Preferences.h @@ -1,78 +1,84 @@ +#ifndef Preferences_h +#define Preferences_h -extern id preferences_i; +#include -extern float lightaxis[3]; +extern id preferences_i; + +extern float lightaxis[3]; // these are personal preferences saved in NeXT defaults, not project // parameters saved in the quake.qe_project file -@interface Preferences:Object +@interface Preferences: NSObject { - id bspSound_i; // actual sound object + id bspSound_i; // actual sound object // internal state - char projectpath[1024]; - char bspSound[1024]; - - BOOL brushOffset; - BOOL showBSP; + NSString *projectpath; + NSString *bspSound; + + BOOL brushOffset; + BOOL showBSP; + + float xlight; + float ylight; + float zlight; // 0.0 - 1.0 + + int startwad; // 0 - 2 - float xlight; - float ylight; - float zlight; // 0.0 - 1.0 - - int startwad; // 0 - 2 - // UI targets - id startproject_i; // TextField + id startproject_i; // TextField - id bspSoundField_i; // TextField of bspSound + id bspSoundField_i; // TextField of bspSound - id brushOffset_i; // Brush Offset checkbox - id showBSP_i; // Show BSP Output checkbox - - id startwad_i; // which wad to load at startup + id brushOffset_i; // Brush Offset checkbox + id showBSP_i; // Show BSP Output checkbox - id xlight_i; // X-side lighting - id ylight_i; // Y-side lighting - id zlight_i; // Z-side lighting + id startwad_i; // which wad to load at startup + + id xlight_i; // X-side lighting + id ylight_i; // Y-side lighting + id zlight_i; // Z-side lighting + + NSUserDefaults *prefs; } -- readDefaults; +- (id) readDefaults; // // validate and set methods called by UI or defaults // -- setProjectPath:(char *)path; -- setBspSoundPath:(char *)path; // set the path of the soundfile externally -- setShowBSP:(int)state; // set the state of ShowBSP -- setBrushOffset:(int)state; // set the state of BrushOffset -- setStartWad:(int)value; // set start wad (0-2) -- setXlight:(float)value; // set Xlight value for CameraView -- setYlight:(float)value; // set Ylight value for CameraView -- setZlight:(float)value; // set Zlight value for CameraView +- (id) setProjectPath: (NSString *)path; +- (id) setBspSoundPath: (NSString *)path; // set the path of the soundfile +- (id) setShowBSP: (int)state; // set the state of ShowBSP +- (id) setBrushOffset: (int)state; // set the state of BrushOffset +- (id) setStartWad: (int)value; // set start wad (0-2) +- (id) setXlight: (float)value; // set Xlight value for CameraView +- (id) setYlight: (float)value; // set Ylight value for CameraView +- (id) setZlight: (float)value; // set Zlight value for CameraView // // UI targets // -- setBspSound:sender; // use OpenPanel to select sound -- setCurrentProject:sender; // make current roject the default -- UIChanged: sender; // target for all checks and fields +- (id) setBspSound: sender; // use OpenPanel to select sound +- (id) setCurrentProject: sender; // make current project the default +- (id) UIChanged: sender; // target for all checks and fields // // methods used by other objects to retreive defaults // -- playBspSound; +- (id) playBspSound; -- (char *)getProjectPath; -- (int)getBrushOffset; // get the state -- (int)getShowBSP; // get the state +- (NSString *) getProjectPath; +- (int) getBrushOffset; // get the state +- (int) getShowBSP; // get the state -- (float)getXlight; // get Xlight value -- (float)getYlight; // get Ylight value -- (float)getZlight; // get Zlight value - -- (int)getStartWad; +- (float) getXlight; // get Xlight value +- (float) getYlight; // get Ylight value +- (float) getZlight; // get Zlight value +- (int) getStartWad; @end +#endif // Preferences_h diff --git a/tools/Forge/Bundles/MapEdit/Preferences.m b/tools/Forge/Bundles/MapEdit/Preferences.m index ba241cb9b..fdf1d04f1 100644 --- a/tools/Forge/Bundles/MapEdit/Preferences.m +++ b/tools/Forge/Bundles/MapEdit/Preferences.m @@ -1,305 +1,272 @@ +#include -#include "qedefs.h" +#include "QF/sys.h" +#include "QF/va.h" -id preferences_i; +#include "Preferences.h" +#include "Map.h" +#include "QuakeEd.h" +#include "Project.h" -#define DEFOWNER "QuakeEd2" +id preferences_i; -float lightaxis[3] = {1, 0.6, 0.75}; +#define DEFOWNER "QuakeEd2" + +float lightaxis[3] = {1, 0.6, 0.75}; @implementation Preferences -- init +void +WriteStringDefault (id prefs, NSString *name, NSString *value) +{ + [prefs setObject: value forKey: name]; +} + +void +WriteNumericDefault (id prefs, NSString *name, float value) +{ + WriteStringDefault (prefs, name, [NSString stringWithFormat: @"%f", value]); +} + +- (id) init { [super init]; preferences_i = self; + + NSMutableDictionary *defaults = [NSMutableDictionary dictionary]; + + WriteStringDefault (defaults, @"ProjectPath", @""); + WriteStringDefault (defaults, @"BspSoundPath", @""); + WriteNumericDefault (defaults, @"ShowBSPOutput", NO); + WriteNumericDefault (defaults, @"OffsetBrushCopy", NO); + WriteNumericDefault (defaults, @"StartWad", 0); + WriteNumericDefault (defaults, @"Xlight", 0); + WriteNumericDefault (defaults, @"Ylight", 0); + WriteNumericDefault (defaults, @"Zlight", 0); + + prefs = [[NSUserDefaults standardUserDefaults] retain]; + [prefs registerDefaults: defaults]; return self; } -int _atoi (char *c) +// Read in at start of program +- (id) readDefaults { - if (!c) - return 0; - return atoi(c); -} + [self setProjectPath: [prefs stringForKey: @"ProjectPath"]]; + [self setBspSoundPath: [prefs stringForKey: @"BspSoundPath"]]; -int _atof (char *c) -{ - if (!c) - return 0; - return atof(c); -} + [self setShowBSP: [[prefs stringForKey: @"ShowBSPOutput"] intValue]]; + [self setBrushOffset: [[prefs stringForKey: @"OffsetBrushCopy"] intValue]]; + [self setStartWad: [[prefs stringForKey: @"StartWad"] intValue]]; -void WriteNumericDefault (char *name, float value) -{ - char str[128]; - - sprintf (str,"%f", value); - NSWriteDefault (DEFOWNER, name, str); -} -void WriteStringDefault (char *name, char *value) -{ - NSWriteDefault (DEFOWNER, name, value); -} - -// -// Read in at start of program -// -- readDefaults -{ - char *string; - float value; - - string = (char *)NSGetDefaultValue(DEFOWNER,"ProjectPath"); - [self setProjectPath: string]; - - string = (char *)NSGetDefaultValue(DEFOWNER,"BspSoundPath"); - [self setBspSoundPath:string]; - - value = _atoi((char *)NSGetDefaultValue(DEFOWNER,"ShowBSPOutput")); - [self setShowBSP:value]; - - value = _atoi((char *)NSGetDefaultValue(DEFOWNER,"OffsetBrushCopy")); - [self setBrushOffset:value]; - - value = _atoi((char *)NSGetDefaultValue(DEFOWNER,"StartWad")); - [self setStartWad:value]; - - value = _atof((char *)NSGetDefaultValue(DEFOWNER,"Xlight")); - [self setXlight:value]; - - value = _atof((char *)NSGetDefaultValue(DEFOWNER,"Ylight")); - [self setYlight:value]; - - value = _atof((char *)NSGetDefaultValue(DEFOWNER,"Zlight")); - [self setZlight:value]; + [self setXlight: [[prefs stringForKey: @"Xlight"] floatValue]]; + [self setYlight: [[prefs stringForKey: @"Ylight"] floatValue]]; + [self setZlight: [[prefs stringForKey: @"Zlight"] floatValue]]; return self; } - -- setProjectPath:(char *)path +- (id) setProjectPath: (NSString *)path { - if (!path) - path = ""; - strcpy (projectpath, path); - [startproject_i setStringValue: path]; - WriteStringDefault ("ProjectPath", path); + [path retain]; + [projectpath release]; + projectpath = path; + [startproject_i setStringValue: projectpath]; + WriteStringDefault (prefs, @"ProjectPath", projectpath); return self; } -- setCurrentProject:sender +- (id) setCurrentProject: sender { [startproject_i setStringValue: [project_i currentProjectFile]]; [self UIChanged: self]; return self; } -- (char *)getProjectPath +- (NSString *) getProjectPath { return projectpath; } - +// =============================================== +// BSP sound stuff +// =============================================== // -//=============================================== -// BSP sound stuff -//=============================================== -// -// Set the BSP sound using an OpenPanel -// -- setBspSound:sender +// Set the BSP sound using an OpenPanel +- (id) setBspSound: sender { - id panel; - char *types[]={"snd",NULL}; - int rtn; - char **filename; - char path[1024], file[64]; - - panel = [OpenPanel new]; + id panel; + NSString *types[] = {@"snd"}; + int rtn; + NSArray *filenames; + NSString *path, *file; - ExtractFilePath (bspSound, path); - ExtractFileBase (bspSound, file); - - rtn = [panel - runModalForDirectory:path - file: file - types: types]; + panel = [NSOpenPanel new]; - if (rtn) - { - filename = (char **)[panel filenames]; - strcpy(bspSound,[panel directory]); - strcat(bspSound,"/"); - strcat(bspSound,filename[0]); - [self setBspSoundPath:bspSound]; + path = [bspSound stringByDeletingLastPathComponent]; + file = [bspSound lastPathComponent]; + + rtn = [panel runModalForDirectory: path file: file + types: [NSArray arrayWithObjects: types + count: 1] + ]; + + if (rtn) { + filenames = [panel filenames]; + [self setBspSoundPath: [filenames objectAtIndex: 0]]; [self playBspSound]; } return self; } - -// -// Play the BSP sound -// -- playBspSound +// Play the BSP sound +- (id) playBspSound { - [bspSound_i play]; + [bspSound_i play]; return self; } - -// -// Set the bspSound path -// -- setBspSoundPath:(char *)path +// Set the bspSound path +- (id) setBspSoundPath: (NSString *)path { - if (!path) - path = ""; - strcpy(bspSound,path); + + [path retain]; + [bspSound release]; + bspSound = path; - if (bspSound_i) - [bspSound_i free]; - bspSound_i = [[Sound alloc] initFromSoundfile:bspSound]; - if (!bspSound_i) - { - strcpy (bspSound, "/NextLibrary/Sounds/Funk.snd"); - bspSound_i = [[Sound alloc] initFromSoundfile:bspSound]; + if (bspSound_i) { + [bspSound_i release]; + bspSound_i = nil; } + if (access ([path cString], R_OK)) { + bspSound_i = [[NSSound alloc] initWithContentsOfFile: bspSound + byReference: YES]; + } + if (!bspSound_i) + return self; + + [bspSoundField_i setStringValue: bspSound]; + + WriteStringDefault (prefs, @"BspSoundPath", bspSound); - [bspSoundField_i setStringValue:bspSound]; - - WriteStringDefault ("BspSoundPath", bspSound); - return self; } -//=============================================== -// Show BSP Output management -//=============================================== +// =============================================== +// Show BSP Output management +// =============================================== -// -// Set the state -// -- setShowBSP:(int)state +// Set the state +- (id) setShowBSP: (int)state { showBSP = state; - [showBSP_i setIntValue:state]; - WriteNumericDefault ("ShowBSPOutput", showBSP); + [showBSP_i setIntValue: state]; + WriteNumericDefault (prefs, @"ShowBSPOutput", showBSP); return self; } -// -// Get the state -// -- (int)getShowBSP +// Get the state +- (int) getShowBSP { return showBSP; } +// =============================================== +// "Offset Brush ..." management +// =============================================== -//=============================================== -// "Offset Brush ..." management -//=============================================== - -// -// Set the state -// -- setBrushOffset:(int)state +// Set the state +- (id) setBrushOffset: (int)state { brushOffset = state; - [brushOffset_i setIntValue:state]; - WriteNumericDefault ("OffsetBrushCopy", state); + [brushOffset_i setIntValue: state]; + WriteNumericDefault (prefs, @"OffsetBrushCopy", state); return self; } -// -// Get the state -// -- (int)getBrushOffset +// Get the state +- (int) getBrushOffset { return brushOffset; } -//=============================================== -// StartWad -//=============================================== +// =============================================== +// StartWad +// =============================================== -- setStartWad:(int)value // set start wad (0-2) +- (id) setStartWad: (int)value // set start wad (0-2) { startwad = value; - if (startwad<0 || startwad>2) + if (startwad < 0 || startwad > 2) startwad = 0; - - [startwad_i selectCellAt:startwad : 0]; - WriteNumericDefault ("StartWad", value); + [startwad_i selectCellAtRow: startwad column: 0]; + + WriteNumericDefault (prefs, @"StartWad", value); return self; } -- (int)getStartWad +- (int) getStartWad { return startwad; } - -//=============================================== -// X,Y,Z light values -//=============================================== +// =============================================== +// X,Y,Z light values +// =============================================== // -// Set the state -// -- setXlight:(float)value +// Set the state +- (id) setXlight: (float)value { xlight = value; if (xlight < 0.25 || xlight > 1) xlight = 0.6; lightaxis[1] = xlight; - [xlight_i setFloatValue:xlight]; - WriteNumericDefault ("Xlight", xlight); + [xlight_i setFloatValue: xlight]; + WriteNumericDefault (prefs, @"Xlight", xlight); return self; } -- setYlight:(float)value + +- (id) setYlight: (float)value { ylight = value; if (ylight < 0.25 || ylight > 1) ylight = 0.75; lightaxis[2] = ylight; - [ylight_i setFloatValue:ylight]; - WriteNumericDefault ("Ylight", ylight); + [ylight_i setFloatValue: ylight]; + WriteNumericDefault (prefs, @"Ylight", ylight); return self; } -- setZlight:(float)value + +- (id) setZlight: (float)value { zlight = value; if (zlight < 0.25 || zlight > 1) zlight = 1; lightaxis[0] = zlight; - [zlight_i setFloatValue:zlight]; - WriteNumericDefault ("Zlight", zlight); + [zlight_i setFloatValue: zlight]; + WriteNumericDefault (prefs, @"Zlight", zlight); return self; } -// -// Get the state -// -- (float)getXlight +// Get the state +- (float) getXlight { return [xlight_i floatValue]; } -- (float)getYlight + +- (float) getYlight { return [ylight_i floatValue]; } -- (float)getZlight + +- (float) getZlight { return [zlight_i floatValue]; } - - /* ============ UIChanged @@ -307,12 +274,12 @@ UIChanged Grab all the current UI state ============ */ --UIChanged: sender +- (id) UIChanged: sender { - qprintf ("defaults updated"); - - [self setProjectPath: (char *)[startproject_i stringValue]]; - [self setBspSoundPath: (char *)[bspSoundField_i stringValue]]; + Sys_Printf ("defaults updated\n"); + + [self setProjectPath: [startproject_i stringValue]]; + [self setBspSoundPath: [bspSoundField_i stringValue]]; [self setShowBSP: [showBSP_i intValue]]; [self setBrushOffset: [brushOffset_i intValue]]; [self setStartWad: [startwad_i selectedRow]]; @@ -320,11 +287,10 @@ Grab all the current UI state [self setYlight: [ylight_i floatValue]]; [self setZlight: [zlight_i floatValue]]; - [map_i makeGlobalPerform: @selector(flushTextures)]; + [map_i makeGlobalPerform: @selector (flushTextures)]; [quakeed_i updateAll]; - + return self; } - @end diff --git a/tools/Forge/Bundles/MapEdit/Project.h b/tools/Forge/Bundles/MapEdit/Project.h index 9aa1dd4cd..488495386 100644 --- a/tools/Forge/Bundles/MapEdit/Project.h +++ b/tools/Forge/Bundles/MapEdit/Project.h @@ -1,108 +1,110 @@ +#ifndef Project_h +#define Project_h #include #include -#define BASEPATHKEY "basepath" -#define MAPNAMESKEY "maps" -#define DESCKEY "desc" -#define WADSKEY "wads" -#define BSPFULLVIS "bspfullvis" -#define BSPFASTVIS "bspfastvis" -#define BSPNOVIS "bspnovis" -#define BSPRELIGHT "bsprelight" -#define BSPLEAKTEST "bspleaktest" -#define BSPENTITIES "bspentities" +#define BASEPATHKEY "basepath" +#define MAPNAMESKEY "maps" +#define DESCKEY "desc" +#define WADSKEY "wads" +#define BSPFULLVIS "bspfullvis" +#define BSPFASTVIS "bspfastvis" +#define BSPNOVIS "bspnovis" +#define BSPRELIGHT "bsprelight" +#define BSPLEAKTEST "bspleaktest" +#define BSPENTITIES "bspentities" -#define SUBDIR_ENT "progs" // subdir names in heirarchy -#define SUBDIR_MAPS "maps" -#define SUBDIR_GFX "gfx" +#define SUBDIR_ENT @"progs" // subdir names in heirarchy +#define SUBDIR_MAPS @"maps" +#define SUBDIR_GFX @"gfx" -extern id project_i; +extern id project_i; -@interface Project:Object +@interface Project: NSObject { - id projectInfo; // dictionary storage of project info + id projectInfo; // dictionary storage of project info - id basepathinfo_i; // outlet to base path info textfield - id mapbrowse_i; // outlet to QuakeEd Maps browser - id currentmap_i; // outlet to current map textfield - id mapList; // list of map names (Storage) - id descList; // list of map descriptions (Storage) - id wadList; // list of wad names (Storage) - - id pis_panel_i; // outlet to Project Info Settings (PIS) panel + id basepathinfo_i; // outlet to base path info textfield + id mapbrowse_i; // outlet to QuakeEd Maps browser + id currentmap_i; // outlet to current map textfield + struct plitem_s *mapList; // list of map names + struct plitem_s *descList; // list of map descriptions + struct plitem_s *wadList; // list of wad names - id pis_basepath_i; // outlet to PIS->base path - id pis_wads_i; // outlet to PIS->wad browser - id pis_fullvis_i; // outlet to PIS->full vis command - id pis_fastvis_i; // outlet to PIS->fast vis command - id pis_novis_i; // outlet to PIS->no vis command - id pis_relight_i; // outlet to PIS->relight command - id pis_leaktest_i; // outlet to PIS->leak test command + id pis_panel_i; // outlet to Project Info Settings (PIS) + // panel - id BSPoutput_i; // outlet to Text - - char path_projectinfo[128]; // path of QE_Project file + id pis_basepath_i; // outlet to PIS->base path + id pis_wads_i; // outlet to PIS->wad browser + id pis_fullvis_i; // outlet to PIS->full vis command + id pis_fastvis_i; // outlet to PIS->fast vis command + id pis_novis_i; // outlet to PIS->no vis command + id pis_relight_i; // outlet to PIS->relight command + id pis_leaktest_i; // outlet to PIS->leak test command - char path_basepath[128]; // base path of heirarchy + id BSPoutput_i; // outlet to Text - char path_progdir[128]; // derived from basepath - char path_mapdirectory[128]; // derived from basepath - char path_finalmapdir[128]; // derived from basepath - - char path_wad8[128]; // path of texture WAD for cmd-8 key - char path_wad9[128]; // path of texture WAD for cmd-9 key - char path_wad0[128]; // path of texture WAD for cmd-0 key + NSString *path_projectinfo; // path of QE_Project file - char string_fullvis[1024]; // cmd-line parm - char string_fastvis[1024]; // cmd-line parm - char string_novis[1024]; // cmd-line parm - char string_relight[1024]; // cmd-line parm - char string_leaktest[1024]; // cmd-line parm - char string_entities[1024]; // cmd-line parm + NSString *path_basepath; // base path of heirarchy - int showDescriptions; // 1 = show map descs in browser + NSString *path_progdir; // derived from basepath + NSString *path_mapdirectory; // derived from basepath + NSString *path_finalmapdir; // derived from basepath - time_t lastModified; // last time project file was modified + char path_wad8[128]; // path of texture WAD for cmd-8 key + char path_wad9[128]; // path of texture WAD for cmd-9 key + char path_wad0[128]; // path of texture WAD for cmd-0 key + + const char *string_fullvis; // cmd-line parm + const char *string_fastvis; // cmd-line parm + const char *string_novis; // cmd-line parm + const char *string_relight; // cmd-line parm + const char *string_leaktest; // cmd-line parm + const char *string_entities; // cmd-line parm + + int showDescriptions; // 1 = show map descs in browser + + time_t lastModified; // last time project file was modified } -- initProject; -- initVars; +- (id) initProject; +- (id) initVars; -- (char *)currentProjectFile; +- (NSString *) currentProjectFile; -- setTextureWad: (char *)wf; +- (id) setTextureWad: (const char *)wf; -- addToOutput:(char *)string; -- clearBspOutput:sender; -- initProjSettings; -- changeChar:(char)f to:(char)t in:(id)obj; -- (int)searchForString:(char *)str in:(id)obj; +- (id) addToOutput: (const char *)string; +- (id) clearBspOutput: (id)sender; +- (id) initProjSettings; -- parseProjectFile; // read defaultsdatabase for project path -- openProjectFile:(char *)path; // called by openProject and newProject -- openProject; -- clickedOnMap:sender; // called if clicked on map in browser -- clickedOnWad:sender; // called if clicked on wad in browser +- (id) parseProjectFile; // read defaultsdatabase for project path +- (id) openProjectFile: (NSString *)path; // called by openProject, newProject +- (id) openProject; +- (id) clickedOnMap: sender; // called if clicked on map in browser +- (id) clickedOnWad: sender; // called if clicked on wad in browser -// methods to querie the project file +// +// methods to query the project file +// +- (NSString *) baseDirectoryPath; +- (NSString *) getMapDirectory; +- (NSString *) getFinalMapDirectory; +- (NSString *) getProgDirectory; -- (char *)getMapDirectory; -- (char *)getFinalMapDirectory; -- (char *)getProgDirectory; +- (const char *) getWAD8; +- (const char *) getWAD9; +- (const char *) getWAD0; -- (char *)getWAD8; -- (char *)getWAD9; -- (char *)getWAD0; - -- (char *)getFullVisCmd; -- (char *)getFastVisCmd; -- (char *)getNoVisCmd; -- (char *)getRelightCmd; -- (char *)getLeaktestCmd; -- (char *)getEntitiesCmd; +- (const char *) getFullVisCmd; +- (const char *) getFastVisCmd; +- (const char *) getNoVisCmd; +- (const char *) getRelightCmd; +- (const char *) getLeaktestCmd; +- (const char *) getEntitiesCmd; @end -void changeString(char cf,char ct,char *string); - +#endif // Project_h diff --git a/tools/Forge/Bundles/MapEdit/Project.m b/tools/Forge/Bundles/MapEdit/Project.m index 4095c87ab..2077bdfd0 100644 --- a/tools/Forge/Bundles/MapEdit/Project.m +++ b/tools/Forge/Bundles/MapEdit/Project.m @@ -1,526 +1,431 @@ -//====================================== +// ====================================== // // QuakeEd Project Management // -//====================================== +// ====================================== -#include "qedefs.h" +#include +#include "QF/qfplist.h" +#include "QF/quakefs.h" +#include "QF/sys.h" +#include "QF/va.h" -id project_i; +#include "Project.h" +#include "Map.h" +#include "QuakeEd.h" +#include "Preferences.h" +#include "Dict.h" +#include "Things.h" +#include "TexturePalette.h" + +id project_i; @implementation Project -- init +- (id) init { project_i = self; return self; } -//=========================================================== +// =========================================================== // -// Project code +// Project code // -//=========================================================== -- initVars +// =========================================================== +- (id) initVars { - char *s; - - s = [preferences_i getProjectPath]; - StripFilename(s); - strcpy(path_basepath,s); - - strcpy(path_progdir,s); - strcat(path_progdir,"/"SUBDIR_ENT); - - strcpy(path_mapdirectory,s); - strcat(path_mapdirectory,"/"SUBDIR_MAPS); // source dir + NSString *ts; - strcpy(path_finalmapdir,s); - strcat(path_finalmapdir,"/"SUBDIR_MAPS); // dest dir - - [basepathinfo_i setStringValue:s]; // in Project Inspector - - #if 0 - if ((s = [projectInfo getStringFor:BASEPATHKEY])) - { - strcpy(path_basepath,s); - - strcpy(path_progdir,s); - strcat(path_progdir,"/"SUBDIR_ENT); - - strcpy(path_mapdirectory,s); - strcat(path_mapdirectory,"/"SUBDIR_MAPS); // source dir + ts = path_projectinfo; + ts = path_basepath = [[ts stringByDeletingLastPathComponent] retain]; - strcpy(path_finalmapdir,s); - strcat(path_finalmapdir,"/"SUBDIR_MAPS); // dest dir - - [basepathinfo_i setStringValue:s]; // in Project Inspector - } - #endif - - if ((s = [projectInfo getStringFor:BSPFULLVIS])) - { - strcpy(string_fullvis,s); - changeString('@','\"',string_fullvis); - } - - if ((s = [projectInfo getStringFor:BSPFASTVIS])) - { - strcpy(string_fastvis,s); - changeString('@','\"',string_fastvis); - } - - if ((s = [projectInfo getStringFor:BSPNOVIS])) - { - strcpy(string_novis,s); - changeString('@','\"',string_novis); - } - - if ((s = [projectInfo getStringFor:BSPRELIGHT])) - { - strcpy(string_relight,s); - changeString('@','\"',string_relight); - } - - if ((s = [projectInfo getStringFor:BSPLEAKTEST])) - { - strcpy(string_leaktest,s); - changeString('@','\"',string_leaktest); - } + path_progdir = [[ts stringByAppendingPathComponent: SUBDIR_ENT] retain]; - if ((s = [projectInfo getStringFor:BSPENTITIES])) - { - strcpy(string_entities,s); - changeString('@','\"', string_entities); + path_mapdirectory = [[ts stringByAppendingPathComponent: SUBDIR_MAPS] retain]; + path_finalmapdir = [[ts stringByAppendingPathComponent: SUBDIR_MAPS] retain]; + + // in Project Inspector + [basepathinfo_i setStringValue: ts]; + +#if 0 // FIXME: for "out-of-tree" projects ? + if ((s = [projectInfo getStringFor: BASEPATHKEY])) { + strcpy (path_basepath, s); + + strcpy (path_progdir, s); + strcat (path_progdir, "/" SUBDIR_ENT); + + strcpy (path_mapdirectory, s); + strcat (path_mapdirectory, "/" SUBDIR_MAPS); // source dir + + strcpy (path_finalmapdir, s); + strcat (path_finalmapdir, "/" SUBDIR_MAPS); // dest dir + + [basepathinfo_i setStringValue: s]; // in Project Inspector } +#endif - // Build list of wads - wadList = [projectInfo parseMultipleFrom:WADSKEY]; + string_fullvis = [projectInfo getStringFor: BSPFULLVIS]; + string_fastvis = [projectInfo getStringFor: BSPFASTVIS]; + string_novis = [projectInfo getStringFor: BSPNOVIS]; + string_relight = [projectInfo getStringFor: BSPRELIGHT]; + string_leaktest = [projectInfo getStringFor: BSPLEAKTEST]; + string_entities = [projectInfo getStringFor: BSPENTITIES]; + + // Build list of wads + wadList = [projectInfo getArrayFor: WADSKEY]; + + // Build list of maps & descriptions + mapList = [projectInfo getArrayFor: MAPNAMESKEY]; + descList = [projectInfo getArrayFor: DESCKEY]; - // Build list of maps & descriptions - mapList = [projectInfo parseMultipleFrom:MAPNAMESKEY]; - descList = [projectInfo parseMultipleFrom:DESCKEY]; - [self changeChar:'_' to:' ' in:descList]; - [self initProjSettings]; return self; } -// -// Init Project Settings fields -// -- initProjSettings +// Init Project Settings fields +- (id) initProjSettings { - [pis_basepath_i setStringValue:path_basepath]; - [pis_fullvis_i setStringValue:string_fullvis]; - [pis_fastvis_i setStringValue:string_fastvis]; - [pis_novis_i setStringValue:string_novis]; - [pis_relight_i setStringValue:string_relight]; - [pis_leaktest_i setStringValue:string_leaktest]; - + [pis_basepath_i setStringValue: path_basepath]; + [pis_fullvis_i setStringValue: [NSString stringWithCString: string_fullvis]]; + [pis_fastvis_i setStringValue: [NSString stringWithCString: string_fastvis]]; + [pis_novis_i setStringValue: [NSString stringWithCString: string_novis]]; + [pis_relight_i setStringValue: [NSString stringWithCString: string_relight]]; + [pis_leaktest_i setStringValue: [NSString stringWithCString: string_leaktest]]; + return self; } -// -// Add text to the BSP Output window -// -- addToOutput:(char *)string +// Add text to the BSP Output window +- (id) addToOutput: (const char *)string { - int end; - + int end; + end = [BSPoutput_i textLength]; - [BSPoutput_i setSel:end :end]; - [BSPoutput_i replaceSel:string]; - + [BSPoutput_i replaceCharactersInRange: NSMakeRange (end, 0) + withString: [NSString stringWithCString: string]]; + end = [BSPoutput_i textLength]; - [BSPoutput_i setSel:end :end]; - [BSPoutput_i scrollSelToVisible]; - + [BSPoutput_i setSelectedRange: NSMakeRange (end, 0)]; + // XXX [BSPoutput_i scrollSelToVisible]; + return self; } -- clearBspOutput:sender +- (id) clearBspOutput: sender { - [BSPoutput_i selectAll:self]; - [BSPoutput_i replaceSel:"\0"]; - + int end; + + end = [BSPoutput_i textLength]; + [BSPoutput_i replaceCharactersInRange: NSMakeRange (0, end) withString: @""]; + return self; } -- print +- (id) print { - [BSPoutput_i printPSCode:self]; + // XXX [BSPoutput_i printPSCode:self]; return self; } - -- initProject +- (id) initProject { [self parseProjectFile]; if (projectInfo == NULL) return self; [self initVars]; - [mapbrowse_i reuseColumns:YES]; + [mapbrowse_i setReusesColumns: YES]; [mapbrowse_i loadColumnZero]; - [pis_wads_i reuseColumns:YES]; + [pis_wads_i setReusesColumns: YES]; [pis_wads_i loadColumnZero]; - [things_i initEntities]; - + [things_i initEntities]; + return self; } -// -// Change a character to another in a Storage list of strings -// -- changeChar:(char)f to:(char)t in:(id)obj +// Fill the QuakeEd Maps or wads browser +// (Delegate method - delegated in Interface Builder) +- (void) browser: sender createRowsForColumn: (int)column inMatrix: matrix { - int i; - int max; - char *string; + id cell; + plitem_t *list; + int max; + const char *name; + int i; - max = [obj count]; - for (i = 0;i < max;i++) - { - string = [obj elementAt:i]; - changeString(f,t,string); - } - return self; -} - -// -// Fill the QuakeEd Maps or wads browser -// (Delegate method - delegated in Interface Builder) -// -- (int)browser:sender fillMatrix:matrix inColumn:(int)column -{ - id cell, list; - int max; - char *name; - int i; - - if (sender == mapbrowse_i) + if (sender == mapbrowse_i) { list = mapList; - else if (sender == pis_wads_i) + } else if (sender == pis_wads_i) { list = wadList; - else - { - list = nil; - Error ("Project: unknown browser to fill"); + } else { + list = 0; + Sys_Error ("Project: unknown browser to fill"); } - - max = [list count]; - for (i = 0 ; i.QE_Project file -// -- parseProjectFile +// Read in the .QE_Project file +- (id) parseProjectFile { - char *path; - int rtn; - + NSString *path; + int rtn; + path = [preferences_i getProjectPath]; - if (!path || !path[0] || access(path,0)) - { - rtn = NSRunAlertPanel("Project Error!", - "A default project has not been found.\n" - , "Open Project", NULL, NULL); - if ([self openProject] == nil) - while (1) // can't run without a project - [NSApp terminate: self]; - return self; + if (![path length] || access ([path cString], 0)) { + rtn = NSRunAlertPanel (@"Project Error!", + @"A default project has not been found.\n", + @"Open Project", NULL, NULL); + if ([self openProject] == nil) { + while (1) + [NSApp terminate: self]; // can't run without a project + } + return self; } - [self openProjectFile:path]; + [self openProjectFile: path]; return self; } -// -// Loads and parses a project file -// -- openProjectFile:(char *)path -{ - FILE *fp; - struct stat s; +// Loads and parses a project file +- (id) openProjectFile: (NSString *)path +{ + FILE *fp; + struct stat s; - strcpy(path_projectinfo,path); + Sys_Printf ("openProjectFile: %s\n", [path cString]); + [path retain]; + [path_projectinfo release]; + path_projectinfo = path; projectInfo = NULL; - fp = fopen(path,"r+t"); + fp = fopen ([path cString], "r+t"); if (fp == NULL) return self; - stat(path,&s); + stat ([path cString], &s); lastModified = s.st_mtime; - projectInfo = [(Dict *)[Dict alloc] initFromFile:fp]; - fclose(fp); - + projectInfo = [(Dict *)[Dict alloc] initFromFile: fp]; + fclose (fp); + return self; } -- (char *)currentProjectFile +- (NSString *) currentProjectFile { return path_projectinfo; } -// -// Open a project file -// -- openProject +// Open a project file +- (id) openProject { - char path[128]; - id openpanel; - int rtn; - char *projtypes[2] = {"qpr",NULL}; - char **filenames; - char *dir; - - openpanel = [OpenPanel new]; - [openpanel allowMultipleFiles:NO]; - [openpanel chooseDirectories:NO]; - rtn = [openpanel runModalForTypes:projtypes]; - if (rtn == NS_OKTAG) - { - (const char *const *)filenames = [openpanel filenames]; - dir = (char *)[openpanel directory]; - sprintf(path,"%s/%s",dir,filenames[0]); - strcpy(path_projectinfo,path); - [self openProjectFile:path]; - return self; + id openpanel; + int rtn; + NSString *projtypes[] = {@"qpr"}; + NSArray *projtypes_array; + NSArray *filenames; + NSString *path; + + openpanel = [NSOpenPanel new]; + [openpanel setAllowsMultipleSelection:NO]; + [openpanel setCanChooseDirectories:NO]; + projtypes_array = [NSArray arrayWithObjects: projtypes count: 1]; + rtn = [openpanel runModalForTypes: projtypes_array]; + if (rtn == NSOKButton) { + filenames = [openpanel filenames]; + path = [filenames objectAtIndex: 0]; + [self openProjectFile: path]; + return self; } - + return nil; } - -// -// Search for a string in a List of strings -// -- (int)searchForString:(char *)str in:(id)obj +- (NSString *) baseDirectoryPath { - int i; - int max; - char *s; - - max = [obj count]; - for (i = 0;i < max; i++) - { - s = (char *)[obj elementAt:i]; - if (!strcmp(s,str)) - return 1; - } - return 0; + return path_basepath; } -- (char *)getMapDirectory +- (NSString *) getMapDirectory { return path_mapdirectory; } -- (char *)getFinalMapDirectory +- (NSString *) getFinalMapDirectory { return path_finalmapdir; } -- (char *)getProgDirectory +- (NSString *) getProgDirectory { return path_progdir; } - -// -// Return the WAD name for cmd-8 -// -- (char *)getWAD8 +// Return the WAD name for cmd-8 +- (const char *) getWAD8 { if (!path_wad8[0]) return NULL; + return path_wad8; } -// -// Return the WAD name for cmd-9 -// -- (char *)getWAD9 +// Return the WAD name for cmd-9 +- (const char *) getWAD9 { if (!path_wad9[0]) return NULL; + return path_wad9; } -// -// Return the WAD name for cmd-0 -// -- (char *)getWAD0 +// Return the WAD name for cmd-0 +- (const char *) getWAD0 { if (!path_wad0[0]) return NULL; + return path_wad0; } -// -// Return the FULLVIS cmd string -// -- (char *)getFullVisCmd +// Return the FULLVIS cmd string +- (const char *) getFullVisCmd { if (!string_fullvis[0]) return NULL; + return string_fullvis; } -// -// Return the FASTVIS cmd string -// -- (char *)getFastVisCmd +// Return the FASTVIS cmd string +- (const char *) getFastVisCmd { if (!string_fastvis[0]) return NULL; + return string_fastvis; } -// -// Return the NOVIS cmd string -// -- (char *)getNoVisCmd +// Return the NOVIS cmd string +- (const char *) getNoVisCmd { if (!string_novis[0]) return NULL; + return string_novis; } -// -// Return the RELIGHT cmd string -// -- (char *)getRelightCmd +// Return the RELIGHT cmd string +- (const char *) getRelightCmd { if (!string_relight[0]) return NULL; + return string_relight; } -// -// Return the LEAKTEST cmd string -// -- (char *)getLeaktestCmd +// Return the LEAKTEST cmd string +- (const char *) getLeaktestCmd { if (!string_leaktest[0]) return NULL; + return string_leaktest; } -- (char *)getEntitiesCmd +- (const char *) getEntitiesCmd { if (!string_entities[0]) return NULL; + return string_entities; } @end - -//==================================================== -// C Functions -//==================================================== - -// -// Change a character to a different char in a string -// -void changeString(char cf,char ct,char *string) -{ - int j; - - for (j = 0;j < strlen(string);j++) - if (string[j] == cf) - string[j] = ct; -} - - diff --git a/tools/Forge/Bundles/MapEdit/QuakeEd.h b/tools/Forge/Bundles/MapEdit/QuakeEd.h index 3c221d762..8caab5e86 100644 --- a/tools/Forge/Bundles/MapEdit/QuakeEd.h +++ b/tools/Forge/Bundles/MapEdit/QuakeEd.h @@ -1,98 +1,110 @@ +#ifndef QuakeEd_h +#define QuakeEd_h -extern id quakeed_i; +#include -extern BOOL filter_light, filter_path, filter_entities; -extern BOOL filter_clip_brushes, filter_water_brushes, filter_world; +extern id quakeed_i; -extern UserPath *upath; +extern BOOL filter_light, filter_path, filter_entities; +extern BOOL filter_clip_brushes, filter_water_brushes, filter_world; -extern id g_cmd_out_i; +extern id g_cmd_out_i; -double I_FloatTime (void); +double I_FloatTime (void); -void NopSound (void); +void NopSound (void); -void qprintf (char *fmt, ...); // prints text to cmd_out_i - -@interface QuakeEd : NSWindow +@interface QuakeEd: NSWindow { - BOOL dirty; - char filename[1024]; // full path with .map extension + BOOL dirty; + NSString *filename; // full path with .map extension + NSBitmapImageRep *cache[3]; + NSRect cache_rect[3]; + BOOL no_restore[3]; + +// // UI objects - id brushcount_i; - id entitycount_i; - id regionbutton_i; +// + id brushcount_i; + id entitycount_i; + id regionbutton_i; - id show_coordinates_i; - id show_names_i; + id show_coordinates_i; + id show_names_i; - id filter_light_i; - id filter_path_i; - id filter_entities_i; - id filter_clip_i; - id filter_water_i; - id filter_world_i; - - id cmd_in_i; // text fields - id cmd_out_i; - - id xy_drawmode_i; // passed over to xyview after init + id filter_light_i; + id filter_path_i; + id filter_entities_i; + id filter_clip_i; + id filter_water_i; + id filter_world_i; + + id cmd_in_i; // text fields + id cmd_out_i; + + id xy_drawmode_i; // passed over to xyview after init } -- setDefaultFilename; -- (char *)currentFilename; +- (id) setDefaultFilename; +- (NSString *) currentFilename; -- updateAll; // when a model has been changed -- updateCamera; // when the camera has moved -- updateXY; -- updateZ; +- (id) updateAll; // when a model has been changed +- (id) updateCamera; // when the camera has moved +- (id) updateXY; +- (id) updateZ; -- updateAll:sender; +- (id) updateAll: sender; -- newinstance; // force next flushwindow to clear all instance drawing -- redrawInstance; // erase and redraw all instance now +- (void) cameraNoRestore: (NSRect)rect; +- (void) xyNoRestore: (NSRect)rect; +- (void) zNoRestore: (NSRect)rect; -- appDidInit:sender; -- appWillTerminate:sender; +- (id) newinstance; // force next flushwindow to clear all + // instance drawing +- (id) redrawInstance; // erase and redraw all instance now -- openProject:sender; +- (id) appWillTerminate: sender; -- textCommand: sender; +- (id) openProject: sender; -- applyRegion: sender; +- (id) textCommand: sender; -- (BOOL)dirty; +- (id) applyRegion: sender; -- clear: sender; -- centerCamera: sender; -- centerZChecker: sender; +- (BOOL) dirty; -- changeXYLookUp: sender; +- (id) clear: sender; +- (id) centerCamera: sender; +- (id) centerZChecker: sender; -- setBrushRegion: sender; -- setXYRegion: sender; +- (id) changeXYLookUp: sender; -- open: sender; -- save: sender; -- saveAs: sender; +- (id) setBrushRegion: sender; +- (id) setXYRegion: sender; -- doOpen: (char *)fname; +- (id) open: sender; +- (id) save: sender; +- (id) saveAs: sender; -- saveBSP:(char *)cmdline dialog:(BOOL)wt; +- (id) doOpen: (NSString *)fname; -- BSP_Full: sender; -- BSP_FastVis: sender; -- BSP_NoVis: sender; -- BSP_relight: sender; -- BSP_stop: sender; -- BSP_entities: sender; +- (id) saveBSP: (const char *)cmdline dialog: (BOOL)wt; + +- (id) BSP_Full: sender; +- (id) BSP_FastVis: sender; +- (id) BSP_NoVis: sender; +- (id) BSP_relight: sender; +- (id) BSP_stop: sender; +- (id) BSP_entities: sender; + +- (id) applicationDefined: (NSEvent *)theEvent; // -// UI querie for other objects +// UI query for other objects // -- (BOOL)showCoordinates; -- (BOOL)showNames; +- (BOOL) showCoordinates; +- (BOOL) showNames; @end - +#endif // QuakeEd_h diff --git a/tools/Forge/Bundles/MapEdit/QuakeEd.m b/tools/Forge/Bundles/MapEdit/QuakeEd.m index 372dde803..2bd0c7ed2 100644 --- a/tools/Forge/Bundles/MapEdit/QuakeEd.m +++ b/tools/Forge/Bundles/MapEdit/QuakeEd.m @@ -1,77 +1,86 @@ +#include +#include +#include +#include +#include -#include "qedefs.h" +#include "QF/dstring.h" +#include "QF/quakeio.h" +#include "QF/sys.h" -id quakeed_i; -id entclasses_i; +#include "QuakeEd.h" +#include "Clipper.h" +#include "XYView.h" +#include "Map.h" +#include "CameraView.h" +#include "ZView.h" +#include "Preferences.h" +#include "InspectorControl.h" +#include "Project.h" -id g_cmd_out_i; +id quakeed_i; +id entclasses_i; -BOOL autodirty; -BOOL filter_light, filter_path, filter_entities; -BOOL filter_clip_brushes, filter_water_brushes, filter_world; +extern NSBezierPath *path; +id g_cmd_out_i; -BOOL running; +BOOL autodirty; +BOOL filter_light, filter_path, filter_entities; +BOOL filter_clip_brushes, filter_water_brushes, filter_world; -int bsppid; +BOOL running; + +int bsppid; #if 0 // example command strings -char *fullviscmd = "rsh satan \"/LocalApps/qbsp $1 $2 ; /LocalApps/light $2 ; /LocalApps/vis $2\""; -char *fastviscmd = "rsh satan \"/LocalApps/qbsp $1 $2 ; /LocalApps/light $2 ; /LocalApps/vis -fast $2\""; -char *noviscmd = "rsh satan \"/LocalApps/qbsp $1 $2 ; /LocalApps/light $2\""; -char *relightcmd = "rsh satan \"/LocalApps/light $2\""; -char *leakcmd = "rsh satan \"/LocalApps/qbsp -mark -notjunc $1 $2\""; +char *fullviscmd = + "rsh satan \"/LocalApps/qbsp $1 $2 ; /LocalApps/light $2 ; /LocalApps/vis $2\""; +char *fastviscmd = + "rsh satan \"/LocalApps/qbsp $1 $2 ; /LocalApps/light $2 ; /LocalApps/vis -fast $2\""; +char *noviscmd = + "rsh satan \"/LocalApps/qbsp $1 $2 ; /LocalApps/light $2\""; +char *relightcmd = "rsh satan \"/LocalApps/light $2\""; +char *leakcmd = "rsh satan \"/LocalApps/qbsp -mark -notjunc $1 $2\""; #endif -void NopSound (void) +void +NopSound (void) { NSBeep (); } -UserPath *upath; - - -void My_Malloc_Error (int code) +void +My_Malloc_Error (int code) { -// recursive toast Error ("Malloc error: %i\n", code); - write (1, "malloc error!\n", strlen("malloc error!\n")+1); +// recursive toast Error ("Malloc error: %i\n", code); + write (1, "malloc error!\n", strlen ("malloc error!\n") + 1); } -/* -=============== -AutoSave - -Every five minutes, save a modified map -=============== -*/ -void AutoSave(DPSTimedEntry tag, double now, void *userData) +#define FN_CMDOUT "/tmp/QuakeEdCmd.txt" +void +DisplayCmdOutput (void) { -// automatic backup - if (autodirty) - { - autodirty = NO; - [map_i writeMapFile: FN_AUTOSAVE useRegion: NO]; - } - [map_i writeStats]; -} + char *buffer; + QFile *file; + int size; - -void DisplayCmdOutput (void) -{ - char *buffer; - - LoadFile (FN_CMDOUT, (void **)&buffer); + file = Qopen (FN_CMDOUT, "rt"); + if (!file) + return; + size = Qfilesize (file); + buffer = malloc (size + 1); + size = Qread (file, buffer, size); + Qclose (file); unlink (FN_CMDOUT); - [project_i addToOutput:buffer]; + [project_i addToOutput: buffer]; free (buffer); if ([preferences_i getShowBSP]) - [inspcontrol_i changeInspectorTo:i_output]; + [inspcontrol_i setCurrentInspector: i_output]; - [preferences_i playBspSound]; - - NSPing (); + [preferences_i playBspSound]; } /* @@ -81,65 +90,66 @@ CheckCmdDone See if the BSP is done =============== */ -DPSTimedEntry cmdte; -void CheckCmdDone(DPSTimedEntry tag, double now, void *userData) +// DPSTimedEntry cmdte; +void +CheckCmdDone (/* DPSTimedEntry tag, */ double now, void *userData) { - union wait statusp; - struct rusage rusage; - - if (!wait4(bsppid, &statusp, WNOHANG, &rusage)) + union wait statusp; + struct rusage rusage; + + if (!wait4 (bsppid, &statusp, WNOHANG, &rusage)) return; DisplayCmdOutput (); bsppid = 0; - DPSRemoveTimedEntry( cmdte ); +// DPSRemoveTimedEntry( cmdte ); } -//============================================================================ +void +QuakeEd_print (const char *fmt, va_list args) +{ + static dstring_t *output; + NSString *string; + + if (!output) + output = dstring_new (); + dvsprintf (output, fmt, args); + string = [NSString stringWithCString: output->str]; + [g_cmd_out_i setStringValue: string]; + fputs (output->str, stdout); +} + +// ============================================================================ @implementation QuakeEd - /* =============== -init +AutoSave + +Every five minutes, save a modified map =============== */ -- initContent:(const NSRect *)contentRect -style:(int)aStyle -backing:(int)backingType -buttonMask:(int)mask -defer:(BOOL)flag +- (void) AutoSave { - [super initContent:contentRect - style:aStyle - backing:backingType - buttonMask:mask - defer:flag]; + // automatic backup + if (autodirty) { + autodirty = NO; +#define FN_AUTOSAVE "/qcache/AutoSaveMap.map" + [map_i writeMapFile: (char *) FN_AUTOSAVE useRegion: NO]; + } + [map_i writeStats]; +} - [self addToEventMask: - NS_RMOUSEDRAGGEDMASK|NS_LMOUSEDRAGGEDMASK]; - - malloc_error(My_Malloc_Error); - - quakeed_i = self; - dirty = autodirty = NO; - - DPSAddTimedEntry(5*60, AutoSave, self, NS_BASETHRESHOLD); - - upath = newUserPath (); +#define FN_TEMPSAVE @"/qcache/temp.map" +- (id) setDefaultFilename +{ + filename = FN_TEMPSAVE; + [filename retain]; + [self setTitleWithRepresentedFilename: filename]; return self; } -- setDefaultFilename -{ - strcpy (filename, FN_TEMPSAVE); - [self setTitleAsFilename:filename]; - - return self; -} - - -- (BOOL)dirty +- (BOOL) dirty { return dirty; } @@ -147,81 +157,106 @@ defer:(BOOL)flag /* =============================================================================== - DISPLAY UPDATING (handles both camera and XYView) + DISPLAY UPDATING (handles both camera and XYView) =============================================================================== */ -BOOL updateinflight; +BOOL updateinflight; -BOOL clearinstance; +BOOL clearinstance; -BOOL updatexy; -BOOL updatez; -BOOL updatecamera; +BOOL updatexy; +BOOL updatez; +BOOL updatecamera; -void postappdefined (void) +void +postappdefined (void) { - NSEvent ev; + NSEvent *ev; if (updateinflight) return; - -// post an event at the end of the que - ev.type = NS_APPDEFINED; - if (DPSPostEvent(&ev, 0) == -1) - printf ("WARNING: DPSPostEvent: full\n"); -//printf ("posted\n"); + // post an event at the end of the que + ev = [NSEvent otherEventWithType: NSApplicationDefined + location: NSZeroPoint + modifierFlags: 0 + timestamp: [[NSDate date] timeIntervalSinceReferenceDate] + windowNumber: 0 + context: [NSApp context] + subtype: 0 + data1: 0 + data2: 0]; + [NSApp postEvent: ev atStart: NO]; updateinflight = YES; } +int c_updateall; -int c_updateall; -- updateAll // when a model has been changed +- (id) updateAll // when a model has been changed { updatecamera = updatexy = updatez = YES; c_updateall++; postappdefined (); + return self; } -- updateAll:sender +- (id) updateAll: sender { [self updateAll]; + return self; } -- updateCamera // when the camera has moved +- (id) updateCamera // when the camera has moved { updatecamera = YES; clearinstance = YES; - + postappdefined (); + return self; } -- updateXY +- (id) updateXY { updatexy = YES; postappdefined (); + return self; } -- updateZ +- (id) updateZ { updatez = YES; postappdefined (); + return self; } +- (void) cameraNoRestore: (NSRect)rect +{ + no_restore[0] = YES; +} -- newinstance +- (void) xyNoRestore: (NSRect)rect +{ + no_restore[1] = YES; +} + +- (void) zNoRestore: (NSRect)rect +{ + no_restore[2] = YES; +} + +- (id) newinstance { clearinstance = YES; return self; } -- redrawInstance +- (id) redrawInstance { clearinstance = YES; [self flushWindow]; @@ -235,53 +270,76 @@ flushWindow instance draw the brush after each flush =============== */ --flushWindow +- (void) flushWindow { - [super flushWindow]; - - if (!running || in_error) - return self; // don't lock focus before nib is finished loading - - if (_flushDisabled) - return self; - - [cameraview_i lockFocus]; - if (clearinstance) - { - PSnewinstance (); - clearinstance = NO; - } + NSRect rect; + int i; + NSView *cv; - PSsetinstance (1); - linestart (0,0,0); - [map_i makeSelectedPerform: @selector(CameraDrawSelf)]; - [clipper_i cameraDrawSelf]; + [super flushWindow]; + + // don't lock focus before nib is finished loading + if (!running) + return; + + if (_disableFlushWindow) + return; + + cv = [self contentView]; + [cv lockFocus]; + for (i = 3; i >= 0; i--) { + if (cache[i]) { + if (!no_restore[i]) { + rect = cache_rect[i]; + [cache[i] drawAtPoint: rect.origin]; + } + no_restore[i] = NO; + [cache[i] release]; + cache[i] = 0; + } + } + rect = [cameraview_i frame]; +// rect = [cv convertRect: rect fromView: cameraview_i]; + cache_rect[0] = rect = NSIntegralRect (rect); + cache[0] = [[NSBitmapImageRep alloc] initWithFocusedViewRect: rect]; + + rect = [[xyview_i superview] frame]; + rect = [cv convertRect: rect fromView: [[xyview_i superview] superview]]; + cache_rect[1] = rect = NSIntegralRect (rect); + cache[1] = [[NSBitmapImageRep alloc] initWithFocusedViewRect: rect]; + + rect = [[zview_i superview] frame]; + rect = [cv convertRect: rect fromView: [[zview_i superview] superview]]; + cache_rect[2] = rect = NSIntegralRect (rect); + cache[2] = [[NSBitmapImageRep alloc] initWithFocusedViewRect: rect]; + [[self contentView] unlockFocus]; + + [cameraview_i lockFocus]; + linestart (0, 0, 0); + [map_i makeSelectedPerform: @selector (CameraDrawSelf)]; lineflush (); - PSsetinstance (0); - [cameraview_i unlockFocus]; + [clipper_i cameraDrawSelf]; + [cameraview_i unlockFocus]; [xyview_i lockFocus]; - PSsetinstance (1); - linestart (0,0,0); - [map_i makeSelectedPerform: @selector(XYDrawSelf)]; + linestart (0, 0, 0); + [map_i makeSelectedPerform: @selector (XYDrawSelf)]; lineflush (); [cameraview_i XYDrawSelf]; [zview_i XYDrawSelf]; [clipper_i XYDrawSelf]; - PSsetinstance (0); [xyview_i unlockFocus]; [zview_i lockFocus]; - PSsetinstance (1); - [map_i makeSelectedPerform: @selector(ZDrawSelf)]; + [map_i makeSelectedPerform: @selector (ZDrawSelf)]; [cameraview_i ZDrawSelf]; [clipper_i ZDrawSelf]; - PSsetinstance (0); [zview_i unlockFocus]; - return self; -} + clearinstance = NO; + [super flushWindow]; +} /* ============================================================================== @@ -291,128 +349,141 @@ App delegate methods ============================================================================== */ -- applicationDefined:(NSEvent *)theEvent +- (id) applicationDefined: (NSEvent *)theEvent { - NSEvent ev, *evp; - + NSEvent *evp; + updateinflight = NO; -//printf ("serviced\n"); - -// update screen - evp = [NSApp peekNextEvent:-1 into:&ev]; - if (evp) - { - postappdefined(); + // update screen + evp = [NSApp nextEventMatchingMask: NSAnyEventMask + untilDate: [NSDate distantPast] + inMode: NSEventTrackingRunLoopMode + dequeue: NO]; + if (evp) { + postappdefined (); return self; } - - [self disableFlushWindow]; + [self disableFlushWindow]; - if ([map_i count] != [entitycount_i intValue]) + if ([map_i count] != (unsigned) [entitycount_i intValue]) [entitycount_i setIntValue: [map_i count]]; - if ([[map_i currentEntity] count] != [brushcount_i intValue]) + + if ([[map_i currentEntity] count] != (unsigned) [brushcount_i intValue]) [brushcount_i setIntValue: [[map_i currentEntity] count]]; - + if (updatecamera) [cameraview_i display]; + if (updatexy) [xyview_i display]; + if (updatez) [zview_i display]; updatecamera = updatexy = updatez = NO; - [self reenableFlushWindow]; + [self enableFlushWindow]; [self flushWindow]; - -// NSPing (); - + return self; } -- appDidInit:sender +- (void) awakeFromNib { - NSScreen const *screens; - int screencount; - + // XXX [self addToEventMask: + // XXX NSRightMouseDragged|NSLeftMouseDragged]; + + // XXX malloc_error(My_Malloc_Error); + + quakeed_i = self; + dirty = autodirty = NO; + + [NSTimer timerWithTimeInterval: 5 * 60 + target: self + selector: @selector (AutoSave) + userInfo: nil + repeats: YES]; + + path = [NSBezierPath new]; +} + +- (void) applicationDidFinishLaunching: (NSNotification *)notification +{ + NSArray *screens; + NSScreen *scrn; + running = YES; - g_cmd_out_i = cmd_out_i; // for qprintf + g_cmd_out_i = cmd_out_i; // for qprintf + Sys_SetStdPrintf (QuakeEd_print); - [preferences_i readDefaults]; - [project_i initProject]; + [preferences_i readDefaults]; + [project_i initProject]; - [xyview_i setModeRadio: xy_drawmode_i]; // because xy view is inside - // scrollview and can't be - // connected directly in IB - - [self setFrameAutosaveName:"EditorWinFrame"]; + [xyview_i setModeRadio: xy_drawmode_i]; + // because xy view is inside + // scrollview and can't be + // connected directly in IB + + [self setFrameAutosaveName: @"EditorWinFrame"]; [self clear: self]; -// go to my second monitor - [NSApp getScreens:&screens count:&screencount]; - if (screencount == 2) - [self moveTopLeftTo:0 : screens[1].screenBounds.size.height - screen:screens+1]; - + // go to my second monitor + screens = [NSScreen screens]; + if ([screens count] == 2) { + NSRect frm; + scrn = [screens objectAtIndex: 1]; + frm = [scrn frame]; + [self setFrameTopLeftPoint: NSMakePoint (frm.origin.x, frm.size.height)]; + } + [self makeKeyAndOrderFront: self]; -//[self doOpen: "/raid/quake/id1_/maps/amlev1.map"]; // DEBUG [map_i newMap]; - - qprintf ("ready."); -//malloc_debug(-1); // DEBUG - + Sys_Printf ("ready.\n"); +} + +- (id) appWillTerminate: sender +{ + // FIXME: save dialog if dirty return self; } -- appWillTerminate:sender +// =========================================================================== + +- (id) textCommand: sender { -// FIXME: save dialog if dirty - return self; -} + char const *t; + t = [[sender stringValue] cString]; -//=========================================================================== + if (!strcmp (t, "texname")) { + texturedef_t *td; + id b; -- textCommand: sender -{ - char const *t; - - t = [sender stringValue]; - - if (!strcmp (t, "texname")) - { - texturedef_t *td; - id b; - b = [map_i selectedBrush]; - if (!b) - { - qprintf ("nothing selected"); + if (!b) { + Sys_Printf ("nothing selected\n"); return self; } td = [b texturedef]; - qprintf (td->texture); + Sys_Printf ("%s\n", td->texture); return self; - } - else - qprintf ("Unknown command\n"); - return self; + } else { + Sys_Printf ("Unknown command\n"); + } return self; } - -- openProject:sender +- (id) openProject: sender { - [project_i openProject]; + [project_i openProject]; return self; } - -- clear: sender -{ +- (id) clear: sender +{ [map_i newMap]; [self updateAll]; @@ -422,47 +493,42 @@ App delegate methods return self; } - -- centerCamera: sender +- (id) centerCamera: sender { - NSRect sbounds; - - [[xyview_i _super_view] getBounds: &sbounds]; - - sbounds.origin.x += sbounds.size.width/2; - sbounds.origin.y += sbounds.size.height/2; - + NSRect sbounds; + + sbounds = [[xyview_i superview] bounds]; + + sbounds.origin.x += sbounds.size.width / 2; + sbounds.origin.y += sbounds.size.height / 2; + [cameraview_i setXYOrigin: &sbounds.origin]; [self updateAll]; - + return self; } -- centerZChecker: sender +- (id) centerZChecker: sender { - NSRect sbounds; - - [[xyview_i _super_view] getBounds: &sbounds]; - - sbounds.origin.x += sbounds.size.width/2; - sbounds.origin.y += sbounds.size.height/2; - + NSRect sbounds; + + sbounds = [[xyview_i superview] bounds]; + + sbounds.origin.x += sbounds.size.width / 2; + sbounds.origin.y += sbounds.size.height / 2; + [zview_i setPoint: &sbounds.origin]; [self updateAll]; - + return self; } -- changeXYLookUp: sender +- (id) changeXYLookUp: sender { if ([sender intValue]) - { xy_viewnormal[2] = 1; - } else - { xy_viewnormal[2] = -1; - } [self updateAll]; return self; } @@ -475,13 +541,12 @@ REGION MODIFICATION ============================================================================== */ - /* ================== applyRegion: ================== */ -- applyRegion: sender +- (id) applyRegion: sender { filter_clip_brushes = [filter_clip_i intValue]; filter_water_brushes = [filter_water_i intValue]; @@ -490,48 +555,45 @@ applyRegion: filter_entities = [filter_entities_i intValue]; filter_world = [filter_world_i intValue]; - if (![regionbutton_i intValue]) - { + if (![regionbutton_i intValue]) { region_min[0] = region_min[1] = region_min[2] = -9999; region_max[0] = region_max[1] = region_max[2] = 9999; } - [map_i makeGlobalPerform: @selector(newRegion)]; - + [map_i makeGlobalPerform: @selector (newRegion)]; + [self updateAll]; return self; } -- setBrushRegion: sender +- (id) setBrushRegion: sender { - id b; + id b; -// get the bounds of the current selection - - if ([map_i numSelected] != 1) - { - qprintf ("must have a single brush selected"); + // get the bounds of the current selection + if ([map_i numSelected] != 1) { + Sys_Printf ("must have a single brush selected\n"); return self; - } + } b = [map_i selectedBrush]; [b getMins: region_min maxs: region_max]; [b remove]; -// turn region on + // turn region on [regionbutton_i setIntValue: 1]; [self applyRegion: self]; - + return self; } -- setXYRegion: sender +- (id) setXYRegion: sender { - NSRect bounds; - -// get xy size - [[xyview_i _super_view] getBounds: &bounds]; + NSRect bounds; + + // get xy size + bounds = [[xyview_i superview] bounds]; region_min[0] = bounds.origin.x; region_min[1] = bounds.origin.y; @@ -539,28 +601,25 @@ applyRegion: region_max[0] = bounds.origin.x + bounds.size.width; region_max[1] = bounds.origin.y + bounds.size.height; region_max[2] = 99999; - -// turn region on + + // turn region on [regionbutton_i setIntValue: 1]; [self applyRegion: self]; - + return self; } -// // UI querie for other objects -// -- (BOOL)showCoordinates +- (BOOL) showCoordinates { return [show_coordinates_i intValue]; } -- (BOOL)showNames +- (BOOL) showNames { return [show_names_i intValue]; } - /* ============================================================================== @@ -568,24 +627,19 @@ BSP PROCESSING ============================================================================== */ - -void ExpandCommand (char *in, char *out, char *src, char *dest) +void +ExpandCommand (const char *in, char *out, const char *src, const char *dest) { - while (*in) - { - if (in[0] == '$') - { - if (in[1] == '1') - { + while (*in) { + if (in[0] == '$') { + if (in[1] == '1') { strcpy (out, src); - out += strlen(src); - } - else if (in[1] == '2') - { + out += strlen (src); + } else if (in[1] == '2') { strcpy (out, dest); - out += strlen(dest); + out += strlen (dest); } - in += 2; + in += 2; continue; } *out++ = *in++; @@ -593,149 +647,134 @@ void ExpandCommand (char *in, char *out, char *src, char *dest) *out = 0; } - /* ============= saveBSP ============= */ -- saveBSP:(char *)cmdline dialog:(BOOL)wt +- (id) saveBSP: (const char *)cmdline dialog: (BOOL)wt { - char expandedcmd[1024]; - char mappath[1024]; - char bsppath[1024]; - int oldLightFilter; - int oldPathFilter; - char *destdir; - - if (bsppid) - { - NSBeep(); + char expandedcmd[1024]; + NSString *mappath; + NSString *bsppath; + int oldLightFilter; + int oldPathFilter; + NSString *destdir; + + if (bsppid) { + NSBeep (); return self; } -// -// turn off the filters so all entities get saved -// + // turn off the filters so all entities get saved oldLightFilter = [filter_light_i intValue]; oldPathFilter = [filter_path_i intValue]; - [filter_light_i setIntValue:0]; - [filter_path_i setIntValue:0]; + [filter_light_i setIntValue: 0]; + [filter_path_i setIntValue: 0]; [self applyRegion: self]; - - if ([regionbutton_i intValue]) - { - strcpy (mappath, filename); - StripExtension (mappath); - strcat (mappath, ".reg"); - [map_i writeMapFile: mappath useRegion: YES]; - wt = YES; // allways pop the dialog on region ops + + if ([regionbutton_i intValue]) { + mappath = [[filename stringByDeletingPathExtension] + stringByAppendingPathExtension: @"reg"]; + [map_i writeMapFile: [mappath cString] useRegion: YES]; + wt = YES; // allways pop the dialog on region ops + } else { + mappath = filename; } - else - strcpy (mappath, filename); - -// save the entire thing, just in case there is a problem + // save the entire thing, just in case there is a problem [self save: self]; - [filter_light_i setIntValue:oldLightFilter]; - [filter_path_i setIntValue:oldPathFilter]; + [filter_light_i setIntValue: oldLightFilter]; + [filter_path_i setIntValue: oldPathFilter]; [self applyRegion: self]; -// -// write the command to the bsp host -// + // write the command to the bsp host destdir = [project_i getFinalMapDirectory]; - strcpy (bsppath, destdir); - strcat (bsppath, "/"); - ExtractFileBase (mappath, bsppath + strlen(bsppath)); - strcat (bsppath, ".bsp"); - - ExpandCommand (cmdline, expandedcmd, mappath, bsppath); + bsppath = [destdir stringByAppendingPathComponent: + [[[mappath lastPathComponent] stringByDeletingPathExtension] + stringByAppendingPathExtension: @"bsp"]]; + + ExpandCommand (cmdline, expandedcmd, [mappath cString], [bsppath cString]); strcat (expandedcmd, " > "); strcat (expandedcmd, FN_CMDOUT); strcat (expandedcmd, "\n"); printf ("system: %s", expandedcmd); - [project_i addToOutput: "\n\n========= BUSY =========\n\n"]; + [project_i addToOutput: (char *) "\n\n========= BUSY =========\n\n"]; [project_i addToOutput: expandedcmd]; if ([preferences_i getShowBSP]) - [inspcontrol_i changeInspectorTo:i_output]; - - if (wt) - { - id panel; - - panel = NSGetAlertPanel("BSP In Progress",expandedcmd,NULL,NULL,NULL); - [panel makeKeyAndOrderFront:NULL]; - system(expandedcmd); - NSFreeAlertPanel(panel); - [self makeKeyAndOrderFront:NULL]; + [inspcontrol_i setCurrentInspector: i_output]; + if (wt) { + id panel; + NSModalSession session; + + panel = NSGetAlertPanel (@"BSP In Progress", + [NSString stringWithCString: expandedcmd], + NULL, NULL, NULL); + session = [NSApp beginModalSessionForWindow: panel]; + system (expandedcmd); + [NSApp endModalSession: session]; + [panel close]; + NSReleaseAlertPanel (panel); DisplayCmdOutput (); - } - else - { - cmdte = DPSAddTimedEntry(1, CheckCmdDone, self, NS_BASETHRESHOLD); - if (! (bsppid = fork ()) ) - { + } else { +// cmdte = DPSAddTimedEntry(1, CheckCmdDone, self, NS_BASETHRESHOLD); + if (!(bsppid = fork ())) { system (expandedcmd); exit (0); } } - + return self; } - -- BSP_Full: sender +- (id) BSP_Full: sender { - [self saveBSP:[project_i getFullVisCmd] dialog: NO]; + [self saveBSP: [project_i getFullVisCmd] dialog: NO]; return self; } -- BSP_FastVis: sender +- (id) BSP_FastVis: sender { - [self saveBSP:[project_i getFastVisCmd] dialog: NO]; + [self saveBSP: [project_i getFastVisCmd] dialog: NO]; return self; } -- BSP_NoVis: sender +- (id) BSP_NoVis: sender { - [self saveBSP:[project_i getNoVisCmd] dialog: NO]; + [self saveBSP: [project_i getNoVisCmd] dialog: NO]; return self; } -- BSP_relight: sender +- (id) BSP_relight: sender { - [self saveBSP:[project_i getRelightCmd] dialog: NO]; + [self saveBSP: [project_i getRelightCmd] dialog: NO]; return self; } -- BSP_entities: sender +- (id) BSP_entities: sender { - [self saveBSP:[project_i getEntitiesCmd] dialog: NO]; + [self saveBSP: [project_i getEntitiesCmd] dialog: NO]; return self; } -- BSP_stop: sender +- (id) BSP_stop: sender { - if (!bsppid) - { - NSBeep(); + if (!bsppid) { + NSBeep (); return self; } - + kill (bsppid, 9); - CheckCmdDone (cmdte, 0, NULL); - [project_i addToOutput: "\n\n========= STOPPED =========\n\n"]; - +// CheckCmdDone (cmdte, 0, NULL); + [project_i addToOutput: (char *) "\n\n========= STOPPED =========\n\n"]; + return self; } - - /* ============== doOpen: @@ -743,284 +782,276 @@ doOpen: Called by open or the project panel ============== */ -- doOpen: (char *)fname; -{ - strcpy (filename, fname); - - [map_i readMapFile:filename]; - +- (id) doOpen: (NSString *)fname; +{ + [fname retain]; + [filename release]; + filename = fname; + + [map_i readMapFile: [filename cString]]; + [regionbutton_i setIntValue: 0]; - [self setTitleAsFilename:fname]; + [self setTitleWithRepresentedFilename: fname]; [self updateAll]; - qprintf ("%s loaded\n", fname); - + Sys_Printf ("%s loaded\n", [fname cString]); + return self; } - /* ============== open ============== */ -- open: sender; +- (id) open: sender; { - id openpanel; - static char *suffixlist[] = {"map", 0}; + id openpanel; + NSString *suffixlist[] = {@"map"}; + NSArray *types = [NSArray arrayWithObjects: suffixlist count: 1]; - openpanel = [OpenPanel new]; + openpanel = [NSOpenPanel new]; - if ( [openpanel - runModalForDirectory: [project_i getMapDirectory] - file: "" - types: suffixlist] != NS_OKTAG) + if ([openpanel + runModalForDirectory: [project_i getMapDirectory] + file: @"" + types: types] != NSOKButton) return self; + [self doOpen: [openpanel filename]]; - [self doOpen: (char *)[openpanel filename]]; - return self; } - /* ============== save: ============== */ -- save: sender; +- (id) save: sender; { - char backup[1024]; + NSString *backup; -// force a name change if using tempname - if (!strcmp (filename, FN_TEMPSAVE) ) + // force a name change if using tempname + if (![filename compare: FN_TEMPSAVE]) return [self saveAs: self]; - dirty = autodirty = NO; - strcpy (backup, filename); - StripExtension (backup); - strcat (backup, ".bak"); - rename (filename, backup); // copy old to .bak + backup = [[filename stringByDeletingPathExtension] + stringByAppendingPathExtension: @"bak"]; + rename ([filename cString], [backup cString]); // copy old to .bak - [map_i writeMapFile: filename useRegion: NO]; + [map_i writeMapFile: [filename cString] useRegion: NO]; return self; } - /* ============== saveAs ============== */ -- saveAs: sender; +- (id) saveAs: sender; { - id panel_i; - char dir[1024]; - - panel_i = [SavePanel new]; - ExtractFileBase (filename, dir); - [panel_i setRequiredFileType: "map"]; - if ( [panel_i runModalForDirectory:[project_i getMapDirectory] file: dir] != NS_OKTAG) + id panel_i; + NSString *dir; + NSString *fname; + + panel_i = [NSSavePanel new]; + dir = [filename stringByDeletingLastPathComponent]; + [panel_i setRequiredFileType: @"map"]; + if ([panel_i runModalForDirectory: [project_i getMapDirectory] file: dir] + != NSOKButton) return self; - - strcpy (filename, [panel_i filename]); - - [self setTitleAsFilename:filename]; - - [self save: self]; - + fname = [[panel_i filename] retain]; + [filename release]; + filename = fname; + + [self setTitleWithRepresentedFilename: filename]; + + [self save: self]; + return self; } - /* =============================================================================== - OTHER METHODS + OTHER METHODS =============================================================================== */ - -// -// AJR - added this for Project info -// -- (char *)currentFilename +// AJR - added this for Project info +- (NSString *) currentFilename { return filename; } -- deselect: sender +- (id) deselect: sender { - if ([clipper_i hide]) // first click hides only the clipper + if ([clipper_i hide]) // first click hides only the clipper return [self updateAll]; - [map_i setCurrentEntity: [map_i objectAt: 0]]; // make world selected - [map_i makeSelectedPerform: @selector(deselect)]; + [map_i setCurrentEntity: [map_i objectAtIndex: 0]]; + + // make world selected + [map_i makeSelectedPerform: @selector (deselect)]; [self updateAll]; - + return self; } - /* =============== keyDown =============== */ -#define KEY_RIGHTARROW 0xae -#define KEY_LEFTARROW 0xac -#define KEY_UPARROW 0xad -#define KEY_DOWNARROW 0xaf - -- keyDown:(NSEvent *)theEvent +- (id) keyDown: (NSEvent *)theEvent { - int ch; - -// function keys - switch (theEvent->data.key.keyCode) - { - case 60: // F2 - [cameraview_i setDrawMode: dr_wire]; - qprintf ("wire draw mode"); - return self; - case 61: // F3 - [cameraview_i setDrawMode: dr_flat]; - qprintf ("flat draw mode"); - return self; - case 62: // F4 - [cameraview_i setDrawMode: dr_texture]; - qprintf ("texture draw mode"); - return self; + NSString *chars = [theEvent characters]; + unichar c = ([chars length] == 1) ? [chars characterAtIndex: 0] : '\0'; - case 63: // F5 - [xyview_i setDrawMode: dr_wire]; - qprintf ("wire draw mode"); - return self; - case 64: // F6 - qprintf ("texture draw mode"); - return self; - - case 66: // F8 - [cameraview_i homeView: self]; - return self; - - case 88: // F12 - [map_i subtractSelection: self]; - return self; + // function keys + switch (c) { + case NSF2FunctionKey: + [cameraview_i setDrawMode: dr_wire]; + Sys_Printf ("wire draw mode\n"); + return self; - case 106: // page up - [cameraview_i upFloor: self]; - return self; - - case 107: // page down - [cameraview_i downFloor: self]; - return self; - - case 109: // end - [self deselect: self]; - return self; - } + case NSF3FunctionKey: + [cameraview_i setDrawMode: dr_flat]; + Sys_Printf ("flat draw mode\n"); + return self; -// portable things - ch = tolower(theEvent->data.key.charCode); - - switch (ch) - { - case KEY_RIGHTARROW: - case KEY_LEFTARROW: - case KEY_UPARROW: - case KEY_DOWNARROW: - case 'a': - case 'z': - case 'd': - case 'c': - case '.': - case ',': - [cameraview_i _keyDown: theEvent]; - break; + case NSF4FunctionKey: + [cameraview_i setDrawMode: dr_texture]; + Sys_Printf ("texture draw mode\n"); + return self; - case 27: // escape - autodirty = dirty = YES; - [self deselect: self]; - return self; - - case 127: // delete - autodirty = dirty = YES; - [map_i makeSelectedPerform: @selector(remove)]; - [clipper_i hide]; - [self updateAll]; - break; + case NSF5FunctionKey: + [xyview_i setDrawMode: dr_wire]; + Sys_Printf ("wire draw mode\n"); + return self; - case '/': - [clipper_i flipNormal]; - [self updateAll]; - break; - - case 13: // enter - [clipper_i carve]; - [self updateAll]; - qprintf ("carved brush"); - break; - - case ' ': - [map_i cloneSelection: self]; - break; - + case NSF6FunctionKey: + Sys_Printf ("texture draw mode\n"); + return self; -// -// move selection keys -// - case '2': - VectorCopy (vec3_origin, sb_translate); - sb_translate[1] = -[xyview_i gridsize]; - [map_i makeSelectedPerform: @selector(translate)]; - [self updateAll]; - break; - case '8': - VectorCopy (vec3_origin, sb_translate); - sb_translate[1] = [xyview_i gridsize]; - [map_i makeSelectedPerform: @selector(translate)]; - [self updateAll]; - break; + case NSF8FunctionKey: + [cameraview_i homeView: self]; + return self; - case '4': - VectorCopy (vec3_origin, sb_translate); - sb_translate[0] = -[xyview_i gridsize]; - [map_i makeSelectedPerform: @selector(translate)]; - [self updateAll]; - break; - case '6': - VectorCopy (vec3_origin, sb_translate); - sb_translate[0] = [xyview_i gridsize]; - [map_i makeSelectedPerform: @selector(translate)]; - [self updateAll]; - break; + case NSF12FunctionKey: + [map_i subtractSelection: self]; + return self; - case '-': - VectorCopy (vec3_origin, sb_translate); - sb_translate[2] = -[xyview_i gridsize]; - [map_i makeSelectedPerform: @selector(translate)]; - [self updateAll]; - break; - case '+': - VectorCopy (vec3_origin, sb_translate); - sb_translate[2] = [xyview_i gridsize]; - [map_i makeSelectedPerform: @selector(translate)]; - [self updateAll]; - break; + case NSPageUpFunctionKey: + [cameraview_i upFloor: self]; + return self; - default: - qprintf ("undefined keypress"); - NopSound (); - break; - } + case NSPageDownFunctionKey: + [cameraview_i downFloor: self]; + return self; - return self; + case NSEndFunctionKey: + [self deselect: self]; + return self; + + case NSRightArrowFunctionKey: + case NSLeftArrowFunctionKey: + case NSUpArrowFunctionKey: + case NSDownArrowFunctionKey: + case 'a': + case 'A': + case 'z': + case 'Z': + case 'd': + case 'D': + case 'c': + case 'C': + case '.': + case ',': + [cameraview_i _keyDown: theEvent]; + break; + + case 27: // escape + autodirty = dirty = YES; + [self deselect: self]; + return self; + + case 127: // delete + autodirty = dirty = YES; + [map_i makeSelectedPerform: @selector (remove)]; + [clipper_i hide]; + [self updateAll]; + break; + + case '/': + [clipper_i flipNormal]; + [self updateAll]; + break; + + case 13: // enter + [clipper_i carve]; + [self updateAll]; + Sys_Printf ("carved brush\n"); + break; + + case ' ': + [map_i cloneSelection: self]; + break; + + // move selection keys + case '2': + VectorCopy (vec3_origin, sb_translate); + sb_translate[1] = -[xyview_i gridsize]; + [map_i makeSelectedPerform: @selector (translate)]; + [self updateAll]; + break; + + case '8': + VectorCopy (vec3_origin, sb_translate); + sb_translate[1] = [xyview_i gridsize]; + [map_i makeSelectedPerform: @selector (translate)]; + [self updateAll]; + break; + + case '4': + VectorCopy (vec3_origin, sb_translate); + sb_translate[0] = -[xyview_i gridsize]; + [map_i makeSelectedPerform: @selector (translate)]; + [self updateAll]; + break; + + case '6': + VectorCopy (vec3_origin, sb_translate); + sb_translate[0] = [xyview_i gridsize]; + [map_i makeSelectedPerform: @selector (translate)]; + [self updateAll]; + break; + + case '-': + VectorCopy (vec3_origin, sb_translate); + sb_translate[2] = -[xyview_i gridsize]; + [map_i makeSelectedPerform: @selector (translate)]; + [self updateAll]; + break; + + case '+': + VectorCopy (vec3_origin, sb_translate); + sb_translate[2] = [xyview_i gridsize]; + [map_i makeSelectedPerform: @selector (translate)]; + [self updateAll]; + break; + + default: + Sys_Printf ("undefined keypress\n"); + NopSound (); + break; + } /* switch */ + + return self; } - @end diff --git a/tools/Forge/Bundles/MapEdit/QuakeEd_main.m b/tools/Forge/Bundles/MapEdit/QuakeEd_main.m index c28b31ef8..5bb8dc286 100644 --- a/tools/Forge/Bundles/MapEdit/QuakeEd_main.m +++ b/tools/Forge/Bundles/MapEdit/QuakeEd_main.m @@ -1,15 +1,27 @@ -/* Generated by the NeXT Project Builder - NOTE: Do NOT change this file -- Project Builder maintains it. -*/ +#include -#include +#include "QF/sys.h" -void main(int argc, char *argv[]) { +#include "QuakeEd.h" - [Application new]; - if ([NSApp loadNibSection:"QuakeEd.nib" owner:NSApp withNames:NO]) - [NSApp run]; - - [NSApp free]; - exit(0); +@interface QuakeEdApp: NSApplication +- (void) sendEvent: (NSEvent *)evt; +@end + +@implementation QuakeEdApp + +- (void) sendEvent: (NSEvent *)evt; +{ + if ([evt type] == NSApplicationDefined) + [quakeed_i applicationDefined: evt]; + else + [super sendEvent: evt]; +} + +@end + +int +main (int argc, const char *argv[]) +{ + return NSApplicationMain (argc, argv); } diff --git a/tools/Forge/Bundles/MapEdit/SetBrush.h b/tools/Forge/Bundles/MapEdit/SetBrush.h index 44e0de503..aa7b3d691 100644 --- a/tools/Forge/Bundles/MapEdit/SetBrush.h +++ b/tools/Forge/Bundles/MapEdit/SetBrush.h @@ -1,158 +1,172 @@ +#ifndef SetBrush_h +#define SetBrush_h +#include -#define MAX_FACES 16 +#include "QF/mathlib.h" -typedef float vec5_t[5]; +#include "TexturePalette.h" -typedef struct -{ - int numpoints; - vec5_t points[8]; // variable sized +#define MAX_FACES 16 + +typedef struct { + int numpoints; + vec5_t points[8]; // variable sized } winding_t; -#define MAX_POINTS_ON_WINDING 64 +#define MAX_POINTS_ON_WINDING 64 -typedef struct -{ - vec3_t normal; - float dist; +typedef struct { + vec3_t normal; + float dist; } plane_t; -typedef struct -{ +typedef struct { // implicit rep - vec3_t planepts[3]; - texturedef_t texture; + vec3_t planepts[3]; + texturedef_t texture; // cached rep - plane_t plane; - qtexture_t *qtexture; - float light; // 0 - 1.0 - winding_t *w; + plane_t plane; + qtexture_t *qtexture; + float light; // 0 - 1.0 + winding_t *w; } face_t; -#define ON_EPSILON 0.1 -#define FP_EPSILON 0.01 -#define VECTOR_EPSILON 0.0001 +#define ON_EPSILON 0.1 +#define FP_EPSILON 0.01 +#define VECTOR_EPSILON 0.0001 -#define SIDE_FRONT 0 -#define SIDE_BACK 1 -#define SIDE_ON 2 +#define SIDE_FRONT 0 +#define SIDE_BACK 1 +#define SIDE_ON 2 +winding_t *ClipWinding (winding_t * in, plane_t *split); +winding_t *CopyWinding (winding_t * w); +winding_t *NewWinding (int points); -winding_t *ClipWinding (winding_t *in, plane_t *split); -winding_t *CopyWinding (winding_t *w); -winding_t *NewWinding (int points); - - -@interface SetBrush : Object +@interface SetBrush: NSObject { - BOOL regioned; // not active - BOOL selected; + BOOL regioned; // not active + BOOL selected; + BOOL invalid; // not a proper polyhedron - BOOL invalid; // not a proper polyhedron - - id parent; // the entity this brush is in - vec3_t bmins, bmaxs; - vec3_t entitycolor; - int numfaces; - face_t faces[MAX_FACES]; + id parent; // the entity this brush is in + vec3_t bmins, bmaxs; + vec3_t entitycolor; + int numfaces; + face_t faces[MAX_FACES]; } -- initOwner: own mins:(float *)mins maxs:(float *)maxs texture:(texturedef_t *)tex; -- initFromTokens: own; -- setMins:(float *)mins maxs:(float *)maxs; +- (SetBrush *) initOwner: (id)own + mins: (float *)mins + maxs: (float *)maxs + texture: (texturedef_t *)tex; -- parent; -- setParent: (id)p; +- (id) initFromScript: (struct script_s *)script + owner: (id)own; -- setEntityColor: (vec3_t)color; +- (id) setMins: (float *)mins maxs: (float *)maxs; -- calcWindings; +- (id) parent; +- (id) setParent: (id)p; -- writeToFILE: (FILE *)f region: (BOOL)reg; +- (id) setEntityColor: (vec3_t)color; -- (BOOL)selected; -- (BOOL)regioned; -- setSelected: (BOOL)s; -- setRegioned: (BOOL)s; +- (id) calcWindings; -- getMins: (vec3_t)mins maxs: (vec3_t)maxs; +- (void) writeToFILE: (FILE *)f region: (BOOL)reg; -- (BOOL)containsPoint: (vec3_t)pt; +- (BOOL) selected; +- (BOOL) regioned; +- (void) setSelected: (BOOL)s; +- (void) setRegioned: (BOOL)s; -- freeWindings; -- removeIfInvalid; +- (void) getMins: (vec3_t)mins maxs: (vec3_t)maxs; -extern vec3_t region_min, region_max; -- newRegion; +- (BOOL) containsPoint: (vec3_t)pt; -- (texturedef_t *)texturedef; -- (texturedef_t *)texturedefForFace: (int)f; -- setTexturedef: (texturedef_t *)tex; -- setTexturedef: (texturedef_t *)tex forFace:(int)f; +- (void) freeWindings; +- (id) removeIfInvalid; -- XYDrawSelf; -- ZDrawSelf; -- CameraDrawSelf; -- XYRenderSelf; -- CameraRenderSelf; +extern vec3_t region_min, region_max; -- hitByRay: (vec3_t)p1 : (vec3_t) p2 : (float *)time : (int *)face; +- (id) newRegion; + +- (texturedef_t *) texturedef; +- (texturedef_t *) texturedefForFace: (int)f; +- (void) setTexturedef: (texturedef_t *)tex; +- (void) setTexturedef: (texturedef_t *)tex forFace: (int)f; + +- (void) XYDrawSelf; +- (void) ZDrawSelf; +- (void) CameraDrawSelf; +- (void) XYRenderSelf; +- (void) CameraRenderSelf; + +- (void) hitByRay: (vec3_t)p1: (vec3_t)p2: (float *)time: (int *)face; // // single brush actions // -extern int numcontrolpoints; -extern float *controlpoints[MAX_FACES*3]; -- getZdragface: (vec3_t)dragpoint; -- getXYdragface: (vec3_t)dragpoint; -- getXYShearPoints: (vec3_t)dragpoint; +extern int numcontrolpoints; +extern float *controlpoints[MAX_FACES * 3]; -- addFace: (face_t *)f; +- (void) getZdragface: (vec3_t)dragpoint; +- (void) getXYdragface: (vec3_t)dragpoint; +- (void) getXYShearPoints: (vec3_t)dragpoint; + +- (id) addFace: (face_t *)f; // // multiple brush actions // -- carveByClipper; +- (void) carveByClipper; -extern vec3_t sb_translate; -- translate; +extern vec3_t sb_translate; -extern id carve_in, carve_out; -- select; -- deselect; -- remove; -- flushTextures; +- (void) translate; -extern vec3_t sb_mins, sb_maxs; -- addToBBox; +extern id carve_in, carve_out; -extern vec3_t sel_x, sel_y, sel_z; -extern vec3_t sel_org; -- transform; +- (void) select; +- (void) deselect; +- (void) remove; +- (void) flushTextures; -- flipNormals; +extern vec3_t sb_mins, sb_maxs; -- carve; -- setCarveVars; +- (void) addToBBox; -extern id sb_newowner; -- moveToEntity; +extern vec3_t sel_x, sel_y, sel_z; +extern vec3_t sel_org; -- takeCurrentTexture; +- (void) transform; -extern vec3_t select_min, select_max; -- selectPartial; -- selectComplete; -- regionPartial; -- regionComplete; +- (void) flipNormals; -extern float sb_floor_dir, sb_floor_dist; -- feetToFloor; +- (id) carve; +- (void) setCarveVars; + +extern id sb_newowner; + +- (void) moveToEntity; + +- (void) takeCurrentTexture; + +extern vec3_t select_min, select_max; + +- (void) selectPartial; +- (void) selectComplete; +- (void) regionPartial; +- (void) regionComplete; + +extern float sb_floor_dir, sb_floor_dist; + +- (void) feetToFloor; - (int) getNumBrushFaces; -- (face_t *)getBrushFace: (int)which; +- (face_t *) getBrushFace: (int)which; @end - +#endif // SetBrush_h diff --git a/tools/Forge/Bundles/MapEdit/SetBrush.m b/tools/Forge/Bundles/MapEdit/SetBrush.m index eed82f400..19519b103 100644 --- a/tools/Forge/Bundles/MapEdit/SetBrush.m +++ b/tools/Forge/Bundles/MapEdit/SetBrush.m @@ -1,61 +1,68 @@ -#include "qedefs.h" +#include "QF/script.h" +#include "QF/sys.h" + +#include "SetBrush.h" +#include "Entity.h" +#include "EntityClass.h" +#include "Map.h" +#include "Preferences.h" +#include "XYView.h" +#include "ZView.h" +#include "CameraView.h" +#include "Clipper.h" +#include "QuakeEd.h" @implementation SetBrush - /* ================== textureAxisFromPlane ================== */ #if 1 -vec3_t baseaxis[18] = -{ -{0,0,1}, {1,0,0}, {0,-1,0}, // floor -{0,0,-1}, {1,0,0}, {0,-1,0}, // ceiling -{1,0,0}, {0,1,0}, {0,0,-1}, // west wall -{-1,0,0}, {0,1,0}, {0,0,-1}, // east wall -{0,1,0}, {1,0,0}, {0,0,-1}, // south wall -{0,-1,0}, {1,0,0}, {0,0,-1} // north wall +vec3_t baseaxis[18] = { + { 0, 0, 1}, {1, 0, 0}, {0, -1, 0}, // floor + { 0, 0, -1}, {1, 0, 0}, {0, -1, 0}, // ceiling + { 1, 0, 0}, {0, 1, 0}, {0, 0, -1}, // west wall + {-1, 0, 0}, {0, 1, 0}, {0, 0, -1}, // east wall + { 0, 1, 0}, {1, 0, 0}, {0, 0, -1}, // south wall + { 0, -1, 0}, {1, 0, 0}, {0, 0, -1} // north wall }; #else -vec3_t baseaxis[18] = -{ -{0,0,1}, {1,0,0}, {0,-1,0}, // floor -{0,0,-1}, {1,0,0}, {0,1,0}, // ceiling -{1,0,0}, {0,1,0}, {0,0,-1}, // west wall -{-1,0,0}, {0,-1,0}, {0,0,-1}, // east wall -{0,1,0}, {-1,0,0}, {0,0,-1}, // south wall -{0,-1,0}, {1,0,0}, {0,0,-1} // north wall +vec3_t baseaxis[18] = { + { 0, 0, 1}, { 1, 0, 0}, {0, -1, 0}, // floor + { 0, 0, -1}, { 1, 0, 0}, {0, 1, 0}, // ceiling + { 1, 0, 0}, { 0, 1, 0}, {0, 0, -1}, // west wall + {-1, 0, 0}, { 0, -1, 0}, {0, 0, -1}, // east wall + { 0, 1, 0}, {-1, 0, 0}, {0, 0, -1}, // south wall + { 0, -1, 0}, { 1, 0, 0}, {0, 0, -1} // north wall }; #endif - -float TextureAxisFromPlane(plane_t *pln, float *xv, float *yv) +float +TextureAxisFromPlane (plane_t *pln, float *xv, float *yv) { - int bestaxis; - float dot,best; - int i; - + int bestaxis; + float dot, best; + int i; + best = 0; bestaxis = 0; - - for (i=0 ; i<6 ; i++) - { - dot = DotProduct (pln->normal, baseaxis[i*3]); - if (dot > best) - { + + for (i = 0; i < 6; i++) { + dot = DotProduct (pln->normal, baseaxis[i * 3]); + if (dot > best) { best = dot; bestaxis = i; } } - - VectorCopy (baseaxis[bestaxis*3+1], xv); - VectorCopy (baseaxis[bestaxis*3+2], yv); - - return lightaxis[bestaxis>>1]; + + VectorCopy (baseaxis[bestaxis * 3 + 1], xv); + VectorCopy (baseaxis[bestaxis * 3 + 2], yv); + + return lightaxis[bestaxis >> 1]; } -#define BOGUS_RANGE 18000 +#define BOGUS_RANGE 18000 /* ================= @@ -64,108 +71,106 @@ CheckFace Note: this will not catch 0 area polygons ================= */ -void CheckFace (face_t *f) +void +CheckFace (face_t * f) { - int i, j; - float *p1, *p2; - float d, edgedist; - vec3_t dir, edgenormal; - winding_t *w; - + int i, j; + float *p1, *p2; + float d, edgedist; + vec3_t dir, edgenormal; + winding_t *w; + w = f->w; if (!w) - Error ("CheckFace: no winding"); - + Sys_Error ("CheckFace: no winding"); + if (w->numpoints < 3) - Error ("CheckFace: %i points",w->numpoints); - - for (i=0 ; inumpoints ; i++) - { + Sys_Error ("CheckFace: %i points", w->numpoints); + + for (i = 0; i < w->numpoints; i++) { p1 = w->points[i]; - for (j=0 ; j<3 ; j++) + for (j = 0; j < 3; j++) { if (p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE) - Error ("CheckFace: BUGUS_RANGE: %f",p1[j]); + Sys_Error ("CheckFace: BUGUS_RANGE: %f", p1[j]); + } - j = i+1 == w->numpoints ? 0 : i+1; - - // check the point is on the face plane + j = i + 1 == w->numpoints ? 0 : i + 1; + + // check the point is on the face plane d = DotProduct (p1, f->plane.normal) - f->plane.dist; if (d < -ON_EPSILON || d > ON_EPSILON) - Error ("CheckFace: point off plane"); - - // check the edge isn't degenerate + Sys_Error ("CheckFace: point off plane"); + + // check the edge isn't degenerate p2 = w->points[j]; VectorSubtract (p2, p1, dir); - + if (VectorLength (dir) < ON_EPSILON) - Error ("CheckFace: degenerate edge"); - + Sys_Error ("CheckFace: degenerate edge"); + CrossProduct (f->plane.normal, dir, edgenormal); VectorNormalize (edgenormal); edgedist = DotProduct (p1, edgenormal); edgedist += ON_EPSILON; - - // all other points must be on front side - for (j=0 ; jnumpoints ; j++) - { + + // all other points must be on front side + for (j = 0; j < w->numpoints; j++) { if (j == i) continue; d = DotProduct (w->points[j], edgenormal); if (d > edgedist) - Error ("CheckFace: non-convex"); + Sys_Error ("CheckFace: non-convex"); } } } - /* ============================================================================= - TURN PLANES INTO GROUPS OF FACES + TURN PLANES INTO GROUPS OF FACES ============================================================================= */ - /* ================== NewWinding ================== */ -winding_t *NewWinding (int points) +winding_t * +NewWinding (int points) { - winding_t *w; - int size; - + winding_t *w; + size_t size; + if (points > MAX_POINTS_ON_WINDING) - Error ("NewWinding: %i points", points); - - size = (int)((winding_t *)0)->points[points]; + Sys_Error ("NewWinding: %i points", points); + + size = (size_t) ((winding_t *) 0)->points[points]; w = malloc (size); memset (w, 0, size); - + return w; } - /* ================== CopyWinding ================== */ -winding_t *CopyWinding (winding_t *w) +winding_t * +CopyWinding (winding_t * w) { - int size; - winding_t *c; - - size = (int)((winding_t *)0)->points[w->numpoints]; + size_t size; + winding_t *c; + + size = (size_t) ((winding_t *) 0)->points[w->numpoints]; c = malloc (size); memcpy (c, w, size); return c; } - /* ================== ClipWinding @@ -174,22 +179,22 @@ Clips the winding to the plane, returning the new winding on the positive side Frees the input winding. ================== */ -winding_t *ClipWinding (winding_t *in, plane_t *split) +winding_t * +ClipWinding (winding_t * in, plane_t *split) { - float dists[MAX_POINTS_ON_WINDING]; - int sides[MAX_POINTS_ON_WINDING]; - int counts[3]; - float dot; - int i, j; - float *p1, *p2, *mid; - winding_t *neww; - int maxpts; - + float dists[MAX_POINTS_ON_WINDING]; + int sides[MAX_POINTS_ON_WINDING]; + int counts[3]; + float dot; + int i, j; + float *p1, *p2, *mid; + winding_t *neww; + int maxpts; + counts[0] = counts[1] = counts[2] = 0; -// determine sides for each point - for (i=0 ; inumpoints ; i++) - { + // determine sides for each point + for (i = 0; i < in->numpoints; i++) { dot = DotProduct (in->points[i], split->normal); dot -= split->dist; dists[i] = dot; @@ -198,37 +203,31 @@ winding_t *ClipWinding (winding_t *in, plane_t *split) else if (dot < -ON_EPSILON) sides[i] = SIDE_BACK; else - { sides[i] = SIDE_ON; - } counts[sides[i]]++; } sides[i] = sides[0]; dists[i] = dists[0]; - + if (!counts[0] && !counts[1]) return in; - - if (!counts[0]) - { + if (!counts[0]) { free (in); return NULL; } if (!counts[1]) return in; - - maxpts = in->numpoints+4; // can't use counts[0]+2 because - // of fp grouping errors + + // can't use counts[0]+2 because of fp grouping errors + maxpts = in->numpoints + 4; neww = NewWinding (maxpts); - - for (i=0 ; inumpoints ; i++) - { + + for (i = 0; i < in->numpoints; i++) { p1 = in->points[i]; - + mid = neww->points[neww->numpoints]; - if (sides[i] == SIDE_FRONT || sides[i] == SIDE_ON) - { + if (sides[i] == SIDE_FRONT || sides[i] == SIDE_ON) { VectorCopy (p1, mid); mid[3] = p1[3]; mid[4] = p1[4]; @@ -237,37 +236,36 @@ winding_t *ClipWinding (winding_t *in, plane_t *split) continue; mid = neww->points[neww->numpoints]; } - - if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i]) + + if (sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i]) continue; - - // generate a split point + + // generate a split point if (i == in->numpoints - 1) p2 = in->points[0]; else p2 = p1 + 5; - + neww->numpoints++; - - dot = dists[i] / (dists[i]-dists[i+1]); - for (j=0 ; j<3 ; j++) - { // avoid round off error when possible + + dot = dists[i] / (dists[i] - dists[i + 1]); + for (j = 0; j < 3; j++) { // avoid round off error when possible if (split->normal[j] == 1) mid[j] = split->dist; else if (split->normal[j] == -1) mid[j] = -split->dist; - mid[j] = p1[j] + dot*(p2[j]-p1[j]); + mid[j] = p1[j] + dot * (p2[j] - p1[j]); } - mid[3] = p1[3] + dot*(p2[3]-p1[3]); - mid[4] = p1[4] + dot*(p2[4]-p1[4]); + mid[3] = p1[3] + dot * (p2[3] - p1[3]); + mid[4] = p1[4] + dot * (p2[4] - p1[4]); } if (neww->numpoints > maxpts) - Error ("ClipWinding: points exceeded estimate"); + Sys_Error ("ClipWinding: points exceeded estimate"); -// free the original winding + // free the original winding free (in); - + return neww; } @@ -278,102 +276,101 @@ BasePolyForPlane There has GOT to be a better way of doing this... ================= */ -winding_t *BasePolyForPlane (face_t *f) +winding_t * +BasePolyForPlane (face_t * f) { - int i, x; - float max, v; - vec3_t org, vright, vup; - vec3_t xaxis, yaxis; - winding_t *w; - texturedef_t *td; - plane_t *p; - float ang, sinv, cosv; - float s, t, ns, nt; + int i, x; + float max, v; + vec3_t org, vright, vup; + vec3_t xaxis, yaxis; + winding_t *w; + texturedef_t *td; + plane_t *p; + float ang, sinv, cosv; + float s, t, ns, nt; p = &f->plane; - -// find the major axis + // find the major axis max = -BOGUS_RANGE; x = -1; - for (i=0 ; i<3; i++) - { - v = fabs(p->normal[i]); - if (v > max) - { + for (i = 0; i < 3; i++) { + v = fabs (p->normal[i]); + if (v > max) { x = i; max = v; } } - if (x==-1) - Error ("BasePolyForPlane: no axis found"); - - VectorCopy (vec3_origin, vup); - switch (x) - { - case 0: - case 1: - vup[2] = 1; - break; - case 2: - vup[0] = 1; - break; + + if (x == -1) + Sys_Error ("BasePolyForPlane: no axis found"); + + VectorCopy (vec3_origin, vup); + switch (x) { + case 0: + case 1: + vup[2] = 1; + break; + + case 2: + vup[0] = 1; + break; } v = DotProduct (vup, p->normal); - VectorMA (vup, -v, p->normal, vup); + VectorMultAdd (vup, -v, p->normal, vup); VectorNormalize (vup); - + VectorScale (p->normal, p->dist, org); - + CrossProduct (vup, p->normal, vright); - + VectorScale (vup, 8192, vup); VectorScale (vright, 8192, vright); -// project a really big axis aligned box onto the plane + // project a really big axis-aligned box onto the plane w = NewWinding (4); w->numpoints = 4; - + VectorSubtract (org, vright, w->points[0]); VectorAdd (w->points[0], vup, w->points[0]); - + VectorAdd (org, vright, w->points[1]); VectorAdd (w->points[1], vup, w->points[1]); - + VectorAdd (org, vright, w->points[2]); VectorSubtract (w->points[2], vup, w->points[2]); - + VectorSubtract (org, vright, w->points[3]); VectorSubtract (w->points[3], vup, w->points[3]); - -// set texture values - f->light = TextureAxisFromPlane(&f->plane, xaxis, yaxis); + + // set texture values + f->light = TextureAxisFromPlane (&f->plane, xaxis, yaxis); td = &f->texture; - -// rotate axis + + // rotate axis ang = td->rotate / 180 * M_PI; - sinv = sin(ang); - cosv = cos(ang); - - if (!td->scale[0]) + sinv = sin (ang); + cosv = cos (ang); + + if (!(td->scale[0])) td->scale[0] = 1; - if (!td->scale[1]) + + if (!(td->scale[1])) td->scale[1] = 1; - for (i=0 ; i<4 ; i++) - { + for (i = 0; i < 4; i++) { s = DotProduct (w->points[i], xaxis); t = DotProduct (w->points[i], yaxis); ns = cosv * s - sinv * t; - nt = sinv * s + cosv * t; + nt = sinv * s + cosv * t; - w->points[i][3] = ns/td->scale[0] + td->shift[0]; - w->points[i][4] = nt/td->scale[1] + td->shift[1]; + w->points[i][3] = ns / td->scale[0] + td->shift[0]; + w->points[i][4] = nt / td->scale[1] + td->shift[1]; } - - return w; + + return w; } /* @@ -385,90 +382,79 @@ If a face has a NULL winding, it is an overconstraining plane and can be removed. =========== */ -- calcWindings +- (id) calcWindings { - int i,j, k; - float v; - face_t *f; - winding_t *w; - plane_t plane; - vec3_t t1, t2, t3; - BOOL useplane[MAX_FACES]; - + int i, j, k; + float v; + face_t *f; + winding_t *w; + plane_t plane; + vec3_t t1, t2, t3; + BOOL useplane[MAX_FACES]; + bmins[0] = bmins[1] = bmins[2] = 99999; bmaxs[0] = bmaxs[1] = bmaxs[2] = -99999; invalid = NO; - + [self freeWindings]; - - for (i=0 ; iplanepts[0][j] - f->planepts[1][j]; t2[j] = f->planepts[2][j] - f->planepts[1][j]; t3[j] = f->planepts[1][j]; } - - CrossProduct(t1,t2, f->plane.normal); - if (VectorCompare (f->plane.normal, vec3_origin)) - { + + CrossProduct (t1, t2, f->plane.normal); + if (VectorCompare (f->plane.normal, vec3_origin)) { useplane[i] = NO; break; } VectorNormalize (f->plane.normal); f->plane.dist = DotProduct (t3, f->plane.normal); - - // if the plane duplicates another plane, ignore it - // (assume it is a brush being edited that will be fixed) + + // if the plane duplicates another plane, ignore it + // (assume it is a brush being edited that will be fixed) useplane[i] = YES; - for (j=0 ; j< i ; j++) - { - if ( f->plane.normal[0] == faces[j].plane.normal[0] - && f->plane.normal[1] == faces[j].plane.normal[1] - && f->plane.normal[2] == faces[j].plane.normal[2] - && f->plane.dist == faces[j].plane.dist ) - { + for (j = 0; j < i; j++) { + if (f->plane.normal[0] == faces[j].plane.normal[0] + && f->plane.normal[1] == faces[j].plane.normal[1] + && f->plane.normal[2] == faces[j].plane.normal[2] + && f->plane.dist == faces[j].plane.dist) { useplane[i] = NO; break; } } - } - - for (i=0 ; iw = w; - if (w) - { + if (w) { CheckFace (f); - for (j=0 ; jnumpoints ; j++) - { - for (k=0 ; k<3 ; k++) - { + for (j = 0; j < w->numpoints; j++) { + for (k = 0; k < 3; k++) { v = w->points[j][k]; - if (fabs(v - rint(v)) < FP_EPSILON) - v = w->points[j][k] = rint(v); + if (fabs (v - rint (v)) < FP_EPSILON) + v = w->points[j][k] = rint (v); if (v < bmins[k]) bmins[k] = v; if (v > bmaxs[k]) @@ -476,91 +462,90 @@ can be removed. } } } - } + } - if (bmins[0] == 99999) - { + if (bmins[0] == 99999) { invalid = YES; VectorCopy (vec3_origin, bmins); VectorCopy (vec3_origin, bmaxs); return nil; } - + return self; } -//============================================================================ +// ============================================================================ /* =========== initOwner::: =========== */ -- initOwner: own mins:(float *)mins maxs:(float *)maxs texture:(texturedef_t *)tex +- (SetBrush *) initOwner: own + mins: (float *)mins + maxs: (float *)maxs + texture: (texturedef_t *)tex { - [super init]; + [super init]; parent = own; - + [self setTexturedef: tex]; [self setMins: mins maxs: maxs]; return self; } -- setMins:(float *)mins maxs:(float *)maxs +- (id) setMins: (float *) + mins maxs: (float *)maxs { - int i, j; - vec3_t pts[4][2]; - - for (i=0 ; i<3 ; i++) - { - if (maxs[i] - mins[i] <= 0) - { + int i, j; + vec3_t pts[4][2]; + + for (i = 0; i < 3; i++) { + if (maxs[i] - mins[i] <= 0) { VectorCopy (mins, bmins); VectorCopy (maxs, bmaxs); invalid = YES; numfaces = 0; return self; - } + } } - + pts[0][0][0] = mins[0]; pts[0][0][1] = mins[1]; - + pts[1][0][0] = mins[0]; pts[1][0][1] = maxs[1]; - + pts[2][0][0] = maxs[0]; pts[2][0][1] = maxs[1]; - + pts[3][0][0] = maxs[0]; pts[3][0][1] = mins[1]; - - for (i=0 ; i<4 ; i++) - { + + for (i = 0; i < 4; i++) { pts[i][0][2] = mins[2]; pts[i][1][0] = pts[i][0][0]; pts[i][1][1] = pts[i][0][1]; pts[i][1][2] = maxs[2]; } - + numfaces = 6; - for (i=0 ; i<4 ; i++) - { - j = (i+1)%4; + for (i = 0; i < 4; i++) { + j = (i + 1) % 4; faces[i].planepts[0][0] = pts[j][1][0]; faces[i].planepts[0][1] = pts[j][1][1]; faces[i].planepts[0][2] = pts[j][1][2]; - + faces[i].planepts[1][0] = pts[i][1][0]; faces[i].planepts[1][1] = pts[i][1][1]; faces[i].planepts[1][2] = pts[i][1][2]; - + faces[i].planepts[2][0] = pts[i][0][0]; faces[i].planepts[2][1] = pts[i][0][1]; faces[i].planepts[2][2] = pts[i][0][2]; } - + faces[4].planepts[0][0] = pts[0][1][0]; faces[4].planepts[0][1] = pts[0][1][1]; faces[4].planepts[0][2] = pts[0][1][2]; @@ -572,7 +557,6 @@ initOwner::: faces[4].planepts[2][0] = pts[2][1][0]; faces[4].planepts[2][1] = pts[2][1][1]; faces[4].planepts[2][2] = pts[2][1][2]; - faces[5].planepts[0][0] = pts[2][0][0]; faces[5].planepts[0][1] = pts[2][0][1]; @@ -585,59 +569,66 @@ initOwner::: faces[5].planepts[2][0] = pts[0][0][0]; faces[5].planepts[2][1] = pts[0][0][1]; faces[5].planepts[2][2] = pts[0][0][2]; - [self calcWindings]; return self; } -- parent +- (id) parent { return parent; } -- setParent: (id)p +- (id) setParent: (id)p { parent = p; return self; } -- setEntityColor: (vec3_t)color +- (id) setEntityColor: (vec3_t)color { VectorCopy (color, entitycolor); return self; } -- freeWindings +- (void) freeWindings { - int i; - - for (i=0 ; iregioned = regioned; + new->selected = selected; + new->invalid = invalid; + new->parent = parent; + VectorCopy (bmins, new->bmins); + VectorCopy (bmaxs, new->bmaxs); + VectorCopy (entitycolor, new->entitycolor); + new->numfaces = numfaces; + memcpy (new->faces, faces, sizeof (new->faces)); + [self calcWindings]; [new calcWindings]; - return new; } -- free +- (void) dealloc { [self freeWindings]; - return [super free]; + return [super dealloc]; } /* @@ -645,89 +636,141 @@ initOwner::: initOwner: fromTokens =========== */ -int numsb; -- initFromTokens: own +int numsb; + +static vec3_t * +ParseVerts (script_t *script, int *n_verts) { - face_t *f; - int i,j; + vec3_t *verts; + int i; + + if (strcmp (Script_Token (script), ":")) + Sys_Error ("parsing map file"); + Script_GetToken (script, false); + *n_verts = atoi (Script_Token (script)); + verts = malloc (sizeof (vec3_t) * *n_verts); + + for (i = 0; i < *n_verts; i++) { + Script_GetToken (script, true); + verts[i][0] = atof (Script_Token (script)); + Script_GetToken (script, true); + verts[i][1] = atof (Script_Token (script)); + Script_GetToken (script, true); + verts[i][2] = atof (Script_Token (script)); + } + return verts; +} + +- (id) initFromScript: (script_t *)script owner: own +{ + face_t *f; + vec3_t *verts = 0; + int n_verts = 0; + int i, j; [self init]; - + parent = own; - + f = faces; numfaces = 0; - do - { - if (!GetToken (true)) + + if (!Script_GetToken (script, true)) + return self; + + if (strcmp (Script_Token (script), "(")) { + verts = ParseVerts (script, &n_verts); + } else { + Script_UngetToken (script); + } + + do { + if (!Script_GetToken (script, true)) break; - if (!strcmp (token, "}") ) + if (!strcmp (Script_Token (script), "}")) break; - - for (i=0 ; i<3 ; i++) - { - if (i != 0) - GetToken (true); - if (strcmp (token, "(") ) - Error ("parsing map file"); - - for (j=0 ; j<3 ; j++) - { - GetToken (false); - f->planepts[i][j] = atoi(token); + + if (verts) { + int n_v, v; + n_v = atoi (Script_Token (script)); + Script_GetToken (script, false); + for (i = 0; i < n_v; i++) { + Script_GetToken (script, false); + v = atoi (Script_Token (script)); + if (i < 3) + VectorCopy (verts[v], f->planepts[i]); + } + printf ("\n"); + Script_GetToken (script, false); + } else { + for (i = 0; i < 3; i++) { + if (i != 0) + Script_GetToken (script, true); + if (strcmp (Script_Token (script), "(")) + Sys_Error ("parsing map file"); + + for (j = 0; j < 3; j++) { + Script_GetToken (script, false); + f->planepts[i][j] = atoi (Script_Token (script)); + } + Script_GetToken (script, false); + + if (strcmp (Script_Token (script), ")")) + Sys_Error ("parsing map file"); } - - GetToken (false); - if (strcmp (token, ")") ) - Error ("parsing map file"); } - GetToken (false); - strcpy (f->texture.texture, token); - GetToken (false); - f->texture.shift[0] = atof(token); - GetToken (false); - f->texture.shift[1] = atof(token); - GetToken (false); - f->texture.rotate = atof(token); - GetToken (false); - f->texture.scale[0] = atof(token); - GetToken (false); - f->texture.scale[1] = atof(token); - + Script_GetToken (script, false); + strcpy (f->texture.texture, Script_Token (script)); + Script_GetToken (script, false); + f->texture.shift[0] = atof (Script_Token (script)); + Script_GetToken (script, false); + f->texture.shift[1] = atof (Script_Token (script)); + Script_GetToken (script, false); + f->texture.rotate = atof (Script_Token (script)); + Script_GetToken (script, false); + f->texture.scale[0] = atof (Script_Token (script)); + Script_GetToken (script, false); + f->texture.scale[1] = atof (Script_Token (script)); + + while (Script_TokenAvailable (script, false)) { + Script_GetToken (script, false); + if (!strcmp (Script_Token (script), "detail")) + ; // XXX implement + else + Sys_Error ("parsing map file"); + } + #if 0 - flags = atoi(token); - + flags = atoi (Script_Token (script)); + flags &= 7; f->texture.rotate = 0; f->texture.scale[0] = 1; f->texture.scale[1] = 1; -#define TEX_FLIPAXIS 1 -#define TEX_FLIPS 2 -#define TEX_FLIPT 4 +# define TEX_FLIPAXIS 1 +# define TEX_FLIPS 2 +# define TEX_FLIPT 4 - if (flags & TEX_FLIPAXIS) - { + if (flags & TEX_FLIPAXIS) { f->texture.rotate = 90; - if ( !(flags & TEX_FLIPT) ) + if (!(flags & TEX_FLIPT)) f->texture.scale[0] = -1; if (flags & TEX_FLIPS) f->texture.scale[1] = -1; - } - else - { + } else { if (flags & TEX_FLIPS) f->texture.scale[0] = -1; if (flags & TEX_FLIPT) f->texture.scale[1] = -1; - } -#endif + } +#endif /* if 0 */ f++; numfaces++; } while (1); - + numsb++; [self calcWindings]; @@ -740,32 +783,32 @@ int numsb; writeToFILE =========== */ -- writeToFILE: (FILE *)f region: (BOOL)reg +- (void) writeToFILE: (FILE *)f + region: (BOOL)reg { - int i,j; - face_t *fa; - texturedef_t *td; - + int i, j; + face_t *fa; + texturedef_t *td; if (reg && regioned) - return self; - + return; fprintf (f, "{\n"); - for (i=0 ; iplanepts[j][0], (int)fa->planepts[j][1], (int)fa->planepts[j][2]); + for (j = 0; j < 3; j++) { + fprintf (f, "( %d %d %d ) ", (int) fa->planepts[j][0], + (int) fa->planepts[j][1], (int) fa->planepts[j][2]); + } td = &fa->texture; - fprintf (f,"%s %d %d %d %f %f\n", td->texture, (int)td->shift[0], (int)td->shift[1], (int)td->rotate, td->scale[0], td->scale[1]); + fprintf (f, "%s %d %d %d %f %f\n", td->texture, (int) td->shift[0], + (int) td->shift[1], (int) td->rotate, td->scale[0], + td->scale[1]); } fprintf (f, "}\n"); - - return self; + + return; } - - /* ============================================================================== @@ -774,66 +817,59 @@ INTERACTION ============================================================================== */ -- getMins: (vec3_t)mins maxs: (vec3_t)maxs +- (void) getMins: (vec3_t)mins + maxs: (vec3_t)maxs { VectorCopy (bmins, mins); VectorCopy (bmaxs, maxs); - return self; } - -- (BOOL)selected +- (BOOL) selected { return selected; } -- setSelected: (BOOL)s +- (void) setSelected: (BOOL)s { selected = s; - return self; } -- (BOOL)regioned +- (BOOL) regioned { return regioned; } -- setRegioned: (BOOL)s +- (void) setRegioned: (BOOL)s { regioned = s; - return self; } - /* =========== setTexturedef =========== */ -- setTexturedef: (texturedef_t *)tex +- (void) setTexturedef: (texturedef_t *)tex { - int i; - - for (i=0 ; i numfaces) - Error ("setTexturedef:forFace: bad face number %i",f); - + if (f > numfaces) + Sys_Error ("setTexturedef:forFace: bad face number %i", f); faces[f].texture = *tex; - faces[f].qtexture = NULL; // recache next render + faces[f].qtexture = NULL; // recache next render - [self calcWindings]; // in case texture coords changed - return self; + [self calcWindings]; // in case texture coords changed } /* @@ -841,17 +877,16 @@ setTexturedef texturedef =========== */ -- (texturedef_t *)texturedef +- (texturedef_t *) texturedef { return &faces[0].texture; } -- (texturedef_t *)texturedefForFace: (int)f +- (texturedef_t *) texturedefForFace: (int)f { return &faces[f].texture; } - /* =========== removeIfInvalid @@ -859,24 +894,23 @@ removeIfInvalid So created veneers don't stay around =========== */ -- removeIfInvalid +- (id) removeIfInvalid { - int i, j; - - for (i=0 ; i= faces[i].plane.dist) return NO; - return YES; + } + return YES; } /* =========== -clipRay +clipRay:::::: =========== */ -- clipRay: (vec3_t)p1 : (vec3_t) p2 - :(vec3_t)frontpoint : (int *)f_face - :(vec3_t)backpoint : (int *)b_face +- (id) clipRay: (vec3_t)p1 + : (vec3_t)p2 + : (vec3_t)frontpoint + : (int *)f_face + : (vec3_t)backpoint + : (int *)b_face { - int frontface, backface; - int i, j; - face_t *f; - float d1, d2, m; - float *start; - + int frontface, backface; + int i, j; + face_t *f; + float d1, d2, m; + float *start; + start = p1; frontface = -2; backface = -2; - + f = faces; - for (i=0 ; iw) - continue; // clipped off plane + continue; // clipped off plane d1 = DotProduct (p1, f->plane.normal) - f->plane.dist; d2 = DotProduct (p2, f->plane.normal) - f->plane.dist; - if (d1 >= 0 && d2 >= 0) - { // the entire ray is in front of the polytope + if (d1 >= 0 && d2 >= 0) { // the whole ray is in front of the polytope *f_face = -1; *b_face = -1; return self; } - if (d1 > 0 && d2 < 0) - { // new front plane + if (d1 > 0 && d2 < 0) { // new front plane frontface = i; - m = d1 / (d1-d2); - for (j=0 ; j<3 ; j++) - frontpoint[j] = p1[j] + m*(p2[j]-p1[j]); + m = d1 / (d1 - d2); + for (j = 0; j < 3; j++) + frontpoint[j] = p1[j] + m * (p2[j] - p1[j]); + p1 = frontpoint; } - if (d1 < 0 && d2 > 0) - { // new back plane + if (d1 < 0 && d2 > 0) { // new back plane backface = i; - m = d1 / (d1-d2); - for (j=0 ; j<3 ; j++) - backpoint[j] = p1[j] + m*(p2[j]-p1[j]); + m = d1 / (d1 - d2); + for (j = 0; j < 3; j++) + backpoint[j] = p1[j] + m * (p2[j] - p1[j]); + p2 = backpoint; } } - + *f_face = frontface; *b_face = backface; - + return self; } - /* =========== -hitByRay +hitByRay:::: =========== */ -- hitByRay: (vec3_t)p1 : (vec3_t) p2 : (float *)time : (int *)face +- (void) hitByRay: (vec3_t)p1 + : (vec3_t)p2 + : (float *)time + : (int *)face { - vec3_t frontpoint, backpoint, dir; - int frontface, backface; - - if (regioned) - { + vec3_t frontpoint, backpoint, dir; + int frontface, backface; + + if (regioned) { *time = -1; *face = -1; - return self; + return; } - - [self clipRay: p1 : p2 : frontpoint: &frontface : backpoint : &backface]; - - if (frontface == -2 && backface == -2) - { // entire ray is inside the brush, select first face + + [self clipRay: p1 : p2 : frontpoint : &frontface : backpoint : &backface]; + + if (frontface == -2 && backface == -2) { + // entire ray is inside the brush, select first face *time = 0; *face = 0; - return self; + return; } - - - if (frontface < 0) - { // ray started inside the polytope, don't select it + + if (frontface < 0) { // ray started inside the polytope, don't select it *time = -1; *face = -1; - return self; + return; } - + VectorSubtract (p2, p1, dir); VectorNormalize (dir); VectorSubtract (frontpoint, p1, frontpoint); *time = DotProduct (frontpoint, dir); if (*time < 0) - Error ("hitByRay: negative t"); + Sys_Error ("hitByRay: negative t"); *face = frontface; - - return self; } - /* ============================================================================== @@ -1016,58 +1048,56 @@ DRAWING ROUTINES ============================================================================== */ -BOOL fakebrush; +BOOL fakebrush; -- drawConnections +- (id) drawConnections { - id obj; - int c, i; - vec3_t dest, origin; - vec3_t mid; - vec3_t forward, right; - char *targname; - vec3_t min, max, temp; - char targ[64]; - - strcpy (targ, [parent valueForQKey: "target"]); + id obj; + int c, i; + vec3_t dest, origin; + vec3_t mid; + vec3_t forward, right; + const char *targname; + vec3_t min, max, temp; + const char *targ; + + targ = [parent valueForQKey: "target"]; if (!targ || !targ[0]) return self; - - origin[0] = (bmins[0] + bmaxs[0]) /2; - origin[1] = (bmins[1] + bmaxs[1]) /2; - + + origin[0] = (bmins[0] + bmaxs[0]) / 2; + origin[1] = (bmins[1] + bmaxs[1]) / 2; + c = [map_i count]; - for (i=0 ; i xy_draw_rect.origin.x + xy_draw_rect.size.width - || bmins[1] > xy_draw_rect.origin.y + xy_draw_rect.size.height) ) - return self; // off view, don't bother + (bmaxs[0] < xy_draw_rect.origin.x + || bmaxs[1] < xy_draw_rect.origin.y + || bmins[0] > xy_draw_rect.origin.x + xy_draw_rect.size.width + || bmins[1] > xy_draw_rect.origin.y + xy_draw_rect.size.height)) + return; // off view, don't bother - for (i=0 ; i -VECTOR_EPSILON) + if (DotProduct (faces[i].plane.normal, xy_viewnormal) > -VECTOR_EPSILON) continue; - - XYmoveto (w->points[w->numpoints-1]); - for (j=0 ; jnumpoints ; j++) + + XYmoveto (w->points[w->numpoints - 1]); + for (j = 0; j < w->numpoints; j++) XYlineto (w->points[j]); } - - if (keybrush) - { -// angle arrow - val = [parent valueForQKey: "angle"]; - if (val && val[0]) - { - ang = atof(val) * M_PI / 180; - if (ang > 0) // negative values are up/down flags - { - mid[0] = (bmins[0]+bmaxs[0])/2; - mid[1] = (bmins[1]+bmaxs[1])/2; - - end[0] = mid[0] + 16*cos(ang); - end[1] = mid[1] + 16*sin(ang); - - s1[0] = mid[0] + 12*cos(ang+0.4); - s1[1] = mid[1] + 12*sin(ang+0.4); - - s2[0] = mid[0] + 12*cos(ang-0.4); - s2[1] = mid[1] + 12*sin(ang-0.4); - - XYmoveto ( mid); - XYlineto ( end ); - XYmoveto ( s1); - XYlineto ( end ); - XYlineto ( s2 ); + + if (keybrush) { + val = [parent valueForQKey: "angle"]; // angle arrow + if (val && val[0]) { + ang = atof (val) * M_PI / 180; + if (ang > 0) { // negative values are up/down flags + mid[0] = (bmins[0] + bmaxs[0]) / 2; + mid[1] = (bmins[1] + bmaxs[1]) / 2; + + end[0] = mid[0] + 16 * cos (ang); + end[1] = mid[1] + 16 * sin (ang); + + s1[0] = mid[0] + 12 * cos (ang + 0.4); + s1[1] = mid[1] + 12 * sin (ang + 0.4); + + s2[0] = mid[0] + 12 * cos (ang - 0.4); + s2[1] = mid[1] + 12 * sin (ang - 0.4); + + XYmoveto (mid); + XYlineto (end); + XYmoveto (s1); + XYlineto (end); + XYlineto (s2); } } } - - return self; + + return; } /* @@ -1203,70 +1226,57 @@ XYDrawSelf ZDrawSelf =========== */ -- ZDrawSelf +- (void) ZDrawSelf { - int i; - vec3_t p1, p2; - vec3_t frontpoint, backpoint; - int frontface, backface; - qtexture_t *q; - - if ([self fakeBrush: @selector(ZDrawSelf)]) - return self; + int i; + NSPoint p; + vec3_t p1, p2; + vec3_t frontpoint, backpoint; + int frontface, backface; + qtexture_t *q; + + if ([self fakeBrush: @selector (ZDrawSelf)]) + return; [zview_i addToHeightRange: bmins[2]]; [zview_i addToHeightRange: bmaxs[2]]; - - if (selected) - { - PSmoveto (1, bmaxs[2]); - PSlineto (23, bmaxs[2]); - PSlineto (23, bmins[2]); - PSlineto (1, bmins[2]); - PSlineto (1, bmaxs[2]); - PSsetrgbcolor (1,0,0); - PSstroke (); + + if (selected) { + [[NSColor redColor] set]; + NSFrameRect (NSMakeRect (1, bmins[2], 24, bmaxs[2] - bmins[2])); } - [zview_i getPoint: (NSPoint *)p1]; - - for (i=0 ; i<2 ; i++) + [zview_i getPoint: &p]; + p1[0] = p.x; + p1[1] = p.y; + for (i = 0; i < 2; i++) { if (bmins[i] >= p1[i] || bmaxs[i] <= p1[i]) - return self; - + return; + } + p1[2] = 4096; p2[0] = p1[0]; p2[1] = p1[1]; p2[2] = -4096; - [self clipRay: p1 : p2 : frontpoint: &frontface : backpoint : &backface]; + [self clipRay: p1 : p2 : frontpoint : &frontface : backpoint : &backface]; if (frontface == -1 || backface == -1) - return self; - - q = TEX_ForName (faces[frontface].texture.texture); - - PSmoveto (-8, frontpoint[2]); - PSlineto (8, frontpoint[2]); - PSlineto (8, backpoint[2]); - PSlineto (-8, backpoint[2]); - PSlineto (-8, frontpoint[2]); - - PSsetrgbcolor (q->flatcolor.chan[0]/255.0 - , q->flatcolor.chan[1]/255.0 - , q->flatcolor.chan[2]/255.0); - PSfill (); + return; - PSmoveto (-12, frontpoint[2]); - PSlineto (12, frontpoint[2]); - PSlineto (12, backpoint[2]); - PSlineto (-12, backpoint[2]); - PSlineto (-12, frontpoint[2]); - - PSsetrgbcolor (0,0,0); - PSstroke (); - - return self; + q = TEX_ForName (faces[frontface].texture.texture); + + [[NSColor colorWithCalibratedRed: q->flatcolor.chan[0] / 255.0 + green: q->flatcolor.chan[1] / 255.0 + blue: q->flatcolor.chan[2] / 255.0 + alpha: 1.0] set]; + NSRectFill (NSMakeRect (-8, backpoint[2], + 17, frontpoint[2] - backpoint[2] + 1)); + [[NSColor blackColor] set]; + NSFrameRect (NSMakeRect (-12, backpoint[2], + 25, frontpoint[2] - backpoint[2] + 1)); + + return; } /* @@ -1274,56 +1284,54 @@ ZDrawSelf CameraDrawSelf =========== */ -- CameraDrawSelf +- (void) CameraDrawSelf { - int i, j; - winding_t *w; - id worldent, currentent; - - if ([self fakeBrush: @selector(CameraDrawSelf)]) - return self; - - worldent = [map_i objectAt: 0]; + int i, j; + winding_t *w; + id worldent, currentent; + + if ([self fakeBrush: @selector (CameraDrawSelf)]) + return; + + worldent = [map_i objectAtIndex: 0]; currentent = [map_i currentEntity]; if (parent != worldent && worldent == currentent) linecolor (entitycolor[0], entitycolor[1], entitycolor[2]); else if (selected) - linecolor (1,0,0); + linecolor (1, 0, 0); else if (parent == [map_i currentEntity]) - linecolor (0,0,0); + linecolor (0, 0, 0); else - linecolor (0,0.5,0); + linecolor (0, 0.5, 0); - for (i=0 ; ipoints[w->numpoints-1]); - for (j=0 ; jnumpoints ; j++) + CameraMoveto (w->points[w->numpoints - 1]); + for (j = 0; j < w->numpoints; j++) CameraLineto (w->points[j]); } - return self; + return; } - /* =========== XYRenderSelf =========== */ -- XYRenderSelf +- (void) XYRenderSelf { - int i; - - if ([self fakeBrush: @selector(XYRenderSelf)]) - return self; - - for (i=0 ; iw; if (!w) continue; - if (dragplane[i] && numdragplanes == 1) - { - for (j=0 ; j<3 ; j++) - { + + if (dragplane[i] && numdragplanes == 1) { + for (j = 0; j < 3; j++) { controlpoints[numcontrolpoints] = faces[i].planepts[j]; numcontrolpoints++; } continue; } + if (!dragplane[i] && numdragplanes > 1) continue; - + facectl = 0; - for (j=0 ; jnumpoints ; j++) - { + for (j = 0; j < w->numpoints; j++) { onplane[j] = NO; - for (k=0 ; kpoints[j], faces[k].plane.normal) - - faces[k].plane.dist; - if (fabs(d) > ON_EPSILON) + - faces[k].plane.dist; + if (fabs (d) > ON_EPSILON) continue; onplane[j] = YES; facectl++; - break; + break; } } + if (facectl == 0) continue; - - // find one or two static points to go with the controlpoints - // and change the plane points + + // find one or two static points to go with the controlpoints + // and change the plane points k = 0; - for (j=0 ; jnumpoints ; j++) - { + for (j = 0; j < w->numpoints; j++) { if (!onplane[j]) continue; - if (facectl >= 2 && !onplane[(j+1)%w->numpoints]) + if (facectl >= 2 && !onplane[(j + 1) % w->numpoints]) continue; - if (facectl == 3 && !onplane[(j+2)%w->numpoints]) + if (facectl == 3 && !onplane[(j + 2) % w->numpoints]) continue; - VectorCopy (w->points[j], f->planepts[k]); controlpoints[numcontrolpoints] = f->planepts[k]; numcontrolpoints++; k++; - if (facectl >= 2) - { - VectorCopy (w->points[(j+1)%w->numpoints], f->planepts[k]); + if (facectl >= 2) { + VectorCopy (w->points[(j + 1) % w->numpoints], f->planepts[k]); controlpoints[numcontrolpoints] = f->planepts[k]; numcontrolpoints++; k++; } - if (facectl == 3) - { - VectorCopy (w->points[(j+2)%w->numpoints], f->planepts[k]); + if (facectl == 3) { + VectorCopy (w->points[(j + 2) % w->numpoints], f->planepts[k]); controlpoints[numcontrolpoints] = f->planepts[k]; numcontrolpoints++; k++; } break; } - - for ( ; jnumpoints && k != 3 ; j++) - if (!onplane[j]) - { + + for ( ; j < w->numpoints && k != 3; j++) { + if (!onplane[j]) { VectorCopy (w->points[j], f->planepts[k]); k++; } - - for (j=0 ; jnumpoints && k != 3 ; j++) - if (!onplane[j]) - { - VectorCopy (w->points[j], f->planepts[k]); - k++; - } - - if (k != 3) - { -// Error ("getXYShearPoints: didn't get three points on plane"); - numcontrolpoints = 0; - return self; } - - for (j=0 ; j<3 ; j++) - for (k=0 ; k<3 ; k++) - f->planepts[j][k] = rint(f->planepts[j][k]); + + for (j = 0; j < w->numpoints && k != 3; j++) { + if (!onplane[j]) { + VectorCopy (w->points[j], f->planepts[k]); + k++; + } + } + + if (k != 3) { +// Sys_Error ("getXYShearPoints: didn't get three points on plane"); + numcontrolpoints = 0; + return; + } + + for (j = 0; j < 3; j++) { + for (k = 0; k < 3; k++) + f->planepts[j][k] = rint (f->planepts[j][k]); + } } - - return self; } /* @@ -1608,7 +1596,7 @@ MULTIPLE BRUSH ACTIONS ============================================================================== */ -vec3_t region_min, region_max; +vec3_t region_min, region_max; /* =========== @@ -1617,222 +1605,201 @@ newRegion Set the regioned flag based on if the object is containted in region_min/max =========== */ -- newRegion +- (id) newRegion { - int i; - char *name; - -// filter away entities - if (parent != [map_i objectAt: 0]) - { - if (filter_entities) - { + int i; + const char *name; + + // filter away entities + if (parent != [map_i objectAtIndex: 0]) { + if (filter_entities) { regioned = YES; return self; } - + name = [parent valueForQKey: "classname"]; - - if ( (filter_light && !strncmp(name,"light",5) ) - || (filter_path && !strncmp(name,"path",4) ) ) - { + + if ((filter_light && !strncmp (name, "light", 5)) + || (filter_path && !strncmp (name, "path", 4))) { regioned = YES; return self; } - } - else if (filter_world) - { + } else if (filter_world) { regioned = YES; return self; } - - if (filter_clip_brushes && !strcasecmp(faces[0].texture.texture, "clip")) - { + + if (filter_clip_brushes && !strcasecmp (faces[0].texture.texture, "clip")) { regioned = YES; return self; } - - if (filter_water_brushes && faces[0].texture.texture[0] == '*') - { + + if (filter_water_brushes && faces[0].texture.texture[0] == '*') { regioned = YES; return self; } - - for (i=0 ; i<3 ; i++) - { - if (region_min[i] >= bmaxs[i] || region_max[i] <= bmins[i]) - { + + for (i = 0; i < 3; i++) { + if (region_min[i] >= bmaxs[i] || region_max[i] <= bmins[i]) { if (selected) [self deselect]; regioned = YES; return self; } } - + regioned = NO; return self; } -vec3_t select_min, select_max; -- selectPartial +vec3_t select_min, select_max; + +- (void) selectPartial { - int i; - for (i=0 ; i<3 ; i++) + int i; + + for (i = 0; i < 3; i++) { if (select_min[i] >= bmaxs[i] || select_max[i] <= bmins[i]) - return self; + return; + } selected = YES; - return self; } -- selectComplete +- (void) selectComplete { - int i; - for (i=0 ; i<3 ; i++) + int i; + + for (i = 0; i < 3; i++) { if (select_min[i] > bmins[i] || select_max[i] < bmaxs[i]) - return self; + return; + } selected = YES; - return self; } - -- regionPartial +- (void) regionPartial { - int i; - for (i=0 ; i<3 ; i++) + int i; + + for (i = 0; i < 3; i++) { if (select_min[i] >= bmaxs[i] || select_max[i] <= bmins[i]) - return self; + return; + } selected = YES; - return self; } -- regionComplete +- (void) regionComplete { - int i; - for (i=0 ; i<3 ; i++) + int i; + + for (i = 0; i < 3; i++) { if (select_min[i] > bmins[i] || select_max[i] < bmaxs[i]) - return self; + return; + } selected = YES; - return self; } +id sb_newowner; -id sb_newowner; -- moveToEntity +- (void) moveToEntity { - id eclass; - float *c; - + id eclass; + float *c; + [parent removeObject: self]; parent = sb_newowner; - -// hack to allow them to be copied to another map - if ( [parent respondsTo:@selector(valueForQKey:)]) - { + + // hack to allow them to be copied to another map + if ([parent respondsToSelector: @selector (valueForQKey:)]) { eclass = [entity_classes_i classForName: [parent valueForQKey: "classname"]]; c = [eclass drawColor]; [self setEntityColor: c]; } - + [parent addObject: self]; - return self; } -vec3_t sb_translate; +vec3_t sb_translate; -- translate +- (void) translate { - int i, j; - -// move the planes - for (i=0; i sb_maxs[k]) sb_maxs[k] = bmaxs[k]; } - - return self; } -- flushTextures -{ // call when texture palette changes - int i; - - for (i=0 ; i 0 && dist < sb_floor_dist) - sb_floor_dist = dist; - } - else - { - if (dist < 0 && dist > sb_floor_dist) - sb_floor_dist = dist; - } - return self; -} + if (sb_floor_dir == 1) { + if (dist > 0 && dist < sb_floor_dist) + sb_floor_dist = dist; + else if (dist < 0 && dist > sb_floor_dist) + sb_floor_dist = dist; + } +} /* =============================================================================== @@ -1930,78 +1884,76 @@ BRUSH SUBTRACTION =============================================================================== */ -vec3_t carvemin, carvemax; -int numcarvefaces; -face_t *carvefaces; -id carve_in, carve_out; +vec3_t carvemin, carvemax; +int numcarvefaces; +face_t *carvefaces; +id carve_in, carve_out; // returns the new brush formed after the addition of the given plane // nil is returned if it faced all of the original setbrush -- addFace: (face_t *)f +- (id) addFace: (face_t *)f { if (numfaces == MAX_FACES) - Error ("addFace: numfaces == MAX_FACES"); - + Sys_Error ("addFace: numfaces == MAX_FACES"); faces[numfaces] = *f; faces[numfaces].texture = faces[0].texture; faces[numfaces].qtexture = NULL; faces[numfaces].w = NULL; numfaces++; [self calcWindings]; - -// remove any degenerate faces + + // remove any degenerate faces return [self removeIfInvalid]; } -- clipByFace: (face_t *)fa front:(id *)f back:(id *)b +- (void) clipByFace: (face_t *)fa + front: (id *)f + back: (id *)b { - id front, back; - face_t fb; - vec3_t temp; - + id front, back; + face_t fb; + vec3_t temp; + fb = *fa; VectorCopy (fb.planepts[0], temp); VectorCopy (fb.planepts[2], fb.planepts[0]); VectorCopy (temp, fb.planepts[2]); - + front = [self copy]; back = [self copy]; *b = [back addFace: fa]; *f = [front addFace: &fb]; - - return self; } -- carve +- (id) carve { - int i; - id front, back; - + int i; + id front, back; + #if 0 - if ( (i = NSMallocCheck()) ) - Error ("MallocCheck failure"); + if ((i = NSMallocCheck ())) + Sys_Error ("MallocCheck failure"); #endif - -// check bboxes - for (i=0 ; i<3 ; i++) - if (bmins[i] >= carvemax[i] || bmaxs[i] <= carvemin[i]) - { + + // check bboxes + for (i = 0; i < 3; i++) { + if (bmins[i] >= carvemax[i] || bmaxs[i] <= carvemin[i]) { [carve_out addObject: self]; return self; } + } -// carve by the planes + // carve by the planes back = self; - for (i=0 ; i + Dept. of Mathematics and Computer Science, Aalborg U., Denmark + + This file is part of the Gnustep Base Library. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +/****************************************************************** + TODO: + Does not implement methods for archiving itself. +******************************************************************/ + +#ifndef __Storage_h_INCLUDE_GNU +#define __Storage_h_INCLUDE_GNU + +#include + +@interface Storage: NSObject +{ + @public + void *dataPtr; /* data of the Storage object */ + const char *description; /* Element description */ + NSUInteger numElements; /* Actual number of elements */ + NSUInteger maxElements; /* Total allocated elements */ + NSUInteger elementSize; /* Element size */ +} + +/* Creating, freeing, initializing, and emptying */ + +- (id) init; +- (id) initCount: (NSUInteger)numSlots + elementSize: (NSUInteger)sizeInBytes + description: (const char *)elemDesc; +- (void) dealloc; +- (id) empty; +- (id) copy; + +/* Manipulating the elements */ + +- (BOOL) isEqual: anObject; +- (const char *) description; +- (NSUInteger) count; +- (void *) elementAt: (NSUInteger)index; +- (id) replaceElementAt: (NSUInteger)index + with: (void *)anElement; + +- (id) setNumSlots: (NSUInteger)numSlots; +- (id) setAvailableCapacity: (NSUInteger)numSlots; +- (id) addElement: (void *)anElement; +- (id) removeLastElement; +- (id) insertElement: (void *)anElement + at: (NSUInteger)index; + +- (id) removeElementAt: (NSUInteger)index; + +/* old-style creation */ + ++ (id) new; ++ (id) newCount: (NSUInteger)count + elementSize: (NSUInteger)sizeInBytes + description: (const char *)descriptor; + +@end + +typedef struct { + @defs (Storage) +} NXStorageId; + +#endif /* __Storage_h_INCLUDE_GNU */ diff --git a/tools/Forge/Bundles/MapEdit/Storage.m b/tools/Forge/Bundles/MapEdit/Storage.m new file mode 100644 index 000000000..1a4c4cd29 --- /dev/null +++ b/tools/Forge/Bundles/MapEdit/Storage.m @@ -0,0 +1,253 @@ +/* Implementation of Objective C NeXT-compatible Storage object + Copyright (C) 1993,1994, 1996 Free Software Foundation, Inc. + + Written by: Kresten Krab Thorup + Dept. of Mathematics and Computer Science, Aalborg U., Denmark + + This file is part of the GNUstep Base Library. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +/* #include */ +#include "Storage.h" +#include +#include + +#define GNU_STORAGE_NTH(x, N) \ + ({GNUStorageId* __s = (GNUStorageId*) (x); \ + (void*) (((char*) __s->dataPtr) + (__s->elementSize * (N))); }) +#define STORAGE_NTH(N) GNU_STORAGE_NTH (self, N) + +typedef struct { + @defs (Storage) +} GNUStorageId; + +@implementation Storage + ++ (id) initialize +{ + if (self == [Storage class]) + [self setVersion: 0]; /* beta release */ + return self; +} + +// INITIALIZING, FREEING; + +- (id) initCount: (NSUInteger)numSlots elementSize: (NSUInteger)sizeInBytes + description: (const char *) + elemDesc; +{ + [super init]; + numElements = numSlots; + maxElements = (numSlots > 0) ? numSlots : 1; + elementSize = sizeInBytes; + description = elemDesc; + dataPtr = (void *) objc_malloc (maxElements * elementSize); + bzero (dataPtr, numElements * elementSize); + return self; +} + +- (id) init +{ + return [self initCount: 1 elementSize: sizeof (id) + description: @encode (id)]; +} + +- (void) dealloc +{ + if (dataPtr) + free (dataPtr); + [super dealloc]; +} + +- (const char *) description +{ + return description; +} + +// COPYING; + +- (id) copy +{ + Storage *c = [super copy]; + + c->dataPtr = (void *) objc_malloc (maxElements * elementSize); + memcpy (c->dataPtr, dataPtr, numElements * elementSize); + return c; +} + +// COMPARING TWO STORAGES; + +- (BOOL) isEqual: anObject +{ + if ([anObject isKindOfClass: [Storage class]] + && [anObject count] == [self count] + && !memcmp (((GNUStorageId *) anObject)->dataPtr, + dataPtr, numElements * elementSize)) + return YES; + else + return NO; +} + +// MANAGING THE STORAGE CAPACITY; + +static inline void +_makeRoomForAnotherIfNecessary (Storage * self) +{ + if (self->numElements == self->maxElements) { + self->maxElements *= 2; + self->dataPtr = (void *) + objc_realloc (self->dataPtr, + self->maxElements * self->elementSize); + } +} + +static inline void +_shrinkIfDesired (Storage * self) +{ + if (self->numElements < (self->maxElements / 2)) { + self->maxElements /= 2; + self->dataPtr = (void *) + objc_realloc (self->dataPtr, + self->maxElements * self->elementSize); + } +} + +- (id) setAvailableCapacity: (NSUInteger)numSlots +{ + if (numSlots > numElements) { + maxElements = numSlots; + dataPtr = (void *) objc_realloc (dataPtr, maxElements * elementSize); + } + return self; +} + +- (id) setNumSlots: (NSUInteger)numSlots +{ + if (numSlots > numElements) { + maxElements = numSlots; + dataPtr = (void *) objc_realloc (dataPtr, maxElements * elementSize); + bzero (STORAGE_NTH (numElements), + (maxElements - numElements) * elementSize); + } else if (numSlots < numElements) { + numElements = numSlots; + _shrinkIfDesired (self); + } + return self; +} + +/* Manipulating objects by index */ + +#define CHECK_INDEX(IND) if (IND >= numElements) return 0 + +- (NSUInteger) count +{ + return numElements; +} + +- (void *) elementAt: (NSUInteger)index +{ + CHECK_INDEX (index); + return STORAGE_NTH (index); +} + +- (id) addElement: (void *)anElement +{ + _makeRoomForAnotherIfNecessary (self); + memcpy (STORAGE_NTH (numElements), anElement, elementSize); + numElements++; + return self; +} + +- (id) insertElement: (void *) + anElement at: (NSUInteger)index +{ + NSUInteger i; + + CHECK_INDEX (index); + _makeRoomForAnotherIfNecessary (self); +#ifndef STABLE_MEMCPY + for (i = numElements; i >= index; i--) + memcpy (STORAGE_NTH (i + 1), STORAGE_NTH (i), elementSize); + +#else + memcpy (STORAGE_NTH (index + 1), + STORAGE_NTH (index), elementSize * (numElements - index)); +#endif + memcpy (STORAGE_NTH (i), anElement, elementSize); + numElements++; + return self; +} + +- (id) removeElementAt: (NSUInteger)index +{ + NSUInteger i; + + CHECK_INDEX (index); + numElements--; +#ifndef STABLE_MEMCPY + for (i = index; i < numElements; i++) + memcpy (STORAGE_NTH (i), STORAGE_NTH (i + 1), elementSize); + +#else + memcpy (STORAGE_NTH (index), + STORAGE_NTH (index + 1), elementSize * (numElements - index - 1)); +#endif + _shrinkIfDesired (self); + return self; +} + +- (id) removeLastElement +{ + if (numElements) { + numElements--; + _shrinkIfDesired (self); + } + return self; +} + +- (id) replaceElementAt: (NSUInteger) + index with: (void *)newElement +{ + CHECK_INDEX (index); + memcpy (STORAGE_NTH (index), newElement, elementSize); + return self; +} + +/* Emptying the Storage */ + +- (id) empty +{ + numElements = 0; + maxElements = 1; + dataPtr = (void *) objc_realloc (dataPtr, maxElements * elementSize); + return self; +} + ++ (id) new +{ + return [[self alloc] init]; +} + ++ (id) newCount: (NSUInteger) + count elementSize: (NSUInteger)sizeInBytes + description: (const char *)descriptor +{ + return [[self alloc] initCount: count elementSize: sizeInBytes description: + descriptor]; +} + +@end diff --git a/tools/Forge/Bundles/MapEdit/THING+NSArray.m b/tools/Forge/Bundles/MapEdit/THING+NSArray.m new file mode 100644 index 000000000..e5f354790 --- /dev/null +++ b/tools/Forge/Bundles/MapEdit/THING+NSArray.m @@ -0,0 +1,35 @@ +@implementation THING (NSArray) + +- (NSUInteger) count +{ + return [array count]; +} + +- (id) objectAtIndex: (NSUInteger)index +{ + if (index >= [self count]) + return 0; + return [array objectAtIndex: index]; +} + +- (void) addObject: (id)anObject +{ + [array addObject: anObject]; +} + +- (void) insertObject: (id)anObject atIndex: (NSUInteger)index +{ + [array insertObject: anObject atIndex: index]; +} + +- (void) removeObjectAtIndex: (NSUInteger)index +{ + [array removeObjectAtIndex: index]; +} + +- (void) replaceObjectAtIndex: (NSUInteger)index withObject: (id)anObject +{ + [array replaceObjectAtIndex: index withObject: anObject]; +} + +@end diff --git a/tools/Forge/Bundles/MapEdit/TexturePalette.h b/tools/Forge/Bundles/MapEdit/TexturePalette.h index 5b4200e57..18b37103c 100644 --- a/tools/Forge/Bundles/MapEdit/TexturePalette.h +++ b/tools/Forge/Bundles/MapEdit/TexturePalette.h @@ -1,113 +1,113 @@ +#ifndef TexturePalette_h +#define TexturePalette_h -typedef union -{ - byte chan[4]; - unsigned p; +#include + +#include "QF/qtypes.h" + +typedef union { + byte chan[4]; + unsigned p; } pixel32_t; - -typedef struct -{ - char texture[16]; - float rotate; - float shift[2]; - float scale[2]; +typedef struct { + char texture[16]; + float rotate; + float shift[2]; + float scale[2]; } texturedef_t; +typedef struct { + char name[16]; -typedef struct -{ - char name[16]; - - int width; - int height; - NSBitmapImageRep *rep; - void *data; - pixel32_t flatcolor; + int width; + int height; + NSBitmapImageRep *rep; + void *data; + pixel32_t flatcolor; } qtexture_t; -#define MAX_TEXTURES 1024 +#define MAX_TEXTURES 1024 -extern int tex_count; -extern qtexture_t qtextures[MAX_TEXTURES]; +extern int tex_count; +extern qtexture_t qtextures[MAX_TEXTURES]; -void TEX_InitFromWad (char *path); -qtexture_t *TEX_ForName (char *name); +qtexture_t *TEX_ForName (const char *name); - -typedef struct -{ - id image; // NSImage - NSRect r; - char *name; - int index; - int display; // flag (on/off) +typedef struct { + NSImageRep *image; + NSRect r; + char *name; + int index; + int display; // flag (on/off) } texpal_t; -#define TEX_INDENT 10 -#define TEX_SPACING 16 +#define TEX_INDENT 10 +#define TEX_SPACING 16 -extern id texturepalette_i; +extern id texturepalette_i; -@interface TexturePalette:Object +@interface TexturePalette: NSObject { - char currentwad[1024]; - id textureList_i; - id textureView_i; - id searchField_i; - id sizeField_i; - - id field_Xshift_i; - id field_Yshift_i; - id field_Xscale_i; - id field_Yscale_i; - id field_Rotate_i; - - int viewWidth; - int viewHeight; - int selectedTexture; + char currentwad[1024]; + id textureList_i; + id textureView_i; + id searchField_i; + id sizeField_i; + + id field_Xshift_i; + id field_Yshift_i; + id field_Xscale_i; + id field_Yscale_i; + id field_Rotate_i; + + int viewWidth; + int viewHeight; + int selectedTexture; } -- (char*)currentWad; -- initPaletteFromWadfile:(char *)wf; -- computeTextureViewSize; -- alphabetize; -- getList; -- (int)getSelectedTexture; -- setSelectedTexture:(int)which; -- (int)getSelectedTexIndex; +- (const char *) currentWad; +- (id) initPaletteFromWadfile: (const char *)wf; +- (id) computeTextureViewSize; +- (id) alphabetize; +- (id) getList; +- (int) getSelectedTexture; +- (id) setSelectedTexture: (int)which; +- (int) getSelectedTexIndex; // Called externally -- (char *)getSelTextureName; -- setTextureByName:(char *)name; +- (const char *) getSelTextureName; +- (id) setTextureByName: (const char *)name; // New methods to replace the 2 above ones -- setTextureDef:(texturedef_t *)td; -- getTextureDef:(texturedef_t *)td; +- (id) setTextureDef: (texturedef_t *)td; +- (id) getTextureDef: (texturedef_t *)td; // Action methods -- searchForTexture:sender; +- (id) searchForTexture: sender; -- clearTexinfo: sender; +- (id) clearTexinfo: sender; -- incXShift:sender; -- decXShift:sender; +- (id) incXShift: sender; +- (id) decXShift: sender; -- incYShift:sender; -- decYShift:sender; +- (id) incYShift: sender; +- (id) decYShift: sender; -- incRotate: sender; -- decRotate: sender; +- (id) incRotate: sender; +- (id) decRotate: sender; -- incXScale:sender; -- decXScale:sender; +- (id) incXScale: sender; +- (id) decXScale: sender; -- incYScale:sender; -- decYScale:sender; +- (id) incYScale: sender; +- (id) decYScale: sender; -- texturedefChanged: sender; -- onlyShowMapTextures:sender; -- (int) searchForTextureInPalette:(char *)texture; -- setDisplayFlag:(int)index to:(int)value; +- (id) texturedefChanged: sender; +- (id) onlyShowMapTextures: sender; +- (int) searchForTextureInPalette: (const char *)texture; +- (id) setDisplayFlag: (int)index + to: (int)value; @end +#endif // TexturePalette_h diff --git a/tools/Forge/Bundles/MapEdit/TexturePalette.m b/tools/Forge/Bundles/MapEdit/TexturePalette.m index 7d674deb0..fb41d8955 100644 --- a/tools/Forge/Bundles/MapEdit/TexturePalette.m +++ b/tools/Forge/Bundles/MapEdit/TexturePalette.m @@ -1,232 +1,268 @@ +#include -#include "qedefs.h" +#include "QF/qendian.h" +#include "QF/quakeio.h" +#include "QF/sys.h" +#include "QF/wadfile.h" +#include "QF/va.h" -id texturepalette_i; +#include "TexturePalette.h" +#include "Preferences.h" +#include "Project.h" +#include "Map.h" +#include "Entity.h" +#include "QuakeEd.h" +#include "SetBrush.h" +#include "Storage.h" -#define TYP_MIPTEX 67 +id texturepalette_i; -int tex_count; -qtexture_t qtextures[MAX_TEXTURES]; +int tex_count; +qtexture_t qtextures[MAX_TEXTURES]; -typedef struct -{ - char name[16]; - unsigned width, height; - unsigned offsets[4]; // four mip maps stored +typedef struct { + char name[16]; + unsigned width, height; + unsigned offsets[4]; // four mip maps stored } miptex_t; -unsigned tex_palette[256]; +unsigned tex_palette[256]; -unsigned badtex_d[] = -{ -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, +unsigned badtex_d[] = { + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff, -0,0,0,0,0,0,0,0, -0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0, 0, 0, 0, + 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff }; -qtexture_t badtex = {"notexture",16,16,NULL, badtex_d, {0,0,255,255}}; +qtexture_t badtex = {"notexture", 16, 16, NULL, badtex_d, {{0, 0, 255, 255}}}; + +void +CleanupName (const char *in, char *out) +{ + int i; + + for (i = 0; i < 16; i++) { + if (!in[i]) + break; + out[i] = toupper (in[i]); + } + for ( ; i < 16; i++) + out[i] = 0; +} /* ============== TEX_InitPalette ============== */ -void TEX_InitPalette (byte *pal) +void +TEX_InitPalette (wad_t *wad, lumpinfo_t *pallump) { - int r,g,b,v; - int i; + byte *pal, *opal; + int r, g, b, v; + int i; - for (i=0 ; i<256 ; i++) - { + opal = pal = malloc (pallump->size); + Qseek (wad->handle, pallump->filepos, SEEK_SET); + Qread (wad->handle, pal, pallump->size); + + for (i = 0; i < 256; i++) { r = pal[0]; g = pal[1]; b = pal[2]; pal += 3; - - v = (r<<24) + (g<<16) + (b<<8) + 255; + + v = (r << 24) + (g << 16) + (b << 8) + 255; v = BigLong (v); - + tex_palette[i] = v; } + free (opal); } - /* ================= TEX_ImageFromMiptex ================= */ -void TEX_ImageFromMiptex (miptex_t *qtex) +void +TEX_ImageFromMiptex (wad_t *wad, lumpinfo_t *qtexlump) { - NSBitmapImageRep *bm; - byte *source; - unsigned *dest; - int width, height, i, count; - qtexture_t *q; - int tr, tg, tb; - - width = LittleLong(qtex->width); - height = LittleLong(qtex->height); + miptex_t *qtex; + NSBitmapImageRep *bm; + byte *source; + unsigned *dest; + int width, height, i, count; + qtexture_t *q; + int tr, tg, tb; + + qtex = malloc (qtexlump->size); + Qseek (wad->handle, qtexlump->filepos, SEEK_SET); + Qread (wad->handle, qtex, qtexlump->size); + + width = LittleLong (qtex->width); + height = LittleLong (qtex->height); + + bm = [[NSBitmapImageRep alloc] + initWithBitmapDataPlanes: NULL + pixelsWide: width + pixelsHigh: height + bitsPerSample: 8 + samplesPerPixel: 3 + hasAlpha: NO + isPlanar: NO + colorSpaceName: NSCalibratedRGBColorSpace + bytesPerRow: width * 4 + bitsPerPixel: 32]; + + dest = (unsigned *) [bm bitmapData]; + count = width * height; + source = (byte *) qtex + LittleLong (qtex->offsets[0]); - bm = [[NSBitmapImageRep alloc] - initData: NULL - pixelsWide: width - pixelsHigh: height - bitsPerSample: 8 - samplesPerPixel:3 - hasAlpha: NO - isPlanar: NO - colorSpace: NS_RGBColorSpace - bytesPerRow: width*4 - bitsPerPixel: 32]; - - dest = (unsigned *)[bm data]; - count = width*height; - source = (byte *)qtex + LittleLong(qtex->offsets[0]); - q = &qtextures[tex_count]; tex_count++; - + q->width = width; q->height = height; + if (q->rep) + [q->rep release]; q->rep = bm; q->data = dest; tr = tg = tb = 0; - - for (i=0 ; ichan[0]; - tg += ((pixel32_t *)&dest[i])->chan[1]; - tb += ((pixel32_t *)&dest[i])->chan[2]; + tr += ((pixel32_t *) &dest[i])->chan[0]; + tg += ((pixel32_t *) &dest[i])->chan[1]; + tb += ((pixel32_t *) &dest[i])->chan[2]; } - + q->flatcolor.chan[0] = tr / count; q->flatcolor.chan[1] = tg / count; q->flatcolor.chan[2] = tb / count; - q->flatcolor.chan[3] = 0xff; + q->flatcolor.chan[3] = 0xff; + free (qtex); } -//============================================================================= - -typedef struct -{ - char identification[4]; // should be WAD2 or 2DAW - int numlumps; - int infotableofs; -} wadinfo_t; - - -typedef struct -{ - int filepos; - int disksize; - int size; // uncompressed - char type; - char compression; - char pad1, pad2; - char name[16]; // must be null terminated -} lumpinfo_t; +// ============================================================================= /* ================= TEX_InitFromWad ================= */ -void TEX_InitFromWad (char *path) +int +TEX_InitFromWad (const char *path) { - int i; - char local[1024]; - char newpath[1024]; - byte *wadfile; - wadinfo_t *wadinfo; - lumpinfo_t *lumpinfo; - int numlumps; - float start, stop; - - start = I_FloatTime (); - - strcpy(newpath, [preferences_i getProjectPath]); - strcat(newpath,"/"); - strcat(newpath, path); - -// free any textures - for (i=0 ; ilumps; + + if (strcasecmp (lumpinfo->name, "PALETTE")) { + lumpinfo_t tlump; + + Sys_Printf ("TEX_InitFromWad: %s doesn't have palette at index 0\n", path); + lumpinfo = wad_find_lump (wad, "PALETTE"); + if (!lumpinfo) { + Sys_Printf ("TEX_InitFromWad: %s doesn't have a palette\n", path); + goto cleanup; + } + + // move the palette lump to the first entry + tlump = *lumpinfo; + *lumpinfo = wad->lumps[0]; + wad->lumps[0] = tlump; + lumpinfo = wad->lumps; + } + + TEX_InitPalette (wad, lumpinfo); + + old_tex_count = tex_count; tex_count = 0; -// try and use the cached wadfile - sprintf (local, "/qcache%s", newpath); - - Sys_UpdateFile (local, newpath); - - LoadFile (local, (void **)&wadfile); - wadinfo = (wadinfo_t *)wadfile; - - if (strncmp (wadfile, "WAD2", 4)) - { - unlink (local); - Error ("TEX_InitFromWad: %s isn't a wadfile", newpath); + lumpinfo++; + for (i = 1; i < wad->numlumps; i++, lumpinfo++) { + if (lumpinfo->type != TYP_MIPTEX) { + Sys_Printf ("TEX_InitFromWad: %s is not a miptex!\n", lumpinfo->name); + continue; + } + CleanupName (lumpinfo->name, qtextures[tex_count].name); + TEX_ImageFromMiptex (wad, lumpinfo); } - - numlumps = LittleLong (wadinfo->numlumps); - lumpinfo = (lumpinfo_t *)(wadfile + LittleLong (wadinfo->infotableofs)); - - if (strcmp (lumpinfo->name, "PALETTE")) - { - unlink (local); - Error ("TEX_InitFromWad: %s doesn't have palette as 0",path); - } - - TEX_InitPalette (wadfile + LittleLong(lumpinfo->filepos)); - - lumpinfo++; - for (i=1 ; itype != TYP_MIPTEX) - Error ("TEX_InitFromWad: %s is not a miptex!",lumpinfo->name); - CleanupName (lumpinfo->name,qtextures[tex_count].name); - TEX_ImageFromMiptex ( (miptex_t *)(wadfile + - LittleLong(lumpinfo->filepos) )); + if (tex_count) { + for (i = tex_count; i < old_tex_count; i++) { + [qtextures[i].rep release]; + qtextures[i].rep = nil; + } + } else { + goto cleanup; } - free (wadfile); + wad_close (wad); - stop = I_FloatTime (); - - qprintf ("loaded %s (%5.1f)", local, stop - start); + stop = Sys_DoubleTime (); + + Sys_Printf ("loaded %s (%.3f seconds)\n", newpath, stop - start); + return 1; + +cleanup: + if (wad) + wad_close (wad); + + NSRunAlertPanel (@"Wad Error", errmsg, @"OK", nil, nil); + + return 0; } /* @@ -234,30 +270,27 @@ void TEX_InitFromWad (char *path) TEX_NumForName ================= */ -qtexture_t *TEX_ForName (char *name) +qtexture_t * +TEX_ForName (const char *name) { - char newname[16]; - int i; - qtexture_t *q; - + char newname[16]; + int i; + qtexture_t *q; + CleanupName (name, newname); - - for (i=0,q = qtextures ; i< tex_count ; i++, q++) - { - if (!strcmp(name, q->name)) + + for (i = 0, q = qtextures; i < tex_count; i++, q++) { + if (!strcmp (newname, q->name)) return q; } - + return &badtex; } - - -//=========================================================================== +// =========================================================================== @implementation TexturePalette - -- init +- (id) init { [super init]; texturepalette_i = self; @@ -265,44 +298,41 @@ qtexture_t *TEX_ForName (char *name) return self; } -- display +- (void) display { [[textureView_i superview] display]; - return self; } - -- (char *)currentWad +- (const char *) currentWad { return currentwad; } -- initPaletteFromWadfile:(char *)wf +- (id) initPaletteFromWadfile: (const char *)wf { - int i; - texpal_t t; - qtexture_t *q; - + int i; + texpal_t t; + qtexture_t *q; + strcpy (currentwad, wf); - [map_i makeGlobalPerform: @selector(flushTextures)]; + [map_i makeGlobalPerform: @selector (flushTextures)]; selectedTexture = -1; - + // Init textures WAD - TEX_InitFromWad(wf); - + if (!TEX_InitFromWad (wf)) + return self; + // Create STORAGE - if (textureList_i) + if (textureList_i) { [textureList_i empty]; - else - textureList_i = [[Storage alloc] - initCount:0 - elementSize:sizeof(texpal_t) - description:NULL]; - + } else { + textureList_i = [[Storage alloc] initCount: 0 + elementSize: sizeof (texpal_t) + description: NULL]; + } // Init STORAGE - - for (i = 0,q=qtextures;i < tex_count; i++,q++) - { + + for (i = 0, q = qtextures; i < tex_count; i++, q++) { t.image = q->rep; t.r.size.width = [t.image pixelsWide]; if (t.r.size.width < 64) @@ -311,52 +341,47 @@ qtexture_t *TEX_ForName (char *name) t.name = q->name; t.index = i; t.display = 1; - [textureList_i addElement:&t]; + [textureList_i addElement: &t]; } // Calculate size of TextureView [self alphabetize]; [self computeTextureViewSize]; - [textureView_i setParent:self]; - [self setSelectedTexture:0]; + [textureView_i setParent: self]; + [self setSelectedTexture: 0]; return self; } - - -// Return texture STORAGE list -- getList +// Return texture STORAGE list +- (id) getList { return textureList_i; } -// Alphabetize texture list - reverse order! -- alphabetize +// Alphabetize texture list - reverse order! +- (id) alphabetize { - int i; - int max; - texpal_t *t1p; - texpal_t *t2p; - texpal_t t1; - texpal_t t2; - int found; - + int i; + int max; + texpal_t *t1p; + texpal_t *t2p; + texpal_t t1; + texpal_t t2; + int found; + max = [textureList_i count]; found = 1; - while(found) - { + while (found) { found = 0; - for (i = 0;i < max-1;i++) - { - t1p = [textureList_i elementAt:i]; - t2p = [textureList_i elementAt:i+1]; - if (strcmp(t1p->name,t2p->name) < 0) - { + for (i = 0; i < max - 1; i++) { + t1p = [textureList_i elementAt: i]; + t2p = [textureList_i elementAt: i + 1]; + if (strcmp (t1p->name, t2p->name) < 0) { t1 = *t1p; t2 = *t2p; - [textureList_i replaceElementAt:i with:&t2]; - [textureList_i replaceElementAt:i+1 with:&t1]; + [textureList_i replaceElementAt: i with: &t2]; + [textureList_i replaceElementAt: i + 1 with: &t1]; found = 1; } } @@ -364,33 +389,31 @@ qtexture_t *TEX_ForName (char *name) return self; } -- computeTextureViewSize +- (id) computeTextureViewSize { - int i; - int max; - int x; - texpal_t *t; - int y; - id view; - NSRect b; - int maxwidth; - int maxheight; - NSPoint pt; - + int i; + int max; + int x; + texpal_t *t; + int y; + id view; + NSRect b; + int maxwidth; + int maxheight; + NSPoint pt; + max = [textureList_i count]; y = 0; maxheight = 0; x = TEX_INDENT; view = [textureView_i superview]; - [view getBounds:&b]; + b = [view bounds]; maxwidth = b.size.width; - for (i = 0;i < max; i++) - { - t = [textureList_i elementAt:i]; - if (x + t->r.size.width + TEX_INDENT > maxwidth) - { + for (i = 0; i < max; i++) { + t = [textureList_i elementAt: i]; + if (x + t->r.size.width + TEX_INDENT > maxwidth) { x = TEX_INDENT; y += maxheight; maxheight = 0; @@ -406,411 +429,374 @@ qtexture_t *TEX_ForName (char *name) viewWidth = maxwidth; viewHeight = y + TEX_SPACING; - [textureView_i sizeTo:viewWidth :viewHeight]; + [textureView_i setFrameSize: NSMakeSize (viewWidth, viewHeight)]; pt.x = pt.y = 0; - [textureView_i scrollPoint:&pt]; + [textureView_i scrollPoint: pt]; return self; } -- windowResized +- (id) windowResized { [self computeTextureViewSize]; return self; } -- texturedefChanged: sender +- (id) texturedefChanged: sender { - if ([map_i numSelected]) - { - if ( [[map_i currentEntity] modifiable] ) - { - [map_i makeSelectedPerform: @selector(takeCurrentTexture)]; + if ([map_i numSelected]) { + if ([[map_i currentEntity] modifiable]) { + [map_i makeSelectedPerform: @selector + (takeCurrentTexture)]; [quakeed_i updateAll]; + } else { + Sys_Printf ("can't modify spawned entities\n"); } - else - qprintf ("can't modify spawned entities"); } [quakeed_i makeFirstResponder: quakeed_i]; return self; } -- clearTexinfo: sender +- (id) clearTexinfo: sender { - [field_Xshift_i setFloatValue:0]; - [field_Yshift_i setFloatValue:0]; - [field_Xscale_i setFloatValue:1]; - [field_Yscale_i setFloatValue:1]; - [field_Rotate_i setFloatValue:0]; - + [field_Xshift_i setFloatValue: 0]; + [field_Yshift_i setFloatValue: 0]; + [field_Xscale_i setFloatValue: 1]; + [field_Yscale_i setFloatValue: 1]; + [field_Rotate_i setFloatValue: 0]; + [self texturedefChanged: self]; return self; } -// -// Set the selected texture -// -- setSelectedTexture:(int)which +// Set the selected texture +- (id) setSelectedTexture: (int)which { - texpal_t *t; - NSRect r; - char string[16]; + texpal_t *t; + NSRect r; -// wipe the fields + // wipe the fields [self clearTexinfo: self]; - - if (which != selectedTexture) - { + + if (which != selectedTexture) { [textureView_i deselect]; selectedTexture = which; - t = [textureList_i elementAt:which]; + t = [textureList_i elementAt: which]; r = t->r; - r.size.width += TEX_INDENT*2; - r.size.height += TEX_INDENT*2; + r.size.width += TEX_INDENT * 2; + r.size.height += TEX_INDENT * 2; r.origin.x -= TEX_INDENT; r.origin.y -= TEX_INDENT; - [textureView_i scrollRectToVisible:&r]; + [textureView_i scrollRectToVisible: r]; [textureView_i display]; - sprintf(string,"%d x %d",(int)t->r.size.width, - (int)t->r.size.height - TEX_SPACING); - [sizeField_i setStringValue:string]; + [sizeField_i setStringValue: + [NSString stringWithFormat: @"%d x %d", + (int) t->r.size.width, + (int) t->r.size.height - TEX_SPACING]]; } - [self texturedefChanged:self]; + [self texturedefChanged: self]; return self; } -// -// Return the selected texture index -// -- (int)getSelectedTexture +// Return the selected texture index +- (int) getSelectedTexture { return selectedTexture; } -// -// Return the original tex_ index of the selected texture -// so the texture info can be indexed from tex_images, etc. -// -- (int)getSelectedTexIndex +// Return the original tex_ index of the selected texture +// so the texture info can be indexed from tex_images, etc. +- (int) getSelectedTexIndex { - texpal_t *t; - + texpal_t *t; + if (selectedTexture == -1) return -1; - t = [textureList_i elementAt:selectedTexture]; + t = [textureList_i elementAt: selectedTexture]; return t->index; } -// -// Return the name of the selected texture -// -- (char *)getSelTextureName +// Return the name of the selected texture +- (const char *) getSelTextureName { - texpal_t *t; - + texpal_t *t; + if (selectedTexture == -1) return NULL; - t = [textureList_i elementAt:selectedTexture]; + t = [textureList_i elementAt: selectedTexture]; return t->name; } -// -// Set selected texture by texture name -// -- setTextureByName:(char *)name +// Set selected texture by texture name +- (id) setTextureByName: (const char *)name { - texpal_t *t; - int i; - int max; - + texpal_t *t; + int i; + int max; + char *nm = strdup (name); + max = [textureList_i count]; - CleanupName(name,name); - for (i = 0;i < max;i++) - { - t = [textureList_i elementAt:i]; - if (!strcmp(t->name,name)) - { + CleanupName (nm, nm); + for (i = 0; i < max; i++) { + t = [textureList_i elementAt: i]; + if (!strcmp (t->name, nm)) { + free (nm); [self setSelectedTexture: i]; return self; } } + free (nm); return self; } -//=================================================== +// =================================================== // -// Action methods +// Action methods // -//=================================================== +// =================================================== - -// -// Search for texture named in searchField -// -- searchForTexture:sender +// Search for texture named in searchField +- (id) searchForTexture: sender { - int i; - int max; - int len; - char name[32]; - texpal_t *t; - + int i; + int max; + int len; + NSMutableString *strname; + const char *name; + texpal_t *t; + if (selectedTexture == -1) return self; max = [textureList_i count]; - strcpy(name,(const char *)[sender stringValue]); - [sender setStringValue:strupr(name)]; - len = strlen(name); - - for (i = selectedTexture-1;i >= 0; i--) - { - t = [textureList_i elementAt:i]; - if (!strncmp(t->name,name,len)) - { - [self setTextureByName:t->name]; - [sender selectText:sender]; - [self texturedefChanged:self]; + strname = [[sender stringValue] mutableCopy]; + [strname uppercaseString]; + [sender setStringValue: strname]; + name = [strname cString]; + len = strlen (name); + + for (i = selectedTexture - 1; i >= 0; i--) { + t = [textureList_i elementAt: i]; + if (!strncmp (t->name, name, len)) { + [self setTextureByName: t->name]; + [sender selectText: sender]; + [self texturedefChanged: self]; return self; } } - - for (i = max-1;i >= selectedTexture; i--) - { - t = [textureList_i elementAt:i]; - if (!strncmp(t->name,name,len)) - { - [self setTextureByName:t->name]; - [sender selectText:sender]; - [self texturedefChanged:self]; + + for (i = max - 1; i >= selectedTexture; i--) { + t = [textureList_i elementAt: i]; + if (!strncmp (t->name, name, len)) { + [self setTextureByName: t->name]; + [sender selectText: sender]; + [self texturedefChanged: self]; return self; } } - - [self texturedefChanged:self]; + + [self texturedefChanged: self]; return self; } -// -// Set texture def from outside TexturePalette -// -- setTextureDef:(texturedef_t *)td +// Set texture def from outside TexturePalette +- (id) setTextureDef: (texturedef_t *)td { - [self setTextureByName:td->texture]; + [self setTextureByName: td->texture]; - [field_Xshift_i setFloatValue:td->shift[0]]; - [field_Yshift_i setFloatValue:td->shift[1]]; - [field_Xscale_i setFloatValue:td->scale[0]]; - [field_Yscale_i setFloatValue:td->scale[1]]; - [field_Rotate_i setFloatValue:td->rotate]; + [field_Xshift_i setFloatValue: td->shift[0]]; + [field_Yshift_i setFloatValue: td->shift[1]]; + [field_Xscale_i setFloatValue: td->scale[0]]; + [field_Yscale_i setFloatValue: td->scale[1]]; + [field_Rotate_i setFloatValue: td->rotate]; + + [self texturedefChanged: self]; - [self texturedefChanged:self]; - return self; } -// -// Return the current texture def to passed * -// -- getTextureDef:(texturedef_t *)td +// Return the current texture def to passed * +- (id) getTextureDef: (texturedef_t *)td { - if (selectedTexture == -1) - { - memset (td, 0, sizeof(*td)); + if (selectedTexture == -1) { + memset (td, 0, sizeof (*td)); strcpy (td->texture, "notexture"); return self; } - - strncpy(td->texture,[self getSelTextureName],16); + + strncpy (td->texture, [self getSelTextureName], 16); td->shift[0] = [field_Xshift_i floatValue]; td->shift[1] = [field_Yshift_i floatValue]; td->scale[0] = [field_Xscale_i floatValue]; td->scale[1] = [field_Yscale_i floatValue]; td->rotate = [field_Rotate_i floatValue]; - + return self; } -//============================================================================ +// ============================================================================ -// -// Change value in a field -// -- changeField:(id)field by:(int)amount +// Change value in a field +- (id) changeField: (id) + field by: (int)amount { - int val; - + int val; + val = [field intValue]; val += amount; - [field setIntValue:val]; + [field setIntValue: val]; - [self texturedefChanged:self]; + [self texturedefChanged: self]; return self; } -// -// Inc/Dec the XShift field -// -- incXShift:sender +// Inc/Dec the XShift field +- (id) incXShift: sender { - [self changeField:field_Xshift_i by:8]; - return self; -} -- decXShift:sender -{ - [self changeField:field_Xshift_i by:-8]; + [self changeField: field_Xshift_i by: 8]; return self; } -// -// Inc/Dec the YShift field -// -- incYShift:sender +- (id) decXShift: sender { - [self changeField:field_Yshift_i by:8]; - return self; -} -- decYShift:sender -{ - [self changeField:field_Yshift_i by:-8]; + [self changeField: field_Xshift_i by: -8]; return self; } -// -// Inc/Dec the Rotate field -// -- incRotate:sender +// Inc/Dec the YShift field +- (id) incYShift: sender { - [self changeField:field_Rotate_i by:90]; - return self; -} -- decRotate:sender -{ - [self changeField:field_Rotate_i by:-90]; + [self changeField: field_Yshift_i by: 8]; return self; } -// -// Inc/Dec the Xscale field -// -- incXScale:sender +- (id) decYShift: sender +{ + [self changeField: field_Yshift_i by: -8]; + return self; +} + +// Inc/Dec the Rotate field +- (id) incRotate: sender +{ + [self changeField: field_Rotate_i by: 90]; + return self; +} + +- (id) decRotate: sender +{ + [self changeField: field_Rotate_i by: -90]; + return self; +} + +// Inc/Dec the Xscale field +- (id) incXScale: sender { [field_Xscale_i setIntValue: 1]; - [self texturedefChanged:self]; + [self texturedefChanged: self]; return self; } -- decXScale:sender + +- (id) decXScale: sender { [field_Xscale_i setIntValue: -1]; - [self texturedefChanged:self]; + [self texturedefChanged: self]; return self; } -// -// Inc/Dec the Yscale field -// -- incYScale:sender +// Inc/Dec the Yscale field +- (id) incYScale: sender { [field_Yscale_i setIntValue: 1]; - [self texturedefChanged:self]; + [self texturedefChanged: self]; return self; } -- decYScale:sender + +- (id) decYScale: sender { [field_Yscale_i setIntValue: -1]; - [self texturedefChanged:self]; + [self texturedefChanged: self]; return self; } +// ============================================================================ -//============================================================================ - - -// -// Search for texture in entire palette -// Return index of texturedef, or -1 if unsuccessful -// -- (int) searchForTextureInPalette:(char *)texture +// Search for texture in entire palette +// Return index of texturedef, or -1 if unsuccessful +- (int) searchForTextureInPalette: (const char *)texture { - int i; - int max; - char name[32]; - texpal_t *t; - + int i; + int max; + texpal_t *t; + if (selectedTexture == -1) return -1; max = [textureList_i count]; - strcpy(name,texture); - - for (i = 0; i < max; i++) - { - t = [textureList_i elementAt:i]; - if (!strcmp(t->name,name)) + + for (i = 0; i < max; i++) { + t = [textureList_i elementAt: i]; + if (!strcmp (t->name, texture)) return i; } return -1; }; -// // Scan thru map & display only textures that are in map -// -- onlyShowMapTextures:sender +- (id) onlyShowMapTextures: sender { - int max; - int i; - int j; - id brushes; - SetBrush *b; - int numfaces; - face_t *f; - int index; - - // Turn 'em off - if ([sender intValue]) - { - max = [textureList_i count]; - for (i = 0;i < max; i++) - [self setDisplayFlag:i to:0]; + int max; + int i; + int j; + id brushes; + SetBrush *b; + int numfaces; + face_t *f; + int index; - brushes = [map_i objectAt:0]; + // Turn 'em off + if ([sender intValue]) { + max = [textureList_i count]; + for (i = 0; i < max; i++) + [self setDisplayFlag: i to: 0]; + + brushes = [map_i objectAtIndex: 0]; max = [brushes count]; - for (i = 0;i < max; i++) - { - b = (SetBrush *)[brushes objectAt:i]; + for (i = 0; i < max; i++) { + b = (SetBrush *) [brushes objectAtIndex: i]; numfaces = [b getNumBrushFaces]; - for (j = 0; j < numfaces; j++) - { - f = [b getBrushFace:j]; - index = [self searchForTextureInPalette:f->texture.texture]; + for (j = 0; j < numfaces; j++) { + f = [b getBrushFace: j]; + index = [self searchForTextureInPalette: f->texture. + texture]; if (index >= 0) - [self setDisplayFlag:index to:1]; + [self setDisplayFlag: index to: 1]; } } } // Turn 'em on - else - { + else { max = [textureList_i count]; - for (i = 0;i < max; i++) - [self setDisplayFlag:i to:1]; + for (i = 0; i < max; i++) + [self setDisplayFlag: i to: 1]; } - + [textureView_i display]; - + return self; } -- setDisplayFlag:(int)index to:(int)value +- (id) setDisplayFlag: (int) + index to: (int)value { - texpal_t *tp; - - tp = [textureList_i elementAt:index]; + texpal_t *tp; + + tp = [textureList_i elementAt: index]; tp->display = value; return self; }; diff --git a/tools/Forge/Bundles/MapEdit/TextureView.h b/tools/Forge/Bundles/MapEdit/TextureView.h index 2f4af37af..2047c6aaf 100644 --- a/tools/Forge/Bundles/MapEdit/TextureView.h +++ b/tools/Forge/Bundles/MapEdit/TextureView.h @@ -1,12 +1,16 @@ +#ifndef TextureView_h +#define TextureView_h +#include -@interface TextureView:NSView +@interface TextureView: NSView { - id parent_i; - int deselectIndex; + id parent_i; + int deselectIndex; } -- setParent:(id)from; -- deselect; +- (id) setParent: (id)from; +- (id) deselect; @end +#endif // TextureView_h diff --git a/tools/Forge/Bundles/MapEdit/TextureView.m b/tools/Forge/Bundles/MapEdit/TextureView.m index 57db12be3..b8dc50827 100644 --- a/tools/Forge/Bundles/MapEdit/TextureView.m +++ b/tools/Forge/Bundles/MapEdit/TextureView.m @@ -1,5 +1,10 @@ +#include "QF/sys.h" -#include "qedefs.h" +#include "KeypairView.h" +#include "TextureView.h" +#include "TexturePalette.h" + +#include "Storage.h" /* @@ -9,143 +14,135 @@ NOTE: I am specifically not using cached image reps, because the data is also ne @implementation TextureView -- init +- (id) init { deselectIndex = -1; return self; } -- setParent:(id)from +- (BOOL) isOpaque +{ + return YES; +} + +- (id) setParent: (id)from { parent_i = from; return self; } -- (BOOL)acceptsFirstMouse +- (BOOL) acceptsFirstMouse { return YES; } -- drawSelf:(const NSRect *)rects :(int)rectCount +- (id) drawRect: (NSRect)rects { - int i; - int max; - id list_i; - texpal_t *t; - int x; - int y; - NSPoint p; - NSRect r; - int selected; - + int i; + int max; + id list_i; + texpal_t *t; + int x; + int y; + NSPoint p; + NSRect r; + int selected; + NSMutableDictionary *attribs = [NSMutableDictionary dictionary]; + selected = [parent_i getSelectedTexture]; list_i = [parent_i getList]; - PSselectfont("Helvetica-Medium",FONTSIZE); - PSrotate(0); - - PSsetgray(NS_LTGRAY); - PSrectfill(rects->origin.x, rects->origin.y, - rects->size.width, rects->size.height); + [[NSFont systemFontOfSize: FONTSIZE] set]; - if (!list_i) // WADfile didn't init + [[NSColor lightGrayColor] set]; + NSRectFill (rects); + + if (!list_i) // WADfile didn't init return self; - - if (deselectIndex != -1) - { - t = [list_i elementAt:deselectIndex]; + if (deselectIndex != -1) { + t = [list_i elementAt: deselectIndex]; r = t->r; r.origin.x -= TEX_INDENT; r.origin.y -= TEX_INDENT; - r.size.width += TEX_INDENT*2; - r.size.height += TEX_INDENT*2; - - PSsetgray(NSGrayComponent(NS_COLORLTGRAY)); - PSrectfill(r.origin.x, r.origin.y, - r.size.width, r.size.height); + r.size.width += TEX_INDENT * 2; + r.size.height += TEX_INDENT * 2; + + [[NSColor lightGrayColor] set]; + NSRectFill (r); p = t->r.origin; p.y += TEX_SPACING; - [t->image drawAt:&p]; - PSsetgray(0); + [t->image drawAtPoint: p]; + [[NSColor blackColor] set]; x = t->r.origin.x; y = t->r.origin.y + 7; - PSmoveto(x,y); - PSshow(t->name); - PSstroke(); + [[NSString stringWithCString: t->name] + drawAtPoint: NSMakePoint (x, y) withAttributes: attribs]; deselectIndex = -1; } max = [list_i count]; - PSsetgray(0); + [[NSColor blackColor] set]; - for (i = 0;i < max; i++) - { - t = [list_i elementAt:i]; + for (i = 0; i < max; i++) { + t = [list_i elementAt: i]; r = t->r; - r.origin.x -= TEX_INDENT/2; + r.origin.x -= TEX_INDENT / 2; r.size.width += TEX_INDENT; r.origin.y += 4; - if (NSIntersectsRect(&rects[0],&r) == YES && - t->display) - { - if (selected == i) - { - PSsetgray(1); - PSrectfill(r.origin.x,r.origin.y, - r.size.width,r.size.height); - PSsetrgbcolor(1,0,0); - PSrectstroke(r.origin.x, r.origin.y, - r.size.width, r.size.height); - PSsetgray(0); + if (NSIntersectsRect (rects, r) == YES && t->display) { + if (selected == i) { + [[NSColor whiteColor] set]; + NSRectFill (r); + [[NSColor redColor] set]; + NSFrameRect (r); + [[NSColor blackColor] set]; } - + p = t->r.origin; p.y += TEX_SPACING; - [t->image drawAt:&p]; + [t->image drawAtPoint: p]; x = t->r.origin.x; y = t->r.origin.y + 7; - PSmoveto(x,y); - PSshow(t->name); + [[NSString stringWithCString: t->name] + drawAtPoint: NSMakePoint (x, y) withAttributes: attribs]; } } - PSstroke(); return self; } -- deselect +- (id) deselect { deselectIndex = [parent_i getSelectedTexture]; return self; } -- mouseDown:(NSEvent *)theEvent +- (id) mouseDown: (NSEvent *)theEvent { - NSPoint loc; - int i; - int max; - int oldwindowmask; - texpal_t *t; - id list; - NSRect r; + NSPoint loc; + int i; + int max; + + // int oldwindowmask; + texpal_t *t; + id list; + NSRect r; + + // oldwindowmask = [window addToEventMask:NSLeftMouseDraggedMask]; + loc = [theEvent locationInWindow]; + loc = [self convertPoint: loc fromView: NULL]; - oldwindowmask = [window addToEventMask:NS_LMOUSEDRAGGEDMASK]; - loc = theEvent->location; - [self convertPoint:&loc fromView:NULL]; - list = [parent_i getList]; max = [list count]; - for (i = 0;i < max; i++) - { - t = [list elementAt:i]; + for (i = 0; i < max; i++) { + t = [list elementAt: i]; r = t->r; - if (NSPointInRect(&loc,&r) == YES) - { - [self deselect]; - [parent_i setSelectedTexture:i]; + if (NSPointInRect (loc, r) == YES) { + [self deselect]; + [parent_i setSelectedTexture: i]; break; } } - - [window setEventMask:oldwindowmask]; + + // [window setEventMask:oldwindowmask]; return self; } diff --git a/tools/Forge/Bundles/MapEdit/Things.h b/tools/Forge/Bundles/MapEdit/Things.h index c2becd888..ec3cbb06a 100644 --- a/tools/Forge/Bundles/MapEdit/Things.h +++ b/tools/Forge/Bundles/MapEdit/Things.h @@ -1,42 +1,46 @@ +#ifndef Things_h +#define Things_h #include -extern id things_i; +#include "Entity.h" -#define ENTITYNAMEKEY "spawn" +extern id things_i; -@interface Things:Object +#define ENTITYNAMEKEY "spawn" + +@interface Things: NSObject { - id entity_browser_i; // browser - id entity_comment_i; // scrolling text window - - id prog_path_i; - - int lastSelected; // last row selected in browser + id entity_browser_i; // browser + id entity_comment_i; // scrolling text window - id keyInput_i; - id valueInput_i; - id flags_i; + id prog_path_i; + + int lastSelected; // last row selected in browser + + id keyInput_i; + id valueInput_i; + id flags_i; } -- initEntities; +- (id) initEntities; -- newCurrentEntity; -- setSelectedKey:(epair_t *)ep; +- (id) newCurrentEntity; +- (id) setSelectedKey: (epair_t *)ep; -- clearInputs; -- (char *)spawnName; +- (id) clearInputs; +- (const char *) spawnName; // UI targets -- reloadEntityClasses: sender; -- selectEntity: sender; -- doubleClickEntity: sender; +- (id) reloadEntityClasses: sender; +- (id) selectEntity: sender; +- (id) doubleClickEntity: sender; // Action methods -- addPair:sender; -- delPair:sender; -- setAngle:sender; -- setFlags:sender; - +- (id) addPair: sender; +- (id) delPair: sender; +- (id) setAngle: sender; +- (id) setFlags: sender; @end +#endif // Things_h diff --git a/tools/Forge/Bundles/MapEdit/Things.m b/tools/Forge/Bundles/MapEdit/Things.m index ec93630f7..777af1782 100644 --- a/tools/Forge/Bundles/MapEdit/Things.m +++ b/tools/Forge/Bundles/MapEdit/Things.m @@ -1,222 +1,223 @@ +#include "QF/sys.h" +#include "QF/va.h" -#include "qedefs.h" +#include "Things.h" +#include "QuakeEd.h" +#include "Map.h" +#include "EntityClass.h" +#include "KeypairView.h" +#include "Project.h" -id things_i; +id things_i; @implementation Things -- init +- (id) init { [super init]; things_i = self; lastSelected = 0; - + return self; } -// -// Load the TEXT object with the entity comment -// -- loadEntityComment:(id)obj +- (void) awakeFromNib { - [entity_comment_i selectAll:self]; - [entity_comment_i replaceSel:[obj comments]]; + // FIXME this should not be needed (bug in gnustep?) + [flags_i selectAll: self]; + [flags_i deselectAllCells]; +} + +// Load the TEXT object with the entity comment +- (id) loadEntityComment: (id)obj +{ + [entity_comment_i selectAll: self]; + [entity_comment_i + replaceCharactersInRange: [entity_comment_i selectedRange] + withString: [NSString stringWithCString: [obj comments]]]; return self; } - -- initEntities -{ - char *path; +- (id) initEntities +{ + NSString *path; path = [project_i getProgDirectory]; [prog_path_i setStringValue: path]; - - [[EntityClassList alloc] initForSourceDirectory: path]; - [self loadEntityComment:[entity_classes_i objectAt:lastSelected]]; + [[EntityClassList alloc] initForSourceDirectory: [path cString]]; + + [self loadEntityComment: [entity_classes_i objectAtIndex: lastSelected]]; [entity_browser_i loadColumnZero]; - [[entity_browser_i matrixInColumn:0] selectCellAt:lastSelected :0]; + [[entity_browser_i matrixInColumn: 0] selectCellAtRow: lastSelected column: 0]; + + [entity_browser_i setDoubleAction: @selector (doubleClickEntity:)]; - [entity_browser_i setDoubleAction: @selector(doubleClickEntity:)]; - return self; } -- selectEntity: sender +- (id) selectEntity: sender { - id matr; - + id matr; + matr = [sender matrixInColumn: 0]; lastSelected = [matr selectedRow]; - [self loadEntityComment:[entity_classes_i objectAt:lastSelected]]; + [self loadEntityComment: [entity_classes_i objectAtIndex: lastSelected]]; [quakeed_i makeFirstResponder: quakeed_i]; - + return self; } -- doubleClickEntity: sender +- (id) doubleClickEntity: sender { [map_i makeEntity: sender]; [quakeed_i makeFirstResponder: quakeed_i]; return self; } -- (char *)spawnName +- (const char *) spawnName { - return [[entity_classes_i objectAt:lastSelected] classname]; + return [[entity_classes_i objectAtIndex: lastSelected] classname]; } - -// -// Flush entity classes & reload them! -// -- reloadEntityClasses: sender +// Flush entity classes & reload them! +- (id) reloadEntityClasses: sender { - EntityClass *ent; - char *path; - - path = (char *)[prog_path_i stringValue]; - if (!path || !path[0]) - { + EntityClass *ent; + NSString *path; + + path = [prog_path_i stringValue]; + if (!path || ![path length]) { path = [project_i getProgDirectory]; [prog_path_i setStringValue: path]; } - - // Free all entity info in memory... - [entity_classes_i freeObjects]; - [entity_classes_i free]; - - // Now, RELOAD! - [[EntityClassList alloc] initForSourceDirectory: path]; + // Free all entity info in memory... + [entity_classes_i removeAllObjects]; + [entity_classes_i release]; + + // Now, RELOAD! + [[EntityClassList alloc] initForSourceDirectory: [path cString]]; lastSelected = 0; - ent = [entity_classes_i objectAt:lastSelected]; - [self loadEntityComment:[entity_classes_i objectAt:lastSelected]]; + ent = [entity_classes_i objectAtIndex: lastSelected]; + [self loadEntityComment: [entity_classes_i objectAtIndex: lastSelected]]; [entity_browser_i loadColumnZero]; - [[entity_browser_i matrixInColumn:0] selectCellAt:lastSelected :0]; + [[entity_browser_i matrixInColumn: 0] selectCellAtRow: lastSelected column: 0]; + + [self newCurrentEntity]; // in case flags changed - [self newCurrentEntity]; // in case flags changed - return self; } - -- selectClass: (char *)class +- (id) selectClass: (const char *)class { - id classent; - - classent = [entity_classes_i classForName:class]; + id classent; + + classent = [entity_classes_i classForName: class]; if (!classent) return self; - lastSelected = [entity_classes_i indexOf: classent]; - + lastSelected = [entity_classes_i indexOfObject: classent]; + if (lastSelected < 0) lastSelected = 0; - - [self loadEntityComment:classent]; - [[entity_browser_i matrixInColumn:0] selectCellAt:lastSelected :0]; - [[entity_browser_i matrixInColumn:0] scrollCellToVisible:lastSelected :0]; + [self loadEntityComment: classent]; + [[entity_browser_i matrixInColumn: 0] selectCellAtRow: lastSelected column: 0]; + [[entity_browser_i matrixInColumn: 0] scrollCellToVisibleAtRow: lastSelected + column: 0]; return self; } - -- newCurrentEntity +- (id) newCurrentEntity { - id ent, classent, cell; - char *classname; - int r, c; - char *flagname; - int flags; - + id ent, classent, cell; + const char *classname; + int r, c; + const char *flagname; + int flags; + ent = [map_i currentEntity]; classname = [ent valueForQKey: "classname"]; - if (ent != [map_i objectAt: 0]) - [self selectClass: classname]; // don't reset for world - classent = [entity_classes_i classForName:classname]; + if (ent != [map_i objectAtIndex: 0]) + [self selectClass: classname]; // don't reset for world + classent = [entity_classes_i classForName: classname]; flagname = [ent valueForQKey: "spawnflags"]; if (!flagname) flags = 0; else - flags = atoi(flagname); - - [flags_i setAutodisplay: NO]; - for (r=0 ; r<4 ; r++) - for (c=0 ; c<3 ; c++) - { - cell = [flags_i cellAt: r : c]; - if (c < 2) - { - flagname = [classent flagName: c*4 + r]; - [cell setTitle: flagname]; + flags = atoi (flagname); + + // [flags_i setAutodisplay:NO]; + for (r = 0; r < 4; r++) { + for (c = 0; c < 3; c++) { + cell = [flags_i cellAtRow: r column: c]; + if (c < 2) { + flagname = [classent flagName: c * 4 + r]; + [cell setTitle: [NSString stringWithCString: flagname]]; } - [cell setIntValue: (flags & (1<< ((c*4)+r)) ) > 0]; + [cell setIntValue: (flags & (1 << ((c * 4) + r))) > 0]; } - [flags_i setAutodisplay: YES]; + } + // [flags_i setAutodisplay:YES]; [flags_i display]; - -// [keyInput_i setStringValue: ""]; -// [valueInput_i setStringValue: ""]; + +// [keyInput_i setStringValue: ""]; +// [valueInput_i setStringValue: ""]; [keypairview_i calcViewSize]; [keypairview_i display]; - + [quakeed_i makeFirstResponder: quakeed_i]; return self; } -// -// Clicked in the Keypair view - set as selected -// -- setSelectedKey:(epair_t *)ep; +// Clicked in the Keypair view - set as selected +- (id) setSelectedKey: (epair_t *)ep; { - [keyInput_i setStringValue:ep->key]; - [valueInput_i setStringValue:ep->value]; - [valueInput_i selectText:self]; + [keyInput_i setStringValue: [NSString stringWithCString: ep->key]]; + [valueInput_i setStringValue: [NSString stringWithCString: ep->value]]; + [valueInput_i selectText: self]; return self; } -- clearInputs +- (id) clearInputs { -// [keyInput_i setStringValue: ""]; -// [valueInput_i setStringValue: ""]; - +// [keyInput_i setStringValue: ""]; +// [valueInput_i setStringValue: ""]; + [quakeed_i makeFirstResponder: quakeed_i]; return self; } -// -// Action methods -// +// Action methods --addPair:sender +- (id) addPair: sender { - char *key, *value; - - key = (char *)[keyInput_i stringValue]; - value = (char *)[valueInput_i stringValue]; - - [ [map_i currentEntity] setKey: key toValue: value ]; + const char *key, *value; + + key = [[keyInput_i stringValue] cString]; + value = [[valueInput_i stringValue] cString]; + + [[map_i currentEntity] setKey: key toValue: value]; [keypairview_i calcViewSize]; [keypairview_i display]; [self clearInputs]; [quakeed_i updateXY]; - + return self; } --delPair:sender +- (id) delPair: sender { [quakeed_i makeFirstResponder: quakeed_i]; - [ [map_i currentEntity] removeKeyPair: (char *)[keyInput_i stringValue] ]; + [[map_i currentEntity] removeKeyPair: [[keyInput_i stringValue] cString]]; [keypairview_i calcViewSize]; [keypairview_i display]; @@ -228,90 +229,78 @@ id things_i; return self; } - -// -// Set the key/value fields to "angle