-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
4031 lines (3177 loc) · 116 KB
/
index.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 globalThis, process, fs, mime, sdWorld, sdEntity, sdModeration, sdShop, sdSnapPack, sdPathFinding, sdDatabase, Buffer, Infinity, sdServerConfigFull, sdInterface, sdLongRangeTeleport, sdServerToServerProtocol, sdCharacter, sdDeepSleep, sdPlayerSpectator, sdStorage, os, sdGun, sdMemoryLeakSeeker, zlib, Promise, sdDictionaryWords, sdSound, LZW, sdEffect, sdTask, WorkerServiceLogic, await, imported, FakeCanvasContext, Server, geckos, https, spawn, http */
let port0 = 3000;
let CloudFlareSupport = false;
let directory_to_save_player_count = null;
/*
Memory usage tracking:
globalThis.inter = setInterval( ()=>{ trace( 'heapTotal: ' + process.memoryUsage().heapTotal ); }, 1000 * 60 );
*/
globalThis.CATCH_HUGE_ARRAYS = false; // Can worsen performance by 2-5%
// http://localhost:3000 + world_slot
// CentOS crontab can be here: /etc/crontab
/*
TODO:
- This could help for high latency cases: https://github.com/geckosio/geckos.io // Actually not that much, main server's low bandwidth is low bandwidth
*/
/*
What to do:
Give progression + purpose to the game
- Vehicles for deeper digging, make shovels less efficient
- Crates? Presets with rare items and entities?
*/
// Early error catching
//console.log('Early error catching enabled, waiting 10 seconds before doing anything...');
//await new Promise(resolve => setTimeout(resolve, 10000)); // Unexpected reserved word
//import heapdump from 'heapdump';
//import ofe from 'ofe';
import zlib from 'zlib';
import _app from 'express';
const app = _app();
import path from 'path';
import fs from 'fs';
globalThis.fs = fs;
import { spawn } from 'child_process';
globalThis.child_process_spawn = spawn;
//import { createServer } from "http";
import http from "http";
import https from "https";
import mime from "mime";
//import pkg from '@geckos.io/server'; //
//const geckos = pkg.default;
import { Server } from "socket.io";
import { Worker } from "worker_threads";
import WorkerServiceLogic from './game/server/worker_service_logic.js';
globalThis.WorkerServiceLogic = WorkerServiceLogic;
const SOCKET_IO_MODE = ( typeof Server !== 'undefined' ); // In else case geckos.io
globalThis.SOCKET_IO_MODE = SOCKET_IO_MODE;
const httpServer = http.createServer( app );
let httpsServer = null;
var isWin = process.platform === "win32";
globalThis.isWin = isWin;
globalThis.trace = console.log;
{
let spoken = new Set();
globalThis.traceOnce = ( ...args )=>
{
let str = args.join(' ');
if ( !spoken.has( str ) )
{
spoken.add( str );
trace( ...args );
}
};
}
globalThis.T = ( s )=>s; // Server won't translate anything
if ( !isWin )
{
let ssl_key_path;
let ssl_cert_path;
let ssl = true;
if ( fs.existsSync( 'sslconfig.json' ) )
{
try
{
const data = fs.readFileSync( './sslconfig.json', 'utf8' );
// parse JSON string to JSON object
const sslconfig = JSON.parse( data );
ssl_cert_path = sslconfig.certpath;
ssl_key_path = sslconfig.keypath;
}
catch (err)
{
console.log(`Error reading file from disk: ${ err }`);
}
}
else
{
if ( fs.existsSync('/usr/') &&
fs.existsSync('/usr/local/') &&
fs.existsSync('/usr/local/directadmin/') &&
fs.existsSync('/usr/local/directadmin/data/') &&
fs.existsSync('/usr/local/directadmin/data/users/') &&
fs.existsSync('/usr/local/directadmin/data/users/admin/') &&
fs.existsSync('/usr/local/directadmin/data/users/admin/domains/') )
{
ssl_key_path = '/usr/local/directadmin/data/users/admin/domains/gevanni.com.key';
ssl_cert_path = '/usr/local/directadmin/data/users/admin/domains/gevanni.com.cert';
}
else
if ( fs.existsSync('/var/') &&
fs.existsSync('/var/cpanel/') &&
fs.existsSync('/var/cpanel/ssl/') &&
fs.existsSync('/var/cpanel/ssl/apache_tls/') &&
fs.existsSync('/var/cpanel/ssl/apache_tls/plazmaburst2.com/') )
{
ssl_key_path = '/var/cpanel/ssl/apache_tls/plazmaburst2.com/combined';
ssl_cert_path = '/var/cpanel/ssl/apache_tls/plazmaburst2.com/combined'; // '/var/cpanel/ssl/apache_tls/plazmaburst2.com/certificates';
port0 = 8443;
CloudFlareSupport = true;
directory_to_save_player_count = '/home/plazmaburst2/public_html/pb2/sd2d_online.v';
}
else
{
// For replit.com-like hosts, they apparently handle all that by themselves
ssl = false;
}
}
if ( ssl )
{
const credentials = {
key: fs.readFileSync( ssl_key_path ),
cert: fs.readFileSync( ssl_cert_path )
};
httpsServer = https.createServer( credentials, app ); // https version
setInterval(()=>{
//console.log( httpsServer.key, httpsServer.cert );
httpsServer.key = fs.readFileSync( ssl_key_path );
httpsServer.cert = fs.readFileSync( ssl_cert_path );
}, 2147483647 );
}
}
// process.cwd() - current working directory
// require.main.paths[0].split('node_modules')[0].slice(0, -1) - ?
let script_path_id = -1;
let script_path_id_alter = -1;
for ( let i = 0; i < process.argv.length; i++ )
{
if ( script_path_id === -1 )
if ( process.argv[ i ].indexOf( 'index.js' ) !== -1 )
script_path_id = i;
if ( script_path_id_alter === -1 )
if ( process.argv[ i ].indexOf( '.js' ) !== -1 )
script_path_id_alter = i;
if ( script_path_id !== -1 )
if ( script_path_id_alter !== -1 )
break;
}
if ( script_path_id === -1 )
script_path_id = script_path_id_alter;
if ( script_path_id === -1 )
{
throw new Error('I have no idea where application folder is... Could not find index.js (or any else .js) in process.argv variable, which is: ', process.argv );
}
let full_path = process.argv[ script_path_id ];
let __dirname;
if ( isWin )
{
__dirname = full_path.split( '\\' );
__dirname[ __dirname.length - 1 ] = '';
__dirname = __dirname.join( '\\' );
}
else
{
__dirname = full_path.split( '/' );
__dirname[ __dirname.length - 1 ] = '';
__dirname = __dirname.join( '/' );
}
//console.log( '__dirname = ' + __dirname );
//throw new Error('manual stop');
/*
const __dirname = ( isWin ) ?
path.resolve()
:
'/home/admin/sd2d/';*/
globalThis.sdServerToServerProtocol = sdServerToServerProtocol;
let io;
if ( SOCKET_IO_MODE ) // Socket.io
{
io = new Server( httpsServer ? httpsServer : httpServer, {
// ...
pingInterval: 30000,
pingTimeout: 15000,
maxHttpBufferSize: 1024 * 1024, // 2048 was good for player-to-server connections but not for server-to-server protocol // 1024 // 512 is minimum that works (but lacks long-name support on join)
perMessageDeflate: {
threshold: 1024
}, // Promised to be laggy but with traffic bottlenecking it might be the only way (and nature of barely optimized network snapshots)
httpCompression: {
threshold: 1024
}
//transports: [ 'websocket' ] // Trying to disable polling one, maybe this will work better?
});
}
else // Geckos
{
console.log( 'geckos is ', geckos );
io = geckos({
authorization: async function( auth, request, response )
{
//debugger;
//response.setHeader('www-authenticate', 'Test testa="testb"');
return { ip:request.connection.remoteAddress }; // or request.headers['x-forwarded-for'] if server is behind proxy
},
cors: { allowAuthorization: true }
});
//io.listen( 3001 );
io.addServer( httpsServer ? httpsServer : httpServer );
}
import THREE from "./game/libs/three-for-server.js";
// let that = this; setTimeout( ()=>{ sdWorld.entity_classes[ that.name ] = that; }, 1 ); // Old register for object spawn code
import sdWorld from './game/sdWorld.js';
import FakeCanvasContext from './game/libs/FakeCanvasContext.js'; // consts
globalThis.FakeCanvasContext = FakeCanvasContext;
import sdRenderer from './game/client/sdRenderer.js';
//globalThis.sdRenderer = { visual_settings: 4 }; // Fake object. Bad, because sdBlock-s will see a real module, and won't know about this altering whenever mimic logic is applied
sdRenderer.visual_settings = 4;
globalThis.sdRenderer = sdRenderer;
import sdEntity from './game/entities/sdEntity.js';
import sdInterface from './game/interfaces/sdInterface.js';
import sdDeepSleep from './game/entities/sdDeepSleep.js';
import sdCharacter from './game/entities/sdCharacter.js';
import sdPlayerDrone from './game/entities/sdPlayerDrone.js';
import sdGun from './game/entities/sdGun.js';
import sdBlock from './game/entities/sdBlock.js';
import sdEffect from './game/entities/sdEffect.js';
import sdCrystal from './game/entities/sdCrystal.js';
import sdBullet from './game/entities/sdBullet.js';
import sdCom from './game/entities/sdCom.js';
import sdAsteroid from './game/entities/sdAsteroid.js';
import sdVirus from './game/entities/sdVirus.js';
import sdAmphid from './game/entities/sdAmphid.js';
import sdTeleport from './game/entities/sdTeleport.js';
import sdDoor from './game/entities/sdDoor.js';
import sdWater from './game/entities/sdWater.js';
import sdBG from './game/entities/sdBG.js';
import sdWeather from './game/entities/sdWeather.js';
import sdTurret from './game/entities/sdTurret.js';
import sdMatterContainer from './game/entities/sdMatterContainer.js';
import sdMatterAmplifier from './game/entities/sdMatterAmplifier.js';
import sdQuickie from './game/entities/sdQuickie.js';
import sdOctopus from './game/entities/sdOctopus.js';
import sdAntigravity from './game/entities/sdAntigravity.js';
import sdCube from './game/entities/sdCube.js';
import sdLamp from './game/entities/sdLamp.js';
import sdCommandCentre from './game/entities/sdCommandCentre.js';
import sdBomb from './game/entities/sdBomb.js';
import sdBeacon from './game/entities/sdBeacon.js';
import sdHover from './game/entities/sdHover.js';
import sdStorage from './game/entities/sdStorage.js';
import sdAsp from './game/entities/sdAsp.js';
import sdModeration from './game/server/sdModeration.js';
import sdDictionaryWords from './game/server/sdDictionaryWords.js';
import sdDatabase from './game/server/sdDatabase.js';
import sdMemoryLeakSeeker from './game/server/sdMemoryLeakSeeker.js';
import sdByteShifter from './game/server/sdByteShifter.js';
import { sdServerConfigShort, sdServerConfigFull } from './game/server/sdServerConfig.js';
globalThis.sdByteShifter = sdByteShifter;
import sdSandWorm from './game/entities/sdSandWorm.js';
import sdGrass from './game/entities/sdGrass.js';
import sdSlug from './game/entities/sdSlug.js';
import sdBarrel from './game/entities/sdBarrel.js';
import sdEnemyMech from './game/entities/sdEnemyMech.js';
import sdArea from './game/entities/sdArea.js';
import sdCrystalCombiner from './game/entities/sdCrystalCombiner.js';
import sdUpgradeStation from './game/entities/sdUpgradeStation.js';
import sdJunk from './game/entities/sdJunk.js';
import sdBadDog from './game/entities/sdBadDog.js';
import sdShark from './game/entities/sdShark.js';
import sdWorkbench from './game/entities/sdWorkbench.js';
import sdRescueTeleport from './game/entities/sdRescueTeleport.js';
import sdRift from './game/entities/sdRift.js';
import sdDrone from './game/entities/sdDrone.js';
import sdLifeBox from './game/entities/sdLifeBox.js';
import sdLost from './game/entities/sdLost.js';
import sdCable from './game/entities/sdCable.js';
import sdCharacterRagdoll from './game/entities/sdCharacterRagdoll.js';
import sdNode from './game/entities/sdNode.js';
import sdSpider from './game/entities/sdSpider.js';
import sdBall from './game/entities/sdBall.js';
import sdTheatre from './game/entities/sdTheatre.js';
import sdCaption from './game/entities/sdCaption.js';
import sdBaseShieldingUnit from './game/entities/sdBaseShieldingUnit.js';
import sdConveyor from './game/entities/sdConveyor.js';
import sdBeamProjector from './game/entities/sdBeamProjector.js';
import sdQuadro from './game/entities/sdQuadro.js';
import sdObelisk from './game/entities/sdObelisk.js';
import sdSunPanel from './game/entities/sdSunPanel.js';
import sdWeaponBench from './game/entities/sdWeaponBench.js';
import sdLongRangeTeleport from './game/entities/sdLongRangeTeleport.js';
import sdTask from './game/entities/sdTask.js';
import sdPortal from './game/entities/sdPortal.js';
import sdPlayerSpectator from './game/entities/sdPlayerSpectator.js';
import { createRequire } from 'module';
const require = createRequire( import.meta.url );
globalThis.acorn = require('./game/libs/acorn.cjs');
async function LoadScriptsFromFolder( path='game/entities/' )
{
//let classes_directory_relative_for_clients = './entities/'; // Prefix for clients
let classes_directory_relative_for_clients = path.split( 'game/' ).join( './' ); // Prefix for clients
let classes_directory_physical = __dirname + path; // For scanning
let classes_directory_relative = './' + path; // For importing
let import_class_promises = [];
let imported_classes = [];
let class_names_set = new Set();//new Map();
let entity_files = fs.readdirSync( classes_directory_physical );
entity_files.forEach( ( file )=>
{
import_class_promises.push( ( async ()=>
{
// Better to import this one manually
if ( file === 'sdEntity' || file === 'sdInterface' )
return;
//trace( 'Auto-import: ' + classes_directory_relative + file );
let imported = await import( classes_directory_relative + file );
imported_classes.push( imported.default );
let name_for_client = classes_directory_relative_for_clients + imported.default.name;
if ( class_names_set.has( name_for_client ) )
throw new Error( 'Class "' + name_for_client + '" is imported twice from two different files:\n' + name_for_client + '\nand\n' + classes_directory_relative + file );
//class_names_set.set( name_for_client, classes_directory_relative + file );
class_names_set.add( name_for_client );
})() );
});
if ( import_class_promises.length < 4 )
console.warn( 'Too few classes ('+import_class_promises.length+') to load. Is folder being read properly?' );
await Promise.all( import_class_promises );
return { class_names_set, imported_classes };
}
let entity_info = await LoadScriptsFromFolder( 'game/entities/' );
let interface_info = await LoadScriptsFromFolder( 'game/interfaces/' );
let get_classes_page = Array.from( entity_info.class_names_set.keys() ).concat( Array.from( interface_info.class_names_set.keys() ) ).join(',');
let all_imported_classes = entity_info.imported_classes.concat( interface_info.imported_classes );
entity_info = null;
import sdServerToServerProtocol from './game/server/sdServerToServerProtocol.js';
import sdPathFinding from './game/ai/sdPathFinding.js';
import LZW from './game/server/LZW.js';
import LZUTF8 from './game/server/LZUTF8.js';
import sdSnapPack from './game/server/sdSnapPack.js';
import sdShop from './game/client/sdShop.js';
import sdSound from './game/sdSound.js';
import sdKeyStates from './game/sdKeyStates.js';
console.warn = console.trace; // Adding stack trace support for console.warn, which it doesn't have by default for some reason in Node.JS
let enf_once = true;
globalThis.CATCH_ERRORS = true;
globalThis.EnforceChangeLog = function EnforceChangeLog( mat, property_to_enforce, value_as_string=true, mode='warn' )
{
if ( enf_once )
{
enf_once = false;
console.warn('Enforcing method applied');
}
let enforced_prop = '_enfroce_' + property_to_enforce;
mat[ enforced_prop ] = mat[ property_to_enforce ];
mat[ property_to_enforce ] = null;
Object.defineProperty( mat, property_to_enforce,
{
enumerable: mat.propertyIsEnumerable( property_to_enforce ),
get: function () { return mat[ enforced_prop ]; },
set: function ( v ) {
if ( mat[ enforced_prop ] !== v )
{
if ( mode === 'abs>100' )
{
if ( Math.abs( mat[ enforced_prop ] - v ) > 100 )
console.warn( 'Big .'+enforced_prop+' change (abs>100) from', mat[ enforced_prop ],' to ', v );
if ( isNaN( v ) )
{
console.warn( 'NaN (',v,') assign attempt. Old value was ', mat[ enforced_prop ] );
throw new Error('NaN ('+v+') assign attempt. Old value was ' + mat[ enforced_prop ] );
}
}
else
if ( mode === 'nan_catch' )
{
if ( isNaN( v ) || v === undefined )
{
console.warn( 'NaN or undefined (',v,') assign attempt. Old value was ', mat[ enforced_prop ] );
throw new Error('NaN or undefined ('+v+') assign attempt. Old value was ' + mat[ enforced_prop ] );
}
}
else
{
if ( v === undefined )
{
throw new Error('undef set');
}
if ( value_as_string )
console.warn( mat.constructor.name,'.'+property_to_enforce+' = '+v );
else
console.warn( mat.constructor.name,'.'+property_to_enforce+' = ',v );
}
mat[ enforced_prop ] = v;
}
}
});
mat[ property_to_enforce+'_unenforce' ] = function()
{
let old_val = mat[ property_to_enforce ];
delete mat[ property_to_enforce ];
mat[ property_to_enforce ] = old_val;
/*
Object.defineProperty( mat, property_to_enforce,
{
get: function () { return mat[ enforced_prop ]; },
set: function ( v ) { mat[ enforced_prop ] = v; }
});*/
};
};
globalThis.getStackTrace = ()=>
{
var obj = {};
try
{
Error.captureStackTrace( obj, globalThis.getStackTrace ); // Webkit
return obj.stack;
}
catch ( e )
{
return ( new Error ).stack; // Firefox
}
};
sdWorld.init_class();
sdEntity.init_class();
sdInterface.init_class();
for ( let i = 0; i < all_imported_classes.length; i++ )
if ( all_imported_classes[ i ].init_class )
all_imported_classes[ i ].init_class();
sdEntity.AllEntityClassesLoadedAndInitiated();
sdServerToServerProtocol.init_class();
sdPathFinding.init_class();
LZW.init_class();
sdSound.init_class();
sdDictionaryWords.init_class();
globalThis.LZW = LZW;
globalThis.sdWorld = sdWorld;
globalThis.sdShop = sdShop;
globalThis.sdModeration = sdModeration;
globalThis.sdDictionaryWords = sdDictionaryWords;
globalThis.sdDatabase = sdDatabase;
globalThis.sdSnapPack = sdSnapPack;
globalThis.sdPathFinding = sdPathFinding;
globalThis.sdSound = sdSound;
sdWorld.FinalizeClasses();
let world_slot = 0; // Default slot adds no prefixes to file names
for ( let i = 0; i < process.argv.length; i++ )
{
let parts = process.argv[ i ].split('=');
if ( parts.length > 1 )
{
if ( parts[ 0 ] === 'world_slot' )
world_slot = ~~( parts[ 1 ] );
let v = parts.slice( 1 ).join('=');
try
{
sdWorld.server_start_values[ parts[ 0 ] ] = JSON.parse( v );
}
catch( e )
{
sdWorld.server_start_values[ parts[ 0 ] ] = v;
}
}
}
console.log('world_slot = ' + world_slot + ' (defines server instance file prefixes, can be added to run command arguments in form of world_slot=1)' );
globalThis.world_slot = world_slot;
let frame = 0;
globalThis.GetFrame = ()=>{ return frame; }; // Call like this: GetFrame()
/*function file_exists( url )
{
return fs.stat( url, function(err, stat)
{
if(err == null) {
return true;
} else if(err.code === 'ENOENT') {
// file does not exist
return false;//fs.writeFile('log.txt', 'Some log\n');
} else {
return false;//console.log('Some other error: ', err.code);
}
});
}*/
const file_exists = fs.existsSync;
globalThis.file_exists = file_exists;
var sockets = [];
var sockets_by_ip = {}; // values are arrays (for easier user counting per ip)
//var sockets_array_locked = false;
sdWorld.sockets = sockets;
const chunks_folder = __dirname + '/chunks' + ( world_slot || '' );
globalThis.chunks_folder = chunks_folder;
const presets_folder = __dirname + '/presets';
globalThis.presets_folder = presets_folder;
if ( !fs.existsSync( globalThis.presets_folder ) )
{
trace( 'Making directory: ' + globalThis.presets_folder );
fs.mkdirSync( globalThis.presets_folder );
}
if ( globalThis.CATCH_HUGE_ARRAYS )
{
const push0 = Array.prototype.push;
const max_size = 200000; // Hopefully it is high enough for all kinds of proper worlds?
const _Buffer = Buffer; // Store locally for least performance hit
Array.prototype.next_panic_size = max_size;
Array.prototype.push = function ( ...args )
{
if ( this.length + args.length > this.next_panic_size )
{
if ( args[ 0 ] instanceof _Buffer ) // Not an array of zlib buffers
{
this.next_panic_size = Infinity;
}
else
{
console.warn( 'Panic: Array at this callstack grows over the size of ' + this.next_panic_size + ' elements (it is best to look for first panic message). Size is becoming: ' + ( this.length + args.length ) + '; Next added element: ', args[ 0 ] );
this.next_panic_size *= 2;
}
}
push0.call( this, ...args );
};
}
eval( 'sdWorld.server_config = ' + sdServerConfigFull.toString() ); // Execute while exposing same classes
sdWorld.UpdateFilePaths( __dirname, world_slot );
{
let file_raw = '';
if ( globalThis.file_exists( sdWorld.server_config_path_const ) )
{
file_raw = fs.readFileSync( sdWorld.server_config_path_const );
}
else
{
console.log('Unable to find file "'+sdWorld.server_config_path_const+'" - will create default one');
file_raw = sdWorld.server_config.__proto__.toString();
fs.writeFileSync( sdWorld.server_config_path_const, file_raw );
}
//eval( 'sdWorld.server_config = ' + file_raw );
//trace( '( sdWorld.server_config.onBeforeSnapshotLoad ) === ', ( sdWorld.server_config.onBeforeSnapshotLoad.toString() ) )
eval( `sdWorld.server_config_loaded = ${ file_raw.toString() };` );
//eval( `sdWorld.server_config = Object.assign( sdWorld.server_config, ${ file_raw.toString() } );` );
let keys = Object.getOwnPropertyNames( sdWorld.server_config_loaded );
for ( let i = 0; i < keys.length; i++ )
{
let prop = keys[ i ];
//trace( prop );
if ( prop !== 'length' )
if ( prop !== 'prototype' )
if ( prop !== 'name' )
sdWorld.server_config[ prop ] = sdWorld.server_config_loaded[ prop ];
}
//trace( '( sdWorld.server_config.onBeforeSnapshotLoad ) === ', ( sdWorld.server_config.onBeforeSnapshotLoad.toString() ) )
}
sdShop.init_class(); // requires plenty of classes due to consts usage
sdWorld.onAfterConfigLoad();
//globalThis.use_parallel_saving = true;
//let snapshot_path = __dirname + '/star_defenders_snapshot.v';
sdWorld.server_config.InstallBackupAndServerShutdownLogic();
if ( sdWorld.server_config.onBeforeSnapshotLoad )
sdWorld.server_config.onBeforeSnapshotLoad();
sdWorld.server_config.InitialSnapshotLoadAttempt();
if ( sdEntity.global_entities.length === 0 )
{
console.log( 'Recreating sdWeather' );
//sdEntity.global_entities.push( new sdWeather({}) );
sdEntity.entities.push( new sdWeather({}) );
}
if ( sdWorld.server_config.onAfterSnapshotLoad )
sdWorld.server_config.onAfterSnapshotLoad();
sdDeepSleep.init();
let file_cache = null;
// Moderators can call it
globalThis.UpdateFileCache = ()=>
{
file_cache = new Map();
const ReadRecursively = ( path )=>
{
fs.readdirSync( path ).forEach( ( file )=>
{
let stat = fs.lstatSync( path + file );
if ( stat.isDirectory() )
{
ReadRecursively( path + file + '/' );
}
else
{
let url = ( path + file ).split( __dirname + '/' ).join( '' );
let data = fs.readFileSync( path + file );
file_cache.set( url, {
data: data,
type: mime.lookup( path + file ),
length: data.length
} );
}
});
};
ReadRecursively( __dirname + '/game/' );
};
globalThis.DisableFileCache = ()=>
{
file_cache = null;
};
if ( sdWorld.server_config.store_game_files_in_ram )
globalThis.UpdateFileCache();
// Slower but less file stacking that could slow down game
let get_busy = false;
let busy_tot = 0;
app.get('/*', function cb( req, res, repeated=false )
{
function Finalize()
{
get_busy = false;
}
if ( repeated !== true )
busy_tot++;
if ( get_busy )
{
setTimeout( ()=>{ cb( req, res, true ); }, 2 + Math.random() * 10 );
return;
}
get_busy = true;
busy_tot--;
if ( busy_tot > 20 )
console.log( 'Slowing down file download due to '+busy_tot+' files requested at the same time' );
var path = __dirname + '/game' + req.url;
//var path = './game' + req.url;
if ( req.url.substring( 0, '/sd_hook'.length ) === '/sd_hook' )
{
let request = req.url.split( '?' )[ 1 ];
let request_parts = request.split( '{' );
let _net_id = parseInt( request_parts[ 0 ] );
let response = null;
let ent = sdEntity.entities_by_net_id_cache_map.get( _net_id );
if ( ent !== undefined )
if ( typeof ent.HandleHookReply !== 'undefined' )
{
let json_obj = null;
try
{
json_obj = JSON.parse( '{' + decodeURI( request_parts.slice( 1 ).join( '{' ) ) ); // Won't accept non-JSON objects
}
catch ( e )
{
debugger;
}
if ( json_obj )
response = ent.HandleHookReply( json_obj );
}
if ( !response )
{
response = { no_response: 1 };
}
res.send( JSON.stringify( response ) );
Finalize();
return;
}
else
if ( req.url === '/get_classes.txt' )
//if ( req.url === '/get_entity_classes.txt' )
{
res.send( get_classes_page );
Finalize();
return;
}
else
if ( file_cache )
{
let url = 'game' + req.url;
if ( url.length > 0 )
if ( url.charAt( url.length - 1 ) === '/' )
url += 'index.html';
// Mespeak's path issue
url = url.split( '//' ).join( '/' );
let obj = file_cache.get( url );
//trace( 'RECV', url );
if ( obj )
{
res.writeHead(200, {'Content-Type': obj.type, 'Content-Length':obj.length});
res.write( obj.data );
res.end();
}
else
{
res.writeHead( 404 );
res.write( '404' );
res.end();
}
Finalize();
}
else
{
let path2 = path.split('?')[0];
fs.access( path2, fs.F_OK, (err) =>
{
//let t3 = Date.now();
if ( !file_exists( path ) ) // Silent
{
res.end();
Finalize();
return;
}
if ( err ) // Access errors usually
{
//res.send( '404' );//console.error(err)
res.status( 404 ).end();
Finalize();
return;
}
//res.sendFile( path );
//file exists
if ( path2[ path2.length - 1 ] === '/' )
path2 += 'index.html';
if ( path2.slice( -5 ) === '.html' )
{
fs.readFile( path2, function(err, data) {
if (err) {
res.send(404);
} else {
res.contentType('text/html'); // Or some other more appropriate value
//transform(data); // use imagination please, replace with custom code
let _parts_all = [];
let parts = data.toString().split( '<?' );
for ( let i = 0; i < parts.length; i++ )
{
parts[ i ] = parts[ i ].split( '?>' );
_parts_all.push( ...parts[ i ] );
}
let code = '';
let out = '';
let print_html = true; // Can be disabled via <? print_html = false; ?>
function print( str )
{
out += str;
}
function printOrReturn( str )
{
if ( print_html )
out += str;
return str;
}
for ( let _i = 0; _i < _parts_all.length; _i++ )
{
/*if ( _parts_all[ _i ].indexOf( '`' ) !== -1 )
{
trace('!!!');
debugger;
}*/
if ( _i % 2 === 0 )
{
let s = _parts_all[ _i ];
//code += 'printOrReturn(`' + s + '`);';
code += 'printOrReturn(' + JSON.stringify( s ) + ');';
}
else
code += '\n' + _parts_all[ _i ] + '\n';
}
eval( code );
res.send( out );
}
});
}
else
res.sendFile( path );
Finalize();
});
}
});