-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_vwf.js
1671 lines (1414 loc) · 44.3 KB
/
node_vwf.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
global.version = 23;
var libpath = require('path'),
http = require("http"),
fs = require('fs'),
url = require("url"),
mime = require('mime'),
sio = require('socket.io'),
YAML = require('js-yaml'),
SandboxAPI = require('./sandboxAPI'),
Shell = require('./ShellInterface'),
DAL = require('./DAL'),
express = require('express'),
app = express(),
Landing = require('./landingRoutes');
var zlib = require('zlib');
var requirejs = require('requirejs');
var compressor = require('node-minify');
//Get the version number. This will used to redirect clients to the proper url, to defeat their local cache when we release
global.version = require('./Version').version;
var appNameCache = [];
// pick the application name out of the URL by finding the index.vwf.yaml
// Cache - this means that adding applications to the server will requrie a restart
function findAppName(uri)
{
var current = "."+libpath.sep;
var testcache = (current + uri);
//cache and avoid some sync directory operations
for(var i =0; i < appNameCache.length; i++)
{
if(testcache.indexOf(appNameCache[i]) ==0)
{
return appNameCache[i];
}
}
while(!fs.existsSync(current+"index.vwf.yaml"))
{
var next = uri.substr(0,Math.max(uri.indexOf('/'),uri.indexOf('\\'))+1);
current += next;
if(!next)
break;
uri = uri.substr(next.length);
}
if(fs.existsSync(current+"index.vwf.yaml"))
{
appNameCache.push(current);
return current;
}
return null;
}
//Generate a random ID for a instance
var ValidIDChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
global.error = function()
{
var red, brown, reset;
red = '\u001b[31m';
brown = '\u001b[33m';
reset = '\u001b[0m';
var args = Array.prototype.slice.call(arguments);
args[0] = red + args[0] + reset;
var level = args.splice(args.length-1)[0];
if(!isNaN(parseInt(level)))
{
level = parseInt(level);
}
else
{
args.push(level)
level = 1;
};
if(level <= global.logLevel)
console.log.apply(this,args);
}
global.log = function()
{
var args = Array.prototype.slice.call(arguments);
var level = args.splice(args.length-1)[0];
if(!isNaN(parseInt(level)))
{
level = parseInt(level);
}
else
{
args.push(level)
level = 1;
};
if(level <= global.logLevel)
console.log.apply(this,args);
}
//amke a random VWF Instance id
function makeid()
{
var text = "";
for( var i=0; i < 16; i++ )
text += ValidIDChars.charAt(Math.floor(Math.random() * ValidIDChars.length));
return text;
}
var WaitingForConnection = 0;
var Active = 1;
var Dead = 2;
function instance(inid)
{
this.id = inid;
this.state = WaitingForConnection;
this.clients = 0;
}
//Redirect the user to a new instance
function RedirectToInstance(request,response,appname,newid)
{
if(newid === undefined)
newid = makeid() + "/";
var query = (url.parse(request.url).query) || "";
if(query)
{
query = '?'+query;
newid += query;
}
var path = url.parse(request.url).pathname;
if(path[path-1] != '/')
newid = path.substr(path.indexOf('/')) + '/' + newid;
newid = newid.replace(/\/\//g,'/');
newid = newid.replace(/\/\/\//g,'/');
redirect(newid,response);
}
//Redirect, just used on some invalid paths
function redirect(url,response)
{
url = url.replace(/\\\\/g,'/');
url = url.replace(/\\/g,'/');
url = url.replace(/\/\//g,'/');
url = url.replace(/\/\/\//g,'/');
//url = url.replace('http://','');
url = url.replace(/\/\/\//g,"/");
url = url.replace(/\/\/\/\//g,"/");
//url = 'http://' + url;
response.writeHead(200, {
"Content-Type": "text/html"
});
response.write( "<html>" +
"<head>" +
" <title>Virtual World Framework</title>" +
" <meta http-equiv=\"REFRESH\" content=\"0;url="+url+"\">" +
"</head>" +
"<body>" +
"</body>" +
"</html>");
response.end();
return;
}
//Find the instance(instance) ID in a URL
function Findinstance(uri)
{
//find the application name
var app = findAppName(uri);
if(!app)
return null;
//remove the application name
var minusapp = uri.substr(app.length-2);
var parts = minusapp.split(libpath.sep);
var testapp = parts[0];
//Really, any slash delimited string after the app name should work
//sticking with 16 characters for now
if(testapp.length == 16)
{
for(var i = 0; i < 16; i++)
{
if(ValidIDChars.indexOf(testapp[i]) == -1)
return null;
}
return testapp;
}
return null;
}
//Remove the instance identifer from the URL
function filterinstance(uri,instance)
{
return uri.replace(instance+libpath.sep,'').replace(instance,libpath.sep);
}
function hash(str)
{
return require('crypto').createHash('md5').update(str).digest("hex");
}
function _FileCache()
{
this.files = [];
this.enabled = true;
this.clear = function()
{
this.files.length = 0;
}
this.getDataType = function(file)
{
var type = file.substr(file.lastIndexOf('.')+1).toLowerCase();
if(type === 'js' || type === 'html' || type === 'xml' || type === 'txt' || type === 'xhtml' || type === 'css')
{
return "utf8";
}
else return "binary";
}
//Get the file entry, or load it
this.getFile = function(path,callback)
{
path = libpath.normalize(path);
path = libpath.resolve(__dirname, path);
//Cannot escape above the application paths!!!!
if(path.toLowerCase().indexOf(__dirname.toLowerCase()) != 0 && path.toLowerCase().indexOf(global.datapath.toLowerCase()) != 0)
{
global.error(path + " is illegal");
callback(null);
return;
}
//Cannot have the users.db!
if(path.toLowerCase().indexOf('users.db') != -1)
{
global.error(path + " is illegal");
callback(null);
return;
}
//Find the record
for(var i =0; i < this.files.length; i++)
{
if(this.files[i].path == path)
{
global.log('serving from cache: ' + path,2);
//Callback with the record
callback(this.files[i]);
return;
}
}
// if got here, have no record;
var datatype = this.getDataType(path);
//Read the raw file
fs.readFile(path,function(err,file){
fs.stat(path,function(err,stats)
{
var self = this;
//Call this after minify, or right away if not js or minify disabled
var preMin = function(file)
{
if(file)
{
//gzip the data
zlib.gzip(file,function(_,zippeddata)
{
//record the data
var newentry = {};
newentry.path = path;
newentry.data = file;
newentry.stats = stats;
newentry.zippeddata = zippeddata;
newentry.datatype = datatype;
newentry.hash = hash(file);
global.log(newentry.hash,2);
global.log('loading into cache: ' + path,2);
// if enabled, cache in memory
if(FileCache.enabled == true)
{
global.log('cache ' + path,2);
FileCache.files.push(newentry);
//minify is currently not compatable with auto-watch of files
if(!FileCache.minify)
{
//reload files that change on disk
fs.watch(path,{},function(event,filename){
global.log(newentry.path + ' has changed on disk',2);
FileCache.files.splice(FileCache.files.indexOf(newentry),1);
});
}
}
//send the record to the caller . Usually FileCache.serveFile
callback(newentry);
return;
});
return;
}
callback(null);
}
//Send right away if not minifying
if(!FileCache.minify)
{
preMin(file);
}
else
{
//if minifying and ends with js
if(strEndsWith(path,'js'))
{
//compress the JS then gzip and save the results
console.log('minify ' + path);
new compressor.minify({
type: 'uglifyjs',
fileIn: path,
fileOut: path+'_min.js',
callback: function(err, min){
if(err)
preMin(file)
else
{
//remove the file on disk - cached in memory
fs.unlinkSync(path+'_min.js');
//completed minify, go ahead and cache and serve
preMin(min);
}
}
});
}
// likewise, try to minify the css
else if(strEndsWith(path,'css'))
{
//compress the css then gzip and save the results
console.log('minify ' + path);
new compressor.minify({
type: 'yui-css',
fileIn: path,
fileOut: path+'_min.css',
callback: function(err, min){
if(err)
preMin(file)
else
{
//remove the file on disk - cached in memory
fs.unlinkSync(path+'_min.css');
//completed minify, go ahead and cache and serve
preMin(min);
}
}
});
}else
{
//minifying, but not a file that can minify
preMin(file);
}
}
});
});
} // end getFile
//Serve a file, takes absolute path
//TODO, handle streaming of audio and video
this.ServeFile = function(request,filename,response,URL)
{
//check if already loaded
FileCache.getFile(filename,function(file)
{
//error if not found
if (!file) {
response.writeHead(500, {
"Content-Type": "text/plain"
});
response.write('file load error' + "\n");
response.end();
return;
}
//get the type
var type = mime.lookup(filename);
//deal with the ETAG
if(request.headers['if-none-match'] === file.hash)
{
response.writeHead(304, {
"Content-Type": type,
"Last-Modified": file.stats.mtime,
"ETag": file.hash,
"Cache-Control":"public; max-age=31536000" ,
});
response.end();
return;
}
//If the clinet can take the gzipped encoding, send that
if(request.headers['accept-encoding'] && request.headers['accept-encoding'].indexOf('gzip') >= 0)
{
response.writeHead(200, {
"Content-Type": type,
"Last-Modified": file.stats.mtime,
"ETag": file.hash,
"Cache-Control":"public; max-age=31536000" ,
'Content-Encoding': 'gzip'
});
response.write(file.zippeddata, file.datatype);
}
//if the client cannot accept the gzip, send raw
else
{
response.writeHead(200, {
"Content-Type": type,
"Last-Modified": file.stats.mtime,
"ETag": file.hash,
"Cache-Control":"public; max-age=31536000"
});
response.write(file.data, file.datatype);
}
response.end();
});
}
} //end FileCache
var FileCache = new _FileCache();
global.FileCache = FileCache;
//Just serve a simple file
function ServeFile(request,filename,response,URL)
{
FileCache.ServeFile(request,filename,response,URL)
}
//Return a 404 not found coude
function _404(response)
{
response.writeHead(404, {
"Content-Type": "text/plain",
"Access-Control-Allow-Origin": "*"
});
response.write("404 Not Found\n");
response.end();
}
//Parse and serve a YAML file
function ServeYAML(filename,response, URL)
{
var tf = filename;
fs.readFile(filename, "utf8", function (err, file) {
if (err) {
response.writeHead(500, {
"Content-Type": "text/plain"
});
response.write(err + "\n");
response.end();
return;
}
//global.log(tf);
try{
var deYAML = JSON.stringify(YAML.load(file));
}catch(e)
{
global.log("error parsing YAML " + filename );
_404(response);
return;
}
var type = "text/json";
var callback = URL.query.callback;
if(callback)
{
deYAML = callback+"(" + deYAML + ")";
type = "application/javascript";
}
response.writeHead(200, {
"Content-Type": type
});
response.write(deYAML, "utf8");
response.end();
});
}
//Serve a JSON object
function ServeJSON(jsonobject,response,URL)
{
response.writeHead(200, {
"Content-Type": "text/json"
});
response.write(JSON.stringify(jsonobject), "utf8");
response.end();
}
//Get the instance ID from the handshake headers for a socket
function getNamespace(socket)
{
try{
var referer = (socket.handshake.headers.referer);
var index = referer.indexOf('/adl/sandbox');
var namespace = referer.substring(index);
if(namespace[namespace.length-1] != "/")
namespace += "/";
return namespace;
}catch(e)
{
return null;
}
}
//Check that a user has permission on a node
function checkOwner(node,name)
{
var level = 0;
if(!node.properties) node.properties = {};
if(!node.properties.permission) node.properties.permission = {}
var permission = node.properties['permission'];
var owner = node.properties['owner'];
if(owner == name)
{
level = Infinity;
return level;
}
if(permission)
{
level = Math.max(level?level:0,permission[name]?permission[name]:0,permission['Everyone']?permission['Everyone']:0);
}
var parent = node.parent;
if(parent)
level = Math.max(level?level:0,checkOwner(parent,name));
return level?level:0;
}
//***node, uses REGEX, escape properly!
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
//Is an event in the websocket stream a mouse event?
function isPointerEvent(message)
{
if(!message) return false;
if(!message.member) return false;
return (message.member == 'pointerMove' ||
message.member == 'pointerHover' ||
message.member == 'pointerEnter' ||
message.member == 'pointerLeave' ||
message.member == 'pointerOver' ||
message.member == 'pointerOut' ||
message.member == 'pointerUp' ||
message.member == 'pointerDown' ||
message.member == 'pointerWheel'
)
}
//change up the ID of the loaded scene so that they match what the client will have
var fixIDs = function(node)
{
if(node.children)
var childnames = {};
for(var i in node.children)
{
childnames[i] = null;
}
for(var i in childnames)
{
var childComponent = node.children[i];
var childName = childComponent.name || i;
var childID = childComponent.id || childComponent.uri || ( childComponent["extends"] ) + "." + childName.replace(/ /g,'-');
childID = childID.replace( /[^0-9A-Za-z_]+/g, "-" );
childComponent.id = childID;
node.children[childID] = childComponent;
node.children[childID].parent = node;
delete node.children[i];
fixIDs(childComponent);
}
}
//Start the VWF HTTP server
function startVWF(){
global.activeinstances = [];
function OnRequest(request, response)
{
try{
var safePathRE = RegExp('/\//'+(libpath.sep=='/' ? '\/' : '\\')+'/g');
var path = "./public".replace(safePathRE);
var URL = url.parse(request.url,true);
var uri = URL.pathname.replace(safePathRE);
//global.log( URL.pathname );
if(URL.pathname.toLowerCase().indexOf('/vwfdatamanager.svc/') != -1)
{
//Route to DataServer
SandboxAPI.serve(request,response);
return;
}
if(URL.pathname == '/' || URL.pathname == '')
{
redirect('/adl/sandbox/',response);
return;
}
var filename = libpath.join(path, uri);
var instance = Findinstance(filename);
//global.log(instance);
//remove the instance identifier from the request
filename = filterinstance(filename,instance);
//obey some old VWF URL formatting
if(uri.indexOf('/admin/'.replace(safePathRE)) != -1)
{
//gets a list of all active sessions on the server, and all clients
if(uri.indexOf('/admin/instances'.replace(safePathRE)) != -1)
{
var data = {};
for(var i in global.instances)
{
data[i] = {clients:{}};
for(var j in global.instances[i].clients)
{
data[i].clients[j] = null;
}
}
ServeJSON(data,response,URL);
return;
}
}
//file is not found - serve index or map to support files
//file is also not a yaml document
var c1;
var c2;
//global.log(filename);
libpath.exists(filename,function(c1){
libpath.exists(filename+".yaml",function(c2){
if(!c1 && !c2)
{
//try to find the correct support file
var appname = findAppName(filename);
if(!appname)
{
filename = filename.substr(13);
filename = "./support/".replace(safePathRE) + filename;
filename = filename.replace('vwf.example.com','proxy/vwf.example.com');
}
else
{
filename = filename.substr(appname.length-2);
if(appname == "")
filename = './support/client/lib/index.html'.replace(safePathRE);
else
filename = './support/client/lib/'.replace(safePathRE) + filename;
}
}
//file does exist, serve normally
libpath.exists(filename,function(c3){
libpath.exists(filename +".yaml",function(c4){
if(c3)
{
//if requesting directory, setup instance
//also, redirect to current instnace name of does not end in slash
fs.stat(filename,function(err,isDir)
{
if (isDir.isDirectory())
{
var appname = findAppName(filename);
if(!appname)
appname = findAppName(filename+libpath.sep);
//no instance id is given, new instance
if(appname && instance == null)
{
//GenerateNewInstance(request,response,appname);
redirect(URL.pathname+"/index.html",response);
//console.log('redirect ' + appname+"./index.html");
return;
}
//instance needs to end in a slash, so redirect but keep instance id
if(appname && strEndsWith(URL.pathname,instance))
{
RedirectToInstance(request,response,appname,"");
return;
}
//no app name but is directory. Not listing directories, so 404
if(!appname)
{
_404(response);
return;
}
//this is the bootstrap html. Must have instnace and appname
filename = './support/client/lib/index.html'.replace(safePathRE);
//when loading the bootstrap, you must have an instance that exists in the database
global.log('Appname:', appname);
var instanceName = appname.substr(8).replace(/\//g,'_').replace(/\\/g,'_') + instance + "_";
DAL.getInstance(instanceName,function(data)
{
if(data)
ServeFile(request,filename,response,URL);
else {
redirect(filterinstance(URL.pathname,instance)+"/index.html",response);
}
});
return;
}
//just serve the file
ServeFile(request,filename,response,URL);
});
}
else if(c4)
{
//was not found, but found if appending .yaml. Serve as yaml
ServeYAML(filename +".yaml",response,URL);
}
// is an admin call, currently only serving instances
else
{
global.log("404 : " + filename)
_404(response);
return;
}
});
});
});
});
}
catch(e)
{
response.writeHead(500, {
"Content-Type": "text/plain"
});
response.write(e.toString(), "utf8");
response.end();
}
} // close onRequest
function WebSocketConnection(socket, _namespace) {
//get instance for new connection
var namespace = _namespace || getNamespace(socket);
if(!namespace)
{
socket.on('setNamespace',function(msg)
{
console.log(msg.space);
WebSocketConnection(socket,msg.space);
socket.emit('namespaceSet',{});
});
return;
}else
{
console.log(namespace);
}
//create or setup instance data
if(!global.instances)
global.instances = {};
//if it's a new instance, setup record
if(!global.instances[namespace])
{
global.instances[namespace] = {};
global.instances[namespace].clients = {};
global.instances[namespace].time = 0.0;
global.instances[namespace].state = {};
//create or open the log for this instance
var log = fs.createWriteStream(SandboxAPI.getDataPath()+'//Logs/'+namespace.replace(/[\\\/]/g,'_'), {'flags': 'a'});
global.instances[namespace].Log = function(message,level)
{
if(global.logLevel >= level)
{
log.write(message +'\n');
global.log(message +'\n');
}
}
global.instances[namespace].Error = function(message,level)
{
var red, brown, reset;
red = '\u001b[31m';
brown = '\u001b[33m';
reset = '\u001b[0m';
if(global.logLevel >= level)
{
log.write(message +'\n');
global.log(red + message + reset + '\n');
}
}
global.instances[namespace].totalerr = 0;
//keep track of the timer for this instance
global.instances[namespace].timerID = setInterval(function(){
var now = process.hrtime();
now = now[0] * 1e9 + now[1];
now = now/1e9;
var timedelta = (now - global.instances[namespace].lasttime) || 0;
var timeerr = (timedelta - .050)*1000;
global.instances[namespace].lasttime = now;
global.instances[namespace].totalerr += timeerr;
global.instances[namespace].time += .05;
for(var i in global.instances[namespace].clients)
{
var client = global.instances[namespace].clients[i];
if(!client.pending)
client.emit('message',{"action":"tick","parameters":[],"time":global.instances[namespace].time});
else
{
client.pendingList.push({"action":"tick","parameters":[],"time":global.instances[namespace].time});
console.log('pending tick');
}
}
},50);
}
var loadClient = null;
if(Object.keys(global.instances[namespace].clients).length != 0)
{
for(var i in global.instances[namespace].clients)
{
var testClient = global.instances[namespace].clients[i];
if(!testClient.pending && testClient.loginData)
{
loadClient = testClient;
break;
}
}
}
//add the new client to the instance data
global.instances[namespace].clients[socket.id] = socket;
socket.pending = true;
socket.pendingList = [];
//The client is the first, is can just load the index.vwf, and mark it not pending
if(!loadClient)
{
console.log('load from db');
//socket.emit('message',{"action":"getState","respond":true,"time":global.instances[namespace].time});
var instance = namespace;
//Get the state and load it.
//Now the server has a rough idea of what the simulation is
var state = SandboxAPI.getState(instance) || [{owner:undefined}];
var state2 = SandboxAPI.getState(instance) || [{owner:undefined}];
global.instances[namespace].state = {nodes:{}};
global.instances[namespace].state.nodes['index-vwf'] = {id:"index-vwf",properties:state[state.length-1],children:{}};
global.instances[namespace].state.findNode = function(id,parent)
{
var ret = null;
if(!parent) parent = this.nodes['index-vwf'];
if(parent.id == id)
ret = parent;
else if(parent.children)
{
for(var i in parent.children)
{
ret = this.findNode(id, parent.children[i]);
if(ret) return ret;
}
}
return ret;
}
global.instances[namespace].state.deleteNode = function(id,parent)
{
if(!parent) parent = this.nodes['index-vwf'];
if(parent.children)
{
for(var i in parent.children)
{
if( i == id)
{
delete parent.children[i];
return
}
}
}
}
fs.readFile("./public/adl/sandbox/index.vwf.yaml", 'utf8',function(err,blankscene)
{
blankscene= YAML.load(blankscene);
blankscene.id = 'index-vwf';
blankscene.patches= "index.vwf";
if(!blankscene.children)
blankscene.children = {};
//only really doing this to keep track of the ownership
for(var i =0; i < state.length-1; i++)
{
var childComponent = state[i];
var childName = state[i].name || state[i].properties.DisplayName + i;
var childID = childComponent.id || childComponent.uri || ( childComponent["extends"] ) + "." + childName.replace(/ /g,'-');
childID = childID.replace( /[^0-9A-Za-z_]+/g, "-" );
//state[i].id = childID;
//state2[i].id = childID;
blankscene.children[childName] = state2[i];
state[i].id = childID;
global.instances[namespace].state.nodes['index-vwf'].children[childID] = state[i];
global.instances[namespace].state.nodes['index-vwf'].children[childID].parent = global.instances[namespace].state.nodes['index-vwf'];
fixIDs(state[i]);
}
var props = state[state.length-1];
if(props)
{
if(!blankscene.properties)
blankscene.properties = {};
for(var i in props)
{
blankscene.properties[i] = props[i];
}
for(var i in blankscene.properties)
{
if( blankscene.properties[i] && blankscene.properties[i].value)
blankscene.properties[i] = blankscene.properties[i].value;
else if(blankscene.properties[i] && (blankscene.properties[i].get || blankscene.properties[i].set))
delete blankscene.properties[i];
}
}
//global.log(Object.keys(global.instances[namespace].state.nodes['index-vwf'].children));
//this is a blank world, go ahead and load the default