-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemp.html
3273 lines (3099 loc) · 489 KB
/
temp.html
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
<!DOCTYPE html>
<html>
<style>
head, body {
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
margin: 0px;
overflow: hidden;
background: #485358;
}
#game {
width: 100%;
height: 100%;
background: #485358;
}
#game canvas {
background: #485358;
}
body > img {
width: 100%;
height: 100%;
}
</style>
<head>
<link rel="stylesheet" type="text/css" media="all" href="game.css"/>
<script type="text/javascript">/*
Common class methods:
_getPixiObjs() : if available, returns an array of DisplayObjects that is used for rendering
Todo:
NEED
C Audio
- Asset (font)
C Effect
C Input (mouse)
- Window
PLUGINS
- Net ?
- Gamepad
- Particle
- Tween
- Bezier
- Physics
- Steam
- UI
*/
var Blanke = (selector, options) => {
let re_sep = /[\\\/]/;
let re_no_ext = /([\/\\\.]*[\w\/\\]+)/;
/*
let elec, nwOS, eWin;
if (typeof require === 'function' && require('electron')) {
elec = require('electron');
nwOS = require('os');
eWin = elec.remote.getCurrentWindow();
}
*/
let elec = null;
try {
elec = require('electron');
} catch (e) {}
let blanke_ref = this;
this.options = Object.assign({
auto_focus: true,
width: 600,
height: 400,
resolution: 1,
config_file: 'config.json',
scale: true, // true: keep original canvas size and scale when game is resized
ide_mode: false,
root: null,
background_color: 0x485358,
scale_mode: 'nearest',
round_pixels: true,
fps: 60,
assets: [],
config: {},
onLoad: () => {}
},options || {});
if (this.options.config.export)
this.options = Object.assign(this.options, this.options.config.export);
// init PIXI
let app;
let parent = document.querySelector(selector);
// PIXI.utils.skipHello();
PIXI.settings.TARGET_FPMS = this.options.fps / 1000;
PIXI.settings.ROUND_PIXELS = this.options.round_pixels;
PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES[this.options.scale_mode.toUpperCase()];
app = new PIXI.Application({
width: this.options.width,
height: this.options.height,
resolution: 1, //window.devicePixelRatio || 1,
backgroundColor: this.options.background_color
});
//parent.innerHTML = "";
// add main container for game
let game_container = new PIXI.Container();
let bg_sprite1, bg_sprite2;
let createBgElements = () => {
bg_sprite1 = new PIXI.Sprite(PIXI.Texture.WHITE); // goes behind game_container
bg_sprite2 = new PIXI.Sprite(PIXI.Texture.WHITE); // goes inside game_container
app.stage.addChild(bg_sprite1);
bg_sprite1.tint = 0x000000;
bg_sprite2.tint = app.renderer.backgroundColor;
game_container.addChild(bg_sprite2);
app.stage.addChild(game_container);
}
createBgElements();
// focus/blur events
this.focused = false;
app.view.tabIndex=-1;
app.view.style.outline="none";
app.view.addEventListener('focus',(e)=> {
blanke_ref.focused = true;
});
app.view.addEventListener('blur',(e)=> {
blanke_ref.focused = false;
});
if (this.options.auto_focus) app.view.focus();
// resize renderer with parent
if (this.options.resizable || this.options.ide_mode)
app.renderer.resize(parent.clientWidth, parent.clientHeight);
// crop width/height of game (dont show stuff out of bounds)
let render_rect = new PIXI.Graphics();
render_rect.beginFill(0xFFFFFF);
render_rect.drawRect(0,0,this.options.width,this.options.height);
render_rect.endFill();
// resize background sprites
bg_sprite1.width = parent.clientWidth;
bg_sprite1.height = parent.clientHeight;
if (blanke_ref.options.ide_mode || blanke_ref.options.scale) {
bg_sprite2.width = parent.clientWidth;
bg_sprite2.height = parent.clientHeight;
} else {
bg_sprite2.width = this.options.width;
bg_sprite2.height = this.options.height;
}
const removeSnaps = () => {
// remove any pause image
let old_img = app.view.parentNode.querySelector("#game-snap");
if (old_img)
old_img.remove();
}
const engineLoaded = () => {
// EFFECT init
Effect.library = {};
// SCENE init
Scene.fn_ref = {}; // { SceneName: { onStart:(), onUpdate:(), ...}}
Scene.ref = {}; // { SceneName: [Scene instance] }
Scene.stack = []; // [ SceneName1, SceneName2 ]
Game.obj = new GameRef(game_container);
if (Game.os != "web") {
window.addEventListener('resize',function(){
app.renderer.resize(parent.clientWidth, parent.clientHeight);
game_container.x = 0;
game_container.y = 0;
if (!blanke_ref.options.ide_mode && blanke_ref.options.scale) {
let scale_x = parent.clientWidth / Game.width;
let scale_y = parent.clientHeight / Game.height;
let scaling = Math.min(scale_x, scale_y);
game_container.scale.set(scaling);
if (scale_x > scale_y)
game_container.x = (parent.clientWidth/2) - (game_container.width/2);
else
game_container.y = (parent.clientHeight/2) - (game_container.height/2);
bg_sprite1.width = parent.clientWidth;
bg_sprite1.height = parent.clientHeight;
// redraw mask
render_rect.clear();
render_rect.beginFill(0xFFFFFF);
render_rect.drawRect(
game_container.x, game_container.y,
game_container.width, game_container.height
);
render_rect.endFill();
game_container.mask = render_rect;
} else {
game_container.scale.set(1);
bg_sprite2.width = parent.clientWidth;
bg_sprite2.height = parent.clientHeight;
game_container.mask = null;
}
if (app.stage.hitArea) {
app.stage.hitArea.width = Game.width;
app.stage.hitArea.height = Game.height;
}
}, false);
}
Game.time = 0;
Game.ide_mode = this.options.ide_mode;
// load config.json
if (this.options.config != null) {
Game.config = this.options.config;
if (this.options.resizable || this.options.ide_mode) {
app.resizeTo = parent;
}
}
// update Map.obj_uuid
if (Game.config.scene) {
for (let uuid in Game.config.scene.objects) {
Map.obj_uuid[Game.config.scene.objects[uuid].name] = uuid;
}
}
// scene callback
Event.on('Scene.end',(name)=>{
// remove Timers
Timer.fn_after = Timer.fn_after.filter(t => t.scene != name);
Timer.fn_every = Timer.fn_every.filter(t => t.scene != name);
// remove Events
for (let name in Event.ref) {
Event.ref[name] = Event.ref[name].filter(e => e.scene != name);
}
})
parent.appendChild(app.view);
removeSnaps();
Asset.add(this.options.assets);
Asset.load(() => {
if (this.options.onLoad)
this.options.onLoad(classes);
if (Game.config.first_scene && Scene.stack.length == 0) {
Scene.start(Game.config.first_scene);
}
})
// default fullscreen shortcut (NOT WORKING)
Input.set('toggle-fullscreen','Alt Enter');
empty_sprite = new Sprite({ no_scene : true });
Text.temp_sprite = new Sprite({ no_scene : true });
Game.loaded = true;
empty_canvas = new Canvas({ no_scene : true });
var new_event = new CustomEvent('blankeLoaded', {'detail': { 'Blanke':classes }});
document.dispatchEvent(new_event);
}
// Pixi object
const replaceChild = (child, new_child) => {
let parent = child.parent;
if (parent) {
child.destroy();
new_child.setParent(parent);
}
}
const aliasProps = (parent, child, props) => {
for (let p of props) {
parent.stop_getset = false;
Object.defineProperty(parent,p,{
get: function () {
if (parent.get && !parent.stop_getset) {
parent.stop_getset = true
parent.get(p);
parent.stop_getset = false;
}
return child[p];
},
set: function (v) {
// TODO: allow user to change value?
child[p] = v;
if (parent.set && !parent.stop_getset) {
parent.stop_getset = true
parent.set(p,v);
parent.stop_getset = false;
}
}
});
}
}
const storeInstance = (c,i) => {
if (!c.instances) c.instances = [];
c.instances.push(i);
}
const quickSort = (items, fn) => {
fn = fn || function (a, b) { return a < b; };
function _sort(array) {
countOuter++;
if(array.length < 2) {
return array;
}
let pivot = array[0];
let lesser = [];
let greater = [];
for(let i = 1; i < array.length; i++) {
countInner++;
if(fn(array[i], pivot)) { // array[i] < pivot) {
lesser.push(array[i]);
} else {
greater.push(array[i]);
}
}
return _sort(lesser).concat(pivot, _sort(greater));
}
return _sort (items);
}
/* -GAMEOBJECT */
let gobject_tex_cache = {};
class GameObject {
constructor () {
this.uuid = Util.uuid();
}
get z () { return this._z || 0; }
set z (v) {
this._z = v;
let containers = [];
if (this._getPixiObjs) {
this._getPixiObjs().forEach(o => {
let container = o.parent;
o.zIndex = this.z;
if (container && !containers.includes(container))
containers.push(container);
});
}
// sort the collected containers
containers.forEach((cont) => {
cont.sortableChildren = true;
cont.sortChildren();
})
}
_getPixiObjs () { return []; }
destroyPixiObjs () { this._getPixiObjs().forEach(o => o.destroy() )}
getRect () { return new Rectangle(); }
get visible () { return this._visible || true; }
set visible (v) {
this._visible = v;
this._getPixiObjs().forEach(o => { o.visible = v });
}
get rect () {
if (this._rect) this.hitArea = obj._rect;
return this._rect || this.getRect() || new Rectangle();
}
set rect (v) {
this._rect = v;
this._getPixiObjs().forEach(pixi_obj => {
pixi_obj.hitArea = v;
})
}
get effect () {
if (!this._effect) {
this._effect = new EffectManager(this);
}
return this._effect.effects;
}
set effect (v) {
if (!this._effect) {
this.effectArea = app.renderer.screen
this._effect = new EffectManager(this);
}
this._effect.add(v);
}
set effectArea (v) {
this._getPixiObjs().forEach(pixi_obj => {
pixi_obj.filterArea = v;
})
}
get particle () {
return this._particle == true;
}
set particle (v) {
this._particle = v;
if (this._particle == true)
this._getPixiObjs().forEach(o => Scene.addParticle(o));
else
this._getPixiObjs().forEach(o => Scene.addDrawable(o));
}
getTexture () {
let cache_id = this.uuid;
let offx = 0, offy = 0;
if (this.is_entity) {
cache_id += this.sprite_index + this.sprite_frame;
}
if (!gobject_tex_cache[cache_id]) {
let max_w = 0, max_h = 0, rect;
this._getPixiObjs().forEach((obj) => {
rect = obj.getBounds();
if (rect.width > max_w) max_w = rect.width;
if (rect.height > max_h) max_h = rect.height;
})
let new_canvas = PIXI.RenderTexture.create(max_w, max_h);
let { x: bx, y: by } = this.sprites[this.sprite_index].sprite.getBounds();
offx = bx - this.x;
offy = by - this.y;
this._getPixiObjs().forEach(obj => {
app.renderer.render(obj, new_canvas, true, new Matrix(1,0,0,1,-bx,-by));
})
gobject_tex_cache[cache_id] = [new_canvas, offx, offy];
}
let cache = gobject_tex_cache[cache_id];
var new_spr = new PIXI.Sprite(cache[0]);
new_spr.pivot.copyFrom(this.sprite_pivot);
new_spr.anchor.copyFrom(this.sprite_anchor);
return new_spr;
}
restorePrevParent () {
if (!this._getPixiObjs) return false;
let pixi_objs = this._getPixiObjs();
for (let o of pixi_objs) {
if (o._last_parent) {
let curr_parent = o.parent;
o.setParent(o._last_parent)
o._last_parent = curr_parent;
}
}
return true;
}
setParent (parent) {
let pixi_objs = this._getPixiObjs();
for (let o of pixi_objs) {
o._last_parent = o.parent;
o.setParent(parent);
}
return true;
}
}
//var cull = new Cull.SpatialHash();
// UUID stuff
function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+
-1e3+
-4e3+
-8e3+
-1e11).replace(/[018]/g,b)}
function uuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)}
/* -GAME */
class GameRef extends GameObject {
constructor (g_container) {
super();
this.container = g_container
}
_getPixiObjs () {
return [this.container];
}
}
var Game = {
config: {},
time: 0,
ms: 0,
loaded: false,
obj: null,
get os () { // ide, win, mac, linux, android, ios
if (blanke_ref.options.ide_mode) return 'ide';
let os_list = ['win','mac','linux','android'];
let browser_list = ['chrome','firefox','safari','opera','opr','msie'];
let not_browser = ['seamonkey','chromium','blanke','electron'];
let u_agent = navigator.userAgent.toLowerCase();
// web browsers
for (let a of browser_list) {
if (u_agent.includes(a)) {
let skip = false;
for (let n of not_browser) {
if (u_agent.includes(n))
skip = true;
}
if (!skip)
return 'web';
}
}
// desktop/android
for (let d of os_list) {
if (u_agent.includes(d))
return d;
}
// ios
if (/ipad|iphone|ipod/i.test(u_agent))
return 'ios';
return '?';
},
get width () {
return (!(blanke_ref.options && blanke_ref.options.scale) || blanke_ref.options.ide_mode) && app.view ? app.view.width : blanke_ref.options.width;
},
get height () {
return (!(blanke_ref.options && blanke_ref.options.scale) || blanke_ref.options.ide_mode) && app.view ? app.view.height : blanke_ref.options.height;
},
get background_color () { return app.renderer.backgroundColor; },
set background_color (v) {
app.renderer.backgroundColor = v;
bg_sprite2.tint = app.renderer.backgroundColor;
},
get effect () {
return Game.obj.effect;
},
set effect (v) {
Game.obj.effect = v;
},
paused: false,
pause: () => {
Game.paused = true;
app.ticker.stop();
if (Game.onPause) Game.onPause();
},
resume: () => {
Game.paused = false;
app.ticker.start();
if (Game.onPause) Game.onPause();
},
step: () => {
/*
app.ticker.update(performance.now());
app.renderer.render(app.stage);
*/
if (Game.paused) {
Game.resume()
app.ticker.addOnce(()=>{
Game.pause();
},null,PIXI.UPDATE_PRIORITY.UTILITY);
}
},
elec_win: null,
get window () {
if (['win','mac','linux'].includes(Game.os) && elec) {
return elec.remote.BrowserWindow.getFocusedWindow();
}
},
// replaces the game with a screenshot
freeze: () => {
if (Game.frozen) return;
Game.frozen = true;
removeSnaps();
let new_rtex = PIXI.RenderTexture.create(Game.width, Game.height);
app.renderer.render(game_container, new_rtex);
let el_img = app.renderer.extract.image(new_rtex);
el_img.id = "game-snap";
parent.appendChild(el_img);
app.stop();
app.view.style.display = "none";
},
unfreeze: () => {
if (!Game.frozen) return;
Game.frozen = false;
if (!app) return;
removeSnaps();
app.start();
app.view.style.display = "initial";
},
get fullscreen () {
if (Game.os != 'ide')
return document.fullscreen;
return false;
},
set fullscreen (v) {
if (Game.os != 'ide') {
let win = Game.window;
if (win)
win.setResizable(true);
let c = app.view;
if (v) {
(
c.requestFullscreen ||
c.mozRequestFullScreen ||
c.webkitRequestFullScreen ||
c.msRequestFullscreen ||
function () {throw new Error("Can't enter fullscreen!")}
).call(c);
} else {
(
document.exitFullscreen ||
document.mozCancelFullScreen ||
document.webkitCancelFullScreen ||
document.msExitFullscreen ||
function () {throw new Error("Can't leave fullscreen!")}
).call(document);
}
if (win)
win.setResizable(blanke_ref.options.resizable);
}
},
end: () => {
if (!app) return;
removeSnaps();
Game.resume();
// destroy scenes
Scene.endAll();
Scene.ref = {};
// remove leftover game objects
Scene.destroyStrays();
game_container.removeChildren();
// reset input stuff
input_ref = {};
Effect.library = {};
Game.loaded = false;
},
destroy: () => { app.destroy(true); }
};
/* -UTIL */
var Util = {
uuid: () => uuid(),
aliasProps: (...args) => aliasProps(...args),
// math
rad: (deg) => deg * (Math.PI/180),
deg: (rad) => rad * (180/Math.PI),
direction_x: (angle, dist) => angle == 0 ? dist : Math.cos(Util.rad(angle)) * dist,
direction_y: (angle, dist) => angle == 0 ? dist : Math.sin(Util.rad(angle)) * dist,
distance: (x1, y1, x2, y2) => Math.sqrt(Math.pow((x2-x1),2)+Math.pow((y2-y1),2)),
direction: (x1, y1, x2, y2) => Util.deg(Math.atan2(y2-y1,x2-x1)),
// rand_range -> int [min,max)
rand_range: (min, max) => Math.floor(Math.random() * (max - min)) + min,
rand_choose: (arr) => arr[Util.rand_range(0,arr.length)],
lerp: (a, b, amt) => a + amt * (b - a),
sinusoidal: (min, max, spd, off=0) => min + -Math.cos(Util.lerp(0,Math.PI/2,off) + Game.time * spd) * ((max - min)/2) + ((max - min)/2),
clamp: (x, min, max) => x < min ? min : x > max ? max : x,
// string
str_count: (string, subString, allowOverlapping) => {
// author: Vitim.us https://gist.github.com/victornpb/7736865
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var n = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++n;
pos += step;
} else break;
}
return n;
},
// programming helper
repeat: (i, fn) => {
while (i-- > 0)
if (fn() == true) i = 0;
},
// file
basename: (path, no_ext) => no_ext == true ? path.split(re_sep).slice(-1)[0].split('.')[0] : path.split(re_sep).slice(-1)[0],
extname: (path) => path.replace(/[\w_\\.\-\/]+\./,'')
}
app.ticker.add((dt)=>{
Game.time += dt;
Game.ms += app.ticker.deltaMS;
if (Input('toggle-fullscreen').released) {
Game.fullscreen = !Game.fullscreen;
}
});
/* -ASSET */
var Asset = {
data: {},
path_name: {},
loader: new PIXI.Loader(),
supported_filetypes: {
/* options: { name, frames, frame_size, offset, columns } */
'image':['png'],
'audio':['wav'],
'map':['map'],
'font':['ttf']
},
base_textures: {},
getType: (path) => {
let parts = path.split('.');
let ext = parts.pop();
let name = Asset.parseAssetName(path);
for (let type in Asset.supported_filetypes) {
if (Asset.supported_filetypes[type].includes(ext))
return [type, Util.basename(name)];
}
return ['file', Util.basename(name)];
},
parseAssetName: (path) => {
return path.replace(/[\w_\\.\-\/]+\/assets\/\w+\//,'').split('.').slice(0,-1).join('.');
},
// callback only used in : json
add: (orig_path, options={}) => {
// adding multiple
if (Array.isArray(orig_path)) {
for (let ast of orig_path) {
Asset.add(...ast);
}
return;
}
let path = (this.options.root ? this.options.root + '/' : '') + orig_path;
let [type, name] = Asset.getType(path);
if (Asset.data[type] && Asset.data[type][name]) return;
// default values
if (type == 'image') {
// IMAGE
// NOTE: do NOT add frame_size as that is mandatory if it's an animated sprite
options = Object.assign({
name: name,
offset: [0,0],
columns: 1,
frames: 1,
speed: 1
}, typeof options === "string" ? {name:options} : (options || {}));
name = options.name;
} else {
name = typeof options === "string" ? options : (options.name || name)
}
// add it to loader
Asset.loader.add(name, path, {metadata:{type:type, options:options}}, Asset._onComplete);
},
_onComplete: (info) => {
let type = info.metadata.type;
let data = info.data;
let name = info.name;
let options = info.metadata.options;
let path = info.url;
let storeAsset = (_type,_path,_name, _data) => {
if (!(_type && _path && _name)) return;
if (!Asset.data[_type]) {
Asset.path_name[_type] = {};
Asset.data[_type] = {};
}
if (!Asset.path_name[_type][_path])
Asset.path_name[_type][_path] = []
Asset.path_name[_type][_path].push(_name);
Asset.data[_type][_name] = _data;
}
switch (type) {
// IMAGE / Animation IMAGE
case 'image':
let img_obj = {path:path, animated:false, options:options};
// base texture
if (!Asset.base_textures[path]) {
Asset.base_textures[path] = info.texture.baseTexture;// PIXI.BaseTexture.from(path, {crossorigin:false});
}
let base_tex = Asset.base_textures[path];
if (options && options.frame_size) {
img_obj.animated = true;
name = options.name;
options.from_asset = true;
// crop texture frames
let result = Asset.texCrop(path, options, base_tex);
img_obj.frames = result.frames;
img_obj.tex_frames = result.tex_frames;
}
img_obj.texture = info.texture;// new PIXI.Texture(base_tex);
storeAsset(type, path, name, img_obj);
Asset.data[type][name] = img_obj;
return img_obj;
break;
// FILE / MAP : json, text, file with data...
case 'file':
case 'map':
storeAsset(type, path, name, data);
break;
// AUDIO
case 'audio':
storeAsset(type, path, name, new Howl({src:[path]}));
break;
}
},
audioSprite: (name, sprites) => {
let path = Asset.getPath('audio',name)
if (!path) return;
let new_audio = new Howl({src:[path], sprite:sprites});
Asset.data.audio[name] = new_audio;
return new_audio;
},
tex_crop_cache: {},
texCrop: (path, opt, base_tex) => {
opt = Object.assign({
offset: [0,0],
spacing: [0,0],
columns: 1,
frames: 1,
speed: 1,
is_key: false,
from_asset: false,
}, opt);
let real_path = Asset.getPath('image', path);
if (real_path)
path = real_path;
else if (!opt.from_asset)
path = (this.options.root ? this.options.root + '/' : '') + path;
if (opt.is_key)
return Asset.tex_crop_cache[path];
if (!base_tex) {
// use supplied name
if (!Asset.base_textures[path]) {
Asset.base_textures[path] = PIXI.BaseTexture.from(path, {crossorigin:false})
}
base_tex = Asset.base_textures[path]
}
let key = [path.match(re_no_ext)[1], opt.offset[0], opt.offset[1], opt.frame_size[0], opt.frame_size[1], opt.columns||0].join(',');
if (!Asset.tex_crop_cache[key]) {
// get options
let offx = opt.offset[0], offy = opt.offset[1];
let framew = opt.frame_size[0], frameh = opt.frame_size[1];
let spacingx = opt.spacing[0], spacingy = opt.spacing[1];
let col = opt.columns;
let x = offx, y = offy, w = framew, h = frameh;
let frames = [];
// generate rectangles
for (let f = 0; f < opt.frames; f++) {
frames.push(
[x, y, w, h]
);
x += framew + spacingx;
// next row?
if ((f % col) - 1 > col) {
x = offx;
y += frameh + spacingy;
}
}
Asset.tex_crop_cache[key] = {
key: key,
frames: frames,
tex_frames: frames.map(dims => new PIXI.Texture(base_tex, new PIXI.Rectangle(dims[0], dims[1], dims[2], dims[3])))
}
}
return Asset.tex_crop_cache[key];
},
load: (cb) => {
Asset.loader.onComplete.add(cb)
Asset.loader.load();
},
get: (type, name) => {
if (Asset.data[type] && Asset.data[type][name])
return Asset.data[type][name];
},
getName: (type, path) => {
if (Asset.path_name[type] && Asset.path_name[type][path])
return Asset.path_name[type][path];
return [];
},
getPath: (type, name) => {
if (Asset.path_name[type]) {
for (let path in Asset.path_name[type]) {
if (Asset.path_name[type][path].includes(name)) {
return path;
}
}
}
}
}
/* -DRAW
Draw([args])
Ex. // Draw a star
new Draw([
['lineStyle', 2, 0xFFFFFF],
['fill', 0x35CC5A, 1],
['star', Game.width/2, Game.height/2, 5, 50],
['fill']
]);
*/
class Draw extends GameObject {
constructor (...args) {
super();
this.graphics = new PIXI.Graphics();
this.auto_clear = true;
aliasProps(this, this.graphics, ['x','y','width','height','visible','alpha','scale','skew','angle'])
Scene.addDrawable(this.graphics);
this.draw(...args);
}
_getPixiObjs () {
return [this.graphics];
}
draw (...args) {
let getTex = (name) => {
let asset_path = Asset.getPath('image',name)
return asset_path ? Asset.base_texture[asset_path] : name;
}
if (this.auto_clear)
this.clear();
let in_hole = false;
for (let arg of args) {
let skip_call = false; // not actually used yet
let name = Draw.functions[arg[0]] || arg[0];
let params = arg.slice(1);
let extra_calls = [];
if (name == 'beginFill' && params.length == 0) {
name = 'endFill';
}
if (name == 'beginTextureFill') {
if (params.length == 0)
name = "endFill";
else
params[0] = getTex(params[0]);
}
if (name == 'lineTextureStyle') // width, line, ...
params[1] = getTex(params[1]);
if (name == 'drawStar' && params.length >= 6)
params[5] = Util.rad(params[5])
if (name == 'arc') {
if (params.length >= 4)
params[3] = Util.rad(params[3])
if (params.length >= 5)
params[4] = Util.rad(params[4])
}
if (name == 'beginHole' && in_hole) {
if (in_hole)
name = 'endHole';
in_hole = !in_hole;
}
if (name == 'entity' && params[0].sprite_index != '') {
name = 'beginTextureFill'
let ent = params[0];
let spr = ent.sprites[ent.sprite_index]
params[0] = spr.texture;
if (!params[1]) params[1] = Draw.white;
if (!params[2]) params[2] = 1;
if (!params[3]) params[3] = spr.matrix;
extra_calls = [
['drawRect',spr.x - spr.pivot.x,spr.y - spr.pivot.y,spr.width,spr.height],
['endFill']
];
}
if (!skip_call && (typeof this.graphics[name]) == 'function')
this.graphics[name](...params);
else
throw new Error(`${name} is not a Draw function`);
if (extra_calls)
for (let call of extra_calls)
this.graphics[call[0]](...call.slice(1));
}
}
containsPoint (x, y) {
return this.graphics.containsPoint(new PIXI.Point(x,y));
}
clear () {
this.graphics.clear();
}
destroy () {
this.graphics.destroy();
}
// rgb to hex
static hex (rgb) {
let _hex = v => {
let h = v.toString(16);
return h.length == 1 ? '0' + h : h;
}
return '#'+_hex(rgb[0])+_hex(rgb[1])+_hex(rgb[2]);
}
// hex to rgb
static rgb (hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)] : null;
}
}
Draw.functions = {
fill: 'beginFill',
texture: 'beginTextureFill',
bezier: 'bezierCurveTo',
quadCurve: 'quadraticCurveTo',
hole: 'beginHole',
rect: 'drawRect',
circle: 'drawCircle',
polygon: 'drawPolygon',
roundRect: 'drawRoundedRect',
ellipse: 'drawEllipse',
star: 'drawStar'
}
Draw.colors = {
red: 0xF44336, pink: 0xE91E63, purple: 0x673AB7,
indigo: 0x3F51B5, baby_blue: 0x80D8FF, blue: 0x2196F3,
dark_blue: 0x0C47A1, green: 0x4CAF50, yellow: 0xFFEB3B,
orange: 0xFFC107, brown: 0x795548, gray: 0x9E9E9E,