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