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