Hi fellow wiki editors!

To help newly registered users get more familiar with the wiki (and maybe older users too) there is now a {{Welcome to the wiki}} template. Have a look at it and feel free to add it to new users discussion pages (and perhaps your own).

I have tried to keep the template short, but meaningful. /Johan G

Difference between revisions of "Howto:Coding a simple Nasal Framework"

From FlightGear wiki
Jump to: navigation, search
m (Variables)
m (Classes as Containers for your Variables)
Line 13: Line 13:
 
== Classes as Containers for your Variables ==
 
== Classes as Containers for your Variables ==
 
{{FGCquote
 
{{FGCquote
   |reading up a little more on OO may help you generalize some of your code a little better - for example, it seems that your code is currently structured such that it only supports a single instance of your EFB ? Once you start using classes and objects, you can easily re-arrange your code to allow your captain/copilot to have independent instances of your EFB, so that they don't affect each other. In fact, you could theoretically have dozens of EFBs running concurrently. This may not seem useful or relevant to you at the moment, but it greatly simplifies coding in the long-term.<br/>
+
   |reading up a little more on OO (object-oriented programming) may help you generalize some of your code a little better - for example, it seems that your code is currently structured such that it only supports a single instance of your EFB ? Once you start using classes and objects, you can easily re-arrange your code to allow your captain/copilot to have independent instances of your EFB, so that they don't affect each other. In fact, you could theoretically have dozens of EFBs running concurrently. This may not seem useful or relevant to you at the moment, but it greatly simplifies coding in the long-term.<br/>
 
Gijs ND/PFD code had the same problem originally - but you will find that it is much easier to write generic code once you start using separate instances/variables for each "version" of your instrument (EFB).<br/>
 
Gijs ND/PFD code had the same problem originally - but you will find that it is much easier to write generic code once you start using separate instances/variables for each "version" of your instrument (EFB).<br/>
 
<br/>
 
<br/>
Line 27: Line 27:
 
<syntaxhighlight lang="nasal">
 
<syntaxhighlight lang="nasal">
 
var EFB = {
 
var EFB = {
 +
 
  # constructor (for making new EFB objects)
 
  # constructor (for making new EFB objects)
 
  new: func(name) {
 
  new: func(name) {
 +
 
  # create a new EFB object, inherited from EFB class
 
  # create a new EFB object, inherited from EFB class
 
  var m = {parents:[EFB] };
 
  var m = {parents:[EFB] };
 +
 
  # add a new field to the class named "name", assign a value to it
 
  # add a new field to the class named "name", assign a value to it
 +
 
  m.name = name;
 
  m.name = name;
  return m; # return the whole thing to the caller
+
  # here you can add other fields that shall be specific to the instance/object, e.g. the root property
 +
 +
# and finally return the new object to the caller
 +
return m;
 
  },
 
  },
 
  # define a method (class function) that can be called to print out the name of the EFB
 
  # define a method (class function) that can be called to print out the name of the EFB
Line 50: Line 57:
 
{{FGCquote
 
{{FGCquote
 
   |(You can use the Nasal console to test this)<br/>
 
   |(You can use the Nasal console to test this)<br/>
As you can see, your two EFBs will inherit from the same EFB class, but they will have their own private namespace - i.e. the "name" member in this case. It can be accessed via the "me" prefix.<br/>
+
As you can see, your two EFBs will inherit from the same EFB class, but they will have their own private namespace - i.e. the "name" member in this case. It can be accessed via the "me" prefix. And each instance (object) will have its own scope, referenced via the '''me''' keyword.<br/>
  
 
   |{{cite web |url=http://forum.flightgear.org/viewtopic.php?p=213105#p213105
 
   |{{cite web |url=http://forum.flightgear.org/viewtopic.php?p=213105#p213105

Revision as of 13:15, 22 June 2014

WIP.png Work in progress
This article or section will be worked on in the upcoming hours or days.
See history for the latest developments.

Objective

Illustrate the basic thought process required to come up with Nasal/Canvas code that is sufficiently generic to meet the following requirements

  • support multiple independent instances (e.g. PFDs or NDs)
  • be aircraft/use-case agnostic (e.g. work without hard-coded properties)
  • configurable without touching back-end code (e.g. via configuration hashes)
  • modular (use separate files for splitting things up)

We'll be using the PFD/ND code as an example here, and won't be using any complicated techniques.


Classes as Containers for your Variables

Cquote1.png reading up a little more on OO (object-oriented programming) may help you generalize some of your code a little better - for example, it seems that your code is currently structured such that it only supports a single instance of your EFB ? Once you start using classes and objects, you can easily re-arrange your code to allow your captain/copilot to have independent instances of your EFB, so that they don't affect each other. In fact, you could theoretically have dozens of EFBs running concurrently. This may not seem useful or relevant to you at the moment, but it greatly simplifies coding in the long-term.

Gijs ND/PFD code had the same problem originally - but you will find that it is much easier to write generic code once you start using separate instances/variables for each "version" of your instrument (EFB).

If you'd like to learn more about using classes and objects (instance variables) to accomplish this, see this little tutorial: Howto:Coding_a_simple_Nasal_Framework

Basically, the idea is to get rid of "global" variables, and instead use "instance" variables that are part of an outer scope (hash), such as:


— Hooray (Sat Jun 21). Re: 777 EFB: initial feedback.
(powered by Instant-Cquotes)
Cquote2.png
var EFB = {
 
 # constructor (for making new EFB objects)
 new: func(name) {

 # create a new EFB object, inherited from EFB class
 var m = {parents:[EFB] };

 # add a new field to the class named "name", assign a value to it

 m.name = name;
 # here you can add other fields that shall be specific to the instance/object, e.g. the root property
 
 # and finally return the new object to the caller
 return m; 
 },
 # define a method (class function) that can be called to print out the name of the EFB
 whoami: func() {
  print("EFB owner:", me.name );
 }
};

var CaptainEFB = EFB.new("captain");
var CopilotEFB = EFB.new("copilot");

CaptainEFB.whoami();
CopilotEFB.whoami();
Cquote1.png (You can use the Nasal console to test this)

As you can see, your two EFBs will inherit from the same EFB class, but they will have their own private namespace - i.e. the "name" member in this case. It can be accessed via the "me" prefix. And each instance (object) will have its own scope, referenced via the me keyword.


— Hooray (Sat Jun 21). Re: 777 EFB: initial feedback.
(powered by Instant-Cquotes)
Cquote2.png

Variables

Also see: http://forum.flightgear.org/viewtopic.php?f=71&t=23047#p209281 In order to support independent instances of each instrument, you need to use separate variables, so rather than having something like this at global scope:

var horizon = nil;
var markerBeacon = nil;
var markerBeaconText = nil;
var speedText = nil;
var machText = nil;
var altText = nil;
var selHdgText = nil;
var fdX = nil;
var fdY = nil;

You would instead use a hash, and populate it with your variables:

var PrimaryFlightDisplay= {
 new: func() { return {parents:[PrimaryFlightDisplay],}; },
 # set up fields
 horizon: nil,
 markerBeacon: nil,
 markerBeaconText: nil,
 speedText: nil,
 machText: nil,
 altText: nil,
 selHdgText: nil,
 fdX: nil,
 fdY:nil,
};

The same thing can be accomplished by doing something like this in your constructor, using a temporary object:

var PrimaryFlightDisplay= {
 new: func() {
  var m = {parents:[PrimaryFlightDisplay]}; 
  m.horizon = nil;
  m.markerBeacon = nil;
  m.markerBeaconText = nil;
  m.speedText = nil;
  m.machText = nil;
  m.altText = "Hello World"; 
  m.selHdgText = nil;
  m.fdX = nil;
  m.fdY = nil;
 
  return m;
 },
};

To create a new object, you would then simply have to call the .new() function:

 var myPFD = PrimaryFlightDisplay.new();
 print( myPDF.altText );

By using this method, you can easily create dozens of independent instances of your class:

 var PFDVector = [];
 forindex(var i=0;i<100;i+=1)
  append(PFDVector, PrimaryFlightDisplay.new() );

Initialization / Constructor

Once these changes are in place, you can easily initialize your members/fields using a single foreach() loop, i.e. instead of having something like this:

canvas.parsesvg(pfd, "Aircraft/747-400/Models/Cockpit/Instruments/PFD/PFD.svg", {'font-mapper': font_mapper});

curAlt1 = pfd.getElementById("curAlt1");
curAlt2 = pfd.getElementById("curAlt2");
curAlt3 = pfd.getElementById("curAlt3");
vsPointer = pfd.getElementById("vsPointer");
curAltBox = pfd.getElementById("curAltBox");
curSpd = pfd.getElementById("curSpd");
curSpdTen = pfd.getElementById("curSpdTen");
spdTrend = pfd.getElementById("spdTrend");

You could use this

var PrimaryFlightDisplay {
 new: func() {
 var m = {parents:[PrimaryFlightDisplay]};
 m.pdf = {};
 canvas.parsesvg(m.pfd, "Aircraft/747-400/Models/Cockpit/Instruments/PFD/PFD.svg", {'font-mapper': font_mapper});

 m.symbols = {};
 foreach(var symbol; ['curAlt1','curAlt2','curAlt3','vsPointer','curAltBox','curSpd','curSpdTen','curAlt1','spdTrend',])
  me.symbols[symbol] = m.getElementById(symbol);
}, # new()

} # PrimaryFlightDisplay

All the original foo=nil initialization can now be removed, this is 100% equivalent, and saves you tons of typing and time!

Note that it makes sense to group your elements according to their initialization requirements, i.e. anything that just needs getElementById() called would go into the same vector, while anything that requires getElementById().updateCenter() called, would get into another vector.

These tips alone will reduce the code required in PFD.nas by about 150 lines.

Dealing with Properties

The next complication is dealing with instrument-specific properties. Typically, code will have lots of getprop()/setprop() equivalent calls in many places. These need to be encapsulated, i.e. you don't want to use setprop/getprop (or prop.nas) directly for any properties that are specific to the instrument, otherwise your code would fail once several instances of it are active at the same time, because their property access may be competing/conflicting, such as overwriting properties.

One simple solution for this is to have your own setprop/getprop equivalent, as part of your class:

var PrimaryFlightDisplay = {

 set: func(property, value) {
 },

 get: func(property, default) {
 },
};

Your methods would then never use setprop/getprop directly, but instead use the set/get methods, by calling me.get() or me.set() respectively. The next step is identifying property that are instance-specific, i.e. that must not be shared with other instruments. One convenient way to accomplish this is using a numbered index for each instance, such as: /instrumentation/pfd[0], /instrumentation/pfd[1], /instrumentation/pfd[2] etc.

This would then be the place for your instance-specific properties.

Moving huge conditionals into hash functions

The next problem we want to tackle is getting rid of huge conditional blocks inside the update() method: [1]

if(abs(deflection) < 0.5) { # need to verify 0.5
                locPtr.setTranslation(deflection*300,0);
                risingRwyPtr.setTranslation(deflection*300,0);
                locScaleExp.show();
                locScale.hide();
            } else {
                locPtr.setTranslation(deflection*150,0);
                risingRwyPtr.setTranslation(deflection*150,0);
                locScaleExp.hide();
                locScale.show();
            }

Such conditionals can be usually spit into:

  • condition (predicate)
  • body if true
  • body if false

Configuration

Note  Discuss config hashes

Modularization

Note  Discuss io.include() and io.load_nasal() for moving declarative config hashes out of *.nas files


Note
F-JJTH's gpsmap196 GUI dialog showing the panel page

This is currently being worked on by F-JJTH & Hooray as part of working on Garmin GPSMap 196

Styling