]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/main.qc
Fix current custom gametype not being kept if gametype vote ends without votes
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / main.qc
1 #include "main.qh"
2
3 #include <common/command/generic.qh>
4 #include <common/constants.qh>
5 #include <common/deathtypes/all.qh>
6 #include <common/debug.qh>
7 #include <common/mapinfo.qh>
8 #include <common/mapobjects/_mod.qh>
9 #include <common/monsters/sv_monsters.qh>
10 #include <common/util.qh>
11 #include <common/vehicles/all.qh>
12 #include <common/weapons/_all.qh>
13 #include <lib/csqcmodel/sv_model.qh>
14 #include <lib/warpzone/common.qh>
15 #include <lib/warpzone/server.qh>
16 #include <server/anticheat.qh>
17 #include <server/bot/api.qh>
18 #include <server/command/common.qh>
19 #include <server/compat/quake3.qh>
20 #include <server/damage.qh>
21 #include <server/gamelog.qh>
22 #include <server/hook.qh>
23 #include <server/ipban.qh>
24 #include <server/mutators/_mod.qh>
25 #include <server/spawnpoints.qh>
26 #include <server/weapons/common.qh>
27 #include <server/weapons/csqcprojectile.qh>
28 #include <server/world.qh>
29
30 void dropclient_do(entity this)
31 {
32         if (this.owner)
33                 dropclient(this.owner);
34         delete(this);
35 }
36
37 /**
38  * Schedules dropclient for a player and returns true;
39  * if dropclient is already scheduled (for that player) it does nothing and returns false.
40  *
41  * NOTE: this function exists only to allow sending a message to the kicked player with
42  * Send_Notification, which doesn't work if called together with dropclient
43  */
44 bool dropclient_schedule(entity this)
45 {
46         bool scheduled = false;
47         FOREACH_ENTITY_CLASS("dropclient_handler", true,
48         {
49                 if(it.owner == this)
50                 {
51                         scheduled = true;
52                         break; // can't use return here, compiler shows a warning
53                 }
54         });
55         if (scheduled)
56                 return false;
57
58         entity e = new_pure(dropclient_handler);
59         setthink(e, dropclient_do);
60         e.owner = this;
61         e.nextthink = time + 0.1;
62         return true;
63 }
64
65 void CreatureFrame_hotliquids(entity this)
66 {
67         if (this.contents_damagetime >= time)
68         {
69                 return;
70         }
71
72         this.contents_damagetime = time + autocvar_g_balance_contents_damagerate;
73
74         if (this.flags & FL_PROJECTILE)
75         {
76                 if (this.watertype == CONTENT_LAVA)
77                         Damage (this, NULL, NULL, autocvar_g_balance_contents_projectiledamage * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_LAVA.m_id, DMG_NOWEP, this.origin, '0 0 0');
78                 else if (this.watertype == CONTENT_SLIME)
79                         Damage (this, NULL, NULL, autocvar_g_balance_contents_projectiledamage * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_SLIME.m_id, DMG_NOWEP, this.origin, '0 0 0');
80         }
81         else
82         {
83                 if (STAT(FROZEN, this))
84                 {
85                         if (this.watertype == CONTENT_LAVA)
86                                 Damage(this, NULL, NULL, 10000, DEATH_LAVA.m_id, DMG_NOWEP, this.origin, '0 0 0');
87                         else if (this.watertype == CONTENT_SLIME)
88                                 Damage(this, NULL, NULL, 10000, DEATH_SLIME.m_id, DMG_NOWEP, this.origin, '0 0 0');
89                 }
90                 else if (this.watertype == CONTENT_LAVA)
91                 {
92                         if (this.watersound_finished < time)
93                         {
94                                 this.watersound_finished = time + 0.5;
95                                 sound (this, CH_PLAYER_SINGLE, SND_LAVA, VOL_BASE, ATTEN_NORM);
96                         }
97                         Damage (this, NULL, NULL, autocvar_g_balance_contents_playerdamage_lava * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_LAVA.m_id, DMG_NOWEP, this.origin, '0 0 0');
98                         if(autocvar_g_balance_contents_playerdamage_lava_burn)
99                                 Fire_AddDamage(this, NULL, autocvar_g_balance_contents_playerdamage_lava_burn * this.waterlevel, autocvar_g_balance_contents_playerdamage_lava_burn_time * this.waterlevel, DEATH_LAVA.m_id);
100                 }
101                 else if (this.watertype == CONTENT_SLIME)
102                 {
103                         if (this.watersound_finished < time)
104                         {
105                                 this.watersound_finished = time + 0.5;
106                                 sound (this, CH_PLAYER_SINGLE, SND_SLIME, VOL_BASE, ATTEN_NORM);
107                         }
108                         Damage (this, NULL, NULL, autocvar_g_balance_contents_playerdamage_slime * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_SLIME.m_id, DMG_NOWEP, this.origin, '0 0 0');
109                 }
110         }
111 }
112
113 void CreatureFrame_Liquids(entity this)
114 {
115         if (this.watertype <= CONTENT_WATER && this.waterlevel > 0) // workaround a retarded bug made by id software :P (yes, it's that old of a bug)
116         {
117                 if (!(this.flags & FL_INWATER))
118                 {
119                         this.flags |= FL_INWATER;
120                         this.contents_damagetime = 0;
121                 }
122
123                 CreatureFrame_hotliquids(this);
124         }
125         else
126         {
127                 if (this.flags & FL_INWATER)
128                 {
129                         // play leave water sound
130                         this.flags &= ~FL_INWATER;
131                         this.contents_damagetime = 0;
132                 }
133         }
134 }
135
136 void CreatureFrame_FallDamage(entity this)
137 {
138         if(IS_VEHICLE(this) || (this.flags & FL_PROJECTILE))
139                 return; // vehicles and projectiles don't receive fall damage
140         if(!(this.velocity || this.oldvelocity))
141                 return; // if the entity hasn't moved and isn't moving, then don't do anything
142
143         // check for falling damage
144         bool have_hook = false;
145         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
146         {
147                 .entity weaponentity = weaponentities[slot];
148                 if(this.(weaponentity).hook && this.(weaponentity).hook.state)
149                 {
150                         have_hook = true;
151                         break;
152                 }
153         }
154         if(!have_hook)
155         {
156                 float dm; // dm is the velocity DECREASE. Velocity INCREASE should never cause a sound or any damage.
157                 if(autocvar_g_balance_falldamage_onlyvertical)
158                         dm = fabs(this.oldvelocity.z) - vlen(this.velocity);
159                 else
160                         dm = vlen(this.oldvelocity) - vlen(this.velocity);
161                 if (IS_DEAD(this))
162                         dm = (dm - autocvar_g_balance_falldamage_deadminspeed) * autocvar_g_balance_falldamage_factor;
163                 else
164                         dm = min((dm - autocvar_g_balance_falldamage_minspeed) * autocvar_g_balance_falldamage_factor, autocvar_g_balance_falldamage_maxdamage);
165                 if (dm > 0)
166                 {
167                         tracebox(this.origin, this.mins, this.maxs, this.origin - '0 0 1', MOVE_NOMONSTERS, this);
168                         if (!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NODAMAGE))
169                                 Damage (this, NULL, NULL, dm, DEATH_FALL.m_id, DMG_NOWEP, this.origin, '0 0 0');
170                 }
171         }
172
173         if(autocvar_g_maxspeed > 0 && vdist(this.velocity, >, autocvar_g_maxspeed))
174                 Damage (this, NULL, NULL, 100000, DEATH_SHOOTING_STAR.m_id, DMG_NOWEP, this.origin, '0 0 0');
175 }
176
177 void CreatureFrame_All()
178 {
179         if(game_stopped || time < game_starttime)
180                 return;
181
182         IL_EACH(g_damagedbycontents, it.damagedbycontents,
183         {
184                 if (it.move_movetype == MOVETYPE_NOCLIP) continue;
185                 CreatureFrame_Liquids(it);
186                 CreatureFrame_FallDamage(it);
187                 it.oldvelocity = it.velocity;
188         });
189 }
190
191 // called shortly after map change in dedicated
192 void Pause_TryPause_Dedicated(entity this)
193 {
194         if (player_count == 0 && !intermission_running && !autocvar__endmatch)
195                 setpause(1);
196 }
197
198 // called every normal frame in singleplayer/listen
199 void Pause_TryPause()
200 {
201         int n = 0, p = 0;
202         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
203                 if (PHYS_INPUT_BUTTON_CHAT(it)) ++p;
204                 ++n;
205         });
206         if (!n) return;
207         if (n == p)
208                 setpause(1);
209         else
210                 setpause(0);
211 }
212
213 // called every paused frame by DP
214 void SV_PausedTic(float elapsedtime)
215 {
216         if (autocvar__endmatch) // `endmatch` while paused
217                 setpause(0); // proceed to intermission
218         else if (!server_is_dedicated)
219         {
220                 if (autocvar_sv_autopause)
221                         Pause_TryPause();
222                 else
223                         setpause(0);
224         }
225 }
226
227 void dedicated_print(string input)
228 {
229         if (server_is_dedicated) print(input);
230 }
231
232 void make_safe_for_remove(entity e)
233 {
234         if (e.initialize_entity)
235         {
236                 entity ent, prev = NULL;
237                 for (ent = initialize_entity_first; ent; )
238                 {
239                         if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
240                         {
241                                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
242                                 // skip it in linked list
243                                 if (prev)
244                                 {
245                                         prev.initialize_entity_next = ent.initialize_entity_next;
246                                         ent = prev.initialize_entity_next;
247                                 }
248                                 else
249                                 {
250                                         initialize_entity_first = ent.initialize_entity_next;
251                                         ent = initialize_entity_first;
252                                 }
253                         }
254                         else
255                         {
256                                 prev = ent;
257                                 ent = ent.initialize_entity_next;
258                         }
259                 }
260         }
261 }
262
263 void remove_except_protected(entity e)
264 {
265         if(e.remove_except_protected_forbidden)
266                 error("not allowed to remove this at this point");
267         builtin_remove(e);
268 }
269
270 void remove_unsafely(entity e)
271 {
272         if(e.classname == "spike")
273                 error("Removing spikes is forbidden (crylink bug), please report");
274         builtin_remove(e);
275 }
276
277 void remove_safely(entity e)
278 {
279         make_safe_for_remove(e);
280         builtin_remove(e);
281 }
282
283 /*
284 =============
285 StartFrame
286
287 Called before each frame by the server
288 =============
289 */
290
291 bool game_delay_last;
292
293 void systems_update();
294 void sys_phys_update(entity this, float dt);
295 void StartFrame()
296 {
297         FOREACH_CLIENT(IS_FAKE_CLIENT(it),
298         {
299                 // DP calls these for real clients only
300                 sys_phys_update(it, frametime); // called by SV_PlayerPhysics for players
301                 PlayerPreThink(it);
302         });
303
304         execute_next_frame();
305
306         delete_fn = remove_unsafely; // not during spawning!
307         serverprevtime = servertime;
308         servertime = time;
309         serverframetime = frametime;
310
311 #ifdef PROFILING
312         if(time > client_cefc_accumulatortime + 1)
313         {
314                 float t = client_cefc_accumulator / (time - client_cefc_accumulatortime);
315                 int c_seeing = 0;
316                 int c_seen = 0;
317                 FOREACH_CLIENT(true, {
318                         if(IS_REAL_CLIENT(it))
319                                 ++c_seeing;
320                         if(IS_PLAYER(it))
321                                 ++c_seen;
322                 });
323                 LOG_INFO(
324                         "CEFC time: ", ftos(t * 1000), "ms; ",
325                         "CEFC calls per second: ", ftos(c_seeing * (c_seen - 1) / t), "; ",
326                         "CEFC 100% load at: ", ftos(solve_quadratic(t, -t, -1) * '0 1 0')
327                 );
328                 client_cefc_accumulatortime = time;
329                 client_cefc_accumulator = 0;
330         }
331 #endif
332
333         IL_EACH(g_projectiles, it.csqcprojectile_clientanimate, CSQCProjectile_Check(it));
334
335         if (RedirectionThink()) return;
336
337         UncustomizeEntitiesRun();
338         InitializeEntitiesRun();
339
340         WarpZone_StartFrame();
341
342         sys_frametime = autocvar_sys_ticrate * autocvar_slowmo;
343         if (sys_frametime <= 0) sys_frametime = 1.0 / 60.0; // somewhat safe fallback
344
345         if (timeout_status == TIMEOUT_LEADTIME) // just before the timeout (when timeout_status will be TIMEOUT_ACTIVE)
346                 orig_slowmo = autocvar_slowmo; // slowmo will be restored after the timeout
347
348         // detect when the pre-game countdown (if any) has ended and the game has started
349         bool game_delay = (time < game_starttime);
350         if (autocvar_sv_eventlog && game_delay_last && !game_delay)
351                 GameLogEcho(":startdelay_ended");
352         game_delay_last = game_delay;
353
354         CreatureFrame_All();
355         CheckRules_World();
356
357         // after CheckRules_World() as it may set intermission_running, and after RedirectionThink() in case listen server is closing
358         if (autocvar_sv_autopause && !server_is_dedicated && !intermission_running)
359                 Pause_TryPause();
360
361         if (warmup_stage && !game_stopped && warmup_limit > 0 && time - game_starttime >= warmup_limit) {
362                 ReadyRestart(true);
363                 return;
364         }
365
366         bot_serverframe();
367         anticheat_startframe();
368         MUTATOR_CALLHOOK(SV_StartFrame);
369
370         GlobalStats_updateglobal();
371         FOREACH_CLIENT(true,
372         {
373                 GlobalStats_update(it);
374                 if (IS_FAKE_CLIENT(it))
375                         PlayerPostThink(it); // DP calls this for real clients only
376                 PlayerFrame(it);
377         });
378 }
379
380 .vector originjitter;
381 .vector anglesjitter;
382 .float anglejitter;
383 .string gametypefilter;
384 .string cvarfilter;
385
386 void SV_OnEntityPreSpawnFunction(entity this)
387 {
388         if (this)
389         if (this.gametypefilter != "")
390         if (!isGametypeInFilter(MapInfo_LoadedGametype, teamplay, have_team_spawns, this.gametypefilter))
391         {
392                 delete(this);
393                 return;
394         }
395         if (this.cvarfilter != "" && !expr_evaluate(this.cvarfilter)) {
396                 delete(this);
397                 return;
398         }
399
400         if (q3compat && DoesQ3ARemoveThisEntity(this)) {
401                 delete(this);
402                 return;
403         }
404
405         set_movetype(this, this.movetype);
406
407         if (this.monster_attack) {
408                 IL_PUSH(g_monster_targets, this);
409         }
410
411         // support special -1 and -2 angle from radiant
412         if (this.angles == '0 -1 0') {
413                 this.angles = '-90 0 0';
414         } else if (this.angles == '0 -2 0') {
415                 this.angles = '+90 0 0';
416         }
417
418         #define X(out, in) MACRO_BEGIN \
419                 if (in != 0) { out = out + (random() * 2 - 1) * in; } \
420         MACRO_END
421         X(this.origin.x, this.originjitter.x); X(this.origin.y, this.originjitter.y); X(this.origin.z, this.originjitter.z);
422         X(this.angles.x, this.anglesjitter.x); X(this.angles.y, this.anglesjitter.y); X(this.angles.z, this.anglesjitter.z);
423         X(this.angles.y, this.anglejitter);
424         #undef X
425
426         if (MUTATOR_CALLHOOK(OnEntityPreSpawn, this)) {
427                 delete(this);
428                 return;
429         }
430 }
431
432 string GetField_fullspawndata(entity e, string f, ...)
433 /* Retrieves the value of a map entity field from fullspawndata
434  * This bypasses field value changes made by the engine,
435  * eg string-to-float and escape sequence substitution.
436  *
437  * Avoids the need to declare fields just to read them once :)
438  *
439  * Returns the last instance of the field to match DarkPlaces behaviour.
440  * Path support: converts \ to / and tests the file if a third (bool, true) arg is passed.
441  * Returns string_null if the entity does not have the field, or the file is not in the VFS.
442  *
443  * FIXME: entities with //comments are not supported.
444  */
445 {
446         string v = string_null;
447
448         if (!e.fullspawndata)
449         {
450                 //LOG_WARNF("^1EDICT %s (classname %s) has no fullspawndata, engine lacks support?", ftos(num_for_edict(e)), e.classname);
451                 return v;
452         }
453
454         if (strstrofs(e.fullspawndata, "//", 0) >= 0)
455         {
456                 // tokenize and tokenize_console return early if "//" is reached,
457                 // which can leave an odd number of tokens and break key:value pairing.
458                 LOG_WARNF("^1EDICT %s fullspawndata contains unsupported //comment^7%s", ftos(num_for_edict(e)), e.fullspawndata);
459                 return v;
460         }
461
462         //print(sprintf("%s(EDICT %s, FIELD %s)\n", __FUNC__, ftos(num_for_edict(e)), f));
463         //print(strcat("FULLSPAWNDATA:", e.fullspawndata, "\n"));
464
465         // tokenize treats \ as an escape, but tokenize_console returns the required literal
466         for (int t = tokenize_console(e.fullspawndata) - 3; t > 0; t -= 2)
467         {
468                 //print(sprintf("\tTOKEN %s:%s\t%s:%s\n", ftos(t), ftos(t + 1), argv(t), argv(t + 1)));
469                 if (argv(t) == f)
470                 {
471                         v = argv(t + 1);
472                         break;
473                 }
474         }
475
476         //print(strcat("RESULT: ", v, "\n\n"));
477
478         if (v && ...(0, bool) == true)
479         {
480                 v = strreplace("\\", "/", v);
481                 if (whichpack(v) == "")
482                         return string_null;
483         }
484
485         return v;
486 }
487
488 /*
489 =============
490 FindFileInMapPack
491
492 Returns the first matching VFS file path that exists in the current map's pack.
493 Returns string_null if no files match or the map isn't packaged.
494 =============
495 */
496 string FindFileInMapPack(string pattern)
497 {
498         if (!checkextension("DP_QC_FS_SEARCH_PACKFILE"))
499                 return string_null;
500
501         string base_pack = whichpack(strcat("maps/", mapname, ".bsp"));
502         if (base_pack == "" || !base_pack) // this map isn't packaged or there was an error
503                 return string_null;
504
505         int glob = search_packfile_begin(pattern, true, true, base_pack);
506         if (glob < 0)
507                 return string_null;
508
509         string file = search_getfilename(glob, 0);
510         search_end(glob);
511         return file;
512 }
513
514 void WarpZone_PostInitialize_Callback()
515 {
516         // create waypoint links for warpzones
517         entity tracetest_ent = spawn();
518         setsize(tracetest_ent, PL_MIN_CONST, PL_MAX_CONST);
519         tracetest_ent.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP | DPCONTENTS_BOTCLIP;
520         //for(entity e = warpzone_first; e; e = e.warpzone_next)
521         for(entity e = NULL; (e = find(e, classname, "trigger_warpzone")); )
522                 waypoint_spawnforteleporter_wz(e, tracetest_ent);
523         delete(tracetest_ent);
524 }
525
526 /** engine callback */
527 void URI_Get_Callback(float id, float status, string data)
528 {
529         if(url_URI_Get_Callback(id, status, data))
530         {
531                 // handled
532         }
533         else if (id == URI_GET_DISCARD)
534         {
535                 // discard
536         }
537         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
538         {
539                 // sv_cmd curl
540                 Curl_URI_Get_Callback(id, status, data);
541         }
542         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
543         {
544                 // online ban list
545                 OnlineBanList_URI_Get_Callback(id, status, data);
546         }
547         else if (MUTATOR_CALLHOOK(URI_GetCallback, id, status, data))
548         {
549                 // handled by a mutator
550         }
551         else
552         {
553                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".");
554         }
555 }
556
557 /*
558 ==================
559 main
560
561 unused but required by the engine
562 ==================
563 */
564 void main ()
565 {
566
567 }