-
Notifications
You must be signed in to change notification settings - Fork 626
Expand file tree
/
Copy pathtilemap.ts
More file actions
2153 lines (1831 loc) · 78.5 KB
/
tilemap.ts
File metadata and controls
2153 lines (1831 loc) · 78.5 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
namespace pxt {
export const IMAGE_MIME_TYPE = "image/x-mkcd-f4"
export const TILEMAP_MIME_TYPE = "application/mkcd-tilemap"
export const ANIMATION_MIME_TYPE = "application/mkcd-animation"
export const SONG_MIME_TYPE = "application/mkcd-song"
export const enum AssetType {
Image = "image",
Tile = "tile",
Tilemap = "tilemap",
Animation = "animation",
Song = "song"
}
export interface AssetMetadata {
displayName?: string;
tags?: string[];
blockIDs?: string[];
temporaryInfo?: TemporaryAssetInfo;
package?: string;
}
export interface TemporaryAssetInfo {
blockId: string;
fieldName: string;
}
export type Asset = ProjectImage | Tile | Animation | ProjectTilemap | Song;
export interface BaseAsset {
internalID: number;
id: string;
meta: AssetMetadata;
previewURI?: string;
}
export interface ProjectImage extends BaseAsset {
type: AssetType.Image;
jresData: string;
bitmap: pxt.sprite.BitmapData;
}
export interface Tile extends BaseAsset {
type: AssetType.Tile;
jresData: string;
bitmap: pxt.sprite.BitmapData;
isProjectTile?: boolean;
}
export interface Animation extends BaseAsset {
type: AssetType.Animation;
frames: pxt.sprite.BitmapData[];
flippedHorizontal?: boolean;
frameIds?: string[];
framePreviewURIs?: string[];
interval: number;
}
export interface TileSet {
tileWidth: number;
tiles: Tile[];
}
export interface TileSetCollection {
extensionID: string;
tileSets: TileSet[];
}
export interface ProjectTilemap extends BaseAsset {
type: AssetType.Tilemap;
data: pxt.sprite.TilemapData;
}
export interface Song extends BaseAsset {
type: AssetType.Song;
song: assets.music.Song;
}
export interface TilemapSnapshot {
revision: number;
projectTilemaps?: ProjectTilemap[];
projectTileSet?: TileSetCollection;
takenNames?: pxt.Map<boolean>
projectImages?: ProjectImage[];
}
interface AssetSnapshot {
revision: number;
tiles: AssetCollection<Tile>;
tilemaps: AssetCollection<ProjectTilemap>;
images: AssetCollection<ProjectImage>;
animations: AssetCollection<Animation>;
songs: AssetCollection<Song>;
}
interface AssetSnapshotDiff {
beforeRevision: number;
afterRevision: number;
tiles: AssetCollectionDiff<Tile>;
tilemaps: AssetCollectionDiff<ProjectTilemap>;
images: AssetCollectionDiff<ProjectImage>;
animations: AssetCollectionDiff<Animation>;
songs: AssetCollectionDiff<Song>;
}
interface AssetUpdateListener {
internalID: number;
callback: () => void;
}
interface AssetCollectionDiff<U> {
before: U[];
after: U[];
}
class AssetCollection<U extends Asset> {
protected assets: U[] = [];
protected takenNames: pxt.Map<boolean> = {};
protected listeners: AssetUpdateListener[] = [];
add(asset: U) {
if (this.takenNames[asset.id]) {
return this.update(asset.id, asset);
}
else {
const clone = cloneAsset(asset);
this.takenNames[clone.id] = true;
this.takenNames[getShortIDForAsset(clone)] = true;
if (clone.meta.displayName && clone.meta.displayName !== clone.id) {
if (this.takenNames[clone.meta.displayName]) {
clone.meta.displayName = this.generateNewDisplayName(clone.meta.displayName);
}
this.takenNames[clone.meta.displayName] = true;
}
this.assets.push(clone);
return cloneAsset(clone);
}
}
getSnapshot(filter?: (asset: U) => boolean) {
if (filter) {
return this.assets.filter(a => filter(a)).map(cloneAsset);
}
return this.assets.map(cloneAsset);
}
update(id: string, newValue: U) {
let asset: U;
if (this.takenNames[id]) {
const existing = this.lookupByID(id);
if (!assetEquals(existing, newValue)) {
if (!validateAsset(newValue) && validateAsset(existing)) {
pxt.warn("Refusing to overwrite asset with invalid version");
pxt.tickEvent("assets.invalidAssetOverwrite", { assetType: newValue.type });
return existing;
}
this.removeByID(id);
asset = this.add(newValue);
this.notifyListener(newValue.internalID);
}
else {
asset = newValue;
}
}
else {
asset = this.add(newValue);
}
return asset;
}
removeByID(id: string): void {
const existing = this.lookupByID(id);
this.assets = this.assets.filter(a => a.id !== id);
delete this.takenNames[id];
if (existing) {
delete this.takenNames[getShortIDForAsset(existing)]
}
if (existing?.meta.displayName) {
delete this.takenNames[existing?.meta.displayName];
}
}
getByID(id: string): U {
const asset = this.lookupByID(id);
return asset && cloneAsset(asset);
}
getByDisplayName(name: string): U {
if (this.takenNames[name]) {
for (const asset of this.assets) {
if (asset.meta.displayName === name || getShortIDForAsset(asset) === name) {
return cloneAsset(asset);
}
}
}
return undefined;
}
getByValue(toFind: U) {
for (const asset of this.assets) {
if (assetEquals(toFind, asset, true)) {
return asset;
}
}
return undefined;
}
isIDTaken(id: string) {
return !!this.takenNames[id];
}
clone() {
const cloned = new AssetCollection<U>();
cloned.assets = this.getSnapshot();
cloned.takenNames = { ...this.takenNames };
return cloned;
}
serializeToJRes(allJRes: pxt.Map<JRes | string> = {}, filter?: (asset: U) => boolean): pxt.Map<JRes | string> {
for (const asset of this.assets) {
if (filter && !filter(asset)) continue;
addAssetToJRes(asset, allJRes);
}
return allJRes;
}
addListener(internalID: number, listener: () => void) {
this.listeners.push({ internalID, callback: listener })
}
removeListener(listener: () => void) {
this.listeners = this.listeners.filter(ref => ref.callback !== listener);
}
diff(past: AssetCollection<U>) {
let diff: AssetCollectionDiff<U> = {
before: [],
after: []
};
let handled: {[index: number]: boolean} = {};
for (const pastAsset of past.assets) {
handled[pastAsset.internalID] = true;
const futureAsset = this.lookupByInternalID(pastAsset.internalID);
if (!futureAsset || !assetEquals(pastAsset, futureAsset)) {
diff.before.push(pastAsset);
diff.after.push(futureAsset);
}
}
for (const futureAsset of this.assets.filter(a => !handled[a.internalID])) {
diff.before.push(null);
diff.after.push(futureAsset);
}
return diff;
}
applyDiff(diff: AssetCollectionDiff<U>, backwards = false) {
const before = backwards ? diff.after : diff.before;
const after = backwards ? diff.before : diff.after;
pxt.Util.assert(before.length === after.length);
for (let i = 0; i < before.length; i++) {
if (!before[i]) {
this.assets.push(after[i]);
this.notifyListener(after[i].internalID);
continue;
}
this.removeByInternalID(before[i].internalID)
if (after[i]) {
this.assets.push(after[i]);
}
this.notifyListener(before[i].internalID);
}
this.takenNames = {};
for (const asset of this.assets) {
pxt.Util.assert(!this.takenNames[asset.id]);
this.takenNames[asset.id] = true;
this.takenNames[getShortIDForAsset(asset)] = true;
if (asset.meta.displayName) {
if (asset.meta.displayName !== asset.id) pxt.Util.assert(!this.takenNames[asset.meta.displayName]);
this.takenNames[asset.meta.displayName] = true;
}
}
}
protected lookupByID(id: string): U {
for (const asset of this.assets) {
if (asset.id === id) {
return asset;
}
}
return null;
}
protected lookupByInternalID(id: number): U {
for (const asset of this.assets) {
if (asset.internalID === id) {
return asset;
}
}
return null;
}
protected removeByInternalID(id: number): void {
this.assets = this.assets.filter(a => a.internalID !== id);
}
protected notifyListener(internalID: number) {
for (const listener of this.listeners) {
if (listener.internalID === internalID) listener.callback();
}
}
protected generateNewDisplayName(prefix: string) {
prefix = prefix.replace(/\d+$/, "");
let index = 0;
while (this.takenNames[prefix + index]) {
++index;
}
return prefix + index;
}
}
export class TilemapProject {
public needsRebuild = true;
protected extensionTileSets: TileSetCollection[];
protected state: AssetSnapshot;
protected committedState: AssetSnapshot;
protected gallery: AssetSnapshot;
protected undoStack: AssetSnapshotDiff[];
protected redoStack: AssetSnapshotDiff[];
protected nextID = 0;
protected nextInternalID = 0;
constructor() {
this.committedState = {
revision: 0,
tilemaps: new AssetCollection(),
tiles: new AssetCollection(),
animations: new AssetCollection(),
images: new AssetCollection(),
songs: new AssetCollection(),
};
this.state = {
revision: this.nextID++,
tilemaps: new AssetCollection(),
tiles: new AssetCollection(),
animations: new AssetCollection(),
images: new AssetCollection(),
songs: new AssetCollection(),
};
this.gallery = {
revision: 0,
tilemaps: new AssetCollection(),
tiles: new AssetCollection(),
animations: new AssetCollection(),
images: new AssetCollection(),
songs: new AssetCollection(),
};
this.undoStack = [];
this.redoStack = [];
}
public getNewInternalId() {
return this.nextInternalID++;
}
public createNewImage(width = 16, height = 16) {
this.onChange();
const id = this.generateNewID(AssetType.Image);
const bitmap = new pxt.sprite.Bitmap(width, height).data()
const newImage: ProjectImage = {
internalID: this.getNewInternalId(),
id,
type: AssetType.Image,
bitmap: bitmap,
meta: {},
jresData: pxt.sprite.base64EncodeBitmap(bitmap)
};
return this.state.images.add(newImage);
}
public createNewAnimation(width = 16, height = 16) {
this.onChange();
const id = this.generateNewID(AssetType.Animation);
const bitmap = new pxt.sprite.Bitmap(width, height).data()
const newAnimation: Animation = {
internalID: this.getNewInternalId(),
id,
type: AssetType.Animation,
frames: [bitmap],
interval: 500,
meta: {},
};
return this.state.animations.add(newAnimation);
}
public createNewAnimationFromData(frames: pxt.sprite.BitmapData[], interval = 500, displayName?: string) {
this.onChange();
const id = this.generateNewID(AssetType.Animation);
const newAnimation: Animation = {
internalID: this.getNewInternalId(),
id,
type: AssetType.Animation,
frames,
interval,
meta: { displayName },
};
return this.state.animations.add(newAnimation);
}
public getGalleryTiles(tileWidth: number): TileSet[] | null {
if (this.extensionTileSets) {
return this.extensionTileSets.map(
collection => collection.tileSets.find(tileSet => tileSet.tileWidth === tileWidth)
).filter(tileSet => tileSet?.tiles.length);
}
return null;
}
public getProjectImages(): ProjectImage[] {
return this.state.images.getSnapshot();
}
public getProjectTiles(tileWidth: number, createIfMissing: boolean): TileSet | null {
const tiles = this.state.tiles.getSnapshot(tile => tile.bitmap.width === tileWidth);
if (tiles.length === 0) {
if (createIfMissing) {
// This will create a new tileset with the correct width
this.createNewTile(new pxt.sprite.Bitmap(tileWidth, tileWidth).data())
return this.getProjectTiles(tileWidth, false);
}
return null;
}
return {
tileWidth,
tiles
}
}
public createNewTile(data: pxt.sprite.BitmapData, id?: string, displayName?: string) {
this.onChange();
if (!id || this.isNameTaken(AssetType.Tile, id)) {
id = this.generateNewID(AssetType.Tile);
}
const newTile: Tile = {
internalID: this.getNewInternalId(),
id,
type: AssetType.Tile,
jresData: pxt.sprite.base64EncodeBitmap(data),
bitmap: data,
meta: {
displayName
},
isProjectTile: true
};
return this.state.tiles.add(newTile);
}
public createNewProjectImage(data: pxt.sprite.BitmapData, displayName?: string) {
this.onChange();
const newImage: ProjectImage = {
internalID: this.getNewInternalId(),
id: this.generateNewID(AssetType.Image),
type: AssetType.Image,
jresData: pxt.sprite.base64EncodeBitmap(data),
meta: {
displayName
},
bitmap: data
};
return this.state.images.add(newImage);
}
public createNewSong(data: pxt.assets.music.Song, displayName?: string) {
this.onChange();
const newSong: Song = {
internalID: this.getNewInternalId(),
id: this.generateNewID(AssetType.Song),
type: AssetType.Song,
song: pxt.assets.music.cloneSong(data),
meta: {
displayName
},
};
return this.state.songs.add(newSong);
}
public updateTile(tile: pxt.Tile) {
this.onChange();
const existing = this.resolveProjectTileByInternalID(tile.internalID);
if (existing) {
this.state.tiles.update(existing.id, tile);
if (existing.id !== tile.id || !pxt.sprite.bitmapEquals(existing.bitmap, tile.bitmap)) {
for (const tm of this.getAssets(AssetType.Tilemap)) {
if (tm.data.tileset.tiles.some(t => t.internalID === tile.internalID)) {
tm.data.tileset.tiles = tm.data.tileset.tiles.map(t => t.internalID === tile.internalID ? tile : t);
this.updateTilemap(tm.id, tm.data);
}
}
}
return tile;
}
return null;
}
public deleteTile(id: string) {
this.onChange();
this.state.tiles.removeByID(id);
}
public getProjectTilesetJRes(projectFiles?: pxt.Map<{content: string}>) {
const blob: pxt.Map<any> = {};
this.state.tiles.serializeToJRes(blob);
// tilemaps are always named assets, so if the user creates a bunch by
// accident (e.g. by dragging out blocks) we want to only serialize the ones
// that are actually used/nonempty
this.state.tilemaps.serializeToJRes(blob, asset => {
if (!projectFiles) return true;
return !pxt.sprite.isTilemapEmptyOrUnused(asset, this, projectFiles)
});
blob["*"] = {
"mimeType": "image/x-mkcd-f4",
"dataEncoding": "base64",
"namespace": pxt.sprite.TILE_NAMESPACE
};
return blob;
}
public getProjectAssetsJRes() {
const blob: pxt.Map<any> = {};
this.state.images.serializeToJRes(blob);
this.state.animations.serializeToJRes(blob);
this.state.songs.serializeToJRes(blob);
blob["*"] = {
"mimeType": "image/x-mkcd-f4",
"dataEncoding": "base64",
"namespace": pxt.sprite.IMAGES_NAMESPACE
};
return blob;
}
public getTilemap(id: string) {
return this.state.tilemaps.getByID(id);
}
public updateTilemap(id: string, data: pxt.sprite.TilemapData): ProjectTilemap {
const existing = this.state.tilemaps.getByID(id);
if (existing) {
this.onChange();
const newValue = {
...existing,
data: data,
};
this.state.tilemaps.update(id, newValue);
return newValue;
}
return null;
}
public createNewTilemap(name: string, tileWidth: number, width = 16, height = 16): [string, pxt.sprite.TilemapData] {
return this.createNewTilemapFromData(this.blankTilemap(tileWidth, width, height), name)
}
public blankTilemap(tileWidth: number, width = 16, height = 16) {
const tilemap = new pxt.sprite.Tilemap(width, height);
const layers = new pxt.sprite.Bitmap(width, height);
const tileset = {
tileWidth,
tiles: [this.getTransparency(tileWidth)]
};
return new pxt.sprite.TilemapData(tilemap, tileset, layers.data());
}
public resolveTile(id: string): Tile {
return this.lookupAsset(AssetType.Tile, id) as Tile;
}
public resolveProjectTileByInternalID(id: number): Tile {
return this.state.tiles.getSnapshot(tile => tile.internalID === id)[0];
}
public resolveTileByBitmap(data: pxt.sprite.BitmapData): Tile {
const dataString = pxt.sprite.base64EncodeBitmap(data);
return this.state.tiles.getSnapshot(tile => tile.jresData === dataString)[0];
}
public getTransparency(tileWidth: number) {
const id = pxt.sprite.TILE_NAMESPACE + ".transparency" + tileWidth;
let tile = this.state.tiles.getByID(id);
if (!tile) {
const bitmap = new pxt.sprite.Bitmap(tileWidth, tileWidth).data();
tile = {
internalID: this.getNewInternalId(),
id,
type: AssetType.Tile,
bitmap: bitmap,
jresData: pxt.sprite.base64EncodeBitmap(bitmap),
meta: {},
isProjectTile: true
};
return this.state.tiles.add(tile);
}
return tile;
}
public createNewTilemapFromData(data: pxt.sprite.TilemapData, name?: string): [string, pxt.sprite.TilemapData] {
this.onChange()
const id = this.generateNewIDInternal(AssetType.Tilemap, name || lf("level"));
this.state.tilemaps.add({
internalID: this.getNewInternalId(),
id,
type: AssetType.Tilemap,
meta: {
displayName: name || id
},
data: data
});
return [id, data];
}
protected cloneState(): AssetSnapshot {
return {
revision: this.state.revision,
images: this.state.images.clone(),
tilemaps: this.state.tilemaps.clone(),
animations: this.state.animations.clone(),
tiles: this.state.tiles.clone(),
songs: this.state.songs.clone(),
}
}
public undo() {
if (this.state.revision !== this.committedState.revision) {
this.pushUndo();
}
if (this.undoStack.length) {
const undo = this.undoStack.pop();
this.state.tiles.applyDiff(undo.tiles, true);
this.state.images.applyDiff(undo.images, true);
this.state.tilemaps.applyDiff(undo.tilemaps, true);
this.state.animations.applyDiff(undo.animations, true);
this.state.songs.applyDiff(undo.songs, true);
this.state.revision = undo.beforeRevision;
this.redoStack.push(undo);
this.committedState = this.cloneState();
this.needsRebuild = true;
}
}
public redo() {
if (this.redoStack.length) {
const redo = this.redoStack.pop();
this.state.tiles.applyDiff(redo.tiles);
this.state.images.applyDiff(redo.images);
this.state.tilemaps.applyDiff(redo.tilemaps);
this.state.animations.applyDiff(redo.animations);
this.state.songs.applyDiff(redo.songs);
this.state.revision = redo.afterRevision;
this.undoStack.push(redo);
this.committedState = this.cloneState();
this.needsRebuild = true;
}
}
public pushUndo() {
if (this.undoStack.length && this.committedState.revision === this.state.revision) return;
this.redoStack = [];
this.undoStack.push({
beforeRevision: this.committedState.revision,
afterRevision: this.state.revision,
tiles: this.state.tiles.diff(this.committedState.tiles),
images: this.state.images.diff(this.committedState.images),
tilemaps: this.state.tilemaps.diff(this.committedState.tilemaps),
animations: this.state.animations.diff(this.committedState.animations),
songs: this.state.songs.diff(this.committedState.songs)
});
this.committedState = this.cloneState();
this.cleanupTemporaryAssets();
}
public revision() {
return this.state.revision;
}
public encodeTilemap(tilemap: sprite.TilemapData, id: string): JRes {
const tm = tilemap.tilemap.data();
const data = new Uint8ClampedArray(5 + tm.data.length + tilemap.layers.data.length);
data[0] = tilemap.tileset.tileWidth;
data[1] = tm.width & 0xff
data[2] = (tm.width >> 8) & 0xff
data[3] = tm.height & 0xff
data[4] = (tm.height >> 8) & 0xff
data.set(tm.data, 5);
data.set(tilemap.layers.data, 5 + tm.data.length);
return {
id,
mimeType: TILEMAP_MIME_TYPE,
data: btoa(pxt.sprite.uint8ArrayToHex(data)),
tileset: tilemap.tileset.tiles.map(t => t.id)
}
}
public forceUpdate() {
this.onChange();
}
public isNameTaken(assetType: AssetType, name: string) {
const isTaken = (id: string) => {
return getAssetCollection(this.state, assetType).isIDTaken(id) ||
getAssetCollection(this.gallery, assetType).isIDTaken(id);
}
const shortId = getShortIDCore(assetType, name);
const checkShortId = shortId && shortId !== name;
return isTaken(name) || (checkShortId && isTaken(shortId));
}
/**
* Checks if the asset is referenced anywhere in the user's code.
* If an asset is referenced in any block we return true, as well
* as if a tile is used in any tilemap.
*
* Ways to reference an asset in TS/Python:
*
* TILES:
* myTiles.shortId
* assets.tile`shortId`
* assets.tile`displayName`
*
* IMAGES:
* assets.image`shortId`
* assets.image`displayName`
*
* ANIMATIONS:
* assets.animation`shortId`
* assets.animation`displayName`
*
* SONGS:
* assets.song`shortId`
* assets.song`displayName`
*
* TILEMAPS:
* tilemap`shortId`
*
* @param skipIDs string[] a list of string ids (block id, asset id, or file name) to ignore
**/
public isAssetUsed(asset: Asset, files?: pxt.Map<{content: string}>, skipIDs?: string[]): boolean {
let blockIds = asset.meta?.blockIDs?.filter(id => !skipIDs || skipIDs?.indexOf(id) < 0) || [];
if (blockIds.length > 0) return true;
if (asset.type == pxt.AssetType.Tile) {
for (const tm of this.getAssets(AssetType.Tilemap)) {
if (skipIDs?.indexOf(tm.id) >= 0) {
continue;
} else if (tm.data.tileset.tiles.some(t => t.id === asset.id)) {
return true;
}
}
}
if (files) {
const shortId = Util.escapeForRegex(getShortIDForAsset(asset));
const displayName = Util.escapeForRegex(asset.meta?.displayName) || "";
let assetTsRefs: string;
switch (asset.type) {
case pxt.AssetType.Tile:
assetTsRefs = `myTiles.${shortId}|assets.tile\`${shortId}\``;
if (displayName) assetTsRefs += `|assets.tile\`${displayName}\``;
break;
case pxt.AssetType.Tilemap:
assetTsRefs = `tilemap\`${shortId}\``;
break;
case pxt.AssetType.Animation:
assetTsRefs = `assets.animation\`${shortId}\``;
if (displayName) assetTsRefs += `|assets.animation\`${displayName}\``;
break;
case pxt.AssetType.Song:
assetTsRefs = `assets.song\`${shortId}\``;
if (displayName) assetTsRefs += `|assets.song\`${displayName}\``;
break;
default:
assetTsRefs = `assets.image\`${shortId}\``;
if (displayName) assetTsRefs += `|assets.image\`${displayName}\``;
break;
}
const assetTsRegex = new RegExp(assetTsRefs, "gm");
let assetPyRefs: string;
switch (asset.type) {
case pxt.AssetType.Tile:
assetPyRefs = `myTiles.${shortId}|assets.tile\("""${shortId}"""\)`;
if (displayName) assetPyRefs += `|assets.tile\("""${displayName}"""\)`;
break;
case pxt.AssetType.Tilemap:
assetPyRefs = `assets.tilemap\("""${shortId}"""\)`;
break;
case pxt.AssetType.Animation:
assetPyRefs = `assets.animation\("""${shortId}"""\)`;
if (displayName) assetPyRefs += `|assets.animation\("""${displayName}"""\)`;
break;
case pxt.AssetType.Song:
assetPyRefs = `assets.song\("""${shortId}"""\)`;
if (displayName) assetPyRefs += `|assets.song\("""${displayName}"""\)`;
break;
default:
assetPyRefs = `assets.image\("""${shortId}"""\)`;
if (displayName) assetPyRefs += `|assets.image\("""${displayName}"""\)`;
break;
}
const assetPyRegex = new RegExp(assetPyRefs, "gm");
for (let filename of Object.keys(files)) {
if (skipIDs?.indexOf(filename) >= 0) continue;
const f = files[filename];
// Match .ts files that are not generated (.g.ts)
if (filename.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)) {
if (f.content.match(assetTsRegex)) return true;
} else if (filename.endsWith(".py")) {
if (f.content.match(assetPyRegex)) return true;
}
}
}
return false;
}
public lookupAsset(assetType: AssetType.Image, name: string): ProjectImage;
public lookupAsset(assetType: AssetType.Tile, name: string): Tile;
public lookupAsset(assetType: AssetType.Tilemap, name: string): ProjectTilemap;
public lookupAsset(assetType: AssetType.Animation, name: string): Animation;
public lookupAsset(assetType: AssetType.Song, name: string): Song;
public lookupAsset(assetType: AssetType, name: string): Asset;
public lookupAsset(assetType: AssetType, name: string) {
return getAssetCollection(this.state, assetType).getByID(name) ||
getAssetCollection(this.gallery, assetType).getByID(name);
}
public lookupAssetByName(assetType: AssetType.Image, name: string): ProjectImage;
public lookupAssetByName(assetType: AssetType.Tile, name: string): Tile;
public lookupAssetByName(assetType: AssetType.Tilemap, name: string): ProjectTilemap;
public lookupAssetByName(assetType: AssetType.Animation, name: string): Animation;
public lookupAssetByName(assetType: AssetType.Song, name: string): Song;
public lookupAssetByName(assetType: AssetType, name: string): Asset;
public lookupAssetByName(assetType: AssetType, name: string) {
return getAssetCollection(this.state, assetType).getByDisplayName(name);
}
public lookupAssetByValue(assetType: AssetType.Image, toFind: ProjectImage): ProjectImage;
public lookupAssetByValue(assetType: AssetType.Tile, toFind: Tile): Tile;
public lookupAssetByValue(assetType: AssetType.Tilemap, toFind: ProjectTilemap): ProjectTilemap;
public lookupAssetByValue(assetType: AssetType.Animation, toFind: Animation): Animation;
public lookupAssetByValue(assetType: AssetType.Song, toFind: Song): Song;
public lookupAssetByValue(assetType: AssetType, toFind: Asset): Asset;
public lookupAssetByValue(assetType: AssetType, toFind: Asset) {
return getAssetCollection(this.state, assetType).getByValue(toFind);
}
public getAssets(type: AssetType.Image): ProjectImage[];
public getAssets(type: AssetType.Tile): Tile[];
public getAssets(type: AssetType.Tilemap): ProjectTilemap[];
public getAssets(type: AssetType.Animation): Animation[];
public getAssets(type: AssetType.Song): Song[];
public getAssets(type: AssetType): Asset[];
public getAssets(type: AssetType) {
return getAssetCollection(this.state, type).getSnapshot();
}
public getGalleryAssets(type: AssetType.Image): ProjectImage[];
public getGalleryAssets(type: AssetType.Tile): Tile[];
public getGalleryAssets(type: AssetType.Tilemap): ProjectTilemap[];
public getGalleryAssets(type: AssetType.Animation): Animation[];
public getGalleryAssets(type: AssetType.Song): Song[];
public getGalleryAssets(type: AssetType): Asset[];
public getGalleryAssets(type: AssetType) {
return getAssetCollection(this.gallery, type).getSnapshot();
}
public lookupBlockAsset(assetType: AssetType.Image, blockID: string): ProjectImage;
public lookupBlockAsset(assetType: AssetType.Tile, blockID: string): Tile;
public lookupBlockAsset(assetType: AssetType.Tilemap, blockID: string): ProjectTilemap;
public lookupBlockAsset(assetType: AssetType.Animation, blockID: string): Animation;
public lookupBlockAsset(assetType: AssetType.Song, blockID: string): Song;
public lookupBlockAsset(assetType: AssetType, blockID: string): Asset;
public lookupBlockAsset(type: AssetType, blockID: string) {
let filter = (a: Asset) => a.meta?.blockIDs?.indexOf(blockID) !== -1;
return getAssetCollection(this.state, type).getSnapshot(filter)[0];
}
public updateAsset(asset: ProjectImage): ProjectImage;
public updateAsset(asset: Tile): Tile;
public updateAsset(asset: ProjectTilemap): ProjectTilemap;
public updateAsset(asset: Animation): Animation;
public updateAsset(asset: Song): Song;
public updateAsset(asset: Asset): Asset;
public updateAsset(asset: Asset) {
this.onChange();
switch (asset.type) {
case AssetType.Tile:
return this.updateTile(asset);
default:
return getAssetCollection(this.state, asset.type).update(asset.id, asset);
}
}
public duplicateAsset(asset: ProjectImage, displayName?: string): ProjectImage;
public duplicateAsset(asset: Tile, displayName?: string): Tile;
public duplicateAsset(asset: ProjectTilemap, displayName?: string): ProjectTilemap;
public duplicateAsset(asset: Animation, displayName?: string): Animation;
public duplicateAsset(asset: Song, displayName?: string): Song;
public duplicateAsset(asset: Asset, displayName?: string): Asset;
public duplicateAsset(asset: Asset, displayName?: string) {
this.onChange();
const clone = cloneAsset(asset);
const name = displayName || clone.meta?.displayName;
let newAsset: pxt.Asset;
switch (asset.type) {
case AssetType.Image:
newAsset = this.createNewProjectImage((clone as pxt.ProjectImage).bitmap, name);
break;
case AssetType.Tile:
newAsset = this.createNewTile((clone as pxt.Tile).bitmap, null, name);
break;
case AssetType.Tilemap:
const [id, tilemap] = this.createNewTilemapFromData((clone as pxt.ProjectTilemap).data, name);
newAsset = this.getTilemap(id);
break;
case AssetType.Animation:
newAsset = this.createNewAnimationFromData((clone as pxt.Animation).frames, (clone as pxt.Animation).interval, name);
break;
case AssetType.Song:
newAsset = this.createNewSong(asset.song, name);
break;