-
Notifications
You must be signed in to change notification settings - Fork 4
/
rotabox.py
1740 lines (1481 loc) · 68.6 KB
/
rotabox.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
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
"""
ROTABOX python 2.7 kivy 1.10 / python 3.7 kivy 2.1
=======
Rotabox is a *kivy widget* with customizable 2D bounds that follow its rotation.
The users can shape their own, specific bounds, to fit an image (or a series of
images in an animation), using a visual editor (See Rotaboxer below).
Rotabox also offers multitouch interactivity (drag, rotation and scaling).
==========================
Features & particularities
Collision detection methods:
Rotabox offers two collision approaches.
They can't be both used at the same time on the same widget and, normally,
collisions are thought to happen between widgets that use the same detection
method.
Combinations between the two are possible but rather heavier.
* Segment intersection detection (Default option):
(See 'Introduction to Algorithms 3rd Edition', ch.33 Computational Geometry
(https://mitpress.mit.edu/books/introduction-algorithms)
and 'Line Segment Intersection' lecture notes by Jeff Erickson
(http://jeffe.cs.illinois.edu/teaching/373/notes/x06-sweepline.pdf))
* Supports open-shaped bounds, down to just a single line segment.
* Interacts with Rotaboxes that use either detection method
(more expensive if method is different) and regular widgets.
* In a positive check against a Rotabox of the same method, instead of
*True*, both the intersected sides' indices and their respecrive
polygons' indices are returned, in the form of:
[(this_pol_i, this_side_i), (that_pol_i, that_side_i)].
* Point membership in polygon detection:
(See 'Even-odd rule'(https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule "")
* It can be less expensive when dealing with complex shapes (more than 15
segments), as it can benefit from breaking these shapes into more simple
ones when making the bounds in the editor.
* Requires mutual collision checks (All involved widgets should check for
an accurate reading).
* Interacts with Rotaboxes that use the same detection method and regular
widgets (but behaving, itself, like a regular widget while doing so).
* In a positive check against a Rotabox of the same method, instead of
*True*, the checker's collided polygon's index is returned, in a tuple
(i) to always evaluate to True.
Open collision bounds (Segment method only)
If a polygon is open, the segment between the last and first points of the
polygon is not considered in the collision checks.
Since the segment collision method is only concerned with the polygon's
sides, a widget can 'enter' an open polygon, passing through the opening,
and then hit the back wall from inside, for example.
Note that *collide_point* doesn't work for an open polygon (i.e. an open
polygon cannot be touched accurately).
Visual point tracking
Since a rotating widget doesn't really rotate, its points lose their
reference to its visual (Positional properties like [top] or [center] don't
rotate).
Rotabox can track any of its own points while rotating, provided that they
are predefined (Hence, the custom bounds' ability).
They then can be accessed using their indices.
This can be useful, for example, in changing the point of rotation to a
predefined point on the widget while the latter is rotating.
Touch interactivity
Since, due to the differences between the Scatter and Rotabox concepts, a
way to combine the two couldn't be found, Rotabox uses the Scatter widget's
code, modified to act on the actual size and position of the widget and
child (essential for accurate collision detection).
It supports single and multitouch drag, rotation and scaling (the latter two
use the *origin* property in the singletouch option).
Cython option
Rotabox tries by default to use a compiled cython module (cybounds.so or
cybounds.pyd) for an about X5 speedup.
User needs to compile it for specific systems using the provided
cybounds.c file.
Restrictions
* In order to be able to maintain any arbitrary aspect ratio (e.g. its image's
ratio), Rotabox can't use the *size_hint* property.
Try using *size* property in a relative manner instead
(e.g. `self.width = self.parent.width * .5`).
* Rotabox can only have one child. It can be an *Image* but not necessarily.
Grandchildren, however, can collide independently, only if the widget is not
rotated ( *angle* must be *0* ).
===
API
Basic Usage
To use Rotabox, just include *rotabox_full.py* in your project files.
from rotabox import Rotabox
...
rb = Rotabox()
rb.add_widget(Image(source='img.png'))
self.add_widget(rb)
The instance's default bounding box will be a rectangle, the size of the image,
that rotates with it.
Use *angle* and *origin* properties for rotation.
_________
Interface
**angle** *NumericProperty* (0):
The angle of rotation in degrees.
**origin** *AliasProperty* *tuple* (center):
Sets the point of rotation. Default position is the widget's center.
**image** *ObjectProperty*:
Rotabox's only child will most likely be an *Image*.
If not so, Rotabox will attempt to find the topmost *Image* in its tree and
assign it to this property.
Otherwise, the user can specify an *image* somewhere in the widget's tree,
that the custom bounds will use as a reference.
An .atlas spritesheet can also be used as an animation source and different
bounds can be defined for each frame.
**aspect_ratio** *NumericProperty* (0.)
If not provided, *image*'s ratio is going to be used.
_______________________________
Customizing the Collidable Area
**Rotaboxer** Visual editor.
A convenient way to define the *custom_bounds* of a Rotabox widget.
To use it, run *rotaboxer.py* directly. It can be found in the
*Visual Editor* folder, at the repository.
Open a *.png* image or an *.atlas* file in the editor, draw bounds for it
and export the resulting code to clipboard, to use in a Rotabox widget.
**custom_bounds** *ObjectProperty* (`[[(0, 0), (1, 0), (1, 1), (0, 1)]]`)
This is where the custom bounds are being defined.
It's also the output of the Rotaboxer tool (above).
It can be a *list* of one or more polygons' data as seen in its default
value, above.
Each polygon's data is a *list* of point tuples `(x, y)`.
Points' values should be expressed as percentages of the widget's *width*
and *height*, where `(0, 0)` is widget's `(x, y)`, `(1, 1)` is widget's
`(right, top)` and `(.5, .5)` is widget's *center*.
Here's another example with more polygons:
self.bounds = [[(0.013, 0.985), (0.022, 0.349),
(0.213, 0.028), (0.217, 0.681)],
[(0.267, 0.346), (0.483, -0.005),
(0.691, 0.316), (0.261, 0.975)],
[(0.539, 0.674), (0.73, 0.37),
(0.983, 0.758)]]
*custom_bounds* can also be a *dictionary*, in case of animated bounds
(different bounds for different frames of an animation sequence in an
*.atlas* file), where the *keys* correspond to the frame names in the
*.atlas* file and each *item* is a *list* of one or more polygons' data
like the above.
Here's an example of such a *dictionary*:
self.bounds = {'00': [[(0.201, 0.803), (0.092, 0.491),
(0.219, 0.184), (0.526, 0.064)],
[(0.419, 0.095), (0.595, 0.088),
(0.644, 0.493)]],
'01': [[(0.357, 0.902), (0.17, 0.65),
(0.184, 0.337), (0.343, 0.095),
(0.644, 0.098)]],
'02': [[(...
...
... etc ]]}
**segment_mode** *BooleanProperty* (True):
Toggle between the two collision detection methods *(See Features above)*.
**open_bounds** *ListProperty*:
If a polygon's index is in this list, the segment between the last and first
points of the polygon is not considered in the collision checks
(segment_mode only).
**pre_check** *BooleanProperty* (False):
A collision optimization switch for larger widgets in Cython.
For small widgets (under 45 points), the tax of extra calculations
outweighs any benefit in collision.
_______________
Touch interface
Most of it is familiar from the Scatter widget.
**touched_to_front** *BooleanProperty* (False)
If touched, the widget will be pushed to the top of the parent widget tree.
**collide_after_children** *BooleanProperty* (True)
If True, limiting the touch inside the bounds will be done after dispaching
the touch to the child and grandchildren, so even outside the bounds they
can still be touched.
*IMPORTANT NOTE: Grandchildren, inside or outside the bounds, can collide
independently ONLY if widget is NOT ROTATED ( *angle* must be *0* ).*
Single touch definitions:
**single_drag_touch** *BoundedNumericProperty* (1, min=1)
How many touches will be treated as one single drag touch.
**single_trans_touch** *BoundedNumericProperty* (1, min=1)
How many touches will be treated as one single transformation touch.
Single touch operations:
**allow_drag_x** *BooleanProperty* (False)
**allow_drag_y** *BooleanProperty* (False)
**allow_drag** *AliasProperty*
**single_touch_rotation** *BooleanProperty* (False)
Rotate around *origin*.
**single_touch_scaling** *BooleanProperty* (False)
Scale around *origin*.
Multitouch rotation/scaling:
**multi_touch_rotation** *BooleanProperty* (False)
**multi_touch_scaling** *BooleanProperty* (False)
_________________
Utility interface
**pivot** *ReferenceListProperty*
The point of rotation and scaling.
While *origin* property sets *pivot*'s position, relatively to widget's
*size* and *pos*, *pivot* itself can be used to position the widget, much
like *pos* or *center*.
**get_point(pol_index, point_index)** *Method*
Returns the current position of a certain point.
The argument indices are based on user's [custom_bounds]' structure.
**read_bounds(filename)** *Method*
Define [custom_bounds] using a rotaboxer's project file (.bounds file).
To work, [size] should be already defined.
**draw_bounds** *NumericProperty* (0)
This option can be useful during testing, as it makes the widget's bounds
visible. (1 for bounds, 2 for bounds & bounding boxes)
**scale** *AliasProperty*
Current widget's scale.
**scale_min** *NumericProperty* (0.01)
**scale_max** *NumericProperty* (1e20)
Optional scale restrictions.
**ready** *BooleanProperty* (False)
Signifies the completion of the widget's initial preparations.
Useful to read in cases where the widget is stationary.
Also, its state changes to False when a size change or reset is triggered
and back to True after said size change or reset.
**prepared** *BooleanProperty* (False)
Its state change signifies a reset.
The reset completion signal, however, is the consequent [ready] state change
to True.
___________________________________________________________________________
A Rotabox example can be seen if this module is run directly.
"""
__author__ = 'unjuan'
__version__ = '0.13.7'
__all__ = ('Rotabox', )
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.vector import Vector
from kivy.graphics import PushMatrix, Rotate, PopMatrix
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Line
from kivy.properties import (NumericProperty, ReferenceListProperty,
AliasProperty, ObjectProperty, BooleanProperty,
ListProperty, BoundedNumericProperty, partial)
from math import radians, sin, cos
import json, sys
if sys.version_info < (3, 0): # Python 2.x
from codecs import open
range = xrange
from future.utils import iteritems, itervalues
try:
from cybounds import define_bounds, resize, aniresize, get_peers, \
update_bounds, aniupdate_bounds, point_in_bounds, collide_bounds
peers = get_peers()
except ImportError:
import logging
logging.log(30, "[Rotabox ] cybounds module NOT found. "
"Using internal functions instead.\n")
from array import array
peers = {}
def scale(points, length, width, height):
for h in range(0, length, 2):
points[h] = points[h] * width
points[h+1] = points[h+1] * height
def move(points, length, pos0, pos1):
for i in range(0, length, 2):
points[i] = points[i] + pos0
points[i+1] = points[i+1] + pos1
def rotate(points, length, angle, orig0, orig1):
c = cos(angle)
s = sin(angle)
for j in range(0, length, 2):
points[j] = points[j] - orig0
points[j+1] = points[j+1] - orig1
pj = points[j]
points[j] = pj * c - points[j+1] * s
points[j+1] = pj * s + points[j+1] * c
points[j] = points[j] + orig0
points[j+1] = points[j+1] + orig1
def calc_segboxes(points, polids, ptids, plens, length, bbox, blefts, bbotts,
brghts, btops):
for k in range(0, length, 2):
k1 = k + 1
off = plens[polids[k]] * 2 - 2
if ptids[k] < plens[polids[k]] - 1:
k2 = k1 + 1
k3 = k2 + 1
else:
k2 = k - off
k3 = k2 + 1
blefts[k] = points[k] if points[k] <= points[k2] else points[k2]
bbotts[k] = points[k1] if points[k1] <= points[k3] else points[k3]
brghts[k] = points[k] if points[k] >= points[k2] else points[k2]
btops[k] = points[k1] if points[k1] >= points[k3] else points[k3]
if blefts[k] < bbox[0]:
bbox[0] = blefts[k]
if brghts[k] > bbox[2]:
bbox[2] = brghts[k]
if bbotts[k] < bbox[1]:
bbox[1] = bbotts[k]
if btops[k] > bbox[3]:
bbox[3] = btops[k]
def calc_polboxes(points, plens, bbox, blefts, bbotts, brghts, btops):
strt = 0
for p in range(len(plens)):
left = float("inf")
bottom = float("inf")
right = 0.
top = 0.
for l in range(strt, strt + plens[p] * 2, 2):
l1 = l + 1
if points[l] < left:
left = points[l]
if points[l] > right:
right = points[l]
if points[l1] < bottom:
bottom = points[l1]
if points[l1] > top:
top = points[l1]
if left < bbox[0]:
bbox[0] = left
if right > bbox[2]:
bbox[2] = right
if bottom < bbox[1]:
bbox[1] = bottom
if top > bbox[3]:
bbox[3] = top
blefts[p] = left
bbotts[p] = bottom
brghts[p] = right
btops[p] = top
strt = strt + plens[p] * 2
def intersection_w(pts, ptids, plens, opens, t_box):
t_pts = [t_box[0], t_box[1], t_box[2], t_box[1],
t_box[2], t_box[3], t_box[0], t_box[3]]
o = 0
strt = 0
for p in range(len(plens)):
if p in opens:
o = 2
for i in range(strt, strt + plens[p] * 2 - o, 2):
i1 = i + 1
off = plens[p] * 2 - 2
if ptids[i] < plens[p] - 1:
i2 = i1 + 1
i3 = i2 + 1
else:
i2 = i - off
i3 = i2 + 1
v10 = pts[i]
v11 = pts[i1]
v20 = pts[i2]
v21 = pts[i3]
for j in range(0, 8, 2):
j1 = j + 1
t_off = 6
if j < 6:
j2 = j1 + 1
j3 = j2 + 1
else:
j2 = j - t_off
j3 = j2 + 1
v30 = t_pts[j]
v31 = t_pts[j1]
v40 = t_pts[j2]
v41 = t_pts[j3]
# Segment intersection detection method:
# If the vertices v1 and v2 are not on opposite sides of the
# segment v3, v4, or the vertices v3 and v4 are not on
# opposite sides of the segment v1, v2, there's no
# intersection.
if (((v40 - v30) * (v11 - v31) -
(v10 - v30) * (v41 - v31) > 0) ==
((v40 - v30) * (v21 - v31) -
(v20 - v30) * (v41 - v31) > 0)):
continue
elif (((v20 - v10) * (v31 - v11) -
(v30 - v10) * (v21 - v11) > 0) ==
((v20 - v10) * (v41 - v11) -
(v40 - v10) * (v21 - v11) > 0)):
continue
return [p, ptids[i], 0, j/2]
strt = strt + plens[p] * 2
return False
def intersection_f(pts, ptids, plens, opens, t_pts, t_polis, t_ptis, t_plens):
o = 0
strt = 0
for p in range(len(plens)):
if p in opens:
o = 2
for i in range(strt, strt + plens[p] * 2 - o, 2):
i1 = i + 1
off = plens[p] * 2 - 2
if ptids[i] < plens[p] - 1:
i2 = i1 + 1
i3 = i2 + 1
else:
i2 = i - off
i3 = i2 + 1
v10 = pts[i]
v11 = pts[i1]
v20 = pts[i2]
v21 = pts[i3]
t_strt = 0
for t_p in range(len(t_plens)):
for j in range(t_strt, t_strt + t_plens[t_p] * 2, 2):
j1 = j + 1
t_off = t_plens[t_polis[j]] * 2 - 2
if t_ptis[j] < t_plens[t_polis[j]] - 1:
j2 = j1 + 1
j3 = j2 + 1
else:
j2 = j - t_off
j3 = j2 + 1
v30 = t_pts[j]
v31 = t_pts[j1]
v40 = t_pts[j2]
v41 = t_pts[j3]
# Segment intersection detection method:
# If the vertices v1 and v2 are not on opposite sides of
# the segment v3, v4, or the vertices v3 and v4 are not
# on opposite sides of the segment v1, v2, there's no
# intersection.
if (((v40 - v30) * (v11 - v31) -
(v10 - v30) * (v41 - v31) > 0) ==
((v40 - v30) * (v21 - v31) -
(v20 - v30) * (v41 - v31) > 0)):
continue
elif (((v20 - v10) * (v31 - v11) -
(v30 - v10) * (v21 - v11) > 0) ==
((v20 - v10) * (v41 - v11) -
(v40 - v10) * (v21 - v11) > 0)):
continue
return [p, ptids[i], t_p, t_ptis[j]]
t_strt = t_strt + t_plens[t_p] * 2
strt = strt + plens[p] * 2
return False
def intersection(pts, ptids, le, plens, opens, lefts, botts, rghts, tops,
t_box, t_pts, t_ptis, t_le, t_plens, t_opens, t_lefts,
t_botts, t_rghts, t_tops):
o = 0
t_o = 0
strt = 0
for p in range(len(plens)):
if p in opens:
o = 2
for i in range(strt, strt + plens[p] * 2 - o, 2):
if rghts[i] < t_box[0]:
continue
if lefts[i] > t_box[2]:
continue
if tops[i] < t_box[1]:
continue
if botts[i] > t_box[3]:
continue
i1 = i + 1
off = plens[p] * 2 - 2
if ptids[i] < plens[p] - 1:
i2 = (i1 + 1) % le
i3 = i2 + 1
else:
i2 = i - off
i3 = i2 + 1
v10 = pts[i]
v11 = pts[i1]
v20 = pts[i2]
v21 = pts[i3]
t_strt = 0
for t_p in range(len(t_plens)):
if t_p in t_opens:
t_o = 2
for j in range(t_strt, t_strt + t_plens[t_p] * 2 - t_o, 2):
if rghts[i] < t_lefts[j]:
continue
if lefts[i] > t_rghts[j]:
continue
if tops[i] < t_botts[j]:
continue
if botts[i] > t_tops[j]:
continue
j1 = j + 1
t_off = t_plens[t_p] * 2 - 2
if t_ptis[j] < t_plens[t_p] - 1:
j2 = (j1+1) % t_le
j3 = j2 + 1
else:
j2 = j - t_off
j3 = j2 + 1
v30 = t_pts[j]
v31 = t_pts[j1]
v40 = t_pts[j2]
v41 = t_pts[j3]
# Segment intersection detection method:
# If the vertices v1 and v2 are not on opposite sides of
# the segment v3, v4, or the vertices v3 and v4 are not
# on opposite sides of the segment v1, v2, there's no
# intersection.
if (((v40 - v30) * (v11 - v31) -
(v10 - v30) * (v41 - v31) > 0) ==
((v40 - v30) * (v21 - v31) -
(v20 - v30) * (v41 - v31) > 0)):
continue
elif (((v20 - v10) * (v31 - v11) -
(v30 - v10) * (v21 - v11) > 0) ==
((v20 - v10) * (v41 - v11) -
(v40 - v10) * (v21 - v11) > 0)):
continue
return [p, ptids[i], t_p, t_ptis[j]]
t_strt = t_strt + t_plens[t_p] * 2
strt = strt + plens[p] * 2
return False
def membership(pts, plens, lefts, botts, rghts, tops,
t_box, t_pts, t_polis, t_le):
strt = 0
for p, pl in enumerate(plens):
# Preliminary 1: pol's bbox vs widget's bbox.
if rghts[p] < t_box[0]:
strt = strt + pl * 2
continue
if lefts[p] > t_box[2]:
strt = strt + pl * 2
continue
if tops[p] < t_box[1]:
strt = strt + pl * 2
continue
if botts[p] > t_box[3]:
strt = strt + pl * 2
continue
for k in range(0, t_le, 2):
x = t_pts[k]
y = t_pts[k + 1]
# Preliminary 2: pol's bbox vs widget's points to filter out.
if rghts[p] < x:
continue
if lefts[p] > x:
continue
if tops[p] < y:
continue
if botts[p] > y:
continue
# Point-in-polygon (oddeven) collision detection method:
# Checking the membership of each poby assuming a ray at 0 angle
# from that poto infinity (through window right) and counting
# the number of times that this ray crosses the polygon line.
# If this number is odd, the pois inside; if it's even, the pois
# outside.
c = 0
j = strt + pl * 2 - 2
for i in range(strt, strt + pl * 2, 2):
x1 = pts[j]
y1 = pts[j+1]
x2 = pts[i]
y2 = pts[i+1]
if (((y2 > y) != (y1 > y))
and x < (x1 - x2) * (y - y2) / (y1 - y2) + x2):
c = not c
j = i
if c:
return [p, t_polis[k]]
strt = strt + pl * 2
return False
def collide_bounds(rid, wid, frame='bounds', tframe='bounds'):
try:
this_box = peers[rid]['bbox']
except KeyError:
return False
try:
that_box = peers[wid]['bbox']
except TypeError:
that_box = wid
try:
if this_box[2] < that_box[0]:
return False
except IndexError:
return False
if this_box[0] > that_box[2]:
return False
if this_box[3] < that_box[1]:
return False
if this_box[1] > that_box[3]:
return False
bounds = peers[rid][frame]
try:
tbounds = peers[wid][tframe]
except TypeError:
return intersection_w(bounds['points'], bounds['pt_ids'],
bounds['pol_lens'], bounds['opens'], that_box)
if peers[rid]['seg']:
if peers[wid]['seg']:
return intersection(bounds['points'], bounds['pt_ids'],
bounds['length'], bounds['pol_lens'],
bounds['opens'], bounds['lefts'],
bounds['botts'], bounds['rights'],
bounds['tops'], that_box,
tbounds['points'], tbounds['pt_ids'],
tbounds['length'], tbounds['pol_lens'],
tbounds['opens'], tbounds['lefts'],
tbounds['botts'], tbounds['rights'],
tbounds['tops'])
else:
return intersection_f(bounds['points'], bounds['pt_ids'],
bounds['pol_lens'], bounds['opens'],
tbounds['points'], tbounds['pol_ids'],
tbounds['pt_ids'], tbounds['pol_lens'])
else:
return membership(bounds['points'], bounds['pol_lens'],
bounds['lefts'], bounds['botts'], bounds['rights'],
bounds['tops'], that_box, tbounds['points'],
tbounds['pol_ids'],
tbounds['length'])
def point_in_bounds(x, y, rid, frame='bounds'):
'''"Oddeven" point-in-polygon method:
Checking the membership of touch poby assuming a ray at 0 angle
from that poto infinity (through window right) and counting the
number of polygon sides that this ray crosses. If this number is
odd, the pois inside; if it's even, the pois outside.
'''
bounds = peers[rid][frame]
strt = 0
for r, rang in enumerate(bounds['pol_lens']):
c = 0
j = strt + rang * 2 - 2
for i in range(strt, strt + rang * 2, 2):
x1, y1 = bounds['points'][j], bounds['points'][j+1]
x2, y2 = bounds['points'][i], bounds['points'][i+1]
if (((y2 > y) != (y1 > y)) and
x < (x1 - x2) * (y - y2) / (y1 - y2) + x2):
c = not c
j = i
if c:
return c
strt = strt + rang * 2
return False
def update_bounds(motion, angle, origin, rid, frame='bounds'):
'''Updating the elements of the collision detection checks.
'''
try:
bounds = peers[rid][frame]
except TypeError:
return
if motion:
move(bounds['points'], bounds['length'], motion[0], motion[1])
if angle:
rotate(bounds['points'], bounds['length'], angle, origin[0],
origin[1])
bbox = array('d', [float("inf"), float("inf"), 0., 0.])
if peers[rid]['seg']:
calc_segboxes(bounds['points'], bounds['pol_ids'], bounds['pt_ids'],
bounds['pol_lens'], bounds['length'], bbox,
bounds['lefts'], bounds['botts'], bounds['rights'],
bounds['tops'])
else:
calc_polboxes(bounds['points'], bounds['pol_lens'], bbox,
bounds['lefts'], bounds['botts'], bounds['rights'],
bounds['tops'])
peers[rid]['bbox'] = bbox
def aniupdate_bounds(motion, pos, angle, origin, rid, frame='bounds'):
'''Updating the elements of the collision detection checks,
in case of an animation.
'''
try:
bounds = peers[rid][frame]
except TypeError:
return
if motion:
bounds['mov_pts'][:] = bounds['sca_pts']
move(bounds['mov_pts'], bounds['length'], pos[0], pos[1])
bounds['points'][:] = bounds['mov_pts']
if angle:
bounds['points'][:] = bounds['mov_pts']
rotate(bounds['points'], bounds['length'], angle, origin[0],
origin[1])
bbox = array('d', [float("inf"), float("inf"), 0., 0.])
if peers[rid]['seg']:
calc_segboxes(bounds['points'], bounds['pol_ids'], bounds['pt_ids'],
bounds['pol_lens'], bounds['length'], bbox,
bounds['lefts'], bounds['botts'], bounds['rights'],
bounds['tops'])
else:
calc_polboxes(bounds['points'], bounds['pol_lens'], bbox,
bounds['lefts'], bounds['botts'], bounds['rights'],
bounds['tops'])
peers[rid]['bbox'] = bbox
def resize(width, height, rid):
for k, frame in iteritems(peers[rid]):
if k == 'bounds':
bounds = peers[rid]['bounds']
bounds['points'][:] = bounds['hints']
scale(bounds['points'], bounds['length'], width, height)
break
else:
for k, frame in iteritems(peers[rid]):
if k != 'bbox' and k != 'vbbox' and k != 'hhits' and k != 'seg' \
and k != 'friendly':
frame['points'][:] = frame['hints']
scale(frame['points'], frame['length'], width, height)
def aniresize(width, height, rid):
for k, frame in iteritems(peers[rid]):
if k == 'bounds':
bounds = peers[rid]['bounds']
bounds['sca_pts'][:] = bounds['hints']
scale(bounds['sca_pts'], bounds['length'], width, height)
break
else:
for k, frame in iteritems(peers[rid]):
if k != 'bbox' and k != 'seg' and k != '':
frame['sca_pts'][:] = frame['hints']
scale(frame['sca_pts'], frame['length'], width, height)
def define_frame(frame, opens, seg_mode, bounds, ani=False):
for p in range(len(frame)):
pol = frame[p]
plen = len(pol)
array.extend(bounds['pol_lens'], array('i', [plen]))
for i in range(plen):
array.extend(bounds['hints'], array('d', [pol[i][0], pol[i][1]]))
array.extend(bounds['pol_ids'], array('i', [p, p]))
array.extend(bounds['pt_ids'], array('i', [i, i]))
bounds['length'] += 2
if seg_mode:
length = bounds['length']
else:
length = len(bounds['pol_lens'])
bounds['lefts'] = array('d', [float("inf")] * length)
bounds['botts'] = array('d', [float("inf")] * length)
bounds['rights'] = array('d', [0.] * length)
bounds['tops'] = array('d', [0.] * length)
if seg_mode:
bounds['opens'] = array('i', opens)
if ani:
bounds['mov_pts'][:] = bounds['sca_pts'][:] = bounds['hints']
bounds['points'][:] = bounds['hints']
def define_bounds(custom_bounds, open_bounds, segment_mode, rid, pc):
'''Organising the data from the user's [self.custom_bounds] hints.
The [pc] parameter is not used. It's here for compatibility with the
equivalent function in the cython module.
'''
frames = {}
if isinstance(custom_bounds, dict): # Animation case
for key, frame in iteritems(custom_bounds):
bounds = {'hints': array('d'), 'sca_pts': array('d'),
'mov_pts': array('d'), 'points': array('d'),
'pol_ids': array('i'), 'pt_ids': array('i'),
'pol_lens': array('i'), 'length': 0}
if isinstance(open_bounds, dict):
opens = array('i', open_bounds[key])
else:
opens = array('i', open_bounds)
define_frame(frame, opens, segment_mode, bounds, ani=True)
frames[key] = bounds
elif isinstance(custom_bounds, list): # Single image case
bounds = {'hints': array('d'), 'points': array('d'),
'pol_ids': array('i'), 'pt_ids': array('i'),
'pol_lens': array('i'), 'length': 0}
define_frame(custom_bounds, open_bounds, segment_mode, bounds)
frames['bounds'] = bounds
frames['bbox'] = array('d', [])
frames['seg'] = segment_mode
peers[rid] = frames
class Rotabox(Widget):
'''See module's documentation.'''
__events__ = ('on_transform_with_touch', 'on_touched_to_front')
# -------------------------------------------------------- VISUAL INTERFACE
'''This should be the image that any custom bounds are meant for.
If not defined, widget will try to locate the topmost image in its tree.'''
image = ObjectProperty()
'''The widget's aspect ratio. If not defined, image's ratio will be used.'''
aspect_ratio = NumericProperty(0.)
# ------------------------------------------------------ ROTATION INTERFACE
'''Angle of Rotation.'''
angle = NumericProperty(0)
def get_origin(self):
return self.pivot
def set_origin(self, point):
angle = -radians(self.last_angle)
orig = self.origin
s = sin(angle)
c = cos(angle)
# normalize (translate point so origin will be 0,0)
dx = point[0] - orig[0]
dy = point[1] - orig[1]
# un-rotate point
xnew = dx * c - dy * s
ynew = dx * s + dy * c
# translate point back:
pivot = xnew + orig[0], ynew + orig[1]
# lock pos-pivot relation
self.pivot_bond = [(pivot[0] - self.x) / float(self.width),
(pivot[1] - self.y) / float(self.height)]
# Since the image (on canvas) always starts each frame in zero angle,
# an [origin] change in any non-zero angle breaks the continuity of
# motion/rotation, introducing an image translation (jump).
# compensating by changing the widget's position.
# prevent a bounds' update to [pos] change below.
self.allow = 0
# compensating for image translation
self.pos = (self.x - (pivot[0] - point[0]),
self.y - (pivot[1] - point[1]))
# cannot wait for the triggered [update], at the end of this frame,
# since it might concern other changes that require a bounds' update.
self.update()
'''Sets the point of rotation. Default value is the widget's center.
Works nicely with the [get_point] method below and points already defined in
[custom_bounds].'''
origin = AliasProperty(get_origin, set_origin)
# ----------------------------------------------------- COLLISION INTERFACE
'''Enables widget's advanced collision detection. If False, widget will
collide as a normal (non-Rotabox) widget.'''
allow_rotabox = BooleanProperty(True)
'''Custom bounds' definition interface. (See module's documentation).'''
custom_bounds = ObjectProperty([[(0., 0.), (1., 0.), (1., 1.), (0., 1.)]])
'''Collision detection method switch (see documentation above).'''
segment_mode = BooleanProperty(True)
'''(segment_mode) If a polygon's index is in this list, the segment
between the last and first points of the polygon is not considered in the
collision checks.'''
open_bounds = ListProperty()
'''(Cython) A collision optimization switch for larger widgets (45+ points).
It's always True in Python but in Cython, for small widgets, the slight tax
in updating the bounds outweighs the benefit in collision.'''
pre_check = BooleanProperty(False)
# --------------------------------------------------------- TOUCH INTERFACE
'''Allow touch translation on the X axis.'''
allow_drag_x = BooleanProperty(False)
'''Allow touch translation on the Y axis.'''
allow_drag_y = BooleanProperty(False)
def get_allow_drag(self):
return self.allow_drag_x, self.allow_drag_y
def set_allow_drag(self, value):
if type(value) in (list, tuple):
self.allow_drag_x, self.allow_drag_y = value
else:
self.allow_drag_x = self.allow_drag_y = bool(value)
'''Allow touch translation on the X or Y axis.'''
allow_drag = AliasProperty(get_allow_drag, set_allow_drag,
bind=('allow_drag_x', 'allow_drag_y'))
'''Allow rotation around [origin]..'''
single_touch_rotation = BooleanProperty(False)
'''Allow scaling around [origin].'''
single_touch_scaling = BooleanProperty(False)
'''Allow multitouch rotation. [origin] is defined each time by the touch.'''
multi_touch_rotation = BooleanProperty(False)
'''Allow multitouch scaling. [origin] is defined each time by the touch.'''
multi_touch_scaling = BooleanProperty(False)
'''How many touches will be treated as one single drag touch.'''
single_drag_touch = BoundedNumericProperty(1, min=1)
'''How many touches will be treated as one single rotation/scaling touch.'''
single_trans_touch = BoundedNumericProperty(1, min=1)
'''If touched, widget will be pushed to the top of parent widget tree.'''
touched_to_front = BooleanProperty(False)
'''If True, limiting the touch inside the bounds will be done after
dispaching the touch to the child and grandchildren, so even outside the
bounds they can still be touched.
IMPORTANT NOTE: Grandchildren, inside or outside the bounds, can collide
independently ONLY if widget is NOT ROTATED ([angle] must be 0).'''
collide_after_children = BooleanProperty(False)
# ------------------------------------------------------- UTILITY INTERFACE