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