-
Notifications
You must be signed in to change notification settings - Fork 1
/
VoiceCommands.as
1653 lines (1369 loc) · 49.1 KB
/
VoiceCommands.as
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 "../SoundCache/StartSoundMsg"
const int ALWAYS_LOAD_SOUND_LIMIT = 10; // fewer sounds than this and the voice will always be loaded
class Talker
{
string name; // What you see in the voice selection menu
dictionary phrases; // each value is a @Phrase
string packFile; // path to packed sound file, if one exists
bool isPrecached = false;
bool alwaysPrecache = false; // for voices that have very few custom sounds
Talker(string displayName) {
name = displayName;
}
int getCustomSoundCount() {
array<string>@ phrase_keys = phrases.getKeys();
dictionary unique_sounds;
for (uint i = 0; i < phrase_keys.length(); i++)
{
array<Phrase@>@ catphrases = cast< array<Phrase@>@ >(phrases[phrase_keys[i]]);
for (uint k = 0; k < catphrases.length(); k++) {
string soundFile = catphrases[k].soundFile;
if (isCustomSound(soundFile)) {
unique_sounds[soundFile.ToLowercase()] = true;
}
}
}
return unique_sounds.size();
}
int getTotalSoundCount() {
array<string>@ phrase_keys = phrases.getKeys();
int count = 0;
dictionary unique_sounds;
for (uint i = 0; i < phrase_keys.length(); i++)
{
array<Phrase@>@ catphrases = cast< array<Phrase@>@ >(phrases[phrase_keys[i]]);
for (uint k = 0; k < catphrases.length(); k++) {
string soundFile = catphrases[k].soundFile;
unique_sounds[soundFile.ToLowercase()] = true;
}
}
return unique_sounds.size();
}
}
class Phrase
{
string soundFile; // path to the sound clip
string talkerId; // voice this phrase belongs to
string categoryId; // e.g. "follow" for the Follow me command
float gain; // 0 to 6, anything above 1.0 needs to be a whole number, anything between 0 and 1 is a percentage
int id; // unique
// packed sound vars (optional)
bool isPacked = false;
float offset = 0;
float duration = 0;
Phrase(string talker, string category, float gainVal, string filePath)
{
talkerId = talker;
categoryId = category;
gain = gainVal;
soundFile = filePath;
}
}
class CommandGroup
{
string name; // display/data name
string sprite; // path to the displayed sprite
int menu; // which menu this command should appear on
CommandGroup(string cmdName, string spritePath, int menuId)
{
name = cmdName;
sprite = spritePath;
menu = menuId;
}
}
class PlayerState
{
CTextMenu@ menu;
string talker_id; // voice this player is using
string want_talker_id; // the voice this player wants to use but isn't precached yet
int pitch; // voice pitch adjustment (100 = normal, range = 1-1000)
float volume; // volume of all voice commands (spoken or heard)
int lastChatMenu; // if non-zero, player currently has a chat menu open
int globalInvert; // set to 1 when a chat menu was opened 3 times (inverse global state)
string lastSample; // store the last soundFile played so we can stop it later
float lastChatTime; // time this player last used a voice command
int lastPhraseId;
bool wasConnectedLastMap;
array<string> muteList;
// sounds scheduled to be stopped (needs to be cleared when playing a new sound or else it stops early)
array<CScheduledFunction@> stopSchedules;
void initMenu(CBasePlayer@ plr, TextMenuPlayerSlotCallback@ callback, bool destroyOldMenu)
{
destroyOldMenu = false; // Unregistering throws an error for whatever reason. TODO: Ask the big man why
if (destroyOldMenu and @menu !is null and menu.IsRegistered()) {
menu.Unregister();
@menu = null;
}
CTextMenu temp(@callback);
@menu = @temp;
}
void openMenu(CBasePlayer@ plr)
{
if ( menu.Register() == false ) {
g_Game.AlertMessage( at_console, "Oh dear menu registration failed\n");
}
menu.Open(10, 0, plr);
}
}
const float PACK_GAP = 0.2f; // seconds of silence between sounds in packed voice files
dictionary g_talkers; // all the voice data
dictionary g_talker_name_upper; // get upper-cased name from all-lowercase name
array<Phrase@> g_all_phrases; // for straight-forward precaching, duplicates the data in g_talkers
array<string> g_talkers_ordered; // used to display talkers/voices in the correct order
array<CommandGroup@> g_commands; // all of em
string command_menu_1_title;
string command_menu_2_title;
string command_menu_3_title;
string command_menu_4_title;
array<EHandle> g_players;
CCVar@ g_enable_gain;
CCVar@ g_global_gain;
CCVar@ g_monster_reactions;
CCVar@ g_command_delay;
CCVar@ g_debug_mode;
CCVar@ g_enable_global;
CCVar@ g_falloff;
CCVar@ g_use_sentences;
dictionary player_states; // persistent-ish player data, organized by steam-id or username if on a LAN server, values are @PlayerState
bool debug_log = false;
bool reload_next_map = false;
string default_voice = 'Scientist';
string plugin_path = 'scripts/plugins/voice_commands/';
// Sound channels that don't don't often conflict with player actions
array<SOUND_CHANNEL> channels = {CHAN_STATIC, CHAN_STREAM, CHAN_VOICE};
string g_previous_map;
CConCommand _extMute( "vcmute_ext", "Mute from other plugin", @extMute ); // for muting from another plugin
CConCommand _reloadSounds( "vcreload", "Reload sounds next map", @reloadSounds ); // for muting from another plugin
void print(string text) { g_Game.AlertMessage( at_console, "[VoiceCommands] " + text); }
void println(string text) { print(text + "\n"); }
void PluginInit()
{
g_Module.ScriptInfo.SetAuthor( "w00tguy" );
g_Module.ScriptInfo.SetContactInfo( "w00tguy123 - forums.svencoop.com" );
g_Hooks.RegisterHook( Hooks::Player::ClientSay, @ClientSay );
g_Hooks.RegisterHook( Hooks::Game::MapChange, @MapChange );
loadConfig();
loadVoiceData();
loadDefaultSentences();
@g_enable_gain = CCVar("enable_gain", 1, "Amplify sounds by playing multiple instances at once (occasionally plays sounds off-sync).", ConCommandFlag::AdminOnly);
@g_global_gain = CCVar("global_gain", 0, "Extra volume applied to all sound files (0-6). Has no effect if gain is disabled.", ConCommandFlag::AdminOnly);
@g_monster_reactions = CCVar("monster_reactions", 1, "Monsters respond to player voice commands (e.g. follow player, detect noise).", ConCommandFlag::AdminOnly);
@g_command_delay = CCVar("delay", 2.5, "Delay between sending commands, in seconds", ConCommandFlag::AdminOnly);
@g_debug_mode = CCVar("debug", 0, "If set to 1, sound details will be printed in chat and sounds will not play in a random order.", ConCommandFlag::AdminOnly);
@g_enable_global = CCVar("enable_global", 1, "Allow global commands", ConCommandFlag::AdminOnly);
@g_falloff = CCVar("falloff", 1.0, "Adjusts how far sounds can be heard (1 = normal, 0 = infinite)", ConCommandFlag::AdminOnly);
@g_use_sentences = CCVar("use_sentences", 1, "Set this to 0 for maps that override custom sentences and break voice commands", ConCommandFlag::AdminOnly);
loadUsageStats();
}
void PluginExit() {
writeUsageStats();
}
int total_precached_sounds = 0;
bool isCustomSound(string path) {
string noExtPath = path.SubString(0, path.FindLastOf("."));
return path.Length() > 0 and path[0] != "!" and !g_default_sentence_sounds.exists(noExtPath);
}
void MapInit()
{
for (uint i = 0; i < g_commands.length(); i++)
g_Game.PrecacheModel(g_commands[i].sprite);
if (reload_next_map) {
loadDefaultSentences();
loadConfig();
loadVoiceData();
loadUsageStats();
reload_next_map = false;
}
g_Game.AlertMessage( at_console, "Precaching " + g_all_phrases.length() + " sounds and " + g_commands.length() + " sprites\n");
dictionary unique_sounds;
if (string(g_Engine.mapname) != g_previous_map) {
updatePrecachedVoices();
}
g_previous_map = g_Engine.mapname;
for (uint i = 0; i < g_all_phrases.length(); i++) {
if (g_all_phrases[i].isPacked) {
continue;
}
Talker@ talker = cast< Talker@ >(g_talkers[g_all_phrases[i].talkerId]);
if (!talker.isPrecached) {
continue;
}
string soundFile = g_all_phrases[i].soundFile;
if (!g_use_sentences.GetBool() and g_all_phrases[i].soundFile.Length() > 0 and g_all_phrases[i].soundFile[0] == "!") {
g_default_sentences.get(soundFile, soundFile);
}
if (soundFile.Length() > 0 and soundFile[0] != "!") {
g_SoundSystem.PrecacheSound(soundFile);
g_Game.PrecacheGeneric("sound/" + soundFile);
}
if (isCustomSound(soundFile)) {
unique_sounds[soundFile.ToLowercase()] = true;
}
}
array<string>@ talkerKeys = g_talkers.getKeys();
for (uint i = 0; i < talkerKeys.length(); i++) {
Talker@ talker = cast< Talker@ >(g_talkers[talkerKeys[i]]);
string packFile = talker.packFile;
if (!talker.isPrecached) {
continue;
}
if (packFile.Length() > 0) {
g_SoundSystem.PrecacheSound(packFile);
g_Game.PrecacheGeneric("sound/" + packFile);
unique_sounds[packFile.ToLowercase()] = true;
}
}
total_precached_sounds = unique_sounds.size();
// Reset temporary vars on map change
array<string>@ states = player_states.getKeys();
for (uint i = 0; i < states.length(); i++)
{
PlayerState@ state = cast< PlayerState@ >(player_states[states[i]]);
state.lastChatTime = 0;
state.lastChatMenu = 0;
state.globalInvert = 0;
state.lastSample = "";
state.lastPhraseId = -1;
}
}
void updatePrecachedVoices() {
array<string>@ talkerKeys = g_talkers.getKeys();
for (uint i = 0; i < talkerKeys.length(); i++) {
Talker@ talker = cast< Talker@ >(g_talkers[talkerKeys[i]]);
if (!talker.alwaysPrecache) {
talker.isPrecached = false;
}
}
int total_loaded_voices = 0;
array<string>@ stateKeys = player_states.getKeys();
for (uint i = 0; i < stateKeys.length(); i++)
{
PlayerState@ state = cast<PlayerState@>( player_states[stateKeys[i]] );
if (state.wasConnectedLastMap) {
if (state.want_talker_id.Length() > 0) {
state.talker_id = state.want_talker_id;
}
Talker@ talker = cast< Talker@ >(g_talkers[state.talker_id]);
if (talker is null) {
continue; // selected a vc that was removed
}
if (!talker.isPrecached) {
total_loaded_voices++;
}
talker.isPrecached = true;
}
}
// precache the most popular ones too
if (total_loaded_voices < 32) {
g_stats.sort(function(a,b) { return a.totalUses > b.totalUses; });
for (uint i = 0; i < g_stats.size(); i++) {
if (!g_stats[i].isValid) {
continue; // voice not loaded
}
string upperName;
g_talker_name_upper.get(g_stats[i].voice, upperName);
Talker@ talker = cast< Talker@ >(g_talkers[upperName]);
if (!talker.isPrecached) {
total_loaded_voices++;
talker.isPrecached = true;
if (total_loaded_voices >= 32) {
break;
}
}
}
}
}
HookReturnCode MapChange()
{
// set all menus to null. Apparently this fixes crashes for some people:
// http://forums.svencoop.com/showthread.php/43310-Need-help-with-text-menu#post515087
array<string>@ stateKeys = player_states.getKeys();
for (uint i = 0; i < stateKeys.length(); i++)
{
PlayerState@ state = cast<PlayerState@>( player_states[stateKeys[i]] );
if (state.menu !is null)
@state.menu = null;
state.wasConnectedLastMap = false;
}
for ( int i = 1; i <= g_Engine.maxClients; i++ )
{
CBasePlayer@ p = g_PlayerFuncs.FindPlayerByIndex(i);
if (p is null or !p.IsConnected()) {
continue;
}
PlayerState@ state = getPlayerState(p);
state.wasConnectedLastMap = true;
}
writeUsageStats();
return HOOK_CONTINUE;
}
enum parse_mode {
PARSE_SETTINGS,
PARSE_VOICES,
PARSE_CMDS_1,
PARSE_CMDS_2,
PARSE_CMDS_3,
PARSE_CMDS_4,
PARSE_SPECIAL_CMDS,
}
dictionary g_default_sentences;
dictionary g_default_sentence_sounds; // sounds that are always precached
void loadDefaultSentences()
{
g_default_sentence_sounds.clear();
g_default_sentences.clear();
string fpath = plugin_path + "default_sentences.txt";
dictionary maps;
File@ f = g_FileSystem.OpenFile( fpath, OpenFile::READ );
if (f is null or !f.IsOpen())
{
println("Failed to open " + fpath);
return;
}
int sentenceCount = 0;
string line;
while( !f.EOFReached() )
{
f.ReadLine(line);
line.Trim();
line.Trim("\t");
if (line.Length() == 0 or line.Find("//") == 0)
continue;
array<string> parts = line.Split(" ");
if (parts.length() > 1) {
string folder = parts[1].SubString(0, parts[1].FindLastOf("/")+1);
for (uint i = 1; i < parts.size(); i++) {
string sound = parts[i];
int fidx = sound.FindLastOf("/");
if (fidx != -1) {
sound = sound.SubString(fidx+1);
}
int pidx = sound.FindFirstOf("(");
int pidx2 = sound.FindFirstOf(")");
if (pidx != -1) {
sound = sound.SubString(0, pidx);
pidx2 = sound.FindFirstOf(")");
if (pidx2 < int(sound.Length()) and pidx2 != -1) {
sound = sound.SubString(pidx2+1);
}
} else if (pidx2 != -1) {
sound = ""; // space separated modifiers included in the split. No sound path here.
}
sound.Replace(".", "");
sound.Replace(",", "");
if (sound.Length() != 0) {
sound = folder + sound;
if (!g_default_sentence_sounds.exists(sound)) {
g_default_sentence_sounds[sound] = true;
}
}
}
if (!g_default_sentences.exists(parts[0]))
continue; // don't care about sentences not used by any voice
if (parts[1].Find("(") != String::INVALID_INDEX)
continue; // complex sentences not supported yet (or ever probably)
string ext = (parts[1].Find("bodyguard") != String::INVALID_INDEX) ? ".ogg" : ".wav";
string sentenceName = "!" + parts[0];
string soundFile = parts[1] + ext;
sentenceCount++;
g_default_sentences[sentenceName] = soundFile;
}
}
//println("Loaded " + sentenceCount + " default sentences");
}
void loadConfig()
{
g_commands.resize(0);
g_talkers.clear();
g_talkers_ordered.resize(0);
string dataPath = plugin_path + "VoiceCommands.cfg";
File@ f = g_FileSystem.OpenFile( dataPath, OpenFile::READ );
int parseMode = PARSE_SETTINGS;
if( f !is null && f.IsOpen() )
{
string line;
while( !f.EOFReached() )
{
f.ReadLine( line );
line.Trim();
line.Trim('\r'); // Linux won't strip these during ReadLine or Trim
if (line.Length() == 0 or line[0] == '/')
continue;
if (line[0] == '/' and line[1] == '/')
continue; // ignore comments
if (line == "[settings]") {
parseMode = PARSE_SETTINGS;
continue;
}
if (line == "[voices]") {
parseMode = PARSE_VOICES;
continue;
}
if (line == "[command_menu_1]") {
parseMode = PARSE_CMDS_1;
continue;
}
if (line == "[command_menu_2]") {
parseMode = PARSE_CMDS_2;
continue;
}
if (line == "[command_menu_3]") {
parseMode = PARSE_CMDS_3;
continue;
}
if (line == "[command_menu_4]") {
parseMode = PARSE_CMDS_4;
continue;
}
if (line == "[special_commands]") {
parseMode = PARSE_SPECIAL_CMDS;
continue;
}
if (parseMode == PARSE_SETTINGS)
{
array<string>@ settingValue = line.Split("=");
if (settingValue.length() != 2)
continue;
settingValue[0].Trim();
settingValue[1].Trim();
if (settingValue[0].Length() == 0 or settingValue[1].Length() == 0)
continue;
if (settingValue[0] == "default_voice")
default_voice = settingValue[1];
if (settingValue[0] == "command_menu_1_title")
command_menu_1_title = settingValue[1];
if (settingValue[0] == "command_menu_2_title")
command_menu_2_title = settingValue[1];
if (settingValue[0] == "command_menu_3_title")
command_menu_3_title = settingValue[1];
if (settingValue[0] == "command_menu_4_title")
command_menu_4_title = settingValue[1];
}
else if (parseMode == PARSE_VOICES)
{
string lowerLine = line;
lowerLine = lowerLine.ToLowercase();
g_talkers[line] = @Talker(line);
g_talkers_ordered.insertLast(line);
g_talker_name_upper[lowerLine] = line;
//g_Game.AlertMessage( at_console, "Got voice: '" + line + "'\n");
}
else if (parseMode == PARSE_CMDS_1 or parseMode == PARSE_CMDS_2 or parseMode == PARSE_CMDS_3 or parseMode == PARSE_CMDS_4 or parseMode == PARSE_SPECIAL_CMDS)
{
array<string>@ cmd_values = line.Split(":");
if (cmd_values.length() != 2)
continue;
cmd_values[0].Trim();
cmd_values[1].Trim();
if (cmd_values[0].Length() == 0 or cmd_values[1].Length() == 0)
continue;
CommandGroup c(cmd_values[0], cmd_values[1], 1);
if (parseMode == PARSE_CMDS_2)
c.menu = 2;
else if (parseMode == PARSE_CMDS_3)
c.menu = 3;
else if (parseMode == PARSE_CMDS_4)
c.menu = 4;
else if (parseMode == PARSE_SPECIAL_CMDS)
c.menu = 0;
g_commands.insertLast(c);
//g_Game.AlertMessage( at_console, "Got command: '" + c.name + " " + c.sprite + "'\n");
}
else
g_Game.AlertMessage( at_console, "Uhhh, something's wrong with your .cfg, check the lines with [] in them" + "\n");
}
}
else
g_Game.AlertMessage( at_console, "Unable to open config file:\n" + dataPath + "\n");
}
void loadVoiceData()
{
g_all_phrases.resize(0);
array<string>@ voiceNames = g_talkers.getKeys();
int phraseIdNum = 0;
for (uint i = 0; i < voiceNames.length(); i++)
{
Talker@ talker = cast< Talker@ >( g_talkers[voiceNames[i]] );
array<Phrase@>@ phrases;
string groupName;
string voicePath = plugin_path + "voices/" + talker.name + ".txt";
File@ f = g_FileSystem.OpenFile( voicePath, OpenFile::READ );
if( f !is null && f.IsOpen() )
{
string line;
while( !f.EOFReached() )
{
f.ReadLine( line );
line.Trim();
line.Trim('\r'); // Linux won't strip these during ReadLine or Trim
if (line.Length() == 0 or line[0] == '/')
continue;
if (line[0] == '[') // Command group name
{
int end = line.FindLastOf(']');
groupName = line.SubString(1, end-1);
if (talker !is null and talker.phrases.exists(groupName) == false)
{
array<Phrase@> p;
talker.phrases[groupName] = @p;
}
@phrases = cast< array<Phrase@>@ >( talker.phrases[groupName] );
}
else // Phrase
{
//if (line.Find)
array<string>@ params = line.Split(":");
params[0].Trim();
params[1].Trim();
if (talker !is null and phrases !is null and params.length() == 2)
{
Phrase p(talker.name, groupName, atof( params[0] ), params[1]);
p.id = phraseIdNum++;
phrases.insertLast( p );
g_all_phrases.insertLast(@p);
if (params[1].Length() > 1 and params[1][0] == "!") {
g_default_sentences[params[1].SubString(1)] = true; // mark this for sentence loading later
}
}
}
//g_Game.AlertMessage( at_console, line + "\n");
}
}
else
g_Game.AlertMessage( at_console, "Unable to open voice data file:\n" + voicePath + "\n");
loadPackInfo(talker.name);
if (talker.getCustomSoundCount() < ALWAYS_LOAD_SOUND_LIMIT) {
talker.isPrecached = talker.alwaysPrecache = true;
}
//g_Game.AlertMessage( at_console, "LOAD voice: '" + talker.name + "'\n");
}
}
void loadPackInfo(string voiceName)
{
Talker@ talker = cast< Talker@ >( g_talkers[voiceName] );
string packPath = plugin_path + "voices/" + talker.name + ".pack";
File@ f = g_FileSystem.OpenFile( packPath, OpenFile::READ );
if( f is null || !f.IsOpen() ) {
//println("No pack info found for voice " + voiceName);
return;
}
string line;
bool readPackPath = false;
while( !f.EOFReached() )
{
f.ReadLine(line);
line.Trim();
line.Trim('\r'); // Linux won't strip these during ReadLine or Trim
if (line.Length() == 0 or line[0] == '/')
continue;
if (!readPackPath) {
talker.packFile = line;
readPackPath = true;
continue;
}
array<string>@ params = line.Split(":");
params[0].Trim();
params[1].Trim();
params[2].Trim();
float offset = atof(params[0]);
float duration = atof(params[1]);
string packSound = params[2].ToLowercase();
bool foundPhrase = false;
array<string>@ phrase_keys = talker.phrases.getKeys();
for (uint i = 0; i < phrase_keys.length(); i++) {
array<Phrase@>@ catphrases = cast< array<Phrase@>@ >(talker.phrases[phrase_keys[i]]);
for (uint k = 0; k < catphrases.length(); k++) {
string soundFile = catphrases[k].soundFile;
soundFile = soundFile.ToLowercase();
if (packSound == soundFile) {
catphrases[k].isPacked = true;
catphrases[k].offset = offset;
catphrases[k].duration = duration;
foundPhrase = true;
}
}
}
if (!foundPhrase) {
println(talker.name + ".pack references unused sound:" + packSound);
}
}
}
void updatePlayerList()
{
g_players.resize(0);
CBaseEntity@ ent = null;
do {
@ent = g_EntityFuncs.FindEntityByClassname(ent, "player");
if (ent !is null)
{
EHandle e = ent;
g_players.insertLast(e);
}
} while (ent !is null);
}
// Returns the monster that the player is looking directly at, if any.
CBaseMonster@ getMonsterLookingAt(CBasePlayer@ plr, float maxDistance)
{
// Calculate position that the player is looking at
Vector vec, vecDummy;
g_EngineFuncs.AngleVectors( plr.pev.v_angle, vec, vecDummy, vecDummy );
TraceResult tr;
const Vector vecEyes = plr.pev.origin + plr.pev.view_ofs;
g_Utility.TraceLine( vecEyes, vecEyes + ( vec * maxDistance ), dont_ignore_monsters, plr.edict(), tr );
if ( tr.flFraction < 1.0 and tr.pHit !is null )
{
CBaseEntity@ hitEnt = g_EntityFuncs.Instance( tr.pHit );
if ( hitEnt !is null and hitEnt.IsMonster() )
{
return cast<CBaseMonster@>(hitEnt);
}
}
return null;
}
void triggerMonsterAction(EHandle h_monster, EHandle h_plr, string action)
{
CBaseMonster@ monster = cast<CBaseMonster@>(h_monster.GetEntity());
CBasePlayer@ plr = cast<CBasePlayer@>(h_plr.GetEntity());
if (monster is null or plr is null) {
return;
}
//CTalkMonster@ talkmon = cast<CTalkMonster@>(monster);
if (action == 'Follow me' or action == 'Help') {
monster.StartPlayerFollowing(plr, false);
} else if (action == 'Stop') {
monster.StopPlayerFollowing(false, false);
} else {
//talkmon.IdleRespond();
//talkmon.Talk(2.0f);
//g_PlayerFuncs.SayTextAll(plr, "talk test");
}
}
int g_idx = 0; // debug
string format_float(float f)
{
uint decimal = uint(((f - int(f)) * 10)) % 10;
return "" + int(f) + "." + decimal;
}
// handles player voice chats
void voiceMenuCallback(CTextMenu@ menu, CBasePlayer@ plr, int page, const CTextMenuItem@ item)
{
if (item is null or plr is null) {
return;
}
PlayerState@ state = getPlayerState(plr);
state.lastChatMenu = 0; // return chat menu to normal order
state.globalInvert = 0; // no inversion either
// Check if player has waited long enough to use another command
float t = g_Engine.time; // Get server time in milliseconds
float delta = t - state.lastChatTime;
if (!g_debug_mode.GetBool() and delta < g_command_delay.GetFloat())
{
float waitTime = g_command_delay.GetFloat() - delta;
g_PlayerFuncs.ClientPrint(plr, HUD_PRINTCENTER, "Wait " + format_float(waitTime) + " seconds\n");
return;
}
state.lastChatTime = t;
// verify talker exists
if (g_talkers.exists(state.talker_id) == false) {
g_Game.AlertMessage( at_console, "Bad talker ID: " + state.talker_id + "\n");
return;
}
string phraseId;
item.m_pUserData.retrieve(phraseId);
bool global = phraseId.Length() > 1 and phraseId[0] == 'G' and phraseId[1] == ':';
if (global)
phraseId = phraseId.SubString(2, phraseId.Length()-2);
// get the selected voice and phrase group
Talker@ talker = cast< Talker@ >(g_talkers[state.talker_id]);
if (plr.pev.deadflag != DEAD_NO)
phraseId = "Dead"; // players can't talk when they're dead, but they can gurgle a bit
// verify phrase id exists for current voice
if (talker.phrases.exists(phraseId) == false) {
g_Game.AlertMessage( at_console, "Bad Phrase ID for " + state.talker_id + ": " + phraseId + "\n");
return;
}
// Get the phrase group list
array<Phrase@>@ phrases = cast< array<Phrase@>@ >(talker.phrases[phraseId]);
// get a random sound clip from the selected phrase group
int idx = Math.RandomLong(0, phrases.length()-1);
// try not to repeat the last thing this player said
if (phrases.length() > 1)
{
for (int i = 0; i < 10 and phrases[idx].id == state.lastPhraseId; i++) {
idx = Math.RandomLong(0, phrases.length()-1);
}
}
state.lastPhraseId = phrases[idx].id;
// play in a linear order for debugging
if (g_debug_mode.GetBool())
{
idx = g_idx % phrases.length();
g_idx += 1;
}
Phrase@ phrase = phrases[idx];
// figure out the volume and gain for this sample
uint gain = g_global_gain.GetInt();
float vol = 1.0f;
if (phrase.gain >= 1)
gain += int(phrase.gain);
if (phrase.gain < 1)
vol = phrase.gain;
if (gain > channels.length())
gain = channels.length();
if (!g_enable_gain.GetBool())
gain = 1;
if (gain < 1) {
gain = 1;
}
updatePlayerList();
string soundFile = phrase.soundFile;
if (!g_use_sentences.GetBool() and soundFile.Length() > 0 and soundFile[0] == "!") {
g_default_sentences.get(soundFile, soundFile); // get the default sound file for the sentence
}
if (phrase.isPacked) {
soundFile = talker.packFile;
}
float soundDuration = (phrase.duration + PACK_GAP*0.5f) * (1.0f / (state.pitch*0.01f));
const string speakerSteamId = g_EngineFuncs.GetPlayerAuthId(plr.edict()).ToLowercase();
for (uint i = 0; i < g_players.length(); i++)
{
if (g_players[i])
{
CBaseEntity@ listener = g_players[i];
PlayerState@ listenerState = getPlayerState(cast<CBasePlayer@>(listener));
CBasePlayer@ speaker = global ? cast<CBasePlayer@>(listener) : plr;
if (listenerState.muteList.find(speakerSteamId) != -1) {
continue;
}
float listenVol = listenerState.volume*vol;
float attn = global ? ATTN_NONE : g_falloff.GetFloat();
if (listenVol <= 0)
continue;
for (uint g = 0; g < channels.length(); g++)
{
if (g < gain) {
if (phrase.isPacked) {
StartSoundMsgParams params;
params.sample = soundFile;
params.channel = channels[g];
params.entindex = plr.entindex();
params.offset = phrase.offset;
params.pitch = state.pitch;
params.volume = listenVol;
params.attenuation = attn;
StartSoundMsg(params, MSG_ONE, listener.edict());
// no way to play for a specific duration, so stopping manually when the sound ends (with some buffer for inconsistent ping)
g_Scheduler.RemoveTimer(state.stopSchedules[g]);
@state.stopSchedules[g] = @g_Scheduler.SetTimeout("delay_stop_sound", soundDuration, EHandle(plr), int(channels[g]), soundFile);
} else {
g_SoundSystem.PlaySound(plr.edict(), channels[g], soundFile, listenVol, attn, 0, state.pitch, listener.entindex());
}
}
else
g_SoundSystem.StopSound(plr.edict(), channels[g], state.lastSample, false);
}
}
}
state.lastSample = soundFile;
if (global)
g_PlayerFuncs.SayTextAll(plr, "(voice) " + plr.pev.netname + ": " + phraseId + "\n");
// Show the command sprite
for (uint i = 0; i < g_commands.length(); i++)
if (g_commands[i].name == phraseId) {
float duration = 2.5f;
if (phrase.isPacked) {
duration = Math.min(Math.max(soundDuration, 1.5f), 30.0f);
}
plr.ShowOverheadSprite(g_commands[i].sprite, 51.0f, duration);
}
// Monster reactions to sounds
if (g_monster_reactions.GetBool())
{
GetSoundEntInstance().InsertSound(4, plr.pev.origin, NORMAL_GUN_VOLUME, 0, plr); // let monsters respond to this sound
CBaseMonster@ target = getMonsterLookingAt(plr, 512.0f);
if ( target !is null ) // Looking at a monster that is within earshot
{
g_Scheduler.SetTimeout( "triggerMonsterAction", 1, EHandle(target), EHandle(plr), phraseId );
}
}
if (g_debug_mode.GetBool())
g_PlayerFuncs.SayTextAll(plr, "Idx: " + idx + "/" + (phrases.length()-1) + " Gain: " + gain + ", Volume: " + vol + ", Pitch: " + state.pitch + ", Sound File: " + soundFile + "\n");
logVoiceStat(plr, talker.name);
}
void delay_stop_sound(EHandle h_plr, int channel, string sample) {
CBasePlayer@ plr = cast<CBasePlayer@>(h_plr.GetEntity());
if (plr is null) {
return;
}
if (plr.pev.effects & EF_NODRAW != 0) {
stopsound_bug_workaround(h_plr, 0, 0);
}
g_SoundSystem.StopSound(plr.edict(), SOUND_CHANNEL(channel), sample, false);
}
// stopsound doesn't work on players with EF_NODRAW (gibbed), so this temporarily removes the flag
// but makes them invisible, then resets the flag after stopsound is sent
void stopsound_bug_workaround(EHandle h_plr, int oldRendermode, float oldRenderamt) {
CBasePlayer@ plr = cast<CBasePlayer@>(h_plr.GetEntity());
if (plr is null) {
return;
}
if (plr.pev.effects & EF_NODRAW != 0) {
g_Scheduler.SetTimeout("stopsound_bug_workaround", 0.05f, h_plr, plr.pev.rendermode, plr.pev.renderamt);
plr.pev.effects &= ~EF_NODRAW;
plr.pev.rendermode = 1;
plr.pev.renderamt = 0;
} else {
plr.pev.effects |= EF_NODRAW;
plr.pev.rendermode = oldRendermode;
plr.pev.renderamt = oldRenderamt;
}
}
// handles player voice selection
void voiceSelectCallback(CTextMenu@ menu, CBasePlayer@ plr, int page, const CTextMenuItem@ item)
{
if (item is null or plr is null) {
return;
}
PlayerState@ state = getPlayerState(plr);
string selection;