forked from g-js-api/G.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1455 lines (1380 loc) · 43.7 KB
/
Copy pathindex.js
File metadata and controls
1455 lines (1380 loc) · 43.7 KB
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
/**
* @module index
* @exports index
* @requires group
* @requires color
* @requires block
*/
const {
on,
touch,
touch_end,
collision,
collision_exit,
death,
count,
x_position,
event,
gamescene,
frame
} = require('./lib/events');
const {
spawn_trigger,
remappable,
sequence,
call_with_delay,
equal_to,
less_than,
greater_than,
for_loop,
frame_loop,
frames
} = require('./lib/control-flow');
const {
item_edit,
item_comp,
timer,
compare
} = require('./lib/items');
const {
camera_offset,
camera_static,
camera_zoom,
camera_mode,
camera_rotate,
camera_edge,
song,
teleport,
move_trigger,
timewarp,
color_trigger,
toggle_on_trigger,
toggle_off_trigger,
hide_player,
gradient,
random,
advanced_random,
gravity,
options,
end,
player_control,
particle_system
} = require('./lib/general-purpose');
const {
shader_layers,
shader_layer,
sepia,
hue_shift,
grayscale,
pixelate,
chromatic,
glitch,
bulge,
split_screen
} = require('./lib/shaders.js');
const keyframe_system = require('./lib/keyframes.js');
const particle_props = require('./properties/particles.js');
const events = require('./properties/game_events.js');
const log = require('./lib/log.js');
const WebSocket = require('ws');
const crypto = require('crypto');
const LevelReader = require('./reader');
const $group = require('./types/group.js');
const $color = require('./types/color.js');
const $block = require('./types/block.js');
const d = require('./properties/obj_props.js');
const { counter, float_counter } = require('./lib/counter');
let explicit = {};
/**
* Extracts values from dictionary into global scope
* @param {dictionary} dict Dictionary to extract
*/
let extract = (x) => {
for (let i in x) {
global[i] = x[i];
}
};
global.all_known = {
groups: [],
colors: [],
blocks: []
}
let [unavailable_g, unavailable_c, unavailable_b] = [0, 0, 0];
let get_new = (n, prop, push = true) => {
let arr = all_known[prop];
if (arr.length == 0) {
arr.push(1);
return 1;
}
arr.sort((a, b) => a - b);
if (arr[0] > 1 && push) {
arr.unshift(1);
return 1;
}
let result;
for (let i = 1; i < arr.length; i++) {
if (arr[i] !== arr[i - 1] + 1) {
result = arr[i - 1] + 1;
break;
}
}
if (!result) result = arr[arr.length - 1] + 1;
if (push) all_known[prop].push(result);
return result;
};
/**
* Creates and returns an unavailable group ID
* @returns {group} Resulting group ID
*/
let unknown_g = () => {
// todo: make this not use group 0
unavailable_g++;
unavailable_g = get_new(unavailable_g, 'groups');
return new $group(unavailable_g);
};
/**
* Creates and returns an unavailable color ID
* @returns {color} Resulting color ID
*/
let unknown_c = () => {
unavailable_c++;
unavailable_c = get_new(unavailable_c, 'colors');
return new $color(unavailable_c);
};
/**
* Creates and returns an unavailable block ID
* @returns {block} Resulting block ID
*/
let unknown_b = () => {
unavailable_b++;
unavailable_b = get_new(unavailable_b, 'blocks');
return new $block(unavailable_b);
};
/**
* @typedef {object} context
* @property {string} name Name of the current context
* @property {group} group Group representing the current context
* @property {array} objects All objects in the current context
* @property {array} children Child contexts
*/
/**
* Class allowing you to interfere with contexts, which are wrappers that assign groups to different objects
* @class
* @constructor
* @public
*/
class Context {
/**
* Creates a new context
* @param {string} name Name of context
* @param {boolean} [setToDefault=false] Whether to automatically switch to the context
* @param {group} [group=unknown_g()] The group to give to the context
*/
constructor(name, setToDefault = false, group = unknown_g()) {
this.name = name;
this.group = group;
this.objects = [];
this.children = [];
Context.last_contexts[name] = name;
if (setToDefault) Context.set(name);
Context.add(this);
}
static last_contexts = {};
static last_context_children = {};
/**
* The name of the current context
*/
static current = "global";
/**
* A list of all contexts added
*/
static list = {};
/**
* Switches the context
* @param {string|group} name Name or group of context to switch to
*/
static set(name) {
if (typeof name == 'object' && name?.value) {
Context.current = Context.findByGroup(name).name;
return;
};
Context.current = name;
}
/**
* Converts an object into a context
* @param {context} context Object to convert into a context
*/
static add(context) {
Context.list[context.name] = context;
}
/**
* Adds an object into the current context
* @param {object} objectToAdd Object to add into current context
*/
static addObject(objectToAdd) {
if (objectToAdd.type == "object") {
Context.findByName(Context.current).objects.push(callback_objects_fn(objectToAdd).obj_props);
return;
}
Context.findByName(Context.current).objects.push(objectToAdd);
}
/**
* Links an existing context into the current one, allowing you to find the parent context of another context
* @param {context} context Context to link into current
* @param {string} ctxLink Optional context that should be the parent of input context
*/
static link(context, ctxLink = undefined) {
let input_context = Context.findByName(context);
let curr_ctx = !ctxLink ? Context.findByName(Context.current) : Context.findByName(ctxLink);
if (Context.isLinked(input_context)) {
input_context.linked_to = curr_ctx.linked_to;
Context.last_context_children[input_context.linked_to] = context;
} else {
input_context.linked_to = curr_ctx.name;
Context.last_contexts[context] = input_context.name;
Context.last_context_children[context] = curr_ctx.name;
}
curr_ctx.children.push(context);
}
/**
* Checks if a context has a parent
* @param {context} ctx Context to check for parent
* @returns {boolean} Whether context has a parent
*/
static isLinked(ctx) {
return 'linked_to' in ctx;
}
/**
* Finds a context based off of its assigned group
* @param {group} groupToSearch
* @returns {context} Found context
*/
static findByGroup(groupToSearch) {
if (typeof groupToSearch == "number") {
groupToSearch = group(groupToSearch);
} else if (!groupToSearch instanceof $group) {
throw new Error(`Expected number or $group instance, got ${groupToSearch} with type ${typeof groupToSearch}`)
}
for (const key in Context.list) {
if (Context.list[key].group.value == groupToSearch.value) {
return Context.list[key];
}
}
}
/**
* Finds a context based off of its name
* @param {string} name Name of the context
* @returns {context} Found context
*/
static findByName(name) {
return Context.list[name];
}
}
Context.add(new Context("global"))
let findDeepestChildContext = (name) => {
let cond = true;
let res_name = name;
while (cond) {
cond = !!Context.last_context_children[name];
if (cond) {
res_name = Context.last_context_children[res_name];
cond = !!Context.last_context_children[res_name];
} else { break };
}
return res_name;
};
/**
* Creates a repeating trigger system that repeats while a condition is true
* @param {condition} condition Condition that defines whether the loop should keep on running (less_than/equal_to/greater_than(counter, number))
* @param {function} func Function to run while the condition is true
* @param {number} delay Delay between each cycle
*/
let while_loop = (r, triggerFunction, del = 0.05) => {
let { count, comparison, other } = r;
let oldContextName = Context.current;
let newContext = new Context(crypto.randomUUID());
let check_func;
if (oldContextName == "global") {
check_func = trigger_function(() => {
count.if_is(comparison, other, newContext.group);
});
} else {
count.if_is(comparison, other, newContext.group);
}
Context.set(newContext.name);
triggerFunction(newContext.group);
Context.set(oldContextName);
triggerFunction = newContext.group;
let context = Context.findByGroup(triggerFunction);
let currentG = Context.findByName(findDeepestChildContext(context.name)).group;
if (!currentG) {
currentG = triggerFunction;
}
$.extend_trigger_func(currentG, () => {
// Context.findByName(oldContextName)
oldContextName == "global" ? check_func.call(del) : Context.findByName(oldContextName).group.call(del);
});
if (check_func) check_func.call(del);
};
let writeClasses = (arr) => {
arr.forEach((class_) => {
let clases = class_.split('/');
let clas = clases.shift();
clases.forEach((expl) => {
if (explicit[expl]) {
explicit[expl] = [explicit[expl], clas];
return;
}
explicit[expl] = clas;
});
});
/**
* Converts a number to a group
* @global
* @param {number} x - The number to convert to a group.
* @returns {group}
*/
global.group = (x) => new $group(x);
/**
* Converts a number to a color
* @global
* @param {number} x - The number to convert to a color.
* @returns {color}
*/
global.color = (x) => new $color(x);
/**
* Converts a number to a block
* @global
* @param {number} x - The number to convert to a block.
* @returns {block}
*/
global.block = (x) => new $block(x);
}
writeClasses([
'group/TARGET/GROUPS/GR_BL/GR_BR/GR_TL/GR_TR/TRUE_ID/FALSE_ID/ANIMATION_GID/TARGET_POS/EXTRA_ID/EXTRA_ID_2/FOLLOW/CENTER/TARGET_DIR_CENTER/SHADER_CENTER_ID',
'color/TARGET/TARGET_COLOR/COLOR/COLOR_2/SHADER_TINT_CHANNEL',
'block/BLOCK_A/BLOCK_B',
]);
/**
* @typedef {dictionary} object
* @property {string} type String dictating that the type of the resulting dictionary is an object
* @property {dictionary} obj_props Dictionary inside of object holding the actual object properties of the object
* @property {function} with Modifies/adds an object property (e.g. `object.with(obj_props.X, 15)`)
* @property {function} add Adds the object
*/
/**
* Takes a dictionary with object props & converts into an object
* @param {dictionary} dict Dictionary to convert to object
* @returns {object}
*/
let object = (dict) => {
let return_val = {
type: 'object',
obj_props: dict,
with: (prop, val) => {
if (typeof prop == "string") {
dict[prop] = val;
return return_val;
}
dict[d[prop]] = val;
return return_val;
},
// copied old $.add code here so I can migrate to enforcing object() usage in the future
add: () => Context.addObject(return_val)
};
return return_val;
};
/**
* Creates a "trigger function" in which triggers can be stored inside of a single group
* @param {function} callback Function storing triggers to put inside of group
* @returns {group} Group ID of trigger function
*/
let trigger_function = (cb) => {
let oldContext = Context.current;
let newContext = new Context(crypto.randomUUID(), true);
cb(newContext.group);
Context.set(oldContext);
return newContext.group;
};
/**
* Waits for a specific amount of seconds
* @param {number} time How long to wait
*/
let wait = (time) => {
if (time == 0) return;
let id = crypto.randomUUID();
let oldContext = Context.current;
let newContext = new Context(id);
$.add(spawn_trigger(newContext.group, time));
Context.set(id);
Context.link(newContext.name, oldContext);
};
let reverse = {};
for (var i in d) {
reverse[d[i]] = i;
}
// stuff for custom things
let dot_separated_keys = [57, 442];
dot_separated_keys = dot_separated_keys.map(x => x.toString())
let levelstring_to_obj = (string) => {
let objects = [];
string
.split(';')
.slice(0, -1)
.forEach((x) => {
let r = {};
let spl = x.split(',');
spl.forEach((x, i) => {
if (!(i % 2)) {
let obj_prop = parseInt(x);
let value = spl[i + 1];
if (value.includes('.') && dot_separated_keys.includes(obj_prop)) value = value.split('.').map(x => parseInt(x));
if (!isNaN(parseInt(value))) value = parseInt(value);
r[d[obj_prop] || obj_prop] = value;
}
});
objects.push(r);
});
return objects;
};
/**
* Helper functions and variables holding existing level info.
* @namespace level
*/
let level = {
/**
* Array of all objects in the level.
* @type {Array<Object>}
*/
objects: [],
/**
* Raw level string of the current level.
* @type {string}
*/
raw_levelstring: '',
/**
* Returns an array of all the objects in the level with a property whose value matches the pattern.
* @param {string|number} prop - The property to check in each object.
* @param {Function} pattern - The function to test the property value.
* @returns {Array<Object>} An array of objects that match the given property and pattern.
*/
get_objects: function (prop, pattern) {
let level_arr = levelstring_to_obj(this.raw_levelstring);
return level_arr.filter(o => {
let cond_1 = prop in o, cond_2;
if (cond_1) cond_2 = pattern(o[prop]);
return cond_1 && cond_2;
});
}
};
let mappings = {
696969: '80',
420420: '80',
6942069: '95',
6969: '51',
42069420: '88',
32984398: '51',
584932: '71',
78534: '480',
45389: '481',
93289: '482',
8754: '51',
8459: '71',
3478234: '71',
45893: '392',
237894: '10',
347832: '70',
34982398: '188',
4895490381243: '51',
45890903: '290',
487999230: '179',
40943900394: '191',
93423877: '181',
8765437289: '182',
645789320: '180',
8765434: '188',
21678934: '190'
};
let find_free = (str) => {
let startIndex = 0;
let endIndex;
while ((endIndex = str.indexOf(';', startIndex)) !== -1) {
let segment = str.substring(startIndex, endIndex);
startIndex = endIndex + 1;
if (!segment) continue;
level.objects.push(segment);
level.raw_levelstring += segment + ';';
let ro = segment.split(',');
for (let i = 0; i < ro.length; i += 2) {
let key = ro[i];
let value = ro[i + 1];
switch (key) {
case "57":
let detected_groups = value.split('.').map(Number).filter(num => num !== remove_group);
for (let group of detected_groups) {
if (!all_known.groups.includes(group)) all_known.groups.push(group);
unavailable_g = get_new(group, 'groups', false);
}
break;
case "21":
case "22":
let detected_color = parseInt(value);
if (!all_known.colors.includes(detected_color)) all_known.colors.push(detected_color);
unavailable_c = get_new(detected_color, 'colors', false);
break;
case "80":
case "95":
let detected_block = parseInt(value);
if (!all_known.blocks.includes(detected_block)) all_known.blocks.push(detected_block);
unavailable_b = get_new(detected_block, 'blocks', false);
break;
}
}
}
};
let obj_to_levelstring = (l) => {
let res = '';
// { x: 15, Y: 10 };
for (var d_ in l) {
let val = l[d_];
let key = reverse[d_];
if (!isNaN(parseInt(d_))) key = d_
if (typeof val == 'boolean') val = +val;
if (explicit[d_] && !val.hasOwnProperty('value')) { // if type is explicitly required for current object property and it is not a group/color/block
if (typeof val == 'object' && dot_separated_keys.includes(key)) { // if val is an array and it is dot separated
val = val.map((x) => x.value).filter(x => x && x != '').join('.');
} else {
throw `Expected type "${explicit[d[parseInt(key)]]
}", got "${typeof val}"`;
}
} else if (explicit[d_] && val.value) {
let cond = typeof explicit[d_] == "string" ? (val.type == explicit[d_]) : (explicit[d_].includes(val.type));
if (cond) {
val = val.value;
} else {
throw `Expected type "${explicit[d_]}", got "${val.type}"`;
}
}
if (mappings.hasOwnProperty(key)) {
key = mappings[key];
}
res += `${key},${val},`;
}
return res.slice(0, -1) + ';';
};
let resulting = '';
let add = (o) => {
if (o?.type !== "object") {
process.emitWarning('Using plain dictionaries as an argument to $.add is deprecated and using the object() function will be enforced in the future.', {
type: 'DeprecationWarning',
detail: 'Wrap the object() function around the dictionary as an argument to $.add instead of using plain dictionaries.'
});
}
if (o?.type == "object") {
o.add(); // does the same thing as below, only reason $.add is not removed is so I can customize $.add in the future
return;
};
let newo = o;
if (newo.with) delete newo.with;
Context.addObject(newo);
};
let remove_group = 9999;
let already_prepped = false;
let indexOfFrom = (array, value, startIndex) => {
let newArr = array.slice(startIndex);
return newArr.indexOf(value) !== -1 ? newArr.indexOf(value) + (array.length - newArr.length) : -1;
}
let ifInGroups = (groupsArr, group) => {
groupsArr?.value == undefined ? (groupsArr.map(x => x.value).includes(group.value)) : groupsArr.value == group.value;
}
// removes contexts if they are empty + any unnecessary triggers associating with them
let optimize = () => {
for (let child in Context.last_context_children) {
let parent = Context.list[Context.last_context_children[child]];
let childCtx = Context.list[child];
// handles empty contexts
if (childCtx.objects.length === 0) {
delete Context.list[child];
let emptyCallIndex = parent.objects.map(x => x.TARGET.value == childCtx.group.value);
parent.objects = parent.objects.filter((_, i) => i !== indexOfFrom(emptyCallIndex, true, i));
}
};
};
let prep_lvl = (optimize_op = true) => {
if (already_prepped) return;
if (optimize_op) optimize();
let name = 'GLOBAL_FULL';
Context.add(new Context(name, true, group(0)))
Context.last_contexts[name] = name;
// contexts.global.group.call();
for (let i in Context.list) {
// undefined prop filter
for (let object in Context.findByName(i).objects) {
object = Context.findByName(i).objects[object];
for (let prop in object) {
if (object[prop] == undefined) delete object[prop];
};
}
// main preparation
if (!(+(i !== 'GLOBAL_FULL') ^ +(i !== 'global'))) { // XOR if it was logical
let context = Context.findByName(i);
// gives groups to objects in context
let objects = context.objects;
for (let i = 0; i < objects.length; i++) {
let object = objects[i];
if (!object.GROUPS) {
object.GROUPS = [context.group, group(remove_group)];
} else {
if (Array.isArray(object.GROUPS)) {
object.GROUPS.push(context.group, group(remove_group));
} else {
object.GROUPS = [object.GROUPS, context.group, group(remove_group)];
}
}
if (!(object.hasOwnProperty("SPAWN_TRIGGERED") || object.hasOwnProperty(obj_props.SPAWN_TRIGGERED))) {
object.SPAWN_TRIGGERED = 1;
}
if (!(object.hasOwnProperty("MULTI_TRIGGER") || object.hasOwnProperty(obj_props.MULTI_TRIGGER))) {
object.MULTI_TRIGGER = 1;
}
// end
}
} else {
let context = Context.findByName(i);
let objects = context.objects;
for (let i = 0; i < objects.length; i++) {
let object = objects[i];
if (!object.GROUPS) {
object.GROUPS = group(remove_group);
} else {
if (Array.isArray(object.GROUPS)) {
object.GROUPS.push(group(remove_group));
} else {
object.GROUPS = [object.GROUPS, group(remove_group)];
}
}
}
}
for (let x in Context.findByName(i).objects) {
let r = obj_to_levelstring(Context.findByName(i).objects[x]);
resulting += r;
}
}
already_prepped = true;
};
let limit = 9999;
let warn_lvlstr = true;
let getLevelString = (options = {}) => {
if (warn_lvlstr) process.emitWarning('Using $.getLevelString is deprecated and will be removed in the future.', {
type: 'DeprecationWarning',
detail: `Migrate by using \`await $.exportConfig({ type: 'levelstring', options: <your options here> })\`. Note that instead of using $.exportConfig at the end of the program, use it at the top, below the G.js import but above all other code.`
});
prep_lvl();
if (unavailable_g <= limit) {
if (options.info) {
console.log('Finished, result stats:');
console.log('Object count:', resulting.split(';').length - 1);
console.log('Group count:', unavailable_g - 1);
console.log('Color count:', unavailable_c);
}
} else {
if (
(options.hasOwnProperty('group_count_warning') &&
options.group_count_warning == true) ||
!options.hasOwnProperty('group_count_warning')
)
throw new Error(`Group count surpasses the limit! (${unavailable_g}/${limit})`);
}
return resulting;
};
/**
* @typedef {object} easing
* @property {number} EASE_IN_OUT Ease in out easing
* @property {number} EASE_IN Ease in easing
* @property {number} EASE_OUT Ease out easing
* @property {number} EXPONENTIAL_IN_OUT Exponential in out easing
* @property {number} EXPONENTIAL_IN Exponential in easing
* @property {number} EXPONENTIAL_OUT Exponential out easing
* @property {number} SINE_IN_OUT Sine in out easing
* @property {number} SINE_IN Sine in easing
* @property {number} SINE_OUT Sine out easing
* @property {number} ELASTIC_IN_OUT Elastic in out easing
* @property {number} ELASTIC_IN Elastic in easing
* @property {number} ELASTIC_OUT Elastic out easing
* @property {number} BACK_IN_OUT Back in out easing
* @property {number} BACK_IN Back in easing
* @property {number} BACK_OUT Back out easing
* @property {number} BOUNCE_IN_OUT Bounce in out easing
* @property {number} BOUNCE_IN Bounce in easing
* @property {number} BOUNCE_OUT Bounce out easing
*/
let easings = {
ELASTIC_OUT: 6,
BACK_IN_OUT: 16,
BOUNCE_IN: 8,
BACK_OUT: 18,
EASE_OUT: 3,
EASE_IN: 2,
EASE_IN_OUT: 1,
ELASTIC_IN_OUT: 4,
BOUNCE_OUT: 9,
EXPONENTIAL_IN: 11,
EXPONENTIAL_OUT: 12,
SINE_IN_OUT: 13,
BOUNCE_IN_OUT: 7,
SINE_IN: 14,
ELASTIC_IN: 5,
SINE_OUT: 15,
EXPONENTIAL_IN_OUT: 10,
BACK_IN: 17,
NONE: 0,
};
extract(easings);
global.obj_props = reverse;
let callback_objects_fn = x => x;
let callback_objects = (cb) => {
callback_objects_fn = cb
};
let extend_trigger_func = (t, cb) => {
const context = Context.findByGroup(t);
const oldContext = Context.current;
Context.set(Context.last_contexts[context.name]);
cb(context.group);
Context.set(oldContext);
};
let remove_past_objects = (lvlstring, name) => {
// remove_group
if (!lvlstring) throw new Error(`Level "${name}" has not been initialized, add any object to initialize the level then rerun this script`);
return lvlstring.split(';').filter(x => {
let keep = true;
let spl = x.split(',');
spl.forEach((z, i) => {
if (!(i % 2)) {
if (z == "57") {
let groups = spl[i + 1]
if (groups.includes('.')) {
groups = groups.split('.');
if (groups.includes(remove_group.toString())) {
keep = false;
}
} else {
if (groups == remove_group) {
keep = false;
}
}
}
}
})
return keep;
}).join(';');
}
let exportToSavefile = (options = {}) => {
process.emitWarning('Using $.exportToSavefile is deprecated and will be removed in the future.', {
type: 'DeprecationWarning',
detail: `Migrate by using \`await $.exportConfig({ type: 'savefile', options: <your options here> })\`. Note that instead of using $.exportConfig at the end of the program, use it at the top, below the G.js import but above all other code.`
});
(async () => {
const level = await new LevelReader(options.level_name, options.path);
let last = remove_past_objects(level.data.levelstring, level.data.name);
prep_lvl();
if (unavailable_g <= limit) {
if (options.info) {
console.log(`Writing to level: ${level.data.name}`);
console.log('Finished, result stats:');
console.log('Object count:', resulting.split(';').length - 1);
console.log('Group count:', unavailable_g);
console.log('Color count:', unavailable_c);
}
} else {
if (
(options.hasOwnProperty('group_count_warning') &&
options.group_count_warning == true) ||
!options.hasOwnProperty('group_count_warning')
)
throw new Error(`Group count surpasses the limit! (${unavailable_g}/${limit})`);
}
last += resulting;
level.set(last);
await level.save();
})()
};
/**
* @typedef {Object} export_config
* @property {string} type Type of export (can be "levelstring", "savefile" or "live_editor")
* @property {save_config} options Configuration for specific export type
*/
/**
* One-size-fits-all function for exporting a level to GD
* @param {export_config} conf Configuration for exporting level
* @returns {null|string} Levelstring if using "levelstring" type, otherwise null
*/
let exportConfig = (conf) => {
return new Promise(async (resolve) => {
let options = conf.options;
switch (conf.type) {
case "levelstring":
prep_lvl(conf?.options?.optimize);
if (unavailable_g <= limit) {
if (options?.info) {
console.log('Finished, result stats:');
console.log('Object count:', resulting.split(';').length - 1);
console.log('Group count:', unavailable_g);
console.log('Color count:', unavailable_c);
}
} else {
if (
(options?.hasOwnProperty('group_count_warning') &&
options?.group_count_warning == true) ||
!options?.hasOwnProperty('group_count_warning')
)
throw new Error(`Group count surpasses the limit! (${unavailable_g}/${limit})`);
}
resolve(resulting);
break;
case "savefile":
const sf_level = await new LevelReader(options?.level_name, options?.path);
let last = remove_past_objects(sf_level.data.levelstring, sf_level.data.name);
find_free(last);
resolve(true);
process.on('beforeExit', error => {
if (!error) {
prep_lvl(conf?.options?.optimize);
if (unavailable_g <= limit) {
if (options?.info) {
console.log(`Writing to level: ${sf_level.data.name}`);
console.log('Finished, result stats:');
console.log('Object count:', resulting.split(';').length - 1);
console.log('Group count:', unavailable_g);
console.log('Color count:', unavailable_c);
}
} else {
if (
(options.hasOwnProperty('group_count_warning') &&
options.group_count_warning == true) ||
!options.hasOwnProperty('group_count_warning')
)
throw new Error(`Group count surpasses the limit! (${unavailable_g}/${limit})`);
}
last += resulting;
sf_level.set(last);
sf_level.save();
process.exit(0);
}
});
break;
case "live_editor":
let socket = new WebSocket('ws://127.0.0.1:1313');
socket.addEventListener('message', (event) => {
event = JSON.parse(event.data);
if (event.response) {
find_free(event.response.split(';').slice(1).join(';'));
level.raw_levelstring = event.response;
resolve(true);
}
if (event.status !== "successful") throw new Error(`Live editor failed, ${event.error}: ${event.message}`)
});
socket.addEventListener('open', (event) => {
socket.send(JSON.stringify({
action: 'REMOVE_OBJECTS',
group: 9999,
})); // clears extra objects
socket.send(JSON.stringify({
action: 'GET_LEVEL_STRING',
close: true
})); // thing to get free groups
process.on('beforeExit', error => {
if (!error) {
let socket2 = new WebSocket('ws://127.0.0.1:1313');
socket2.addEventListener('message', (event) => {
event = JSON.parse(event.data);
if (event.response) {
find_free(event.response.split(';').slice(1).join(';'));
}
if (event.status !== "successful") throw new Error(`Live editor failed, ${event.error}: ${event.message}`)
});
socket2.addEventListener('open', async (event) => {
let pre_lvlstr = await exportConfig({ type: "levelstring", options });
let lvlString = group_arr(pre_lvlstr.split(';'), 250).map(x => x.join(';'));
if (!error) {
lvlString.forEach((chunk, i) => {
setTimeout(() => {
socket2.send(JSON.stringify({
action: 'ADD_OBJECTS',
objects: chunk + ';',
close: i == lvlString.length - 1
}));
if (i == lvlString.length - 1) process.exit(0);
}, i * 75);
});
}
});
}
});
});
socket.addEventListener('error', () => {
throw new Error(`Connecting to WSLiveEditor failed! Make sure you have installed the WSLiveEditor mod inside of Geode and have the editor open!`);
});
break;
default: throw new Error(`The "${conf.type}" configuration type is not valid!`)
}
});
};
const group_arr = (arr, x) => arr.reduce((acc, _, i) => (i % x ? acc[acc.length - 1].push(arr[i]) : acc.push([arr[i]]), acc), []);
let liveEditor = (conf) => {
process.emitWarning('Using $.liveEditor is deprecated and will be removed in the future.', {
type: 'DeprecationWarning',
detail: `Migrate by using \`await $.exportConfig({ type: 'live_editor', options: <your options here> })\`. Note that instead of using $.exportConfig at the end of the program, use it at the top, below the G.js import but above all other code.`
});
const socket = new WebSocket('ws://127.0.0.1:1313');
warn_lvlstr = false;
let lvlString = group_arr($.getLevelString(conf).split(';'), 250).map(x => x.join(';'));
socket.addEventListener('message', (event) => {
event = JSON.parse(event.data);
if (event.status !== "successful") throw new Error(`Live editor failed, ${event.error}: ${event.message}`)
});
socket.addEventListener('open', (event) => {
socket.send(JSON.stringify({
action: 'REMOVE',
group: 9999,
})); // clears extra objects
lvlString.forEach((chunk, i) => {
setTimeout(() => {
socket.send(JSON.stringify({
action: 'ADD',
objects: chunk + ';',
close: i == lvlString.length - 1
}));
}, i * 75);
});
});
socket.addEventListener('error', () => {
throw new Error(`Connecting to WSLiveEditor failed! Make sure you have installed the WSLiveEditor mod inside of Geode!`);
});
};