| 1 |
################################################################################ |
| 2 |
## MapStructure mapping/charting framework for Nasal/Canvas, by Philosopher |
| 3 |
## See: http://wiki.flightgear.org/MapStructure |
| 4 |
############################################################################### |
| 5 |
|
| 6 |
|
| 7 |
####### |
| 8 |
## Dev Notes: |
| 9 |
## |
| 10 |
## - consider adding two types of SymbolLayers (sub-classes): Static (fixed positions, navaids/fixes) Dynamic (frequently updated, TFC/WXR, regardless of aircraft position) |
| 11 |
## - FLT should be managed by aircraftpos.controller probably (interestign corner case actually) |
| 12 |
## - consider adding an Overlay, i.e. for things like compass rose, lat/lon coordinate grid, but also tiled map data fetched on line |
| 13 |
## - consider patching svg.nas to allow elements to be styled via the options hash by rewriting attributes, could even support animations that way |
| 14 |
## - style handling/defaults should be moved to symbol files probably |
| 15 |
## - consider pre-populating layer environments via bind() by providing APIs and fields for sane defaults: |
| 16 |
## - parents |
| 17 |
## - __self__ |
| 18 |
## - del (managing all listeners and timers) |
| 19 |
## - searchCmd -> filtering |
| 20 |
## |
| 21 |
## APIs to be wrapped for each layer: |
| 22 |
## logprint(), die(), debug.bt(), benchmark() |
| 23 |
|
| 24 |
var _MP_dbg_lvl = LOG_DEBUG; |
| 25 |
#var _MP_dbg_lvl = DEV_ALERT; |
| 26 |
|
| 27 |
var makedie = func(prefix) func(msg) globals.die(prefix~" "~msg); |
| 28 |
|
| 29 |
var __die = makedie("MapStructure"); |
| 30 |
|
| 31 |
## |
| 32 |
# Try to call a method on an object with no arguments. Should |
| 33 |
# work for both ghosts and hashes; catches the error only when |
| 34 |
# the method doesn't exist -- errors raised during the call |
| 35 |
# are re-thrown. |
| 36 |
# |
| 37 |
var try_aux_method = func(obj, method_name) { |
| 38 |
var name = "<test%"~id(caller(0)[0])~">"; |
| 39 |
call(compile("obj."~method_name~"()", name), nil, var err=[]); # try... |
| 40 |
#debug.dump(err); |
| 41 |
if (size(err)) # ... and either leave caght or rethrow |
| 42 |
if (err[1] != name) |
| 43 |
die(err[0]); |
| 44 |
} |
| 45 |
|
| 46 |
## |
| 47 |
# Combine a specific hash with a default hash, e.g. for |
| 48 |
# options/df_options and style/df_style in a SymbolLayer. |
| 49 |
# |
| 50 |
var default_hash = func(opt, df) { |
| 51 |
if (opt != nil and typeof(opt)=='hash') { |
| 52 |
if (df != nil and opt != df and !isa(opt, df)) { |
| 53 |
if (contains(opt, "parents")) |
| 54 |
opt.parents ~= [df]; |
| 55 |
else |
| 56 |
opt.parents = [df]; |
| 57 |
} |
| 58 |
return opt; |
| 59 |
} else return df; |
| 60 |
} |
| 61 |
|
| 62 |
## |
| 63 |
# to be used for prototyping, performance & stress testing (especially with multiple instance driven by AI traffic) |
| 64 |
# |
| 65 |
|
| 66 |
var MapStructure_selfTest = func() { |
| 67 |
var temp = {}; |
| 68 |
temp.dlg = canvas.Window.new([600,400],"dialog"); |
| 69 |
temp.canvas = temp.dlg.createCanvas().setColorBackground(1,1,1,0.5); |
| 70 |
temp.root = temp.canvas.createGroup(); |
| 71 |
var TestMap = temp.root.createChild("map"); |
| 72 |
TestMap.setController("Aircraft position"); |
| 73 |
TestMap.setRange(25); # TODO: implement zooming/panning via mouse/wheel here, for lack of buttons :-/ |
| 74 |
TestMap.setTranslation( |
| 75 |
temp.canvas.get("view[0]")/2, |
| 76 |
temp.canvas.get("view[1]")/2 |
| 77 |
); |
| 78 |
var r = func(name,vis=1,zindex=nil) return caller(0)[0]; |
| 79 |
# TODO: we'll need some z-indexing here, right now it's just random |
| 80 |
# TODO: use foreach/keys to show all layers in this case by traversing SymbolLayer.registry direclty ? |
| 81 |
# maybe encode implicit z-indexing for each lcontroller ctor call ? - i.e. preferred above/below order ? |
| 82 |
foreach(var type; [r('TFC',0),r('APT'),r('DME'),r('VOR'),r('NDB'),r('FIX',0),r('RTE'),r('WPT'),r('FLT'),r('WXR'),r('APS'), ] ) |
| 83 |
TestMap.addLayer(factory: canvas.SymbolLayer, type_arg: type.name, |
| 84 |
visible: type.vis, priority: type.zindex, |
| 85 |
); |
| 86 |
foreach(var type; [ r('OSM') ]) { |
| 87 |
TestMap.addLayer(factory: canvas.OverlayLayer, type_arg: type.name, |
| 88 |
visible: type.vis, priority: type.zindex, |
| 89 |
style: Styles.get(type.name), |
| 90 |
options: Options.get(type.name) ); |
| 91 |
} |
| 92 |
}; # MapStructure_selfTest |
| 93 |
|
| 94 |
|
| 95 |
## |
| 96 |
# wrapper for each cached element: keeps the canvas and |
| 97 |
# texture map coordinates for the corresponding raster image. |
| 98 |
# |
| 99 |
var CachedElement = { |
| 100 |
new: func(canvas_path, name, source, size, offset) { |
| 101 |
var m = {parents:[CachedElement] }; |
| 102 |
if (isa(canvas_path, canvas.Canvas)) { |
| 103 |
canvas_path = canvas_path.getPath(); |
| 104 |
} |
| 105 |
m.canvas_src = canvas_path; |
| 106 |
m.name = name; |
| 107 |
m.source = source; |
| 108 |
m.size = size; |
| 109 |
m.offset = offset; |
| 110 |
return m; |
| 111 |
}, |
| 112 |
|
| 113 |
render: func(group, trans0=0, trans1=0) { |
| 114 |
# create a raster image child in the render target/group |
| 115 |
var n = group.createChild("image", me.name) |
| 116 |
.setFile(me.canvas_src) |
| 117 |
.setSourceRect(me.source, 0) |
| 118 |
.setSize(me.size) |
| 119 |
.setTranslation(trans0,trans1); |
| 120 |
n.createTransform().setTranslation(me.offset); |
| 121 |
return n; |
| 122 |
}, |
| 123 |
}; # of CachedElement |
| 124 |
|
| 125 |
var SymbolCache = { |
| 126 |
# We can draw symbols either with left/top, centered, |
| 127 |
# or right/bottom alignment. Specify two in a vector |
| 128 |
# to mix and match, e.g. left/centered would be |
| 129 |
# [SymbolCache.DRAW_LEFT_TOP,SymbolCache.DRAW_CENTERED] |
| 130 |
DRAW_LEFT_TOP: 0.0, |
| 131 |
DRAW_CENTERED: 0.5, |
| 132 |
DRAW_RIGHT_BOTTOM: 1.0, |
| 133 |
new: func(dim...) { |
| 134 |
var m = { parents:[SymbolCache] }; |
| 135 |
# to keep track of the next free caching spot (in px) |
| 136 |
m.next_free = [0, 0]; |
| 137 |
# to store each type of symbol |
| 138 |
m.dict = {}; |
| 139 |
if (size(dim) == 1 and typeof(dim[0]) == 'vector') |
| 140 |
dim = dim[0]; |
| 141 |
# Two sizes: canvas and symbol |
| 142 |
if (size(dim) == 2) { |
| 143 |
var canvas_x = var canvas_y = dim[0]; |
| 144 |
var image_x = var image_y = dim[1]; |
| 145 |
# Two widths (canvas and symbol) and then height/width ratio |
| 146 |
} else if (size(dim) == 3) { |
| 147 |
var (canvas_x,image_x,ratio) = dim; |
| 148 |
var canvas_y = canvas_x * ratio; |
| 149 |
var image_y = image_x * ratio; |
| 150 |
# Explicit canvas and symbol widths/heights |
| 151 |
} else if (size(dim) == 4) { |
| 152 |
var (canvas_x,canvas_y,image_x,image_y) = dim; |
| 153 |
} |
| 154 |
m.canvas_sz = [canvas_x, canvas_y]; |
| 155 |
m.image_sz = [image_x, image_y]; |
| 156 |
|
| 157 |
# allocate a canvas |
| 158 |
m.canvas_texture = canvas.new( { |
| 159 |
"name": "SymbolCache"~canvas_x~'x'~canvas_y, |
| 160 |
"size": m.canvas_sz, |
| 161 |
"view": m.canvas_sz, |
| 162 |
"mipmapping": 1 |
| 163 |
}); |
| 164 |
m.canvas_texture.setColorBackground(0, 0, 0, 0); #rgba |
| 165 |
# add a placement |
| 166 |
m.canvas_texture.addPlacement( {"type": "ref"} ); |
| 167 |
|
| 168 |
m.path = m.canvas_texture.getPath(); |
| 169 |
m.root = m.canvas_texture.createGroup("entries"); |
| 170 |
|
| 171 |
# TODO: register a reset/re-init listener to optionally purge/rebuild the cache ? |
| 172 |
|
| 173 |
return m; |
| 174 |
}, |
| 175 |
## |
| 176 |
# Add a cached symbol based on a drawing callback. |
| 177 |
# @note this assumes that the object added by callback |
| 178 |
# fits into the dimensions provided to the constructor, |
| 179 |
# and any larger dimensionalities are liable to be cut off. |
| 180 |
# |
| 181 |
add: func(name, callback, draw_mode=0) { |
| 182 |
if (typeof(draw_mode) == 'scalar') |
| 183 |
var draw_mode0 = var draw_mode1 = draw_mode; |
| 184 |
else var (draw_mode0,draw_mode1) = draw_mode; |
| 185 |
|
| 186 |
# get canvas texture that we use as cache |
| 187 |
# get next free spot in texture (column/row) |
| 188 |
# run the draw callback and render into a new group |
| 189 |
var gr = me.root.createChild("group",name); |
| 190 |
# draw the symbol into the group |
| 191 |
callback(gr); |
| 192 |
|
| 193 |
gr.update(); # if we need sane output from getTransformedBounds() |
| 194 |
#debug.dump ( gr.getTransformedBounds() ); |
| 195 |
gr.setTranslation( me.next_free[0] + me.image_sz[0]*draw_mode0, |
| 196 |
me.next_free[1] + me.image_sz[1]*draw_mode1); |
| 197 |
|
| 198 |
# get assumed the bounding box, i.e. coordinates for texture map |
| 199 |
var coords = me.next_free~me.next_free; |
| 200 |
foreach (var i; [0,1]) |
| 201 |
coords[i+1] += me.image_sz[i]; |
| 202 |
foreach (var i; [0,1]) |
| 203 |
coords[i*2+1] = me.canvas_sz[i] - coords[i*2+1]; |
| 204 |
# get the offset we used to position correctly in the bounds of the canvas |
| 205 |
var offset = [-me.image_sz[0]*draw_mode0, -me.image_sz[1]*draw_mode1]; |
| 206 |
|
| 207 |
# update next free position in cache (column/row) |
| 208 |
me.next_free[0] += me.image_sz[0]; |
| 209 |
if (me.next_free[0] >= me.canvas_sz[0]) |
| 210 |
{ me.next_free[0] = 0; me.next_free[1] += me.image_sz[1] } |
| 211 |
if (me.next_free[1] >= me.canvas_sz[1]) |
| 212 |
__die("SymbolCache: ran out of space after adding '"~name~"'"); |
| 213 |
|
| 214 |
if (contains(me.dict, name)) print("MapStructure/SymbolCache Warning: Overwriting existing cache entry named:", name); |
| 215 |
|
| 216 |
# store texture map coordinates in lookup map using the name as identifier |
| 217 |
return me.dict[name] = CachedElement.new( |
| 218 |
canvas_path: me.path, |
| 219 |
name: name, |
| 220 |
source: coords, |
| 221 |
size:me.image_sz, |
| 222 |
offset: offset, |
| 223 |
); |
| 224 |
}, # add() |
| 225 |
get: func(name) { |
| 226 |
return me.dict[name]; |
| 227 |
}, # get() |
| 228 |
}; |
| 229 |
|
| 230 |
# Excerpt from gen module |
| 231 |
var denied_symbols = [ |
| 232 |
"", "func", "if", "else", "var", |
| 233 |
"elsif", "foreach", "for", |
| 234 |
"forindex", "while", "nil", |
| 235 |
"return", "break", "continue", |
| 236 |
]; |
| 237 |
var issym = func(string) { |
| 238 |
foreach (var d; denied_symbols) |
| 239 |
if (string == d) return 0; |
| 240 |
var sz = size(string); |
| 241 |
var s = string[0]; |
| 242 |
if ((s < `a` or s > `z`) and |
| 243 |
(s < `A` or s > `Z`) and |
| 244 |
(s != `_`)) return 0; |
| 245 |
for (var i=1; i<sz; i+=1) |
| 246 |
if (((s=string[i]) != `_`) and |
| 247 |
(s < `a` or s > `z`) and |
| 248 |
(s < `A` or s > `Z`) and |
| 249 |
(s < `0` or s > `9`)) return 0; |
| 250 |
return 1; |
| 251 |
}; |
| 252 |
var internsymbol = func(symbol) { |
| 253 |
#assert("argument not a symbol", issym, symbol); |
| 254 |
if (!issym(symbol)) die("argument not a symbol"); |
| 255 |
var get_interned = compile(""" |
| 256 |
keys({"~symbol~":})[0] |
| 257 |
"""); |
| 258 |
return get_interned(); |
| 259 |
}; |
| 260 |
var tryintern = func(symbol) issym(symbol) ? internsymbol(symbol) : symbol; |
| 261 |
|
| 262 |
# End excerpt |
| 263 |
|
| 264 |
# Helpers for below |
| 265 |
var unescape = func(s) string.replace(s~"", "'", "\\'"); |
| 266 |
var hashdup = func(_,rkeys=nil) { |
| 267 |
var h={}; var k=rkeys!=nil?rkeys:members(_); |
| 268 |
foreach (var k;k) h[tryintern(k)]=member(_,k); h |
| 269 |
} |
| 270 |
var opt_member = func(h,k) { |
| 271 |
if (contains(h, k)) return h[k]; |
| 272 |
if (contains(h, "parents")) { |
| 273 |
var _=h.parents; |
| 274 |
for (var i=0;i<size(_);i+=1){ |
| 275 |
var v = opt_member(_[i], k); |
| 276 |
if (v != nil) return v; |
| 277 |
} |
| 278 |
} |
| 279 |
return nil; |
| 280 |
} |
| 281 |
var member = func(h,k) { |
| 282 |
if (contains(h, k)) return h[k]; |
| 283 |
if (contains(h, "parents")) { |
| 284 |
var _=h.parents; |
| 285 |
for (var i=0;i<size(_);i+=1) |
| 286 |
if (contains(_[i], k)) return _[i][k]; |
| 287 |
elsif (contains(_[i], "parents") and size(_[i].parents)) |
| 288 |
{_=h.parents~_[i+1:];i=0} |
| 289 |
} |
| 290 |
die("member not found: '"~unescape(k)~"'"); |
| 291 |
} |
| 292 |
var _in = func(vec,k) { foreach (var _;vec) if(_==k)return 1; 0; } |
| 293 |
var members = func(h,vec=nil) { |
| 294 |
if (vec == nil) vec = []; |
| 295 |
foreach (var k; keys(h)) |
| 296 |
if (k == "parents") |
| 297 |
foreach (var p; h[k]) |
| 298 |
members(p,vec); |
| 299 |
elsif (!_in(vec,k)) |
| 300 |
append(vec, k); |
| 301 |
return vec; |
| 302 |
} |
| 303 |
var serialize = func(m,others=nil) { |
| 304 |
var t = typeof(m); |
| 305 |
if (t == 'scalar') |
| 306 |
if (num(m) != nil) |
| 307 |
return m~""; |
| 308 |
else return "'" ~ unescape(m) ~ "'"; |
| 309 |
if (others == nil) others = {}; |
| 310 |
var i = id(m); |
| 311 |
if (contains(others, i)) return "..."; |
| 312 |
others[i] = nil; |
| 313 |
if (t == 'vector') { |
| 314 |
var ret = "["; |
| 315 |
foreach (var l; m) { |
| 316 |
if (ret != "[") ret ~= ","; |
| 317 |
ret ~= serialize(l,others); |
| 318 |
} |
| 319 |
return ret~"]"; |
| 320 |
} else die("type not supported for style serialization: '"~t~"'"); |
| 321 |
} |
| 322 |
|
| 323 |
# Drawing functions have the form: |
| 324 |
# func(group) { group.createChild(...).set<Option>(<option>); ... } |
| 325 |
# The style is passed as (essentially) their local namespace/variables, |
| 326 |
# while the group is a regular argument. |
| 327 |
var call_draw = func(draw, style, arg=nil, relevant_keys=nil) { |
| 328 |
return call(draw, arg, nil, hashdup(style,relevant_keys)); |
| 329 |
} |
| 330 |
|
| 331 |
# Serialize a style into a string. |
| 332 |
var style_string = func(style, relevant_keys=nil) { |
| 333 |
if (relevant_keys == nil) relevant_keys = members(style); |
| 334 |
relevant_keys = sort(relevant_keys, cmp); |
| 335 |
var str = ""; |
| 336 |
foreach (var k; relevant_keys) { |
| 337 |
var m = member(style,k); |
| 338 |
if (m == nil) continue; |
| 339 |
if (str) str ~= ";"; |
| 340 |
str ~= k ~ ":"; |
| 341 |
str ~= serialize(m); |
| 342 |
} |
| 343 |
return str; |
| 344 |
} |
| 345 |
|
| 346 |
## |
| 347 |
# A class to mix styling and caching. Using the above helpers it |
| 348 |
# serializes style hashes. |
| 349 |
# |
| 350 |
var StyleableCacheable = { |
| 351 |
## |
| 352 |
# Construct an object. |
| 353 |
# @param name Prefix to use for entries in the cache |
| 354 |
# @param draw_func Function for the cache that will draw the |
| 355 |
# symbol onto a group using the style parameters. |
| 356 |
# @param cache The #SymbolCache to use for these symbols. |
| 357 |
# @param draw_mode See #SymbolCache |
| 358 |
# @param relevant_keys A list of keys for the style used by the |
| 359 |
# draw_func. Although it defaults to all |
| 360 |
# available keys, it is highly recommended |
| 361 |
# that it be specified. |
| 362 |
# |
| 363 |
new: func(name, draw_func, cache, draw_mode=0, relevant_keys=nil) { |
| 364 |
return { |
| 365 |
parents: [StyleableCacheable], |
| 366 |
_name: name, |
| 367 |
_draw_func: draw_func, |
| 368 |
_cache: cache, |
| 369 |
_draw_mode: draw_mode, |
| 370 |
relevant_keys: relevant_keys, |
| 371 |
}; |
| 372 |
}, |
| 373 |
# Note: configuration like active/inactive needs |
| 374 |
# to also use the passed style hash, unless it is |
| 375 |
# chosen not to cache symbols that are, e.g., active. |
| 376 |
request: func(style) { |
| 377 |
var s = style_string(style, me.relevant_keys); |
| 378 |
#debug.dump(style, s); |
| 379 |
var s1 = me._name~s; |
| 380 |
var c = me._cache.get(s1); |
| 381 |
if (c != nil) return c; |
| 382 |
return me.draw(style,s1); |
| 383 |
}, |
| 384 |
render: func(element, style) { |
| 385 |
var c = me.request(style); |
| 386 |
c.render(element); |
| 387 |
}, |
| 388 |
draw: func(style,s1) { |
| 389 |
var fn = func call_draw(me._draw_func, style, arg, me.relevant_keys); |
| 390 |
me._cache.add(s1, fn, me._draw_mode); |
| 391 |
}, |
| 392 |
}; |
| 393 |
|
| 394 |
## |
| 395 |
# A base class for Symbols placed on a map. |
| 396 |
# |
| 397 |
# Note: for the derived objects, the element is stored as obj.element. |
| 398 |
# This is also part of the object's parents vector, which allows |
| 399 |
# callers to use obj.setVisible() et al. However, for code that |
| 400 |
# manipulates the element's path (if it is a Canvas Path), it is best |
| 401 |
# to use obj.element.addSegmentGeo() et al. for consistency. |
| 402 |
# |
| 403 |
var Symbol = { |
| 404 |
# Static/singleton: |
| 405 |
registry: {}, |
| 406 |
add: func(type, class) |
| 407 |
me.registry[type] = class, |
| 408 |
get: func(type) |
| 409 |
if ((var class = me.registry[type]) == nil) |
| 410 |
__die("Symbol.get():unknown type '"~type~"'"); |
| 411 |
else return class, |
| 412 |
# Calls corresonding symbol constructor |
| 413 |
# @param group #Canvas.Group to place this on. |
| 414 |
# @param layer The #SymbolLayer this is a child of. |
| 415 |
new: func(type, group, layer, arg...) { |
| 416 |
var ret = call((var class = me.get(type)).new, [group, layer]~arg, class); |
| 417 |
ret.element.set("symbol-type", type); |
| 418 |
return ret; |
| 419 |
}, |
| 420 |
# Private constructor: |
| 421 |
_new: func(m) { |
| 422 |
m.style = m.layer.style; |
| 423 |
m.options = m.layer.options; |
| 424 |
if (m.controller != nil) { |
| 425 |
temp = m.controller.new(m,m.model); |
| 426 |
if (temp != nil) |
| 427 |
m.controller = temp; |
| 428 |
} |
| 429 |
else __die("Symbol._new(): default controller not found"); |
| 430 |
}, |
| 431 |
# Non-static: |
| 432 |
df_controller: nil, # default controller -- Symbol.Controller by default, see below |
| 433 |
# Update the drawing of this object (position and others). |
| 434 |
update: func() |
| 435 |
__die("Abstract Symbol.update(): not implemented for this symbol type!"), |
| 436 |
draw: func() , |
| 437 |
del: func() { |
| 438 |
if (me.controller != nil) |
| 439 |
me.controller.del(me, me.model); |
| 440 |
try_aux_method(me.model, "del"); |
| 441 |
}, |
| 442 |
|
| 443 |
# Add a text element with styling |
| 444 |
newText: func(text=nil, color=nil) { |
| 445 |
var t = me.element.createChild("text") |
| 446 |
.setDrawMode( canvas.Text.TEXT ) |
| 447 |
.setText(text) |
| 448 |
.setFont(me.layer.style.font) |
| 449 |
.setFontSize(me.layer.style.font_size); |
| 450 |
if (color != nil) |
| 451 |
t.setColor(color); |
| 452 |
return t; |
| 453 |
}, |
| 454 |
# Helper method that can be used to create a formatted String using |
| 455 |
# values extracted from the current model. |
| 456 |
# |
| 457 |
# SYNOPSIS: |
| 458 |
# |
| 459 |
# symbol.formattedString(format, model_property_names) |
| 460 |
# |
| 461 |
# Arguments: |
| 462 |
# - format: string |
| 463 |
# - model_property_names: a vector of strings representing the model |
| 464 |
# property names to be used as arguments |
| 465 |
# |
| 466 |
# EXAMPLE: |
| 467 |
# |
| 468 |
# var label = waypoint.formattedString('Waypoint %s: lat %.4f, lng %.4f', [model.id, model.lat, model.lon]); |
| 469 |
formattedString: func(frmt, model_props){ |
| 470 |
if(me.model == nil) return frmt; |
| 471 |
var args = []; |
| 472 |
foreach(var prop; model_props){ |
| 473 |
if(contains(me.model, prop)){ |
| 474 |
var val = me.model[prop]; |
| 475 |
var tp = typeof(val); |
| 476 |
if(tp != 'scalar'){ |
| 477 |
val = ''; |
| 478 |
#logprint(LOG_WARN, "formattedString: invalid type for "~prop~" ("Â ~ tp ~ ")"); |
| 479 |
} else { |
| 480 |
append(args, val); |
| 481 |
} |
| 482 |
} |
| 483 |
} |
| 484 |
return call(sprintf, [frmt] ~ args); |
| 485 |
}, |
| 486 |
|
| 487 |
# Wrapper method for accessing options. It allows to pass a default value |
| 488 |
# if the requested option is not defined. |
| 489 |
# |
| 490 |
# EXAMPLE: |
| 491 |
# var ok = (contains(me.options, 'enabled') ? me.options.enabled : 0); |
| 492 |
# var ok = me.getOption('enabled', 0); |
| 493 |
getOption: func(name, default = nil){ |
| 494 |
var opt = me.options; |
| 495 |
if(opt == nil) |
| 496 |
opt = me.layer.options; |
| 497 |
if(opt == nil) return default; |
| 498 |
var val = opt_member(opt, name); |
| 499 |
if(val == nil) return default; |
| 500 |
return val; |
| 501 |
}, |
| 502 |
|
| 503 |
# Wrapper method for accessing style. It allows to pass a default value |
| 504 |
# if the requested style is not defined. |
| 505 |
# It also automatically resolves style properties when they're defined as |
| 506 |
# functions, by calling the corresponding function using the 'me' context |
| 507 |
# |
| 508 |
# EXAMPLE: |
| 509 |
# |
| 510 |
# me.style = { |
| 511 |
# color: [1,1,1], |
| 512 |
# line_color: func(){ |
| 513 |
# me.model.tuned ? [0,0,1] : [1,1,1] |
| 514 |
# } |
| 515 |
# } |
| 516 |
# var color = me.getStyle('color'); # --> [1,1,1] |
| 517 |
# me.model.tuned = 1; |
| 518 |
# var line_color = me.getStyle('line_color'); # --> [0,0,1] |
| 519 |
# var txt_color = me.getStyle('text_color', [1,1,1]); # --> [1,1,1] |
| 520 |
getStyle: func(name, default = nil){ |
| 521 |
var st = me.style; |
| 522 |
if(st == nil) |
| 523 |
st = me.layer.style; |
| 524 |
if(st == nil) return default; |
| 525 |
var val = opt_member(st, name); |
| 526 |
if(typeof(val) == 'func'){ |
| 527 |
val = (call(val,[],me)); |
| 528 |
} |
| 529 |
if(val == nil) return default; |
| 530 |
return val; |
| 531 |
}, |
| 532 |
getLabelFromModel: func(default_val = nil){ |
| 533 |
if(me.model == nil) return default_val; |
| 534 |
if(default_val == nil and contains(me.model, 'id')) |
| 535 |
default_val = me.model.id; |
| 536 |
var label_content = me.getOption('label_content'); |
| 537 |
if(label_content == nil) return default_val; |
| 538 |
if(typeof(label_content) == 'scalar') |
| 539 |
label_content = [label_content]; |
| 540 |
var format_s = me.getOption('label_format'); |
| 541 |
var label = ''; |
| 542 |
if(format_s == nil){ |
| 543 |
format_s = "%s"; |
| 544 |
} |
| 545 |
return me.formattedString(format_s, label_content); |
| 546 |
}, |
| 547 |
# Executes callback function specified by the first argument with |
| 548 |
# variable arguments. The callback is executed within the 'me' context. |
| 549 |
# Callbacks must be defined inside the options hash. |
| 550 |
# |
| 551 |
# EXAMPLE: |
| 552 |
# |
| 553 |
# me.options = { |
| 554 |
# dump_callback: func(){ |
| 555 |
# print('Waypoint '~ me.model.id); |
| 556 |
# } |
| 557 |
# } |
| 558 |
# me.callback('dump'); |
| 559 |
callback: func(name, args...){ |
| 560 |
name = name ~'_callback'; |
| 561 |
var f = me.getOption(name); |
| 562 |
if(typeof(f) == 'func'){ |
| 563 |
return call(f, args, me); |
| 564 |
} |
| 565 |
} |
| 566 |
}; # of Symbol |
| 567 |
|
| 568 |
|
| 569 |
Symbol.Controller = { |
| 570 |
# Static/singleton: |
| 571 |
registry: {}, |
| 572 |
add: func(type, class) |
| 573 |
me.registry[type] = class, |
| 574 |
get: func(type) |
| 575 |
if ((var class = me.registry[type]) == nil) |
| 576 |
__die("Symbol.Controller.get(): unknown type '"~type~"'"); |
| 577 |
else return class, |
| 578 |
# Calls corresonding symbol controller constructor |
| 579 |
# @param model Model to control this object (position and other attributes). |
| 580 |
new: func(type, symbol, model, arg...) |
| 581 |
return call((var class = me.get(type)).new, [symbol, model]~arg, class), |
| 582 |
# Non-static: |
| 583 |
# Update anything related to a particular model. Returns whether the object needs updating: |
| 584 |
update: func(symbol, model) return 1, |
| 585 |
# Delete an object from this controller (or delete the controller itself): |
| 586 |
del: func(symbol, model) , |
| 587 |
# Return whether this model/symbol is (should be) visible: |
| 588 |
isVisible: func(model) return 1, |
| 589 |
# Get the position of this symbol/object: |
| 590 |
getpos: func(model) , # default provided below |
| 591 |
}; # of Symbol.Controller |
| 592 |
# Add this to Symbol as the default controller, but replace the Static .new() method with a blank |
| 593 |
Symbol.df_controller = { parents:[Symbol.Controller], new: func nil }; |
| 594 |
|
| 595 |
var getpos_fromghost = func(positioned_g) |
| 596 |
return [positioned_g.lat, positioned_g.lon]; |
| 597 |
|
| 598 |
# to add support for additional ghosts, just append them to the vector below, possibly at runtime: |
| 599 |
var supported_ghosts = ['positioned','Navaid','Fix','flightplan-leg','FGAirport']; |
| 600 |
var is_positioned_ghost = func(obj) { |
| 601 |
var gt = ghosttype(obj); |
| 602 |
foreach(var ghost; supported_ghosts) { |
| 603 |
if (gt == ghost) return 1; # supported ghost was found |
| 604 |
} |
| 605 |
return 0; # not a known/supported ghost |
| 606 |
}; |
| 607 |
|
| 608 |
var register_supported_ghost = func(name) append(supported_ghosts, name); |
| 609 |
|
| 610 |
# Generic getpos: get lat/lon from any object: |
| 611 |
# (geo.Coord and positioned ghost currently) |
| 612 |
Symbol.Controller.getpos = func(obj, p=nil) { |
| 613 |
if (obj == nil) __die("Symbol.Controller.getpos(): received nil"); |
| 614 |
if (p == nil) { |
| 615 |
var ret = Symbol.Controller.getpos(obj, obj); |
| 616 |
if (ret != nil) return ret; |
| 617 |
if (contains(obj, "parents")) { |
| 618 |
foreach (var p; obj.parents) { |
| 619 |
var ret = Symbol.Controller.getpos(obj, p); |
| 620 |
if (ret != nil) return ret; |
| 621 |
} |
| 622 |
} |
| 623 |
debug.dump(obj); |
| 624 |
__die("Symbol.Controller.getpos(): no suitable getpos() found! Of type: "~typeof(obj)); |
| 625 |
} else { |
| 626 |
if (typeof(p) == 'ghost') |
| 627 |
if ( is_positioned_ghost(p) ) |
| 628 |
return getpos_fromghost(obj); |
| 629 |
else |
| 630 |
__die("Symbol.Controller.getpos(): bad/unsupported ghost of type '"~ghosttype(obj)~"' (see MapStructure.nas Symbol.Controller.getpos() to add new ghosts)"); |
| 631 |
if (typeof(p) == 'hash') |
| 632 |
if (p == geo.Coord) |
| 633 |
return subvec(obj.latlon(), 0, 2); |
| 634 |
if (p == props.Node) |
| 635 |
return [ |
| 636 |
obj.getValue("position/latitude-deg") or obj.getValue("latitude-deg"), |
| 637 |
obj.getValue("position/longitude-deg") or obj.getValue("longitude-deg") |
| 638 |
]; |
| 639 |
if (contains(p,'lat') and contains(p,'lon')) |
| 640 |
return [obj.lat, obj.lon]; |
| 641 |
return nil; |
| 642 |
} |
| 643 |
}; |
| 644 |
|
| 645 |
Symbol.Controller.equals = func(l, r, p=nil) { |
| 646 |
if (l == r) return 1; |
| 647 |
if (p == nil) { |
| 648 |
var ret = Symbol.Controller.equals(l, r, l); |
| 649 |
if (ret != nil) return ret; |
| 650 |
if (contains(l, "parents")) { |
| 651 |
foreach (var p; l.parents) { |
| 652 |
var ret = Symbol.Controller.equals(l, r, p); |
| 653 |
if (ret != nil) return ret; |
| 654 |
} |
| 655 |
} |
| 656 |
debug.dump(l); |
| 657 |
__die("Symbol.Controller: no suitable equals() found! Of type: "~typeof(l)); |
| 658 |
} else { |
| 659 |
if (typeof(p) == 'ghost') |
| 660 |
if ( is_positioned_ghost(p) ) |
| 661 |
return l.id == r.id; |
| 662 |
else |
| 663 |
__die("Symbol.Controller: bad/unsupported ghost of type '"~ghosttype(l)~"' (see MapStructure.nas Symbol.Controller.getpos() to add new ghosts)"); |
| 664 |
if (typeof(p) == 'hash') |
| 665 |
# Somewhat arbitrary convention: |
| 666 |
# * l.equals(r) -- instance method, i.e. uses "me" and "arg[0]" |
| 667 |
# * parent._equals(l,r) -- class method, i.e. uses "arg[0]" and "arg[1]" |
| 668 |
if (contains(p, "equals")) |
| 669 |
return l.equals(r); |
| 670 |
if (contains(p, "_equals")) |
| 671 |
return p._equals(l,r); |
| 672 |
} |
| 673 |
return nil; # scio correctum est |
| 674 |
}; |
| 675 |
|
| 676 |
|
| 677 |
var assert_m = func(hash, member) |
| 678 |
if (!contains(hash, member)) |
| 679 |
__die("assert_m: required field not found: '"~member~"'"); |
| 680 |
var assert_ms = func(hash, members...) |
| 681 |
foreach (var m; members) |
| 682 |
if (m != nil) assert_m(hash, m); |
| 683 |
|
| 684 |
## |
| 685 |
# Implementation for a particular type of symbol (for the *.symbol files) |
| 686 |
# to handle details. |
| 687 |
# |
| 688 |
var DotSym = { |
| 689 |
parents: [Symbol], |
| 690 |
element_id: nil, |
| 691 |
# Static/singleton: |
| 692 |
makeinstance: func(name, hash) { |
| 693 |
if (!isa(hash, DotSym)) |
| 694 |
__die("DotSym: OOP error"); |
| 695 |
return Symbol.add(name, hash); |
| 696 |
}, |
| 697 |
# For the instances returned from makeinstance: |
| 698 |
# @param group The #Canvas.Group to add this to. |
| 699 |
# @param layer The #SymbolLayer this is a child of. |
| 700 |
# @param model A correct object (e.g. positioned ghost) as |
| 701 |
# expected by the .draw file that represents |
| 702 |
# metadata like position, speed, etc. |
| 703 |
# @param controller Optional controller "glue". Each method |
| 704 |
# is called with the model as the only argument. |
| 705 |
new: func(group, layer, model, controller=nil) { |
| 706 |
if (me == nil) __die(); |
| 707 |
var m = { |
| 708 |
parents: [me], |
| 709 |
group: group, |
| 710 |
layer: layer, |
| 711 |
model: model, |
| 712 |
map: layer.map, |
| 713 |
controller: controller == nil ? me.df_controller : controller, |
| 714 |
element: group.createChild( |
| 715 |
me.element_type, me.element_id |
| 716 |
), |
| 717 |
}; |
| 718 |
append(m.parents, m.element); |
| 719 |
Symbol._new(m); |
| 720 |
|
| 721 |
m.init(); |
| 722 |
return m; |
| 723 |
}, |
| 724 |
del: func() { |
| 725 |
logprint(_MP_dbg_lvl, "DotSym.del()"); |
| 726 |
me.deinit(); |
| 727 |
call(Symbol.del, nil, me); |
| 728 |
me.element.del(); |
| 729 |
}, |
| 730 |
# Default wrappers: |
| 731 |
init: func() me.draw(), |
| 732 |
deinit: func(), |
| 733 |
update: func() { |
| 734 |
if (me.controller != nil) { |
| 735 |
if (!me.controller.update(me, me.model)) return; |
| 736 |
elsif (!me.controller.isVisible(me.model)) { |
| 737 |
me.element.hide(); |
| 738 |
return; |
| 739 |
} |
| 740 |
} else |
| 741 |
me.element.show(); |
| 742 |
me.draw(); |
| 743 |
if(me.getOption('disable_position', 0)) return; |
| 744 |
var pos = me.controller.getpos(me.model); |
| 745 |
if (size(pos) == 2) |
| 746 |
pos~=[nil]; # fall through |
| 747 |
if (size(pos) == 3) |
| 748 |
var (lat,lon,rotation) = pos; |
| 749 |
else __die("DotSym.update(): bad position: "~debug.dump(pos)); |
| 750 |
# print(me.model.id, ": Position lat/lon: ", lat, "/", lon); |
| 751 |
me.element.setGeoPosition(lat,lon); |
| 752 |
if (rotation != nil) |
| 753 |
me.element.setRotation(rotation); |
| 754 |
}, |
| 755 |
}; # of DotSym |
| 756 |
|
| 757 |
## |
| 758 |
# Small wrapper for DotSym: parse a SVG on init(). |
| 759 |
# |
| 760 |
var SVGSymbol = { |
| 761 |
parents:[DotSym], |
| 762 |
element_type: "group", |
| 763 |
cacheable: 0, |
| 764 |
init: func() { |
| 765 |
me.callback('init_before'); |
| 766 |
var opt_path = me.getStyle('svg_path'); |
| 767 |
if(opt_path != nil) |
| 768 |
me.svg_path = opt_path; |
| 769 |
if (!me.cacheable) { |
| 770 |
if(me.svg_path != nil and me.svg_path != '') |
| 771 |
canvas.parsesvg(me.element, me.svg_path); |
| 772 |
# hack: |
| 773 |
if (var scale = me.layer.style['scale_factor']) |
| 774 |
me.element.setScale(scale); |
| 775 |
if ((var transl = me.layer.style['translate']) != nil) |
| 776 |
me.element.setTranslation(transl); |
| 777 |
} else { |
| 778 |
__die("cacheable not implemented yet!"); |
| 779 |
} |
| 780 |
me.callback('init_after'); |
| 781 |
me.draw(); |
| 782 |
}, |
| 783 |
draw: func{ |
| 784 |
me.callback('draw'); |
| 785 |
}, |
| 786 |
}; # of SVGSymbol |
| 787 |
|
| 788 |
|
| 789 |
## |
| 790 |
# wrapper for symbols based on raster images (i.e. PNGs) |
| 791 |
# TODO: generalize this and port WXR.symbol accordingly |
| 792 |
# |
| 793 |
var RasterSymbol = { |
| 794 |
parents:[DotSym], |
| 795 |
element_type: "group", |
| 796 |
cacheable: 0, |
| 797 |
size: [32,32], scale: 1, |
| 798 |
init: func() { |
| 799 |
if (!me.cacheable) { |
| 800 |
me.element.createChild("image", me.name) |
| 801 |
.setFile(me.file_path) |
| 802 |
.setSize(me.size) |
| 803 |
.setScale(me.scale); |
| 804 |
} else { |
| 805 |
__die("cacheable not implemented yet!"); |
| 806 |
} |
| 807 |
me.draw(); |
| 808 |
}, |
| 809 |
draw: func, |
| 810 |
|
| 811 |
}; # of RasterSymbol |
| 812 |
|
| 813 |
|
| 814 |
|
| 815 |
var LineSymbol = { |
| 816 |
parents:[Symbol], |
| 817 |
element_id: nil, |
| 818 |
needs_update: 1, |
| 819 |
# Static/singleton: |
| 820 |
makeinstance: func(name, hash) { |
| 821 |
if (!isa(hash, LineSymbol)) |
| 822 |
__die("LineSymbol: OOP error"); |
| 823 |
return Symbol.add(name, hash); |
| 824 |
}, |
| 825 |
# For the instances returned from makeinstance: |
| 826 |
new: func(group, layer, model, controller=nil) { |
| 827 |
if (me == nil) __die("Need me reference for LineSymbol.new()"); |
| 828 |
if (typeof(model) != 'vector') { |
| 829 |
if(typeof(model) == 'hash'){ |
| 830 |
if(!contains(model, 'path')) |
| 831 |
__die("LineSymbol.new(): model hash requires path"); |
| 832 |
} |
| 833 |
else __die("LineSymbol.new(): need a vector of points or a hash"); |
| 834 |
} |
| 835 |
var m = { |
| 836 |
parents: [me], |
| 837 |
group: group, |
| 838 |
layer: layer, |
| 839 |
model: model, |
| 840 |
controller: controller == nil ? me.df_controller : controller, |
| 841 |
element: group.createChild( |
| 842 |
"path", me.element_id |
| 843 |
), |
| 844 |
}; |
| 845 |
append(m.parents, m.element); |
| 846 |
Symbol._new(m); |
| 847 |
|
| 848 |
m.init(); |
| 849 |
return m; |
| 850 |
}, |
| 851 |
# Non-static: |
| 852 |
draw: func() { |
| 853 |
if (!me.needs_update) return; |
| 854 |
me.callback('draw_before'); |
| 855 |
logprint(_MP_dbg_lvl, "redrawing a LineSymbol "~me.layer.type); |
| 856 |
me.element.reset(); |
| 857 |
var cmds = []; |
| 858 |
var coords = []; |
| 859 |
var cmd = canvas.Path.VG_MOVE_TO; |
| 860 |
var path = me.model; |
| 861 |
if(typeof(path) == 'hash'){ |
| 862 |
path = me.model.path; |
| 863 |
if(path == nil) |
| 864 |
__die("LineSymbol model requires a 'path' member (vector)"); |
| 865 |
} |
| 866 |
foreach (var m; path) { |
| 867 |
if(size(keys(m)) >= 2){ |
| 868 |
var (lat,lon) = me.controller.getpos(m); |
| 869 |
append(coords,"N"~lat); |
| 870 |
append(coords,"E"~lon); |
| 871 |
append(cmds,cmd); |
| 872 |
cmd = canvas.Path.VG_LINE_TO; |
| 873 |
} else { |
| 874 |
cmd = canvas.Path.VG_MOVE_TO; |
| 875 |
} |
| 876 |
} |
| 877 |
me.element.setDataGeo(cmds, coords); |
| 878 |
me.element.update(); # this doesn't help with flickering, it seems |
| 879 |
me.callback('draw_after'); |
| 880 |
}, |
| 881 |
del: func() { |
| 882 |
logprint(_MP_dbg_lvl, "LineSymbol.del()"); |
| 883 |
me.deinit(); |
| 884 |
call(Symbol.del, nil, me); |
| 885 |
me.element.del(); |
| 886 |
}, |
| 887 |
# Default wrappers: |
| 888 |
init: func() me.draw(), |
| 889 |
deinit: func(), |
| 890 |
update: func() { |
| 891 |
if (me.controller != nil) { |
| 892 |
if (!me.controller.update(me, me.model)) return; |
| 893 |
elsif (!me.controller.isVisible(me.model)) { |
| 894 |
me.element.hide(); |
| 895 |
return; |
| 896 |
} |
| 897 |
} else |
| 898 |
me.element.show(); |
| 899 |
me.draw(); |
| 900 |
}, |
| 901 |
}; # of LineSymbol |
| 902 |
|
| 903 |
## |
| 904 |
# Base class for a SymbolLayer, e.g. MultiSymbolLayer or SingleSymbolLayer. |
| 905 |
# |
| 906 |
var SymbolLayer = { |
| 907 |
# Default implementations/values: |
| 908 |
df_controller: nil, # default controller |
| 909 |
df_priority: nil, # default priority for display sorting |
| 910 |
df_style: nil, |
| 911 |
df_options: nil, |
| 912 |
type: nil, # type of #Symbol to add (MANDATORY) |
| 913 |
id: nil, # id of the group #canvas.Element (OPTIONAL) |
| 914 |
# Static/singleton: |
| 915 |
registry: {}, |
| 916 |
add: func(type, class) |
| 917 |
me.registry[type] = class, |
| 918 |
get: func(type) { |
| 919 |
foreach(var invalid; var invalid_types = [nil,'vector','hash']) |
| 920 |
if ( (var t=typeof(type)) == invalid) __die(" invalid SymbolLayer type (non-scalar) of type:"~t); |
| 921 |
if ((var class = me.registry[type]) == nil) |
| 922 |
__die("SymbolLayer.get(): unknown type '"~type~"'"); |
| 923 |
else return class; |
| 924 |
}, |
| 925 |
# Calls corresonding layer constructor |
| 926 |
# @param group #Canvas.Group to place this on. |
| 927 |
# @param map The #Canvas.Map this is a member of. |
| 928 |
# @param controller A controller object. |
| 929 |
# @param style An alternate style. |
| 930 |
# @param options Extra options/configurations. |
| 931 |
# @param visible Initially set it up as visible or invisible. |
| 932 |
new: func(type, group, map, controller=nil, style=nil, options=nil, visible=1, arg...) { |
| 933 |
# XXX: Extra named arguments are (obviously) not preserved well... |
| 934 |
var ret = call((var class = me.get(type)).new, [group, map, controller, style, options, visible]~arg, class); |
| 935 |
ret.group.set("layer-type", type); |
| 936 |
return ret; |
| 937 |
}, |
| 938 |
# Private constructor: |
| 939 |
_new: func(m, style, controller, options) { |
| 940 |
# print("SymbolLayer setup options:", m.options!=nil); |
| 941 |
m.style = default_hash(style, m.df_style); |
| 942 |
m.options = default_hash(options, m.df_options); |
| 943 |
|
| 944 |
if (controller == nil) |
| 945 |
controller = m.df_controller; |
| 946 |
assert_m(controller, "parents"); |
| 947 |
if (controller.parents[0] == SymbolLayer.Controller) |
| 948 |
controller = controller.new(m); |
| 949 |
assert_m(controller, "parents"); |
| 950 |
assert_m(controller.parents[0], "parents"); |
| 951 |
if (controller.parents[0].parents[0] != SymbolLayer.Controller) |
| 952 |
__die("MultiSymbolLayer: OOP error"); |
| 953 |
if(options != nil){ |
| 954 |
var listeners = opt_member(controller, 'listeners'); |
| 955 |
var listen = opt_member(options, 'listen'); |
| 956 |
if (listen != nil and listeners != nil){ |
| 957 |
var listen_tp = typeof(listen); |
| 958 |
if(listen_tp != 'vector' and listen_tp != 'scalar') |
| 959 |
__die("Options 'listen' cannot be a "~ listen_tp); |
| 960 |
if(typeof(listen) == 'scalar') |
| 961 |
listen = [listen]; |
| 962 |
foreach(var node_name; listen){ |
| 963 |
var node = opt_member(options, node_name); |
| 964 |
if(node == nil) |
| 965 |
node = node_name; |
| 966 |
append(controller.listeners, |
| 967 |
setlistener(node, func call(m.update,[],m),0,0)); |
| 968 |
} |
| 969 |
} |
| 970 |
} |
| 971 |
m.controller = controller; |
| 972 |
}, |
| 973 |
# For instances: |
| 974 |
del: func() if (me.controller != nil) { me.controller.del(); me.controller = nil }, |
| 975 |
update: func() __die("Abstract SymbolLayer.update() not implemented for this Layer"), |
| 976 |
}; |
| 977 |
|
| 978 |
# Class to manage controlling a #SymbolLayer. |
| 979 |
# Currently handles: |
| 980 |
# * Searching for new symbols (positioned ghosts or other objects with unique id's). |
| 981 |
# * Updating the layer (e.g. on an update loop or on a property change). |
| 982 |
SymbolLayer.Controller = { |
| 983 |
# Static/singleton: |
| 984 |
registry: {}, |
| 985 |
add: func(type, class) |
| 986 |
me.registry[type] = class, |
| 987 |
get: func(type) |
| 988 |
if ((var class = me.registry[type]) == nil) |
| 989 |
__die("unknown type '"~type~"'"); |
| 990 |
else return class, |
| 991 |
# Calls corresonding controller constructor |
| 992 |
# @param layer The #SymbolLayer this controller is responsible for. |
| 993 |
new: func(type, layer, arg...) |
| 994 |
return call((var class = me.get(type)).new, [layer]~arg, class), |
| 995 |
# Default implementations for derived classes: |
| 996 |
# @return List of positioned objects. |
| 997 |
searchCmd: func() |
| 998 |
__die("Abstract method searchCmd() not implemented for this SymbolLayer.Controller type!"), |
| 999 |
addVisibilityListener: func() { |
| 1000 |
var m = me; |
| 1001 |
append(m.listeners, setlistener( |
| 1002 |
m.layer._node.getNode("visible",1), |
| 1003 |
func m.layer.update(), |
| 1004 |
#compile("m.layer.update()", "<layer visibility on node "~m.layer._node.getNode("visible").getPath()~" for layer "~m.layer.type~">"), |
| 1005 |
0,0 |
| 1006 |
)); |
| 1007 |
}, |
| 1008 |
# Default implementations for derived objects: |
| 1009 |
# For SingleSymbolLayer: retreive the model object |
| 1010 |
getModel: func me._model, # assume they store it here - otherwise they can override this |
| 1011 |
}; # of SymbolLayer.Controller |
| 1012 |
|
| 1013 |
## |
| 1014 |
# A layer that manages a list of symbols (using delta positioned handling |
| 1015 |
# with a searchCmd to retreive placements). |
| 1016 |
# |
| 1017 |
var MultiSymbolLayer = { |
| 1018 |
parents: [SymbolLayer], |
| 1019 |
# Default implementations/values: |
| 1020 |
# @param group A group to place this on. |
| 1021 |
# @param map The #Canvas.Map this is a member of. |
| 1022 |
# @param controller A controller object (parents=[SymbolLayer.Controller]) |
| 1023 |
# or implementation (parents[0].parents=[SymbolLayer.Controller]). |
| 1024 |
# @param style An alternate style. |
| 1025 |
# @param options Extra options/configurations. |
| 1026 |
# @param visible Initially set it up as visible or invisible. |
| 1027 |
new: func(group, map, controller=nil, style=nil, options=nil, visible=1) { |
| 1028 |
#print("Creating new SymbolLayer instance"); |
| 1029 |
if (me == nil) __die("MultiSymbolLayer constructor needs to know its parent class"); |
| 1030 |
var m = { |
| 1031 |
parents: [me], |
| 1032 |
map: map, |
| 1033 |
group: group.createChild("group", me.type), |
| 1034 |
list: [], |
| 1035 |
}; |
| 1036 |
append(m.parents, m.group); |
| 1037 |
m.setVisible(visible); |
| 1038 |
# N.B.: this has to be here for the controller |
| 1039 |
m.searcher = geo.PositionedSearch.new(me.searchCmd, me.onAdded, me.onRemoved, m); |
| 1040 |
SymbolLayer._new(m, style, controller, options); |
| 1041 |
|
| 1042 |
m.update(); |
| 1043 |
return m; |
| 1044 |
}, |
| 1045 |
update: func() { |
| 1046 |
if (!me.getVisible()) |
| 1047 |
return; |
| 1048 |
#debug.warn("update traceback for "~me.type); |
| 1049 |
|
| 1050 |
var updater = func { |
| 1051 |
me.searcher.update(); |
| 1052 |
foreach (var e; me.list) |
| 1053 |
e.update(); |
| 1054 |
} |
| 1055 |
|
| 1056 |
if (me.options != nil and me.options['update_wrapper'] !=nil) { |
| 1057 |
me.options.update_wrapper( me, updater ); # call external wrapper (usually for profiling purposes) |
| 1058 |
} else { |
| 1059 |
updater(); |
| 1060 |
} |
| 1061 |
}, |
| 1062 |
del: func() { |
| 1063 |
logprint(_MP_dbg_lvl, "MultiSymbolLayer.del()"); |
| 1064 |
foreach (var e; me.list) |
| 1065 |
e.del(); |
| 1066 |
call(SymbolLayer.del, nil, me); |
| 1067 |
}, |
| 1068 |
delsym: func(model) { |
| 1069 |
forindex (var i; me.list) { |
| 1070 |
var e = me.list[i]; |
| 1071 |
if (Symbol.Controller.equals(e.model, model)) { |
| 1072 |
# Remove this element from the list |
| 1073 |
# TODO: maybe C function for this? extend pop() to accept index? |
| 1074 |
var prev = subvec(me.list, 0, i); |
| 1075 |
var next = subvec(me.list, i+1); |
| 1076 |
me.list = prev~next; |
| 1077 |
e.del(); |
| 1078 |
return 1; |
| 1079 |
} |
| 1080 |
} |
| 1081 |
return 0; |
| 1082 |
}, |
| 1083 |
searchCmd: func() { |
| 1084 |
if (me.map.getPosCoord() == nil or me.map.getRange() == nil) { |
| 1085 |
print("Map not yet initialized, returning empty result set!"); |
| 1086 |
return []; # handle maps not yet fully initialized |
| 1087 |
} |
| 1088 |
var result = me.controller.searchCmd(); |
| 1089 |
# some hardening |
| 1090 |
var type=typeof(result); |
| 1091 |
if(type != 'nil' and type != 'vector') |
| 1092 |
__die("MultiSymbolLayer: searchCmd() method MUST return a vector of valid positioned ghosts/Geo.Coord objects or nil! (was:"~type~")"); |
| 1093 |
return result; |
| 1094 |
}, |
| 1095 |
# Adds a symbol. |
| 1096 |
onAdded: func(model) { |
| 1097 |
logprint(_MP_dbg_lvl, "Adding symbol of type "~me.type); |
| 1098 |
if (model == nil) __die("MultiSymbolLayer: Model was nil for layer:"~debug.string(me.type)~ " Hint:check your equality check method!"); |
| 1099 |
append(me.list, Symbol.new(me.type, me.group, me, model)); |
| 1100 |
}, |
| 1101 |
# Removes a symbol. |
| 1102 |
onRemoved: func(model) { |
| 1103 |
logprint(_MP_dbg_lvl, "Deleting symbol of type "~me.type); |
| 1104 |
if (!me.delsym(model)) __die("model not found"); |
| 1105 |
try_aux_method(model, "del"); |
| 1106 |
#call(func model.del(), nil, var err = []); # try... |
| 1107 |
#if (size(err) and err[0] != "No such member: del") # ... and either catch or rethrow |
| 1108 |
# die(err[0]); |
| 1109 |
}, |
| 1110 |
}; # of MultiSymbolLayer |
| 1111 |
|
| 1112 |
## |
| 1113 |
# A layer that manages a list of statically-positioned navaid symbols (using delta positioned handling |
| 1114 |
# with a searchCmd to retrieve placements). |
| 1115 |
# This is not yet supposed to work properly, it's just there to help get rid of all the identical boilerplate code |
| 1116 |
# in lcontroller files, so needs some reviewing and customizing still |
| 1117 |
# |
| 1118 |
var NavaidSymbolLayer = { |
| 1119 |
parents: [MultiSymbolLayer], |
| 1120 |
# static generator/functor maker: |
| 1121 |
make: func(query) { |
| 1122 |
#print("Creating searchCmd() for NavaidSymbolLayer:", query); |
| 1123 |
return func { |
| 1124 |
logprint(_MP_dbg_lvl, "Running query:", query); |
| 1125 |
var range = me.map.getRange(); |
| 1126 |
if (range == nil) return; |
| 1127 |
return positioned.findWithinRange(me.map.getPosCoord(), range, query); |
| 1128 |
}; |
| 1129 |
}, |
| 1130 |
}; # of NavaidSymbolLayer |
| 1131 |
|
| 1132 |
|
| 1133 |
|
| 1134 |
### |
| 1135 |
## TODO: wrappers for Horizontal vs. Vertical layers ? |
| 1136 |
## |
| 1137 |
|
| 1138 |
var SingleSymbolLayer = { |
| 1139 |
parents: [SymbolLayer], |
| 1140 |
# Default implementations/values: |
| 1141 |
# @param group A group to place this on. |
| 1142 |
# @param map The #Canvas.Map this is a member of. |
| 1143 |
# @param controller A controller object (parents=[SymbolLayer.Controller]) |
| 1144 |
# or implementation (parents[0].parents=[SymbolLayer.Controller]). |
| 1145 |
# @param style An alternate style. |
| 1146 |
# @param options Extra options/configurations. |
| 1147 |
# @param visible Initially set it up as visible or invisible. |
| 1148 |
new: func(group, map, controller=nil, style=nil, options=nil, visible=1) { |
| 1149 |
#print("Creating new SymbolLayer instance"); |
| 1150 |
if (me == nil) __die("SingleSymbolLayer constructor needs to know its parent class"); |
| 1151 |
var m = { |
| 1152 |
parents: [me], |
| 1153 |
map: map, |
| 1154 |
group: group.createChild("group", me.type), |
| 1155 |
}; |
| 1156 |
append(m.parents, m.group); |
| 1157 |
m.setVisible(visible); |
| 1158 |
SymbolLayer._new(m, style, controller, options); |
| 1159 |
|
| 1160 |
m.symbol = Symbol.new(m.type, m.group, m, m.controller.getModel()); |
| 1161 |
m.update(); |
| 1162 |
return m; |
| 1163 |
}, |
| 1164 |
update: func() { |
| 1165 |
if (!me.getVisible()) |
| 1166 |
return; |
| 1167 |
|
| 1168 |
var updater = func { |
| 1169 |
if (typeof(me.symbol.model) == 'hash') try_aux_method(me.symbol.model, "update"); |
| 1170 |
me.symbol.update(); |
| 1171 |
} |
| 1172 |
|
| 1173 |
if (me.options != nil and me.options['update_wrapper'] != nil) { |
| 1174 |
me.options.update_wrapper( me, updater ); # call external wrapper (usually for profiling purposes) |
| 1175 |
} else { |
| 1176 |
updater(); |
| 1177 |
} |
| 1178 |
}, |
| 1179 |
del: func() { |
| 1180 |
logprint(_MP_dbg_lvl, "SymbolLayer.del()"); |
| 1181 |
me.symbol.del(); |
| 1182 |
call(SymbolLayer.del, nil, me); |
| 1183 |
}, |
| 1184 |
}; # of SingleSymbolLayer |
| 1185 |
|
| 1186 |
## |
| 1187 |
# Base class for a OverlayLayer, e.g. a TileLayer |
| 1188 |
# |
| 1189 |
var OverlayLayer = { |
| 1190 |
# Default implementations/values: |
| 1191 |
df_controller: nil, # default controller |
| 1192 |
df_priority: nil, # default priority for display sorting |
| 1193 |
df_style: nil, |
| 1194 |
df_options: nil, |
| 1195 |
type: nil, # type of #Symbol to add (MANDATORY) |
| 1196 |
id: nil, # id of the group #canvas.Element (OPTIONAL) |
| 1197 |
# Static/singleton: |
| 1198 |
registry: {}, |
| 1199 |
add: func(type, class) { |
| 1200 |
me.registry[type] = class; |
| 1201 |
}, |
| 1202 |
get: func(type) { |
| 1203 |
foreach(var invalid; var invalid_types = [nil,'vector','hash']) |
| 1204 |
if ( (var t=typeof(type)) == invalid) __die(" invalid OverlayLayer type (non-scalar) of type:"~t); |
| 1205 |
if ((var class = me.registry[type]) == nil) |
| 1206 |
__die("OverlayLayer.get(): unknown type '"~type~"'"); |
| 1207 |
else return class; |
| 1208 |
}, |
| 1209 |
# Calls corresonding layer constructor |
| 1210 |
# @param group #Canvas.Group to place this on. |
| 1211 |
# @param map The #Canvas.Map this is a member of. |
| 1212 |
# @param style An alternate style. |
| 1213 |
# @param options Extra options/configurations. |
| 1214 |
# @param visible Initially set it up as visible or invisible. |
| 1215 |
new: func(type, group, map, controller=nil, style=nil, options=nil, visible=1, arg...) { |
| 1216 |
# XXX: Extra named arguments are (obviously) not preserved well... |
| 1217 |
if (me == nil) __die("OverlaySymbolLayer constructor needs to know its parent class"); |
| 1218 |
|
| 1219 |
var ret = call((var class = me.get(type)).new, [group, map, controller, style, options, visible], class); |
| 1220 |
ret.type = type; |
| 1221 |
ret.group.set("layer-type", type); |
| 1222 |
return ret; |
| 1223 |
}, |
| 1224 |
|
| 1225 |
# Private constructor: |
| 1226 |
_new: func(m, style, controller, options) { |
| 1227 |
m.style = default_hash(style, m.df_style); |
| 1228 |
m.options = default_hash(options, m.df_options); |
| 1229 |
|
| 1230 |
if (controller == nil) { |
| 1231 |
if (m.df_controller == nil) { |
| 1232 |
controller = OverlayLayer.Controller; |
| 1233 |
} else { |
| 1234 |
controller = m.df_controller; |
| 1235 |
} |
| 1236 |
} |
| 1237 |
|
| 1238 |
assert_m(controller, "parents"); |
| 1239 |
if (controller.parents[0] == OverlayLayer.Controller) |
| 1240 |
controller = controller.new(m); |
| 1241 |
assert_m(controller, "parents"); |
| 1242 |
assert_m(controller.parents[0], "parents"); |
| 1243 |
if(options != nil){ |
| 1244 |
var listeners = opt_member(controller, 'listeners'); |
| 1245 |
var listen = opt_member(options, 'listen'); |
| 1246 |
if (listen != nil and listeners != nil){ |
| 1247 |
var listen_tp = typeof(listen); |
| 1248 |
if(listen_tp != 'vector' and listen_tp != 'scalar') |
| 1249 |
__die("Options 'listen' cannot be a "~ listen_tp); |
| 1250 |
if(typeof(listen) == 'scalar') |
| 1251 |
listen = [listen]; |
| 1252 |
foreach(var node_name; listen){ |
| 1253 |
var node = opt_member(options, node_name); |
| 1254 |
if(node == nil) |
| 1255 |
node = node_name; |
| 1256 |
append(controller.listeners, |
| 1257 |
setlistener(node, func call(m.update,[],m),0,0)); |
| 1258 |
} |
| 1259 |
} |
| 1260 |
} |
| 1261 |
m.controller = controller; |
| 1262 |
}, |
| 1263 |
# For instances: |
| 1264 |
del: func() if (me.controller != nil) { me.controller.del(); me.controller = nil }, |
| 1265 |
update: func() { _die("Abstract OverlayLayer.update() not implemented for this Layer"); }, |
| 1266 |
}; |
| 1267 |
|
| 1268 |
var TileLayer = { |
| 1269 |
parents: [OverlayLayer], |
| 1270 |
# Default implementations/values: |
| 1271 |
# @param group A group to place this on. |
| 1272 |
# @param map The #Canvas.Map this is a member of. |
| 1273 |
# @param controller A controller object (parents=[OverlayLayer.Controller]) |
| 1274 |
# or implementation (parents[0].parents=[OverlayLayer.Controller]). |
| 1275 |
# @param style An alternate style. |
| 1276 |
# @param options Extra options/configurations. |
| 1277 |
# @param visible Initially set it up as visible or invisible. |
| 1278 |
new: func(group, map, controller=nil, style=nil, options=nil, visible=1) { |
| 1279 |
if (me == nil) __die("TileLayer constructor needs to know its parent class"); |
| 1280 |
var m = { |
| 1281 |
parents: [me], |
| 1282 |
map: map, |
| 1283 |
group: group.createChild("group", me.type), |
| 1284 |
maps_base: "", |
| 1285 |
controller: controller, |
| 1286 |
num_tiles: [9,9], |
| 1287 |
makeURL: nil, |
| 1288 |
makePath: nil, |
| 1289 |
center_tile_offset : [], |
| 1290 |
tile_size: 256, |
| 1291 |
zoom: 9, |
| 1292 |
max_zoom: 16, |
| 1293 |
min_zoom: 4, |
| 1294 |
tile_type: "map", |
| 1295 |
last_tile_type: "map", |
| 1296 |
last_tile : [-1,-1], |
| 1297 |
tiles: [], |
| 1298 |
}; |
| 1299 |
|
| 1300 |
# Determine the number of tiles dynamically based on the canvas size |
| 1301 |
#var width = map.getCanvas().get("size[0]"); |
| 1302 |
#var height = map.getCanvas().get("size[1]"); |
| 1303 |
#m.num_tiles= [ math.ceil(width / m.tile_size), |
| 1304 |
# math.ceil(height / m.tile_size) ]; |
| 1305 |
|
| 1306 |
|
| 1307 |
m.maps_base = getprop("/sim/fg-home") ~ '/cache/maps'; |
| 1308 |
m.tiles = setsize([], m.num_tiles[0]); |
| 1309 |
m.center_tile_offset = [ |
| 1310 |
(m.num_tiles[0] - 1.0) / 2.0, |
| 1311 |
(m.num_tiles[1] - 1.0) / 2.0 |
| 1312 |
]; |
| 1313 |
|
| 1314 |
append(m.parents, m.group); |
| 1315 |
m.setVisible(visible); |
| 1316 |
OverlayLayer._new(m, style, controller, options); |
| 1317 |
|
| 1318 |
for(var x = 0; x < m.num_tiles[0]; x += 1) |
| 1319 |
{ |
| 1320 |
m.tiles[x] = setsize([], m.num_tiles[1]); |
| 1321 |
for(var y = 0; y < m.num_tiles[1]; y += 1) { |
| 1322 |
m.tiles[x][y] = m.group.createChild("image", "map-tile"); |
| 1323 |
} |
| 1324 |
} |
| 1325 |
|
| 1326 |
m.update(); |
| 1327 |
return m; |
| 1328 |
}, |
| 1329 |
updateLayer: func() |
| 1330 |
{ |
| 1331 |
if (me.controller != nil) me.controller.updateLayer(); |
| 1332 |
|
| 1333 |
# get current position |
| 1334 |
var lat = me.map.getLat(); |
| 1335 |
var lon = me.map.getLon(); |
| 1336 |
var range_nm = me.map.getRange(); |
| 1337 |
var screen_range = me.map.getScreenRange(); |
| 1338 |
|
| 1339 |
if (screen_range == nil) screen_range = 200; |
| 1340 |
|
| 1341 |
# Screen resolution m/pixel is range/screen_range |
| 1342 |
var screen_resolution = range_nm * globals.NM2M / screen_range; |
| 1343 |
|
| 1344 |
# Slippy map resolution is |
| 1345 |
# 156543.03 meters/pixel * cos(latitude) / (2 ^ zoomlevel) |
| 1346 |
# Determine the closest zoom level and scaling ratio. Each increase in zoom level doubles resolution. |
| 1347 |
var ideal_zoom = math.ln(156543.03 * math.cos(lat * math.pi/180.0) / screen_resolution) / math.ln(2); |
| 1348 |
|
| 1349 |
me.zoom = math.ceil(ideal_zoom); |
| 1350 |
if (me.zoom < me.min_zoom) me.zoom = me.min_zoom; |
| 1351 |
if (me.zoom > me.max_zoom) me.zoom = me.max_zoom; |
| 1352 |
|
| 1353 |
var ratio = 1 / math.pow(2,me.zoom - ideal_zoom); |
| 1354 |
|
| 1355 |
for(var x = 0; x < me.num_tiles[0]; x += 1) |
| 1356 |
{ |
| 1357 |
for(var y = 0; y < me.num_tiles[1]; y += 1) { |
| 1358 |
me.tiles[x][y].setTranslation(int((x - me.center_tile_offset[0]) * me.tile_size * ratio + 0.5), |
| 1359 |
int((y - me.center_tile_offset[1]) * me.tile_size * ratio + 0.5)); |
| 1360 |
me.tiles[x][y].setScale(ratio); |
| 1361 |
me.tiles[x][y].scale_factor = ratio; |
| 1362 |
} |
| 1363 |
} |
| 1364 |
|
| 1365 |
var ymax = math.pow(2, me.zoom); |
| 1366 |
|
| 1367 |
# Slippy map location of center point |
| 1368 |
var slippy_center = [ |
| 1369 |
math.floor(ymax * ((lon + 180.0) / 360.0)), |
| 1370 |
math.floor((1 - math.ln(math.tan(lat * math.pi/180.0) + 1 / math.cos(lat * math.pi/180.0)) / math.pi) / 2.0 * ymax) |
| 1371 |
]; |
| 1372 |
|
| 1373 |
# This is the Slippy Map location of the 0,0 tile |
| 1374 |
var offset = [slippy_center[0] - me.center_tile_offset[0], |
| 1375 |
slippy_center[1] - me.center_tile_offset[1]]; |
| 1376 |
|
| 1377 |
var tile_index = [math.floor(offset[0]), math.floor(offset[1])]; |
| 1378 |
|
| 1379 |
# Find the lon, lat of the center tile |
| 1380 |
var center_tile_lon = slippy_center[0]/ymax * 360.0 - 180.0; |
| 1381 |
var nn = math.pi - 2.0 * math.pi * slippy_center[1]/ ymax; |
| 1382 |
var center_tile_lat = 180.0 / math.pi * math.atan(0.5 * (math.exp(nn) - math.exp(-nn))); |
| 1383 |
|
| 1384 |
me.group.setGeoPosition(center_tile_lat, center_tile_lon); |
| 1385 |
|
| 1386 |
if( tile_index[0] != me.last_tile[0] |
| 1387 |
or tile_index[1] != me.last_tile[1] |
| 1388 |
or me.tile_type != me.last_tile_type ) |
| 1389 |
{ |
| 1390 |
for(var x = 0; x < me.num_tiles[0]; x += 1) { |
| 1391 |
for(var y = 0; y < me.num_tiles[1]; y += 1) { |
| 1392 |
var pos = { |
| 1393 |
z: me.zoom, |
| 1394 |
x: int(tile_index[0] + x), |
| 1395 |
y: int(tile_index[1] + y), |
| 1396 |
tms_y: ymax - int(tile_index[1] + y) - 1, |
| 1397 |
type: me.tile_type |
| 1398 |
}; |
| 1399 |
|
| 1400 |
(func { |
| 1401 |
var img_path = me.makePath(pos); |
| 1402 |
var tile = me.tiles[x][y]; |
| 1403 |
|
| 1404 |
if( io.stat(img_path) == nil ) { |
| 1405 |
# image not found, save in $FG_HOME |
| 1406 |
var img_url = me.makeURL(pos); |
| 1407 |
#print('requesting ' ~ img_url); |
| 1408 |
http.save(img_url, img_path) |
| 1409 |
.done(func { tile.set("src", img_path);}) |
| 1410 |
.fail(func (r) print('Failed to get image ' ~ img_path ~ ' ' ~ r.status ~ ': ' ~ r.reason)); |
| 1411 |
} else { |
| 1412 |
# Re-use cached image |
| 1413 |
#print('loading ' ~ img_path); |
| 1414 |
tile.set("src", img_path) |
| 1415 |
} |
| 1416 |
})(); |
| 1417 |
} |
| 1418 |
} |
| 1419 |
|
| 1420 |
me.last_tile = tile_index; |
| 1421 |
me.last_type = me.type; |
| 1422 |
} |
| 1423 |
}, |
| 1424 |
update: func() { |
| 1425 |
if (!me.getVisible()) |
| 1426 |
return; |
| 1427 |
#debug.warn("update traceback for "~me.type); |
| 1428 |
|
| 1429 |
if (me.options != nil and me.options['update_wrapper'] !=nil) { |
| 1430 |
me.options.update_wrapper( me, me.updateLayer ); # call external wrapper (usually for profiling purposes) |
| 1431 |
} else { |
| 1432 |
me.updateLayer(); |
| 1433 |
} |
| 1434 |
}, |
| 1435 |
del: func() { |
| 1436 |
logprint(_MP_dbg_lvl, "SymbolLayer.del()"); |
| 1437 |
call(OverlayLayer.del, nil, me); |
| 1438 |
}, |
| 1439 |
}; # of TileLayer |
| 1440 |
|
| 1441 |
# Class to manage controlling a OverlayLayer. |
| 1442 |
# Currently handles: |
| 1443 |
# * Simple update() call |
| 1444 |
OverlayLayer.Controller = { |
| 1445 |
# Static/singleton: |
| 1446 |
registry: {}, |
| 1447 |
add: func(type, class) |
| 1448 |
me.registry[type] = class, |
| 1449 |
get: func(type) |
| 1450 |
if ((var class = me.registry[type]) == nil) |
| 1451 |
__die("unknown type '"~type~"'"); |
| 1452 |
else return class, |
| 1453 |
# Calls corresponding controller constructor |
| 1454 |
# @param layer The #OverlayLayer this controller is responsible for. |
| 1455 |
new: func(type, layer, arg...) |
| 1456 |
return call((var class = me.get(type)).new, [layer]~arg, class), |
| 1457 |
# Default implementations for derived classes: |
| 1458 |
# @return List of positioned objects. |
| 1459 |
updateLayer: func() |
| 1460 |
__die("Abstract method updateLayer() not implemented for this OverlayLayer.Controller type!"), |
| 1461 |
addVisibilityListener: func() { |
| 1462 |
var m = me; |
| 1463 |
append(m.listeners, setlistener( |
| 1464 |
m.layer._node.getNode("visible", 1), |
| 1465 |
func m.layer.update(), |
| 1466 |
#compile("m.layer.update()", "<layer visibility on node "~m.layer._node.getNode("visible").getPath()~" for layer "~m.layer.type~">"), |
| 1467 |
0,0 |
| 1468 |
)); |
| 1469 |
}, |
| 1470 |
addRangeListener: func() { |
| 1471 |
var m = me; |
| 1472 |
append(m.listeners, setlistener( |
| 1473 |
m.layer._node.getNode("range",1), |
| 1474 |
func m.layer.update(), |
| 1475 |
#compile("m.layer.update()", "<layer visibility on node "~m.layer._node.getNode("visible").getPath()~" for layer "~m.layer.type~">"), |
| 1476 |
0,0 |
| 1477 |
)); |
| 1478 |
}, |
| 1479 |
addScreenRangeListener: func() { |
| 1480 |
var m = me; |
| 1481 |
append(m.listeners, setlistener( |
| 1482 |
m.layer._node.getNode("screen-range",1), |
| 1483 |
func m.layer.update(), |
| 1484 |
#compile("m.layer.update()", "<layer visibility on node "~m.layer._node.getNode("visible").getPath()~" for layer "~m.layer.type~">"), |
| 1485 |
0,0 |
| 1486 |
)); |
| 1487 |
}, |
| 1488 |
}; # of OverlayLayer.Controller |
| 1489 |
|
| 1490 |
|
| 1491 |
### |
| 1492 |
# set up a cache for 32x32 symbols (initialized below in load_MapStructure) |
| 1493 |
var SymbolCache32x32 = nil; |
| 1494 |
var SymbolCache256x256 = nil; |
| 1495 |
|
| 1496 |
var MapStructure = { |
| 1497 |
# Generalized load methods used to load various symbols, layer controllers,... |
| 1498 |
loadFile : func(file, name) { |
| 1499 |
if (name == nil) |
| 1500 |
var name = split("/", file)[-1]; |
| 1501 |
var code = io.readfile(file); |
| 1502 |
var code = call(func compile(code, file), [code], var err=[]); |
| 1503 |
if (size(err)) { |
| 1504 |
if (substr(err[0], 0, 12) == "Parse error:") { # hack around Nasal feature |
| 1505 |
var e = split(" at line ", err[0]); |
| 1506 |
if (size(e) == 2) |
| 1507 |
err[0] = string.join("", [e[0], "\n at ", file, ", line ", e[1], "\n "]); |
| 1508 |
} |
| 1509 |
for (var i = 1; (var c = caller(i)) != nil; i += 1) |
| 1510 |
err ~= subvec(c, 2, 2); |
| 1511 |
debug.printerror(err); |
| 1512 |
return; |
| 1513 |
} |
| 1514 |
#code=bind( |
| 1515 |
call(code, nil, nil, var hash = {}); |
| 1516 |
|
| 1517 |
# validate |
| 1518 |
var url = ' http://wiki.flightgear.org/MapStructure#'; |
| 1519 |
# TODO: these rules should be extended for all main files lcontroller/scontroller and symbol |
| 1520 |
var checks = [ |
| 1521 |
{ extension:'symbol', symbol:'update', type:'func', error:' update() must not be overridden:', id:300}, |
| 1522 |
# Sorry, this one doesn't work with the new LineSymbol |
| 1523 |
# { extension:'symbol', symbol:'draw', type:'func', required:1, error:' symbol files need to export a draw() routine:', id:301}, |
| 1524 |
# Sorry, this one doesn't work with the new SingleSymbolLayer |
| 1525 |
# { extension:'lcontroller', symbol:'searchCmd', type:'func', required:1, error:' lcontroller without searchCmd method:', id:100}, |
| 1526 |
]; |
| 1527 |
|
| 1528 |
|
| 1529 |
var makeurl = func(scope, id) url ~ scope ~ ':' ~ id; |
| 1530 |
var bailout = func(file, message, scope, id) __die(file~message~"\n"~makeurl(scope,id) ); |
| 1531 |
|
| 1532 |
var current_ext = split('.', file)[-1]; |
| 1533 |
foreach(var check; checks) { |
| 1534 |
# check if we have any rules matching the current file extension |
| 1535 |
if (current_ext == check.extension) { |
| 1536 |
# check for fields that must not be overridden |
| 1537 |
if (check['error'] != nil and |
| 1538 |
hash[check.symbol]!=nil and !check['required'] and |
| 1539 |
typeof(hash[check.symbol])==check.type ) { |
| 1540 |
bailout(file,check.error,check.extension,check.id); |
| 1541 |
} |
| 1542 |
|
| 1543 |
# check for required fields |
| 1544 |
if (check['required'] != nil and |
| 1545 |
hash[check.symbol]==nil and |
| 1546 |
typeof( hash[check.symbol]) != check.type) { |
| 1547 |
bailout(file,check.error,check.extension,check.id); |
| 1548 |
} |
| 1549 |
} |
| 1550 |
} |
| 1551 |
|
| 1552 |
return hash; |
| 1553 |
} |
| 1554 |
}; |
| 1555 |
|
| 1556 |
|
| 1557 |
var load_MapStructure = func { |
| 1558 |
canvas.load_MapStructure = func; # disable any subsequent attempt to load |
| 1559 |
|
| 1560 |
Map.Controller = { |
| 1561 |
# Static/singleton: |
| 1562 |
registry: {}, |
| 1563 |
add: func(type, class) |
| 1564 |
me.registry[type] = class, |
| 1565 |
get: func(type) |
| 1566 |
if ((var class = me.registry[type]) == nil) |
| 1567 |
__die("unknown type '"~type~"'"); |
| 1568 |
else return class, |
| 1569 |
# Calls corresonding controller constructor |
| 1570 |
# @param map The #SymbolMap this controller is responsible for. |
| 1571 |
new: func(type, map, arg...) { |
| 1572 |
var m = call((var class = me.get(type)).new, [map]~arg, class); |
| 1573 |
if (!contains(m, "map")) |
| 1574 |
m.map = map; |
| 1575 |
elsif (m.map != map and !isa(m.map, map) and ( |
| 1576 |
m.get_position != Map.Controller.get_position |
| 1577 |
or m.query_range != Map.Controller.query_range |
| 1578 |
or m.in_range != Map.Controller.in_range)) |
| 1579 |
{ __die("m must store the map handle as .map if it uses the default method(s)"); } |
| 1580 |
}, |
| 1581 |
# Default implementations: |
| 1582 |
get_position: func() { |
| 1583 |
debug.warn("get_position is deprecated"); |
| 1584 |
return me.map.getLatLon()~[me.map.getAlt()]; |
| 1585 |
}, |
| 1586 |
query_range: func() { |
| 1587 |
debug.warn("query_range is deprecated"); |
| 1588 |
return me.map.getRange() or 30; |
| 1589 |
}, |
| 1590 |
in_range: func(lat, lon, alt=0) { |
| 1591 |
var range = me.map.getRange(); |
| 1592 |
if(range == nil) __die("in_range: Invalid query range!"); |
| 1593 |
# print("Query Range is:", range ); |
| 1594 |
if (lat == nil or lon == nil) __die("in_range: lat/lon invalid"); |
| 1595 |
var pos = geo.Coord.new(); |
| 1596 |
pos.set_latlon(lat, lon, alt or 0); |
| 1597 |
var map_pos = me.map.getPosCoord(); |
| 1598 |
if (map_pos == nil) |
| 1599 |
return 0; # should happen *ONLY* when map is uninitialized |
| 1600 |
var distance_m = pos.distance_to( map_pos ); |
| 1601 |
var is_in_range = distance_m < range * NM2M; |
| 1602 |
# print("Distance:",distance_m*M2NM," nm in range check result:", is_in_range); |
| 1603 |
return is_in_range; |
| 1604 |
}, |
| 1605 |
}; |
| 1606 |
|
| 1607 |
####### LOAD FILES ####### |
| 1608 |
(func { |
| 1609 |
var FG_ROOT = getprop("/sim/fg-root"); |
| 1610 |
|
| 1611 |
# sets up a shared symbol cache, which will be used by all MapStructure maps and layers |
| 1612 |
canvas.SymbolCache32x32 = SymbolCache.new(1024,32); |
| 1613 |
canvas.SymbolCache256x256 = SymbolCache.new(1024,256); |
| 1614 |
|
| 1615 |
# Find files and load them: |
| 1616 |
var contents_dir = FG_ROOT~"/Nasal/canvas/map/"; |
| 1617 |
var dep_names = [ |
| 1618 |
# With these extensions, in this order: |
| 1619 |
"lcontroller", |
| 1620 |
"symbol", |
| 1621 |
"scontroller", |
| 1622 |
"controller", |
| 1623 |
"overlay" |
| 1624 |
]; |
| 1625 |
var deps = {}; |
| 1626 |
foreach (var d; dep_names) deps[d] = []; |
| 1627 |
foreach (var f; directory(contents_dir)) { |
| 1628 |
var ext = size(var s=split(".", f)) > 1 ? s[-1] : nil; |
| 1629 |
foreach (var d; dep_names) { |
| 1630 |
if (ext == d) { |
| 1631 |
append(deps[d], f); |
| 1632 |
break |
| 1633 |
} |
| 1634 |
} |
| 1635 |
} |
| 1636 |
foreach (var d; dep_names) { |
| 1637 |
foreach (var f; deps[d]) { |
| 1638 |
var name = split(".", f)[0]; |
| 1639 |
MapStructure.loadFile(contents_dir~f, name); |
| 1640 |
} |
| 1641 |
} |
| 1642 |
})(); |
| 1643 |
|
| 1644 |
}; # load_MapStructure |
| 1645 |
|
| 1646 |
setlistener("/nasal/canvas/loaded", load_MapStructure); # end ugly module init listener hack. FIXME: do smart Nasal bootstrapping, quod est callidus! |
| 1647 |
# Actually, it would be even better to support reloading MapStructure files, and maybe even MapStructure itself by calling the dtor/del method for each Map and then re-running the ctor |