forked from mbenkmann/pydance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.py
2102 lines (1812 loc) · 75.2 KB
/
ui.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
'''
Copyright (C) 2018 Matthias S. Benkmann
Permission is hereby granted, free of charge, to any person obtaining a copy
of this file (originally named ui.py) 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.
'''
import pygame
from copy import copy, deepcopy
from collections import deque
import os
from constants import *
import i18n
# for debugging purposes, we keep a history of this many most recent pygame.event.Events.
MAX_KEEP_PYGAME_EVENTS = 128
# ID numbers for semantic events returned by the UI class.
# An input event as used in pydance is a pair (pid, evid) where
# evid is one of the following event IDs (negative if the event is turned off)
# and pid identifies the dance pad
# the event is associated with: -1 (not dance-related, menuing), 0 (player 1), 1 (player 2).
# The special ID "PASS" means "event queue is empty".
# The special ID "QUIT" is a request to terminate the program asap.
(PASS, CANCEL, UP, UPLEFT, LEFT, DOWNLEFT, DOWN, DOWNRIGHT,
RIGHT, UPRIGHT, CENTER, OPTIONS, RANDOM, SCREENSHOT,
CONFIRM, PGUP, PGDN, FULLSCREEN, SORT, QUIT) = list(range(20))
EVNAMES = ("PASS", "CANCEL", "UP", "UPLEFT", "LEFT", "DOWNLEFT", "DOWN", "DOWNRIGHT",
"RIGHT", "UPRIGHT", "CENTER", "OPTIONS", "RANDOM", "SCREENSHOT",
"CONFIRM", "PGUP", "PGDN", "FULLSCREEN", "SORT", "QUIT")
# Maximum number of players. Note that old code assumes 2 players in some places.
MAX_PLAYERS = 4
# Bitmask for pid. Used on special events used with generic buttons. These have
# the controller id encoded in pid.
PLAYERS_MASK = MAX_PLAYERS - 1
# maximum buttons supported for 1 controller
MAX_BUTTONS = 32
# a number greather than any of the semantic events above. This serves as the base
# for generic button events which are used internally for learning directional
# buttons from observing how they are activated simultaneously with axes.
GENERIC_BUTTON = 64
# Bit shift for encoding controller number in generic button event's pid.
GENERIC_BUTTON_SHIFTER = 8
# Minimum number of times a generic button must have been pressed
# (with no other buttons pressed at the same time) before it can be learned as
# UP/DOWN/LEFT/RIGHT.
MIN_LEARN_GENERIC_BUTTON_COUNT = 5
# Minimum percentage of times a generic button must have been seen together with
# direction X to learn it as that direction.
LEARN_GENERIC_BUTTON_DIRECTION = .85
# Maximum percentage of times a generic button must have been seen together with
# any direction for it to be learned as independent of directions.
LEARN_GENERIC_BUTTON_INDEPENDENT = .5
# Unfortunately the old SDL version that pygame uses does not give us events when
# controllers are plugged in or removed. So in order to support hotplugging we have
# to reinit the events system regularly. Because that risks losing events, we
# only do that if we have not received any events for a certain amount of time.
# Because losing events during dancing must be avoided at all costs and because it
# is less likely that someone would un/plug controllers during a dance, the wait
# time during dancing is very high. The reason we do it during dancing at all is
# that if someone pulls out the controller during the dance on a keyboardless system
# he would have to wait for the complete song to finish before he could interact
# with the machine again. That could be several minutes.
# When the reinit has been triggered by the expiration of the *_NO_EVENT_TIME, we
# poll for new devices every *_INTERVAL until we see the first event.
POLL_REINIT_CONTROLLERS_AFTER_NO_EVENT_TIME = 3000
POLL_REINIT_CONTROLLERS_INTERVAL = 2000
POLL_DANCE_REINIT_CONTROLLERS_AFTER_NO_EVENT_TIME = 20000
POLL_DANCE_REINIT_CONTROLLERS_INTERVAL = 5000
# If no output change occurs for this many milliseconds, UI.poll() will start
# repeating REPEATABLE outputs that are being held. Mostly used so that you
# can hold an arrow to move through menus and don't have to constantly tap it.
REPEAT_INITIAL_DELAY = 250
# Delay between repeats after REPEAT_INITIAL_DELAY.
REPEAT_DELAY = 80
# Events that are repeatable by auto-repeat (see REPEAT_INITIAL_DELAY and poll())
REPEATABLE = frozenset(((-1,UP),(-1,DOWN),(-1,LEFT),(-1,RIGHT),
(0,UP),(0,DOWN),(0,LEFT),(0,RIGHT),
(1,UP),(1,DOWN),(1,LEFT),(1,RIGHT),
(2,UP),(2,DOWN),(2,LEFT),(2,RIGHT),
(3,UP),(3,DOWN),(3,LEFT),(3,RIGHT)))
# These events are prefixed with "P1_" or "P2_" in the config file and
# have a pid 0 or 1 associated with them when used in pydance input events.
dance_events = {
"UP": UP,
"DOWN": DOWN,
"LEFT": LEFT,
"RIGHT": RIGHT,
"UPLEFT": UPLEFT,
"UPRIGHT": UPRIGHT,
"DOWNLEFT": DOWNLEFT,
"DOWNRIGHT": DOWNRIGHT,
"CENTER": CENTER,
}
# These events do not have a prefix in the config file and
# have a pid -1 associated with them when used in pydance input events.
# Note that "P1_UP" is not the same as "UP". On a dance pad, the up arrow
# would usually be configured to produce both at the same time, but a
# typical gamepad would have the d-pad produce only UP because the
# d-pad can't be used for dancing because you can't press up and down at
# the same time.
# Most pydance code does not need to care for this distinction because
# ui.poll() does not return dance events. Only the dancing code which
# uses ui.poll_dance() needs to care because that function returns
# everything.
control_events = {
"CANCEL": CANCEL,
"UP": UP,
"DOWN": DOWN,
"LEFT": LEFT,
"RIGHT": RIGHT,
"PGUP": PGUP,
"PGDN": PGDN,
"OPTIONS": OPTIONS,
"RANDOM": RANDOM,
"CONFIRM": CONFIRM,
"FULLSCREEN": FULLSCREEN,
"QUIT": QUIT,
"SCREENSHOT": SCREENSHOT,
"SORT": SORT,
}
def evstr(pid, evid):
prefix = ""
if evid < 0:
evid = -evid
prefix = "-"
if evid >= GENERIC_BUTTON:
prefix = ("C%d " % (pid >> GENERIC_BUTTON_SHIFTER)) + prefix
if pid > 0: pid = pid & PLAYERS_MASK
return "(%d,%s%s)" % (pid, prefix, EVNAMES[evid])
class EventValve(object):
'''
Produces events based on the crossing of a "pressure" threshold.
'''
def __init__(self, pid, evid, evlist, start_pressure):
'''
Creates an EventValve with value start_pressure. Whenever the
pressure goes from 0 to 1 by use of the plus() method, a tuple
(pid, evid) will be appended to evlist.
Whenever the pressure goes from 1 to 0 by use of the minus() method,
a tuple (pid, -evid) will be appended to evlist.
There are 2 major applications:
a) start_pressure == 0: The EventValve will function as an OR gate
for its inputs. It will be open if at least
one input is open.
b) start_pressure == -N: The EventValve will function as an AND gate
for N+1 inputs. It will be closed if at least
one input is closed.
'''
self.open = (pid, evid)
self.closed = (pid, -evid)
self.evlist = evlist
self.pressure = start_pressure
self.start_pressure = start_pressure
self.enabled = True
def plus(self):
if self.enabled and self.pressure == 0:
self.evlist.append(self.open)
self.pressure += 1
def minus(self):
self.pressure -= 1
if self.enabled and self.pressure == 0:
self.evlist.append(self.closed)
def reset(self):
''' Set pressure to start pressure. '''
self.pressure = self.start_pressure
def visit(self, idx, state, visitor):
visitor.visit([idx], [self])
def __deepcopy__(self, memo): # never deepcopy self.evlist. It's a reference.
return copy(self)
# the buffer to which EventValves created below append their output events.
# This is the default buffer for the UI class.
event_buffer = deque()
# maps a semantic event name as used in the config file (e.g. "P1_UP") to an EventValve for that event.
# ATTENTION! The EventValves in this dict must not be used directly. They have to be copied first, usually
# indirectly by EventPlumbing.clone().
valves = {}
# maps a (pid,evid) pair to an event name as used in the config file. (e.g. (0,UP) => "P1_UP")).
# This is basically the reverse of the valves dict.
valvenames = {}
# Create EventValves for all possible semantic events.
for evname, evid in control_events.items():
valves[evname] = EventValve(-1, evid, event_buffer, 0)
valvenames[(-1, evid)] = evname
for pid in range(MAX_PLAYERS):
for evname, evid in dance_events.items():
fullname = "P%d_%s" % (pid+1, evname)
valves[fullname] = EventValve(pid, evid, event_buffer, 0)
valvenames[(pid,evid)] = fullname
for butt in range(MAX_BUTTONS):
fullname = "P%d_BUTTON_%d" % (pid+1, butt)
valves[fullname] = EventValve(pid, GENERIC_BUTTON+butt, event_buffer, 0)
valvenames[(pid, GENERIC_BUTTON+butt)] = fullname
class EventForkValve(object):
'''
Passes on "pressure" to multiple EventValves based on the crossing of a "pressure" threshold.
'''
def __init__(self, start_pressure, output_valves):
'''
Creates an EventForkValve with value start_pressure. Whenever the
pressure goes from 0 to 1 by use of the plus() method, the call x.plus() is
performed for all x in output_valves.
Whenever the pressure goes from 1 to 0 by use of the minus() method,
the call x.minus() is performed for all x in output_valves.
There are 2 major applications:
a) start_pressure == 0: The EventForkValve will function as an OR gate
for its inputs. It will be open if at least
one input is open.
b) start_pressure == -N: The EventForkValve will function as an AND gate
for N+1 inputs. It will be closed if at least
one input is closed.
'''
self.pressure = start_pressure
self.start_pressure = start_pressure
self.output_valves = output_valves
def plus(self):
if self.pressure == 0:
for x in self.output_valves: x.plus()
self.pressure += 1
def minus(self):
self.pressure -= 1
if self.pressure == 0:
for x in self.output_valves: x.minus()
def reset(self):
''' Resets pressure to start pressure for this valve and all of its output valves. '''
self.pressure = self.start_pressure
for x in self.output_valves: x.reset()
def visit(self, idx, state, visitor):
lst = state.setdefault(self,[])
lst.append(idx)
if len(lst) == -self.start_pressure+1:
visitor.visit(lst, self.output_valves)
del state[self]
def replace_valve(self, oldpidevid, newvalve, already_counted):
i = 0
have = False
while i < len(self.output_valves):
x = self.output_valves[i]
if x.open == oldpidevid:
self.output_valves[i] = newvalve
if x not in already_counted:
newvalve.pressure += x.pressure
already_counted.add(x)
if self.output_valves[i] == newvalve: # do not replace "self.output_valves[i]" with "x". It would be wrong!
if have:
del self.output_valves[i]
i -= 1
have = True
i += 1
class PIDTransposer(object):
def __init__(self, adder):
self.adder = adder
self.done = set()
def visit(self, inputs, outputs):
for valve in outputs:
if valve not in self.done:
self.done.add(valve)
pid, evid = valve.open
if pid >= 0:
pid = (pid & ~PLAYERS_MASK) + ((pid + self.adder) & PLAYERS_MASK)
valve.open = (pid, valve.open[1])
valve.closed = (pid, valve.closed[1])
class MenuControlsEnabled(object):
def __init__(self, onoff):
self.onoff = onoff
def visit(self, inputs, outputs):
for valve in outputs:
if valve.open[0] < 0:
valve.enabled = self.onoff
class PlumbingStringer(object):
'''
Used with EventPlumbing.visit() to produce a string representation of
the whole EventPlumbing. The result is found in the lines attribute.
'''
def __init__(self, is_keyboard):
self.lines = []
self.is_keyboard = is_keyboard
def visit(self, inputs, outputs):
input_strings = []
for i in inputs:
if i >= MAX_BUTTONS and not self.is_keyboard:
input_strings.append(chr(ord('A')+(i-MAX_BUTTONS)/3) + ('-','0','+')[(i-MAX_BUTTONS)%3])
else:
input_strings.append(str(i))
output_strings = []
for valve in outputs:
pid,evid = valve.open
if pid > 0: pid = pid & PLAYERS_MASK
if evid != PASS:
if valve.enabled:
output_strings.append(valvenames[(pid,evid)])
else:
output_strings.append('!'+valvenames[(pid,evid)])
if len(output_strings) > 0 and len(input_strings) > 0:
self.lines.append("%s = %s" % (" ".join(input_strings), " ".join(output_strings)))
class EventPlumbing(object):
def __init__(self, container, blueprint):
'''
An EventPlumbing is a network of EventForkValves and EventValves. The entry point to
the network are pipes with numeric indexes. Each index may have zero or more valves
attached. These indexes correspond to actual buttons or keys or virtual buttons derived
from controller axis states. Pressure for each index is controlled via the plus() and minus()
methods. The pressure is passed on to the connected valves, causing them to open/close and
finally producing event tuples (pid, evid) that are appended to a buffer.
This constructor takes the endpoint valves from the ui.valves dict, so they determine
which buffer events get appended to (usually ui.event_buffer).
ATTENTION! An EventPlumbing constructed with this constructor should usually not be used
directly. You need to clone() it first. Otherwise you would be pumping pressure into the
valves from ui.valves which are shared with other EventPlumbings.
container must be able to map ints to objects by use of "[]". If the container can not accept
all indexes right away, it must support an append() method and len().
Normally you would use
{} if the number of possible indexes is unreasonably high for a list.
[] if the maximum index is reasonable.
blueprint is the text representation of the plumbing. Syntax is as follows:
<input1> ... = <output1> ...
<input2> ... = <output2> ...
...
where each <input> may be one of
<uint> a non-negative integer identifying a button on a controller or keyboard key
L-, L0 or L+ where "L" is any letter from A-Z. This is a virtual button corresponding
to an axis state. The axis number is L-'A' (i.e. 'A' is axis 0) and the state
is value < -.5 for '-', value > .5 for '+' and between -.5 and .5 for '0'.
So at all times an axis will cause exactly one of these virtual buttons to
appear pressed.
If multiple <input> appear on the same line, all of these buttons have to pressed at
the same time in order to produce an output.
If multiple <output> appear on the same line, all of these outputs will be produced at
the same time. This is exactly identical to having an individual line for each output with
the same <input>... list. The EventPlumbing constructor optimizes the network, so that it
does not matter which form you use.
'''
# This is set based on the number of buttons occuring and is used when converting an
# EventPlumbing to text. If is_keyboard == True, virtual button to axis name conversion is
# disabled.
self.is_keyboard = False
# The name of the file to save changes to this plumbing in.
self.filename = None
# First line to output when saving to self.filename. Usually "[Controller Name]".
self.header = ""
# True => If this plumbing contains menuing events (e.g. CANCEL), disable them
# when clone() is used to create a copy if this plumbing.
self.menuing_disabled = False
self.container = container
for line in blueprint.splitlines():
line = line.strip().upper()
if line == "": continue
input,unused,output = line.partition("=")
if output == "":
raise SyntaxError(_("Missing '=' or empty right side in \"%s\"") % (line,))
if input == "":
raise SyntaxError(_("Empty left side in \"%s\"") % (line,))
inputset = set()
for iword in input.split():
if iword.isdigit(): # button number
i = int(iword)
if i >= MAX_BUTTONS:
self.is_keyboard = True
inputset.add(i)
else: # virtual button derived from axis
i = ord(iword[0])
if len(iword) != 2 or iword[1] not in ('-','0','+') or i < ord("A") or i > ord("Z"):
raise SyntaxError(_("Invalid axis state descriptor: \"%s\"") % (iword,))
i = (i - ord("A")) * 3
if iword[1] == "0":
i += 1
elif iword[1] == "+":
i += 2
inputset.add(MAX_BUTTONS+i)
for oword in output.split():
if oword[0] == "!":
oword = oword[1:]
# At this time we support only disabling of menu commands, so if we see any disabled
# output even we simply assume that this is what's happening.
self.menuing_disabled = True
self.add(inputset, oword)
def add(self, inputs, valvename):
'''
Adds a connection from inputs to valves[valvename].
inputs may either be a single non-negative int or any iterable of
non-negative ints.
All of the buttons identified by inputs must be pressed simultaneously
to activate the valve.
Raises SyntaxError if valvename is not valid.
WARNING! This function must not be used on an EventPlumbing whose plus()/minus()
are being used. It must only be used on an EventPlumbing that will serve as a
template to be duplicated by using the clone() method.
NOTE! Optimizations are performed so that adding the same connection multiple
times does not bloat the network. Nor does the order of add() calls influence
the resulting network.
'''
try:
valve = valves[valvename]
except KeyError:
raise SyntaxError(_("Invalid event name \"%s\"") % (valvename,))
if hasattr(inputs, "__len__") and len(inputs) == 1:
inputs = list(inputs)[0]
if type(inputs) == int: # single button input => map directly to EventValve
try:
for v in self.container[inputs]:
if type(v) == EventValve and v.open == valve.open:
break # inputs -> valvename connection already exists
else:
raise KeyError
# no existing connection found => make a new one
except (KeyError,IndexError):
self._make_index_valid(inputs)
self.container[inputs].append(valve)
else: # multi-button input => need to use EventForkValve
try:
# convert the lists (of EventForkValves and EventValves) for all inputs into sets
l = [set(self.container[i]) for i in inputs]
# create the intersection of all these sets, i.e. the set of all EventForkValves and EventValves
# that are fed into by all of the inputs
for s in l[1:]:
l[0] &= s
# now check if the intersection contains an EventForkValve with exactly len(inputs) inputs
# (determined by checking start_pressure). If such an EFV is found, it follows that its
# inputs are exactly the indexes from inputs, no more, no less.
for v in l[0]:
if type(v) == EventForkValve and v.start_pressure == -len(inputs)+1:
# Append the target valve to the output list if its not already there.
if valve.open not in [o.open for o in v.output_valves]:
v.output_valves.append(valve)
break
else:
raise KeyError
# no existing connection found => make a new one
except (KeyError,IndexError):
for i in inputs:
self._make_index_valid(i)
fork = EventForkValve(-len(inputs)+1, [valve])
for i in inputs:
self.container[i].append(fork)
def plus(self, index):
try:
for fork in self.container[index]:
fork.plus()
except (KeyError,IndexError):
pass
def minus(self, index):
try:
for fork in self.container[index]:
fork.minus()
except (KeyError,IndexError):
pass
def reset(self):
'''
Resets all valves in the network to their starting pressure.
ATTENTION! Usually you would also want to clear the output buffer (ui.event_buffer)
when you call this function .
'''
try:
iter = iter(self.container.values())
except AttributeError:
iter = self.container
for lst in iter:
for x in lst:
x.reset()
def transpose_player(self, adder):
'''Adds adder to all EventValves' pid >=0 , wrapping around at MAX_PLAYERS.'''
self.visit(PIDTransposer(adder))
def menu_controls_enabled(self, onoff):
''' Enables (onoff=True) or disables (onoff=False) all EventValves with pid < 0. '''
self.menuing_disabled = True
self.visit(MenuControlsEnabled(onoff))
def clone(self):
'''
Creates an independent copy of this valve network. In particular it makes copies of the
output valves that have been taken directly from ui.valves by the constructor.
It is necessary to clone() an EventPlumbing before using its plus()/minus().
'''
c = deepcopy(self)
if self.menuing_disabled: c.menu_controls_enabled(False)
return c
def save_to_disk(self):
'''If this plumbing has a filename set and mainconfig["saveinput"], this plumbing is stored to disk.'''
if self.filename is not None and mainconfig["saveinput"]:
try:
with open(os.path.join(input_d_path, self.filename), "w") as f:
f.write(self.header)
f.write("\n")
f.write(repr(self))
except:
print(_("W: Unable to write input configuration file %s") % (self.filename,))
print(sys.exc_info()[1])
def visit(self, visitor):
'''
For every inputs => outputs connection, calls visitor.visit(input_list, output_list)
where input_list is a list of ints and output_list is a list of EventValves.
'''
state = {}
try:
iter = list(self.container.keys())
iter.sort()
except AttributeError:
iter = list(range(len(self.container)))
for idx in iter:
for x in self.container[idx]:
x.visit(idx, state, visitor)
def replace_valve(self, oldpidevid, newvalve):
'''
Every EventValve in this plumbing whose open value is oldpidevid will be replaced
with newvalve. Note that this means replacing the actual object pointer. The pressure
values of all replaced valves will be summed up and added to newvalve.
'''
try:
iter = list(self.container.keys())
except AttributeError:
iter = list(range(len(self.container)))
already_counted = set()
for idx in iter:
k = 0
have = False
while k < len(self.container[idx]):
x = self.container[idx][k]
if type(x) == EventValve:
if x.open == oldpidevid:
self.container[idx][k] = newvalve
if x not in already_counted:
newvalve.pressure += x.pressure
already_counted.add(x)
if self.container[idx][k] == newvalve: # DO NOT REPLACE "self.container[idx][k]" WITH "x". It would be wrong!
if have:
del self.container[idx][k]
k -= 1
have = True
else:
x.replace_valve(oldpidevid, newvalve, already_counted)
k += 1
def __repr__(self):
pbs = PlumbingStringer(self.is_keyboard)
self.visit(pbs)
return "\n".join(pbs.lines)
def _make_index_valid(self, idx):
if hasattr(self.container,"append"): # container is a list or similar
# make sure index idx is valid
while len(self.container) <= idx: self.container.append([])
else: # container is a dict or similar
self.container.setdefault(idx,[])
# The numbers are the .key property of the pygame.event.
# The event names are those from the valves dict (defined further above).
default_keyboard_plumbing = EventPlumbing([], '''
13 = CONFIRM
271 = CONFIRM
9 = RANDOM
282 = OPTIONS
292 = FULLSCREEN
263 = P1_UPLEFT
265 = P1_UPRIGHT
261 = P1_CENTER
257 = P1_DOWNLEFT
259 = P1_DOWNRIGHT
260 = LEFT P1_LEFT
276 = LEFT P1_LEFT
262 = RIGHT P1_RIGHT
275 = RIGHT P1_RIGHT
258 = DOWN P1_DOWN
274 = DOWN P1_DOWN
264 = UP P1_UP
273 = UP P1_UP
8 = CANCEL
27 = CANCEL
280 = PGUP
281 = PGDN
305 113 = QUIT
305 120 = QUIT
306 113 = QUIT
306 120 = QUIT
308 113 = QUIT
308 120 = QUIT
313 113 = QUIT
313 120 = QUIT
316 = SCREENSHOT
277 = SORT
''')
# Most gamepads seem to have Start on a button >=6 (based on https://raw.githubusercontent.com/gabomdq/SDL_GameControllerDB/master/gamecontrollerdb.txt).
# with an odd number (1st place 9, 2nd place 7, 3rd place 11). We default all odd numbered
# buttons >6 to OPTIONS and the rest to CANCEL. Because OPTIONS works as CONFIRM in most places
# this allows players to navigate the game without button mappings right away.
default_controller_plumbing = EventPlumbing([], '''
A- = LEFT P1_LEFT
A+ = RIGHT P1_RIGHT
B- = UP P1_UP
B+ = DOWN P1_DOWN
0 = P1_BUTTON_0
1 = P1_BUTTON_1
2 = P1_BUTTON_2
3 = P1_BUTTON_3
4 = P1_BUTTON_4
5 = P1_BUTTON_5
6 = CANCEL
7 = OPTIONS
8 = CANCEL
9 = OPTIONS
10 = CANCEL
11 = OPTIONS
12 = CANCEL
13 = OPTIONS
14 = CANCEL
15 = OPTIONS
16 = CANCEL
17 = OPTIONS
18 = CANCEL
19 = OPTIONS
20 = CANCEL
21 = OPTIONS
22 = CANCEL
23 = OPTIONS
24 = CANCEL
25 = OPTIONS
26 = CANCEL
27 = OPTIONS
28 = CANCEL
29 = OPTIONS
30 = CANCEL
31 = OPTIONS
''')
# Maps a pygame.joystick.Joystick.get_name() to a list L of EventPlumbing objects, where
# L[i] is the plumbing to be used for the i-th controller of that name attached to the
# system. Some L[i] may be None. In that case the plumbing will be derived through transposition.
plumbing_templates = {}
def read_plumbing_templates():
if os.path.exists(input_d_path):
try:
lst = os.listdir(input_d_path)
lst.sort()
except OSError:
lst = []
for fn in lst:
if fn.endswith(".cfg"):
try:
inp = open(os.path.join(input_d_path,fn), "rU").read(-1)
start = inp.find("[")
if start < 0: raise SyntaxError(_("'[' not found"))
end = inp.find("]", start)
if end < 0: raise SyntaxError(_("']' not found"))
controller_name = inp[start+1:end].strip()
hash = controller_name.rfind("#")
controller_index = 0
if hash > 0 and controller_name[hash+1:].isdigit():
controller_index = int(controller_name[hash+1:])
controller_name = controller_name[:hash].strip()
pb = EventPlumbing([], inp[end+1:])
print((_("Loaded %s") % (fn,)))
pb.filename = fn
if controller_index > 0:
pb.header = "[%s #%d]" % (controller_name, controller_index)
else:
pb.header = "[%s]" % (controller_name,)
pbtlst = plumbing_templates.setdefault(controller_name,[])
while controller_index >= len(pbtlst):
pbtlst.append(None)
pbtlst[controller_index] = pb
except:
print(_("W: Unable to load input configuration file %s") % (fn,))
print(sys.exc_info()[1])
def get_plumbing(name, idx):
if name in plumbing_templates:
lst = plumbing_templates[name]
i = idx
while i > 0 and (i >= len(lst) or lst[i] is None): i -= 1
if lst[i] is None: # implies i == 0
i = idx
while lst[i] is None: i += 1
pb = lst[i].clone()
if i != idx:
print((_("Transposing %s to get mapping for %s #%d") % (pb.header, name, idx)))
pb.transpose_player(idx - i)
pb.menu_controls_enabled(False) # don't want player 2 to control menu
assert pb.filename.endswith(".cfg")
pb.filename = pb.filename[:-4]
underscore = pb.filename.rfind("_")
if underscore >= 0:
pb.filename = pb.filename[:underscore]
if idx != 0:
pb.filename += "_%d" % (idx,)
pb.filename += ".cfg"
if pb.filename[0:2].isdigit() and pb.filename[2] == "-":
pb.filename = pb.filename[3:]
pb.filename = "10-" + pb.filename
hash = pb.header.rfind("#")
if hash < 0:
hash = len(pb.header)-1 # point to "]"
pb.header = pb.header[:hash] + (" #%d]" % (idx,) )
else:
print((_("Using mapping for %s #%d") % (name, idx)))
else:
if name == "keyboard":
pb = default_keyboard_plumbing.clone()
pb.filename = "10-keyboard.cfg"
pb.header = "[keyboard]"
else:
print((_("Using default mapping for %s #%d") % (name, idx)))
pb = default_controller_plumbing.clone()
pb.filename = "10-" + "".join(ch.lower() for ch in name if ch.isalnum())
pb.header = "[" + name
if idx > 0:
pb.filename += "_%d" % (idx,)
pb.header += " #%d" % (idx,)
pb.transpose_player(idx)
pb.menu_controls_enabled(False) # don't want player 2 to control menu
pb.filename += ".cfg"
pb.header += "]"
return pb
class GenericButtonsFixup(object):
'''
Embeds joy << GENERIC_BUTTON_SHIFTER in the pid of every EventValve's output event that refers to a
event id >= GENERIC_BUTTON.
'''
def __init__(self, joy):
self.fixup = joy << GENERIC_BUTTON_SHIFTER
def visit(self, inputs, outputs):
for valve in outputs:
if valve.open[1] >= GENERIC_BUTTON:
valve.open = ((valve.open[0] & PLAYERS_MASK)+self.fixup, valve.open[1])
valve.closed = ((valve.closed[0] & PLAYERS_MASK)+self.fixup, valve.closed[1])
class ReplaceEvent(object):
def __init__(self, oldpidevid, pid, evid):
self.oldpidevid = oldpidevid
self.pid = pid
self.evid = evid
def visit(self, inputs, outputs):
for valve in outputs:
if valve.open == self.oldpidevid:
valve.open = (self.pid, self.evid)
valve.closed = (self.pid, -self.evid)
class DisableEvent(object):
def __init__(self, pid, evid):
self.pidevid = (pid, evid)
def visit(self, inputs, outputs):
for valve in outputs:
if valve.open == self.pidevid:
valve.enabled = False
class RepeatEvent(object):
def __init__(self):
self.already_done = set()
def visit(self, inputs, outputs):
for valve in outputs:
if valve.pressure > 0 and valve.open in REPEATABLE and valve not in self.already_done:
valve.evlist.append(valve.open)
self.already_done.add(valve)
class CountOpenValves(object):
def __init__(self):
self.already_done = set()
self.count = 0
def visit(self, inputs, outputs):
for valve in outputs:
if valve not in self.already_done:
self.already_done.add(valve)
if valve.pressure > 0:
self.count += 1
class FindEvent(object):
def __init__(self, pid, evid):
self.valve = None
self.ev = (pid,evid)
def visit(self, inputs, outputs):
for valve in outputs:
if valve.open == self.ev:
self.valve = valve
break
class DebugValves(object):
def visit(self, inputs, outputs):
for valve in outputs:
if valve.pressure != valve.start_pressure:
print(("%s %s" % (id(valve),valve.__dict__)))
class Controller(object):
def __init__(self, pygame):
self.pygame = pygame
self.plumbing = None
self.num_hats = pygame.get_numhats()
self.button_state = [False] * MAX_BUTTONS
self.num_pressed = 0 # number of buttons currently in pressed state
# axis_state is a list of N booleans corresponding to the virtual buttons derived from
# the axes. The list always starts with states derived from hats. Each
# hat generates 6 axis states: x < 0, x == 0, x > 0, y < 0, y == 0, y > 0
# This is followed by the axis states for the analog axes. Each analog axis generates
# 3 axis states: a < -.5, a in [-.5,.5], a > .5
self.axis_state = []
for h in range(self.num_hats):
self.axis_state.extend((False,False,False,False,False,False))
for a in range(pygame.get_numaxes()):
self.axis_state.extend((False,False,False))
# Used for learning the relationship (if any) of generic buttons with directional axes.
# for button >= GENERIC_BUTTON: generic_buttons[button] = [total, left, right, up, down]
# where
# total is the total number of times this button has been seen in the event_buffer
# up is the number of times (pid, UP) was seen at the same time in the event_buffer
# ditto for left,right,down
self.generic_buttons = {}
def pressed(self, button):
if not self.button_state[button]:
self.button_state[button] = True
self.plumbing.plus(button)
self.num_pressed += 1
def released(self, button):
if self.button_state[button]:
self.button_state[button] = False
self.plumbing.minus(button)
self.num_pressed -= 1
def reset(self):
for i in range(len(self.button_state)):
self.button_state[i] = False
for i in range(len(self.axis_state)):
self.axis_state[i] = False
self.generic_buttons = {}
self.num_pressed = 0
class UI(object):
'''
Receives raw user input from pygame.event and translates
it into higher level semantic events used by pydance. The translation is highly
configurable and permits things such as translating 2 simultaneous button presses
into a ui.SCREENSHOT event. See EventPlumbing.
'''
def __init__(self, ebuf = event_buffer):
# list of lists of pygame.event.Event objects, one for each call of pump().
self.pygame_events = deque()
# sum of the lengths of all lists in pygame_events.
self.pygame_events_count = 0
# stores tuples (pid, evid) or (pid, -evid) for button presses/releases.
# Used as FIFO. EventValves append data. poll() and poll_dance() remove it.
self.event_buffer = ebuf
# this logs the last time an output even was produced in pump()
self.last_valve_change_time = pygame.time.get_ticks()
# this logs the last time, a non-empty event list was received from pygame
self.last_pygame_events_time = pygame.time.get_ticks()
# this is the earliest time at which poll() will trigger an auto-repeat.
self.next_repeat_time = pygame.time.get_ticks()
# the pressed/released state of every keyboard key by pygame.Event.key number.
self.key_state = [False] * 512
# the EventPlumbing used for keyboard inputs.
self.keyboard_plumbing = get_plumbing("keyboard", 0)
# list of Controller objects. Array index matches pygame's joystick id.
self.controllers = []
# controller_names[i] is controllers[i].pygame.get_name()
self.controller_names = []
# Used by _can_skip_init_controllers()
self._init_controllers_state = {}