/
ai.c
3305 lines (2758 loc) · 80.4 KB
/
ai.c
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
/*
* See Licensing and Copyright notice in naev.h
*/
/**
* @file ai.c
*
* @brief Controls the Pilot AI.
*
* AI Overview
*
* Concept: Goal (Task) Based AI with additional Optimization
*
* AI uses the goal (task) based AI approach with tasks scripted in lua,
* additionally there is a task that is hardcoded and obligatory in any AI
* script, the 'control' task, whose sole purpose is to assign tasks if there
* is no current tasks and optimizes or changes tasks if there are.
*
* For example: Pilot A is attacking Pilot B. Say that Pilot C then comes in
* the same system and is of the same faction as Pilot B, and therefore attacks
* Pilot A. Pilot A would keep on fighting Pilot B until the control task
* kicks in. Then he/she could run if it deems that Pilot C and Pilot B
* together are too strong for him/her, or attack Pilot C because it's an
* easier target to finish off then Pilot B. Therefore there are endless
* possibilities and it's up to the AI coder to set up.
*
*
* Specification
*
* - AI will follow basic tasks defined from Lua AI script.
* - if Task is NULL, AI will run "control" task
* - Task is continued every frame
* - Tasks can have subtasks which will be closed when parent task is dead.
* - "control" task is a special task that MUST exist in any given Pilot AI
* (missiles and such will use "seek")
* - "control" task is not permanent, but transitory
* - "control" task sets another task
* - "control" task is also run at a set rate (depending on Lua global "control_rate")
* to choose optimal behaviour (task)
*
* Memory
*
* The AI currently has per-pilot memory which is accessible as "mem". This
* memory is actually stored in the table pilotmem[cur_pilot->id]. This allows
* the pilot to keep some memory always accesible between runs without having
* to rely on the storage space a task has.
*
* @note Nothing in this file can be considered reentrant. Plan accordingly.
*
* @todo Clean up most of the code, it was written as one of the first
* subsystems and is pretty lacking in quite a few aspects. Notably
* removing the entire lightuserdata thing and actually go with full
* userdata.
*/
#include "ai.h"
#include "ai_extra.h"
#include "naev.h"
#include <stdlib.h>
#include <stdio.h> /* malloc realloc */
#include <string.h> /* strncpy strlen strncat strcmp strdup */
#include <math.h>
#include <ctype.h> /* isdigit */
/* yay more lua */
#include "lauxlib.h"
#include "lualib.h"
#include "log.h"
#include "pilot.h"
#include "player.h"
#include "physics.h"
#include "ndata.h"
#include "rng.h"
#include "space.h"
#include "faction.h"
#include "escort.h"
#include "nlua.h"
#include "nluadef.h"
#include "nlua_space.h"
#include "nlua_vec2.h"
#include "nlua_rnd.h"
#include "nlua_pilot.h"
#include "nlua_faction.h"
#include "board.h"
#include "hook.h"
#include "array.h"
/**
* @def lua_regnumber(l,s,n)
*
* @brief Registers a number constant n to name s (syntax like lua_regfunc).
*/
#define lua_regnumber(l,s,n) \
(lua_pushnumber(l,n), lua_setglobal(l,s))
/*
* ai flags
*
* They can be used for stuff like movement or for pieces of code which might
* run AI stuff when the AI module is not reentrant.
*/
#define ai_setFlag(f) (pilot_flags |= f ) /**< Sets pilot flag f */
#define ai_isFlag(f) (pilot_flags & f ) /**< Checks pilot flag f */
/* flags */
#define AI_PRIMARY (1<<0) /**< Firing primary weapon */
#define AI_SECONDARY (1<<1) /**< Firing secondary weapon */
#define AI_DISTRESS (1<<2) /**< Sent distress signal. */
/*
* file info
*/
#define AI_PREFIX "ai/" /**< AI file prefix. */
#define AI_SUFFIX ".lua" /**< AI file suffix. */
#define AI_INCLUDE "include/" /**< Where to search for includes. */
#define AI_MEM "__mem" /**< Internal pilot memory. */
#define AI_MEM_DEF "def" /**< Default pilot memory. */
/*
* all the AI profiles
*/
static AI_Profile* profiles = NULL; /**< Array of AI_Profiles loaded. */
static lua_State *equip_L = NULL; /**< Equipment state. */
/*
* extern pilot hacks
*/
extern Pilot** pilot_stack;
extern int pilot_nstack;
/*
* prototypes
*/
/* Internal C routines */
static void ai_run( lua_State *L, const char *funcname );
static int ai_loadProfile( const char* filename );
static void ai_setMemory (void);
static void ai_create( Pilot* pilot, char *param );
static int ai_loadEquip (void);
/* Task management. */
static Task* ai_createTask( lua_State *L, int subtask );
static int ai_tasktarget( lua_State *L, Task *t );
/*
* AI routines for Lua
*/
/* tasks */
static int aiL_pushtask( lua_State *L ); /* pushtask( string, number/pointer ) */
static int aiL_poptask( lua_State *L ); /* poptask() */
static int aiL_taskname( lua_State *L ); /* string taskname() */
static int aiL_gettarget( lua_State *L ); /* pointer gettarget() */
static int aiL_pushsubtask( lua_State *L ); /* pushsubtask( string, number/pointer, number ) */
static int aiL_popsubtask( lua_State *L ); /* popsubtask() */
static int aiL_subtaskname( lua_State *L ); /* string subtaskname() */
static int aiL_getsubtarget( lua_State *L ); /* pointer subtarget() */
/* consult values */
static int aiL_getplayer( lua_State *L ); /* number getPlayer() */
static int aiL_getrndpilot( lua_State *L ); /* number getrndpilot() */
static int aiL_getnearestpilot( lua_State *L ); /* number getnearestpilot() */
static int aiL_armour( lua_State *L ); /* armour() */
static int aiL_shield( lua_State *L ); /* shield() */
static int aiL_parmour( lua_State *L ); /* parmour() */
static int aiL_pshield( lua_State *L ); /* pshield() */
static int aiL_pcurenergy( lua_State *L ); /* pcurenergy() */
static int aiL_getdistance( lua_State *L ); /* number getdist(Vector2d) */
static int aiL_getflybydistance( lua_State *L ); /* number getflybydist(Vector2d) */
static int aiL_getpos( lua_State *L ); /* getpos(number) */
static int aiL_minbrakedist( lua_State *L ); /* number minbrakedist( [number] ) */
static int aiL_cargofree( lua_State *L ); /* number cargofree() */
static int aiL_shipclass( lua_State *L ); /* string shipclass( [number] ) */
static int aiL_shipmass( lua_State *L ); /* string shipmass( [number] ) */
static int aiL_isbribed( lua_State *L ); /* bool isbribed( number ) */
static int aiL_getstanding( lua_State *L ); /* number getstanding( number ) */
/* boolean expressions */
static int aiL_exists( lua_State *L ); /* boolean exists() */
static int aiL_ismaxvel( lua_State *L ); /* boolean ismaxvel() */
static int aiL_isstopped( lua_State *L ); /* boolean isstopped() */
static int aiL_isenemy( lua_State *L ); /* boolean isenemy( number ) */
static int aiL_isally( lua_State *L ); /* boolean isally( number ) */
static int aiL_incombat( lua_State *L ); /* boolean incombat( [number] ) */
static int aiL_isdisabled( lua_State *L ); /* boolean isdisabled( number ) */
static int aiL_haslockon( lua_State *L ); /* boolean haslockon() */
/* movement */
static int aiL_accel( lua_State *L ); /* accel(number); number <= 1. */
static int aiL_turn( lua_State *L ); /* turn(number); abs(number) <= 1. */
static int aiL_face( lua_State *L ); /* face( number/pointer, bool) */
static int aiL_aim( lua_State *L ); /* aim(number) */
static int aiL_iface( lua_State *L ); /* iface(number/pointer) */
static int aiL_dir( lua_State *L ); /* dir(number/pointer) */
static int aiL_idir( lua_State *L ); /* idir(number/pointer) */
static int aiL_drift_facing( lua_State *L ); /* drift_facing(number/pointer) */
static int aiL_brake( lua_State *L ); /* brake() */
static int aiL_getnearestplanet( lua_State *L ); /* Vec2 getnearestplanet() */
static int aiL_getrndplanet( lua_State *L ); /* Vec2 getrndplanet() */
static int aiL_getlandplanet( lua_State *L ); /* Vec2 getlandplanet() */
static int aiL_land( lua_State *L ); /* bool land() */
static int aiL_takingoff( lua_State *L ); /* bool takingoff() */
static int aiL_stop( lua_State *L ); /* stop() */
static int aiL_relvel( lua_State *L ); /* relvel( number ) */
/* Hyperspace. */
static int aiL_nearhyptarget( lua_State *L ); /* pointer rndhyptarget() */
static int aiL_rndhyptarget( lua_State *L ); /* pointer rndhyptarget() */
static int aiL_hyperspace( lua_State *L ); /* [number] hyperspace() */
/* escorts */
static int aiL_e_attack( lua_State *L ); /* bool e_attack() */
static int aiL_e_hold( lua_State *L ); /* bool e_hold() */
static int aiL_e_clear( lua_State *L ); /* bool e_clear() */
static int aiL_e_return( lua_State *L ); /* bool e_return() */
static int aiL_dock( lua_State *L ); /* dock( number ) */
/* combat */
static int aiL_combat( lua_State *L ); /* combat( number ) */
static int aiL_settarget( lua_State *L ); /* settarget( number ) */
static int aiL_weapSet( lua_State *L ); /* weapset( number ) */
static int aiL_shoot( lua_State *L ); /* shoot( number ); number = 1,2,3 */
static int aiL_hasturrets( lua_State *L ); /* bool hasturrets() */
static int aiL_getenemy( lua_State *L ); /* number getenemy() */
static int aiL_getenemy_size( lua_State *L ); /* number getenemy_size() */
static int aiL_getenemy_heuristic( lua_State *L ); /* number getenemy_heuristic() */
static int aiL_hostile( lua_State *L ); /* hostile( number ) */
static int aiL_getweaprange( lua_State *L ); /* number getweaprange() */
static int aiL_canboard( lua_State *L ); /* boolean canboard( number ) */
static int aiL_relsize( lua_State *L ); /* boolean relsize( number ) */
static int aiL_reldps( lua_State *L ); /* boolean reldps( number ) */
static int aiL_relhp( lua_State *L ); /* boolean relhp( number ) */
/* timers */
static int aiL_settimer( lua_State *L ); /* settimer( number, number ) */
static int aiL_timeup( lua_State *L ); /* boolean timeup( number ) */
/* messages */
static int aiL_comm( lua_State *L ); /* say( number, string ) */
static int aiL_broadcast( lua_State *L ); /* broadcast( string ) */
static int aiL_distress( lua_State *L ); /* distress( string [, bool] ) */
/* loot */
static int aiL_credits( lua_State *L ); /* credits( number ) */
static int aiL_cargo( lua_State *L ); /* cargo( name, quantity ) */
static int aiL_shipprice( lua_State *L ); /* shipprice() */
/* misc */
static int aiL_board( lua_State *L ); /* boolean board() */
static int aiL_refuel( lua_State *L ); /* boolean, boolean refuel() */
static int aiL_donerefuel( lua_State *L ); /* boolean donerefuel() */
static int aiL_sysradius( lua_State *L ); /* number sysradius() */
static const luaL_reg aiL_methods[] = {
/* tasks */
{ "pushtask", aiL_pushtask },
{ "poptask", aiL_poptask },
{ "taskname", aiL_taskname },
{ "target", aiL_gettarget },
{ "pushsubtask", aiL_pushsubtask },
{ "popsubtask", aiL_popsubtask },
{ "subtaskname", aiL_subtaskname },
{ "subtarget", aiL_getsubtarget },
/* is */
{ "exists", aiL_exists },
{ "ismaxvel", aiL_ismaxvel },
{ "isstopped", aiL_isstopped },
{ "isenemy", aiL_isenemy },
{ "isally", aiL_isally },
{ "incombat", aiL_incombat },
{ "isdisabled", aiL_isdisabled },
{ "haslockon", aiL_haslockon },
/* get */
{ "getPlayer", aiL_getplayer },
{ "rndpilot", aiL_getrndpilot },
{ "nearestpilot", aiL_getnearestpilot },
{ "armour", aiL_armour },
{ "shield", aiL_shield },
{ "parmour", aiL_parmour },
{ "pshield", aiL_pshield },
{ "pcurenergy", aiL_pcurenergy },
{ "dist", aiL_getdistance },
{ "flyby_dist", aiL_getflybydistance },
{ "pos", aiL_getpos },
{ "minbrakedist", aiL_minbrakedist },
{ "cargofree", aiL_cargofree },
{ "shipclass", aiL_shipclass },
{ "shipmass", aiL_shipmass },
{ "isbribed", aiL_isbribed },
{ "getstanding", aiL_getstanding },
/* movement */
{ "nearestplanet", aiL_getnearestplanet },
{ "rndplanet", aiL_getrndplanet },
{ "landplanet", aiL_getlandplanet },
{ "land", aiL_land },
{ "takingoff", aiL_takingoff },
{ "accel", aiL_accel },
{ "turn", aiL_turn },
{ "face", aiL_face },
{ "iface", aiL_iface },
{ "dir", aiL_dir },
{ "idir", aiL_idir },
{ "drift_facing", aiL_drift_facing },
{ "brake", aiL_brake },
{ "stop", aiL_stop },
{ "relvel", aiL_relvel },
/* Hyperspace. */
{ "nearhyptarget", aiL_nearhyptarget },
{ "rndhyptarget", aiL_rndhyptarget },
{ "hyperspace", aiL_hyperspace },
/* escorts */
{ "e_attack", aiL_e_attack },
{ "e_hold", aiL_e_hold },
{ "e_clear", aiL_e_clear },
{ "e_return", aiL_e_return },
{ "dock", aiL_dock },
/* combat */
{ "aim", aiL_aim },
{ "combat", aiL_combat },
{ "settarget", aiL_settarget },
{ "weapset", aiL_weapSet },
{ "hasturrets", aiL_hasturrets },
{ "shoot", aiL_shoot },
{ "getenemy", aiL_getenemy },
{ "getenemy_size", aiL_getenemy_size },
{ "getenemy_heuristic", aiL_getenemy_heuristic },
{ "hostile", aiL_hostile },
{ "getweaprange", aiL_getweaprange },
{ "canboard", aiL_canboard },
{ "relsize", aiL_relsize },
{ "reldps", aiL_reldps },
{ "relhp", aiL_relhp },
/* timers */
{ "settimer", aiL_settimer },
{ "timeup", aiL_timeup },
/* messages */
{ "comm", aiL_comm },
{ "broadcast", aiL_broadcast },
{ "distress", aiL_distress },
/* loot */
{ "setcredits", aiL_credits },
{ "setcargo", aiL_cargo },
{ "shipprice", aiL_shipprice },
/* misc */
{ "board", aiL_board },
{ "refuel", aiL_refuel },
{ "donerefuel", aiL_donerefuel },
{ "sysradius", aiL_sysradius },
{0,0} /* end */
}; /**< Lua AI Function table. */
/*
* current pilot "thinking" and assorted variables
*/
static Pilot *cur_pilot = NULL; /**< Current pilot. All functions use this. */
static double pilot_acc = 0.; /**< Current pilot's acceleration. */
static double pilot_turn = 0.; /**< Current pilot's turning. */
static int pilot_flags = 0; /**< Handle stuff like weapon firing. */
static int pilot_firemode = 0; /**< Method pilot is using to shoot. */
static char aiL_distressmsg[PATH_MAX]; /**< Buffer to store distress message. */
/*
* ai status, used so that create functions can't be used elsewhere
*/
#define AI_STATUS_NORMAL 1 /**< Normal ai function behaviour. */
#define AI_STATUS_CREATE 2 /**< AI is running create function. */
static int aiL_status = AI_STATUS_NORMAL; /**< Current AI run status. */
/**
* @brief Sets the cur_pilot's ai.
*/
static void ai_setMemory (void)
{
lua_State *L;
L = cur_pilot->ai->L;
lua_getglobal(L, AI_MEM); /* pm */
lua_pushnumber(L, cur_pilot->id); /* pm, id */
lua_gettable(L, -2); /* pm, t */
lua_setglobal(L, "mem"); /* pm */
lua_pop(L,1); /* */
}
/**
* @brief Sets the pilot for furthur AI calls.
*
* @param p Pilot to set.
*/
void ai_setPilot( Pilot *p )
{
cur_pilot = p;
ai_setMemory();
}
/**
* @brief Attempts to run a function.
*
* @param[in] L Lua state to run function on.
* @param[in] funcname Function to run.
*/
static void ai_run( lua_State *L, const char *funcname )
{
lua_getglobal(L, funcname);
#ifdef DEBUGGING
if (lua_isnil(L, -1)) {
WARN("Pilot '%s' ai -> '%s': attempting to run non-existant function",
cur_pilot->name, funcname );
lua_pop(L,1);
return;
}
#endif /* DEBUGGING */
if (lua_pcall(L, 0, 0, 0)) { /* error has occured */
WARN("Pilot '%s' ai -> '%s': %s", cur_pilot->name, funcname, lua_tostring(L,-1));
lua_pop(L,1);
}
}
/**
* @brief Initializes the pilot in the ai.
*
* Mainly used to create the pilot's memory table.
*
* @param p Pilot to initialize in AI.
* @param ai AI to initialize pilot.
* @return 0 on success.
*/
int ai_pinit( Pilot *p, const char *ai )
{
int i, n;
AI_Profile *prof;
lua_State *L;
char buf[PATH_MAX], param[PATH_MAX];
/* Split parameter from ai itself. */
n = 0;
for (i=0; ai[i] != '\0'; i++) {
/* Overflow protection. */
if (i > PATH_MAX)
break;
/* Check to see if we find the splitter. */
if (ai[i] == '*') {
buf[i] = '\0';
n = i+1;
continue;
}
if (n==0)
buf[i] = ai[i];
else
param[i-n] = ai[i];
}
if (n!=0) param[i-n] = '\0'; /* Terminate string if needed. */
else buf[i] = '\0';
/* Set up the profile. */
prof = ai_getProfile(buf);
if (prof == NULL) {
WARN("AI Profile '%s' not found.", buf);
return -1;
}
p->ai = prof;
L = p->ai->L;
/* Set fuel. Hack until we do it through AI itself. */
if (!pilot_isPlayer(p)) {
p->fuel = (RNG_2SIGMA()/4. + 0.5) * (p->fuel_max - HYPERSPACE_FUEL);
p->fuel += HYPERSPACE_FUEL;
}
/* Adds a new pilot memory in the memory table. */
lua_getglobal(L, AI_MEM); /* pm */
lua_newtable(L); /* pm, nt */
lua_pushnumber(L, p->id); /* pm, nt, n */
lua_pushvalue(L,-2); /* pm, nt, n, nt */
lua_settable(L,-4); /* pm, nt */
/* Copy defaults over. */
lua_pushstring(L, AI_MEM_DEF);/* pm, nt, s */
lua_gettable(L, -3); /* pm, nt, dt */
#if DEBUGGING
if (lua_isnil(L,-1))
WARN( "AI profile '%s' has no default memory for pilot '%s'.",
buf, p->name );
#endif
lua_pushnil(L); /* pm, nt, dt, nil */
while (lua_next(L,-2) != 0) { /* pm, nt, dt, k, v */
lua_pushvalue(L,-2); /* pm, nt, dt, k, v, k */
lua_pushvalue(L,-2); /* pm, nt, dt, k, v, k, v */
lua_remove(L, -3); /* pm, nt, dt, k, k, v */
lua_settable(L,-5); /* pm, nt, dt, k */
} /* pm, nt, dt */
lua_pop(L,3); /* */
/* Create the pilot. */
ai_create( p, (n!=0) ? param : NULL );
pilot_setFlag(p, PILOT_CREATED_AI);
return 0;
}
/**
* @brief Clears the pilot's tasks.
*
* @param p Pilot to clear tasks of.
*/
void ai_cleartasks( Pilot* p )
{
/* Clean up tasks. */
if (p->task)
ai_freetask( p->task );
p->task = NULL;
}
/**
* @brief Destroys the ai part of the pilot
*
* @param[in] p Pilot to destroy it's AI part.
*/
void ai_destroy( Pilot* p )
{
lua_State *L;
L = p->ai->L;
/* Get rid of pilot's memory. */
if (!pilot_isPlayer(p)) { /* Player is an exception as more than one ship shares pilot id. */
lua_getglobal(L, AI_MEM); /* t */
lua_pushnumber(L, p->id); /* t, id */
lua_pushnil(L); /* t, id, nil */
lua_settable(L,-3); /* t */
lua_pop(L,1); /* */
}
/* Clear the tasks. */
ai_cleartasks( p );
}
/**
* @brief Initializes the AI stuff which is basically Lua.
*
* @return 0 on no errors.
*/
int ai_load (void)
{
char** files;
uint32_t nfiles, i;
char path[PATH_MAX];
int flen, suflen;
int n;
/* get the file list */
files = ndata_list( AI_PREFIX, &nfiles );
/* load the profiles */
suflen = strlen(AI_SUFFIX);
for (i=0; i<nfiles; i++) {
flen = strlen(files[i]);
if ((flen > suflen) &&
strncmp(&files[i][flen-suflen], AI_SUFFIX, suflen)==0) {
snprintf( path, PATH_MAX, AI_PREFIX"%s", files[i] );
if (ai_loadProfile(path)) /* Load the profile */
WARN("Error loading AI profile '%s'", path);
}
/* Clean up. */
free(files[i]);
}
n = array_size(profiles);
DEBUG("Loaded %d AI Profile%c", n, (n==1)?' ':'s');
/* More clean up. */
free(files);
/* Load equipment thingy. */
return ai_loadEquip();
}
/**
* @brief Loads the equipment selector script.
*/
static int ai_loadEquip (void)
{
char *buf;
uint32_t bufsize;
const char *filename = "ai/equip/equip.lua";
lua_State *L;
/* Make sure doesn't already exist. */
if (equip_L != NULL)
lua_close(equip_L);
/* Create new state. */
equip_L = nlua_newState();
L = equip_L;
/* Prepare state. */
nlua_loadStandard(L,0);
/* Load the file. */
buf = ndata_read( filename, &bufsize );
if (luaL_dobuffer(L, buf, bufsize, filename) != 0) {
WARN("Error loading file: %s\n"
"%s\n"
"Most likely Lua file has improper syntax, please check",
filename, lua_tostring(L,-1));
return -1;
}
free(buf);
return 0;
}
/**
* @brief Initializes an AI_Profile and adds it to the stack.
*
* @param[in] filename File to create the profile from.
* @return 0 on no error.
*/
static int ai_loadProfile( const char* filename )
{
char* buf = NULL;
uint32_t bufsize = 0;
lua_State *L;
AI_Profile *prof;
size_t len;
/* Create array if necessary. */
if (profiles == NULL)
profiles = array_create( AI_Profile );
/* Grow array. */
prof = &array_grow(&profiles);
/* Set name. */
len = strlen(filename)-strlen(AI_PREFIX)-strlen(AI_SUFFIX);
prof->name = malloc(sizeof(char)*(len+1) );
strncpy( prof->name, &filename[strlen(AI_PREFIX)], len );
prof->name[len] = '\0';
/* Create Lua. */
prof->L = nlua_newState();
if (prof->L == NULL) {
WARN("Unable to create a new Lua state");
return -1;
}
L = prof->L;
/* open basic lua stuff */
nlua_loadBasic(L);
/* constants */
lua_regnumber(L, "player", PLAYER_ID); /* player ID */
/* Register C functions in Lua */
luaL_register(L, "ai", aiL_methods);
nlua_loadRnd(L);
/* Metatables to register. */
nlua_loadVector(L);
/* Add the player memory table. */
lua_newtable(L); /* pm */
lua_pushvalue(L,-1); /* pm, pm */
lua_setglobal(L, AI_MEM ); /* pm */
/* Set "mem" to be default template. */
lua_newtable(L); /* pm, nt */
lua_pushvalue(L,-1); /* pm, nt, nt */
lua_setfield(L,-3,AI_MEM_DEF); /* pm, nt */
lua_setglobal(L, "mem"); /* pm */
lua_pop(L,1); /* */
/* Now load the file since all the functions have been previously loaded */
buf = ndata_read( filename, &bufsize );
if (luaL_dobuffer(L, buf, bufsize, filename) != 0) {
WARN("Error loading AI file: %s\n"
"%s\n"
"Most likely Lua file has improper syntax, please check",
filename, lua_tostring(L,-1));
array_erase( &profiles, prof, &prof[1] );
free(prof->name);
lua_close( L );
free(buf);
return -1;
}
free(buf);
return 0;
}
/**
* @brief Gets the AI_Profile by name.
*
* @param[in] name Name of the profile to get.
* @return The profile or NULL on error.
*/
AI_Profile* ai_getProfile( char* name )
{
int i;
if (profiles == NULL)
return NULL;
for (i=0; i<array_size(profiles); i++)
if (strcmp(name,profiles[i].name)==0)
return &profiles[i];
WARN("AI Profile '%s' not found in AI stack", name);
return NULL;
}
/**
* @brief Cleans up global AI.
*/
void ai_exit (void)
{
int i;
/* Free AI profiles. */
for (i=0; i<array_size(profiles); i++) {
free(profiles[i].name);
lua_close(profiles[i].L);
}
array_free( profiles );
/* Free equipment Lua. */
if (equip_L != NULL)
lua_close(equip_L);
equip_L = NULL;
}
/**
* @brief Heart of the AI, brains of the pilot.
*
* @param pilot Pilot that needs to think.
*/
void ai_think( Pilot* pilot, const double dt )
{
(void) dt;
lua_State *L;
ai_setPilot(pilot);
L = cur_pilot->ai->L; /* set the AI profile to the current pilot's */
/* clean up some variables */
pilot_acc = 0;
pilot_turn = 0.;
pilot_flags = 0;
pilot_firemode = 0;
cur_pilot->target = cur_pilot->id;
/* control function if pilot is idle or tick is up */
if (!pilot_isFlag(cur_pilot, PILOT_MANUAL_CONTROL) &&
((cur_pilot->tcontrol < 0.) || (cur_pilot->task == NULL))) {
ai_run(L, "control"); /* run control */
lua_getglobal(L,"control_rate");
cur_pilot->tcontrol = lua_tonumber(L,-1);
lua_pop(L,1);
}
/* pilot has a currently running task */
if (cur_pilot->task != NULL) {
/* Run subtask if availible, otherwise run main task. */
if (cur_pilot->task->subtask != NULL)
ai_run(L, cur_pilot->task->subtask->name);
else
ai_run(L, cur_pilot->task->name);
/* If task is over and pilot is in manual control run the idle hook. */
if ((cur_pilot->task==NULL) && pilot_isFlag(cur_pilot, PILOT_MANUAL_CONTROL))
pilot_runHook( cur_pilot, PILOT_HOOK_IDLE );
}
/* make sure pilot_acc and pilot_turn are legal */
pilot_acc = CLAMP( 0., 1., pilot_acc );
pilot_turn = CLAMP( -1., 1., pilot_turn );
/* Set turn and thrust. */
pilot_setTurn( cur_pilot, pilot_turn );
pilot_setThrust( cur_pilot, pilot_acc );
/* fire weapons if needed */
if (ai_isFlag(AI_PRIMARY))
pilot_shoot(cur_pilot, 0); /* primary */
if (ai_isFlag(AI_SECONDARY))
pilot_shoot(cur_pilot, 1 ); /* secondary */
/* other behaviours. */
if (ai_isFlag(AI_DISTRESS))
pilot_distress(cur_pilot, aiL_distressmsg, 0);
}
/**
* @brief Triggers the attacked() function in the pilot's AI.
*
* @param attacked Pilot that is attacked.
* @param[in] attacker ID of the attacker.
*/
void ai_attacked( Pilot* attacked, const unsigned int attacker )
{
lua_State *L;
HookParam hparam;
/* Custom hook parameters. */
hparam.type = HOOK_PARAM_PILOT;
hparam.u.lp.pilot = attacker;
/* Behaves differently if manually overriden. */
pilot_runHookParam( attacked, PILOT_HOOK_ATTACKED, &hparam, 1 );
if (pilot_isFlag( attacked, PILOT_MANUAL_CONTROL ))
return;
/* Must have an AI profile and not be player. */
if (attacked->ai == NULL)
return;
ai_setPilot( attacked ); /* Sets cur_pilot. */
L = cur_pilot->ai->L;
lua_getglobal(L, "attacked");
lua_pushnumber(L, attacker);
if (lua_pcall(L, 1, 0, 0)) {
WARN("Pilot '%s' ai -> 'attacked': %s", cur_pilot->name, lua_tostring(L,-1));
lua_pop(L,1);
}
}
/**
* @brief Has a pilot attempt to refuel the other.
*
* @param refueler Pilot doing the refueling.
* @param target Pilot to refuel.
*/
void ai_refuel( Pilot* refueler, unsigned int target )
{
Task *t;
/* Create the task. */
t = malloc(sizeof(Task));
t->next = NULL;
t->subtask = NULL;
t->name = strdup("refuel");
t->dtype = TASKDATA_INT;
t->dat.num = target;
/* Prepend the task. */
t->next = refueler->task;
refueler->task = t;
return;
}
/**
* @brief Sends a distress signal to a pilot.
*
* @param p Pilot recieving the distress signal.
* @param distressed Pilot sending the distress signal.
*/
void ai_getDistress( Pilot* p, const Pilot* distressed )
{
lua_State *L;
/* Ignore distress signals when under manual control. */
if (pilot_isFlag( p, PILOT_MANUAL_CONTROL ))
return;
/* Set up the environment. */
ai_setPilot(p);
L = cur_pilot->ai->L;
/* See if function exists. */
lua_getglobal(L, "distress");
if (lua_isnil(L,-1)) {
lua_pop(L,1);
return;
}
/* Run the function. */
lua_pushnumber(L, distressed->id);
lua_pushnumber(L, distressed->target);
if (lua_pcall(L, 2, 0, 0)) {
WARN("Pilot '%s' ai -> 'distress': %s", cur_pilot->name, lua_tostring(L,-1));
lua_pop(L,1);
}
}
/**
* @brief Runs the create() function in the pilot.
*
* Should create all the gear and sucth the pilot has.
*
* @param pilot Pilot to "create".
* @param param Parameter to pass to "create" function.
*/
static void ai_create( Pilot* pilot, char *param )
{
LuaPilot lp;
LuaFaction lf;
lua_State *L;
/* Set creation mode. */
if (!pilot_isFlag(pilot, PILOT_CREATED_AI))
aiL_status = AI_STATUS_CREATE;
/* Prepare AI. */
ai_setPilot( pilot );
/* Create equipment first - only if creating for the first time. */
if (!pilot_isFlag(pilot,PILOT_PLAYER) && ((aiL_status==AI_STATUS_CREATE) ||
!pilot_isFlag(pilot, PILOT_EMPTY))) {
L = equip_L;
lua_getglobal(L, "equip");
lp.pilot = cur_pilot->id;
lua_pushpilot(L,lp);
lf.f = cur_pilot->faction;
lua_pushfaction(L,lf);
if (lua_pcall(L, 2, 0, 0)) { /* Error has occurred. */
WARN("Pilot '%s' equip -> '%s': %s", cur_pilot->name, "equip", lua_tostring(L,-1));
lua_pop(L,1);
}
}
/* Prepare stack. */
L = cur_pilot->ai->L;
lua_getglobal(L, "create");
/* Parse parameter. */
if (param != NULL) {
/* Number */
if (isdigit(param[0]))
lua_pushnumber(L, atoi(param));
/* Special case player. */
else if (strcmp(param,"player")==0)
lua_pushnumber(L, PLAYER_ID);
/* Default. */
else
lua_pushstring(L, param);
}
/* Run function. */
if (lua_pcall(L, (param!=NULL) ? 1 : 0, 0, 0)) { /* error has occured */
WARN("Pilot '%s' ai -> '%s': %s", cur_pilot->name, "create", lua_tostring(L,-1));
lua_pop(L,1);
}
/* Recover normal mode. */
if (!pilot_isFlag(pilot, PILOT_CREATED_AI))
aiL_status = AI_STATUS_NORMAL;
}
/**
* @brief Creates a new AI task.
*/
Task *ai_newtask( Pilot *p, const char *func, int subtask, int pos )
{
Task *t, *pointer;
/* Create the new task. */
t = malloc( sizeof(Task) );
t->next = NULL;
t->subtask = NULL;
t->name = strdup(func);
t->dtype = TASKDATA_NULL;
/* Handle subtask and general task. */
if (!subtask) {