]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/items/items.qc
6b653d9c33ebde54776661e4481371a217239eec
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / items / items.qc
1 #include "items.qh"
2
3 #include <common/constants.qh>
4 #include <common/deathtypes/all.qh>
5 #include <common/gamemodes/gamemode/cts/cts.qh>
6 #include <common/items/_mod.qh>
7 #include <common/mapobjects/subs.qh>
8 #include <common/mapobjects/triggers.qh>
9 #include <common/monsters/_mod.qh>
10 #include <common/mutators/mutator/buffs/buffs.qh>
11 #include <common/mutators/mutator/buffs/sv_buffs.qh>
12 #include <common/mutators/mutator/powerups/_mod.qh>
13 #include <common/mutators/mutator/status_effects/_mod.qh>
14 #include <common/net_linked.qh>
15 #include <common/notifications/all.qh>
16 #include <common/resources/resources.qh>
17 #include <common/util.qh>
18 #include <common/weapons/_all.qh>
19 #include <common/wepent.qh>
20 #include <lib/warpzone/common.qh>
21 #include <lib/warpzone/util_server.qh>
22 #include <server/bot/api.qh>
23 #include <server/command/vote.qh>
24 #include <server/damage.qh>
25 #include <server/mutators/_mod.qh>
26 #include <server/teamplay.qh>
27 #include <server/weapons/common.qh>
28 #include <server/weapons/selection.qh>
29 #include <server/weapons/weaponsystem.qh>
30 #include <server/world.qh>
31
32 bool ItemSend(entity this, entity to, int sf)
33 {
34         if(this.gravity)
35                 sf |= ISF_DROP;
36         else
37                 sf &= ~ISF_DROP;
38
39         WriteHeader(MSG_ENTITY, ENT_CLIENT_ITEM);
40         WriteByte(MSG_ENTITY, sf);
41
42         //WriteByte(MSG_ENTITY, this.cnt);
43         if(sf & ISF_LOCATION)
44         {
45                 WriteVector(MSG_ENTITY, this.origin);
46         }
47
48         if(sf & ISF_ANGLES)
49         {
50                 WriteAngleVector(MSG_ENTITY, this.angles);
51         }
52
53         // sets size on the client, unused on server
54         //if(sf & ISF_SIZE)
55
56         if(sf & ISF_STATUS)
57                 WriteByte(MSG_ENTITY, this.ItemStatus);
58
59         if(sf & ISF_MODEL)
60         {
61                 WriteShort(MSG_ENTITY, bound(0, this.fade_end, 32767));
62                 WriteShort(MSG_ENTITY, bound(0, this.fade_start, 32767));
63
64                 if(this.mdl == "")
65                         LOG_TRACE("^1WARNING!^7 this.mdl is unset for item ", this.classname, "expect a crash just about now");
66
67                 WriteString(MSG_ENTITY, this.mdl);
68                 WriteByte(MSG_ENTITY, bound(0, this.skin, 255));
69         }
70
71         if(sf & ISF_COLORMAP)
72         {
73                 WriteShort(MSG_ENTITY, this.colormap);
74                 WriteByte(MSG_ENTITY, this.glowmod.x * 255.0);
75                 WriteByte(MSG_ENTITY, this.glowmod.y * 255.0);
76                 WriteByte(MSG_ENTITY, this.glowmod.z * 255.0);
77         }
78
79         if(sf & ISF_DROP)
80         {
81                 WriteVector(MSG_ENTITY, this.velocity);
82         }
83
84         return true;
85 }
86
87 void ItemUpdate(entity this)
88 {
89         this.oldorigin = this.origin;
90         this.SendFlags |= ISF_LOCATION;
91 }
92
93 void UpdateItemAfterTeleport(entity this)
94 {
95         if(getSendEntity(this) == ItemSend)
96                 ItemUpdate(this);
97 }
98
99 bool have_pickup_item(entity this)
100 {
101         if(this.itemdef.instanceOfPowerup)
102         {
103                 if(autocvar_g_powerups > 0)
104                         return true;
105                 if(autocvar_g_powerups == 0)
106                         return false;
107         }
108         else
109         {
110                 if(autocvar_g_pickup_items > 0)
111                         return true;
112                 if(autocvar_g_pickup_items == 0)
113                         return false;
114                 if(g_weaponarena)
115                         if(STAT(WEAPONS, this) || this.itemdef.instanceOfAmmo) // no item or ammo pickups in weaponarena
116                                 return false;
117         }
118         return true;
119 }
120
121 void Item_Show(entity e, int mode)
122 {
123         e.effects &= ~(EF_ADDITIVE | EF_STARDUST | EF_FULLBRIGHT | EF_NODEPTHTEST);
124         e.ItemStatus &= ~ITS_STAYWEP;
125         entity def = e.itemdef;
126         if (mode > 0)
127         {
128                 // make the item look normal, and be touchable
129                 e.model = e.mdl;
130                 e.solid = SOLID_TRIGGER;
131                 e.spawnshieldtime = 1;
132                 e.ItemStatus |= ITS_AVAILABLE;
133         }
134         else if (mode < 0)
135         {
136                 // hide the item completely
137                 e.model = string_null;
138                 e.solid = SOLID_NOT;
139                 e.spawnshieldtime = 1;
140                 e.ItemStatus &= ~ITS_AVAILABLE;
141         }
142         else
143         {
144                 bool nostay = def.instanceOfWeaponPickup ? !!(def.m_weapon.m_wepset & WEPSET_SUPERWEAPONS) : false // no weapon-stay on superweapons
145                         || e.team // weapon stay isn't supported for teamed weapons
146                         ;
147                 if(def.instanceOfWeaponPickup && !nostay && g_weapon_stay)
148                 {
149                         // make the item translucent and not touchable
150                         e.model = e.mdl;
151                         e.solid = SOLID_TRIGGER; // can STILL be picked up!
152                         e.effects |= EF_STARDUST;
153                         e.spawnshieldtime = 0; // field indicates whether picking it up may give you anything other than the weapon
154                         e.ItemStatus |= (ITS_AVAILABLE | ITS_STAYWEP);
155                 }
156                 else
157                 {
158                         //setmodel(e, "null");
159                         e.solid = SOLID_NOT;
160                         e.colormod = '0 0 0';
161                         //e.glowmod = e.colormod;
162                         e.spawnshieldtime = 1;
163                         e.ItemStatus &= ~ITS_AVAILABLE;
164                 }
165         }
166
167         if (def.m_glow)
168                 e.ItemStatus |= ITS_GLOW;
169
170         if (autocvar_g_nodepthtestitems)
171                 e.effects |= EF_NODEPTHTEST;
172
173         if (autocvar_g_fullbrightitems)
174                 e.ItemStatus |= ITS_ALLOWFB;
175         else
176                 e.ItemStatus &= ~ITS_ALLOWFB;
177
178         if (autocvar_sv_simple_items)
179                 e.ItemStatus |= ITS_ALLOWSI;
180
181         // relink entity (because solid may have changed)
182         setorigin(e, e.origin);
183         e.SendFlags |= ISF_STATUS;
184 }
185
186 void Item_Think(entity this)
187 {
188         this.nextthink = time;
189         if(this.origin != this.oldorigin)
190                 ItemUpdate(this);
191 }
192
193 bool Item_ItemsTime_SpectatorOnly(GameItem it);
194 bool Item_ItemsTime_Allow(GameItem it);
195 float Item_ItemsTime_UpdateTime(entity e, float t);
196 void Item_ItemsTime_SetTime(entity e, float t);
197 void Item_ItemsTime_SetTimesForAllPlayers();
198
199 void Item_Respawn(entity this)
200 {
201         Item_Show(this, 1);
202         sound(this, CH_TRIGGER, this.itemdef.m_respawnsound, VOL_BASE, ATTEN_NORM);     // play respawn sound
203
204         if (Item_ItemsTime_Allow(this.itemdef) || (STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS))
205         {
206                 float t = Item_ItemsTime_UpdateTime(this, 0);
207                 Item_ItemsTime_SetTime(this, t);
208                 Item_ItemsTime_SetTimesForAllPlayers();
209         }
210
211         setthink(this, Item_Think);
212         this.nextthink = time;
213
214         //Send_Effect(EFFECT_ITEM_RESPAWN, this.origin + this.mins_z * '0 0 1' + '0 0 48', '0 0 0', 1);
215         Send_Effect(EFFECT_ITEM_RESPAWN, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
216 }
217
218 void Item_RespawnCountdown(entity this)
219 {
220         if(this.item_respawncounter >= ITEM_RESPAWN_TICKS)
221         {
222                 if(this.waypointsprite_attached)
223                         WaypointSprite_Kill(this.waypointsprite_attached);
224                 Item_Respawn(this);
225         }
226         else
227         {
228                 this.nextthink = time + 1;
229                 this.item_respawncounter += 1;
230                 if(this.item_respawncounter == 1)
231                 {
232                         do {
233                                 {
234                                         entity wi = REGISTRY_GET(Weapons, this.weapon);
235                                         if (wi != WEP_Null) {
236                                                 entity wp = WaypointSprite_Spawn(WP_Weapon, 0, 0, this, '0 0 64', NULL, 0, this, waypointsprite_attached, true, RADARICON_Weapon);
237                                                 wp.wp_extra = wi.m_id;
238                                                 break;
239                                         }
240                                 }
241                                 {
242                                         entity ii = this.itemdef;
243                                         if (ii != NULL) {
244                                                 entity wp = WaypointSprite_Spawn(WP_Item, 0, 0, this, '0 0 64', NULL, 0, this, waypointsprite_attached, true, RADARICON_Item);
245                                                 wp.wp_extra = ii.m_id;
246                                                 break;
247                                         }
248                                 }
249                         } while (0);
250                         bool mutator_returnvalue = MUTATOR_CALLHOOK(Item_RespawnCountdown, this);
251                         if(this.waypointsprite_attached)
252                         {
253                                 GameItem def = this.itemdef;
254                                 if (Item_ItemsTime_SpectatorOnly(def) && !mutator_returnvalue)
255                                         WaypointSprite_UpdateRule(this.waypointsprite_attached, 0, SPRITERULE_SPECTATOR);
256                                 WaypointSprite_UpdateBuildFinished(this.waypointsprite_attached, time + ITEM_RESPAWN_TICKS);
257                         }
258                 }
259
260                 if(this.waypointsprite_attached)
261                 {
262                         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
263                                 if(this.waypointsprite_attached.waypointsprite_visible_for_player(this.waypointsprite_attached, it, it))
264                                 {
265                                         msg_entity = it;
266                                         soundto(MSG_ONE, this, CH_TRIGGER, SND(ITEMRESPAWNCOUNTDOWN), VOL_BASE, ATTEN_NORM, 0); // play respawn sound
267                                 }
268                         });
269
270                         WaypointSprite_Ping(this.waypointsprite_attached);
271                         //WaypointSprite_UpdateHealth(this.waypointsprite_attached, this.item_respawncounter);
272                 }
273         }
274 }
275
276 void Item_RespawnThink(entity this)
277 {
278         this.nextthink = time;
279         if(this.origin != this.oldorigin)
280                 ItemUpdate(this);
281
282         if(time >= this.wait)
283                 Item_Respawn(this);
284 }
285
286 void Item_ScheduleRespawnIn(entity e, float t)
287 {
288         // if the respawn time is longer than 10 seconds, show a waypoint, otherwise, just respawn normally
289         if ((Item_ItemsTime_Allow(e.itemdef) || (STAT(WEAPONS, e) & WEPSET_SUPERWEAPONS) || MUTATOR_CALLHOOK(Item_ScheduleRespawn, e, t)) && (t - ITEM_RESPAWN_TICKS) > 0)
290         {
291                 setthink(e, Item_RespawnCountdown);
292                 e.nextthink = time + max(0, t - ITEM_RESPAWN_TICKS);
293                 e.scheduledrespawntime = e.nextthink + ITEM_RESPAWN_TICKS;
294                 e.item_respawncounter = 0;
295                 if(Item_ItemsTime_Allow(e.itemdef) || (STAT(WEAPONS, e) & WEPSET_SUPERWEAPONS))
296                 {
297                         t = Item_ItemsTime_UpdateTime(e, e.scheduledrespawntime);
298                         Item_ItemsTime_SetTime(e, t);
299                         Item_ItemsTime_SetTimesForAllPlayers();
300                 }
301         }
302         else
303         {
304                 setthink(e, Item_RespawnThink);
305                 e.nextthink = time;
306                 e.scheduledrespawntime = time + t;
307                 e.wait = time + t;
308
309                 if(Item_ItemsTime_Allow(e.itemdef) || (STAT(WEAPONS, e) & WEPSET_SUPERWEAPONS))
310                 {
311                         t = Item_ItemsTime_UpdateTime(e, e.scheduledrespawntime);
312                         Item_ItemsTime_SetTime(e, t);
313                         Item_ItemsTime_SetTimesForAllPlayers();
314                 }
315         }
316 }
317
318 AUTOCVAR(g_pickup_respawntime_scaling_reciprocal, float, 0.0, "Multiply respawn time by `reciprocal / (p + offset) + linear` where `p` is the current number of players, takes effect with 2 or more players present, `reciprocal` (with `offset` and `linear` set to 0) can be used to achieve a constant number of items spawned *per player*");
319 AUTOCVAR(g_pickup_respawntime_scaling_offset, float, 0.0, "Multiply respawn time by `reciprocal / (p + offset) + linear` where `p` is the current number of players, takes effect with 2 or more players present, `offset` offsets the curve left or right - the results are not intuitive and I recommend plotting the respawn time and the number of items per player to see what's happening");
320 AUTOCVAR(g_pickup_respawntime_scaling_linear, float, 1.0, "Multiply respawn time by `reciprocal / (p + offset) + linear` where `p` is the current number of players, takes effect with 2 or more players present, `linear` can be used to simply scale the respawn time linearly");
321
322 /// Adjust respawn time according to the number of players.
323 float adjust_respawntime(float normal_respawntime) {
324         float r = autocvar_g_pickup_respawntime_scaling_reciprocal;
325         float o = autocvar_g_pickup_respawntime_scaling_offset;
326         float l = autocvar_g_pickup_respawntime_scaling_linear;
327
328         if (r == 0 && l == 1) {
329                 return normal_respawntime;
330         }
331
332         entity balance = TeamBalance_CheckAllowedTeams(NULL);
333         TeamBalance_GetTeamCounts(balance, NULL);
334         int players = 0;
335         for (int i = 1; i <= NUM_TEAMS; ++i)
336         {
337                 if (TeamBalance_IsTeamAllowed(balance, i))
338                 {
339                         players += TeamBalance_GetNumberOfPlayers(balance, i);
340                 }
341         }
342         TeamBalance_Destroy(balance);
343
344         if (players >= 2) {
345                 return normal_respawntime * (r / (players + o) + l);
346         } else {
347                 return normal_respawntime;
348         }
349 }
350
351 void Item_ScheduleRespawn(entity e)
352 {
353         if(e.respawntime > 0)
354         {
355                 Item_Show(e, 0);
356
357                 float adjusted_respawntime = adjust_respawntime(e.respawntime);
358                 //LOG_INFOF("item %s will respawn in %f", e.classname, adjusted_respawntime);
359
360                 // range: adjusted_respawntime - respawntimejitter .. adjusted_respawntime + respawntimejitter
361                 float respawn_in = adjusted_respawntime + crandom() * e.respawntimejitter;
362                 Item_ScheduleRespawnIn(e, respawn_in);
363         }
364         else // if respawntime is -1, this item does not respawn
365                 Item_Show(e, -1);
366 }
367
368 AUTOCVAR(g_pickup_respawntime_initial_random, int, 1,
369         "For items that don't start spawned: 0: spawn after their normal respawntime; 1: spawn after `random * respawntime` with the *same* random; 2: same as 1 but each item has separate random");
370
371 void Item_ScheduleInitialRespawn(entity e)
372 {
373         Item_Show(e, 0);
374
375         float spawn_in;
376         if (autocvar_g_pickup_respawntime_initial_random == 0)
377         {
378                 // range: respawntime .. respawntime + respawntimejitter
379                 spawn_in = e.respawntime + random() * e.respawntimejitter;
380         }
381         else
382         {
383                 float rnd;
384                 if (autocvar_g_pickup_respawntime_initial_random == 1)
385                 {
386                         static float shared_random = 0;
387                         // NOTE this code works only if items are scheduled at the same time (normal case)
388                         // NOTE2 random() can't return exactly 1 so this check always work as intended
389                         if (!shared_random || floor(time) > shared_random)
390                                 shared_random = floor(time) + random();
391                         rnd = shared_random - floor(time);
392                 }
393                 else
394                         rnd = random();
395
396                 // range:
397                 // if respawntime >= ITEM_RESPAWN_TICKS: ITEM_RESPAWN_TICKS .. respawntime + respawntimejitter
398                 // else: 0 .. ITEM_RESPAWN_TICKS
399                 // this is to prevent powerups spawning unexpectedly without waypoints
400                 spawn_in = ITEM_RESPAWN_TICKS + rnd * (e.respawntime + e.respawntimejitter - ITEM_RESPAWN_TICKS);
401         }
402
403         Item_ScheduleRespawnIn(e, max(0, game_starttime - time) + ((e.respawntimestart) ? e.respawntimestart : spawn_in));
404 }
405
406 void GiveRandomWeapons(entity receiver, int num_weapons, string weapon_names,
407         entity ammo_entity)
408 {
409         if (num_weapons == 0)
410         {
411                 return;
412         }
413         int num_potential_weapons = tokenize_console(weapon_names);
414         for (int give_attempt = 0; give_attempt < num_weapons; ++give_attempt)
415         {
416                 RandomSelection_Init();
417                 for (int weapon_index = 0; weapon_index < num_potential_weapons;
418                         ++weapon_index)
419                 {
420                         string weapon = argv(weapon_index);
421                         FOREACH(Weapons, it != WEP_Null,
422                         {
423                                 // Finding a weapon which player doesn't have.
424                                 if (!(STAT(WEAPONS, receiver) & it.m_wepset) && (it.netname == weapon))
425                                 {
426                                         RandomSelection_AddEnt(it, 1, 1);
427                                         break;
428                                 }
429                         });
430                 }
431                 if (RandomSelection_chosen_ent == NULL)
432                 {
433                         return;
434                 }
435                 STAT(WEAPONS, receiver) |= RandomSelection_chosen_ent.m_wepset;
436                 if (RandomSelection_chosen_ent.ammo_type == RES_NONE)
437                 {
438                         continue;
439                 }
440                 if (GetResource(receiver,
441                         RandomSelection_chosen_ent.ammo_type) != 0)
442                 {
443                         continue;
444                 }
445                 GiveResource(receiver, RandomSelection_chosen_ent.ammo_type,
446                         GetResource(ammo_entity,
447                         RandomSelection_chosen_ent.ammo_type));
448         }
449 }
450
451 bool Item_GiveAmmoTo(entity item, entity player, Resource res_type, float ammomax)
452 {
453         float amount = GetResource(item, res_type);
454         if (amount == 0)
455         {
456                 return false;
457         }
458         float player_amount = GetResource(player, res_type);
459         if (item.spawnshieldtime)
460         {
461                 if ((player_amount >= ammomax) && (item.pickup_anyway <= 0))
462                         return false;
463         }
464         else if (g_weapon_stay == 2)
465         {
466                 ammomax = min(amount, ammomax);
467                 if(player_amount >= ammomax)
468                         return false;
469         }
470         else
471                 return false;
472         if (amount < 0)
473                 TakeResourceWithLimit(player, res_type, -amount, ammomax);
474         else
475                 GiveResourceWithLimit(player, res_type, amount, ammomax);
476         return true;
477 }
478
479 void Item_NotifyWeapon(entity player, int wep)
480 {
481         FOREACH_CLIENT(IS_REAL_CLIENT(it) && (it == player || (IS_SPEC(it) && it.enemy == player)), {
482                 msg_entity = it;
483                 WriteHeader(MSG_ONE, TE_CSQC_WEAPONPICKUP);
484                 WriteByte(MSG_ONE, wep);
485         });
486 }
487
488 bool Item_GiveTo(entity item, entity player)
489 {
490         // if nothing happens to player, just return without taking the item
491         int _switchweapon = 0;
492         // in case the player has autoswitch enabled do the following:
493         // if the player is using their best weapon before items are given, they
494         // probably want to switch to an even better weapon after items are given
495
496         if(CS_CVAR(player).cvar_cl_autoswitch)
497         {
498                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
499                 {
500                         .entity weaponentity = weaponentities[slot];
501                         if(player.(weaponentity).m_weapon != WEP_Null || slot == 0)
502                         {
503                                 if(player.(weaponentity).m_switchweapon == w_getbestweapon(player, weaponentity))
504                                         _switchweapon |= BIT(slot);
505
506                                 if(!(STAT(WEAPONS, player) & WepSet_FromWeapon(player.(weaponentity).m_switchweapon)))
507                                         _switchweapon |= BIT(slot);
508                         }
509                 }
510         }
511         bool pickedup = false;
512         pickedup |= Item_GiveAmmoTo(item, player, RES_HEALTH, item.max_health);
513         pickedup |= Item_GiveAmmoTo(item, player, RES_ARMOR, item.max_armorvalue);
514         pickedup |= Item_GiveAmmoTo(item, player, RES_SHELLS, g_pickup_shells_max);
515         pickedup |= Item_GiveAmmoTo(item, player, RES_BULLETS, g_pickup_nails_max);
516         pickedup |= Item_GiveAmmoTo(item, player, RES_ROCKETS, g_pickup_rockets_max);
517         pickedup |= Item_GiveAmmoTo(item, player, RES_CELLS, g_pickup_cells_max);
518         pickedup |= Item_GiveAmmoTo(item, player, RES_PLASMA, g_pickup_plasma_max);
519         pickedup |= Item_GiveAmmoTo(item, player, RES_FUEL, g_pickup_fuel_max);
520         if (item.itemdef.instanceOfWeaponPickup)
521         {
522                 WepSet w, wp;
523                 w = STAT(WEAPONS, item);
524                 wp = w & ~STAT(WEAPONS, player);
525
526                 if (wp || (item.spawnshieldtime && item.pickup_anyway > 0))
527                 {
528                         pickedup = true;
529                         FOREACH(Weapons, it != WEP_Null, {
530                                 if(w & (it.m_wepset))
531                                         Item_NotifyWeapon(player, it.m_id);
532
533                                 if(wp & (it.m_wepset))
534                                 {
535                                         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
536                                         {
537                                                 .entity weaponentity = weaponentities[slot];
538                                                 if(player.(weaponentity).m_weapon != WEP_Null || slot == 0)
539                                                         W_DropEvent(wr_pickup, player, it.m_id, item, weaponentity);
540                                         }
541                                         W_GiveWeapon(player, it.m_id);
542                                 }
543                         });
544                 }
545         }
546
547         if (item.itemdef.instanceOfPowerup)
548         {
549                 if ((item.itemdef == ITEM_JetpackRegen) && !(player.items & IT_FUEL_REGEN))
550                         Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ITEM_FUELREGEN_GOT);
551                 else if ((item.itemdef == ITEM_Jetpack) && !(player.items & IT_JETPACK))
552                         Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ITEM_JETPACK_GOT);
553         }
554
555         int its;
556         if((its = (item.items - (item.items & player.items)) & IT_PICKUPMASK))
557         {
558                 pickedup = true;
559                 player.items |= its;
560                 // TODO: we probably want to show a message in the console, but not this one!
561                 //Send_Notification(NOTIF_ONE, player, MSG_INFO, INFO_ITEM_WEAPON_GOT, item.netname);
562         }
563
564         if (item.strength_finished)
565         {
566                 pickedup = true;
567                 float t = max(StatusEffects_gettime(STATUSEFFECT_Strength, player), time);
568                 if (autocvar_g_powerups_stack)
569                         t += item.strength_finished;
570                 else
571                         t = max(t, time + item.strength_finished);
572                 StatusEffects_apply(STATUSEFFECT_Strength, player, t, 0);
573         }
574         if (item.invincible_finished)
575         {
576                 pickedup = true;
577                 float t = max(StatusEffects_gettime(STATUSEFFECT_Shield, player), time);
578                 if (autocvar_g_powerups_stack)
579                         t += item.invincible_finished;
580                 else
581                         t = max(t, time + item.invincible_finished);
582                 StatusEffects_apply(STATUSEFFECT_Shield, player, t, 0);
583         }
584         if (item.speed_finished)
585         {
586                 pickedup = true;
587                 float t = max(StatusEffects_gettime(STATUSEFFECT_Speed, player), time);
588                 if (autocvar_g_powerups_stack)
589                         t += item.speed_finished;
590                 else
591                         t = max(t, time + item.speed_finished);
592                 StatusEffects_apply(STATUSEFFECT_Speed, player, t, 0);
593         }
594         if (item.invisibility_finished)
595         {
596                 pickedup = true;
597                 float t = max(StatusEffects_gettime(STATUSEFFECT_Invisibility, player), time);
598                 if (autocvar_g_powerups_stack)
599                         t += item.invisibility_finished;
600                 else
601                         t = max(t, time + item.invisibility_finished);
602                 StatusEffects_apply(STATUSEFFECT_Invisibility, player, t, 0);
603         }
604         if (item.superweapons_finished)
605         {
606                 pickedup = true;
607                 StatusEffects_apply(STATUSEFFECT_Superweapons, player, max(StatusEffects_gettime(STATUSEFFECT_Superweapons, player), time) + item.superweapons_finished, 0);
608         }
609
610         // always eat teamed entities
611         if(item.team)
612                 pickedup = true;
613
614         if (!pickedup)
615                 return false;
616
617         // crude hack to enforce switching weapons
618         if(g_cts && item.itemdef.instanceOfWeaponPickup && !CS_CVAR(player).cvar_cl_cts_noautoswitch)
619         {
620                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
621                 {
622                         .entity weaponentity = weaponentities[slot];
623                         if(player.(weaponentity).m_weapon != WEP_Null || slot == 0)
624                                 W_SwitchWeapon_Force(player, REGISTRY_GET(Weapons, item.weapon), weaponentity);
625                 }
626                 return true;
627         }
628
629         if(_switchweapon)
630         {
631                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
632                 {
633                         .entity weaponentity = weaponentities[slot];
634                         if(_switchweapon & BIT(slot))
635                         if(player.(weaponentity).m_switchweapon != w_getbestweapon(player, weaponentity))
636                                 W_SwitchWeapon_Force(player, w_getbestweapon(player, weaponentity), weaponentity);
637                 }
638         }
639
640         return true;
641 }
642
643 void Item_Touch(entity this, entity toucher)
644 {
645         // remove the item if it's currnetly in a NODROP brush or hits a NOIMPACT surface (such as sky)
646         if (Item_IsLoot(this))
647         {
648                 if (ITEM_TOUCH_NEEDKILL())
649                 {
650                         RemoveItem(this);
651                         return;
652                 }
653         }
654
655         if(!(toucher.flags & FL_PICKUPITEMS)
656         || STAT(FROZEN, toucher)
657         || IS_DEAD(toucher)
658         || (this.solid != SOLID_TRIGGER)
659         || (this.owner == toucher)
660         || (time < this.item_spawnshieldtime)
661         ) { return; }
662
663         switch (MUTATOR_CALLHOOK(ItemTouch, this, toucher))
664         {
665                 case MUT_ITEMTOUCH_RETURN: { return; }
666                 case MUT_ITEMTOUCH_PICKUP: { toucher = M_ARGV(1, entity); goto pickup; }
667         }
668
669         toucher = M_ARGV(1, entity);
670
671         if (Item_IsExpiring(this))
672         {
673                 this.strength_finished = max(0, this.strength_finished - time);
674                 this.invincible_finished = max(0, this.invincible_finished - time);
675                 this.speed_finished = max(0, this.speed_finished - time);
676                 this.invisibility_finished = max(0, this.invisibility_finished - time);
677                 this.superweapons_finished = max(0, this.superweapons_finished - time);
678         }
679         bool gave = ITEM_HANDLE(Pickup, this.itemdef, this, toucher);
680         if (!gave)
681         {
682                 if (Item_IsExpiring(this))
683                 {
684                         // undo what we did above
685                         this.strength_finished += time;
686                         this.invincible_finished += time;
687                         this.speed_finished += time;
688                         this.invisibility_finished += time;
689                         this.superweapons_finished += time;
690                 }
691                 return;
692         }
693
694 LABEL(pickup)
695
696         if(this.target && this.target != "" && this.target != "###item###") // defrag support
697                 SUB_UseTargets(this, toucher, NULL);
698
699         STAT(LAST_PICKUP, toucher) = time;
700
701         Send_Effect(EFFECT_ITEM_PICKUP, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
702         _sound (toucher, (this.itemdef.instanceOfPowerup ? CH_TRIGGER_SINGLE : CH_TRIGGER), (this.item_pickupsound ? this.item_pickupsound : Sound_fixpath(this.item_pickupsound_ent)), VOL_BASE, ATTEN_NORM);
703
704         MUTATOR_CALLHOOK(ItemTouched, this, toucher);
705         if (wasfreed(this))
706         {
707                 return;
708         }
709
710         if (Item_IsLoot(this))
711         {
712                 delete(this);
713                 return;
714         }
715         if (!this.spawnshieldtime)
716         {
717                 return;
718         }
719         entity e;
720         if (this.team)
721         {
722                 RandomSelection_Init();
723                 IL_EACH(g_items, it.team == this.team,
724                 {
725                         if (it.itemdef) // is a registered item
726                         {
727                                 Item_Show(it, -1);
728                                 it.scheduledrespawntime = 0;
729                                 RandomSelection_AddEnt(it, it.cnt, 0);
730                         }
731                 });
732                 e = RandomSelection_chosen_ent;
733                 Item_Show(e, 1); // reset its state so it is visible (extra sendflags doesn't matter, this happens anyway)
734         }
735         else
736                 e = this;
737         Item_ScheduleRespawn(e);
738 }
739
740 void Item_Reset(entity this)
741 {
742         Item_Show(this, !this.state);
743
744         if (Item_IsLoot(this))
745         {
746                 return;
747         }
748         setthink(this, Item_Think);
749         this.nextthink = time;
750         if (this.waypointsprite_attached)
751         {
752                 WaypointSprite_Kill(this.waypointsprite_attached);
753         }
754         if (this.itemdef.instanceOfPowerup || (STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS)) // do not spawn powerups initially!
755         {
756                 Item_ScheduleInitialRespawn(this);
757         }
758 }
759
760 void Item_FindTeam(entity this)
761 {
762         if(!(this.effects & EF_NOGUNBOB)) // marker for item team search
763                 return;
764
765         LOG_TRACE("Initializing item team ", ftos(this.team));
766         RandomSelection_Init();
767         IL_EACH(g_items, it.team == this.team,
768         {
769                 if(it.itemdef) // is a registered item
770                         RandomSelection_AddEnt(it, it.cnt, 0);
771         });
772
773         entity e = RandomSelection_chosen_ent;
774         if (!e)
775                 return;
776
777         IL_EACH(g_items, it.team == this.team,
778         {
779                 if(it.itemdef) // is a registered item
780                 {
781                         if(it != e)
782                         {
783                                 Item_Show(it, -1); // make it non-spawned
784                                 if (it.waypointsprite_attached)
785                                         WaypointSprite_Kill(it.waypointsprite_attached);
786                                 it.nextthink = 0; // disable any scheduled powerup spawn
787                         }
788                         else
789                                 Item_Reset(it);
790
791                         // leave 'this' marked so Item_FindTeam() works when called again via this.reset
792                         if(it != this)
793                                 it.effects &= ~EF_NOGUNBOB;
794                 }
795         });
796 }
797
798 void Item_CopyFields(entity this, entity to)
799 {
800         setorigin(to, this.origin);
801         to.spawnflags = this.spawnflags;
802         to.noalign = Item_ShouldKeepPosition(this);
803         to.cnt = this.cnt;
804         to.team = this.team;
805         to.spawnfunc_checked = true;
806         // TODO: copy respawn times? this may not be desirable in some cases
807         //to.respawntime = this.respawntime;
808         //to.respawntimejitter = this.respawntimejitter;
809 }
810
811 // Savage: used for item garbage-collection
812 void RemoveItem(entity this)
813 {
814         if(wasfreed(this) || !this) { return; }
815         if(this.waypointsprite_attached)
816                 WaypointSprite_Kill(this.waypointsprite_attached);
817         Send_Effect(EFFECT_ITEM_PICKUP, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
818         delete(this);
819 }
820
821 // pickup evaluation functions
822 // these functions decide how desirable an item is to the bots
823
824 float generic_pickupevalfunc(entity player, entity item) {return item.bot_pickupbasevalue;}
825
826 float weapon_pickupevalfunc(entity player, entity item)
827 {
828         // See if I have it already
829         if(STAT(WEAPONS, player) & STAT(WEAPONS, item))
830         {
831                 // If I can pick it up
832                 if(!item.spawnshieldtime)
833                         return 0;
834                 return ammo_pickupevalfunc(player, item);
835         }
836
837         // reduce weapon value if bot already got a good arsenal
838         float c = 1;
839         int weapons_value = 0;
840         FOREACH(Weapons, it != WEP_Null && (STAT(WEAPONS, player) & it.m_wepset), {
841                 weapons_value += it.bot_pickupbasevalue;
842         });
843         c -= bound(0, weapons_value / 20000, 1) * 0.5;
844
845         return item.bot_pickupbasevalue * c;
846 }
847
848 float ammo_pickupevalfunc(entity player, entity item)
849 {
850         entity item_resource = NULL; // pointer to the resource that may be associated with the given item
851         entity wpn = NULL;
852         float c = 0;
853         float rating = 0;
854
855         // detect needed ammo
856         if(item.itemdef.instanceOfWeaponPickup)
857         {
858                 entity res = item.itemdef.m_weapon.ammo_type;
859                 entity ammo = (res != RES_NONE) ? GetAmmoItem(res) : NULL;
860                 if(!ammo)
861                         return 0;
862                 if(res != RES_NONE && GetResource(item, res))
863                         item_resource = res;
864
865                 wpn = item;
866                 rating = ammo.m_botvalue;
867         }
868         else
869         {
870                 FOREACH(Weapons, it != WEP_Null, {
871                         if(!(STAT(WEAPONS, player) & (it.m_wepset)))
872                                 continue;
873                         if(it.ammo_type == RES_NONE)
874                                 continue;
875
876                         if(GetResource(item, it.ammo_type))
877                         {
878                                 item_resource = it.ammo_type;
879                                 break;
880                         }
881                 });
882                 rating = item.bot_pickupbasevalue;
883         }
884
885         float noammorating = 0.5;
886
887         if(item_resource && (GetResource(player, item_resource) < GetResourceLimit(player, item_resource)))
888                 c = GetResource(item, item_resource) / max(noammorating, GetResource(player, item_resource));
889
890         rating *= min(c, 2);
891         if(wpn)
892                 rating += wpn.bot_pickupbasevalue * 0.1;
893         return rating;
894 }
895
896 float healtharmor_pickupevalfunc(entity player, entity item)
897 {
898         float c = 0;
899         float rating = item.bot_pickupbasevalue;
900
901         float itemarmor = GetResource(item, RES_ARMOR);
902         float itemhealth = GetResource(item, RES_HEALTH);
903
904         if(item.item_group)
905         {
906                 itemarmor *= min(4, item.item_group_count);
907                 itemhealth *= min(4, item.item_group_count);
908         }
909
910         if (itemarmor && (GetResource(player, RES_ARMOR) < item.max_armorvalue))
911                 c = itemarmor / max(1, GetResource(player, RES_ARMOR) * 2/3 + GetResource(player, RES_HEALTH) * 1/3);
912
913         if (itemhealth && (GetResource(player, RES_HEALTH) < item.max_health))
914                 c = itemhealth / max(1, GetResource(player, RES_HEALTH));
915
916         rating *= min(2, c);
917         return rating;
918 }
919
920 void Item_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force)
921 {
922         if(ITEM_DAMAGE_NEEDKILL(deathtype))
923                 RemoveItem(this);
924 }
925
926 void item_use(entity this, entity actor, entity trigger)
927 {
928         // use the touch function to handle collection
929         gettouch(this)(this, actor);
930 }
931
932 void _StartItem(entity this, entity def, float defaultrespawntime, float defaultrespawntimejitter)
933 {
934         string itemname = def.m_name;
935         Model itemmodel = def.m_model;
936         Sound pickupsound = def.m_sound;
937         float(entity player, entity item) pickupevalfunc = def.m_pickupevalfunc;
938         float pickupbasevalue = def.m_botvalue;
939         int itemflags = def.m_itemflags;
940
941         startitem_failed = false;
942
943         this.item_model_ent = itemmodel;
944         this.item_pickupsound_ent = pickupsound;
945
946         if(def.m_iteminit)
947                 def.m_iteminit(def, this);
948
949         if(!this.respawntime) // both need to be set
950         {
951                 this.respawntime = defaultrespawntime;
952                 this.respawntimejitter = defaultrespawntimejitter;
953         }
954
955         if(!this.pickup_anyway && def.m_pickupanyway)
956                 this.pickup_anyway = def.m_pickupanyway();
957
958         int itemid = def.m_itemid;
959         this.items = itemid;
960         int weaponid = def.instanceOfWeaponPickup ? def.m_weapon.m_id : 0;
961         this.weapon = weaponid;
962
963         if(!this.fade_end)
964         {
965                 this.fade_start = autocvar_g_items_mindist;
966                 this.fade_end = autocvar_g_items_maxdist;
967         }
968
969         if(weaponid)
970                 STAT(WEAPONS, this) = WepSet_FromWeapon(REGISTRY_GET(Weapons, weaponid));
971
972         this.flags = FL_ITEM | itemflags;
973         IL_PUSH(g_items, this);
974
975         if(MUTATOR_CALLHOOK(FilterItem, this)) // error means we do not want the item
976         {
977                 startitem_failed = true;
978                 delete(this);
979                 return;
980         }
981
982         precache_model(this.model);
983         precache_sound(this.item_pickupsound);
984
985         if(q3compat && !this.team)
986         {
987                 string t = GetField_fullspawndata(this, "team", false);
988                 // bones_was_here: this hack is cheaper than changing to a .string strcmp()
989                 if(t) this.team = crc16(false, t);
990         }
991
992         if (Item_IsLoot(this))
993         {
994                 this.reset = RemoveItem;
995                 set_movetype(this, MOVETYPE_TOSS);
996
997                 // Savage: remove thrown items after a certain period of time ("garbage collection")
998                 setthink(this, RemoveItem);
999                 this.nextthink = time + autocvar_g_items_dropped_lifetime;
1000
1001                 this.takedamage = DAMAGE_YES;
1002                 this.event_damage = Item_Damage;
1003                 // enable this to have thrown items burn in lava
1004                 //this.damagedbycontents = true;
1005                 //IL_PUSH(g_damagedbycontents, this);
1006
1007                 if (Item_IsExpiring(this))
1008                 {
1009                         // if item is worthless after a timer, have it expire then
1010                         this.nextthink = max(this.strength_finished, this.invincible_finished, this.superweapons_finished);
1011                 }
1012
1013                 // don't drop if in a NODROP zone (such as lava)
1014                 traceline(this.origin, this.origin, MOVE_NORMAL, this);
1015                 if (trace_dpstartcontents & DPCONTENTS_NODROP)
1016                 {
1017                         startitem_failed = true;
1018                         delete(this);
1019                         return;
1020                 }
1021         }
1022         else
1023         {
1024                 if(!have_pickup_item(this))
1025                 {
1026                         startitem_failed = true;
1027                         delete(this);
1028                         return;
1029                 }
1030
1031                 if(this.angles != '0 0 0')
1032                         this.SendFlags |= ISF_ANGLES;
1033
1034                 this.reset = this.team ? Item_FindTeam : Item_Reset;
1035                 // it's a level item
1036                 if(this.spawnflags & 1)
1037                         this.noalign = 1;
1038                 if (this.noalign > 0)
1039                         set_movetype(this, MOVETYPE_NONE);
1040                 else
1041                         set_movetype(this, MOVETYPE_TOSS);
1042                 // do item filtering according to game mode and other things
1043                 if (this.noalign <= 0)
1044                 {
1045                         // first nudge it off the floor a little bit to avoid math errors
1046                         setorigin(this, this.origin + '0 0 1');
1047                         // set item size before we spawn a spawnfunc_waypoint
1048                         setsize(this, def.m_mins, def.m_maxs);
1049                         this.SendFlags |= ISF_SIZE;
1050                         // note droptofloor returns false if stuck/or would fall too far
1051                         if (!this.noalign)
1052                                 droptofloor(this);
1053                         waypoint_spawnforitem(this);
1054                 }
1055
1056                 /*
1057                  * can't do it that way, as it would break maps
1058                  * TODO make a target_give like entity another way, that perhaps has
1059                  * the weapon name in a key
1060                 if(this.targetname)
1061                 {
1062                         // target_give not yet supported; maybe later
1063                         print("removed targeted ", this.classname, "\n");
1064                         startitem_failed = true;
1065                         delete(this);
1066                         return;
1067                 }
1068                 */
1069
1070                 if(this.targetname != "" && (this.spawnflags & 16))
1071                         this.use = item_use;
1072
1073                 if(autocvar_spawn_debug >= 2)
1074                 {
1075                         // why not flags & fl_item?
1076                         FOREACH_ENTITY_RADIUS(this.origin, 3, it.is_item, {
1077                                 LOG_TRACE("XXX Found duplicated item: ", itemname, vtos(this.origin));
1078                                 LOG_TRACE(" vs ", it.netname, vtos(it.origin));
1079                                 error("Mapper sucks.");
1080                         });
1081                         this.is_item = true;
1082                 }
1083
1084                 weaponsInMap |= WepSet_FromWeapon(REGISTRY_GET(Weapons, weaponid));
1085
1086                 if (        def.instanceOfPowerup
1087                         ||  def.instanceOfWeaponPickup
1088                         || (def.instanceOfHealth && def != ITEM_HealthSmall)
1089                         || (def.instanceOfArmor && def != ITEM_ArmorSmall)
1090                         || (itemid & (IT_KEY1 | IT_KEY2))
1091                 )
1092                 {
1093                         if(!this.target || this.target == "")
1094                                 this.target = "###item###"; // for finding the nearest item using findnearest
1095                 }
1096
1097                 Item_ItemsTime_SetTime(this, 0);
1098         }
1099
1100         this.bot_pickup = true;
1101         this.bot_pickupevalfunc = pickupevalfunc;
1102         this.bot_pickupbasevalue = pickupbasevalue;
1103         this.mdl = this.model ? this.model : strzone(this.item_model_ent.model_str());
1104         this.netname = itemname;
1105         settouch(this, Item_Touch);
1106         setmodel(this, MDL_Null); // precision set below
1107         //this.effects |= EF_LOWPRECISION;
1108
1109         // support skinned models for powerups
1110         if(!this.skin)
1111                 this.skin = def.m_skin;
1112
1113         setsize (this, this.pos1 =  def.m_mins, this.pos2 = def.m_maxs);
1114
1115         this.SendFlags |= ISF_SIZE;
1116
1117         if (!(this.spawnflags & 1024)) {
1118                 if(def.instanceOfPowerup)
1119                         this.ItemStatus |= ITS_ANIMATE1;
1120
1121                 if(GetResource(this, RES_ARMOR) || GetResource(this, RES_HEALTH))
1122                         this.ItemStatus |= ITS_ANIMATE2;
1123         }
1124
1125         if(Item_IsLoot(this))
1126                 this.gravity = 1;
1127         else
1128                 this.glowmod = def.m_color;
1129
1130         if(def.instanceOfWeaponPickup)
1131         {
1132                 if (!Item_IsLoot(this)) // if dropped, colormap is already set up nicely
1133                         this.colormap = 1024; // color shirt=0 pants=0 grey
1134                 if (!(this.spawnflags & 1024))
1135                         this.ItemStatus |= ITS_ANIMATE1;
1136                 this.SendFlags |= ISF_COLORMAP;
1137         }
1138
1139         this.state = 0;
1140         if(this.team)
1141         {
1142                 if(!this.cnt)
1143                         this.cnt = 1; // item probability weight
1144
1145                 this.effects |= EF_NOGUNBOB; // marker for item team search
1146                 InitializeEntity(this, Item_FindTeam, INITPRIO_FINDTARGET);
1147         }
1148         else
1149                 Item_Reset(this);
1150
1151         Net_LinkEntity(this, !(def.instanceOfPowerup || def.instanceOfHealth || def.instanceOfArmor), 0, ItemSend);
1152
1153         // call this hook after everything else has been done
1154         if (MUTATOR_CALLHOOK(Item_Spawn, this))
1155         {
1156                 startitem_failed = true;
1157                 delete(this);
1158                 return;
1159         }
1160
1161         setItemGroup(this);
1162 }
1163
1164 void StartItem(entity this, GameItem def)
1165 {
1166         def = def.m_spawnfunc_hookreplace(def, this);
1167
1168         if (def.spawnflags & ITEM_FLAG_MUTATORBLOCKED)
1169         {
1170                 delete(this);
1171                 return; // TODO does not set startitem_failed
1172         }
1173
1174         this.classname = def.m_canonical_spawnfunc;
1175
1176         _StartItem(
1177                 this,
1178                 this.itemdef = def,
1179                 def.m_respawntime(), // defaultrespawntime
1180                 def.m_respawntimejitter() // defaultrespawntimejitter
1181         );
1182 }
1183
1184 #define IS_SMALL(def) ((def.instanceOfHealth && def == ITEM_HealthSmall) || (def.instanceOfArmor && def == ITEM_ArmorSmall))
1185 int group_count = 1;
1186
1187 void setItemGroup(entity this)
1188 {
1189         if(!IS_SMALL(this.itemdef) || Item_IsLoot(this))
1190                 return;
1191
1192         FOREACH_ENTITY_RADIUS(this.origin, 120, (it != this) && IS_SMALL(it.itemdef),
1193         {
1194                 if(!this.item_group)
1195                 {
1196                         if(!it.item_group)
1197                         {
1198                                 it.item_group = group_count;
1199                                 group_count++;
1200                         }
1201                         this.item_group = it.item_group;
1202                 }
1203                 else // spawning item is already part of a item_group X
1204                 {
1205                         if(!it.item_group)
1206                                 it.item_group = this.item_group;
1207                         else if(it.item_group != this.item_group) // found an item near the spawning item that is part of a different item_group Y
1208                         {
1209                                 int grY = it.item_group;
1210                                 // move all items of item_group Y to item_group X
1211                                 IL_EACH(g_items, IS_SMALL(it.itemdef),
1212                                 {
1213                                         if(it.item_group == grY)
1214                                                 it.item_group = this.item_group;
1215                                 });
1216                         }
1217                 }
1218         });
1219 }
1220
1221 void setItemGroupCount()
1222 {
1223         for (int k = 1; k <= group_count; k++)
1224         {
1225                 int count = 0;
1226                 IL_EACH(g_items, IS_SMALL(it.itemdef) && it.item_group == k, { count++; });
1227                 if (count)
1228                         IL_EACH(g_items, IS_SMALL(it.itemdef) && it.item_group == k, { it.item_group_count = count; });
1229         }
1230 }
1231
1232 void target_items_use(entity this, entity actor, entity trigger)
1233 {
1234         if(Item_IsLoot(actor))
1235         {
1236                 EXACTTRIGGER_TOUCH(this, trigger);
1237                 delete(actor);
1238                 return;
1239         }
1240
1241         if (!IS_PLAYER(actor) || IS_DEAD(actor))
1242                 return;
1243
1244         if(trigger.solid == SOLID_TRIGGER)
1245         {
1246                 EXACTTRIGGER_TOUCH(this, trigger);
1247         }
1248
1249         IL_EACH(g_items, it.enemy == actor && Item_IsLoot(it),
1250         {
1251                 delete(it);
1252         });
1253
1254         if(GiveItems(actor, 0, tokenize_console(this.netname)))
1255                 centerprint(actor, this.message);
1256 }
1257
1258 spawnfunc(target_items)
1259 {
1260         this.use = target_items_use;
1261         if(!this.strength_finished)
1262                 this.strength_finished = autocvar_g_balance_powerup_strength_time;
1263         if(!this.invincible_finished)
1264                 this.invincible_finished = autocvar_g_balance_powerup_invincible_time;
1265         if(!this.speed_finished)
1266                 this.speed_finished = autocvar_g_balance_powerup_speed_time;
1267         if(!this.invisibility_finished)
1268                 this.invisibility_finished = autocvar_g_balance_powerup_invisibility_time;
1269         if(!this.superweapons_finished)
1270                 this.superweapons_finished = autocvar_g_balance_superweapons_time;
1271
1272         string str;
1273         int n = tokenize_console(this.netname);
1274         if(argv(0) == "give")
1275         {
1276                 str = substring(this.netname, argv_start_index(1), argv_end_index(-1) - argv_start_index(1));
1277         }
1278         else
1279         {
1280                 for(int j = 0; j < n; ++j)
1281                 {
1282                         // this is from a time when unlimited superweapons were handled together with ammo in some parts of the code
1283                         if     (argv(j) == "unlimited_ammo")         this.items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
1284                         else if(argv(j) == "unlimited_weapon_ammo")  this.items |= IT_UNLIMITED_AMMO;
1285                         else if(argv(j) == "unlimited_superweapons") this.items |= IT_UNLIMITED_SUPERWEAPONS;
1286                         else if(argv(j) == "strength")               this.items |= ITEM_Strength.m_itemid;
1287                         else if(argv(j) == "invincible")             this.items |= ITEM_Shield.m_itemid;
1288                         else if(argv(j) == "speed")                  this.items |= ITEM_Speed.m_itemid;
1289                         else if(argv(j) == "invisibility")           this.items |= ITEM_Invisibility.m_itemid;
1290                         else if(argv(j) == "superweapons")           this.items |= IT_SUPERWEAPON;
1291                         else if(argv(j) == "jetpack")                this.items |= ITEM_Jetpack.m_itemid;
1292                         else if(argv(j) == "fuel_regen")             this.items |= ITEM_JetpackRegen.m_itemid;
1293                         else
1294                         {
1295                                 FOREACH(StatusEffect, it.instanceOfBuff,
1296                                 {
1297                                         string s = Buff_CompatName(argv(j));
1298                                         if(s == it.netname)
1299                                         {
1300                                                 this.buffdef = it;
1301                                                 if(!this.buffs_finished)
1302                                                         this.buffs_finished = it.m_time(it);
1303                                                 break;
1304                                         }
1305                                 });
1306                                 FOREACH(Weapons, it != WEP_Null, {
1307                                         string s = argv(j);
1308                                         if(s == it.netname || s == it.m_deprecated_netname)
1309                                         {
1310                                                 STAT(WEAPONS, this) |= (it.m_wepset);
1311                                                 if(this.spawnflags == 0 || this.spawnflags == 2)
1312                                                         it.wr_init(it);
1313                                                 break;
1314                                         }
1315                                 });
1316                         }
1317                 }
1318
1319                 string itemprefix, valueprefix;
1320                 if(this.spawnflags == 0)
1321                 {
1322                         itemprefix = "";
1323                         valueprefix = "";
1324                 }
1325                 else if(this.spawnflags == 1)
1326                 {
1327                         itemprefix = "max ";
1328                         valueprefix = "max ";
1329                 }
1330                 else if(this.spawnflags == 2)
1331                 {
1332                         itemprefix = "min ";
1333                         valueprefix = "min ";
1334                 }
1335                 else if(this.spawnflags == 4)
1336                 {
1337                         itemprefix = "minus ";
1338                         valueprefix = "max ";
1339                 }
1340                 else
1341                 {
1342                         error("invalid spawnflags");
1343                         itemprefix = valueprefix = string_null;
1344                 }
1345
1346                 str = "";
1347                 str = sprintf("%s %s%d %s", str, itemprefix, boolean(this.items & IT_UNLIMITED_AMMO), "unlimited_weapon_ammo");
1348                 str = sprintf("%s %s%d %s", str, itemprefix, boolean(this.items & IT_UNLIMITED_SUPERWEAPONS), "unlimited_superweapons");
1349                 str = sprintf("%s %s%d %s", str, valueprefix, this.strength_finished * boolean(this.items & ITEM_Strength.m_itemid), "strength");
1350                 str = sprintf("%s %s%d %s", str, valueprefix, this.invincible_finished * boolean(this.items & ITEM_Shield.m_itemid), "invincible");
1351                 str = sprintf("%s %s%d %s", str, valueprefix, this.invisibility_finished * boolean(this.items & ITEM_Invisibility.m_itemid), "invisibility");
1352                 str = sprintf("%s %s%d %s", str, valueprefix, this.speed_finished * boolean(this.items & ITEM_Speed.m_itemid), "speed");
1353                 str = sprintf("%s %s%d %s", str, valueprefix, this.superweapons_finished * boolean(this.items & IT_SUPERWEAPON), "superweapons");
1354                 str = sprintf("%s %s%d %s", str, itemprefix, boolean(this.items & ITEM_Jetpack.m_itemid), "jetpack");
1355                 str = sprintf("%s %s%d %s", str, itemprefix, boolean(this.items & ITEM_JetpackRegen.m_itemid), "fuel_regen");
1356                 float res;
1357                 res = GetResource(this, RES_SHELLS);  if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "shells");
1358                 res = GetResource(this, RES_BULLETS); if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "nails");
1359                 res = GetResource(this, RES_ROCKETS); if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "rockets");
1360                 res = GetResource(this, RES_CELLS);   if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "cells");
1361                 res = GetResource(this, RES_PLASMA);  if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "plasma");
1362                 res = GetResource(this, RES_FUEL);    if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "fuel");
1363                 res = GetResource(this, RES_HEALTH);  if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "health");
1364                 res = GetResource(this, RES_ARMOR);   if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "armor");
1365                 FOREACH(StatusEffect, it.instanceOfBuff, str = sprintf("%s %s%d %s", str, valueprefix, this.buffs_finished * boolean(this.buffdef == it), it.netname));
1366                 FOREACH(Weapons, it != WEP_Null, str = sprintf("%s %s%d %s", str, itemprefix, !!(STAT(WEAPONS, this) & (it.m_wepset)), it.netname));
1367         }
1368         this.netname = strzone(str);
1369
1370         n = tokenize_console(this.netname);
1371         for(int j = 0; j < n; ++j)
1372         {
1373                 string cmd = argv(j);
1374                 FOREACH(Weapons, it != WEP_Null && (cmd == it.netname || cmd == it.m_deprecated_netname), {
1375                         it.wr_init(it);
1376                         break;
1377                 });
1378         }
1379 }
1380
1381 float GiveWeapon(entity e, float wpn, float op, float val)
1382 {
1383         WepSet v0, v1;
1384         WepSet s = WepSet_FromWeapon(REGISTRY_GET(Weapons, wpn));
1385         v0 = (STAT(WEAPONS, e) & s);
1386         switch(op)
1387         {
1388                 case OP_SET:
1389                         if(val > 0)
1390                                 STAT(WEAPONS, e) |= s;
1391                         else
1392                                 STAT(WEAPONS, e) &= ~s;
1393                         break;
1394                 case OP_MIN:
1395                 case OP_PLUS:
1396                         if(val > 0)
1397                                 STAT(WEAPONS, e) |= s;
1398                         break;
1399                 case OP_MAX:
1400                         if(val <= 0)
1401                                 STAT(WEAPONS, e) &= ~s;
1402                         break;
1403                 case OP_MINUS:
1404                         if(val > 0)
1405                                 STAT(WEAPONS, e) &= ~s;
1406                         break;
1407         }
1408         v1 = (STAT(WEAPONS, e) & s);
1409         return (v0 != v1);
1410 }
1411
1412 bool GiveBuff(entity e, Buff thebuff, int op, int val)
1413 {
1414         bool had_buff = StatusEffects_active(thebuff, e);
1415         float new_buff_time = ((had_buff) ? StatusEffects_gettime(thebuff, e) : 0);
1416         switch (op)
1417         {
1418                 case OP_SET:
1419                         new_buff_time = val;
1420                         break;
1421                 case OP_MIN:
1422                         new_buff_time = max(new_buff_time, val);
1423                         break;
1424                 case OP_MAX:
1425                         new_buff_time = min(new_buff_time, val);
1426                         break;
1427                 case OP_PLUS:
1428                         new_buff_time += val;
1429                         break;
1430                 case OP_MINUS:
1431                         new_buff_time -= val;
1432                         break;
1433         }
1434         if(new_buff_time <= 0)
1435         {
1436                 if(had_buff) // only trigger removal mechanics if there is an effect to remove!
1437                         StatusEffects_remove(thebuff, e, STATUSEFFECT_REMOVE_NORMAL);
1438         }
1439         else
1440         {
1441                 buff_RemoveAll(e, STATUSEFFECT_REMOVE_CLEAR); // clear old buffs on the player first!
1442                 StatusEffects_apply(thebuff, e, new_buff_time, 0);
1443         }
1444         bool have_buff = StatusEffects_active(thebuff, e);
1445         return (had_buff != have_buff);
1446 }
1447
1448 void GiveSound(entity e, float v0, float v1, float t, Sound snd_incr, Sound snd_decr)
1449 {
1450         if(v1 == v0)
1451                 return;
1452         if(v1 <= v0 - t)
1453         {
1454                 if(snd_decr != NULL)
1455                         sound(e, CH_TRIGGER, snd_decr, VOL_BASE, ATTEN_NORM);
1456         }
1457         else if(v0 >= v0 + t)
1458         {
1459                 if(snd_incr != NULL)
1460                         sound(e, ((snd_incr == SND_POWERUP) ? CH_TRIGGER_SINGLE : CH_TRIGGER), snd_incr, VOL_BASE, ATTEN_NORM);
1461         }
1462 }
1463
1464 void GiveRot(entity e, float v0, float v1, .float rotfield, float rottime, .float regenfield, float regentime)
1465 {
1466         if(v0 < v1)
1467                 e.(rotfield) = max(e.(rotfield), time + rottime);
1468         else if(v0 > v1)
1469                 e.(regenfield) = max(e.(regenfield), time + regentime);
1470 }
1471 bool GiveResourceValue(entity e, Resource res_type, int op, int val)
1472 {
1473         int v0 = GetResource(e, res_type);
1474         float new_val = 0;
1475         switch (op)
1476         {
1477                 // min 100 cells = at least 100 cells
1478                 case OP_SET: new_val = val; break;
1479                 case OP_MIN: new_val = max(v0, val); break;
1480                 case OP_MAX: new_val = min(v0, val); break;
1481                 case OP_PLUS: new_val = v0 + val; break;
1482                 case OP_MINUS: new_val = v0 - val; break;
1483                 default: return false;
1484         }
1485
1486         return SetResourceExplicit(e, res_type, new_val);
1487 }
1488 bool GiveStatusEffect(entity e, StatusEffects this, int op, float val)
1489 {
1490         bool had_eff = StatusEffects_active(this, e);
1491         float new_eff_time = ((had_eff) ? StatusEffects_gettime(this, e) : 0);
1492         switch (op)
1493         {
1494                 case OP_SET:
1495                         new_eff_time = val;
1496                         break;
1497                 case OP_MIN:
1498                         new_eff_time = max(new_eff_time, val);
1499                         break;
1500                 case OP_MAX:
1501                         new_eff_time = min(new_eff_time, val);
1502                         break;
1503                 case OP_PLUS:
1504                         new_eff_time += val;
1505                         break;
1506                 case OP_MINUS:
1507                         new_eff_time -= val;
1508                         break;
1509         }
1510         if(new_eff_time <= 0)
1511         {
1512                 if(had_eff) // only trigger removal mechanics if there is an effect to remove!
1513                         StatusEffects_remove(this, e, STATUSEFFECT_REMOVE_NORMAL);
1514         }
1515         else
1516                 StatusEffects_apply(this, e, new_eff_time, 0);
1517         bool have_eff = StatusEffects_active(this, e);
1518         return (had_eff != have_eff);
1519 }
1520
1521 float GiveItems(entity e, float beginarg, float endarg)
1522 {
1523         float got, i, val, op;
1524         string cmd;
1525
1526         val = 999;
1527         op = OP_SET;
1528
1529         got = 0;
1530
1531         int _switchweapon = 0;
1532
1533         if(CS_CVAR(e).cvar_cl_autoswitch)
1534         {
1535                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1536                 {
1537                         .entity weaponentity = weaponentities[slot];
1538                         if(e.(weaponentity).m_weapon != WEP_Null || slot == 0)
1539                         if(e.(weaponentity).m_switchweapon == w_getbestweapon(e, weaponentity))
1540                                 _switchweapon |= BIT(slot);
1541                 }
1542         }
1543
1544         if(e.statuseffects)
1545         {
1546                 FOREACH(StatusEffect, true,
1547                 {
1548                         e.statuseffects.statuseffect_time[it.m_id] = max(0, e.statuseffects.statuseffect_time[it.m_id] - time);
1549                 });
1550         }
1551
1552         PREGIVE(e, items);
1553         PREGIVE_WEAPONS(e);
1554         PREGIVE_STATUSEFFECT(e, STATUSEFFECT_Strength);
1555         PREGIVE_STATUSEFFECT(e, STATUSEFFECT_Shield);
1556         PREGIVE_STATUSEFFECT(e, STATUSEFFECT_Speed);
1557         PREGIVE_STATUSEFFECT(e, STATUSEFFECT_Invisibility);
1558         //PREGIVE_STATUSEFFECT(e, STATUSEFFECT_Superweapons);
1559         PREGIVE_RESOURCE(e, RES_BULLETS);
1560         PREGIVE_RESOURCE(e, RES_CELLS);
1561         PREGIVE_RESOURCE(e, RES_PLASMA);
1562         PREGIVE_RESOURCE(e, RES_SHELLS);
1563         PREGIVE_RESOURCE(e, RES_ROCKETS);
1564         PREGIVE_RESOURCE(e, RES_FUEL);
1565         PREGIVE_RESOURCE(e, RES_ARMOR);
1566         PREGIVE_RESOURCE(e, RES_HEALTH);
1567
1568         for(i = beginarg; i < endarg; ++i)
1569         {
1570                 cmd = argv(i);
1571
1572                 if(cmd == "0" || stof(cmd))
1573                 {
1574                         val = stof(cmd);
1575                         continue;
1576                 }
1577                 switch(cmd)
1578                 {
1579                         case "no":
1580                                 op = OP_MAX;
1581                                 val = 0;
1582                                 continue;
1583                         case "max":
1584                                 op = OP_MAX;
1585                                 continue;
1586                         case "min":
1587                                 op = OP_MIN;
1588                                 continue;
1589                         case "plus":
1590                                 op = OP_PLUS;
1591                                 continue;
1592                         case "minus":
1593                                 op = OP_MINUS;
1594                                 continue;
1595                         case "ALL":
1596                                 got += GiveBit(e, items, ITEM_JetpackRegen.m_itemid, op, val);
1597                                 FOREACH(StatusEffect, it.instanceOfPowerups, got += GiveStatusEffect(e, it, op, val));
1598                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS, op, val);
1599                         case "all":
1600                                 got += GiveBit(e, items, ITEM_Jetpack.m_itemid, op, val);
1601                                 got += GiveResourceValue(e, RES_HEALTH, op, val);
1602                                 got += GiveResourceValue(e, RES_ARMOR, op, val);
1603                         case "allweapons":
1604                                 FOREACH(Weapons, it != WEP_Null && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)), got += GiveWeapon(e, it.m_id, op, val));
1605                         //case "allbuffs": // all buffs makes a player god, do not want!
1606                                 //FOREACH(StatusEffect, it.instanceOfBuff, got += GiveBuff(e, it, op, val));
1607                         case "allammo":
1608                                 got += GiveResourceValue(e, RES_CELLS, op, val);
1609                                 got += GiveResourceValue(e, RES_PLASMA, op, val);
1610                                 got += GiveResourceValue(e, RES_SHELLS, op, val);
1611                                 got += GiveResourceValue(e, RES_BULLETS, op, val);
1612                                 got += GiveResourceValue(e, RES_ROCKETS, op, val);
1613                                 got += GiveResourceValue(e, RES_FUEL, op, val);
1614                                 break;
1615                         case "unlimited_ammo":
1616                                 // this is from a time when unlimited superweapons were handled together with ammo in some parts of the code
1617                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS, op, val);
1618                                 break;
1619                         case "unlimited_weapon_ammo":
1620                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO, op, val);
1621                                 break;
1622                         case "unlimited_superweapons":
1623                                 got += GiveBit(e, items, IT_UNLIMITED_SUPERWEAPONS, op, val);
1624                                 break;
1625                         case "jetpack":
1626                                 got += GiveBit(e, items, ITEM_Jetpack.m_itemid, op, val);
1627                                 break;
1628                         case "fuel_regen":
1629                                 got += GiveBit(e, items, ITEM_JetpackRegen.m_itemid, op, val);
1630                                 break;
1631                         case "strength":
1632                                 got += GiveStatusEffect(e, STATUSEFFECT_Strength, op, val);
1633                                 break;
1634                         case "invincible":
1635                         case "shield":
1636                                 got += GiveStatusEffect(e, STATUSEFFECT_Shield, op, val);
1637                                 break;
1638                         case "speed":
1639                                 got += GiveStatusEffect(e, STATUSEFFECT_Speed, op, val);
1640                                 break;
1641                         case "invisibility":
1642                                 got += GiveStatusEffect(e, STATUSEFFECT_Invisibility, op, val);
1643                                 break;
1644                         case "superweapons":
1645                                 got += GiveStatusEffect(e, STATUSEFFECT_Superweapons, op, val);
1646                                 break;
1647                         case "cells":
1648                                 got += GiveResourceValue(e, RES_CELLS, op, val);
1649                                 break;
1650                         case "plasma":
1651                                 got += GiveResourceValue(e, RES_PLASMA, op, val);
1652                                 break;
1653                         case "shells":
1654                                 got += GiveResourceValue(e, RES_SHELLS, op, val);
1655                                 break;
1656                         case "nails":
1657                         case "bullets":
1658                                 got += GiveResourceValue(e, RES_BULLETS, op, val);
1659                                 break;
1660                         case "rockets":
1661                                 got += GiveResourceValue(e, RES_ROCKETS, op, val);
1662                                 break;
1663                         case "health":
1664                                 got += GiveResourceValue(e, RES_HEALTH, op, val);
1665                                 break;
1666                         case "armor":
1667                                 got += GiveResourceValue(e, RES_ARMOR, op, val);
1668                                 break;
1669                         case "fuel":
1670                                 got += GiveResourceValue(e, RES_FUEL, op, val);
1671                                 break;
1672                         default:
1673                                 FOREACH(StatusEffect, it.instanceOfBuff && buff_Available(it) && Buff_CompatName(cmd) == it.netname,
1674                                 {
1675                                         got += GiveBuff(e, it, op, val);
1676                                         break;
1677                                 });
1678                                 FOREACH(Weapons, it != WEP_Null && (cmd == it.netname || cmd == it.m_deprecated_netname), {
1679                     got += GiveWeapon(e, it.m_id, op, val);
1680                     break;
1681                                 });
1682                                 break;
1683                 }
1684                 val = 999;
1685                 op = OP_SET;
1686         }
1687
1688         POSTGIVE_BIT(e, items, ITEM_JetpackRegen.m_itemid, SND_ITEMPICKUP, SND_Null);
1689         POSTGIVE_BIT(e, items, IT_UNLIMITED_SUPERWEAPONS, SND_POWERUP, SND_POWEROFF);
1690         POSTGIVE_BIT(e, items, IT_UNLIMITED_AMMO, SND_POWERUP, SND_POWEROFF);
1691         POSTGIVE_BIT(e, items, ITEM_Jetpack.m_itemid, SND_ITEMPICKUP, SND_Null);
1692         FOREACH(Weapons, it != WEP_Null, {
1693                 POSTGIVE_WEAPON(e, it, SND_WEAPONPICKUP, SND_Null);
1694                 if(!(save_weapons & (it.m_wepset)))
1695                         if(STAT(WEAPONS, e) & (it.m_wepset))
1696                                 it.wr_init(it);
1697         });
1698         POSTGIVE_STATUSEFFECT(e, STATUSEFFECT_Strength, SND_POWERUP, SND_POWEROFF);
1699         POSTGIVE_STATUSEFFECT(e, STATUSEFFECT_Shield, SND_POWERUP, SND_POWEROFF);
1700         POSTGIVE_STATUSEFFECT(e, STATUSEFFECT_Speed, SND_POWERUP, SND_POWEROFF);
1701         POSTGIVE_STATUSEFFECT(e, STATUSEFFECT_Invisibility, SND_POWERUP, SND_POWEROFF);
1702         POSTGIVE_RESOURCE(e, RES_BULLETS, 0, SND_ITEMPICKUP, SND_Null);
1703         POSTGIVE_RESOURCE(e, RES_CELLS, 0, SND_ITEMPICKUP, SND_Null);
1704         POSTGIVE_RESOURCE(e, RES_PLASMA, 0, SND_ITEMPICKUP, SND_Null);
1705         POSTGIVE_RESOURCE(e, RES_SHELLS, 0, SND_ITEMPICKUP, SND_Null);
1706         POSTGIVE_RESOURCE(e, RES_ROCKETS, 0, SND_ITEMPICKUP, SND_Null);
1707         POSTGIVE_RES_ROT(e, RES_FUEL, 1, pauserotfuel_finished, autocvar_g_balance_pause_fuel_rot, pauseregen_finished, autocvar_g_balance_pause_fuel_regen, SND_ITEMPICKUP, SND_Null);
1708         POSTGIVE_RES_ROT(e, RES_ARMOR, 1, pauserotarmor_finished, autocvar_g_balance_pause_armor_rot, pauseregen_finished, autocvar_g_balance_pause_health_regen, SND_ARMOR25, SND_Null);
1709         POSTGIVE_RES_ROT(e, RES_HEALTH, 1, pauserothealth_finished, autocvar_g_balance_pause_health_rot, pauseregen_finished, autocvar_g_balance_pause_health_regen, SND_MEGAHEALTH, SND_Null);
1710
1711         if(!StatusEffects_active(STATUSEFFECT_Superweapons, e))
1712         {
1713                 if(!g_weaponarena && (STAT(WEAPONS, e) & WEPSET_SUPERWEAPONS))
1714                         StatusEffects_apply(STATUSEFFECT_Superweapons, e, autocvar_g_balance_superweapons_time, 0);
1715         }
1716
1717         if(e.statuseffects)
1718         {
1719                 FOREACH(StatusEffect, true,
1720                 {
1721                         if(e.statuseffects.statuseffect_time[it.m_id] <= 0)
1722                                 e.statuseffects.statuseffect_time[it.m_id] = 0;
1723                         else
1724                                 e.statuseffects.statuseffect_time[it.m_id] += time;
1725                 });
1726                         
1727                 StatusEffects_update(e);
1728         }
1729
1730         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1731         {
1732                 .entity weaponentity = weaponentities[slot];
1733                 if(e.(weaponentity).m_weapon != WEP_Null || slot == 0)
1734                 if(!(STAT(WEAPONS, e) & WepSet_FromWeapon(e.(weaponentity).m_switchweapon)))
1735                         _switchweapon |= BIT(slot);
1736         }
1737
1738         if(_switchweapon)
1739         {
1740                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1741                 {
1742                         .entity weaponentity = weaponentities[slot];
1743                         if(_switchweapon & BIT(slot))
1744                         {
1745                                 Weapon wep = w_getbestweapon(e, weaponentity);
1746                                 if(wep != e.(weaponentity).m_switchweapon)
1747                                         W_SwitchWeapon_Force(e, wep, weaponentity);
1748                         }
1749                 }
1750         }
1751
1752         return got;
1753 }