-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMegaHAL.cpp
1899 lines (1460 loc) · 49.5 KB
/
MegaHAL.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
//
// Copyright © 2003-2010, by YaPB Development Team. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// MegaHAL.cpp
//
// Version: $ID:$
//
/*
MegaHAL Stuff
code from PM's RACC Bot (http://racc.bots-united.com) Check it out!
adapted to rcbot code
MegaHAL - http://megahal.sourceforge.net
*/
// RACC - AI development project for first-person shooter games derivated from Valve's Half-Life
// (http://www.racc-ai.com/)
//
// The game to engine interfacing code is based on the work done by Jeffrey 'Botman' Broome
// (http://planethalflife.com/botman/)
//
// This project is partially based on the work done by Eric Bieschke in his BSDbot
// (http://gamershomepage.com/csbot/)
//
// This project is partially based on the work done by Brendan 'Spyro' McCarthy in his ODD Bot
// (http://oddbot.hlfusion.com/)
//
// This project is partially based on the work done by Alistair 'eLiTe' Stewart in his TEAMbot
// (http://www.planethalflife.com/teambot/)
//
// This project is partially based on the work done by Johannes '@$3.1415rin' Lampel in his JoeBot
// (http://www.joebot.net/)
//
// Rational Autonomous Cybernetic Commandos AI
//
// bot_chat.cpp
//
#include <Core.hpp>
const char *const name_in_msg ("%n");
void BotChatReply (YaPB *pBot, char *szMsg, Client *pSender, char *szReplyMsg)
{
// the purpose of this function is to make the bot keep an eye on what's happening in the
// chat room, and in case of new messages, think about a possible reply.
// no message!
if (!szMsg || !*szMsg)
return;
// is bot chat allowed AND this message is not from this bot itself?
if (/*!gBotGlobals.IsConfigSettingOn (BOT_CONFIG_CHATTING) || */pSender == pBot)
return;
int iNameLength;
char *szName;
iNameLength = GetStringLength <unsigned char> (pBot->GetName ());
szName = new char[iNameLength + 1];
RemoveNameTags (pBot->GetName (), szName);
szName[iNameLength] = '\0';
//int i, j;
bool bNameInMsg = false;
char *szNamePos;
StringMakeLowerCase (szMsg);
StringMakeLowerCase (szName);
szNamePos = strstr (szMsg, szName);
bNameInMsg = (szNamePos != NULL);
int iSenderNameLength = GetStringLength <unsigned char> (pSender->GetName ());
char *szSenderName = new char[iSenderNameLength + 1];
RemoveNameTags (pSender->GetName (), szSenderName);
szSenderName[iSenderNameLength] = '\0';
/*while (szNamePos != NULL)
{
i = 0;
strstr (szNamePos, szName);
}*/
if (bNameInMsg)
BotFunc_FillString (szMsg, szName, name_in_msg, GetStringLength <unsigned short> (szMsg));
// break the new message into an array of words
HAL_MakeWords (szMsg, pBot->GetProfile ()->m_HAL->input_words);
unsigned char iRep (5u);//pBot->GetProfile ()->m_Rep.GetClientRep (pSender);
// does the bot feel concerned? (more chances of replying if its name appears)
// if real mode is on, then bot chat is affected by bots rep with sender
// and depends on chat_reply_percent command
if (33u/*gBotGlobals.m_iBotChatReplyPercent*/ > 0u && (bNameInMsg || /*gBotGlobals.m_Clients*/
((/*!gBotGlobals.IsConfigSettingOn (BOT_CONFIG_REAL_MODE) || */ g_randomNumberGenerator.GetValueBetween <unsigned char> (BOT_MIN_REP, BOT_MAX_REP) < iRep) && g_randomNumberGenerator.GetValueBetween <unsigned char> (0, 100) < 33u/*gBotGlobals.m_iBotChatReplyPercent*/) || g_server->GetClientManager ()->GetClientsCount () == 2u))
{
//UNUSED IN RCBot ALSO!!! pBot->m_MegaHALTalkEdict = pSender;
BotHALGenerateReply (pBot, szReplyMsg); // generate the reply
// HalfLifeEngine::Globals::g_halfLifeEngine->ServerPrintFormat ("BotChatReply(): CALLED! szMsg: \"%s\".\n", szMsg);
if (szReplyMsg[0u] != '\0')
{
BotFunc_FillString (szReplyMsg, name_in_msg, szSenderName, BOT_CHAT_MESSAGE_LENGTH);
if (strcmp (szReplyMsg, szMsg) != 0) // not the exact same message? :-p
StringMakeLowerCase (szReplyMsg); // convert the output string to lowercase
else
szReplyMsg[0u] = '\0';
// HalfLifeEngine::Globals::g_halfLifeEngine->ServerPrint ("------------------------------------------------------>DONE!!\n");
}
}
// if sender is not a bot then learn from it's message
// do this after working out a reply so the bots dont just say the same thing back.
if (/*!gBotGlobals.IsConfigSettingOn (BOT_CONFIG_CHAT_DONT_LEARN) && */!pSender->IsYaPB ())
HAL_Learn (pBot->GetProfile ()->m_HAL->bot_model, pBot->GetProfile ()->m_HAL->input_words); // only learn from humans
delete [] szName;
delete [] szSenderName;
}
// from old rcbot
void HumanizeString (char *string)
{
const int drop_percent = 1;
const int swap_percent = 1;
const int capitalise_percent = 1;
const int lower_percent = 2;
int length = GetStringLength <unsigned short> (string);
int i = 0;
int n = 0;
int rand;
char temp;
while (i < length)
{
if (((i + 1) < length) && (g_randomNumberGenerator.GetValueBetween <unsigned char> (0, 100) < swap_percent))
{
temp = string[i];
string[i] = string[i + 1];
string[i + 1] = temp;
i+=2;
continue;
}
if (((rand = g_randomNumberGenerator.GetValueBetween <unsigned char> (0, 100)) < drop_percent) ||
(((string[n] < '0') && (string[n] > '9')) && (rand < drop_percent*2)))
{
n = i;
while (n < (length - 1))
{
string[n] = string[n + 1];
++n;
}
string[--length] = '\0';
++i;
continue;
}
if (!isupper (string[i]) && ((i == 0) || (string[i-1] == ' ')))
{
if (g_randomNumberGenerator.GetValueBetween <unsigned char> (0, 100) < (capitalise_percent * 2))
string[i] = static_cast <char> (toupper (string[i]));
}
if (isupper (string[i]) && (g_randomNumberGenerator.GetValueBetween <unsigned char> (0, 100) < lower_percent))
string[i] = static_cast <char> (tolower (string[i]));
++i;
}
}
// from old rcbot
void RemoveNameTags (const char *in_string, char *out_string)
{
int i = 0; // index of in_string
int n = 0; // length of out_string
out_string[0] = '\0';
int length;
char current_char;
char tag_start;
int tag_size = 0;
bool space_allowed = false;
bool inside_tag;
if (in_string == NULL)
return;
length = GetStringLength <unsigned short> (in_string);
InternalAssert (length <= 127);
/* if (length > 127)
{
if (gBotGlobals.m_iDebugLevels & BOT_DEBUG_THINK_LEVEL)
ALERT (at_console, "Error : RemoveNameTags (): Input netname is too long!\n");
return;
}
*/
inside_tag = false;
while (i < length)
{
current_char = 0;
if (inside_tag)
{
if (((i + 1) < length) && (in_string[i] == '=') && (in_string[i+i] == '-'))
{
inside_tag = false;
i += 2;
continue;
}
else if ((in_string[i] == ')') || (in_string[i] == ']') || (in_string[i] == '}'))
{
//char temp = in_string[i];
inside_tag = false;
//if (tag_size == 0)
//{
// out_string[n++] = tag_start;
// out_string[n++] = temp;
//}
++i;
continue;
}
else
{
++tag_size;
++i;
continue;
}
}
if (isalnum (in_string[i]))
{
current_char = in_string[i];
space_allowed = true;
}
else if ((in_string[i] == ' (') || (in_string[i] == '[') || (in_string[i] == '{'))
{
inside_tag = true;
tag_start = in_string[i];
tag_size=0;
++i;
continue;
}
else if (((i + 1) < length) && (in_string[i] == '-') && (in_string[i+i] == '='))
{
inside_tag = true;
i += 2;
continue;
}
else
{
if (space_allowed)
{
current_char = ' ';
space_allowed = false;
}
else
{
++i;
continue;
}
}
// l33t to normal
switch (current_char)
{
case '5':
current_char = 's';
break;
case '0':
current_char = 'o';
break;
case '7':
current_char = 't';
break;
case '3':
current_char = 'e';
break;
case '1':
current_char = 'i';
break;
case '4':
current_char = 'a';
break;
}
tag_size=0;
out_string[n] = current_char;
++n;
++i;
}
if (out_string[0] != 0)
{
out_string[n] = '\0';
--n;
while ((n > 0) && (out_string[n] == ' '))
out_string[n--] = '\0';
}
if (out_string[0] == 0)
strcpy (out_string, in_string);
StringMakeLowerCase (out_string);
/*
// more 'l33t stuff
// "l33t" R
BotFunc_FillString (out_string, "|2", "r", length);
// fat "l33ty" P's I's and M's
BotFunc_FillString (out_string, "[]D", "p", length);
BotFunc_FillString (out_string, "[]V[]", "m", length);
BotFunc_FillString (out_string, "[]", "i", length);
// http://www.bbc.co.uk/dna/h2g2/A787917
BotFunc_FillString (out_string, " ()", "o", length);
BotFunc_FillString (out_string, "|_|", "u", length);
BotFunc_FillString (out_string, "|)", "d", length);
BotFunc_FillString (out_string, "\\/\\/", "w", length);
BotFunc_FillString (out_string, "$", "s", length);
*/
}
void BotHALGenerateReply (YaPB *pBot, char *output)
{
// this function takes a string of user input and return a string of output which may
// vaguely be construed as containing a reply to whatever is in the input string.
// Create an array of keywords from the words in the user's input...
HAL_DICTIONARY *keywords, *replywords;
int tries_count, last_entry, last_character, length = 1;
unsigned int i, j;
keywords = BotHALMakeKeywords (pBot, pBot->GetProfile ()->m_HAL->input_words);
replywords = BotHALBuildReplyDictionary (pBot, keywords);
last_entry = pBot->GetProfile ()->m_HAL->input_words->size - 1;
last_character = pBot->GetProfile ()->m_HAL->input_words->entry[last_entry].length - 1;
// was it a question (i.e. was the last word in the general chat record a question mark?)
if (pBot->GetProfile ()->m_HAL->input_words->entry[last_entry].word[last_character] == '?')
{
// try ten times to answer something relevant
for (tries_count = 0; tries_count < 10; ++tries_count)
{
if (HAL_DictionariesDiffer (pBot->GetProfile ()->m_HAL->input_words, replywords))
break; // stop as soon as we've got something to say
replywords = BotHALBuildReplyDictionary (pBot, keywords); // else think again
}
// if we've finally found something to say, generate the reply
if (tries_count < 10)
{
// if no words in the reply dictionary...
if (replywords->size == 0)
{
// the HAL is too young to talk yet
output[0] = '\0';
return;
}
for (i = 0; i < replywords->size; ++i)
length += replywords->entry[i].length;
char *const output_template (new char[length]);
if (output_template == NULL)
{
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_MakeOutput() unable to allocate output\n");
return;
}
output_template[0] = '\0'; // first reset the reply string
length = 0;
for (i = 0; i < replywords->size; ++i)
for (j = 0; j < replywords->entry[i].length; ++j)
output_template[length++] = replywords->entry[i].word[j];
if (length >= BOT_CHAT_MESSAGE_LENGTH)
output_template[BOT_CHAT_MESSAGE_LENGTH - 1u] = '\0'; // disallow strings to be longer than BOT_CHAT_MESSAGE_LENGTH chars
else
output_template[length] = '\0'; // terminate the string
strcpy (output, output_template); // then copy the answer
delete [] output_template;
return;
}
}
// else if we are not paraphrazing, generate a string from the dictionary of reply words
else if (HAL_DictionariesDiffer (pBot->GetProfile ()->m_HAL->input_words, replywords))
{
// if no words in the reply dictionary...
if (replywords->size == 0)
{
// the HAL is too young to talk yet
output[0] = '\0';
return;
}
for (i = 0; i < replywords->size; ++i)
length += replywords->entry[i].length;
char *const output_template (new char[length]);
if (output_template == NULL)
{
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_MakeOutput() unable to allocate output\n");
return;
}
output_template[0] = '\0'; // first reset the reply string
length = 0;
for (i = 0; i < replywords->size; ++i)
for (j = 0; j < replywords->entry[i].length; ++j)
output_template[length++] = replywords->entry[i].word[j];
if (length >= BOT_CHAT_MESSAGE_LENGTH)
output_template[BOT_CHAT_MESSAGE_LENGTH - 1u] = '\0'; // disallow strings to be longer than 128 chars
else
output_template[length] = '\0'; // terminate the string
strcpy (output, output_template); // then copy the answer
delete [] output_template;
return;
}
}
unsigned short HAL_AddWord (HAL_DICTIONARY *dictionary, HAL_STRING word)
{
// this function adds a word to a dictionary, and return the identifier assigned to the
// word. If the word already exists in the dictionary, then return its current identifier
// without adding it again.
int i;
int position;
bool found;
// if the word's already in the dictionary, there is no need to add it
position = HAL_SearchDictionary (dictionary, word, found);
if (found)
return dictionary->index[position];
// increase the number of words in the dictionary
++dictionary->size;
// allocate one more entry for the word index
if (dictionary->index == NULL)
dictionary->index = static_cast <unsigned short *> (malloc (sizeof (unsigned short) * (dictionary->size)));
else
dictionary->index = static_cast <unsigned short *> (realloc (dictionary->index, sizeof (unsigned short) * dictionary->size));
if (dictionary->index == NULL)
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_AddWord() unable to reallocate the dictionary index\n");
// allocate one more entry for the word array
if (dictionary->entry == NULL)
dictionary->entry = static_cast <HAL_STRING *> (malloc (sizeof (HAL_STRING) * (dictionary->size)));
else
dictionary->entry = static_cast <HAL_STRING *> (realloc (dictionary->entry, sizeof (HAL_STRING) * dictionary->size));
if (dictionary->entry == NULL)
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_AddWord() unable to reallocate the dictionary to %d elements\n", dictionary->size);
// copy the new word into the word array
dictionary->entry[dictionary->size - 1u].length = word.length;
dictionary->entry[dictionary->size - 1u].word = static_cast <char *> (malloc (sizeof (char) * (word.length + 1u)));
if (dictionary->entry[dictionary->size - 1u].word == NULL)
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_AddWord() unable to allocate the word\n");
for (i = 0; i < word.length; ++i)
dictionary->entry[dictionary->size - 1u].word[i] = word.word[i];
dictionary->entry[dictionary->size - 1u].word[word.length] = '\0';
// shuffle the word index to keep it sorted alphabetically
for (i = dictionary->size - 1; i > position; --i)
dictionary->index[i] = dictionary->index[i - 1];
// copy the new symbol identifier into the word index
dictionary->index[position] = static_cast <unsigned short> (dictionary->size - 1u);
return dictionary->index[position];
}
int HAL_SearchDictionary (HAL_DICTIONARY *dictionary, HAL_STRING word, bool &find)
{
// search the dictionary for the specified word, returning its position in the index if
// found, or the position where it should be inserted otherwise
int imin;
int imax;
int middle;
int compar;
// if the dictionary is empty, then obviously the word won't be found
if (dictionary->size == 0)
{
find = false;
return 0;
}
// initialize the lower and upper bounds of the search
imin = 0;
imax = dictionary->size - 1;
//bool bDone = false;
//int iFound = 0;
// search repeatedly, halving the search space each time, until either the entry is found,
// or the search space becomes empty
for (;;)
{
// see whether the middle element of the search space is greater than, equal to, or
// less than the element being searched for.
middle = (imin + imax) / 2;
compar = HAL_CompareWords (word, dictionary->entry[dictionary->index[middle]]);
// if equal then we have found the element. Otherwise halve the search space accordingly
if (compar == 0)
{
find = true;
return middle;
}
else if (compar > 0)
{
if (imax == middle)
{
find = false;
return middle + 1;
}
imin = middle + 1;
}
else
{
if (imin == middle)
{
find = false;
return middle;
}
imax = middle - 1;
}
}
}
unsigned short HAL_FindWord (HAL_DICTIONARY *dictionary, HAL_STRING word)
{
// this function returns the symbol corresponding to the word specified. We assume that
// the word with index zero is equal to a NULL word, indicating an error condition.
bool found;
int position = HAL_SearchDictionary (dictionary, word, found);
if (found == true)
return dictionary->index[position];
return 0;
}
int HAL_CompareWords (HAL_STRING word1, HAL_STRING word2)
{
// this function compares two words, and return an integer indicating whether the first
// word is less than, equal to or greater than the second word
int i;
int bound;
try
{
bound = min (word1.length, word2.length);
for (i = 0; i < bound; ++i)
if (toupper (word1.word[i]) != toupper (word2.word[i]))
return static_cast <int> (toupper (word1.word[i]) - toupper (word2.word[i]));
}
catch (...)
{
AddLogEntry (true, LogLevel_Error, false, "First chance exception in HAL_CompareWords ()\r\n (May be a problem with HAL Files)");
}
if (word1.length < word2.length)
return -1;
else if (word1.length > word2.length)
return 1;
return 0;
}
void HAL_InitializeDictionary (HAL_DICTIONARY *dictionary)
{
// this function adds dummy words to the dictionary
HAL_STRING word = {GET_STATIC_STRING_LENGTH ("<ERROR>"), "<ERROR>"};
HAL_STRING end = {GET_STATIC_STRING_LENGTH ("<FIN>"), "<FIN>"};
HAL_AddWord (dictionary, word);
HAL_AddWord (dictionary, end);
}
HAL_DICTIONARY *HAL_NewDictionary (void)
{
// this function allocates room for a new dictionary
HAL_DICTIONARY *dictionary = static_cast <HAL_DICTIONARY *> (malloc (sizeof (HAL_DICTIONARY)));
if (dictionary == NULL)
{
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_NewDictionary() unable to allocate dictionary\n");
return NULL;
}
dictionary->size = 0;
dictionary->index = NULL;
dictionary->entry = NULL;
return dictionary;
}
void HAL_SaveDictionary (FILE *file, HAL_DICTIONARY *dictionary)
{
// this function saves a dictionary to the specified file
unsigned int i;
unsigned char j;
fwrite (&dictionary->size, sizeof (unsigned long), 1, file);
// save each word to the file
for (i = 0u; i < dictionary->size; ++i)
{
fwrite (&dictionary->entry[i].length, sizeof (unsigned char), 1, file);
for (j = 0u; j < dictionary->entry[i].length; ++j)
fwrite (&dictionary->entry[i].word[j], sizeof (char), 1, file);
}
}
void HAL_LoadDictionary (FILE *file, HAL_DICTIONARY *dictionary)
{
// this function loads a dictionary from the specified file
int i;
int size;
HAL_STRING word;
if (file == NULL)
return;
fread (&size, sizeof (unsigned long), 1, file);
// load each dictionary word from the file
for (i = 0; i < size; ++i)
{
fread (&word.length, sizeof (unsigned char), 1, file);
word.word = new char[word.length + 1];
if (word.word == NULL)
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_LoadDictionary() unable to allocate word\n");
//for (j = 0; j < word.length; ++j)
fread (word.word, sizeof (char), word.length, file);
word.word[word.length] = '\0';
HAL_AddWord (dictionary, word);
delete [] word.word;
}
}
HAL_TREE *HAL_NewNode (void)
{
// allocate a new node for the n-gram tree, and initialise its contents to sensible values
// allocate memory for the new node
HAL_TREE *const node (static_cast <HAL_TREE *> (malloc (sizeof (HAL_TREE))));
if (node == NULL)
{
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_NewNode() unable to allocate node\n");
return NULL;
}
// initialise the contents of the node
node->symbol = 0;
node->usage = 0;
node->count = 0;
node->branch = 0;
node->tree = NULL;
return node;
}
HAL_MODEL *HAL_NewModel (int order)
{
// this function creates and initializes a new ngram model
HAL_MODEL *model (new HAL_MODEL ());
if (model == NULL)
{
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_NewModel() unable to allocate model\n");
return NULL;
}
model->order = (unsigned char) order;
model->forward = HAL_NewNode ();
model->backward = HAL_NewNode ();
model->context = static_cast <HAL_TREE **> (malloc (sizeof (HAL_TREE *) * (order + 2)));
if (model->context == NULL)
{
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_NewModel() unable to allocate context array\n");
return NULL;
}
HAL_InitializeContext (model);
model->dictionary = HAL_NewDictionary ();
HAL_InitializeDictionary (model->dictionary);
return model;
}
void HAL_UpdateModel (HAL_MODEL *model, int symbol)
{
// this function uppdates the model with the specified symbol
int i;
// update all of the models in the current context with the specified symbol
for (i = model->order + 1; i > 0; --i)
if (model->context[i - 1] != NULL)
model->context[i] = HAL_AddSymbol (model->context[i - 1], (unsigned short) symbol);
return;
}
void HAL_UpdateContext (HAL_MODEL *model, int symbol)
{
// this function updates the context of the model without adding the symbol
int i;
for (i = model->order + 1; i > 0; --i)
if (model->context[i - 1] != NULL)
model->context[i] = HAL_FindSymbol (model->context[i - 1], symbol);
}
HAL_TREE *HAL_AddSymbol (HAL_TREE *tree, unsigned short symbol)
{
// this function updates the statistics of the specified tree with the specified symbol,
// which may mean growing the tree if the symbol hasn't been seen in this context before
// search for the symbol in the subtree of the tree node
HAL_TREE *node (HAL_FindSymbolAdd (tree, symbol));
// increment the symbol counts
if (node->count < 65535)
{
++node->count;
++tree->usage;
}
return node;
}
HAL_TREE *HAL_FindSymbol (HAL_TREE *node, int symbol)
{
// this function returns a pointer to the child node, if one exists, which contains symbol
int i;
HAL_TREE *found = NULL;
bool found_symbol = false;
// perform a binary search for the symbol
i = HAL_SearchNode (node, symbol, &found_symbol);
if (found_symbol)
found = node->tree[i];
return found;
}
HAL_TREE *HAL_FindSymbolAdd (HAL_TREE *node, int symbol)
{
// this function is conceptually similar to HAL_FindSymbol, apart from the fact that if the
// symbol is not found, a new node is automatically allocated and added to the tree
int i;
HAL_TREE *found = NULL;
bool found_symbol = false;
// perform a binary search for the symbol. If the symbol isn't found, attach a new sub-node
// to the tree node so that it remains sorted.
i = HAL_SearchNode (node, symbol, &found_symbol);
if (found_symbol)
found = node->tree[i];
else
{
found = HAL_NewNode ();
found->symbol = (unsigned short) symbol;
HAL_AddNode (node, found, i);
}
return found;
}
void HAL_AddNode (HAL_TREE *tree, HAL_TREE *node, int position)
{
// this function attachs a new child node to the sub-tree of the tree specified
int i;
// allocate room for one more child node, which may mean allocating the sub-tree from scratch
if (tree->tree == NULL)
tree->tree = static_cast <HAL_TREE **> (malloc (sizeof (HAL_TREE *) * (tree->branch+1)));
else
{
tree->tree = static_cast <HAL_TREE **> (realloc (tree->tree, sizeof (HAL_TREE *) * (tree->branch + 1)));
}
if (tree->tree == NULL)
AddLogEntry (true, LogLevel_Error, false, "HAL: HAL_AddNode() unable to reallocate subtree\n");
// shuffle nodes down so that we can insert new node at subtree index given by position
for (i = tree->branch; i > position; --i)
tree->tree[i] = tree->tree[i - 1];
// add the new node to the sub-tree
tree->tree[position] = node;
++tree->branch;
}
int HAL_SearchNode (HAL_TREE *node, int symbol, bool *found_symbol)
{
// this function performs a binary search for the specified symbol on the subtree of the
// given node. Return the position of the child node in the subtree if the symbol was found,
// or the position where it should be inserted to keep the subtree sorted if it wasn't
int imin;
int imax;
int middle;
int compar;
// handle the special case where the subtree is empty
if (node->branch == 0)
{
*found_symbol = false;
return 0;
}
// perform a binary search on the subtree
imin = 0;
imax = node->branch - 1;
for (;;)
{
middle = (imin + imax) / 2;
compar = symbol-node->tree[middle]->symbol;
if (compar == 0)
{
*found_symbol = true;
return middle;
}
else if (compar > 0)
{
if (imax == middle)
{
*found_symbol = false;
return middle + 1;
}
imin = middle + 1;
}
else
{
if (imin == middle)
{
*found_symbol = false;
return middle;
}
imax = middle - 1;
}
}
}
void HAL_InitializeContext (HAL_MODEL *model)
{
// this function sets the context of the model to a default value
int i;
for (i = 0; i <= model->order; ++i)
model->context[i] = NULL; // reset all the context elements
}
void HAL_Learn (HAL_MODEL *model, HAL_DICTIONARY *words)
{
// this function learns from the user's input
unsigned int i;
unsigned short symbol;
if (words->size <= model->order)
return; // only learn from inputs which are long enough
// train the model in the forward direction. Start by initializing the context of the model
HAL_InitializeContext (model);
model->context[0] = model->forward;
for (i = 0; i < words->size; ++i)
{
// add the symbol to the model's dictionary if necessary, and update the model accordingly
symbol = HAL_AddWord (model->dictionary, words->entry[i]);
HAL_UpdateModel (model, symbol);
}
// add the sentence-terminating symbol
HAL_UpdateModel (model, 1);
// train the model in the backwards direction. Start by initializing the context of the model
HAL_InitializeContext (model);
model->context[0] = model->backward;
for (i = words->size - 1; static_cast <int> (i) >= 0; --i)
{
// find the symbol in the model's dictionary, and update the backward model accordingly
symbol = HAL_FindWord (model->dictionary, words->entry[i]);
HAL_UpdateModel (model, symbol);
}
// add the sentence-terminating symbol
HAL_UpdateModel (model, 1);
return;