Howto:Duplicate and Clamp Properties

From FlightGear wiki
Jump to navigation Jump to search

Objective

Demonstrate how to duplicate existing properties, so that you can adapt them as needed (i.e. wrapping/clamping value ranges), without depending on the original property.

# save in $FG_ROOT/sync.nas

var debug_on = 1; # set to 0 if you want to disable the print statements

# create a new function which just registers a timer
# the timer will invoke the "sync" function after a delay
# of 1 sec

var interval_sec = 1.00; # sync properties at an interval of 1 sec
var run_sync =  func() settimer(sync, interval_sec);

var clamp = func(min,max) {
  return func(x) {
   if (x < min) return min;
   if (x > max) return max;
   return x;
  }
}

# list of properties that you want sync'ed (source => target)
# specify a "process" callback if you want the property to be further processed, i.e. clamped to a certain range
var properties = [
 
 { source: "/velocities/airspeed-kt", target: "/mossies/airspeed-kt", process: clamp(min:10,max:50)  },
 { source: "/velocities/airspeed-kt", target: "/hoorays/airspeed-kt", process: clamp(min:0 ,max:100) },

# add more lines/properties as needed here (copy/paste and customize)
# use the property tree browser to check if it's working!
];

# this is our main function which just goes through your "properties" list
# and which will copy each "source" property to the "target" property
# at the end it will call "run_sync" again to register the timer, so
# that the function will call itself again after another second has passed

var sync = func {
 if (debug_on) print("Syncing properties:");
 foreach(var property; properties) {
  var target_prop  = property.target;
  var source_value = getprop(property.source);
  var processed_value = property.process!=nil and property.process(source_value);
  if (debug_on) print("  Syncing: ", property.source, "(",source_value,") =>", target_prop, " Processed:", processed_value);
  setprop( target_prop, source_value );
 }
 run_sync();
}


# this will make sure that the sync() function will only
# get called after the FDM is fully up and running, i.e. initialized

_setlistener("/sim/signals/fdm-initialized",  run_sync);
if (debug_on) print("sync.nas loaded");