forked from CleverRaven/Cataclysm-DDA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ranged.cpp
3728 lines (3317 loc) · 145 KB
/
ranged.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "ranged.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <iterator>
#include <map>
#include <memory>
#include <new>
#include <set>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "activity_actor_definitions.h"
#include "avatar.h"
#include "ballistics.h"
#include "cached_options.h"
#include "calendar.h"
#include "cata_utility.h"
#include "catacharset.h"
#include "character.h"
#include "color.h"
#include "creature.h"
#include "creature_tracker.h"
#include "cursesdef.h"
#include "damage.h"
#include "debug.h"
#include "dispersion.h"
#include "enums.h"
#include "event.h"
#include "event_bus.h"
#include "flag.h"
#include "game.h"
#include "game_constants.h"
#include "gun_mode.h"
#include "input.h"
#include "item.h"
#include "item_location.h"
#include "item_pocket.h"
#include "itype.h"
#include "line.h"
#include "magic.h"
#include "map.h"
#include "math_defines.h"
#include "memory_fast.h"
#include "messages.h"
#include "monster.h"
#include "morale_types.h"
#include "mtype.h"
#include "npc.h"
#include "optional.h"
#include "options.h"
#include "output.h"
#include "panels.h"
#include "point.h"
#include "projectile.h"
#include "ret_val.h"
#include "rng.h"
#include "skill.h"
#include "sounds.h"
#include "string_formatter.h"
#include "translations.h"
#include "trap.h"
#include "try_parse_integer.h"
#include "type_id.h"
#include "ui.h"
#include "ui_manager.h"
#include "units.h"
#include "units_utility.h"
#include "value_ptr.h"
#include "vehicle.h"
#include "vpart_position.h"
#include "weakpoint.h"
static const bionic_id bio_railgun( "bio_railgun" );
static const character_modifier_id
character_modifier_melee_thrown_move_balance_mod( "melee_thrown_move_balance_mod" );
static const character_modifier_id
character_modifier_melee_thrown_move_manip_mod( "melee_thrown_move_manip_mod" );
static const character_modifier_id
character_modifier_ranged_dispersion_manip_mod( "ranged_dispersion_manip_mod" );
static const character_modifier_id character_modifier_thrown_dex_mod( "thrown_dex_mod" );
static const efftype_id effect_downed( "downed" );
static const efftype_id effect_hit_by_player( "hit_by_player" );
static const efftype_id effect_on_roof( "on_roof" );
static const fault_id fault_gun_blackpowder( "fault_gun_blackpowder" );
static const fault_id fault_gun_chamber_spent( "fault_gun_chamber_spent" );
static const fault_id fault_gun_dirt( "fault_gun_dirt" );
static const itype_id itype_12mm( "12mm" );
static const itype_id itype_40x46mm( "40x46mm" );
static const itype_id itype_40x53mm( "40x53mm" );
static const itype_id itype_66mm( "66mm" );
static const itype_id itype_84x246mm( "84x246mm" );
static const itype_id itype_arrow( "arrow" );
static const itype_id itype_bolt( "bolt" );
static const itype_id itype_flammable( "flammable" );
static const itype_id itype_m235( "m235" );
static const itype_id itype_metal_rail( "metal_rail" );
static const material_id material_glass( "glass" );
static const material_id material_iron( "iron" );
static const material_id material_steel( "steel" );
static const proficiency_id proficiency_prof_bow_basic( "prof_bow_basic" );
static const proficiency_id proficiency_prof_bow_expert( "prof_bow_expert" );
static const proficiency_id proficiency_prof_bow_master( "prof_bow_master" );
static const skill_id skill_archery( "archery" );
static const skill_id skill_dodge( "dodge" );
static const skill_id skill_driving( "driving" );
static const skill_id skill_gun( "gun" );
static const skill_id skill_launcher( "launcher" );
static const skill_id skill_throw( "throw" );
static const trait_id trait_PYROMANIA( "PYROMANIA" );
static const trap_str_id tr_practice_target( "tr_practice_target" );
static const std::set<material_id> ferric = { material_iron, material_steel };
// Maximum duration of aim-and-fire loop, in turns
static constexpr int AIF_DURATION_LIMIT = 10;
static projectile make_gun_projectile( const item &gun );
static int time_to_attack( const Character &p, const itype &firing );
/**
* Handle spent ammo casings and linkages.
* @param weap Weapon.
* @param ammo Ammo used.
* @param pos Character position.
*/
static void cycle_action( item &weap, const itype_id &ammo, const tripoint &pos );
static void make_gun_sound_effect( const Character &p, bool burst, item *weapon );
class target_ui
{
public:
/* None of the public members (except ammo and range) should be modified during execution */
enum class TargetMode : int {
Fire,
Throw,
ThrowBlind,
Turrets,
TurretManual,
Reach,
Spell
};
// Avatar
avatar *you;
// Interface mode
TargetMode mode = TargetMode::Fire;
// Weapon being fired/thrown
item *relevant = nullptr;
// Cached selection range from player's position
int range = 0;
// Cached current ammo to display
const itype *ammo = nullptr;
// Turret being manually fired
turret_data *turret = nullptr;
// Turrets being fired (via vehicle controls)
const std::vector<vehicle_part *> *vturrets = nullptr;
// Vehicle that turrets belong to
vehicle *veh = nullptr;
// Spell being cast
spell *casting = nullptr;
// Spell cannot fail
bool no_fail = false;
// Spell does not require mana
bool no_mana = false;
// Relevant activity
aim_activity_actor *activity = nullptr;
enum class ExitCode : int {
Abort,
Fire,
Timeout,
Reload
};
// Initialize UI and run the event loop
target_handler::trajectory run();
private:
enum class Status : int {
Good, // All UI elements are enabled
BadTarget, // Bad 'dst' selected; forbid aiming/firing
OutOfAmmo, // Selected gun mode is out of ammo; forbid moving cursor,aiming and firing
OutOfRange // Selected target is out of range of current gun mode; forbid aiming/firing
};
// Ui status (affects which UI controls are temporarily disabled)
Status status = Status::Good;
// Current trajectory
std::vector<tripoint> traj;
// Aiming source (player's position)
tripoint src;
// Aiming destination (cursor position)
// Use set_cursor_pos() to modify
tripoint dst;
// Creature currently under cursor. nullptr if aiming at empty tile,
// yourself or a creature you cannot see
Creature *dst_critter = nullptr;
// List of visible hostile targets
std::vector<Creature *> targets;
// 'true' if map has z levels and 3D fov is on
bool allow_zlevel_shift = false;
// Snap camera to cursor. Can be permanently toggled in settings
// or temporarily in this window
bool snap_to_target = false;
// If true, LEVEL_UP, LEVEL_DOWN and directional keys
// responsible for moving cursor will shift view instead.
bool shifting_view = false;
// Compact layout
bool compact = false;
// Tiny layout - when extremely short on space
bool tiny = false;
// Narrow layout - to keep in theme with
// "compact" and "labels-narrow" sidebar styles.
bool narrow = false;
// Window
catacurses::window w_target;
// Input context
input_context ctxt;
/* These members are relevant for TargetMode::Fire */
// Weapon sight dispersion
int sight_dispersion = 0;
// List of available weapon aim types
std::vector<aim_type> aim_types;
// Currently selected aim mode
std::vector<aim_type>::iterator aim_mode;
// 'Recoil' value the player will reach if they
// start aiming at cursor position. Equals player's
// 'recoil' while they are actively spending moves to aim,
// but increases the further away the new aim point will be
// relative to the current one.
double predicted_recoil = 0;
// For AOE spells, list of tiles affected by the spell
// relevant for TargetMode::Spell
std::set<tripoint> spell_aoe;
// Represents a turret and a straight line from that turret to target
struct turret_with_lof {
vehicle_part *turret;
std::vector<tripoint> line;
};
// List of vehicle turrets in range (out of those listed in 'vturrets')
std::vector<turret_with_lof> turrets_in_range;
// If true, draws turret lines
// relevant for TargetMode::Turrets
bool draw_turret_lines = false;
// Create window and set up input context
void init_window_and_input();
// Handle input related to cursor movement.
// Returns 'true' if action was recognized and processed.
// 'skip_redraw' is set to 'true' if there is no need to redraw the UI.
bool handle_cursor_movement( const std::string &action, bool &skip_redraw );
// Set cursor position. If new position is out of range,
// selects closest position in range.
// Returns 'false' if cursor position did not change
bool set_cursor_pos( const tripoint &new_pos );
// Called when range/ammo changes (or may have changed)
void on_range_ammo_changed();
// Updates 'targets' for current range
void update_target_list();
// Choose where to position the cursor when opening the ui
tripoint choose_initial_target();
/**
* Try to re-acquire target for aim-and-fire.
* @param critter whether were aiming at a critter, or a tile
* @param new_dst where to move aim cursor (if e.g. critter moved)
* @returns true on success
*/
bool try_reacquire_target( bool critter, tripoint &new_dst );
// Update 'status' variable
void update_status();
// Calculates distance from 'src'. For consistency, prefer using this over rl_dist.
int dist_fn( const tripoint &p );
// Set creature (or tile) under cursor as player's last target
void set_last_target();
// Prompts player to confirm attack on neutral NPC
// Returns 'true' if attack should proceed
bool confirm_non_enemy_target();
// Prompts player to re-confirm an ongoing attack if
// a non-hostile NPC / friendly creatures enters line of fire.
// Returns 'true' if attack should proceed
bool prompt_friendlies_in_lof();
// List friendly creatures currently occupying line of fire.
std::vector<weak_ptr_fast<Creature>> list_friendlies_in_lof();
// Toggle snap-to-target
void toggle_snap_to_target();
// Cycle targets. 'direction' is either 1 or -1
void cycle_targets( int direction );
// Set new view offset. Updates map cache if necessary
void set_view_offset( const tripoint &new_offset );
// Updates 'turrets_in_range'
void update_turrets_in_range();
// Recalculate 'recoil' penalty. This should be called if
// avatar's 'recoil' value has been modified
// Relevant for TargetMode::Fire
void recalc_aim_turning_penalty();
// Apply penalty to avatar's 'recoil' value based on
// how much they moved their aim point.
// Relevant for TargetMode::Fire
void apply_aim_turning_penalty();
// Switch firing mode.
bool action_switch_mode();
// Switch ammo. Returns 'false' if requires a reloading UI.
bool action_switch_ammo();
// Aim for 10 turns. Returns 'false' if ran out of moves
bool action_aim();
// Aim and shoot. Returns 'false' if ran out of moves
bool action_aim_and_shoot( const std::string &action );
// Draw UI-specific terrain overlays
void draw_terrain_overlay();
// Draw aiming window
void draw_ui_window();
// Generate ui window title
std::string uitext_title();
// Generate flavor text for 'Fire!' key
std::string uitext_fire();
void draw_window_title();
void draw_help_notice();
// Draw list of available controls at the bottom of the window.
// text_y - first free line counting from the top
void draw_controls_list( int text_y );
void panel_cursor_info( int &text_y );
void panel_gun_info( int &text_y );
void panel_recoil( int &text_y );
void panel_spell_info( int &text_y );
void panel_target_info( int &text_y, bool fill_with_blank_if_no_target );
void panel_fire_mode_aim( int &text_y );
void panel_turret_list( int &text_y );
// On-selected-as-target checks that act as if they are on-hit checks.
// `harmful` is `false` if using a non-damaging spell
void on_target_accepted( bool harmful );
};
target_handler::trajectory target_handler::mode_fire( avatar &you, aim_activity_actor &activity )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::Fire;
ui.activity = &activity;
ui.relevant = activity.get_weapon();
gun_mode gun = ui.relevant->gun_current_mode();
ui.range = gun.target->gun_range( &you );
ui.ammo = gun->ammo_data();
return ui.run();
}
target_handler::trajectory target_handler::mode_throw( avatar &you, item &relevant,
bool blind_throwing )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = blind_throwing ? target_ui::TargetMode::ThrowBlind : target_ui::TargetMode::Throw;
ui.relevant = &relevant;
ui.range = you.throw_range( relevant );
return ui.run();
}
target_handler::trajectory target_handler::mode_reach( avatar &you, item &weapon )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::Reach;
ui.relevant = &weapon;
ui.range = weapon.current_reach_range( you );
return ui.run();
}
target_handler::trajectory target_handler::mode_turret_manual( avatar &you, turret_data &turret )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::TurretManual;
ui.turret = &turret;
ui.relevant = &*turret.base();
ui.range = turret.range();
ui.ammo = turret.ammo_data();
return ui.run();
}
target_handler::trajectory target_handler::mode_turrets( avatar &you, vehicle &veh,
const std::vector<vehicle_part *> &turrets )
{
// Find radius of a circle centered at u encompassing all points turrets can aim at
// FIXME: this calculation is fine for square distances, but results in an underestimation
// when used with real circles
int range_total = 0;
for( vehicle_part *t : turrets ) {
int range = veh.turret_query( *t ).range();
tripoint pos = veh.global_part_pos3( *t );
int res = 0;
res = std::max( res, rl_dist( you.pos(), pos + point( range, 0 ) ) );
res = std::max( res, rl_dist( you.pos(), pos + point( -range, 0 ) ) );
res = std::max( res, rl_dist( you.pos(), pos + point( 0, range ) ) );
res = std::max( res, rl_dist( you.pos(), pos + point( 0, -range ) ) );
range_total = std::max( range_total, res );
}
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::Turrets;
ui.veh = &veh;
ui.vturrets = &turrets;
ui.range = range_total;
return ui.run();
}
target_handler::trajectory target_handler::mode_spell( avatar &you, spell &casting, bool no_fail,
bool no_mana )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::Spell;
ui.casting = &casting;
ui.range = casting.range();
ui.no_fail = no_fail;
ui.no_mana = no_mana;
return ui.run();
}
static double occupied_tile_fraction( creature_size target_size )
{
switch( target_size ) {
case creature_size::tiny:
return 0.1;
case creature_size::small:
return 0.25;
case creature_size::medium:
return 0.5;
case creature_size::large:
return 0.75;
case creature_size::huge:
return 1.0;
case creature_size::num_sizes:
debugmsg( "ERROR: Invalid Creature size class." );
break;
}
return 0.5;
}
double Creature::ranged_target_size() const
{
if( has_flag( MF_HARDTOSHOOT ) ) {
switch( get_size() ) {
case creature_size::tiny:
case creature_size::small:
return occupied_tile_fraction( creature_size::tiny );
case creature_size::medium:
return occupied_tile_fraction( creature_size::small );
case creature_size::large:
return occupied_tile_fraction( creature_size::medium );
case creature_size::huge:
return occupied_tile_fraction( creature_size::large );
case creature_size::num_sizes:
debugmsg( "ERROR: Invalid Creature size class." );
break;
}
}
return occupied_tile_fraction( get_size() );
}
int range_with_even_chance_of_good_hit( int dispersion )
{
int even_chance_range = 0;
while( static_cast<unsigned>( even_chance_range ) <
Creature::dispersion_for_even_chance_of_good_hit.size() &&
dispersion < Creature::dispersion_for_even_chance_of_good_hit[ even_chance_range ] ) {
even_chance_range++;
}
return even_chance_range;
}
int Character::gun_engagement_moves( const item &gun, int target, int start,
Target_attributes attributes ) const
{
int mv = 0;
double penalty = start;
while( penalty > target ) {
double adj = aim_per_move( gun, penalty, attributes );
if( adj <= 0 ) {
break;
}
penalty -= adj;
mv++;
}
return mv;
}
bool Character::handle_gun_damage( item &it )
{
// Below item (maximum dirt possible) should be greater than or equal to dirt range in item_group.cpp. Also keep in mind that monster drops can have specific ranges and these should be below the max!
const double dirt_max_dbl = 10000;
if( !it.is_gun() ) {
debugmsg( "Tried to handle_gun_damage of a non-gun %s", it.tname() );
return false;
}
int dirt = it.get_var( "dirt", 0 );
int dirtadder = 0;
double dirt_dbl = static_cast<double>( dirt );
if( it.has_fault_flag( "JAMMED_GUN" ) ) {
return false;
}
const auto &curammo_effects = it.ammo_effects();
const islot_gun &firing = *it.type->gun;
// misfire chance based on dirt accumulation. Formula is designed to make chance of jam highly unlikely at low dirt levels, but levels increase geometrically as the dirt level reaches max (10,000). The number used is just a figure I found reasonable after plugging the number into excel and changing it until the probability made sense at high, medium, and low levels of dirt.
if( !it.has_flag( flag_NEVER_JAMS ) &&
x_in_y( dirt_dbl * dirt_dbl * dirt_dbl,
1000000000000.0 ) ) {
add_msg_player_or_npc(
_( "Your %s misfires with a muffled click!" ),
_( "<npcname>'s %s misfires with a muffled click!" ),
it.tname() );
// at high dirt levels the chance to misfire gets to significant levels. 10,000 is max and 7800 is quite high so above that the player gets some relief in the form of exchanging time for some dirt reduction. Basically jiggling the parts loose to remove some dirt and get a few more shots out.
if( dirt_dbl >
7800 ) {
add_msg_player_or_npc(
_( "Perhaps taking the ammo out of your %s and reloading will help." ),
_( "Perhaps taking the ammo out of <npcname>'s %s and reloading will help." ),
it.tname() );
}
return false;
}
// Here we check if we're underwater and whether we should misfire.
// As a result this causes no damage to the firearm, note that some guns are waterproof
// and so are immune to this effect, note also that WATERPROOF_GUN status does not
// mean the gun will actually be accurate underwater.
int effective_durability = firing.durability;
if( is_underwater() && !it.has_flag( flag_WATERPROOF_GUN ) && one_in( effective_durability ) ) {
add_msg_player_or_npc( _( "Your %s misfires with a wet click!" ),
_( "<npcname>'s %s misfires with a wet click!" ),
it.tname() );
return false;
// Here we check for a chance for the weapon to suffer a mechanical malfunction.
// Note that some weapons never jam up 'NEVER_JAMS' and thus are immune to this
// effect as current guns have a durability between 5 and 9 this results in
// a chance of mechanical failure between 1/(64*3) and 1/(1024*3) on any given shot.
// the malfunction can't cause damage
} else if( one_in( ( 2 << effective_durability ) * 3 ) && !it.has_flag( flag_NEVER_JAMS ) ) {
add_msg_player_or_npc( _( "Your %s malfunctions!" ),
_( "<npcname>'s %s malfunctions!" ),
it.tname() );
return false;
// Here we check for a chance for the weapon to suffer a misfire due to
// using player-made 'RECYCLED' bullets. Note that not all forms of
// player-made ammunition have this effect.
} else if( curammo_effects.count( "RECYCLED" ) && one_in( 256 ) ) {
add_msg_player_or_npc( _( "Your %s misfires with a muffled click!" ),
_( "<npcname>'s %s misfires with a muffled click!" ),
it.tname() );
return false;
// Here we check for a chance for attached mods to get damaged if they are flagged as 'CONSUMABLE'.
// This is mostly for crappy handmade expedient stuff or things that rarely receive damage during normal usage.
// Default chance is 1/10000 unless set via json, damage is proportional to caliber(see below).
// Can be toned down with 'consume_divisor.'
} else if( it.has_flag( flag_CONSUMABLE ) && !curammo_effects.count( "LASER" ) &&
!curammo_effects.count( "PLASMA" ) && !curammo_effects.count( "EMP" ) ) {
int uncork = ( ( 10 * it.ammo_data()->ammo->loudness )
+ ( it.ammo_data()->ammo->recoil / 2 ) ) / 100;
uncork = std::pow( uncork, 3 ) * 6.5;
for( item *mod : it.gunmods() ) {
if( mod->has_flag( flag_CONSUMABLE ) ) {
int dmgamt = uncork / mod->type->gunmod->consume_divisor;
int modconsume = mod->type->gunmod->consume_chance;
int initstate = it.damage();
// fuzz damage if it's small
if( dmgamt < 1000 ) {
dmgamt = rng( dmgamt, dmgamt + 200 );
// ignore damage if inconsequential.
}
if( dmgamt < 800 ) {
dmgamt = 0;
}
if( one_in( modconsume ) ) {
if( mod->mod_damage( dmgamt ) ) {
add_msg_player_or_npc( m_bad, _( "Your attached %s is destroyed by your shot!" ),
_( "<npcname>'s attached %s is destroyed by their shot!" ),
mod->tname() );
i_rem( mod );
} else if( it.damage() > initstate ) {
add_msg_player_or_npc( m_bad, _( "Your attached %s is damaged by your shot!" ),
_( "<npcname>'s %s is damaged by their shot!" ),
mod->tname() );
}
}
}
}
}
if( it.has_fault_flag( "UNLUBRICATED" ) &&
x_in_y( dirt_dbl, dirt_max_dbl ) ) {
add_msg_player_or_npc( m_bad, _( "Your %s emits a grimace-inducing screech!" ),
_( "<npcname>'s %s emits a grimace-inducing screech!" ),
it.tname() );
it.inc_damage();
}
if( !it.has_flag( flag_PRIMITIVE_RANGED_WEAPON ) ) {
if( it.ammo_data() != nullptr && ( ( it.ammo_data()->ammo->recoil < firing.min_cycle_recoil ) ||
( it.has_fault_flag( "BAD_CYCLING" ) && one_in( 16 ) ) ) &&
it.faults_potential().count( fault_gun_chamber_spent ) ) {
add_msg_player_or_npc( m_bad, _( "Your %s fails to cycle!" ),
_( "<npcname>'s %s fails to cycle!" ),
it.tname() );
it.faults.insert( fault_gun_chamber_spent );
// Don't return false in this case; this shot happens, follow-up ones won't.
}
// These are the dirtying/fouling mechanics
if( !curammo_effects.count( "NON_FOULING" ) && !it.has_flag( flag_NON_FOULING ) ) {
if( dirt < static_cast<int>( dirt_max_dbl ) ) {
dirtadder = curammo_effects.count( "BLACKPOWDER" ) * ( 200 - firing.blackpowder_tolerance *
2 );
// dirtadder is the dirt-increasing number for shots fired with gunpowder-based ammo. Usually dirt level increases by 1, unless it's blackpowder, in which case it increases by a higher number, but there is a reduction for blackpowder resistance of a weapon.
if( dirtadder < 0 ) {
dirtadder = 0;
}
// in addition to increasing dirt level faster, regular gunpowder fouling is also capped at 7,150, not 10,000. So firing with regular gunpowder can never make the gun quite as bad as firing it with black gunpowder. At 7,150 the chance to jam is significantly lower (though still significant) than it is at 10,000, the absolute cap.
if( curammo_effects.count( "BLACKPOWDER" ) ||
dirt < 7150 ) {
it.set_var( "dirt", std::min( static_cast<int>( dirt_max_dbl ), dirt + dirtadder + 1 ) );
}
}
dirt = it.get_var( "dirt", 0 );
dirt_dbl = static_cast<double>( dirt );
if( dirt > 0 && !it.has_fault_flag( "NO_DIRTYING" ) ) {
it.faults.insert( fault_gun_dirt );
}
if( dirt > 0 && curammo_effects.count( "BLACKPOWDER" ) ) {
it.faults.erase( fault_gun_dirt );
it.faults.insert( fault_gun_blackpowder );
}
// end fouling mechanics
}
}
// chance to damage gun due to high levels of dirt. Very unlikely, especially at lower levels and impossible below 5,000. Lower than the chance of a jam at the same levels. 555555... is an arbitrary number that I came up with after playing with the formula in excel. It makes sense at low, medium, and high levels of dirt.
if( dirt_dbl > 5000 &&
x_in_y( dirt_dbl * dirt_dbl * dirt_dbl,
5555555555555 ) ) {
add_msg_player_or_npc( m_bad, _( "Your %s is damaged by the high pressure!" ),
_( "<npcname>'s %s is damaged by the high pressure!" ),
it.tname() );
// Don't increment until after the message
it.inc_damage();
}
return true;
}
void npc::pretend_fire( npc *source, int shots, item &gun )
{
int curshot = 0;
if( one_in( 50 ) ) {
add_msg_if_player_sees( *source, m_info, _( "%s shoots something." ), source->disp_name() );
}
while( curshot != shots ) {
const int required = gun.ammo_required();
if( gun.ammo_consume( required, pos(), this ) != required ) {
debugmsg( "Unexpected shortage of ammo whilst firing %s", gun.tname().c_str() );
break;
}
item *weapon = &gun;
const item::sound_data data = weapon->gun_noise( shots > 1 );
add_msg_if_player_sees( *source, m_warning, _( "You hear %s." ), data.sound );
curshot++;
moves -= 100;
}
}
int Character::fire_gun( const tripoint &target, int shots )
{
return fire_gun( target, shots, get_wielded_item() );
}
int Character::fire_gun( const tripoint &target, int shots, item &gun )
{
if( !gun.is_gun() ) {
debugmsg( "%s tried to fire non-gun (%s).", get_name(), gun.tname() );
return 0;
}
if( gun.has_flag( flag_CHOKE ) && !gun.ammo_effects().count( "SHOT" ) ) {
add_msg_if_player( _( "A shotgun equipped with choke cannot fire slugs." ) );
return 0;
}
bool is_mech_weapon = false;
if( is_mounted() &&
mounted_creature->has_flag( MF_RIDEABLE_MECH ) ) {
is_mech_weapon = true;
}
// Number of shots to fire is limited by the amount of remaining ammo
if( gun.ammo_required() ) {
shots = std::min( shots, static_cast<int>( gun.ammo_remaining() / gun.ammo_required() ) );
}
// cap our maximum burst size by the amount of UPS power left
if( !gun.has_flag( flag_VEHICLE ) && gun.get_gun_ups_drain() > 0 ) {
shots = std::min( shots, static_cast<int>( available_ups() / gun.get_gun_ups_drain() ) );
}
if( shots <= 0 ) {
debugmsg( "Attempted to fire zero or negative shots using %s", gun.tname() );
}
map &here = get_map();
// usage of any attached bipod is dependent upon terrain or on being prone
bool bipod = here.has_flag_ter_or_furn( ter_furn_flag::TFLAG_MOUNTABLE, pos() ) || is_prone();
if( !bipod ) {
if( const optional_vpart_position vp = here.veh_at( pos() ) ) {
bipod = vp->vehicle().has_part( pos(), "MOUNTABLE" );
}
}
// Up to 50% of recoil can be delayed until end of burst dependent upon relevant skill
/** @EFFECT_PISTOL delays effects of recoil during automatic fire */
/** @EFFECT_SMG delays effects of recoil during automatic fire */
/** @EFFECT_RIFLE delays effects of recoil during automatic fire */
/** @EFFECT_SHOTGUN delays effects of recoil during automatic fire */
double absorb = std::min( get_skill_level( gun.gun_skill() ),
MAX_SKILL ) / static_cast<double>( MAX_SKILL * 2 );
itype_id gun_id = gun.typeId();
skill_id gun_skill = gun.gun_skill();
tripoint aim = target;
int curshot = 0;
int hits = 0; // total shots on target
int delay = 0; // delayed recoil that has yet to be applied
while( curshot != shots ) {
if( gun.has_fault_flag( "JAMMED_GUN" ) && curshot == 0 ) {
moves -= 50;
gun.faults.erase( fault_gun_chamber_spent );
add_msg_if_player( _( "You cycle your %s manually." ), gun.tname() );
}
if( !handle_gun_damage( gun ) ) {
break;
}
// If this is a vehicle mounted turret, which vehicle is it mounted on?
const vehicle *in_veh = has_effect( effect_on_roof ) ? veh_pointer_or_null( here.veh_at(
pos() ) ) : nullptr;
weakpoint_attack wp_attack;
wp_attack.weapon = &gun;
projectile proj = make_gun_projectile( gun );
dispersion_sources dispersion = get_weapon_dispersion( gun );
dispersion.add_range( recoil_total() );
dispersion.add_spread( proj.shot_spread );
bool first = true;
bool headshot = false;
bool multishot = proj.count > 1;
std::map< Creature *, std::pair < int, int >> targets_hit;
for( int projectile_number = 0; projectile_number < proj.count; ++projectile_number ) {
dealt_projectile_attack shot = projectile_attack( proj, pos(), aim,
dispersion, this, in_veh, wp_attack, first );
first = false;
if( shot.hit_critter ) {
int damage = shot.dealt_dam.total_damage();
if( damage > 0 ) {
targets_hit[ shot.hit_critter ].second += damage;
}
targets_hit[ shot.hit_critter ].first++;
}
if( shot.missed_by <= .1 ) {
headshot = true;
}
if( proj.count > 1 && rl_dist( pos(), shot.end_point ) == 1 ) {
// Point-blank shots don't act like shot, everything hits the same target.
multishot = false;
break;
}
}
if( !targets_hit.empty() ) {
hits++;
}
for( std::pair<Creature *const, std::pair<int, int>> &hit_entry : targets_hit ) {
if( monster *const m = hit_entry.first->as_monster() ) {
get_event_bus().send<event_type::character_ranged_attacks_monster>(
getID(), gun_id, m->type->id );
} else if( Character *const c = hit_entry.first->as_character() ) {
get_event_bus().send<event_type::character_ranged_attacks_character>(
getID(), gun_id, c->getID(), c->get_name() );
}
if( multishot ) {
// TODO: Pull projectile name from the ammo entry.
multi_projectile_hit_message( hit_entry.first, hit_entry.second.first, hit_entry.second.second,
n_gettext( "projectile", "projectiles", hit_entry.second.first ) );
}
}
if( headshot ) {
// TODO: check head existence for headshot
get_event_bus().send<event_type::character_gets_headshot>( getID() );
}
curshot++;
if( !gun.is_gun() ) {
// If we lose our gun as a side effect of firing it, skip the rest of the loop body.
break;
}
int qty = gun.gun_recoil( *this, bipod );
delay += qty * absorb;
// Temporarily scale by 5x as we adjust MAX_RECOIL.
recoil += 5.0 * ( qty * ( 1.0 - absorb ) );
make_gun_sound_effect( *this, shots > 1, &gun );
sfx::generate_gun_sound( *this, gun );
const itype_id current_ammo = gun.ammo_current();
if( has_trait( trait_PYROMANIA ) && !has_morale( MORALE_PYROMANIA_STARTFIRE ) ) {
if( current_ammo == itype_flammable || current_ammo == itype_66mm ||
current_ammo == itype_84x246mm || current_ammo == itype_m235 ) {
add_msg_if_player( m_good, _( "You feel a surge of euphoria as flames roar out of the %s!" ),
gun.tname() );
add_morale( MORALE_PYROMANIA_STARTFIRE, 15, 15, 8_hours, 6_hours );
rem_morale( MORALE_PYROMANIA_NOFIRE );
}
}
const int required = gun.ammo_required();
if( gun.ammo_consume( required, pos(), this ) != required ) {
debugmsg( "Unexpected shortage of ammo whilst firing %s", gun.tname() );
break;
}
if( !current_ammo.is_null() ) {
cycle_action( gun, current_ammo, pos() );
}
if( !gun.has_flag( flag_VEHICLE ) ) {
consume_ups( gun.get_gun_ups_drain() );
}
if( gun_skill == skill_launcher ) {
continue; // skip retargeting for launchers
}
}
// Use different amounts of time depending on the type of gun and our skill
moves -= time_to_attack( *this, *gun_id );
// Practice the base gun skill proportionally to number of hits, but always by one.
practice( skill_gun, ( hits + 1 ) * 5 );
// launchers train weapon skill for both hits and misses.
int practice_units = gun_skill == skill_launcher ? curshot : hits;
practice( gun_skill, ( practice_units + 1 ) * 5 );
if( !gun.is_gun() ) {
// If we lose our gun as a side effect of firing it, skip the rest of the function.
return curshot;
}
// apply shot counter to gun and its mods.
gun.set_var( "shot_counter", gun.get_var( "shot_counter", 0 ) + curshot );
for( item *mod : gun.gunmods() ) {
mod->set_var( "shot_counter", mod->get_var( "shot_counter", 0 ) + curshot );
}
if( gun.has_flag( flag_RELOAD_AND_SHOOT ) ) {
// Reset aim for bows and other reload-and-shoot weapons.
recoil = MAX_RECOIL;
} else {
// apply delayed recoil
recoil += delay;
if( is_mech_weapon ) {
// mechs can handle recoil far better. they are built around their main gun.
// TODO: shouldn't this affect only recoil accumulated during this function?
recoil = recoil / 2;
}
// Cap
recoil = std::min( MAX_RECOIL, recoil );
}
return curshot;
}
int throw_cost( const Character &c, const item &to_throw )
{
// Very similar to player::attack_speed
// TODO: Extract into a function?
// Differences:
// Dex is more (2x) important for throwing speed
// At 10 skill, the cost is down to 0.75%, not 0.66%
const int base_move_cost = to_throw.attack_time() / 2;
const int throw_skill = std::min( MAX_SKILL, c.get_skill_level( skill_throw ) );
///\EFFECT_THROW increases throwing speed
const int skill_cost = static_cast<int>( ( base_move_cost * ( 20 - throw_skill ) / 20 ) );
///\EFFECT_DEX increases throwing speed
const int dexbonus = c.get_dex();
const float stamina_ratio = static_cast<float>( c.get_stamina() ) / c.get_stamina_max();
const float stamina_penalty = 1.0 + std::max( ( 0.25f - stamina_ratio ) * 4.0f, 0.0f );
int move_cost = base_move_cost;
move_cost *= c.get_modifier( character_modifier_melee_thrown_move_manip_mod );
move_cost *= c.get_modifier( character_modifier_melee_thrown_move_balance_mod );
// Stamina penalty only affects base/2 and encumbrance parts of the cost
move_cost *= stamina_penalty;
move_cost += skill_cost;
move_cost -= dexbonus;
move_cost *= c.mutation_value( "attackcost_modifier" );
return std::max( 25, move_cost );
}
int Character::throw_dispersion_per_dodge( bool /* add_encumbrance */ ) const
{
// +200 per dodge point at 0 dexterity
// +100 at 8, +80 at 12, +66.6 at 16, +57 at 20, +50 at 24
// Each 10 encumbrance on either hand is like -1 dex (can bring penalty to +400 per dodge)
///\EFFECT_DEX increases throwing accuracy against targets with good dodge stat
float effective_dex = 2 + get_dex() / 4.0f;
effective_dex *= get_modifier( character_modifier_thrown_dex_mod );
return static_cast<int>( 100.0f / std::max( 1.0f, effective_dex ) );
}
// Perfect situation gives us 1000 dispersion at lvl 0
// This goes down linearly to 250 dispersion at lvl 10
int Character::throwing_dispersion( const item &to_throw, Creature *critter,
bool is_blind_throw ) const
{
units::mass weight = to_throw.weight();
units::volume volume = to_throw.volume();
if( to_throw.count_by_charges() && to_throw.charges > 1 ) {
weight /= to_throw.charges;
volume /= to_throw.charges;
}
int throw_difficulty = 1000;
// 1000 penalty for every liter after the first
// TODO: Except javelin type items
throw_difficulty += std::max<int>( 0, units::to_milliliter( volume - 1_liter ) );
// 1 penalty for gram above str*100 grams (at 0 skill)
///\ARM_STR decreases throwing dispersion when throwing heavy objects
const int weight_in_gram = units::to_gram( weight );
throw_difficulty += std::max( 0, weight_in_gram - get_arm_str() * 100 );
// Dispersion from difficult throws goes from 100% at lvl 0 to 25% at lvl 10
///\EFFECT_THROW increases throwing accuracy
const int throw_skill = std::min( MAX_SKILL, get_skill_level( skill_throw ) );
int dispersion = 10 * throw_difficulty / ( 8 * throw_skill + 4 );