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