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