-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtilengine.py
More file actions
2349 lines (1972 loc) · 72.2 KB
/
tilengine.py
File metadata and controls
2349 lines (1972 loc) · 72.2 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
"""
Python wrapper for Tilengine retro graphics engine
Updated to library version 2.11.0
http://www.tilengine.org
"""
"""
Copyright (c) 2017-2022 Marc Palacios Domenech
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# pylint: disable=C0103
# pylint: disable=W0614
# pylint: disable=W0312
# pylint: disable=R0201
from sys import platform as _platform
from ctypes import *
from os import path
from typing import List, Union, Optional
# constants --------------------------------------------------------------------
class WindowFlags:
"""
List of flag values for window creation
"""
FULLSCREEN = (1 << 0)
VSYNC = (1 << 1)
S1 = (1 << 2)
S2 = (2 << 2)
S3 = (3 << 2)
S4 = (4 << 2)
S5 = (5 << 2)
NEAREST = (1 << 6)
class Flags:
"""
List of flags for tiles and sprites
"""
FLIPX = (1 << 15) # horizontal flip
FLIPY = (1 << 14) # vertical flip
ROTATE = (1 << 13) # row/column flip (unsupported, Tiled compatibility)
PRIORITY = (1 << 12) # tile goes in front of sprite layer
MASKED = (1 << 11) # sprite won't be drawn inside masked region
TILESET = (7 << 8) # tileset index
class Error:
"""
List of possible error codes returned by :meth:`Engine.get_last_error()`
"""
OK = 0 # No error
OUT_OF_MEMORY = 1 # Not enough memory
IDX_LAYER = 2 # Layer index out of range
IDX_SPRITE = 3 # Sprite index out of range
IDX_ANIMATION = 4 # Animation index out of range
IDX_PICTURE = 5 # Picture or tile index out of range
REF_TILESET = 6 # Invalid Tileset reference
REF_TILEMAP = 7 # Invalid Tilemap reference
REF_SPRITESET = 8 # Invalid Spriteset reference
REF_PALETTE = 9 # Invalid Palette reference
REF_SEQUENCE = 10 # Invalid SequencePack reference
REF_SEQPACK = 11 # Invalid Sequence reference
REF_BITMAP = 12 # Invalid Bitmap reference
NULL_POINTER = 13 # Null pointer as argument
FILE_NOT_FOUND = 14 # Resource file not found
WRONG_FORMAT = 15 # Resource file has invalid format
WRONG_SIZE = 16 # A width or height parameter is invalid
UNSUPPORTED = 17 # Unsupported function
REF_LIST = 18 # Invalid ObjectList reference
class LogLevel:
"""
Log levels for :meth:`Engine.set_log_level()`
"""
NONE, ERRORS, VERBOSE = range(3)
class Blend:
"""
Available blending modes
"""
NONE, MIX25, MIX50, MIX75, ADD, SUB, MOD, CUSTOM = range(8)
MIX = MIX50
class Input:
"""
Available inputs to query in :meth:`Window.get_input`
"""
NONE, UP, DOWN, LEFT, RIGHT, A, B, C, D, E, F, START, QUIT, CRT = range(14)
BUTTON1, BUTTON2, BUTTON3, BUTTON4, BUTTON5, BUTTON6 = range(A, START)
P1, P2, P3, P4 = range(0, 128, 32)
PLAYER1, PLAYER2, PLAYER3, PLAYER4 = range(4)
class Overlay:
"""
Unised, kept for backwards compatibility with pre-2.10 release
"""
NONE, SHADOWMASK, APERTURE, SCANLINES, CUSTOM = range(5)
class CRT:
"""
Types of crt effect for release 2.10
"""
SLOT, APERTURE, SHADOW = range(3)
class TilengineException(Exception):
"""
Tilengine exception class
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
# structures ------------------------------------------------------------------
class Tile(Structure):
"""
Tile data contained in each cell of a :class:`Tilemap` object
:attr:`index`: tile index
:attr:`flags`: sum of :class:`Flags` values
"""
_fields_ = [
("index", c_ushort),
("flags", c_ushort)
]
class ColorStrip(Structure):
"""
Data used to define each frame of a color cycle for :class:`Sequence` objects
"""
_fields_ = [
("delay", c_int),
("first", c_ubyte),
("count", c_ubyte),
("dir", c_ubyte)
]
def __init__(self, delay: int, first: int, count: int, direction: int):
self.delay = delay
self.first = first
self.count = count
self.dir = direction
class SequenceInfo(Structure):
"""Sequence info returned by :meth:`Sequence.get_info`"""
_fields_ = [
("name", c_char * 32),
("num_frames", c_int)
]
class SequenceFrame(Structure):
"""
Data used to define each frame of an animation for :class:`Sequence` objects
"""
_fields_ = [
("index", c_int),
("delay", c_int)
]
def __init__(self, index: int, delay: int):
self.index = index
self.delay = delay
class SpriteInfo(Structure):
"""
Data returned by :meth:`Spriteset.get_sprite_info` with dimensions of the required sprite
"""
_fields_ = [
("w", c_int),
("h", c_int)
]
class TileInfo(Structure):
"""
Data returned by :meth:`Layer.get_tile` about a given tile inside a background layer
"""
_fields_ = [
("index", c_ushort),
("flags", c_ushort),
("row", c_int),
("col", c_int),
("xoffset", c_int),
("yoffset", c_int),
("color", c_ubyte),
("type", c_ubyte),
("empty", c_bool)
]
class SpriteData(Structure):
"""
Data used to create :class:`Spriteset` objects
"""
_fields_ = [
("name", c_char * 64),
("x", c_int),
("y", c_int),
("w", c_int),
("h", c_int)
]
def __init__(self, name: str, x: int, y: int, width: int, height: int):
self.name = _encode_string(name)
self.x = x
self.y = y
self.w = width
self.h = height
class TileAttributes(Structure):
"""
Data used to create :class:`Tileset` objects
"""
_fields_ = [
("type", c_ubyte),
("priority", c_bool)
]
def __init__(self, tile_type: int, priority: bool):
self.type = tile_type
self.priority = priority
class PixelMap(Structure):
"""
Data passed to :meth:`Layer.set_pixel_mapping` in a list
"""
_fields_ = [
("dx", c_short),
("dy", c_short)
]
class ObjectInfo(Structure):
"""
Object item info returned by :meth:`ObjectInfo.get_info()`
"""
_fields_ = [
("id", c_ushort),
("gid", c_ushort),
("flags", c_ushort),
("x", c_int),
("y", c_int),
("width", c_int),
("height", c_int),
("type", c_ubyte),
("visible", c_bool),
("name", c_char * 64)
]
class TileImage(Structure):
"""
Image Tile items for TLN_CreateImageTileset()
"""
_fields_ = [
("bitmap", c_void_p),
("id", c_ushort),
("type", c_ubyte)
]
class SpriteState(Structure):
"""
Sprite state for :meth:`Sprite.get_state()`
"""
_fields_ = [
("x", c_int),
("y", c_int),
("w", c_int),
("h", c_int),
("flags", c_ushort),
("palette", c_void_p),
("spriteset", c_void_p),
("index", c_int),
("enabled", c_bool),
("collision", c_bool)
]
class Color(object):
"""
Represents a color value in RGB format
"""
def __init__(self, r: int, g: int, b: int):
self.r = r
self.g = g
self.b = b
@classmethod
def fromstring(cls, string: str):
""" creates a color from a ccs-style #rrggbb string """
r = int(string[1:3], 16)
g = int(string[3:5], 16)
b = int(string[5:7], 16)
return Color(r, g, b)
# module internal variables
_tln: "Engine" # handle to shared native library
_window: "Window" # singleton window
_window_created = False # singleton window is created
# select library depending on OS
_library = ""
if _platform == "linux" or _platform == "linux2":
_library = "libTilengine.so"
elif _platform == "win32":
_library = "Tilengine.dll"
elif _platform == "darwin":
_library = "Tilengine.dylib"
else:
raise OSError("Unsupported platform: must be Windows, Linux or Mac OS")
# load native library. Try local path, if not, system path
if path.isfile(_library):
_tln = cdll.LoadLibrary(f"./{_library}")
else:
_tln = cdll.LoadLibrary(_library)
# callback types for user functions
_video_callback_function = CFUNCTYPE(None, c_int)
_blend_function = CFUNCTYPE(c_ubyte, c_ubyte, c_ubyte)
# convert string to c_char_p
def _encode_string(string: Optional[str]):
if string is not None:
return string.encode()
return None
# convert c_char_p to string
def _decode_string(byte_array: Optional[bytearray]):
if byte_array is not None:
return byte_array.decode()
return None
# error handling --------------------------------------------------------------
_tln.TLN_GetLastError.restype = c_int
_tln.TLN_GetErrorString.argtypes = [c_int]
_tln.TLN_GetErrorString.restype = c_char_p
# raises exception depending on error code
def _raise_exception(result: bool=False):
if result is not True:
error = _tln.TLN_GetLastError()
error_string = _tln.TLN_GetErrorString(error)
raise TilengineException(error_string.decode())
# World management
_tln.TLN_LoadWorld.argtypes = [c_char_p, c_int]
_tln.TLN_LoadWorld.restype = c_bool
_tln.TLN_SetWorldPosition.argtypes = [c_int, c_int]
_tln.TLN_SetWorldPosition.restype = None
_tln.TLN_SetLayerParallaxFactor.argtypes = [c_int, c_float, c_float]
_tln.TLN_SetLayerParallaxFactor.restype = c_bool
_tln.TLN_SetSpriteWorldPosition.argtypes = [c_int, c_int, c_int]
_tln.TLN_SetSpriteWorldPosition.restype = c_bool
_tln.TLN_ReleaseWorld.argtypes = None
_tln.TLN_ReleaseWorld.restype = None
# basic management ------------------------------------------------------------
_tln.TLN_Init.argtypes = [c_int, c_int, c_int, c_int, c_int]
_tln.TLN_Init.restype = c_void_p
_tln.TLN_DeleteContext.argtypes = [c_void_p]
_tln.TLN_DeleteContext.restype = c_bool
_tln.TLN_SetContext.argtypes = [c_void_p]
_tln.TLN_SetContext.restype = c_bool
_tln.TLN_GetContext.restype = c_void_p
_tln.TLN_GetNumObjects.restype = c_int
_tln.TLN_GetVersion.restype = c_int
_tln.TLN_GetUsedMemory.restype = c_int
_tln.TLN_SetBGColor.argtypes = [c_ubyte, c_ubyte, c_ubyte]
_tln.TLN_SetBGColorFromTilemap.argtypes = [c_void_p]
_tln.TLN_SetBGColorFromTilemap.restype = c_bool
_tln.TLN_SetBGBitmap.argtypes = [c_void_p]
_tln.TLN_SetBGBitmap.restype = c_bool
_tln.TLN_SetBGPalette.argtypes = [c_void_p]
_tln.TLN_SetBGPalette.restype = c_bool
_tln.TLN_SetRenderTarget.argtypes = [c_void_p, c_int]
_tln.TLN_UpdateFrame.argtypes = [c_int]
_tln.TLN_SetLoadPath.argtypes = [c_char_p]
_tln.TLN_SetLogLevel.argtypes = [c_int]
_tln.TLN_OpenResourcePack.argtypes = [c_char_p, c_char_p]
_tln.TLN_OpenResourcePack.restype = c_bool
_tln.TLN_SetSpritesMaskRegion.argtypes = [c_int, c_int]
class Engine(object):
"""
Main object for engine creation and rendering
:ivar layers: tuple of Layer objects, one entry per layer
:ivar sprites: tuple of Sprite objects, one entry per sprite
:ivar animations: tuple of Animation objects, one entry per animation
:ivar version: library version number
"""
def __init__(self, handle: c_void_p, num_layers: int, num_sprites: int, num_animations: int):
self._as_parameter_ = handle
self.layers = tuple([Layer(n) for n in range(num_layers)])
self.sprites = tuple([Sprite(n) for n in range(num_sprites)])
self.animations = tuple([Animation(n) for n in range(num_animations)])
self.version = _tln.TLN_GetVersion()
self.cb_raster_func = None
self.cb_frame_func = None
self.cb_blend_func = None
self.library = _tln
version = [2,11,0] # expected library version
req_version = (version[0] << 16) + (version[1] << 8) + version[2]
if self.version < req_version:
maj_version = self.version >> 16
min_version = (self.version >> 8) & 255
bug_version = self.version & 255
print("WARNING: Library version is %d.%d.%d, expected at least %d.%d.%d!" % \
(maj_version, min_version, bug_version, version[0], version[1], version[2]))
@classmethod
def create(cls, width: int, height: int, num_layers: int, num_sprites: int, num_animations: int) -> "Engine":
"""
Static method that creates a new instance of the engine
:param width: horizontal resolution in pixels
:param height: vertical resolution in pixels
:param num_layers: max number of background layers
:param num_sprites: max number of sprites
:param num_animations: number of color-cycle animations
:return: new instance
"""
handle = _tln.TLN_Init(width, height, num_layers, num_sprites, num_animations)
if handle is not None:
_engine = Engine(handle, num_layers, num_sprites, num_animations)
return _engine
else:
_raise_exception()
def __del__(self):
_tln.TLN_DeleteContext(self)
def get_num_objects(self) -> int:
"""
:return: the number of objets used by the engine so far
"""
return _tln.TLN_GetNumObjects()
def get_used_memory(self) -> int:
"""
:return: the total amount of memory used by the objects
"""
return _tln.TLN_GetUsedMemory()
def set_background_color(self, param):
"""
Sets the background color
:param param: can be a Color object or a Tilemap object. In this case, \
it assigns de background color as defined inside the tilemap
"""
param_type = type(param)
if param_type is Color:
_tln.TLN_SetBGColor(param.r, param.g, param.b)
elif param_type is Tilemap:
_tln.TLN_SetBGColorFromTilemap(param)
def disable_background_color(self):
"""
Disales background color rendering. If you know that the last background layer will always
cover the entire screen, you can disable it to gain some performance
"""
_tln.TLN_DisableBGColor()
def set_background_bitmap(self, bitmap: "Bitmap"):
"""
Sets a static bitmap as background
:param bitmap: Bitmap object to set as background. Set None to disable it.
"""
ok = _tln.TLN_SetBGBitmap(bitmap)
_raise_exception(ok)
def set_background_palette(self, palette: "Palette"):
"""
Sets the palette for the background bitmap. By default it is assigned the palette
of the bitmap passed in :meth:`Engine.set_background_bitmap`
:param palette: Palette object to set
"""
ok = _tln.TLN_SetBGPalette(palette)
_raise_exception(ok)
def set_raster_callback(self, raster_callback):
"""
Enables raster effects processing, like a virtual HBLANK interrupt where any render parameter can be modified between scanlines.
:param raster_callback: name of the user-defined function to call for each scanline. Set None to disable. \
This function takes one integer parameter that indicates the current scanline, between 0 and vertical resolution.
Example::
def my_raster_callback(num_scanline):
if num_scanline is 32:
engine.set_background_color(Color(0,0,0))
engine.set_raster_callback(my_raster_callback)
"""
if raster_callback is None:
self.cb_raster_func = None
else:
self.cb_raster_func = _video_callback_function(raster_callback)
_tln.TLN_SetRasterCallback(self.cb_raster_func)
def set_frame_callback(self, frame_callback):
"""
Enables user callback for each drawn frame, like a virtual VBLANK interrupt
:param frame_callback: name of the user-defined function to call for each frame. Set None to disable. \
This function takes one integer parameter that indicates the current frame.
Example::
def my_frame_callback(num_frame):
engine.set_background_color(Color(0,0,0))
engine.set_frame_callback(my_frame_callback)
"""
if frame_callback is None:
self.cb_frame_func = None
else:
self.cb_frame_func = _video_callback_function(frame_callback)
_tln.TLN_SetFrameCallback(self.cb_frame_func)
def set_render_target(self, pixels, pitch):
"""
Sets the output surface for rendering
:param pixels: Pointer to the start of the target framebuffer
:param pitch: Number of bytes per each scanline of the framebuffer
"""
_tln.TLN_SetRenderTarget(pixels, pitch)
def update_frame(self, num_frame=0):
"""
Draws the frame to the previously specified render target
:param num_frame: optional frame number for animation control
"""
_tln.TLN_UpdateFrame(num_frame)
def set_load_path(self, path: str):
"""
Sets base path for all data loading static methods `fromfile`
:param path: Base path. Files will load at path/filename. Set None to use current directory
"""
_tln.TLN_SetLoadPath(_encode_string(path))
def set_custom_blend_function(self, blend_function):
"""
Sets custom blend function to use in sprites or background layers when `BLEND_CUSTOM` mode
is selected with the :meth:`Layer.set_blend_mode` and :meth:`Sprite.set_blend_mode` methods.
:param blend_function: name of the user-defined function to call when blending that takes \
two integer arguments: source component intensity, destination component intensity, and returns \
the desired intensity.
Example::
# do 50%/50% blending
def blend_50(src, dst):
return (src + dst) / 2
engine.set_custom_blend_function(blend_50)
"""
self.cb_blend_func = _blend_function(blend_function)
_tln.TLN_SetCustomBlendFunction(self.cb_blend_func)
def set_log_level(self, log_level: int):
"""
Sets output messages
"""
_tln.TLN_SetLogLevel(log_level)
def get_available_sprite(self) -> int:
"""
:return: Index of the first unused sprite (starting from 0) or -1 if none found
"""
index = _tln.TLN_GetAvailableSprite()
return index
def get_available_animation(self) -> int:
"""
:return: Index of the first unused animation (starting from 0) or -1 if none found
"""
index = _tln.TLN_GetAvailableAnimation()
return index
def open_resource_pack(self, filename: str, key: str=''):
"""
Opens the resource package with optional aes-128 key and binds it
:param filename: file with the resource package (.dat extension)
:param key: optional null-terminated ASCII string with aes decryption key
"""
ok = _tln.TLN_OpenResourcePack(_encode_string(str(filename)), _encode_string(str(key)))
_raise_exception(ok)
def close_resource_pack(self):
"""
Closes currently opened resource package and unbinds it
"""
return _tln.TLN_CloseResourcePack()
def set_sprites_mask_region(self, top: int, bottom: int):
"""
Defines a sprite masking region between the two scanlines. Sprites masked with Sprite.enable_mask_region() won't be drawn inside this region
:param top: upper scaline of the exclusion region
:param bottom: lower scanline of the exclusion region
"""
ok = _tln.TLN_SetSpritesMaskRegion(top, bottom)
_raise_exception(ok)
def load_world(self, filename: str, first_layer: int=0):
"""
Loads and assigns complete TMX file
:param filename: main .tmx file to load
:first_layer: optional layer index to start to assign, by default 0
"""
ok =_tln.TLN_LoadWorld(filename, first_layer)
_raise_exception(ok)
def set_world_position(self, x: int, y: int):
"""
Sets global world position, moving all layers in sync according to their parallax factor
:param x: horizontal position in world space
:param y: vertical position in world space
"""
ok = _tln.TLN_SetWorldPosition(x, y)
_raise_exception(ok)
def release_world(self):
"""
Releases world resources loaded with Engine.load_world
"""
_tln.TLN_ReleaseWorld()
# window management -----------------------------------------------------------
_tln.TLN_CreateWindow.argtypes = [c_char_p, c_int]
_tln.TLN_CreateWindow.restype = c_bool
_tln.TLN_CreateWindowThread.argtypes = [c_char_p, c_int]
_tln.TLN_CreateWindowThread.restype = c_bool
_tln.TLN_ProcessWindow.restype = c_bool
_tln.TLN_IsWindowActive.restype = c_bool
_tln.TLN_GetInput.argtypes = [c_int]
_tln.TLN_GetInput.restype = c_bool
_tln.TLN_EnableInput.argtypes = [c_int, c_bool]
_tln.TLN_AssignInputJoystick.argtypes = [c_int, c_int]
_tln.TLN_DefineInputKey.argtypes = [c_int, c_int, c_uint]
_tln.TLN_DefineInputButton.argtypes = [c_int, c_int, c_ubyte]
_tln.TLN_DrawFrame.argtypes = [c_int]
_tln.TLN_EnableCRTEffect.argtypes = [c_int, c_ubyte, c_ubyte, c_ubyte, c_ubyte, c_ubyte, c_ubyte, c_bool, c_ubyte]
_tln.TLN_ConfigCRTEffect.argtypes = [c_int, c_bool]
_tln.TLN_GetTicks.restype = c_int
_tln.TLN_Delay.argtypes = [c_int]
_tln.TLN_GetWindowWidth.restype = c_int
_tln.TLN_GetWindowHeight.restype = c_int
class Window(object):
"""
Built-in window manager for easy setup and testing
:ivar num_frame: current frame being drawn, starting from 0
:ivar width: actual window width (after scaling)
:ivar height: actual window height (after scaling)
"""
def __init__(self):
self.cb_sdl_func = None
@classmethod
def create(cls, title:str='Tilengine window', overlay=None, flags:int=WindowFlags.VSYNC) -> "Window":
"""
Static method that creates a single-threaded window that must be used in conjunction with
:meth:`Window.process` in a loop
:param overlay: obsolete, kept for compatibility with pre 2.10 release with old CRT effect
:param flags: optional flags combination of :class:`WindowFlags` values
:return: instance of the created window
"""
global _window, _window_created
"""Added the ability to choose the window title ~AleK3y"""
_tln.TLN_SetWindowTitle(_encode_string(str(title)))
if _window_created:
return _window
ok = _tln.TLN_CreateWindow(_encode_string(overlay), flags)
if ok is True:
_window = Window()
_window.num_frame = 0
_window.width = _tln.TLN_GetWindowWidth()
_window.height = _tln.TLN_GetWindowHeight()
_window_created = True
return _window
else:
_raise_exception(ok)
@classmethod
def create_threaded(cls, overlay=None, flags:int=WindowFlags.VSYNC) -> "Window":
"""
Static method that creates a multi-threaded window that runs in its own thread without user loop.
Used mainly in python interactive console
:param overlay: obsolete, kept for compatibility with pre 2.10 release with old CRT effect
:param flags: optional flags combination of :class:`WindowFlags` values
"""
global _window
if _window is not None:
return _window
ok = _tln.TLN_CreateWindowThread(_encode_string(overlay), flags)
if ok is True:
_window = Window()
_window.width = _tln.TLN_GetWindowWidth()
_window.height = _tln.TLN_GetWindowHeight()
return _window
else:
_raise_exception(ok)
def process(self):
"""
Does basic window housekeeping in signgle-threaded window, created with :meth:`Window.create`.
This method must be called in a loop by the main thread.
:return: True if window is active or False if the user has requested to end the application
(by pressing Esc key or clicking the close button)
"""
_tln.TLN_DrawFrame(self.num_frame)
self.num_frame += 1
return _tln.TLN_ProcessWindow()
def is_active(self) -> bool:
"""
:return: True if window is active or False if the user has requested to end the application \
(by pressing Esc key or clicking the close button)
"""
return _tln.TLN_IsWindowActive()
def get_input(self, input_id: int) -> bool:
"""
Returns the state of a given input
:param input_id: one of the :class:`Input` defined values. By default it requests input of player 1. \
To request input of a given player, add one of the possible P1 - P4 values.
:return: True if that input is pressed or False if not
Example::
# check if player 1 is pressing right:
value = window.get_input(Input.RIGHT)
# check if player 2 is pressing action button 1:
value = window.get_input(Input.P2 + Input.BUTTON1)
"""
return _tln.TLN_GetInput(input_id)
def enable_input(self, player: int, state: bool):
"""
Enables or disables input for specified player
:param player: player identifier to configure (PLAYER1 - PLAYER4)
:param state: True to enable, False to disable
"""
_tln.TLN_EnableInput(player, state)
def assign_joystick(self, player: int, joystick_index: int):
"""
:param player: player identifier to configure (PLAYER1 - PLAYER4)
:param joystick_index: zero-based joystick index to assign. 0 = first, 1 = second.... Disable with -1
"""
_tln.TLN_AssignInputJoystick(player, joystick_index)
def define_input_key(self, player: int, input: int, key: int):
"""
Assigns a keyboard input to a player
:param player: player identifier to configure (PLAYER1 - PLAYER4)
:param input: input to assign, member of :class:`Input`
:param key: ASCII key value or scancode as defined in SDL.h
"""
_tln.TLN_DefineInputKey(player, input, key)
def define_input_button(self, player: int, input: int, button: int):
"""
Assigns a joystick button input to a player
:param player: player identifier to configure (PLAYER1 - PLAYER4)
:param input: input to assign, member of :class:`Input`
:param button: button index
"""
_tln.TLN_DefineInputButton(player, input, button)
def draw_frame(self, num_frame=0):
"""
Deprecated, kept for old source code compatibility. Subsumed by :meth:`Window.process`.
"""
def wait_redraw(self):
"""
In multi-threaded windows, it waits until the current frame has finished rendering.
"""
_tln.TLN_WaitRedraw()
def config_crt_effect(self, crt_type: int, rf_blur: bool):
"""
Enables CRT simulation post-processing effect to give true retro appeareance
:param crt_type: One possible value of \ref CRT class
:param rf_blur: Optional RF (horizontal) blur, increases CPU usage
"""
_tln.TLN_ConfigCRTEffect(crt_type, rf_blur)
def enable_crt_effect(self, overlay_id, overlay_blend, threshold, v0, v1, v2, v3, blur, glow_factor):
"""
Obsolete, kept for backward compatibility with pre- 2.10 release. Use config_crt_effect() instead.
"""
_tln.TLN_EnableCRTEffect(overlay_id, overlay_blend, threshold, v0, v1, v2, v3, blur, glow_factor)
def disable_crt_effect(self):
"""
Disables the CRT post-processing effect enabled with :meth:`Window.enable_crt_effect`
"""
_tln.TLN_DisableCRTEffect()
def set_sdl_callback(self, sdl_callback):
"""
Sets callback to process other SDL2 events inside the window
"""
if sdl_callback is None:
self.cb_sdl_func = None
else:
from sdl2 import SDL_Event
_sdl_callback_function = CFUNCTYPE(None, SDL_Event)
self.cb_sdl_func = _sdl_callback_function(sdl_callback)
_tln.TLN_SetSDLCallback(self.cb_sdl_func)
def get_ticks(self) -> int:
"""
:return: the number of milliseconds since application start
"""
return _tln.TLN_GetTicks()
def delay(self, msecs: int):
"""
Suspends execition for a fixed time
:param msecs: number of milliseconds to pause
"""
_tln.TLN_Delay(msecs)
# spritesets management -----------------------------------------------------------
_tln.TLN_CreateSpriteset.argtypes = [c_void_p, POINTER(SpriteData), c_int]
_tln.TLN_CreateSpriteset.restype = c_void_p
_tln.TLN_LoadSpriteset.argtypes = [c_char_p]
_tln.TLN_LoadSpriteset.restype = c_void_p
_tln.TLN_CloneSpriteset.argtypes = [c_void_p]
_tln.TLN_CloneSpriteset.restype = c_void_p
_tln.TLN_GetSpriteInfo.argtypes = [c_void_p, c_int, POINTER(SpriteInfo)]
_tln.TLN_GetSpriteInfo.restype = c_bool
_tln.TLN_GetSpritesetPalette.argtypes = [c_void_p]
_tln.TLN_GetSpritesetPalette.restype = c_void_p
_tln.TLN_SetSpritesetData.argtypes = [c_void_p, c_int, POINTER(SpriteData), POINTER(c_ubyte), c_int]
_tln.TLN_SetSpritesetData.restype = c_bool
_tln.TLN_DeleteSpriteset.argtypes = [c_void_p]
_tln.TLN_DeleteSpriteset.restype = c_bool
class Spriteset(object):
"""
The Spriteset object holds the graphic data used to render moving objects (sprites)
:ivar palette: original palette attached inside the resource file
"""
def __init__(self, handle: c_void_p, owner: bool=True):
self._as_parameter_ = handle
self.owner = owner
self.library = _tln
self.palette = Palette(_tln.TLN_GetSpritesetPalette(handle), False)
@classmethod
def create(cls, bitmap: "Bitmap", sprite_data: POINTER(SpriteData)) -> "Spriteset":
"""
Static method that creates an empty spriteset
:param bitmap: Bitmap object containing the packaged sprite pictures
:param sprite_data: list of SpriteData tuples describing each sprite pictures
:return: instance of the created object
"""
handle = _tln.TLN_CreateSpriteset(bitmap, sprite_data, len(sprite_data))
if handle is not None:
return Spriteset(handle)
else:
_raise_exception()
@classmethod
def fromfile(cls, filename: str) -> "Spriteset":
"""
Static method that loads a spriteset from a pair of png/txt files
:param filename: png filename with bitmap data
:return: instance of the created object
"""
handle = _tln.TLN_LoadSpriteset(_encode_string(filename))
if handle is not None:
return Spriteset(handle)
else:
_raise_exception()
def clone(self) -> "Spriteset":
"""
Creates a copy of the object
:return: instance of the copy
"""
handle = _tln.TLN_CloneSpriteset(self)
if handle is not None:
return Spriteset(handle)
else:
_raise_exception()
def set_sprite_data(self, entry: int, data: POINTER(SpriteData), pixels: POINTER(c_byte), pitch: int):
"""
Sets attributes and pixels of a given sprite inside a spriteset
:param entry: The entry index inside the spriteset to modify [0, num_sprites - 1]
:param data: Pointer to a user-provided SpriteData structure with sprite description
:param pixels: Pointer to user-provided pixel data block
:param pitch: Number of bytes per scanline of the source pixel data
"""
ok = _tln.TLN_SetSpritesetData(self, entry, data, pixels, pitch)
_raise_exception(ok)
def get_sprite_info(self, entry: int, info: POINTER(SpriteInfo)):
"""
Gets info about a given sprite into an user-provided SpriteInfo tuple
:param entry: sprite index to query
:param info: SpriteInfo to get the data
"""
ok = _tln.TLN_GetSpriteInfo(self, entry, info)
_raise_exception(ok)
def __del__(self):
if self.owner:
ok = self.library.TLN_DeleteSpriteset(self)
_raise_exception(ok)
# tilesets management ---------------------------------------------------------
_tln.TLN_CreateTileset.argtypes = [c_int, c_int, c_int, c_void_p, c_void_p, POINTER(TileAttributes)]