forked from X-Friese/FlyWithLua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlyWithLua.cpp
7277 lines (6530 loc) · 253 KB
/
FlyWithLua.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
// ----------------------------------
// FlyWithLua Plugin for X-Plane 11
// ----------------------------------
#define PLUGIN_VERSION "2.6.2 build " __DATE__ " " __TIME__
#if CREATECOMPLETEEDITION
#define PLUGIN_NAME "FlyWithLua Complete"
#define PLUGIN_DESCRIPTION "Batteries included version of Pandora's box with additional features."
#else
#define PLUGIN_NAME "FlyWithLua Core"
#define PLUGIN_DESCRIPTION "Core version of FlyWithLua with full support but less features."
#endif // CREATECOMPLETEEDITION
// Copyright (c) 2012 Carsten Lynker
//
// 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.
/***** (this is old stuff reused from FlyVFR)
* Snagar Modifications
* v2.0.7 [added] namespace to not conflict with missionx plugin.
* [replace] explicit extern call, with lua.hpp, does the same.
* [compatibility code] Since my gcc is 4.6 new x0 abilities are not available.
* Added some code with #ifdef directives to workaround these issues.
* [fyi] static link against lua 5.1.4 library, since many airplanes plugins uses this lua library. It resolve the crashing of XPLANE.
*
* v2.1.14 [compatibility] some (int) cast were changed to std::size_t to compile under gcc x86_64
* [changed] " string " was changed to "char x[size] ={...}" to fix gcc deprecate conversion warning.
* [changed] Linux: dynamic linked against LuaJIT2.0.0 final and XPSDK211
* v2.1.15 [added] OSX x64 + XP10x64 test code for Ben Supnik, to test LuaJit.
* v2.1.18 [added] lin.xpl and mac.xpl 32-bit build by Snagar, no code change compared to 2.1.17
* v2.1.29 [linux/osx build] removed disabled HID codefor OSX (again)
*/
/** Commands made during FlyWithLua development
* Carsten (X-Friese):
* v2.1.4 [changed] dynamic link against LuaJIT 1.1.8 library on Windows system.
* v2.1.5 [changed] dynamic link against a nightly build of LuaJIT 2.0 to take advantage of FFI library
* [fyi] must observe LuaJIT development, to grap a stable version than the beta10 we use at the moment
* a stable 2.0 of LuaJIT is announced for 2013 by Mike Pall, see http://www.freelists.org/post/luajit/LuaJIT-Roadmap-20122013
* v2.1.6 [fyi] first (Windows only) stable release of FlyWithLua 2.1, same code as 2.1.5, some fine tuning to the manual (logo added)
* v2.1.8 [solved] will no longer load files like "this.is.no.lua.script" or "backup.lua~"
* [solved] disable and enable won't crash Lua engine any more
* [solved] strings containing '\n' now result in multiple lines when send to XSquawkBox
* [added] two new libraries: LuaXML and proteaAudio from http://viremo.eludi.net/index.html
* [added] custom init and exit file user.ini and user.exit, to be edited by the user
* (no need to touch Internals folder when adding complex libraries)
* v2.1.12 [changed] dynamic linked against LuaJIT2.0.0 final and XPSDK211
* [changed] new fat format for 32/64 bit plugins
* v2.1.13 [added] the 32-bit plugin will ignore script file endian ".lua64" and the 64-bit plugin ignores ".lua32"
* v2.1.16 [changed] redesign of LuaDrawString(), added a helper function to fill the RGB array
* v2.1.17 [changed] enabled alpha testing (and blending) by default in function FWLDrawWindowCallback(), lines 507ff
* v2.1.19 [changed] bug fixed in LuaSetAxisAssignments(), it now sets non-reverse correct
* v2.1.21 [changed] function ReadScriptFile() was made Mountain Lion safe
* v2.1.24 [added] new Lua functions to draw a string: draw_string_Helvetica_10(), draw_string_Helvetica_12(), draw_string_Helvetica_18(),
* draw_string_Times_Roman_10() and draw_string_Times_Roman_24()
* v2.1.25 [changed] LuaJIT.DLL now with Ben's modification on Windows 64-bit
* v2.1.28 [solved] some misspelling corrected
* [solved] Key commands won't be blocked if Lua crashes (disabled key sniffer if Lua is not running)
* [solved] error messages containing multiple lines are now well formatted
* v2.2.0 [added] mouse click and wheel event callbacks do_on_mouse_click() and do_on_mouse_wheel()
* v2.2.1 [changed] no more classic or modern script mixing errors (hopefully)
* [added] new functions set_pilots_head() and get_pilots_head()
* v2.3.0 [added] OpenAL sound support!
* v2.3.3 [added] Support for Arcaze USB hardware.
* v2.4.2 [changed] More sound files can be loaded into memory
* v2.4.3 [added] sounds can be replaced in memory
* v2.4.4 [changed] new axis assignments in X-Plane 10.5x added to function set_axis_assignment()
* v2.6.0 [added] now we can create custom DataRefs
* [changed] from version 2.6.0 this plugin will only support X-Plane 11
* v2.6.2 [added] new compiler flag "CREATECOMPLETEEDITION" to get a separated version without restrictions
*
* Markus (Teddii):
* v2.1.20 [changed] bug fixed in Luahid_open() and Luahid_open_path(), setting last HID device index back if no device was found
* [changed] extended logMsg() with logType=logToAll|logToDevCon|logToSqkBox. If XSquawkBox is not connected logMsg() will fall back to DevCon
* [changed] overworked all logMsg() and XSBSpeakString() calls - so there are no more doubled strings in the code
* [fixed] fixed some copy/pasted logMessages in LuaAddMacro(), LuaLastButton(), LuaSetArray()
* [fixed] fixed a bug in function LuaSpeakString()
*/
/* Configure Code:Blocks to compile FlyWithLua on Windows
* ======================================================
*
* 1. Download and install Code:Blocks with MinGW from this website: http://www.codeblocks.org/downloads/26
* (Choose the file "codeblocks-12.11mingw-setup.exe".)
*
* 2. Download and install MinGW 64-bit from this website: http://mingw-w64.sourceforge.net/
* (Choose the latest automated build for Windows from "WIN64 Downloads", it should be a file
* like this "mingw-w64-bin_i686-mingw_20111220.zip".)
*
* 3. Extract the ZIP archive containing MinGW64 to the path "P:\MinGW64\", or any other path you like.
*
* 4. Start Code:Blocks, click on "Settings" -> "Compiler ..."
*
* 5. Copy the settings "GNU GCC Compiler" and name the new setting "gcc64".
*
* 6. Change the names and paths inside the tab "toolchain executables" to point to MinGW64.
* The names have to start with "x86_64-w64-mingw32-", as you can check out in "P:\MinGW64\bin\".
*
* 7. Jump to tab "Additional path" and add this path: "P:\MinGW64\libexec\gcc\x86_64-w64-mingw32\4.7.0"
* or the path with the version number of your MinGW64.
*
* 8. Now add this paths at "Search directories" -> "Compiler":
* P:\MinGW64\include
* P:\MinGW64\x86_64-w64-mingw32\include
* P:\MinGW64\x86_64-w64-mingw32\include\c++\<VERSION>
* P:\MinGW64\x86_64-w64-mingw32\include\c++\<VERSION>\backward
* P:\MinGW64\x86_64-w64-mingw32\include\c++\<VERSION>\x86_64-w64-mingw32
* P:\MinGW64\lib\gcc\x86_64-w64-mingw32\<VERSION>\include
*
* 9. Add this to "Search directories" -> "Linker":
* P:\MinGW64\lib
* P:\MinGW64\x86_64-w64-mingw32\lib
*
* 10. Close Code:Blocks now.
*
* 11. Create a new folder "P:\Plugin Development\".
*
* 12. Go to this website and download the X-Plane SDK: http://www.xsquawkbox.net/xpsdk/mediawiki/Download
* Download the latest version and the 2.0 version too.
*
* 13. Create a subfolder "P:\Plugin Development\SDK201\" and an equivalent subfolder for the latest version (like "P:\Plugin Development\SDK212\").
*
* 14. Extract the ZIP files containing the X-Plane SDKs into the corresponding subfolders.
* (There is now a file like this "P:\Plugin Development\SDK201\SDK\Libraries\Win\XPLM.lib".)
*
* 15. Extract all files from "sourcecode.zip" into a new folder "P:\Plugin Development\FlyWithLua2\".
*
* 16. Step into "P:\Plugin Development\FlyWithLua2\" and double-click on "FlyWithLua.cbp".
*
* 17. Click on "Project" -> "Build options..." -> "WIN64 SDK212" -> "Pre/post build steps" and setup all post build steps as you like.
* You may want to erase all of them, as they didn't fit your paths.
*/
#if IBM
#include <windows.h>
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return true;
}
#include <unistd.h>
#endif
// OK, load as much as you can ;)
#include "XPLMPlugin.h"
#include "XPLMDisplay.h"
#include "XPLMGraphics.h"
#include "XPLMProcessing.h"
#include "XPLMDataAccess.h"
#include "XPLMMenus.h"
#include "XPLMUtilities.h"
#include "XPWidgets.h"
#include "XPStandardWidgets.h"
#include "XPLMScenery.h"
#include "XPLMNavigation.h"
#include "XPLMPlanes.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <wchar.h>
#include "XSBComDefs.h"
// include OpenGL
#if IBM
#include <gl/GL.h>
#include <gl/glut.h>
#else
#if LIN
#define TRUE 1
#define FALSE 0
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
// #include <libudev.h>
#else
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#include <Carbon/Carbon.h>
#endif
#endif
// include OpenAL
#include "OpenAL/al.h"
#include "OpenAL/alc.h"
//get low level access to HID devices
// disable HID in OSX until be able to create binaries.
//#ifndef APL
#include <hidapi.h>
//#endif
// include the extern command provided by the LUA team
#include <lua.hpp>
namespace flywithlua
{
using namespace std; // snagar
// Maybe usefull to be platform independend
#ifndef M_PI
#define M_PI 3.14159265358979323846f
#endif
#define NORMALSTRING 250
#define SHORTSRTING 80
#define LONGSTRING 1024
#define MAXDATAREFS 400
#define MAXMACROS 150
#define MAXCOMMANDS 250
#define MAXJOYSTICKBUTTONS 1600 // this value is set by the length of DataRef sim/joystick/joystick_button_values
#define MAXSOUNDS 100 // the number of OpelAL sound buffers
// Do we want to access a forbidden DataRef?
#if CREATECOMPLETEEDITION
#define CHECK_IF_DATAREF_ALLOWED(DataRefWanted) // we only want to check DataRefWanted in Core Edition
#else
#define CHECK_IF_DATAREF_ALLOWED(DataRefWanted) if (strncmp(DataRefWanted, "sim/private/", 12)==0) \
{ \
logMsg(logToAll, string("FlyWithLua Error: The DataRef \"").append(DataRefWanted).append("\" can not be accessed from FlyWithLua, as it is a private DataRef. Reading or writing private DataRefs is prohibited by Laminar Research.")); \
logMsg(logToAll, string("FlyWithLua Info: Ben Subnik told us this: (Please see http://developer.x-plane.com/2014/05/art-controls-are-an-active-volcano/ for more details.)")); \
logMsg(logToAll, string("FlyWithLua Info: The art controls are not a public interface to make X-Plane add-ons. They are an internal development tool. They are unsupported, undocumented, unsafe, and most importantly subject to change with every patch of X-Plane.")); \
logMsg(logToAll, string("FlyWithLua Info: If you create an add-on that requires reading or writing the art controls, you can expect that your add-on will stop working when X-Plane is updated. When your add-on breaks, please do not complain or file a bug.")); \
LuaIsRunning = false; \
return 0; \
}
#endif // CREATECOMPLETEEDITION
//Code from Ben Supnik Regarding Luajit in 64bit build
struct lua_alloc_request_t
{
void * ud;
void * ptr;
size_t osize;
size_t nsize;
};
#define ALLOC_OPEN 0x00A110C1
#define ALLOC_REALLOC 0x00A110C2
#define ALLOC_CLOSE 0x00A110C3
/* new in X-Plane 10.40 */
/* but totally unused in FlyWithLua at the moment */
#define ALLOC_LOCK 0x00A110C4
#define ALLOC_UNLOCK 0x00A110C5
#define ALLOC_LOCK_RO 0x00A110C6
static void *lj_alloc_create(void)
{
struct lua_alloc_request_t r = { 0 };
XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_OPEN,&r);
return r.ud;
}
static void lj_alloc_destroy(void *msp)
{
struct lua_alloc_request_t r = { 0 };
r.ud = msp;
XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_CLOSE,&r);
}
static void *lj_alloc_f(void *msp, void *ptr, size_t osize, size_t nsize)
{
struct lua_alloc_request_t r = { 0 };
r.ud = msp;
r.ptr = ptr;
r.osize = osize;
r.nsize = nsize;
XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_REALLOC,&r);
return r.ptr;
}
// Added since compiler argued about duplicate definitions on OSX
#ifndef APL
struct RGBColor
{
float red;
float green;
float blue;
};
#endif
// qsort needs a compare function, let's use strcmp for it
// as qsort gives void pointers, we have to convert them to char pointers
static int compare_filenames(const void *a, const void *b)
{
return strcmp (*(const char **) a, *(const char **) b);
}
//#ifndef APL
#define MAXHIDDEVICES 127
void* HIDSloppyTable[MAXHIDDEVICES];
int LAST_SLOPPY_HID = -1;
void CloseAllOpenHIDDevices( void )
{
if (LAST_SLOPPY_HID >= 0)
{
for (int i=0; i<=LAST_SLOPPY_HID; i++)
{
hid_close((hid_device *) HIDSloppyTable[i]);
}
}
LAST_SLOPPY_HID = -1;
return;
}
//#endif
struct DataRefTableStructure
{
char DataRefName[NORMALSTRING];
char LuaVariable[NORMALSTRING];
bool IsReadOnly;
XPLMDataRef DataRefId;
int Index;
XPLMDataTypeID DataRefTypeId;
};
static DataRefTableStructure DataRefTable[MAXDATAREFS];
static int DataRefTableLastElement = -1;
struct MacroTableStructure
{
bool IsSwitch;
string MacroName;
string ActivateCommand;
string DeactivateCommand;
int XPLM_Index;
};
static MacroTableStructure MacroTable[MAXMACROS];
static int MacroTableLastElement = -1;
enum SwitchTypes {Switch, PositiveEdge, NegativeEdge, PositiveIncrement, NegativeIncrement, PositiveDecrement, NegativeDecrement, ABCEncoder, PositiveFlip, NegativeFlip, AxisMedian};
struct SwitchTableStructure
{
SwitchTypes SwitchType;
XPLMDataRef DataRefID;
XPLMDataTypeID DataRefType;
string DataRefName;
int button;
int button2;
int index;
int on_int;
int off_int;
float on_float;
float off_float;
double on_double;
double off_double;
float upper_limit_float;
float lower_limit_float;
float stepping_float;
float round;
int upper_limit_int;
int lower_limit_int;
int stepping_int;
};
static SwitchTableStructure SwitchTable[MAXDATAREFS];
static int SwitchTableLastElement = -1;
bool CrashReportDisplayed = false;
static int LuaResetCount = 0;
bool UserWantsANewPlane = false;
bool UserWantsToLoadASituation = false;
bool UserWantsToReplaceAircraft = false;
char UserWantedFilename[LONGSTRING];
bool WeAreNotInDrawingState = true;
void EraseDataRefTable( void )
{
XPLMDataRef DoNothing = XPLMFindDataRef("sim/none/none");
for (int i=0; i<MAXDATAREFS; i++)
{
DataRefTable[i].IsReadOnly = true;
DataRefTable[i].DataRefId = DoNothing;
strcpy(DataRefTable[i].DataRefName, "");
DataRefTable[i].DataRefTypeId = xplmType_Unknown;
DataRefTable[i].Index = 0;
strcpy(DataRefTable[i].LuaVariable, "");
}
DataRefTableLastElement = -1;
for (int i=0; i<MAXMACROS; i++)
{
MacroTable[i].IsSwitch = false;
MacroTable[i].MacroName.clear();
MacroTable[i].ActivateCommand.clear();
MacroTable[i].DeactivateCommand.clear();
MacroTable[i].XPLM_Index = 0;
}
MacroTableLastElement = -1;
for (int i=0; i<MAXDATAREFS; i++)
{
SwitchTable[i].button = 0;
SwitchTable[i].DataRefID = DoNothing;
SwitchTable[i].DataRefName.clear();
SwitchTable[i].DataRefType = xplmType_Unknown;
SwitchTable[i].off_int = 0;
SwitchTable[i].off_float = 0;
SwitchTable[i].off_double = 0;
SwitchTable[i].on_int = 1;
SwitchTable[i].on_float = 1;
SwitchTable[i].on_double = 1;
}
SwitchTableLastElement = -1;
}
struct CommandTableStructure
{
XPLMCommandRef Reference;
string Name;
string Description;
string BeginCommand;
string ContinueCommand;
string EndCommand;
};
static CommandTableStructure CommandTable[MAXCOMMANDS];
static int CommandTableLastElement = -1;
struct OpenALTableStructure
{
string filename;
float pitch;
float gain;
bool loop;
};
static OpenALTableStructure OpenALTable[MAXSOUNDS];
static int OpenALTableLastElement = -1;
static ALuint OpenALBuffers[MAXSOUNDS];
static ALuint OpenALSources[MAXSOUNDS];
lua_State *FWLLua;
void *ud;
// ----8<---- Some code from this example: http://www.xsquawkbox.net/xpsdk/mediawiki/OpenAL_Shared_Example ----
/**************************************************************************************************************
* WAVE FILE LOADING
**************************************************************************************************************/
// You can just use alutCreateBufferFromFile to load a wave file, but there seems to be a lot of problems with
// alut not beign available, being deprecated, etc. So...here's a stupid routine to load a wave file. I have
// tested this only on x86 machines, so if you find a bug on PPC please let me know.
// Macros to swap endian-values.
#define SWAP_32(value) \
(((((unsigned short)value)<<8) & 0xFF00) | \
((((unsigned short)value)>>8) & 0x00FF))
#define SWAP_16(value) \
(((((unsigned int)value)<<24) & 0xFF000000) | \
((((unsigned int)value)<< 8) & 0x00FF0000) | \
((((unsigned int)value)>> 8) & 0x0000FF00) | \
((((unsigned int)value)>>24) & 0x000000FF))
// Wave files are RIFF files, which are "chunky" - each section has an ID and a length. This lets us skip
// things we can't understand to find the parts we want. This header is common to all RIFF chunks.
struct chunk_header {
int id;
int size;
};
// WAVE file format info. We pass this through to OpenAL so we can support mono/stereo, 8/16/bit, etc.
struct format_info {
short format; // PCM = 1, not sure what other values are legal.
short num_channels;
int sample_rate;
int byte_rate;
short block_align;
short bits_per_sample;
};
// This utility returns the start of data for a chunk given a range of bytes it might be within. Pass 1 for
// swapped if the machine is not the same endian as the file.
static char * find_chunk(char * file_begin, char * file_end, int desired_id, int swapped)
{
while(file_begin < file_end)
{
chunk_header * h = (chunk_header *) file_begin;
if(h->id == desired_id && !swapped)
return file_begin+sizeof(chunk_header);
if(h->id == SWAP_32(desired_id) && swapped)
return file_begin+sizeof(chunk_header);
int chunk_size = swapped ? SWAP_32(h->size) : h->size;
char * next = file_begin + chunk_size + sizeof(chunk_header);
if(next > file_end || next <= file_begin)
return NULL;
file_begin = next;
}
return NULL;
}
// Given a chunk, find its end by going back to the header.
static char * chunk_end(char * chunk_start, int swapped)
{
chunk_header * h = (chunk_header *) (chunk_start - sizeof(chunk_header));
return chunk_start + (swapped ? SWAP_32(h->size) : h->size);
}
#define FAIL(X) { XPLMDebugString(X); free(mem); return 0; }
#define RIFF_ID 0x46464952 // 'RIFF'
#define FMT_ID 0x20746D66 // 'FMT '
#define DATA_ID 0x61746164 // 'DATA'
ALuint load_wave(const char * file_name)
{
// First: we open the file and copy it into a single large memory buffer for processing.
FILE * fi = fopen(file_name,"rb");
if(fi == NULL)
{
XPLMDebugString("WAVE file load failed - could not open.\n");
return 0;
}
fseek(fi,0,SEEK_END);
int file_size = ftell(fi);
fseek(fi,0,SEEK_SET);
char * mem = (char*) malloc(file_size);
if(mem == NULL)
{
XPLMDebugString("WAVE file load failed - could not allocate memory.\n");
fclose(fi);
return 0;
}
if (fread(mem, 1, file_size, fi) != file_size)
{
XPLMDebugString("WAVE file load failed - could not read file.\n");
free(mem);
fclose(fi);
return 0;
}
fclose(fi);
char * mem_end = mem + file_size;
// Second: find the RIFF chunk. Note that by searching for RIFF both normal
// and reversed, we can automatically determine the endian swap situation for
// this file regardless of what machine we are on.
int swapped = 0;
char * riff = find_chunk(mem, mem_end, RIFF_ID, 0);
if(riff == NULL)
{
riff = find_chunk(mem, mem_end, RIFF_ID, 1);
if(riff)
swapped = 1;
else
FAIL("Could not find RIFF chunk in wave file.\n")
}
// The wave chunk isn't really a chunk at all. :-( It's just a "WAVE" tag
// followed by more chunks. This strikes me as totally inconsistent, but
// anyway, confirm the WAVE ID and move on.
if (riff[0] != 'W' ||
riff[1] != 'A' ||
riff[2] != 'V' ||
riff[3] != 'E')
FAIL("Could not find WAVE signature in wave file.\n")
char * format = find_chunk(riff+4, chunk_end(riff,swapped), FMT_ID, swapped);
if(format == NULL)
FAIL("Could not find FMT chunk in wave file.\n")
// Find the format chunk, and swap the values if needed. This gives us our real format.
format_info * fmt = (format_info *) format;
if(swapped)
{
fmt->format = SWAP_16(fmt->format);
fmt->num_channels = SWAP_16(fmt->num_channels);
fmt->sample_rate = SWAP_32(fmt->sample_rate);
fmt->byte_rate = SWAP_32(fmt->byte_rate);
fmt->block_align = SWAP_16(fmt->block_align);
fmt->bits_per_sample = SWAP_16(fmt->bits_per_sample);
}
// Reject things we don't understand...expand this code to support weirder audio formats.
if(fmt->format != 1) FAIL("Wave file is not PCM format data.\n")
if(fmt->num_channels != 1 && fmt->num_channels != 2) FAIL("Must have mono or stereo sound.\n")
if(fmt->bits_per_sample != 8 && fmt->bits_per_sample != 16) FAIL("Must have 8 or 16 bit sounds.\n")
char * data = find_chunk(riff+4, chunk_end(riff,swapped), DATA_ID, swapped) ;
if(data == NULL)
FAIL("I could not find the DATA chunk.\n")
int sample_size = fmt->num_channels * fmt->bits_per_sample / 8;
int data_bytes = chunk_end(data,swapped) - data;
int data_samples = data_bytes / sample_size;
// If the file is swapped and we have 16-bit audio, we need to endian-swap the audio too or we'll
// get something that sounds just astoundingly bad!
if(fmt->bits_per_sample == 16 && swapped)
{
short * ptr = (short *) data;
int words = data_samples * fmt->num_channels;
while(words--)
{
*ptr = SWAP_16(*ptr);
++ptr;
}
}
// Finally, the OpenAL crud. Build a new OpenAL buffer and send the data to OpenAL, passing in
// OpenAL format enums based on the format chunk.
OpenALBuffers[OpenALTableLastElement] = 0;
alGenBuffers(1, &OpenALBuffers[OpenALTableLastElement]);
if(OpenALBuffers[OpenALTableLastElement] == 0) FAIL("Could not generate buffer id.\n");
alBufferData(OpenALBuffers[OpenALTableLastElement], fmt->bits_per_sample == 16 ?
(fmt->num_channels == 2 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16) :
(fmt->num_channels == 2 ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8),
data, data_bytes, fmt->sample_rate);
free(mem);
return OpenALBuffers[OpenALTableLastElement];
}
/**************************************************************************************************************
* SAMPLE OEPNAL PLUGIN:
**************************************************************************************************************/
// we use our own table for this
// static ALuint snd_src =0; // Sample source and buffer - this is one "sound" we play.
// static ALuint snd_buffer =0;
// static float pitch = 1.0f; // Start with 1.0 pitch - no pitch shift.
static ALCdevice * my_dev = NULL; // We make our own device and context to play sound through.
static ALCcontext * my_ctx = NULL;
// This is a stupid logging error function...useful for debugging, but not good error checking.
#define CHECK_ERR() __CHECK_ERR(__FILE__,__LINE__)
static void __CHECK_ERR(const char * f, int l)
{
ALuint e = alGetError();
if (e != AL_NO_ERROR)
printf("ERROR: %d (%s:%d\n", e, f, l);
}
// Mac specific: this converts file paths from HFS (which we get from the SDK) to Unix (which the OS wants).
// See this for more info:
//
// http://www.xsquawkbox.net/xpsdk/mediawiki/FilePathsAndMacho
#if APL
static int ConvertPath(const char * inPath, char * outPath, int outPathMaxLen) {
CFStringRef inStr = CFStringCreateWithCString(kCFAllocatorDefault, inPath ,kCFStringEncodingMacRoman);
if (inStr == NULL)
return -1;
CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, inStr, kCFURLHFSPathStyle,0);
CFStringRef outStr = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
if (!CFStringGetCString(outStr, outPath, outPathMaxLen, kCFURLPOSIXPathStyle))
return -1;
CFRelease(outStr);
CFRelease(url);
CFRelease(inStr);
return 0;
}
#endif
// Initialization code.
static float init_sound(float elapsed, float elapsed_sim, int counter, void * ref)
{
CHECK_ERR();
char buf[2048];
// We have to save the old context and restore it later, so that we don't interfere with X-Plane
// and other plugins.
ALCcontext * old_ctx = alcGetCurrentContext();
if(old_ctx == NULL)
{
printf("0x%08x: I found no OpenAL, I will be the first to init.\n",XPLMGetMyID());
my_dev = alcOpenDevice(NULL);
if(my_dev == NULL)
{
XPLMDebugString("Could not open the default OpenAL device.\n");
return 0;
}
my_ctx = alcCreateContext(my_dev, NULL);
if(my_ctx == NULL)
{
if(old_ctx)
alcMakeContextCurrent(old_ctx);
alcCloseDevice(my_dev);
my_dev = NULL;
XPLMDebugString("Could not create a context.\n");
return 0;
}
// Make our context current, so that OpenAL commands affect our, um, stuff.
alcMakeContextCurrent(my_ctx);
printf("0x%08x: I created the context.\n",XPLMGetMyID(), my_ctx);
ALCint major_version, minor_version;
const char * al_hw=alcGetString(my_dev,ALC_DEVICE_SPECIFIER );
const char * al_ex=alcGetString(my_dev,ALC_EXTENSIONS);
alcGetIntegerv(NULL,ALC_MAJOR_VERSION,sizeof(major_version),&major_version);
alcGetIntegerv(NULL,ALC_MINOR_VERSION,sizeof(minor_version),&minor_version);
printf("OpenAL version : %d.%d\n",major_version,minor_version);
printf("OpenAL hardware : %s\n", (al_hw?al_hw:"(none)"));
printf("OpenAL extensions: %s\n", (al_ex?al_ex:"(none)"));
CHECK_ERR();
}
else
{
printf("0x%08x: I found someone else's context 0x%08x.\n",XPLMGetMyID(), old_ctx);
}
// skipping some code, as we don't want to load the example sound file
return 0.0f;
}
// ----------------- End of code from example --------------->8------------------
// Modified by Snagar
std::string pluginMainDir;
std::string scriptDir;
// END modified by Snagar
// The user will be able to handle the plugin with commands
XPLMCommandRef MyReloadScriptsCommand = NULL;
int MyReloadScriptsCommandHandler(XPLMCommandRef inCommand,
XPLMCommandPhase inPhase,
void * inRefcon);
//Teddii: Enum fuer "logMsg"
enum ELogType
{
logToAll = 0,
logToDevCon = 1,
logToSqkBox = 2
};
void logMsg (ELogType logType, std::string message ); //Teddii: added parameter logType //void logMsg ( std::string message );
void initPluginDirectory ( ); // snagar
void ResetLuaEngine( void );
bool RunLuaString(string LuaCommandString);
void CopyDataRefsToLua( void );
void CopyDataRefsToXPlane( void );
bool ReadScriptFile(char *FileNameToRead);
bool RunLuaChunk(const char *ChunkName);
// new way to handle classic and modern DataRaf access
void update_Lua_dataref_variables(XPLMDataRef DataRefID, int Index, float Value);
void update_Lua_dataref_strings(XPLMDataRef DataRefID, int Index, char * ValueString);
// These things will run periodically
float MyEveryFrameLoopCallback(
float inElapsedSinceLastCall,
float inElapsedTimeSinceLastFlightLoop,
int inCounter,
void * inRefcon);
float MyFastLoopCallback(
float inElapsedSinceLastCall,
float inElapsedTimeSinceLastFlightLoop,
int inCounter,
void * inRefcon);
float MySlowLoopCallback(
float inElapsedSinceLastCall,
float inElapsedTimeSinceLastFlightLoop,
int inCounter,
void * inRefcon);
// let's give the last Metar to Lua
XPLMDataRef gXSBMetarStringXDataRef = NULL;
// Some variables used global in this plugin
static string EveryFrameCallbackCommand = "";
static string CallbackCommand = "";
static string LongTimeCallbackCommand = "";
static string KeyEventCommand = "";
static string NewMetarCommand = "";
float TimeBetweenCallbacks = 1.0; // processed every second
float LongTimeBetweenCallbacks = 10.0; // not so often processed
// to increase performance
bool LuaIsRunning = false; // Are we working with Lua?
int JoystickButtonValues[MAXJOYSTICKBUTTONS];
int JoystickButtonLastValues[MAXJOYSTICKBUTTONS];
// We need some DataRefs
XPLMDataRef gJoystickButtonAssignments;
XPLMDataRef gJoystickButtonValues;
XPLMDataRef gJoystickAxisAssignments;
XPLMDataRef gJoystickAxisReverse;
XPLMDataRef gJoystickAxisValues;
XPLMDataRef gPlaneICAO;
XPLMDataRef gPlaneTailNumber;
// We interact with XSquawkBox
XPLMPluginID XSBPluginId;
XPLMDataRef XSBInputUsrMsgXDataRef;
XPLMDataRef XSBInputStringXDataRef;
XPLMDataRef XSBDestinationXDataRef;
XPLMDataRef XSBAlternativeXDataRef;
XPLMDataRef XSBStartAirportXDataRef;
XPLMDataRef XSBATCFreqXDataRef;
XPLMDataRef XSBATCCallsignXDataRef;
static bool WeHaveXSB = false;
static int NewMetarCountdown = 0;
// DataRefs used by set_pilots_head()
static XPLMDataRef FWLPilotsHeadX = XPLMFindDataRef("sim/graphics/view/pilots_head_x");
static XPLMDataRef FWLPilotsHeadY = XPLMFindDataRef("sim/graphics/view/pilots_head_y");
static XPLMDataRef FWLPilotsHeadZ = XPLMFindDataRef("sim/graphics/view/pilots_head_z");
static XPLMDataRef FWLPilotsHeadHeading = XPLMFindDataRef("sim/graphics/view/pilots_head_psi");
static XPLMDataRef FWLPilotsHeadPitch = XPLMFindDataRef("sim/graphics/view/pilots_head_the");
static XPLMDataRef FWLViewType = XPLMFindDataRef("sim/graphics/view/view_type");
// Don't want to use buttons? Here is a nice little menu
void FlyWithLuaMenuHandler(void *, void *);
XPLMMenuID FlyWithLuaMenuId;
int FlyWithLuaMenuItem;
void MacroMenuHandler(void *, void *);
XPLMMenuID MacroMenuId;
XPLMMenuID ATCMenuId;
int MacroMenuItem;
int ATCMenuItem;
// to be able to draw text we need a container to carry Lua commands
string LuaDrawCommand;
// and we need a window to catch mouse events
XPLMWindowID FWLMouseEventWindowID;
string LuaMouseClickCommand;
string LuaMouseWheelCommand;
int LAST_SCREEN_WIDTH, LAST_SCREEN_HIGHT;
void FWLMouseEventWindowDraw(XPLMWindowID inWindowID, void * inRefcon)
{
// we have nothing to draw inside the mouse event window
}
void FWLMouseEventWindowKey(XPLMWindowID inWindowID, char inKey, XPLMKeyFlags inFlags, char vkey, void * inRefcon, int losingFocus)
{
// no keyboard handling to catch mouse events
}
int FWLMouseEventWindowMouse(XPLMWindowID inWindowID, int x, int y, XPLMMouseStatus isDown, void * inRefcon)
{
// is Lua running? If not, give the control back to X-Plane
if (!LuaIsRunning)
{
return 0;
}
// setup the predefined variables
lua_pushboolean(FWLLua, false);
lua_setglobal(FWLLua, "RESUME_MOUSE_CLICK");
if (isDown == xplm_MouseDown)
{
lua_pushstring(FWLLua, "down");
}
else if (isDown == xplm_MouseDrag)
{
lua_pushstring(FWLLua, "drag");
}
else
{
lua_pushstring(FWLLua, "up");
}
lua_setglobal(FWLLua, "MOUSE_STATUS");
// let Lua do it's work
RunLuaChunk("DO_ON_MOUSE_CLICK_CHUNK");
// should we resume the mouse click?
lua_getglobal(FWLLua, "RESUME_MOUSE_CLICK");
if (lua_toboolean(FWLLua, 1))
{
lua_pop(FWLLua, 1);
return 1;
}
else
{
lua_pop(FWLLua, 1);
return 0;
}
}
int FWLMouseEventWindowMouseWheel(XPLMWindowID inWindowID,
int x,
int y,
int wheel,
int clicks,
void * inRefcon)
{
// is Lua running? If not, give the control back to X-Plane
if (!LuaIsRunning)
{
return 0;
}
// setup the predefined variables
lua_pushboolean(FWLLua, false);
lua_setglobal(FWLLua, "RESUME_MOUSE_WHEEL");
lua_pushnumber(FWLLua, wheel);
lua_setglobal(FWLLua, "MOUSE_WHEEL_NUMBER");
lua_pushnumber(FWLLua, clicks);
lua_setglobal(FWLLua, "MOUSE_WHEEL_CLICKS");
// let Lua do it's work
RunLuaChunk("DO_ON_MOUSE_WHEEL_CHUNK");
// should we resume the mouse wheel?
lua_getglobal(FWLLua, "RESUME_MOUSE_WHEEL");
if (lua_toboolean(FWLLua, 1))
{
lua_pop(FWLLua, 1);
return 1;
}
else
{
lua_pop(FWLLua, 1);