Debian Codegraph @

Nasal/aircraft.nas

raw
1 # This module provide basic functions and classes for use in aircraft specific
2 # Nasal context.
3
4
5
6 # helper functions
7 # ==============================================================================
8
9 # creates (if necessary) and returns a property node from arg[0],
10 # which can be a property node already, or a property path
11 #
12 var makeNode = func(n) {
13 if (isa(n, props.Node))
14 return n;
15 else
16 return props.globals.getNode(n, 1);
17 }
18
19
20 # returns args[index] if available and non-nil, or default otherwise
21 #
22 var optarg = func(args, index, default) {
23 size(args) > index and args[index] != nil ? args[index] : default;
24 }
25
26
27
28 # door
29 # ==============================================================================
30 # class for objects moving at constant speed, with the ability to
31 # reverse moving direction at any point. Appropriate for doors, canopies, etc.
32 #
33 # SYNOPSIS:
34 # door.new(<property>, <swingtime> [, <startpos>]);
35 #
36 # property ... door node: property path or node
37 # swingtime ... time in seconds for full movement (0 -> 1)
38 # startpos ... initial position (default: 0)
39 #
40 # PROPERTIES:
41 # ./position-norm (double) (default: <startpos>)
42 # ./enabled (bool) (default: 1)
43 #
44 # EXAMPLE:
45 # var canopy = aircraft.door.new("sim/model/foo/canopy", 5);
46 # canopy.open();
47 #
48 var door = {
49 new: func(node, swingtime, pos = 0) {
50 var m = { parents: [door] };
51 m.node = makeNode(node);
52 m.swingtime = swingtime;
53 m.enabledN = m.node.initNode("enabled", 1, "BOOL");
54 m.positionN = m.node.initNode("position-norm", pos);
55 m.target = pos < 0.5;
56 return m;
57 },
58 # door.enable(bool) -> set ./enabled
59 enable: func(v) {
60 me.enabledN.setBoolValue(v);
61 me;
62 },
63 # door.setpos(double) -> set ./position-norm without movement
64 setpos: func(pos) {
65 me.stop();
66 me.positionN.setValue(pos);
67 me.target = pos < 0.5;
68 me;
69 },
70 # double door.getpos() -> return current position as double
71 getpos: func {
72 me.positionN.getValue();
73 },
74 # door.close() -> move to closed state
75 close: func {
76 me.move(me.target = 0);
77 },
78 # door.open() -> move to open state
79 open: func {
80 me.move(me.target = 1);
81 },
82 # door.toggle() -> move to opposite end position
83 toggle: func {
84 me.move(me.target);
85 },
86 # door.stop() -> stop movement
87 stop: func {
88 interpolate(me.positionN);
89 },
90 # door.move(double) -> move to arbitrary position
91 move: func(target) {
92 var pos = me.getpos();
93 if (pos != target) {
94 var time = abs(pos - target) * me.swingtime;
95 interpolate(me.positionN, target, time);
96 }
97 me.target = !me.target;
98 },
99 };
100
101
102
103 # light
104 # ==============================================================================
105 # class for generation of pulsing values. Appropriate for controlling
106 # beacons, strobes, etc.
107 #
108 # SYNOPSIS:
109 # light.new(<property>, <pattern> [, <switch>]);
110 # light.new(<property>, <stretch>, <pattern> [, <switch>]);
111 #
112 # property ... light node: property path or node
113 # stretch ... multiplicator for all pattern values
114 # pattern ... array of on/off time intervals (in seconds)
115 # switch ... property path or node to use as switch (default: ./enabled)
116 # instead of ./enabled
117 #
118 # PROPERTIES:
119 # ./state (bool) (default: 0)
120 # ./enabled (bool) (default: 0) except if <switch> given)
121 #
122 # EXAMPLES:
123 # aircraft.light.new("sim/model/foo/beacon", [0.4, 0.4]); # anonymous light
124 #-------
125 # var strobe = aircraft.light.new("sim/model/foo/strobe", [0.05, 0.05, 0.05, 1],
126 # "controls/lighting/strobe");
127 # strobe.switch(1);
128 #-------
129 # var switch = props.globals.getNode("controls/lighting/strobe", 1);
130 # var pattern = [0.02, 0.03, 0.02, 1];
131 # aircraft.light.new("sim/model/foo/strobe-top", 1.001, pattern, switch);
132 # aircraft.light.new("sim/model/foo/strobe-bot", 1.005, pattern, switch);
133 #
134 var light = {
135 new: func {
136 var m = { parents: [light] };
137 m.node = makeNode(arg[0]);
138 var stretch = 1.0;
139 var c = 1;
140 if (isscalar(arg[c])) {
141 stretch = arg[c];
142 c += 1;
143 }
144 m.pattern = arg[c];
145 c += 1;
146 if (size(arg) > c and arg[c] != nil)
147 m.switchN = makeNode(arg[c]);
148 else
149 m.switchN = m.node.getNode("enabled", 1);
150
151 m.switchN.initNode(nil, 0, "BOOL");
152 m.stateN = m.node.initNode("state", 0, "BOOL");
153
154 forindex (var i; m.pattern)
155 m.pattern[i] *= stretch;
156
157 m.index = 0;
158 m.loopid = 0;
159 m.continuous = 0;
160 m.lastswitch = 0;
161 m.seqcount = -1;
162 m.endstate = 0;
163 m.count = nil;
164 m.switchL = setlistener(m.switchN, func m._switch_(), 1);
165 return m;
166 },
167 # class destructor
168 del: func {
169 removelistener(me.switchL);
170 },
171 # light.switch(bool) -> set light switch (also affects other lights
172 # that use the same switch)
173 switch: func(v) {
174 me.switchN.setBoolValue(v);
175 me;
176 },
177 # light.toggle() -> toggle light switch
178 toggle: func {
179 me.switchN.setBoolValue(!me.switchN.getValue());
180 me;
181 },
182 # light.cont() -> continuous light
183 cont: func {
184 if (!me.continuous) {
185 me.continuous = 1;
186 me.loopid += 1;
187 me.stateN.setBoolValue(me.lastswitch);
188 }
189 me;
190 },
191 # light.blink() -> blinking light (default)
192 # light.blink(3) -> when switched on, only run three blink sequences;
193 # second optional arg defines state after the sequences
194 blink: func(count = -1, endstate = 0) {
195 me.seqcount = count;
196 me.endstate = endstate;
197 if (me.continuous) {
198 me.continuous = 0;
199 me.index = 0;
200 me.stateN.setBoolValue(0);
201 me.lastswitch and me._loop_(me.loopid += 1);
202 }
203 me;
204 },
205 _switch_: func {
206 var switch = me.switchN.getBoolValue();
207 switch != me.lastswitch or return;
208 me.lastswitch = switch;
209 me.loopid += 1;
210 if (me.continuous or !switch) {
211 me.stateN.setBoolValue(switch);
212 } elsif (switch) {
213 me.stateN.setBoolValue(0);
214 me.index = 0;
215 me.count = me.seqcount;
216 me._loop_(me.loopid);
217 }
218 },
219 _loop_: func(id) {
220 id == me.loopid or return;
221 if (!me.count) {
222 me.loopid += 1;
223 me.stateN.setBoolValue(me.endstate);
224 return;
225 }
226 me.stateN.setBoolValue(me.index == 2 * int(me.index / 2));
227 settimer(func me._loop_(id), me.pattern[me.index]);
228 if ((me.index += 1) >= size(me.pattern)) {
229 me.index = 0;
230 if (me.count > 0)
231 me.count -= 1;
232 }
233 },
234 };
235
236
237
238 # lowpass
239 # ==============================================================================
240 # class that implements a variable-interval EWMA (Exponentially Weighted
241 # Moving Average) lowpass filter with characteristics independent of the
242 # frame rate.
243 #
244 # SYNOPSIS:
245 # lowpass.new(<coefficient>);
246 #
247 # EXAMPLE:
248 # var lp = aircraft.lowpass.new(1.5);
249 # print(lp.filter(10)); # prints 10
250 # print(lp.filter(0));
251 #
252 var lowpass = {
253 new: func(coeff) {
254 var m = { parents: [lowpass] };
255 m.coeff = coeff >= 0 ? coeff : die("aircraft.lowpass(): coefficient must be >= 0");
256 m.value = nil;
257 m.delta_sec_node = props.globals.getNode("/sim/time/delta-sec",1);
258 return m;
259 },
260 # filter(raw_value) -> push new value, returns filtered value
261 filter: func(v) {
262 me.filter = me._filter_;
263 me.value = v;
264 },
265 # get() -> returns filtered value
266 get: func {
267 me.value;
268 },
269 # set() -> sets new average and returns it
270 set: func(v) {
271 me.value = v;
272 },
273 _filter_: func(v) {
274 me.dt = me.delta_sec_node.getValue();
275 me.c = me.dt / (me.coeff + me.dt);
276 me.value = v * me.c + me.value * (1 - me.c);
277 },
278 };
279
280
281
282 # angular lowpass
283 # ==============================================================================
284 # same as above, but for angles. Filters sin/cos separately and calculates the
285 # angle again from them. This avoids unexpected jumps from 179.99 to -180 degree.
286 #
287 var angular_lowpass = {
288 new: func(coeff) {
289 var m = { parents: [angular_lowpass] };
290 m.sin = lowpass.new(coeff);
291 m.cos = lowpass.new(coeff);
292 m.value = nil;
293 return m;
294 },
295 filter: func(v) {
296 v *= D2R;
297 me.value = math.atan2(me.sin.filter(math.sin(v)), me.cos.filter(math.cos(v))) * R2D;
298 },
299 set: func(v) {
300 v *= D2R;
301 me.sin.set(math.sin(v));
302 me.cos.set(math.cos(v));
303 },
304 get: func {
305 me.value;
306 },
307 };
308
309
310
311 # data
312 # ==============================================================================
313 # class that loads and saves properties to aircraft-specific data files in
314 # ~/.fgfs/aircraft-data/ (Unix) or %APPDATA%\flightgear.org\aircraft-data\.
315 # There's no public constructor, as the only needed instance gets created
316 # by the system.
317 #
318 # SYNOPSIS:
319 # data.add(<properties>);
320 # data.save([<interval>])
321 #
322 # properties ... about any combination of property nodes (props.Node)
323 # or path name strings, or lists or hashes of them,
324 # lists of lists of them, etc.
325 # interval ... save in <interval> minutes intervals, or only once
326 # if 'nil' or empty (and again at reinit/exit)
327 #
328 # SIGNALS:
329 # /sim/signals/save ... set to 'true' right before saving. Can be used
330 # to update values that are to be saved
331 #
332 # EXAMPLE:
333 # var p = props.globals.getNode("/sim/model", 1);
334 # var vec = [p, p];
335 # var hash = {"foo": p, "bar": p};
336 #
337 # # add properties
338 # aircraft.data.add("/sim/fg-root", p, "/sim/fg-home");
339 # aircraft.data.add(p, vec, hash, "/sim/fg-root");
340 #
341 # # now save only once (and at exit/reinit, which is automatically done)
342 # aircraft.data.save();
343 #
344 # # or save now and every 30 sec (and at exit/reinit)
345 # aircraft.data.save(0.5);
346 #
347 var data = {
348 init: func {
349 me.path = getprop("/sim/fg-home") ~ "/aircraft-data/" ~ getprop("/sim/aircraft") ~ ".xml";
350 me.signalN = props.globals.getNode("/sim/signals/save", 1);
351 me.catalog = [];
352 me._timer = maketimer(60, me, me._save_);
353
354 setlistener("/sim/signals/reinit", func(n) {
355 if (n.getBoolValue() and getprop("/sim/startup/save-on-exit")) {
356 me._save_();
357 }
358 });
359 setlistener("/sim/signals/exit", func {
360 if (getprop("/sim/startup/save-on-exit")) {
361 me._save_();
362 }
363 });
364 return me;
365 },
366
367 load: func {
368 if (io.stat(me.path) != nil) {
369 logprint(LOG_INFO, "loading aircraft data from ", me.path);
370 io.read_properties(me.path, props.globals);
371 }
372 return me;
373 },
374
375 save: func(v = nil) {
376 if (v == nil) {
377 me._save_();
378 me._timer.stop();
379 } else {
380 me._timer.restart(60 * v);
381 }
382 return me;
383 },
384
385 _save_: func {
386 size(me.catalog) or return;
387 logprint(LOG_INFO, "saving aircraft data to ", me.path);
388 me.signalN.setBoolValue(1);
389 var data = props.Node.new();
390 foreach (var c; me.catalog) {
391 if (c[0] == `/`) {
392 c = substr(c, 1);
393 }
394 props.copy(props.globals.getNode(c, 1), data.getNode(c, 1));
395 }
396 io.write_properties(me.path, data);
397 },
398
399 add: func(p...) {
400 foreach (var n; props.nodeList(p)) {
401 append(me.catalog, n.getPath());
402 }
403 return me;
404 },
405 remove: func(p...) {
406 foreach (var n; props.nodeList(p)) {
407 var i = vecindex(me.catalog, n.getPath());
408 if (i != nil) {
409 me.catalog = subvec(me.catalog, 0, i) ~ subvec(me.catalog, i + 1);
410 }
411 }
412 return me;
413 },
414 };
415
416
417
418 # timer
419 # ==============================================================================
420 # class that implements timer that can be started, stopped, reset, and can
421 # have its value saved to the aircraft specific data file. Saving the value
422 # is done automatically by the aircraft.Data class.
423 #
424 # SYNOPSIS:
425 # timer.new(<property> [, <resolution:double> [, <save:bool>]])
426 #
427 # <property> ... property path or props.Node hash that holds the timer value
428 # <resolution> ... timer update resolution -- interval in seconds in which the
429 # timer property is updated while running (default: 1 s)
430 # <save> ... bool that defines whether the timer value should be saved
431 # and restored next time, as needed for Hobbs meters
432 # (default: 1)
433 #
434 # EXAMPLES:
435 # var hobbs_turbine = aircraft.timer.new("/sim/time/hobbs/turbine[0]", 60);
436 # hobbs_turbine.start();
437 #
438 # aircraft.timer.new("/sim/time/hobbs/battery", 60).start(); # anonymous timer
439 #
440 var timer = {
441 new: func(prop, res = 1, save = 1) {
442 var m = { parents: [timer] };
443 m.node = makeNode(prop);
444 if (m.node.getType() == "NONE")
445 m.node.setDoubleValue(0);
446
447 me.systimeN = props.globals.getNode("/sim/time/elapsed-sec", 1);
448 m.last_systime = nil;
449 m.interval = res;
450 m.loopid = 0;
451 m.running = 0;
452 m.reinitL = setlistener("/sim/signals/reinit", func(n) {
453 if (n.getValue()) {
454 m.stop();
455 m.total = m.node.getValue();
456 } else {
457 m.node.setDoubleValue(m.total);
458 }
459 });
460 if (save) {
461 data.add(m.node);
462 m.saveL = setlistener("/sim/signals/save", func m._save_());
463 } else {
464 m.saveL = nil;
465 }
466 return m;
467 },
468 del: func {
469 me.stop();
470 removelistener(me.reinitL);
471 if (me.saveL != nil)
472 removelistener(me.saveL);
473 },
474 start: func {
475 me.running and return;
476 me.last_systime = me.systimeN.getValue();
477 if (me.interval != nil)
478 me._loop_(me.loopid);
479 me.running = 1;
480 me;
481 },
482 stop: func {
483 me.running or return;
484 me.running = 0;
485 me.loopid += 1;
486 me._apply_();
487 me;
488 },
489 reset: func {
490 me.node.setDoubleValue(0);
491 me.last_systime = me.systimeN.getValue();
492 },
493 _apply_: func {
494 var sys = me.systimeN.getValue();
495 me.node.setDoubleValue(me.node.getValue() + sys - me.last_systime);
496 me.last_systime = sys;
497 },
498 _save_: func {
499 if (me.running)
500 me._apply_();
501 },
502 _loop_: func(id) {
503 id != me.loopid and return;
504 me._apply_();
505 settimer(func me._loop_(id), me.interval);
506 },
507 };
508
509
510
511 # livery
512 # =============================================================================
513 # Class that maintains livery XML files (see English Electric Lightning for an
514 # example). The last used livery is saved on exit and restored next time. Livery
515 # files are regular PropertyList XML files whose properties are copied to the
516 # main tree.
517 #
518 # SYNOPSIS:
519 # livery.init(<livery-dir> [, <name-path> [, <sort-path>]]);
520 #
521 # <livery-dir> ... directory with livery XML files, relative to $FG_ROOT
522 # <name-path> ... property path to the livery name in the livery files
523 # and the property tree (default: sim/model/livery/name)
524 # <sort-path> ... property path to the sort criterion (default: same as
525 # <name-path> -- that is: alphabetic sorting)
526 #
527 # EXAMPLE:
528 # aircraft.livery.init("Aircraft/Lightning/Models/Liveries",
529 # "sim/model/livery/variant",
530 # "sim/model/livery/index"); # optional
531 #
532 # aircraft.livery.dialog.toggle();
533 # aircraft.livery.select("OEBH");
534 # aircraft.livery.next();
535 #
536 var livery = {
537 init: func(dir, nameprop = "sim/model/livery/name", sortprop = nil) {
538 me.parents = [gui.OverlaySelector.new("Select Livery", dir, nameprop,
539 sortprop, "sim/model/livery/file")];
540 me.dialog = me.parents[0];
541 },
542 };
543
544
545
546 # livery_update
547 # =============================================================================
548 # Class for maintaining liveries in MP aircraft. It is used in Nasal code that's
549 # embedded in aircraft animation XML files, and checks in intervals whether the
550 # parent aircraft has changed livery, in which case it changes the livery
551 # in the remote aircraft accordingly. This class is a wrapper for overlay_update.
552 #
553 # SYNOPSIS:
554 # livery_update.new(<livery-dir> [, <interval:10> [, <func>]]);
555 #
556 # <livery-dir> ... directory with livery files, relative to $FG_ROOT
557 # <interval> ... checking interval in seconds (default: 10)
558 # <func> ... callback function that's called with the ./sim/model/livery/file
559 # contents as argument whenever the livery has changed. This can
560 # be used for post-processing.
561 #
562 # EXAMPLE:
563 # <nasal>
564 # <load>
565 # var livery_update = aircraft.livery_update.new(
566 # "Aircraft/R22/Models/Liveries", 30,
567 # func print("R22 livery update"));
568 # </load>
569 #
570 # <unload>
571 # livery_update.stop();
572 # </unload>
573 # </nasal>
574 #
575 var livery_update = {
576 new: func(liveriesdir, interval = 10.01, callback = nil) {
577 var m = { parents: [livery_update, overlay_update.new()] };
578 m.parents[1].add(liveriesdir, "sim/model/livery/file", callback);
579 m.parents[1].interval = interval;
580 return m;
581 },
582 stop: func {
583 me.parents[1].stop();
584 },
585 };
586
587
588
589 # overlay_update
590 # =============================================================================
591 # Class for maintaining overlays in MP aircraft. It is used in Nasal code that's
592 # embedded in aircraft animation XML files, and checks in intervals whether the
593 # parent aircraft has changed an overlay, in which case it copies the respective
594 # overlay to the aircraft's root directory.
595 #
596 # SYNOPSIS:
597 # livery_update.new();
598 # livery_update.add(<overlay-dir>, <property> [, <callback>]);
599 #
600 # <overlay-dir> ... directory with overlay files, relative to $FG_ROOT
601 # <property> ... MP property where the overlay file name can be found
602 # (usually one of the sim/multiplay/generic/string properties)
603 # <callback> ... callback function that's called with two arguments:
604 # the file name (without extension) and the overlay directory
605 #
606 # EXAMPLE:
607 # <nasal>
608 # <load>
609 # var update = aircraft.overlay_update.new();
610 # update.add("Aircraft/F4U/Models/Logos", "sim/multiplay/generic/string");
611 # </load>
612 #
613 # <unload>
614 # update.stop();
615 # </unload>
616 # </nasal>
617 #
618 var overlay_update = {
619 new: func {
620 var m = { parents: [overlay_update] };
621 m.root = cmdarg();
622 m.data = {};
623 m.interval = 10.01;
624 if (m.root.getName() == "multiplayer")
625 m._loop_();
626 return m;
627 },
628 add: func(path, prop, callback = nil) {
629 var path = path ~ '/';
630 me.data[path] = [me.root.initNode(prop, ""), "",
631 isfunc(callback) ? callback : func nil];
632 return me;
633 },
634 stop: func {
635 me._loop_ = func nil;
636 },
637 _loop_: func {
638 foreach (var path; keys(me.data)) {
639 var v = me.data[path];
640 var file = v[0].getValue();
641 if (file != v[1]) {
642 io.read_properties(path ~ file ~ ".xml", me.root);
643 v[2](v[1] = file, path);
644 }
645 }
646 settimer(func me._loop_(), me.interval);
647 },
648 };
649
650
651
652 # steering
653 # =============================================================================
654 # Class that implements differential braking depending on rudder position.
655 # Note that this overrides the controls.applyBrakes() wrapper. If you need
656 # your own version, then override it again after the steering.init() call.
657 #
658 # SYNOPSIS:
659 # steering.init([<property> [, <threshold>]]);
660 #
661 # <property> ... property path or props.Node hash that enables/disables
662 # brake steering (usually bound to the js trigger button)
663 # <threshold> ... defines range (+- threshold) around neutral rudder
664 # position in which both brakes are applied
665 #
666 # EXAMPLES:
667 # aircraft.steering.init("/controls/gear/steering", 0.2);
668 # aircraft.steering.init();
669 #
670 var steering = {
671 init: func(switch = "/controls/gear/brake-steering", threshold = 0.3) {
672 me.threshold = threshold;
673 me.switchN = makeNode(switch);
674 me.switchN.setBoolValue(me.switchN.getBoolValue());
675 me.leftN = props.globals.getNode("/controls/gear/brake-left", 1);
676 me.rightN = props.globals.getNode("/controls/gear/brake-right", 1);
677 me.rudderN = props.globals.getNode("/controls/flight/rudder", 1);
678 me.loopid = 0;
679
680 controls.applyBrakes = func(v, w = 0) {
681 if (w < 0)
682 steering.leftN.setValue(v);
683 elsif (w > 0)
684 steering.rightN.setValue(v);
685 else
686 steering.switchN.setValue(v);
687 }
688 setlistener(me.switchN, func(n) {
689 me.loopid += 1;
690 if (n.getValue())
691 me._loop_(me.loopid);
692 else
693 me.setbrakes(0, 0);
694 }, 1);
695 },
696 _loop_: func(id) {
697 id == me.loopid or return;
698 var rudder = me.rudderN.getValue();
699 if (rudder > me.threshold)
700 me.setbrakes(0, rudder);
701 elsif (rudder < -me.threshold)
702 me.setbrakes(-rudder, 0);
703 else
704 me.setbrakes(1, 1);
705
706 settimer(func me._loop_(id), 0);
707 },
708 setbrakes: func(left, right) {
709 me.leftN.setDoubleValue(left);
710 me.rightN.setDoubleValue(right);
711 },
712 };
713
714
715
716 # autotrim
717 # =============================================================================
718 # Singleton class that supports quick trimming and compensates for the lack
719 # of resistance/force feedback in most joysticks. Normally the pilot trims such
720 # that no real or artificially generated (by means of servo motors and spring
721 # preloading) forces act on the stick/yoke and it is in a comfortable position.
722 # This doesn't work well on computer joysticks.
723 #
724 # SYNOPSIS:
725 # autotrim.start(); # on key/button press
726 # autotrim.stop(); # on key/button release (mod-up)
727 #
728 # USAGE:
729 # (1) move the stick such that the aircraft is in an orientation that
730 # you want to trim for (forward flight, hover, ...)
731 # (2) press autotrim button and keep it pressed
732 # (3) move stick/yoke to neutral position (center)
733 # (4) release autotrim button
734 #
735 var autotrim = {
736 init: func {
737 me.elevator = me.Trim.new("elevator");
738 me.aileron = me.Trim.new("aileron");
739 me.rudder = me.Trim.new("rudder");
740 me.loopid = 0;
741 me.active = 0;
742 },
743 start: func {
744 me.active and return;
745 me.active = 1;
746 me.elevator.start();
747 me.aileron.start();
748 me.rudder.start();
749 me._loop_(me.loopid += 1);
750 },
751 stop: func {
752 me.active or return;
753 me.active = 0;
754 me.loopid += 1;
755 me.update();
756 },
757 _loop_: func(id) {
758 id == me.loopid or return;
759 me.update();
760 settimer(func me._loop_(id), 0);
761 },
762 update: func {
763 me.elevator.update();
764 me.aileron.update();
765 me.rudder.update();
766 },
767 Trim: {
768 new: func(name) {
769 var m = { parents: [autotrim.Trim] };
770 m.trimN = props.globals.getNode("/controls/flight/" ~ name ~ "-trim", 1);
771 m.ctrlN = props.globals.getNode("/controls/flight/" ~ name, 1);
772 return m;
773 },
774 start: func {
775 me.last = me.ctrlN.getValue();
776 },
777 update: func {
778 var v = me.ctrlN.getValue();
779 me.trimN.setDoubleValue(me.trimN.getValue() + me.last - v);
780 me.last = v;
781 },
782 },
783 };
784
785
786
787
788
789 # tyresmoke
790 # =============================================================================
791 # Provides a property which can be used to contol particles used to simulate tyre
792 # smoke on landing. Weight on wheels, vertical speed, ground speed, ground friction
793 # factor are taken into account. Tyre slip is simulated by low pass filters.
794 #
795 # Modifications to the model file are required.
796 #
797 # Generic XML particle files are available, but are not mandatory
798 # (see Hawker Seahawk for an example).
799 #
800 # SYNOPSIS:
801 # aircraft.tyresmoke.new(gear index [, auto = 0])
802 # gear index - the index of the gear to which the tyre smoke is attached
803 # auto - enable automatic update (recommended). defaults to 0 for backward compatibility.
804 # aircraft.tyresmoke.del()
805 # destructor.
806 # aircraft.tyresmoke.update()
807 # Runs the update. Not required if automatic updates are enabled.
808 #
809 # EXAMPLE:
810 # var tyresmoke_0 = aircraft.tyresmoke.new(0);
811 # tyresmoke_0.update();
812 #
813 # PARAMETERS:
814 #
815 # number: index of gear to be animated, i.e. "2" for /gear/gear[2]/...
816 #
817 # auto: 1 when tyresmoke should start on update loop. 0 when you're going
818 # to call the update method from one of your own loops.
819 #
820 # diff_norm: value adjusting the necessary percental change of roll-speed
821 # to trigger tyre smoke. Default value is 0.05. More realistic results can
822 # be achieved with significantly higher values (i.e. use 0.8).
823 #
824 # check_vspeed: 1 when tyre smoke should only be triggered when vspeed is negative
825 # (usually doesn't work for all gear, since vspeed=0.0 after the first gear touches
826 # ground). Use 0 to make tyre smoke independent of vspeed.
827 # Note: in reality, tyre smoke doesn't depend on vspeed, but only on acceleration
828 # and friction.
829 #
830 # rain_norm_trigger: threshold for deciding that there is enough standing water to
831 # calculate spray. This is compared against rain-norm.
832 #
833 var tyresmoke = {
834 new: func(number, auto = 0, diff_norm = 0.05, check_vspeed=1, rain_norm_trigger=0.2) {
835 var m = {
836 parents: [tyresmoke],
837 filtered_touchdown: 0
838 };
839 m.vertical_speed = (!check_vspeed) ? nil : props.globals.initNode("velocities/vertical-speed-fps");
840 m.diff_norm = diff_norm;
841 m.speed = props.globals.initNode("velocities/groundspeed-kt");
842 m.rain_node = props.globals.initNode("environment/metar/rain-norm");
843 m.rain_norm_trigger = rain_norm_trigger;
844 var gear = props.globals.getNode("gear/gear[" ~ number ~ "]/");
845 m.wow_node = gear.initNode("wow");
846 m.last_wow = m.wow_node.getValue();
847 m.tyresmoke = gear.initNode("tyre-smoke", 0, "BOOL");
848 m.friction_factor_node = gear.initNode("ground-friction-factor", 1);
849 m.sprayspeed = gear.initNode("sprayspeed-ms");
850 m.spray = gear.initNode("spray", 0, "BOOL");
851 m.spraydensity = gear.initNode("spray-density", 0, "DOUBLE");
852 m.auto = auto;
853 m.listener = nil;
854 m.lastwow=0;
855 m.active=0;
856
857 if (getprop("sim/flight-model") == "jsb") {
858 var wheel_speed = "fdm/jsbsim/gear/unit[" ~ number ~ "]/wheel-speed-fps";
859 m.rollspeed_node = props.globals.initNode(wheel_speed);
860 m.get_rollspeed = func m.rollspeed_node.getValue() * 0.3043;
861 } else {
862 m.rollspeed_node = gear.initNode("rollspeed-ms");
863 m.get_rollspeed = func m.rollspeed_node.getValue();
864 }
865
866 m.lp = aircraft.lowpass.new(2);
867 m.lpf_touchdown = aircraft.lowpass.new(0.15);
868 auto and m.update();
869 return m;
870 },
871 del: func {
872 if (me.listener != nil) {
873 removelistener(me.listener);
874 me.listener = nil;
875 }
876 me.auto = 0;
877 },
878 calc_spray_factor: func(groundspeed_kts)
879 {
880 # based on Figure 31(a)[1]; Variation of drag parameter with ground speed in water
881 # for dual tandem wheels without spray-drag alleviator curve fitted and normalized.
882 #
883 # My The logic here is that the spray will be a factor of the drag and using the
884 # curve from Figure 31(a) is at least based in reality, whereas previously
885 # a simple factor was used which tended to give spray at much too low groundspeeds.
886 #
887 # |
888 # |
889 # 1 | +-------------------------------------------------
890 # | __/
891 # | /
892 # | /
893 # | /
894 # | /
895 # | /
896 # | /
897 # | /
898 # | /
899 # | /
900 # | /
901 # | /
902 # | /
903 # | /
904 # | _/
905 # 0| __--
906 # +--------------------------------------------------------------------
907 # 0 20 40 60 80 100 120 140 160 180 200 220 240
908 #
909 #_______________________________________________________________________________
910 # ref: https://ntrs.nasa.gov/api/citations/19660021919/downloads/19660021919.pdf
911 #-------------------
912 # Curve fit: MMF Model: y = (a * b + c * x ^ d) / (b + x ^ d)
913 # Coefficient Data: a=0.03048 b=59175231 c=2.38119 d=5.08271
914 # Normalized by using max value 2.38105217250475
915
916 return ((0.03048 * 59175231 + 2.38119 * math.pow(groundspeed_kts, 5.08271))
917 / (59175231 + math.pow(groundspeed_kts, 5.08271)) / 2.38105217250475)
918 ;
919 },
920 update: func {
921 me.rollspeed = me.get_rollspeed();
922 me.vert_speed = (me.vertical_speed) != nil ? me.vertical_speed.getValue() : -999;
923 me.groundspeed_kts = me.speed.getValue();
924 me.friction_factor = me.friction_factor_node.getValue();
925 me.wow = me.wow_node.getValue();
926 me.rain = me.rain_node.getValue();
927
928 me.filtered_rollspeed = me.lp.filter(me.rollspeed);
929 me.rollspeed_diff = math.abs(me.rollspeed - me.filtered_rollspeed);
930 me.rollspeed_diff_norm = me.rollspeed_diff > 0 ? me.rollspeed_diff / me.rollspeed : 0;
931 me.spray_factor = me.calc_spray_factor(me.groundspeed_kts);
932
933 # touchdown
934 # - wow changed (previously false)
935 # - use a filter on touchdown and use this to determine if the smoke is active.
936 me.touchdown = 0;
937 if (me.wow != me.lastwow){
938 if (me.wow){
939 me.lpf_touchdown.set(math.abs(me.vert_speed));
940 }
941 else me.filtered_touchdown = me.lpf_touchdown.filter(0);
942 }
943 else me.filtered_touchdown = me.lpf_touchdown.filter(0);
944
945 # touchdown smoke when
946 # * recently touched down
947 # * rollspeed must be over the limit
948 # * friction must be over a limit (no idea why this is 0.7)
949 # * moving at ground speed > 50kts (not sure about this)
950 # * not raining
951 # possibly using ground speed is somewhat irrelevant - but I'm leaving that here
952 # as it may filter out unwanted smoke.
953 if (me.filtered_touchdown > 1.0
954 and me.rollspeed_diff_norm > me.diff_norm
955 and me.friction_factor > 0.7
956 and me.groundspeed_kts > 50
957 and me.rain <me.rain_norm_trigger) {
958 me.tyresmoke.setValue(1);
959 me.spray.setValue(0);
960 me.spraydensity.setValue(0);
961 me.active = 1;
962 } elsif (me.wow and me.rain >= me.rain_norm_trigger) {
963 me.tyresmoke.setValue(0);
964 me.spray.setValue(1);
965 me.sprayspeed.setValue(me.rollspeed * 6);
966 me.spraydensity.setValue(me.rain * me.spray_factor * me.groundspeed_kts);
967 me.active = 1;
968 } else {
969 me.active = 0;
970 me.tyresmoke.setValue(0);
971 me.spray.setValue(0);
972 me.sprayspeed.setValue(0);
973 me.spraydensity.setValue(0);
974 }
975 if (me.auto) {
976 if (me.active or me.wow) {
977 settimer(func me.update(), 0);
978 if (me.listener != nil) {
979 removelistener(me.listener);
980 me.listener = nil;
981 }
982 } elsif (me.listener == nil) {
983 me.listener = setlistener(me.wow_node, func me._wowchanged_(), 0, 0);
984 }
985 }
986 me.lastwow = me.wow;
987 },
988 _wowchanged_: func() {
989 if (me.wow_node.getValue()) {
990 me.lp.set(0);
991 me.update();
992 }
993 },
994 };
995
996
997 # tyresmoke_system
998 # =============================================================================
999 # Helper class to contain the tyresmoke objects for all the gears.
1000 # Will update automatically, nothing else needs to be done by the caller.
1001 #
1002 # SYNOPSIS:
1003 # aircraft.tyresmoke_system.new(<gear index 1>, <gear index 2>, ...)
1004 # <gear index> - the index of the gear to which the tyre smoke is attached
1005 # aircraft.tyresmoke_system.del()
1006 # destructor
1007 # EXAMPLE:
1008 # var tyresmoke_system = aircraft.tyresmoke_system.new(0, 1, 2, 3, 4);
1009
1010 var tyresmoke_system = {
1011 new: func {
1012 var m = { parents: [tyresmoke_system] };
1013 # preset array to proper size
1014 m.gears = [];
1015 setsize(m.gears, size(arg));
1016 for(var i = size(arg) - 1; i >= 0; i -= 1) {
1017 m.gears[i] = tyresmoke.new(arg[i], 1);
1018 }
1019 return m;
1020 },
1021 del: func {
1022 foreach(var gear; me.gears) {
1023 gear.del();
1024 }
1025 }
1026 };
1027
1028 # rain
1029 # =============================================================================
1030 # Provides a property which can be used to control rain. Can be used to turn
1031 # off rain in internal views, and or used with a texture on canopies etc.
1032 # The output is co-ordinated with system precipitation:
1033 #
1034 # /sim/model/rain/raining-norm rain intensity
1035 # /sim/model/rain/flow-mps drop flow speed [m/s]
1036 #
1037 # See Hawker Seahawk for an example.
1038 #
1039 # SYNOPSIS:
1040 # aircraft.rain.init();
1041 # aircraft.rain.update();
1042 #
1043 var rain = {
1044 init: func {
1045 me.elapsed_timeN = props.globals.getNode("sim/time/elapsed-sec");
1046 me.dtN = props.globals.getNode("sim/time/delta-sec");
1047
1048 me.enableN = props.globals.initNode("sim/rendering/precipitation-aircraft-enable", 0, "BOOL");
1049 me.precip_levelN = props.globals.initNode("environment/params/precipitation-level-ft", 0);
1050 me.altitudeN = props.globals.initNode("position/altitude-ft", 0);
1051 me.iasN = props.globals.initNode("velocities/airspeed-kt", 0);
1052 me.rainingN = props.globals.initNode("sim/model/rain/raining-norm", 0);
1053 me.flowN = props.globals.initNode("sim/model/rain/flow-mps", 0);
1054
1055 var canopyN = props.globals.initNode("gear/canopy/position-norm", 0);
1056 var thresholdN = props.globals.initNode("sim/model/rain/flow-threshold-kt", 15);
1057
1058 setlistener(canopyN, func(n) me.canopy = n.getValue(), 1, 0);
1059 setlistener(thresholdN, func(n) me.threshold = n.getValue(), 1);
1060 setlistener("sim/rendering/precipitation-gui-enable", func(n) me.enabled = n.getValue(), 1);
1061 setlistener("environment/metar/rain-norm", func(n) me.rain = n.getValue(), 1);
1062 setlistener("sim/current-view/internal", func(n) me.internal = n.getValue(), 1);
1063 },
1064 update: func {
1065 var altitude = me.altitudeN.getValue();
1066 var precip_level = me.precip_levelN.getValue();
1067
1068 if (me.enabled and me.internal and altitude < precip_level and me.canopy < 0.001) {
1069 var time = me.elapsed_timeN.getValue();
1070 var ias = me.iasN.getValue();
1071 var dt = me.dtN.getValue();
1072
1073 me.flowN.setDoubleValue(ias < me.threshold ? 0 : time * 0.5 + ias * NM2M * dt / 3600);
1074 me.rainingN.setDoubleValue(me.rain);
1075 if (me.enableN.getBoolValue())
1076 me.enableN.setBoolValue(0);
1077 } else {
1078 me.flowN.setDoubleValue(0);
1079 me.rainingN.setDoubleValue(0);
1080 if (me.enableN.getBoolValue() != 1)
1081 me.enableN.setBoolValue(1);
1082 }
1083 },
1084 };
1085
1086
1087
1088 # teleport
1089 # =============================================================================
1090 # Usage: aircraft.teleport(lat:48.3, lon:32.4, alt:5000);
1091 #
1092 var teleport = func(airport = "", runway = "", lat = -9999, lon = -9999, alt = 0,
1093 speed = 0, distance = 0, azimuth = 0, glideslope = 0, heading = 9999) {
1094 setprop("/sim/presets/airport-id", airport);
1095 setprop("/sim/presets/runway", runway);
1096 setprop("/sim/presets/parkpos", "");
1097 setprop("/sim/presets/latitude-deg", lat);
1098 setprop("/sim/presets/longitude-deg", lon);
1099 setprop("/sim/presets/altitude-ft", alt);
1100 setprop("/sim/presets/airspeed-kt", speed);
1101 setprop("/sim/presets/offset-distance-nm", distance);
1102 setprop("/sim/presets/offset-azimuth-deg", azimuth);
1103 setprop("/sim/presets/glideslope-deg", glideslope);
1104 setprop("/sim/presets/heading-deg", heading);
1105 fgcommand("reposition");
1106 }
1107
1108
1109
1110 # returns wind speed [kt] from given direction [deg]; useful for head-wind
1111 #
1112 var wind_speed_from = func(azimuth) {
1113 var dir = (getprop("/environment/wind-from-heading-deg") - azimuth) * D2R;
1114 return getprop("/environment/wind-speed-kt") * math.cos(dir);
1115 }
1116
1117
1118
1119 # returns true airspeed for given indicated airspeed [kt] and altitude [m]
1120 #
1121 var kias_to_ktas = func(kias, altitude) {
1122 var seapress = getprop("/environment/pressure-sea-level-inhg");
1123 var seatemp = getprop("/environment/temperature-sea-level-degc");
1124 var coralt_ft = altitude * M2FT + (29.92 - seapress) * 910;
1125 return kias * (1 + 0.00232848233 * (seatemp - 15))
1126 * (1.0025 + coralt_ft * (0.0000153
1127 - kias * (coralt_ft * 0.0000000000003 + 0.0000000045)
1128 + (0.0000119 * (math.exp(coralt_ft * 0.000016) - 1))));
1129 }
1130
1131
1132
1133 # HUD control class to handle both HUD implementations
1134 # ==============================================================================
1135 #
1136 var HUD = {
1137 init: func {
1138 me.vis1N = props.globals.getNode("/sim/hud/visibility[1]", 1);
1139 me.currcolN = props.globals.getNode("/sim/hud/current-color", 1);
1140 me.currentPathN = props.globals.getNode("/sim/hud/current-path", 1);
1141 me.hudN = props.globals.getNode("/sim/hud", 1);
1142 me.paletteN = props.globals.getNode("/sim/hud/palette", 1);
1143 me.brightnessN = props.globals.getNode("/sim/hud/color/brightness", 1);
1144 me.currentN = me.vis1N;
1145
1146 # keep compatibility with earlier version of FG - hud/path[1] is
1147 # the default Hud
1148 me.currentPathN.setIntValue(1);
1149 },
1150 cycle_color: func { # h-key
1151 if (!me.currentN.getBoolValue()) # if off, turn on
1152 return me.currentN.setBoolValue(1);
1153
1154 var i = me.currcolN.getValue() + 1; # if through, turn off
1155 if (i < 0 or i >= size(me.paletteN.getChildren("color"))) {
1156 me.currentN.setBoolValue(0);
1157 me.currcolN.setIntValue(0);
1158 } else { # otherwise change color
1159 me.currentN.setBoolValue(1);
1160 me.currcolN.setIntValue(i);
1161 }
1162 },
1163 cycle_brightness: func { # H-key
1164 me.is_active() or return;
1165 var br = me.brightnessN.getValue() - 0.2;
1166 me.brightnessN.setValue(br > 0.01 ? br : 1);
1167 },
1168 normal_type: func { # i-key
1169 me.currentPathN.setIntValue(1);
1170 },
1171 cycle_type: func { # I-key
1172 var i = me.currentPathN.getValue() + 1;
1173 if (i < 1 or i > size(me.hudN.getChildren("path"))) {
1174 # back to the start
1175 me.currentPathN.setIntValue(1);
1176 } else {
1177 me.currentPathN.setIntValue(i);
1178 }
1179 },
1180 is_active: func {
1181 me.vis1N.getValue();
1182 },
1183 };
1184
1185 # crossfeed_valve
1186 # =============================================================================
1187 # class that creates a fuel tank cross-feed valve. Designed for YASim aircraft;
1188 # JSBSim aircraft can simply use systems code within the FDM (see 747-400 for
1189 # an example).
1190 #
1191 # WARNING: this class requires the tank properties to be ready, so call new()
1192 # after the FDM is initialized.
1193 #
1194 # SYNOPSIS:
1195 # crossfeed_valve.new(<max_flow_rate>, <property>, <tank>, <tank>, ... );
1196 # crossfeed_valve.open(<update>);
1197 # crossfeed_valve.close(<update>);
1198 #
1199 # <max_flow_rate> ... maximum transfer rate between the tanks in lbs/sec
1200 # <property> ... property path to use as switch - pass nil to use no such switch
1201 # <tank> ... number of a tank to connect - can have unlimited number of tanks connected
1202 # <update> ... update switch property when opening/closing valve via Nasal - 0 or 1; by default, 1
1203 #
1204 #
1205 # EXAMPLES:
1206 # aircraft.crossfeed_valve.new(0.5, "/controls/fuel/x-feed", 0, 1, 2);
1207 #-------
1208 # var xfeed = aircraft.crossfeed_valve.new(1, nil, 0, 1);
1209 # xfeed.open();
1210 #
1211 var crossfeed_valve = {
1212 new: func(flow_rate, path) {
1213 var m = { parents: [crossfeed_valve] };
1214 m.valve_open = 0;
1215 m.interval = 0.5;
1216 m.loopid = -1;
1217 m.flow_rate = flow_rate;
1218 if (path != nil) {
1219 m.switch_node = props.globals.initNode(path, 0, "BOOL");
1220 setlistener(path, func(node) {
1221 if (node.getBoolValue()) m.open(0);
1222 else m.close(0);
1223 }, 1, 0);
1224 }
1225 m.tanks = [];
1226 for (var i = 0; i < size(arg); i += 1) {
1227 var tank = props.globals.getNode("consumables/fuel/tank[" ~ arg[i] ~ "]");
1228 if (tank.getChild("level-lbs") != nil) append(m.tanks, tank);
1229 }
1230 return m;
1231 },
1232 open: func(update_prop = 1) {
1233 if (me.valve_open == 1) return;
1234 if (update_prop and contains(me, "switch_node")) me.switch_node.setBoolValue(1);
1235 me.valve_open = 1;
1236 me.loopid += 1;
1237 settimer(func me._loop_(me.loopid), me.interval);
1238 },
1239 close: func(update_prop = 1) {
1240 if (update_prop and contains(me, "switch_node")) me.switch_node.setBoolValue(0);
1241 me.valve_open = 0;
1242 },
1243 _loop_: func(id) {
1244 if (id != me.loopid) return;
1245 var average_level = 0;
1246 var count = size(me.tanks);
1247 for (var i = 0; i < count; i += 1) {
1248 var level_node = me.tanks[i].getChild("level-lbs");
1249 average_level += level_node.getValue();
1250 }
1251 average_level /= size(me.tanks);
1252 var highest_diff = 0;
1253 for (var i = 0; i < count; i += 1) {
1254 var level = me.tanks[i].getChild("level-lbs").getValue();
1255 var diff = math.abs(average_level - level);
1256 if (diff > highest_diff) highest_diff = diff;
1257 }
1258 for (var i = 0; i < count; i += 1) {
1259 var level_node = me.tanks[i].getChild("level-lbs");
1260 var capacity = me.tanks[i].getChild("capacity-gal_us").getValue() * me.tanks[i].getChild("density-ppg").getValue();
1261 var diff = math.abs(average_level - level_node.getValue());
1262 var min_level = math.max(0, level_node.getValue() - me.flow_rate * diff / highest_diff);
1263 var max_level = math.min(capacity, level_node.getValue() + me.flow_rate * diff / highest_diff);
1264 var level = level_node.getValue() > average_level ? math.max(min_level, average_level) : math.min(max_level, average_level);
1265 level_node.setValue(level);
1266 }
1267 if (me.valve_open) settimer(func me._loop_(id), me.interval);
1268 }
1269 };
1270
1271 props.globals.initNode("/sim/time/elapsed-sec", 0);
1272 props.globals.initNode("/sim/time/delta-sec", 0);
1273 props.globals.initNode("/sim/time/delta-realtime-sec", 0.00000001);
1274
1275 HUD.init();
1276 data.init();
1277 autotrim.init();
1278
1279 ##### temporary hack to provide backward compatibility for /sim/auto-coordination
1280 ##### remove this code when all references to /sim/auto-coordination are gone
1281 var ac = props.globals.getNode("/sim/auto-coordination");
1282 if (ac != nil) {
1283 logprint(LOG_ALERT, "WARNING: using deprecated property "~
1284 "/sim/auto-coordination. Please change to /controls/flight/auto-coordination");
1285 ac.alias(props.globals.getNode("/controls/flight/auto-coordination", 1));
1286 }
1287 #### end of temporary hack for /sim/auto-coordination
1288
1289 if (!getprop("/sim/startup/restore-defaults")) {
1290 # load user-specific aircraft settings
1291 data.load();
1292 var n = props.globals.getNode("/sim/aircraft-data");
1293 if (n != nil) {
1294 foreach (var c; n.getChildren("path")) {
1295 if (c.getType() != "NONE")
1296 data.add(c.getValue());
1297 }
1298 }
1299 }