1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8 
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12 
13 See the GNU General Public License for more details.
14 
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 
19 
20 */
21 // sv_edict.c -- entity dictionary
22 
23 #ifndef CLIENTONLY
24 #include "qwsvdef.h"
25 
26 dprograms_t		*progs;
27 dfunction_t		*pr_functions;
28 char			*pr_strings;
29 ddef_t			*pr_fielddefs;
30 ddef_t			*pr_globaldefs;
31 dstatement_t	*pr_statements;
32 globalvars_t	*pr_global_struct;
33 float			*pr_globals;			// same as pr_global_struct
34 int				pr_edict_size;	// in bytes
35 
36 #define NQ_PROGHEADER_CRC 5927
37 
38 #ifdef WITH_NQPROGS
39 qbool pr_nqprogs;
40 int pr_fieldoffsetpatch[106];
41 int pr_globaloffsetpatch[62];
42 static int pr_globaloffsetpatch_nq[62] = {0,0,0,0,0,666,-4,-4,8,8,
43 8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,
44 8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8, 8,8};
45 #endif
46 
47 static int type_size[8] =
48 {
49 	1,                  // void
50 	1,                  // string_t
51 	1,                  // float
52 	3,                  // vector
53 	1,                  // entity
54 	1,                  // field
55 	1,                  // func_t
56 	1                   // pointer (its an int index)
57 };
58 
59 ddef_t *ED_FieldAtOfs (int ofs);
60 qbool ED_ParseEpair (void *base, ddef_t *key, char *s);
61 
62 #define	MAX_FIELD_LEN	64
63 #define GEFV_CACHESIZE	2
64 
65 typedef struct
66 {
67 	ddef_t	*pcache;
68 	char	field[MAX_FIELD_LEN];
69 }
70 gefv_cache;
71 
72 static gefv_cache	gefvCache[GEFV_CACHESIZE] = {{NULL, ""}, {NULL, ""}};
73 
74 func_t mod_SpectatorConnect, mod_SpectatorThink, mod_SpectatorDisconnect;
75 func_t GE_ClientCommand, GE_PausedTic, GE_ShouldPause;
76 
77 func_t mod_ConsoleCmd, mod_UserCmd;
78 func_t mod_UserInfo_Changed, mod_localinfoChanged;
79 func_t mod_ChatMessage;
80 
81 cvar_t	sv_progsname = {"sv_progsname", "qwprogs"};
82 #ifdef WITH_NQPROGS
83 cvar_t  sv_forcenqprogs = {"sv_forcenqprogs", "0"};
84 #endif
85 
86 /*
87 =================
88 ED_ClearEdict
89 
90 Sets everything to NULL
91 =================
92 */
ED_ClearEdict(edict_t * e)93 void ED_ClearEdict (edict_t *e)
94 {
95 	memset(&e->v, 0, pr_edict_size - sizeof(edict_t) + sizeof(entvars_t));
96 	e->e->lastruntime = 0;
97 	e->e->free = false;
98 	PR_ClearEdict(e);
99 }
100 
101 /*
102 =================
103 ED_Alloc
104 
105 Either finds a free edict, or allocates a new one.
106 Try to avoid reusing an entity that was recently freed, because it
107 can cause the client to think the entity morphed into something else
108 instead of being removed and recreated, which can cause interpolated
109 angles and bad trails.
110 =================
111 */
ED_Alloc(void)112 edict_t *ED_Alloc (void)
113 {
114 	int			i;
115 	edict_t		*e;
116 
117 	for (i = MAX_CLIENTS + 1; i < sv.num_edicts; i++)
118 	{
119 		e = EDICT_NUM(i);
120 		// the first couple seconds of server time can involve a lot of
121 		// freeing and allocating, so relax the replacement policy
122 		if (e->e->free && (e->e->freetime < 2 || sv.time - e->e->freetime > 0.5))
123 		{
124 			ED_ClearEdict(e);
125 			return e;
126 		}
127 	}
128 
129 	if (i == sv.max_edicts)
130 	{
131 		Con_Printf ("WARNING: ED_Alloc: no free edicts [%d]\n", sv.max_edicts);
132 		i--;	// step on whatever is the last edict
133 		e = EDICT_NUM(i);
134 		SV_UnlinkEdict(e);
135 	}
136 	else
137 	{
138 		sv.num_edicts++;
139 		e = EDICT_NUM(i);
140 	}
141 
142 	ED_ClearEdict(e);
143 
144 	return e;
145 }
146 
147 /*
148 =================
149 ED_Free
150 
151 Marks the edict as free
152 FIXME: walk all entities and NULL out references to this entity
153 =================
154 */
ED_Free(edict_t * ed)155 void ED_Free (edict_t *ed)
156 {
157 	SV_UnlinkEdict (ed);		// unlink from world bsp
158 
159 	ed->e->free = true;
160 	ed->v.model = 0;
161 	ed->v.takedamage = 0;
162 	ed->v.modelindex = 0;
163 	ed->v.colormap = 0;
164 	ed->v.skin = 0;
165 	ed->v.frame = 0;
166 	ed->v.health = 0;
167 	ed->v.classname = 0;
168 	VectorClear (ed->v.origin);
169 	VectorClear (ed->v.angles);
170 	ed->v.nextthink = -1;
171 	ed->v.solid = 0;
172 
173 	ed->e->freetime = sv.time;
174 }
175 
176 //===========================================================================
177 
178 /*
179 ============
180 ED_GlobalAtOfs
181 ============
182 */
ED_GlobalAtOfs(int ofs)183 ddef_t *ED_GlobalAtOfs (int ofs)
184 {
185 	ddef_t		*def;
186 	int			i;
187 
188 	for (i=0 ; i<progs->numglobaldefs ; i++)
189 	{
190 		def = &pr_globaldefs[i];
191 		if (def->ofs == ofs)
192 			return def;
193 	}
194 	return NULL;
195 }
196 
197 /*
198 ============
199 ED_FieldAtOfs
200 ============
201 */
ED_FieldAtOfs(int ofs)202 ddef_t *ED_FieldAtOfs (int ofs)
203 {
204 	ddef_t		*def;
205 	int			i;
206 
207 	for (i=0 ; i<progs->numfielddefs ; i++)
208 	{
209 		def = &pr_fielddefs[i];
210 		if (def->ofs == ofs)
211 			return def;
212 	}
213 	return NULL;
214 }
215 
216 /*
217 ============
218 ED_FindField
219 ============
220 */
ED_FindField(char * name)221 ddef_t *ED_FindField (char *name)
222 {
223 	ddef_t		*def;
224 	int			i;
225 
226 	for (i=0 ; i<progs->numfielddefs ; i++)
227 	{
228 		def = &pr_fielddefs[i];
229 		if (!strcmp(PR1_GetString(def->s_name),name) )
230 			return def;
231 	}
232 	return NULL;
233 }
234 
235 
236 /*
237 ============
238 ED_FindGlobal
239 ============
240 */
ED_FindGlobal(char * name)241 ddef_t *ED_FindGlobal (char *name)
242 {
243 	ddef_t		*def;
244 	int			i;
245 
246 	for (i=0 ; i<progs->numglobaldefs ; i++)
247 	{
248 		def = &pr_globaldefs[i];
249 		if (!strcmp(PR1_GetString(def->s_name),name) )
250 			return def;
251 	}
252 	return NULL;
253 }
254 
255 /*
256 ============
257 ED1_FindFieldOffset
258 ============
259 */
ED1_FindFieldOffset(char * field)260 int ED1_FindFieldOffset (char *field)
261 {
262 	ddef_t *d;
263 	d = ED_FindField(field);
264 	if (!d)
265 		return 0;
266 	return d->ofs*4;
267 }
268 
269 /*
270 ============
271 ED_FindFunction
272 ============
273 */
ED_FindFunction(char * name)274 dfunction_t *ED_FindFunction (char *name)
275 {
276 	register dfunction_t		*func;
277 	register int				i;
278 
279 	if (!progs)
280 		return NULL;
281 
282 	for (i=0 ; i<progs->numfunctions ; i++)
283 	{
284 		func = &pr_functions[i];
285 		if (!strcmp(PR1_GetString(func->s_name), name))
286 			return func;
287 	}
288 	return NULL;
289 }
290 
ED_FindFunctionOffset(char * name)291 func_t ED_FindFunctionOffset (char *name)
292 {
293 	dfunction_t *func;
294 
295 	func = ED_FindFunction (name);
296 	return func ? (func_t)(func - pr_functions) : 0;
297 }
298 
PR1_GetEdictFieldValue(edict_t * ed,char * field)299 eval_t *PR1_GetEdictFieldValue(edict_t *ed, char *field)
300 {
301 	ddef_t			*def = NULL;
302 	int				i;
303 	static int		rep = 0;
304 
305 	for (i=0 ; i<GEFV_CACHESIZE ; i++)
306 	{
307 		if (!strcmp(field, gefvCache[i].field))
308 		{
309 			def = gefvCache[i].pcache;
310 			goto Done;
311 		}
312 	}
313 
314 	def = ED_FindField (field);
315 
316 	if (strlen(field) < MAX_FIELD_LEN)
317 	{
318 		gefvCache[rep].pcache = def;
319 		strlcpy (gefvCache[rep].field, field, MAX_FIELD_LEN);
320 		rep ^= 1;
321 	}
322 
323 Done:
324 	if (!def)
325 		return NULL;
326 
327 	return (eval_t *)((char *)&ed->v + def->ofs*4);
328 }
329 
330 /*
331 ============
332 PR_ValueString
333 
334 Returns a string describing *data in a type specific manner
335 =============
336 */
PR_ValueString(etype_t type,eval_t * val)337 char *PR_ValueString (etype_t type, eval_t *val)
338 {
339 	static char	line[256];
340 	ddef_t		*def;
341 	dfunction_t	*f;
342 
343 	type = (etype_t) (type & ~DEF_SAVEGLOBAL);
344 
345 	switch (type)
346 	{
347 	case ev_string:
348 		snprintf (line, sizeof(line), "%s", PR1_GetString(val->string));
349 		break;
350 	case ev_entity:
351 		snprintf (line, sizeof(line), "entity %i", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict)) );
352 		break;
353 	case ev_function:
354 		f = pr_functions + val->function;
355 		snprintf (line, sizeof(line), "%s()", PR1_GetString(f->s_name));
356 		break;
357 	case ev_field:
358 		def = ED_FieldAtOfs ( val->_int );
359 		snprintf (line, sizeof(line), ".%s", PR1_GetString(def->s_name));
360 		break;
361 	case ev_void:
362 		snprintf (line, sizeof(line), "void");
363 		break;
364 	case ev_float:
365 		snprintf (line, sizeof(line), "%5.1f", val->_float);
366 		break;
367 	case ev_vector:
368 		snprintf (line, sizeof(line), "'%5.1f %5.1f %5.1f'", val->vector[0], val->vector[1], val->vector[2]);
369 		break;
370 	case ev_pointer:
371 		snprintf (line, sizeof(line), "pointer");
372 		break;
373 	default:
374 		snprintf (line, sizeof(line), "bad type %i", type);
375 		break;
376 	}
377 
378 	return line;
379 }
380 
381 /*
382 ============
383 PR_UglyValueString
384 
385 Returns a string describing *data in a type specific manner
386 Easier to parse than PR_ValueString
387 =============
388 */
PR_UglyValueString(etype_t type,eval_t * val)389 char *PR_UglyValueString (etype_t type, eval_t *val)
390 {
391 	static char	line[256];
392 	ddef_t		*def;
393 	dfunction_t	*f;
394 
395 	type = (etype_t) (type & ~DEF_SAVEGLOBAL);
396 
397 	switch (type)
398 	{
399 	case ev_string:
400 		snprintf (line, sizeof(line), "%s", PR1_GetString(val->string));
401 		break;
402 	case ev_entity:
403 		snprintf (line, sizeof(line), "%i", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict)));
404 		break;
405 	case ev_function:
406 		f = pr_functions + val->function;
407 		snprintf (line, sizeof(line), "%s", PR1_GetString(f->s_name));
408 		break;
409 	case ev_field:
410 		def = ED_FieldAtOfs ( val->_int );
411 		snprintf (line, sizeof(line), "%s", PR1_GetString(def->s_name));
412 		break;
413 	case ev_void:
414 		snprintf (line, sizeof(line), "void");
415 		break;
416 	case ev_float:
417 		snprintf (line, sizeof(line), "%f", val->_float);
418 		break;
419 	case ev_vector:
420 		snprintf (line, sizeof(line), "%f %f %f", val->vector[0], val->vector[1], val->vector[2]);
421 		break;
422 	default:
423 		snprintf (line, sizeof(line), "bad type %i", type);
424 		break;
425 	}
426 
427 	return line;
428 }
429 
430 /*
431 ============
432 PR_GlobalString
433 
434 Returns a string with a description and the contents of a global,
435 padded to 20 field width
436 ============
437 */
PR_GlobalString(int ofs)438 char *PR_GlobalString (int ofs)
439 {
440 	char	*s;
441 	int		i;
442 	ddef_t	*def;
443 	void	*val;
444 	static char	line[128];
445 
446 	val = (void *)&pr_globals[ofs];
447 	def = ED_GlobalAtOfs(ofs);
448 	if (!def)
449 	{
450 		snprintf (line, sizeof(line), "%i(?""?""?)", ofs); // separate the ?'s to shut up gcc
451 	}
452 	else
453 	{
454 		s = PR_ValueString ((etype_t)def->type, (eval_t *) val);
455 		snprintf (line, sizeof(line), "%i(%s)%s", ofs, PR1_GetString(def->s_name), s);
456 	}
457 
458 	i = strlen(line);
459 	for ( ; i<20 ; i++)
460 		strlcat (line, " ", sizeof(line));
461 	strlcat (line, " ", sizeof(line));
462 
463 	return line;
464 }
465 
PR_GlobalStringNoContents(int ofs)466 char *PR_GlobalStringNoContents (int ofs)
467 {
468 	int		i;
469 	ddef_t	*def;
470 	static char	line[128];
471 
472 	def = ED_GlobalAtOfs(ofs);
473 	if (!def)
474 		snprintf (line, sizeof(line), "%i(?""?""?)", ofs); // separate the ?'s to shut up gcc
475 	else
476 		snprintf (line, sizeof(line), "%i(%s)", ofs, PR1_GetString(def->s_name));
477 
478 	i = strlen(line);
479 	for ( ; i<20 ; i++)
480 		strlcat (line, " ", sizeof(line));
481 	strlcat (line, " ", sizeof(line));
482 
483 	return line;
484 }
485 
486 
487 /*
488 =============
489 ED_Print
490 
491 For debugging
492 =============
493 */
ED_Print(edict_t * ed)494 void ED_Print (edict_t *ed)
495 {
496 	int		l;
497 	ddef_t	*d;
498 	int		*v;
499 	int		i, j;
500 	char	*name;
501 	int		type;
502 
503 	if (ed->e->free)
504 	{
505 		Con_Printf ("FREE\n");
506 		return;
507 	}
508 
509 	for (i=1 ; i<progs->numfielddefs ; i++)
510 	{
511 		d = &pr_fielddefs[i];
512 		name = PR1_GetString(d->s_name);
513 		if (name[strlen(name)-2] == '_')
514 			continue;	// skip _x, _y, _z vars
515 
516 		v = (int *)((char *)&ed->v + d->ofs*4);
517 
518 		// if the value is still all 0, skip the field
519 		type = d->type & ~DEF_SAVEGLOBAL;
520 
521 		for (j = 0; j < type_size[type]; j++) {
522 			if (v[j]) {
523 				break;
524 			}
525 		}
526 		if (j == type_size[type]) {
527 			continue;
528 		}
529 
530 		Con_Printf ("%s",name);
531 		l = strlen (name);
532 		while (l++ < 15) {
533 			Con_Printf(" ");
534 		}
535 
536 		Con_Printf ("%s\n", PR_ValueString((etype_t)d->type, (eval_t *)v));
537 	}
538 }
539 
540 /*
541 =============
542 ED_Write
543 
544 For savegames
545 =============
546 */
ED_Write(FILE * f,edict_t * ed)547 void ED_Write (FILE *f, edict_t *ed)
548 {
549 	ddef_t	*d;
550 	int		*v;
551 	int		i, j;
552 	char	*name;
553 	int		type;
554 
555 	fprintf (f, "{\n");
556 
557 	if (ed->e->free)
558 	{
559 		fprintf (f, "}\n");
560 		return;
561 	}
562 
563 	for (i=1 ; i<progs->numfielddefs ; i++)
564 	{
565 		d = &pr_fielddefs[i];
566 		name = PR1_GetString(d->s_name);
567 		if (name[strlen(name)-2] == '_')
568 			continue;	// skip _x, _y, _z vars
569 
570 		v = (int *)((char *)&ed->v + d->ofs*4);
571 
572 		// if the value is still all 0, skip the field
573 		type = d->type & ~DEF_SAVEGLOBAL;
574 		for (j=0 ; j<type_size[type] ; j++)
575 			if (v[j])
576 				break;
577 		if (j == type_size[type])
578 			continue;
579 
580 		fprintf (f,"\"%s\" ",name);
581 		fprintf (f,"\"%s\"\n", PR_UglyValueString((etype_t)d->type, (eval_t *)v));
582 	}
583 
584 	fprintf (f, "}\n");
585 }
586 
ED_PrintNum(int ent)587 void ED_PrintNum (int ent)
588 {
589 	ED_Print (EDICT_NUM(ent));
590 }
591 
592 /*
593 =============
594 ED_PrintEdicts
595 
596 For debugging, prints all the entities in the current server
597 =============
598 */
ED_PrintEdicts(void)599 void ED_PrintEdicts (void)
600 {
601 	int		i;
602 
603 	Con_Printf ("%i entities\n", sv.num_edicts);
604 	for (i=0 ; i<sv.num_edicts ; i++)
605 	{
606 		Con_Printf ("\nEDICT %i:\n",i);
607 		ED_PrintNum (i);
608 	}
609 }
610 
611 /*
612 =============
613 ED_PrintEdict_f
614 
615 For debugging, prints a single edicy
616 =============
617 */
ED_PrintEdict_f(void)618 void ED_PrintEdict_f (void)
619 {
620 	int		i;
621 
622 	if (Cmd_Argc () != 2)
623 	{
624 		Con_Printf ("\nUsage:\nedict [num]\n");
625 		return;
626 	}
627 
628 	i = Q_atoi (Cmd_Argv(1));
629 	if(i < 0 || i >= sv.num_edicts)
630 	{
631 		Con_Printf ("\nNo such edict: %i\n", i);
632 		return;
633 	}
634 
635 	Con_Printf ("\n EDICT %i:\n",i);
636 	ED_PrintNum (i);
637 }
638 
639 /*
640 =============
641 ED_Count
642 
643 For debugging
644 =============
645 */
ED_Count(void)646 void ED_Count (void)
647 {
648 	int		i;
649 	edict_t	*ent;
650 	int		active, models, solid, step;
651 
652 	active = models = solid = step = 0;
653 	for (i=0 ; i<sv.num_edicts ; i++)
654 	{
655 		ent = EDICT_NUM(i);
656 		if (ent->e->free)
657 			continue;
658 		active++;
659 		if (ent->v.solid)
660 			solid++;
661 		if (ent->v.model)
662 			models++;
663 		if (ent->v.movetype == MOVETYPE_STEP)
664 			step++;
665 	}
666 
667 	Con_Printf ("num_edicts:%3i\n", sv.num_edicts);
668 	Con_Printf ("active    :%3i\n", active);
669 	Con_Printf ("view      :%3i\n", models);
670 	Con_Printf ("touch     :%3i\n", solid);
671 	Con_Printf ("step      :%3i\n", step);
672 
673 }
674 
675 /*
676 ==============================================================================
677 
678 					ARCHIVING GLOBALS
679 
680 FIXME: need to tag constants, doesn't really work
681 ==============================================================================
682 */
683 
684 /*
685 =============
686 ED_WriteGlobals
687 =============
688 */
ED_WriteGlobals(FILE * f)689 void ED_WriteGlobals (FILE *f)
690 {
691 	ddef_t		*def;
692 	int			i;
693 	char		*name;
694 	int			type;
695 
696 	fprintf (f,"{\n");
697 	for (i=0 ; i<progs->numglobaldefs ; i++)
698 	{
699 		def = &pr_globaldefs[i];
700 		type = def->type;
701 		if ( !(def->type & DEF_SAVEGLOBAL) )
702 			continue;
703 		type &= ~DEF_SAVEGLOBAL;
704 
705 		if (type != ev_string
706 		        && type != ev_float
707 		        && type != ev_entity)
708 			continue;
709 
710 		name = PR1_GetString(def->s_name);
711 		fprintf (f,"\"%s\" ", name);
712 		fprintf (f,"\"%s\"\n", PR_UglyValueString((etype_t)type, (eval_t *)&pr_globals[def->ofs]));
713 	}
714 	fprintf (f,"}\n");
715 }
716 
717 /*
718 =============
719 ED_ParseGlobals
720 =============
721 */
ED_ParseGlobals(const char * data)722 void ED_ParseGlobals (const char *data)
723 {
724 	char	keyname[64];
725 	ddef_t	*key;
726 
727 	while (1)
728 	{
729 		// parse key
730 		data = COM_Parse (data);
731 		if (com_token[0] == '}')
732 			break;
733 		if (!data)
734 			SV_Error ("ED_ParseEntity: EOF without closing brace");
735 
736 		strlcpy (keyname, com_token, sizeof(keyname));
737 
738 		// parse value
739 		data = COM_Parse (data);
740 		if (!data)
741 			SV_Error ("ED_ParseEntity: EOF without closing brace");
742 
743 		if (com_token[0] == '}')
744 			SV_Error ("ED_ParseEntity: closing brace without data");
745 
746 		key = ED_FindGlobal (keyname);
747 		if (!key)
748 		{
749 			Con_Printf ("%s is not a global\n", keyname);
750 			continue;
751 		}
752 
753 		if (!ED_ParseEpair ((void *)pr_globals, key, com_token))
754 			SV_Error ("ED_ParseGlobals: parse error");
755 	}
756 }
757 
758 //============================================================================
759 
760 
761 /*
762 =============
763 ED_NewString
764 =============
765 */
ED_NewString(char * string)766 char *ED_NewString (char *string)
767 {
768 	char	*nuw, *new_p;
769 	int		i,l;
770 
771 	l = strlen(string) + 1;
772 	nuw = (char *) Hunk_Alloc (l);
773 	new_p = nuw;
774 
775 	for (i=0 ; i< l ; i++)
776 	{
777 		if (string[i] == '\\' && i < l-1)
778 		{
779 			i++;
780 			if (string[i] == 'n')
781 				*new_p++ = '\n';
782 			else
783 				*new_p++ = '\\';
784 		}
785 		else
786 			*new_p++ = string[i];
787 	}
788 
789 	return nuw;
790 }
791 
792 
793 /*
794 =============
795 ED_ParseEval
796 
797 Can parse either fields or globals
798 returns false if error
799 =============
800 */
ED_ParseEpair(void * base,ddef_t * key,char * s)801 qbool ED_ParseEpair (void *base, ddef_t *key, char *s)
802 {
803 	int		i;
804 	char	string[128];
805 	ddef_t	*def;
806 	char	*v, *w;
807 	void	*d;
808 	dfunction_t	*func;
809 
810 	d = (void *)((int *)base + key->ofs);
811 
812 	switch (key->type & ~DEF_SAVEGLOBAL)
813 	{
814 	case ev_string:
815 		PR1_SetString((string_t *)d, ED_NewString (s));
816 		break;
817 
818 	case ev_float:
819 		*(float *)d = Q_atof (s);
820 		break;
821 
822 	case ev_vector:
823 		strlcpy (string, s, sizeof(string));
824 		v = string;
825 		w = string;
826 		for (i=0 ; i<3 ; i++)
827 		{
828 			while (*v && *v != ' ')
829 				v++;
830 			*v = 0;
831 			((float *)d)[i] = Q_atof (w);
832 			w = v = v+1;
833 		}
834 		break;
835 
836 	case ev_entity:
837 		*(int *)d = EDICT_TO_PROG(EDICT_NUM(Q_atoi (s)));
838 		break;
839 
840 	case ev_field:
841 		def = ED_FindField (s);
842 		if (!def)
843 		{
844 			Con_Printf ("Can't find field %s\n", s);
845 			return false;
846 		}
847 		*(int *)d = G_INT(def->ofs);
848 		break;
849 
850 	case ev_function:
851 		func = ED_FindFunction (s);
852 		if (!func)
853 		{
854 			Con_Printf ("Can't find function %s\n", s);
855 			return false;
856 		}
857 		*(func_t *)d = func - pr_functions;
858 		break;
859 
860 	default:
861 		break;
862 	}
863 	return true;
864 }
865 
866 /*
867 ====================
868 ED_ParseEdict
869 
870 Parses an edict out of the given string, returning the new position
871 ed should be a properly initialized empty edict.
872 Used for initial level load and for savegames.
873 ====================
874 */
ED_ParseEdict(const char * data,edict_t * ent)875 const char *ED_ParseEdict (const char *data, edict_t *ent)
876 {
877 	ddef_t		*key;
878 	qbool		anglehack;
879 	qbool		init;
880 	char		keyname[256];
881 
882 	init = false;
883 
884 	// go through all the dictionary pairs
885 	while (1)
886 	{
887 		// parse key
888 		data = COM_Parse (data);
889 		if (com_token[0] == '}')
890 			break;
891 		if (!data)
892 			SV_Error ("ED_ParseEntity: EOF without closing brace");
893 
894 		// anglehack is to allow QuakeEd to write single scalar angles
895 		// and allow them to be turned into vectors. (FIXME...)
896 		if (!strcmp(com_token, "angle"))
897 		{
898 			strlcpy (com_token, "angles", MAX_COM_TOKEN);
899 			anglehack = true;
900 		}
901 		else
902 			anglehack = false;
903 
904 		// FIXME: change light to _light to get rid of this hack
905 		if (!strcmp(com_token, "light"))
906 			strlcpy (com_token, "light_lev", MAX_COM_TOKEN);	// hack for single light def
907 
908 		strlcpy (keyname, com_token, sizeof(keyname));
909 
910 		// parse value
911 		data = COM_Parse (data);
912 		if (!data)
913 			SV_Error ("ED_ParseEntity: EOF without closing brace");
914 
915 		if (com_token[0] == '}')
916 			SV_Error ("ED_ParseEntity: closing brace without data");
917 
918 		init = true;
919 
920 		// keynames with a leading underscore are used for utility comments,
921 		// and are immediately discarded by quake
922 		if (keyname[0] == '_')
923 			continue;
924 
925 		key = ED_FindField (keyname);
926 		if (!key)
927 		{
928 			Con_Printf ("%s is not a field\n", keyname);
929 			continue;
930 		}
931 
932 		if (anglehack)
933 		{
934 			char	temp[32];
935 			strlcpy (temp, com_token, sizeof(temp));
936 			snprintf (com_token, MAX_COM_TOKEN, "0 %s 0", temp);
937 		}
938 
939 		if (!ED_ParseEpair ((void *)&ent->v, key, com_token))
940 			SV_Error ("ED_ParseEdict: parse error");
941 	}
942 
943 	if (!init)
944 		ent->e->free = true;
945 
946 	return data;
947 }
948 
949 
950 /*
951 ================
952 ED_LoadFromFile
953 
954 The entities are directly placed in the array, rather than allocated with
955 ED_Alloc, because otherwise an error loading the map would have entity
956 number references out of order.
957 
958 Creates a server's entity / program execution context by
959 parsing textual entity definitions out of an ent file.
960 
961 Used for both fresh maps and savegame loads.  A fresh map would also need
962 to call ED_CallSpawnFunctions () to let the objects initialize themselves.
963 ================
964 */
ED_LoadFromFile(const char * data)965 void ED_LoadFromFile (const char *data)
966 {
967 	edict_t		*ent;
968 	int			inhibit;
969 	dfunction_t	*func;
970 
971 	ent = NULL;
972 	inhibit = 0;
973 	pr_global_struct->time = sv.time;
974 
975 	// parse ents
976 	while (1)
977 	{
978 		// parse the opening brace
979 		data = COM_Parse (data);
980 		if (!data)
981 			break;
982 		if (com_token[0] != '{')
983 			SV_Error ("ED_LoadFromFile: found %s when expecting {",com_token);
984 
985 		if (!ent)
986 			ent = EDICT_NUM(0);
987 		else
988 			ent = ED_Alloc ();
989 		data = ED_ParseEdict (data, ent);
990 
991 		// remove things from different skill levels or deathmatch
992 		if ((int)deathmatch.value)
993 		{
994 			if (((int)ent->v.spawnflags & SPAWNFLAG_NOT_DEATHMATCH))
995 			{
996 				ED_Free (ent);
997 				inhibit++;
998 				continue;
999 			}
1000 		}
1001 		else if ((current_skill == 0 && ((int)ent->v.spawnflags & SPAWNFLAG_NOT_EASY))
1002 		         || (current_skill == 1 && ((int)ent->v.spawnflags & SPAWNFLAG_NOT_MEDIUM))
1003 		         || (current_skill >= 2 && ((int)ent->v.spawnflags & SPAWNFLAG_NOT_HARD)) )
1004 		{
1005 			ED_Free (ent);
1006 			inhibit++;
1007 			continue;
1008 		}
1009 
1010 		//
1011 		// immediately call spawn function
1012 		//
1013 		if (!ent->v.classname)
1014 		{
1015 			Con_Printf ("No classname for:\n");
1016 			ED_Print (ent);
1017 			ED_Free (ent);
1018 			continue;
1019 		}
1020 
1021 		// look for the spawn function
1022 		func = ED_FindFunction ( PR1_GetString(ent->v.classname) );
1023 
1024 		if (!func)
1025 		{
1026 			Con_Printf ("No spawn function for:\n");
1027 			ED_Print (ent);
1028 			ED_Free (ent);
1029 			continue;
1030 		}
1031 
1032 		pr_global_struct->self = EDICT_TO_PROG(ent);
1033 		PR_ExecuteProgram (func - pr_functions);
1034 		SV_FlushSignon();
1035 	}
1036 
1037 	Con_DPrintf ("%i entities inhibited\n", inhibit);
1038 }
1039 extern redirect_t	sv_redirected;
PR_ConsoleCmd(void)1040 qbool PR_ConsoleCmd(void)
1041 {
1042 	if (mod_ConsoleCmd)
1043 	{
1044 		if (sv_redirected != RD_MOD)
1045 		{
1046 			pr_global_struct->time = sv.time;
1047 			pr_global_struct->self = 0;
1048 		}
1049 		PR_ExecuteProgram (mod_ConsoleCmd);
1050 		return (int) G_FLOAT(OFS_RETURN);
1051 	}
1052 
1053 	return false;
1054 }
1055 
PR1_ClientCmd(void)1056 qbool PR1_ClientCmd(void)
1057 {
1058 	// ZQ_CLIENTCOMMAND extension
1059 	if (GE_ClientCommand)
1060 	{
1061 		static char cmd_copy[128], args_copy[1024] /* Ouch! */;
1062 		strlcpy (cmd_copy, Cmd_Argv(0), sizeof(cmd_copy));
1063 		strlcpy (args_copy, Cmd_Args(), sizeof(args_copy));
1064 		PR1_SetString (&((int *)pr_globals)[OFS_PARM0], cmd_copy);
1065 		PR1_SetString (&((int *)pr_globals)[OFS_PARM1], args_copy);
1066 		PR_ExecuteProgram (GE_ClientCommand);
1067 		return G_FLOAT(OFS_RETURN) ? true : false;
1068 	}
1069 
1070 	if (mod_UserCmd)
1071 	{
1072 		static char cmd_copy[128];
1073 		strlcpy (cmd_copy, Cmd_Argv(0), sizeof(cmd_copy));
1074 		PR1_SetString (&((int *)pr_globals)[OFS_PARM0], cmd_copy);
1075 
1076 		PR_ExecuteProgram (mod_UserCmd);
1077 		return G_FLOAT(OFS_RETURN) ? true : false;
1078 	}
1079 
1080 	return false;
1081 }
1082 
1083 
1084 /*
1085 ===============
1086 PR1_LoadProgs
1087 ===============
1088 */
1089 void PF_clear_strtbl(void);
1090 
1091 #ifdef WITH_NQPROGS
PR_InitPatchTables(void)1092 void PR_InitPatchTables (void)
1093 {
1094 	int i;
1095 
1096 	if (pr_nqprogs)
1097 	{
1098 		memcpy (pr_globaloffsetpatch, pr_globaloffsetpatch_nq, sizeof(pr_globaloffsetpatch));
1099 		for (i = 0; i < 106; i++)
1100 		{
1101 			pr_fieldoffsetpatch[i] = (i < 8) ? i : (i < 25) ? i + 1 :
1102 				(i < 28) ? i + (102 - 25) : (i < 73) ? i - 2 :
1103 				(i < 74) ? i + (105 - 73) : (i < 105) ? i - 3 : /* (i == 105) */ 8;
1104 		}
1105 
1106 		for (i=0 ; i<progs->numfielddefs ; i++)
1107 			pr_fielddefs[i].ofs = PR_FIELDOFS(pr_fielddefs[i].ofs);
1108 	}
1109 	else
1110 	{
1111 		memset (pr_globaloffsetpatch, 0, sizeof(pr_globaloffsetpatch));
1112 
1113 		for (i = 0; i < 106; i++)
1114 			pr_fieldoffsetpatch[i] = i;
1115 	}
1116 }
1117 #endif
1118 
PR1_LoadProgs(void)1119 void PR1_LoadProgs (void)
1120 {
1121 	int	i;
1122 	char num[32];
1123 	int filesize;
1124 
1125 	// flush the non-C variable lookup cache
1126 	for (i = 0; i < GEFV_CACHESIZE; i++)
1127 		gefvCache[i].field[0] = 0;
1128 
1129 	// clear pr_newstrtbl
1130 	PF_clear_strtbl();
1131 
1132 	progs = NULL;
1133 #ifdef WITH_NQPROGS
1134 	pr_nqprogs = false;
1135 
1136 	// forced load of NQ progs.
1137 	if (!progs && Cvar_Value("sv_forcenqprogs") && (progs = (dprograms_t *)FS_LoadHunkFile ("progs.dat", &filesize)))
1138 		pr_nqprogs = true;
1139 #endif
1140 
1141 	if (!progs)
1142 	{
1143 		char name[MAX_OSPATH];
1144 		snprintf(name, sizeof(name), "%s.dat", sv_progsname.string);
1145 		progs = (dprograms_t *)FS_LoadHunkFile (name, &filesize);
1146 	}
1147 	if (!progs)
1148 		progs = (dprograms_t *)FS_LoadHunkFile ("qwprogs.dat", &filesize);
1149 	if (!progs)
1150 		progs = (dprograms_t *)FS_LoadHunkFile ("spprogs.dat", &filesize);
1151 #ifdef WITH_NQPROGS
1152 	// low priority load of NQ progs.
1153 	if (!progs && (progs = (dprograms_t *)FS_LoadHunkFile ("progs.dat", &filesize)))
1154 		pr_nqprogs = true;
1155 #endif
1156 
1157 	if (!progs)
1158 		SV_Error ("PR1_LoadProgs: couldn't load progs.dat");
1159 	Con_DPrintf ("Programs occupy %iK.\n", filesize/1024);
1160 
1161 #ifdef WITH_NQPROGS
1162 	if (pr_nqprogs)
1163 		Con_DPrintf ("NQ progs.\n");
1164 #endif
1165 
1166 	// add prog crc to the serverinfo
1167 	snprintf (num, sizeof(num), "%i", CRC_Block ((byte *)progs, filesize));
1168 	Info_SetValueForStarKey (svs.info, "*progs", num, MAX_SERVERINFO_STRING);
1169 
1170 	// byte swap the header
1171 	for (i = 0; i < (int) sizeof(*progs) / 4 ; i++)
1172 		((int *)progs)[i] = LittleLong ( ((int *)progs)[i] );
1173 
1174 	if (progs->version != PROG_VERSION)
1175 		SV_Error ("qwprogs.dat has wrong version number (%i should be %i)", progs->version, PROG_VERSION);
1176 	if (progs->crc != (pr_nqprogs ? NQ_PROGHEADER_CRC : PROGHEADER_CRC))
1177 		SV_Error ("You must have the qwprogs.dat from QuakeWorld installed");
1178 
1179 	pr_functions = (dfunction_t *)((byte *)progs + progs->ofs_functions);
1180 	pr_strings = (char *)progs + progs->ofs_strings;
1181 	pr_globaldefs = (ddef_t *)((byte *)progs + progs->ofs_globaldefs);
1182 	pr_fielddefs = (ddef_t *)((byte *)progs + progs->ofs_fielddefs);
1183 	pr_statements = (dstatement_t *)((byte *)progs + progs->ofs_statements);
1184 
1185 	num_prstr = 0;
1186 
1187 	pr_global_struct = (globalvars_t *)((byte *)progs + progs->ofs_globals);
1188 	pr_globals = (float *)pr_global_struct;
1189 
1190 	pr_edict_size = progs->entityfields * 4 + sizeof (edict_t) - sizeof(entvars_t);
1191 
1192 	// byte swap the lumps
1193 	for (i = 0; i < progs->numstatements; i++)
1194 	{
1195 		pr_statements[i].op = LittleShort(pr_statements[i].op);
1196 		pr_statements[i].a = LittleShort(pr_statements[i].a);
1197 		pr_statements[i].b = LittleShort(pr_statements[i].b);
1198 		pr_statements[i].c = LittleShort(pr_statements[i].c);
1199 	}
1200 
1201 	for (i = 0; i < progs->numfunctions; i++)
1202 	{
1203 		pr_functions[i].first_statement = LittleLong (pr_functions[i].first_statement);
1204 		pr_functions[i].parm_start = LittleLong (pr_functions[i].parm_start);
1205 		pr_functions[i].s_name = LittleLong (pr_functions[i].s_name);
1206 		pr_functions[i].s_file = LittleLong (pr_functions[i].s_file);
1207 		pr_functions[i].numparms = LittleLong (pr_functions[i].numparms);
1208 		pr_functions[i].locals = LittleLong (pr_functions[i].locals);
1209 	}
1210 
1211 	for (i = 0; i < progs->numglobaldefs; i++)
1212 	{
1213 		pr_globaldefs[i].type = LittleShort (pr_globaldefs[i].type);
1214 		pr_globaldefs[i].ofs = LittleShort (pr_globaldefs[i].ofs);
1215 		pr_globaldefs[i].s_name = LittleLong (pr_globaldefs[i].s_name);
1216 	}
1217 
1218 	for (i = 0; i < progs->numfielddefs; i++)
1219 	{
1220 		pr_fielddefs[i].type = LittleShort (pr_fielddefs[i].type);
1221 		if (pr_fielddefs[i].type & DEF_SAVEGLOBAL)
1222 			SV_Error ("PR1_LoadProgs: pr_fielddefs[i].type & DEF_SAVEGLOBAL");
1223 		pr_fielddefs[i].ofs = LittleShort (pr_fielddefs[i].ofs);
1224 		pr_fielddefs[i].s_name = LittleLong (pr_fielddefs[i].s_name);
1225 	}
1226 
1227 	for (i = 0; i < progs->numglobals; i++)
1228 		((int *)pr_globals)[i] = LittleLong (((int *)pr_globals)[i]);
1229 
1230 	PR_InitBuiltins();
1231 }
1232 
PR1_InitProg(void)1233 void PR1_InitProg(void)
1234 {
1235 	sv.edicts = (edict_t*) Hunk_AllocName (MAX_EDICTS * pr_edict_size, "edicts");
1236 	sv.max_edicts = MAX_EDICTS;
1237 }
1238 
1239 /*
1240 ===============
1241 PR1_Init
1242 ===============
1243 */
PR1_Init(void)1244 void PR1_Init (void)
1245 {
1246 	Cvar_Register(&sv_progsname);
1247 #ifdef WITH_NQPROGS
1248 	Cvar_Register(&sv_forcenqprogs);
1249 #endif
1250 
1251 	Cmd_AddCommand ("edict", ED_PrintEdict_f);
1252 	Cmd_AddCommand ("edicts", ED_PrintEdicts);
1253 	Cmd_AddCommand ("edictcount", ED_Count);
1254 	Cmd_AddCommand ("profile", PR_Profile_f);
1255 
1256 	memset(pr_newstrtbl, 0, sizeof(pr_newstrtbl));
1257 }
1258 
EDICT_NUM(int n)1259 edict_t *EDICT_NUM(int n)
1260 {
1261 	if (n < 0 || n >= sv.max_edicts)
1262 		SV_Error ("EDICT_NUM: bad number %i", n);
1263 	return (edict_t *)((byte *)sv.edicts+ (n)*pr_edict_size);
1264 }
1265 
NUM_FOR_EDICT(edict_t * e)1266 int NUM_FOR_EDICT(edict_t *e)
1267 {
1268 	int		b;
1269 
1270 	b = (byte *)e - (byte *)sv.edicts;
1271 	b /= pr_edict_size;
1272 
1273 	if (b < 0 || b >= sv.num_edicts)
1274 		SV_Error ("NUM_FOR_EDICT: bad pointer");
1275 
1276 	return b;
1277 }
1278 
1279 #endif // !CLIENTONLY
1280