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