-
Notifications
You must be signed in to change notification settings - Fork 2
/
tile.py
593 lines (484 loc) · 21.4 KB
/
tile.py
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
"""
Tile Class
Contains all the data needed to create a Block or BGO in SMBX2
"""
import os
import sys
import tkinter
from tkinter import PhotoImage, NW, NORMAL, HIDDEN, Canvas, SW, NE, SE, N, S, W, E, CENTER
from typing import Union
from PIL import Image, ImageTk
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
# -------------------------------
# Tile Type Drawing Functions
# -------------------------------
TILE_INSET = 6
T = TILE_INSET
def draw_square_tile(c, x1, y1, x2, y2, passthrough=False):
poly = c.create_rectangle(x1 + T, y1 + T, x2 - T, y2 - T)
if passthrough:
c.itemconfigure(poly, dash=(8, 8))
return poly
def draw_semisolid(c, x1, y1, x2, y2):
return c.create_polygon(x1 + T, y1 + T, x2 - T, y1 + T, x2 - T, y2 - T, x1 + T, y2 - T, x1 + T, y1 + T,
(x1 + x2) // 2, (y1 + y2) // 2, x2 - T, y1 + T)
def draw_slope_1(c, x1, y1, x2, y2):
# Slope ◢
return c.create_polygon(x2 - T, y1 + T, x2 - T, y2 - T, x1 + T, y2 - T)
def draw_slope_2(c, x1, y1, x2, y2):
# Slope ◣
return c.create_polygon(x1 + T, y1 + T, x2 - T, y2 - T, x1 + T, y2 - T)
def draw_slope_3(c, x1, y1, x2, y2):
# Slope ◥
return c.create_polygon(x1 + T, y1 + T, x2 - T, y1 + T, x2 - T, y2 - T)
def draw_slope_4(c, x1, y1, x2, y2):
# Slope ◤
return c.create_polygon(x1 + T, y1 + T, x2 - T, y1 + T, x1 + T, y2 - T)
def draw_semisolid_slope_1(c, x1, y1, x2, y2):
return c.create_polygon(x1 + T, y2 - T, x2 - T, y1 + T)
def draw_semisolid_slope_2(c, x1, y1, x2, y2):
return c.create_polygon(x1 + T, y1 + T, x2 - T, y2 - T)
def draw_passthrough(c, x1, y1, x2, y2):
return draw_square_tile(c, x1, y1, x2, y2, True)
tile_draw_functions = {
'Solid ■': draw_square_tile,
'Solid ◢': draw_slope_1,
'Solid ◣': draw_slope_2,
'Solid ◥': draw_slope_3,
'Solid ◤': draw_slope_4,
'Semisolid ■': draw_semisolid,
'Semisolid ◢': draw_semisolid_slope_1,
'Semisolid ◣': draw_semisolid_slope_2,
'Passthrough': draw_passthrough,
}
# -------------------------------
# Defaults
# -------------------------------
defaults = {
# General information
'tile_type': 'Block',
'tile_id': '',
'tile_name': '',
'tile_description': '',
'grid_size': (32, 32), # The grid size as the tile was created (only used if grid_padding is nonzero)
'grid_padding': 0, # The grid padding as the tile was created (used w/grid_size in _slice_n_splice)
# Animation
'frames': '1',
'framespeed': '8',
# Light
'no_shadows': False,
'light_source': False,
'lightoffsetx': '0',
'lightoffsety': '0',
'lightradius': '128',
'lightbrightness': '1',
'lightcolor': '#ffffff',
'lightflicker': False,
# BGO Exclusive
'priority': '-85',
# Behavior (Block Exclusive)
'collision_type': 'Solid ■',
'content_type': 'Empty',
'content_id': '1',
'smashable': '0',
'playerfilter': '0',
'npcfilter': '0',
'sizable': False,
'pswitchable': False,
'slippery': False,
'lava': False,
'bumpable': False,
'customhurt': False,
'ediblebyvine': False,
'walkpaststair': False,
}
# Settings to be checked for all tiles
unconditional_settings = ['tile_type', 'tile_id', 'tile_name', 'tile_description', 'frames', 'framespeed', 'no_shadows',
'light_source', 'grid_size', 'grid_padding']
# Settings for light sources only
light_settings = ['lightoffsetx', 'lightoffsety', 'lightradius', 'lightbrightness', 'lightcolor', 'lightflicker']
# Settings for BGOs only
bgo_settings = ['priority']
# Settings for Blocks only
block_settings = ['collision_type', 'content_type', 'smashable', 'playerfilter', 'npcfilter', 'sizable', 'pswitchable',
'slippery', 'lava', 'bumpable', 'customhurt', 'ediblebyvine', 'walkpaststair']
content_settings = ['content_id']
# All settings (for load) -- currently unused
# all_settings = ['tile_type', 'tile_id', 'frames', 'framespeed', 'no_shadows', 'light_source', 'lightoffsetx',
# 'lightoffsety', 'lightradius', 'lightbrightness', 'lightcolor', 'lightflicker', 'priority',
# 'collision_type', 'content_type', 'smashable', 'playerfilter', 'npcfilter', 'sizable', 'pswitchable',
# 'slippery', 'lava', 'bumpable', 'customhurt', 'ediblebyvine', 'content_id']
# -------------------------------
# Tile Export Rules
# -------------------------------
def export_rule_default(key, value):
if type(value) == bool:
value = str(value).lower()
return f'{key} = {value}'
def export_rule_non_empty(key, value):
if value == '':
return ''
return export_rule_default(key, value) + '\n'
legacy_to_new_collision_type = {
"Solid": "Solid ■",
"Slope ◢": "Solid ◢",
"Slope ◣": "Solid ◣",
"Slope ◥": "Solid ◥",
"Slope ◤": "Solid ◤",
"Semisolid": "Semisolid ■"
}
export_rules_collision_type = {
# Need to cover all these fields to override any default behavior
"Solid ■": 'semisolid = false\npassthrough = false\nfloorslope = 0\nceilingslope = 0\n',
"Solid ◢": 'semisolid = false\npassthrough = false\nfloorslope = -1\nceilingslope = 0\n',
"Solid ◣": 'semisolid = false\npassthrough = false\nfloorslope = 1\nceilingslope = 0\n',
"Solid ◥": 'semisolid = false\npassthrough = false\nfloorslope = 0\nceilingslope = 1\n',
"Solid ◤": 'semisolid = false\npassthrough = false\nfloorslope = 0\nceilingslope = -1\n',
"Semisolid ■": 'semisolid = true\npassthrough = false\nfloorslope = 0\nceilingslope = 0\n',
"Semisolid ◢": 'semisolid = true\npassthrough = false\nfloorslope = -1\nceilingslope = 0\n',
"Semisolid ◣": 'semisolid = true\npassthrough = false\nfloorslope = 1\nceilingslope = 0\n',
"Passthrough": 'semisolid = false\npassthrough = true\nfloorslope = 0\nceilingslope = 0\n',
}
export_rules = { # Fields without rules here will just use the default
'no_shadows': lambda value: export_rule_default('noshadows', value) + '\n',
'collision_type': lambda value: export_rules_collision_type[value],
'content_id_npc': lambda value: f'default-npc-content = {int(value) + 1000}\n',
'slippery': lambda value: f'default-slippery = {1 if value else 0}\n',
'tile_name': lambda value: export_rule_non_empty('name', value),
'tile_description': lambda value: export_rule_non_empty('description', value),
}
# These properties do not need to be written to the .txt file
export_excluded = {'tile_type', 'tile_id', 'content_type', 'light_source', 'grid_size', 'grid_padding'}
class Tile:
def apply_tile_settings(self, tile_data):
"""
Copies the values of tkinter variables from tile_data to this object's data.
:param tile_data: The data to copy
:return: None
"""
for k in defaults.keys():
if k not in {'grid_size', 'grid_padding'}:
self.data[k] = tile_data[k].get()
def configure_bounding_box(self, **kwargs):
"""
Apply configuration changes to the tile's bounding box.
:param kwargs: Settings to apply to the bounding box. Accepts any named arguments that can be passed to
tkinter.Canvas.itemconfigure
:return: None
"""
self.canvas.itemconfigure(self.bounding_box, **kwargs)
def _scale_poly(self, poly, scale):
"""Scales any object drawn on the canvas"""
canvas = self.canvas
new_pts = []
for pt in canvas.coords(poly):
new_pts.append(pt / self.scale * scale)
canvas.coords(poly, *new_pts)
def _scale_grid_settings(self, scale):
"""Scale the tile's grid settings"""
data = self.data
data['grid_size'] = [x // self.scale * scale for x in data['grid_size']]
data['grid_padding'] = int(data['grid_padding'] // self.scale * scale)
def set_scale(self, scale):
"""
Set the scaling of the tile to <scale>
:param scale: The desired scale amount
:return: None
"""
if scale != self.scale:
self._scale_grid_settings(scale)
self._scale_poly(self.bounding_box, scale)
self.canvas.delete(self.type_poly)
self.type_poly = self.draw_type()
self.scale = scale
def increment_bad_field_count(self):
self.bad_field_count += 1
if self.bad_field_count == 1:
self.redraw()
def decrement_bad_field_count(self):
self.bad_field_count = max(self.bad_field_count - 1, 0)
if self.bad_field_count == 0:
self.redraw()
def draw_type(self, tile_type=None, collision_type=None, **kwargs):
"""Draw a little picture showing the Tile's type"""
tile_data = self.data
tile_type = tile_type or tile_data['tile_type']
collision_type = 'Passthrough' if tile_type == 'BGO' else collision_type or tile_data['collision_type']
canvas = self.canvas
(x1, y1, x2, y2) = self.canvas.coords(self.bounding_box)
poly = tile_draw_functions[collision_type](canvas, x1, y1, x2, y2)
kwargs.pop('outline', None)
kwargs.pop('width', None)
canvas.itemconfigure(poly, outline=self.color, width=self.border_width, fill='', **kwargs)
return poly
def draw_error_indicator(self):
canvas = self.canvas
if self.error_indicator is not None:
canvas.delete(self.error_indicator)
(x, y, *_) = canvas.coords(self.bounding_box)
return canvas.create_image(x + 1, y + 1, anchor=NW, image=self.error_image, tags='bad_ind')
def redraw(self, **tile_data):
"""Redraw the Tile"""
data = self.data
canvas = self.canvas
tile_type = None
collision_type = None
scale = None
color = None
if 'tile_type' in tile_data:
tile_type = tile_data['tile_type']
if 'collision_type' in tile_data:
collision_type = tile_data['collision_type']
if 'scale' in tile_data:
scale = tile_data['scale']
if 'highlight_color' in tile_data:
color = tile_data['highlight_color']
if (tile_type and tile_type != data['tile_type']) \
or collision_type and (collision_type != data['collision_type']):
# Tile type or collision type has changed.
canvas.delete(self.type_poly)
self.type_poly = self.draw_type(tile_type, collision_type)
if tile_type:
data['tile_type'] = tile_type
if collision_type:
data['collision_type'] = collision_type
if scale and scale != self.scale: # Scale has changed.
self.set_scale(scale)
self.scale = scale
outline = (color or self.color) if self.selected else ''
canvas.itemconfigure(self.bounding_box, outline=outline)
if color and color != self.color: # Highlight Color has changed.
canvas.itemconfigure(self.type_poly, outline=color)
self.color = color
self.error_indicator = self.draw_error_indicator()
if self.bad_field_count > 0:
self.canvas.itemconfigure(self.error_indicator, state=NORMAL)
else:
self.canvas.itemconfigure(self.error_indicator, state=HIDDEN)
# Ensure that the tile is always rendered above the grid.
canvas.tag_raise(self.bounding_box)
canvas.tag_raise(self.type_poly)
canvas.tag_raise(self.error_indicator)
def select(self):
self.selected = True
self.redraw()
def deselect(self):
self.selected = False
self.redraw()
def overlaps(self, bbox):
"""
Check whether <bbox> overlaps with <self.bounding_box>.
:param bbox: The bounding box to check. This must be in <self.canvas>, or a TclError exception will be raised.
:return: True if there is an overlap, False otherwise.
"""
(sx1, sy1, sx2, sy2) = self.canvas.coords(self.bounding_box)
(ox1, oy1, ox2, oy2) = self.canvas.coords(bbox)
return sx2 > ox1 and sx1 < ox2 and sy2 > oy1 and sy1 < oy2
@staticmethod
def _collect_non_default_data(keys, data, save_data):
"""
Collect the non-default data values stored at <data>[<keys>] into <save_data>
:param keys: The keys to check and possibly copy over
:param data: All the Tile's data
:param save_data: The data that will be encoded to .json and written to the save file
:return:
"""
for k in keys:
if data[k] != defaults[k]:
save_data[k] = data[k]
def load_to_ui(self, ui_data, ui_inputs):
"""Load the Tile's data to the UI"""
data = self.data
for k in defaults:
if k not in {'grid_size', 'grid_padding'}:
ui_data[k].set(data[k])
if k in ui_inputs:
ui_inputs[k].check_variable()
def get_save_ready_data(self):
"""
Convert the tile's data into a dict object that is ready to be written to a .json file
:return: A dict containing all non-default configurations.
"""
data = self.data
save_data = {}
(x1, y1, x2, y2) = self.canvas.coords(self.bounding_box)
save_data['x1'] = int(x1)
save_data['y1'] = int(y1)
save_data['x2'] = int(x2)
save_data['y2'] = int(y2)
self._collect_non_default_data(unconditional_settings, data, save_data)
if data['light_source']:
self._collect_non_default_data(light_settings, data, save_data)
if data['tile_type'] == 'Block':
self._collect_non_default_data(block_settings, data, save_data)
if data['content_type'] != 'Empty':
self._collect_non_default_data(content_settings, data, save_data)
else:
self._collect_non_default_data(bgo_settings, data, save_data)
if 'assigned_id' in data:
save_data['assigned_id'] = data['assigned_id']
return save_data
def assign_id(self, generated_id):
"""
Assigns an ID to the Tile.
:param generated_id: The ID that will be assigned to the tile if the user did not provide one.
:return: The ID assigned.
"""
data = self.data
if 'assigned_id' not in data:
data['assigned_id'] = int(data['tile_id']) if data['tile_id'] != '' else generated_id
return data['assigned_id']
def clear_assigned_id(self):
"""Clear the tile's assigned ID field. Has no effect if this field is not set."""
self.data.pop('assigned_id', None)
@staticmethod
def _export_txt_property(key, value):
if key in export_excluded:
return ''
if key in export_rules:
return export_rules[key](value)
return export_rule_default(key, value) + '\n'
@staticmethod
def _slice_n_splice(image, grid_size, grid_padding):
"""
Cuts out the padded areas out of the image
:param image: The image to slice 'n' splice
:type image: PIL.Image.Image
"""
w = image.width
h = image.height
grid_w = grid_size[0]
grid_h = grid_size[1]
new_img = Image.new('RGBA', ((w + grid_padding) // (grid_w + grid_padding) * grid_w,
(h + grid_padding) // (grid_h + grid_padding) * grid_h))
y = 0
pad_y = 0
while y + pad_y < h:
x = 0
pad_x = 0
while x + pad_x < w:
chunk = image.crop((x + pad_x, y + pad_y, x + grid_w + pad_x, y + grid_h + pad_y))
new_img.paste(chunk, (x, y, x + grid_w, y + grid_h))
x += grid_w
pad_x += grid_padding
y += grid_h
pad_y += grid_padding
return new_img
def _get_tile_image(self, image: Union[PhotoImage, Image.Image]):
if isinstance(image, PhotoImage):
image = ImageTk.getimage(image)
image = image.crop(self.canvas.coords(self.bounding_box))
if int(self.data['grid_padding']) > 0:
image = self._slice_n_splice(image, self.data['grid_size'], int(self.data['grid_padding']))
return image
def load_preview(self, window):
"""
Load a preview of the tile.
:param window: Tileset Importer window instance.
:return: None
"""
# image = window.tileset_image
image = self._get_tile_image(window.tileset_image)
w = image.width
h = image.height
image = ImageTk.PhotoImage(image)
# image = ImageTk.getimage(image)
# image.save('test1.png')
# image = ImageTk.PhotoImage(image)
# image = ImageTk.getimage(image)
# image.save('test2.png')
canvas: tkinter.Canvas = window.tile_preview_canvas
canvas.configure(width=w, height=h)
canvas.create_image(0, 0, anchor=NW, image=image, tags='tile_preview')
# canvas.create_polygon(0, 0, w, 0, w, h, 0, h)
window.tile_preview_image = image
def export(self, image, path):
"""
Export the tile to png and txt files for use in SMBX2.
:param image: The image containing the entire tileset
:type image: PIL.Image
:param path: The export path
"""
data = self.data
tile_type = data['tile_type']
export_name = path + ('/block-' if tile_type == 'Block' else '/background-') \
+ str(tile_id := data['assigned_id'])
# Export the image
# Easier than I thought it would be
image = self._get_tile_image(image)
image.save(export_name + '.png')
# Export the .txt file
with open(export_name + '.txt', 'w') as f:
if 751 <= tile_id <= 1000:
type_name = 'background' if data['tile_type'] == 'BGO' else 'block'
f.write(f'image = {type_name}-{tile_id}.png\n')
for k in unconditional_settings:
f.write(self._export_txt_property(k, data[k]))
tile_type_settings = bgo_settings if tile_type == 'BGO' else block_settings
if data['light_source']:
for k in light_settings:
f.write(self._export_txt_property(k, data[k]))
for k in tile_type_settings:
f.write(self._export_txt_property(k, data[k]))
if tile_type == 'Block':
if (content_type := data['content_type']) == 'NPC':
f.write(self._export_txt_property('content_id_npc', data['content_id']))
elif content_type == 'Coins':
f.write(self._export_txt_property('content_id', data['content_id']))
else: # To override blocks that originally had contents
f.write(self._export_txt_property('content_id', 0))
def __getitem__(self, item):
return self.data[item]
def __setitem__(self, key, value):
self.data[key] = value
def __lt__(self, other):
"""Used during .tileset.ini file creation. Compares Tiles based on their x-position in the canvas."""
return self.canvas.coords(self.bounding_box)[0] < other.canvas.coords(other.bounding_box)[0]
def __init__(self, canvas, x1, y1, x2, y2, *, outline=None, width=None, scale=1, **kwargs):
"""
CONSTRUCTOR
:param canvas: The canvas that the tile will be drawn to
:type canvas: tkinter.Canvas
:param x1: The left boundary of the tile
:param y1: The top boundary of the tile
:param x2: The right boundary of the tile
:param y2: The bottom boundary of the tile
:param kwargs: Settings to apply to the bounding box. Accepts any named arguments that can be passed to
tkinter.Canvas.itemconfigure
"""
self.error_image = PhotoImage(file=resource_path('data/tile_error.png'))
# For backward compatibility with .tileset.json files created before v0.2.
if 'grid_size' in kwargs and type(old_val := kwargs['grid_size']) == int:
kwargs['grid_size'] = (old_val, old_val)
data = {}
for k in defaults.keys():
if k in kwargs:
# For backward compatibility with .tileset.json files created before v0.3.
if k == "collision_type" and kwargs[k] in legacy_to_new_collision_type:
kwargs[k] = legacy_to_new_collision_type[kwargs[k]]
data[k] = kwargs[k]
del kwargs[k] # Remove the key, so it won't be passed on to the Canvas items and cause an error
else:
data[k] = defaults[k]
if 'assigned_id' in kwargs:
data['assigned_id'] = kwargs['assigned_id']
del kwargs['assigned_id']
self.data = data
self.color = outline or 'black'
self.border_width = width or 3
self.canvas = canvas
self.scale = scale
self.selected = False
self.bounding_box = canvas.create_rectangle(x1, y1, x2, y2, outline=self.color, width=self.border_width,
**kwargs)
self.type_poly = self.draw_type(outline=self.color, width=self.border_width, **kwargs)
self.bad_field_count = 0
self.error_indicator = None
self.error_indicator = self.draw_error_indicator()
def __del__(self):
canvas = self.canvas
canvas.delete(self.bounding_box)
canvas.delete(self.type_poly)