Debian Codegraph @

Nasal/mp_broadcast.nas

raw
1 ###############################################################################
2 ##
3 ## A message based information broadcast for the multiplayer network.
4 ##
5 ## Copyright (C) 2008 - 2013 Anders Gidenstam (anders(at)gidenstam.org)
6 ## This file is licensed under the GPL license version 2 or later.
7 ##
8 ###############################################################################
9
10 ###############################################################################
11 # Event broadcast channel using a MP enabled string property.
12 # Events from users in multiplayer.ignore are ignored.
13 #
14 # EventChannel.new(mpp_path)
15 # Create a new event broadcast channel. Any MP user with the same
16 # primitive will receive all messages sent to the channel from the point
17 # she/he joined (barring severe MP packet loss).
18 # NOTE: Message delivery is not guaranteed.
19 # mpp_path - MP property path : string
20 #
21 # EventChannel.register(event_hash, handler)
22 # Register a handler for the event identified by the hash event_hash.
23 # event_hash - hash value for the event : a unique 4 character string
24 # handler - a handler function for the event : func (sender, msg)
25 #
26 # EventChannel.deregister(event_hash)
27 # Deregister the handler for the event identified by the hash event_hash.
28 # event_hash - hash value for the event : a unique 4 character string
29 #
30 # EventChannel.send(event_hash, msg)
31 # Sends the event event_hash with the message msg to the channel.
32 # event_hash - hash value for the event : a unique 4 character string
33 # msg - text string with Binary data encoded data : string
34 #
35 # EventChannel.die()
36 # Destroy this EventChannel instance.
37 #
38 var EventChannel = {};
39 EventChannel.new = func (mpp_path) {
40 var obj = BroadcastChannel.new(mpp_path,
41 func (n, msg) { obj._process(n, msg) });
42 # Save send from being overriden.
43 obj.parent_send = obj.send;
44 # Put EventChannel methods before BroadcastChannel methods.
45 obj.parents = [EventChannel] ~ obj.parents;
46 obj.events = {};
47 return obj;
48 }
49 EventChannel.register = func (event_hash,
50 handler) {
51 me.events[event_hash] = handler;
52 }
53 EventChannel.deregister = func (event_hash) {
54 delete(me.events, event_hash);
55 }
56 EventChannel.send = func (event_hash,
57 msg) {
58 me.parent_send(event_hash ~ msg);
59 }
60 ############################################################
61 # Internals.
62 EventChannel._process = func (n, msg) {
63 var event_hash = Binary.readHash(msg);
64 if (contains(me.events, event_hash)) {
65 me.events[event_hash](n, substr(msg, Binary.sizeOf["Hash"]));
66 }
67 }
68
69 ###############################################################################
70 # Broadcast primitive using a MP enabled string property.
71 # Broadcasts from users in multiplayer.ignore are ignored.
72 #
73 # BroadcastChannel.new(mpp_path, process)
74 # Create a new broadcast primitive. Any MP user with the same
75 # primitive will receive all messages sent to the channel from the point
76 # she/he joined (barring severe MP packet loss).
77 # NOTE: Message delivery is not guaranteed.
78 # mpp_path - MP property path : string
79 # process - handler called when receiving a message : func (n, msg)
80 # n is the base node of the senders property tree
81 # (i.e. /ai/models/multiplay[x])
82 # send_to_self - if 1 locally sent messages are : int {0,1}
83 # delivered just like remote messages.
84 # If 0 locally sent messages are not delivered
85 # to the local receiver.
86 # accept_predicate - function to select which : func (p)
87 # multiplayers to listen to.
88 # p is the multiplayer entry node.
89 # The default is to accept any multiplayer.
90 # on_disconnect - function to be called when an : func (p)
91 # accepted MP user leaves.
92 # enable_send - Set to 0 to disable sending.
93 #
94 # BroadcastChannel.send(msg)
95 # Sends the message msg to the channel.
96 # msg - text string with Binary data encoded data : string
97 #
98 # BroadcastChannel.die()
99 # Destroy this BroadcastChannel instance.
100 #
101 var BroadcastChannel = {};
102 BroadcastChannel.new = func (mpp_path, process,
103 send_to_self = 0,
104 accept_predicate = nil,
105 on_disconnect = nil,
106 enable_send=1) {
107 var obj = { parents : [BroadcastChannel],
108 mpp_path : mpp_path,
109 send_node : enable_send ? props.globals.getNode(mpp_path, 1)
110 : nil,
111 process_msg : process,
112 send_to_self : send_to_self,
113 accept_predicate :
114 (accept_predicate != nil) ? accept_predicate
115 : func (p) { return 1; },
116 on_disconnect : (on_disconnect != nil) ? on_disconnect
117 : func (p) { return; },
118 # Internal state.
119 started : 0, # External state: started/stopped.
120 running : 0, # Internal state: running or not.
121 send_buf : [],
122 peers : {},
123 loopid : 0,
124 last_time : 0.0, # For join handling.
125 last_send : 0.0 # For the send queue
126 };
127 if (enable_send and (obj.send_node == nil)) {
128 logprint(LOG_WARN, "BroadcastChannel invalid send node.");
129 return nil;
130 }
131 setlistener(obj.ONLINE_pp, func {
132 obj.set_state();
133 });
134 obj.start();
135
136 return obj;
137 }
138 BroadcastChannel.send = func (msg) {
139 if (!me.running or me.send_node == nil)
140 return;
141
142 var t = getprop("/sim/time/elapsed-sec");
143 if (((t - me.last_send) > me.SEND_TIME) and (size(me.send_buf) == 0)) {
144 me.send_node.setValue(msg);
145 me.last_send = t;
146 if (me.send_to_self) me.process_msg(props.globals, msg);
147 } else {
148 append(me.send_buf, msg);
149 }
150 }
151 BroadcastChannel.die = func {
152 me.loopid += 1;
153 me.started = 0;
154 me.running = 0;
155 #print("BroadcastChannel[" ~ me.mpp_path ~ "] ... destroyed.");
156 }
157 BroadcastChannel.start = func {
158 #print("mp_broadcast.nas: starting channel " ~ me.mpp_path ~ ".");
159 me.started = 1;
160 me.set_state();
161 }
162 BroadcastChannel.stop = func {
163 #print("mp_broadcast.nas: stopping channel " ~ me.mpp_path ~ ".");
164 me.started = 0;
165 me.set_state();
166 }
167
168 ############################################################
169 # Internals.
170 BroadcastChannel.ONLINE_pp = "/sim/multiplay/online";
171 BroadcastChannel.PERIOD = 1.3;
172 BroadcastChannel.SEND_TIME = 0.6;
173 BroadcastChannel.set_state = func {
174 if (me.started and getprop(me.ONLINE_pp)) {
175 if (me.running) return;
176 #print("mp_broadcast.nas: activating channel " ~ me.mpp_path ~ ".");
177 me.running = 1;
178 me._loop_(me.loopid += 1);
179 } else {
180 #print("mp_broadcast.nas: deactivating channel " ~ me.mpp_path ~ ".");
181 me.running = 0;
182 me.loopid += 1;
183 }
184 }
185 BroadcastChannel.update = func {
186 var t = getprop("/sim/time/elapsed-sec");
187 var process_msg = me.process_msg;
188
189 # Handled join/leave. This is done more seldom.
190 if ((t - me.last_time) > me.PERIOD) {
191 var mpplayers =
192 props.globals.getNode("/ai/models").getChildren("multiplayer");
193 foreach (var pilot; mpplayers) {
194 var valid = pilot.getChild("valid");
195 if ((valid != nil) and valid.getValue() and
196 !contains(multiplayer.ignore,
197 pilot.getChild("callsign").getValue())) {
198 if ((me.peers[pilot.getIndex()] == nil) and
199 me.accept_predicate(pilot)) {
200 me.peers[pilot.getIndex()] =
201 MessageChannel.
202 new(pilot.getNode(me.mpp_path),
203 MessageChannel.new_message_handler(process_msg, pilot));
204 }
205 } else {
206 if (contains(me.peers, pilot.getIndex())) {
207 delete(me.peers, pilot.getIndex());
208 me.on_disconnect(pilot);
209 }
210 }
211 }
212 me.last_time = t;
213 }
214 # Process new messages.
215 foreach (var w; keys(me.peers)) {
216 if (me.peers[w] != nil) me.peers[w].update();
217 }
218 # Check send buffer.
219 if (me.send_node == nil) return;
220
221 if ((t - me.last_send) > me.SEND_TIME) {
222 if (size(me.send_buf) > 0) {
223 me.send_node.setValue(me.send_buf[0]);
224 if (me.send_to_self) me.process_msg(props.globals, me.send_buf[0]);
225 me.send_buf = subvec(me.send_buf, 1);
226 me.last_send = t;
227 } else {
228 # Nothing new to send. Reset the send property to save bandwidth.
229 me.send_node.setValue("");
230 }
231 }
232 }
233 BroadcastChannel._loop_ = func (id) {
234 me.running or return;
235 id == me.loopid or return;
236
237 #print("mp_broadcast.nas: " ~ me.mpp_path ~ ":" ~ id ~ ".");
238 me.update();
239 settimer(func { me._loop_(id); }, 0, 1);
240 }
241 ######################################################################
242
243 ###############################################################################
244 # Lamport clock. Useful for creating a total order for events or messages.
245 # The users' callsigns are used to break ties.
246 #
247 # LamportClock.new()
248 # Creates a new lamport clock for this user.
249 #
250 # LamportClock.merge(sender, sender_timestamp)
251 # Merges the timestamp from the sender with the local clock.
252 # sender : base node of the senders property tree
253 # sender_timestamp : the timestamp received from the sender.
254 # Returns 1 if the local clock was advanced; 0 otherwise.
255 #
256 # LamportClock.advance()
257 # Advances the local clock one tick.
258 #
259 # LamportClock.timestamp()
260 # Returns an encoded 4 character long timestamp from the local clock.
261 #
262 var LamportClock = {
263 # LamportClock.new()
264 # Creates a new lamport clock for this user.
265 new : func {
266 var obj = {
267 parents : [LamportClock],
268 callsign : getprop("/sim/multiplay/callsign"),
269 time : 0
270 };
271 return obj;
272 },
273 merge : func (sender, sender_timestamp) {
274 var sender_time = Binary.decodeInt28(sender_timestamp);
275 if (sender_time > me.time) {
276 me.time = sender_time;
277 return 1;
278 } elsif ((sender_time == me.time) and
279 (cmp(sender.getNode("callsign").getValue(), me.callsign) > 0)) {
280 return 1;
281 } else {
282 # The received timestamp is old and should be ignored.
283 return 0;
284 }
285 },
286 advance : func {
287 me.time += 1;
288 },
289 timestamp : func {
290 return Binary.encodeInt28(me.time);
291 }
292 };
293
294
295 ###############################################################################
296 # Some routines for encoding/decoding values into/from a string.
297 # NOTE: MP is picky about what it sends in a string propery.
298 # Encode 7 bits as a printable 8 bit character.
299 var Binary = {};
300 Binary.TWOTO27 = 134217728;
301 Binary.TWOTO28 = 268435456;
302 Binary.TWOTO31 = 2147483648;
303 Binary.TWOTO32 = 4294967296;
304 Binary.sizeOf = {};
305 ############################################################
306 Binary.sizeOf["int"] = 5;
307 Binary.encodeInt = func (int) {
308 var bf = bits.buf(5);
309 if (int < 0) int += Binary.TWOTO32;
310 var r = int;
311 for (var i = 0; i < 5; i += 1) {
312 var c = math.mod(r, 128);
313 bf[4-i] = c + `A`;
314 r = (r - c)/128;
315 }
316 return bf;
317 }
318 ############################################################
319 Binary.decodeInt = func (str) {
320 var v = 0;
321 var b = 1;
322 for (var i = 0; i < 5; i += 1) {
323 v += (str[4-i] - `A`) * b;
324 b *= 128;
325 }
326 if (v / Binary.TWOTO31 >= 1) v -= Binary.TWOTO32;
327 return int(v);
328 }
329 ############################################################
330 # NOTE: This encodes a 7 bit byte.
331 Binary.sizeOf["byte"] = 1;
332 Binary.encodeByte = func (int) {
333 var bf = bits.buf(1);
334 if (int < 0) int += 128;
335 bf[0] = math.mod(int, 128) + `A`;
336 return bf;
337 }
338 ############################################################
339 Binary.decodeByte = func (str) {
340 var v = str[0] - `A`;
341 if (v / 64 >= 1) v -= 128;
342 return int(v);
343 }
344 ############################################################
345 # NOTE: This encodes a 28 bit integer.
346 Binary.sizeOf["int28"] = 4;
347 Binary.encodeInt28 = func (int) {
348 var bf = bits.buf(4);
349 if (int < 0) int += Binary.TWOTO32;
350 var r = int;
351 for (var i = 0; i < 4; i += 1) {
352 var c = math.mod(r, 128);
353 bf[3-i] = c + `A`;
354 r = (r - c)/128;
355 }
356 return bf;
357 }
358 ############################################################
359 Binary.decodeInt28 = func (str) {
360 var v = 0;
361 var b = 1;
362 for (var i = 0; i < 4; i += 1) {
363 v += (str[3-i] - `A`) * b;
364 b *= 128;
365 }
366 if (v / Binary.TWOTO27 >= 1) v -= Binary.TWOTO28;
367 return int(v);
368 }
369 ############################################################
370 # NOTE: This can neither handle huge values nor really tiny.
371 Binary.sizeOf["double"] = 2*Binary.sizeOf["int"];
372 Binary.encodeDouble = func (d) {
373 return Binary.encodeInt(int(d)) ~
374 Binary.encodeInt((d - int(d)) * Binary.TWOTO31);
375 }
376 ############################################################
377 Binary.decodeDouble = func (str) {
378 return Binary.decodeInt(substr(str, 0)) +
379 Binary.decodeInt(substr(str, 5)) / Binary.TWOTO31;
380 }
381 ############################################################
382 # Encodes a geo.Coord object.
383 Binary.sizeOf["Coord"] = 3*Binary.sizeOf["double"];
384 Binary.encodeCoord = func (coord) {
385 return Binary.encodeDouble(coord.lat()) ~
386 Binary.encodeDouble(coord.lon()) ~
387 Binary.encodeDouble(coord.alt());
388 }
389 ############################################################
390 # Decodes an encoded geo.Coord object.
391 Binary.decodeCoord = func (str) {
392 var coord = geo.aircraft_position();
393 coord.set_latlon(Binary.decodeDouble(substr(str, 0)),
394 Binary.decodeDouble(substr(str, 10)),
395 Binary.decodeDouble(substr(str, 20)));
396 return coord;
397 }
398 ############################################################
399 # Encodes a string as a hash value.
400 Binary.sizeOf["Hash"] = 4;
401 Binary.stringHash = func (str) {
402 var hash = 0;
403 for(var i=0; i<size(str); i+=1) {
404 hash += math.mod(32*hash + str[i], Binary.TWOTO28-3);
405 }
406 return substr(Binary.encodeInt(hash), 1, 4);
407 }
408 ############################################################
409 # Decodes an encoded geo.Coord object.
410 Binary.readHash = func (str) {
411 return substr(str, 0, Binary.sizeOf["Hash"]);
412 }
413 ############################################################
414 Binary.sizeOf["LamportTS"] = 4;
415 ######################################################################
416
417 ###############################################################################
418 # Detects incomming messages encoded in a string property.
419 # n - MP source : property node
420 # process - action : func (v)
421 # NOTE: This is a low level component.
422 # The same object is seldom used for both sending and receiving.
423 var MessageChannel = {};
424 MessageChannel.new = func (n = nil, process = nil) {
425 var obj = { parents : [MessageChannel],
426 node : n,
427 process_msg : process,
428 old : "" };
429 return obj;
430 }
431 MessageChannel.update = func {
432 if (me.node == nil) return;
433
434 var msg = me.node.getValue();
435 if (!streq(typeof(msg), "scalar")) return;
436
437 if ((me.process_msg != nil) and
438 !streq(msg, "") and
439 !streq(msg, me.old)) {
440 me.process_msg(msg);
441 me.old = msg;
442 }
443 }
444 MessageChannel.send = func (msg) {
445 me.node.setValue(msg);
446 }
447 MessageChannel.new_message_handler = func (handler, arg1) {
448 var local_arg1 = arg1; # Disconnect from future changes to arg1.
449 return func (msg) { handler(local_arg1, msg) };
450 };