forked from hlorus/CAD_Sketcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperators.py
2882 lines (2257 loc) · 86.3 KB
/
operators.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
############### Operators ###############
import bpy, bgl, gpu
from gpu_extras.batch import batch_for_shader
from bpy.types import Operator
from . import global_data, functions, class_defines, convertors
from bpy.props import (
IntProperty,
StringProperty,
FloatProperty,
FloatVectorProperty,
EnumProperty,
BoolProperty,
)
import math
from mathutils import Vector, Matrix
from mathutils.geometry import intersect_line_plane, distance_point_to_plane
import functools
import logging
logger = logging.getLogger(__name__)
def draw_selection_buffer(context):
# Draw elements offscreen
region = context.region
# create offscreen
width, height = region.width, region.height
offscreen = global_data.offscreen = gpu.types.GPUOffScreen(width, height)
with offscreen.bind():
bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
bgl.glClear(bgl.GL_COLOR_BUFFER_BIT)
entities = list(context.scene.sketcher.entities.all)
for e in reversed(entities):
if e.slvs_index in global_data.ignore_list:
continue
if not hasattr(e, "draw_id"):
continue
e.draw_id(context)
def ensure_selection_texture(context):
if not global_data.redraw_selection_buffer:
return
draw_selection_buffer(context)
global_data.redraw_selection_buffer = False
# TODO: Avoid to always update batches and selection texture
def update_elements(context, force=False):
entities = list(context.scene.sketcher.entities.all)
msg = ""
for e in reversed(entities):
if not hasattr(e, "update"):
continue
if not force and not e.is_dirty:
continue
msg += "\n - " + str(e) + str(e.is_dirty)
e.update()
if msg:
logger.debug("Update geometry batches:" + msg)
def draw_elements(context):
for e in context.scene.sketcher.entities.all:
if hasattr(e, "draw"):
e.draw(context)
def draw_cb():
context = bpy.context
prefs = functions.get_prefs()
update_elements(context, force=prefs.force_redraw)
draw_elements(context)
global_data.redraw_selection_buffer = True
class HighlightElement:
"""
Mix-in class to highlight the element this operator acts on. The element can
either be an entity or a constraint. The element has to be specified by an index
property for entities and additionaly with a type property for constraints.
index: IntProperty
type: StringProperty
Note that this defines the invoke and description functions, an operator that
defines one of those has to manually make a call to either of the following:
self.handle_highlight_active(context) -> from invoke()
cls.handle_highlight_hover(context, properties) -> from description()
Settings:
highlight_hover -> highlights the element as soon as the tooltip is shown
highlight_active -> highlights the element when the operator is invoked
"""
highlight_hover: BoolProperty(name="Highlight Hover")
highlight_active: BoolProperty(name="Highlight Hover")
@classmethod
def _do_highlight(cls, context, properties):
if not properties.is_property_set("index"):
return cls.__doc__
if hasattr(properties, "type") and properties.is_property_set("type"):
c = context.scene.sketcher.constraints.get_from_type_index(properties.type, properties.index)
global_data.highlight_constraint = c
else:
global_data.hover = properties.index
context.area.tag_redraw()
return cls.__doc__
def handle_highlight_active(self, context):
properties = self.properties
if properties.highlight_active:
self._do_highlight(context, properties)
@classmethod
def handle_highlight_hover(cls, context, properties):
if properties.highlight_hover:
cls._do_highlight(context, properties)
@classmethod
def description(cls, context, properties):
cls.handle_highlight_hover(context, properties)
def invoke(self, context, event):
self.handle_highlight_active(context)
return self.execute(context)
class View3D_OT_slvs_register_draw_cb(Operator):
bl_idname = "view3d.slvs_register_draw_cb"
bl_label = "Register Draw Callback"
def execute(self, context):
global_data.draw_handle = bpy.types.SpaceView3D.draw_handler_add(
draw_cb, (), "WINDOW", "POST_VIEW"
)
return {"FINISHED"}
class View3D_OT_slvs_unregister_draw_cb(Operator):
bl_idname = "view3d.slvs_unregister_draw_cb"
bl_label = ""
def execute(self, context):
global_data.draw_handler.remove_handle()
return {"FINISHED"}
def deselect_all(context):
global_data.selected.clear()
def entities_3d(context):
for e in context.scene.sketcher.entities.all:
if hasattr(e, "sketch"):
continue
yield e
def select_all(context):
sketch = context.scene.sketcher.active_sketch
if sketch:
generator = sketch.sketch_entities(context)
else:
generator = entities_3d(context)
for e in generator:
if e.selected:
continue
if not e.is_visible(context):
continue
if not e.is_active(context.scene.sketcher.active_sketch):
continue
e.selected = True
class View3D_OT_slvs_select(Operator, HighlightElement):
"""
Select an entity
Either the entity specified by the index property or the hovered index
if the index property is not set
"""
bl_idname = "view3d.slvs_select"
bl_label = "Select Solvespace Entities"
index: IntProperty(name="Index", default=-1)
# TODO: Add selection modes
@classmethod
def poll(cls, context):
return True
def execute(self, context):
index = self.index if self.properties.is_property_set("index") else global_data.hover
if index != -1:
entity = context.scene.sketcher.entities.get(index)
entity.selected = not entity.selected
else:
deselect_all(context)
context.area.tag_redraw()
return {"FINISHED"}
class View3D_OT_slvs_select_all(Operator):
"""Select / Deselect all entities"""
bl_idname = "view3d.slvs_select_all"
bl_label = "Select / Deselect Entities"
deselect: BoolProperty(name="Deselect")
def execute(self, context):
if self.deselect:
deselect_all(context)
else:
select_all(context)
context.area.tag_redraw()
return {"FINISHED"}
class View3D_OT_slvs_context_menu(Operator, HighlightElement):
"""Show element's settings"""
bl_idname = "view3d.slvs_context_menu"
bl_label = "Solvespace Context Menu"
type: StringProperty(name="Type", options={'SKIP_SAVE'})
index: IntProperty(name="Index", default=-1, options={'SKIP_SAVE'})
@classmethod
def poll(cls, context):
return True
def execute(self, context):
is_entity = True
entity_index = None
constraint_index = None
element = None
# Constraints
if self.properties.is_property_set("type"):
constraint_index = self.index
constraints = context.scene.sketcher.constraints
element = constraints.get_from_type_index(self.type, self.index)
is_entity = False
else:
# Entities
entity_index = self.index if self.properties.is_property_set("index") else global_data.hover
if entity_index != -1:
element = context.scene.sketcher.entities.get(entity_index)
def draw_context_menu(self, context):
col = self.layout.column()
if not element:
col.label(text="Nothing hovered")
return
col.label(text="Type: " + type(element).__name__)
if is_entity:
if functions.get_prefs().show_debug_settings:
col.label(text="Index: " + str(element.slvs_index))
col.label(text="Is Origin: " + str(element.origin))
col.separator()
col.prop(element, "visible")
col.prop(element, "fixed")
col.prop(element, "construction")
elif element.failed:
col.label(text="Failed", icon="ERROR")
col.separator()
if hasattr(element, "draw_props"):
element.draw_props(col)
col.separator()
# Delete operator
if is_entity:
col.operator(View3D_OT_slvs_delete_entity.bl_idname, icon='X').index = element.slvs_index
else:
props = col.operator(View3D_OT_slvs_delete_constraint.bl_idname, icon='X')
props.type = element.type
props.index = constraint_index
context.window_manager.popup_menu(draw_context_menu)
return {"FINISHED"}
class View3D_OT_slvs_show_solver_state(Operator):
"""Show details about solver status"""
bl_idname = "view3d.slvs_show_solver_state"
bl_label = "Solver Status"
index: IntProperty(default=-1)
@classmethod
def poll(cls, context):
return True
def execute(self, context):
index = self.index
if index == -1:
return {"CANCELLED"}
def draw_item(self, context):
layout = self.layout
sketch = context.scene.sketcher.entities.get(index)
state = sketch.get_solver_state()
row = layout.row(align=True)
row.alignment = "LEFT"
row.label(text=state.name, icon=state.icon)
layout.separator()
layout.label(text=state.description)
context.window_manager.popup_menu(draw_item)
return {"FINISHED"}
from .solver import Solver, solve_system
class View3D_OT_slvs_solve(Operator):
bl_idname = "view3d.slvs_solve"
bl_label = "Solve"
all: BoolProperty(name="Solve All", options={"SKIP_SAVE"})
def execute(self, context):
sketch = context.scene.sketcher.active_sketch
solver = Solver(context, sketch, all=self.all)
ok = solver.solve()
# Keep messages simple, sketches are marked with solvestate
if ok:
self.report({"INFO"}, "Successfully solved")
else:
self.report({"WARNING"}, "Solver failed")
context.area.tag_redraw()
return {"FINISHED"}
def add_point(context, pos, name=""):
data = bpy.data
ob = data.objects.new(name, None)
ob.location = pos
context.collection.objects.link(ob)
return ob
class View3D_OT_slvs_tweak(Operator):
"""Tweak the hovered element"""
bl_idname = "view3d.slvs_tweak"
bl_label = "Tweak Solvespace Entities"
bl_options = {"UNDO"}
@classmethod
def poll(cls, context):
return True
def invoke(self, context, event):
index = global_data.hover
# TODO: hover should be -1 if nothing is hovered, not None!
if index == None or index == -1:
return {"CANCELLED"}
entity = context.scene.sketcher.entities.get(index)
self.entity = entity
coords = (event.mouse_region_x, event.mouse_region_y)
origin, view_vector = functions.get_picking_origin_dir(context, coords)
if not hasattr(entity, "closest_picking_point"):
if not hasattr(entity, "sketch"):
self.report(
{"WARNING"}, "Cannot tweak element of type {}".format(type(entity))
)
return {"CANCELLED"}
# For 2D entities it should be enough precise to get picking point from intersection with workplane
wp = entity.sketch.wp
coords = (event.mouse_region_x, event.mouse_region_y)
origin, dir = functions.get_picking_origin_dir(context, coords)
end_point = dir * context.space_data.clip_end + origin
pos = intersect_line_plane(origin, end_point, wp.p1.location, wp.normal)
else:
pos = entity.closest_picking_point(origin, view_vector)
# find the depth
self.depth = (pos - origin).length
context.window_manager.modal_handler_add(self)
return {"RUNNING_MODAL"}
def modal(self, context, event):
if event.type == "LEFTMOUSE" and event.value == "RELEASE":
context.window.cursor_modal_restore()
return {"FINISHED"}
context.window.cursor_modal_set("HAND")
if event.type == "MOUSEMOVE":
entity = self.entity
coords = (event.mouse_region_x, event.mouse_region_y)
# Get tweaking position
origin, dir = functions.get_picking_origin_dir(context, coords)
if hasattr(entity, "sketch"):
wp = entity.wp
end_point = dir * context.space_data.clip_end + origin
pos = intersect_line_plane(origin, end_point, wp.p1.location, wp.normal)
else:
pos = dir * self.depth + origin
sketch = context.scene.sketcher.active_sketch
solver = Solver(context, sketch)
solver.tweak(entity, pos)
retval = solver.solve(report=False)
# NOTE: There's no blocking cursor
# also solving frequently returns an error while tweaking which causes flickering
# if retval != 0:
# context.window.cursor_modal_set("WAIT")
# self.report({'WARNING'}, "Cannot solve sketch, error: {}".format(retval))
context.area.tag_redraw()
return {"RUNNING_MODAL"}
def write_selection_buffer_image(image_name):
offscreen = global_data.offscreen
width, height = offscreen.width, offscreen.height
buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4)
with offscreen.bind():
bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer)
if not image_name in bpy.data.images:
bpy.data.images.new(image_name, width, height)
image = bpy.data.images[image_name]
image.scale(width, height)
image.pixels = buffer
return image
class VIEW3D_OT_slvs_write_selection_texture(Operator):
"""Write selection texture to image for debuging"""
bl_idname = "view3d.slvs_write_selection_texture"
bl_label = "Write selection texture"
def execute(self, context):
if context.area.type != "VIEW_3D":
self.report({"WARNING"}, "View3D not found, cannot run operator")
return {"CANCELLED"}
if not global_data.offscreen:
self.report({'WARNING'}, "Selection texture is not available")
return {'CANCELLED'}
image = write_selection_buffer_image("selection_buffer")
self.report({"INFO"}, "Wrote buffer to image: {}".format(image.name))
return {"FINISHED"}
# NOTE: The draw handler has to be registered before this has any effect, currently it's possible that
# entities are first created with an entity that was hovered in the previous state
# Not sure if it's possible to force draw handlers...
# Also note that a running modal operator might prevent redraws, avoid returning running_modal
def ignore_hover(entity):
ignore_list = global_data.ignore_list
ignore_list.append(entity.slvs_index)
# TODO: could probably check entity type only through index, instead of getting the entity first...
def get_hovered(context, *types):
hovered = global_data.hover
entity = None
if hovered != -1:
entity = context.scene.sketcher.entities.get(hovered)
if type(entity) in types:
return entity
return None
def format_types(types):
entity_names = ", ".join([e.__name__ for e in types])
return "[" + entity_names + "]"
def state_desc(name, desc, types):
type_desc = ""
if types:
type_desc = "Types: " + format_types(types)
return " ".join((name + ":", desc, type_desc))
def stateful_op_desc(base, *state_descs):
states = ""
length = len(state_descs)
for i, state in enumerate(state_descs):
states += " - {}{}".format(
state, (" \n" if i < length - 1 else "")
)
desc = "{} \n \nStates: \n{}".format(base, states)
return desc
numeric_events = (
"ZERO",
"ONE",
"TWO",
"THREE",
"FOUR",
"FIVE",
"SIX",
"SEVEN",
"EIGHT",
"NINE",
"PERIOD",
"NUMPAD_0",
"NUMPAD_1",
"NUMPAD_2",
"NUMPAD_3",
"NUMPAD_4",
"NUMPAD_5",
"NUMPAD_6",
"NUMPAD_7",
"NUMPAD_8",
"NUMPAD_9",
"NUMPAD_PERIOD",
"MINUS",
"NUMPAD_MINUS",
)
class StatefulOperator:
state_index: IntProperty(options={"HIDDEN", "SKIP_SAVE"})
wait_for_input: BoolProperty(options={"HIDDEN", "SKIP_SAVE"}, default=True)
continuose_draw: BoolProperty(name="Continuose Draw", default=False)
executed = False
_state_data = {}
_last_coords = Vector((0, 0))
_numeric_input = {}
@property
def state(self):
return self.states[self.state_index]
def _index_from_state(self, state):
return [e.name for e in self.states].index(state)
@state.setter
def state(self, state):
self.state_index = self._index_from_state(state)
def set_state(self, context, index):
self.state_index = index
self.init_numeric(False)
self.init_substate()
self.set_status_text(context)
def next_state(self, context):
i = self.state_index
if (i + 1) >= len(self.states):
return False
self.set_state(context, i + 1)
return True
def set_status_text(self, context):
# Setup state
state = self.state
desc = (
state.description(self, state)
if callable(state.description)
else state.description
)
msg = state_desc(state.name, desc, state.types)
if self.state_data.get("is_numeric_edit", False):
index = self._substate_index
prop = self._stateprop
type = prop.type
array_length = prop.array_length if prop.array_length else 1
if type == "FLOAT":
input = [0.0] * array_length
for key, val in self._numeric_input.items():
input[key] = val
input[index] = "*" + str(input[index])
input = str(input).replace('"', "").replace("'", "")
elif type == "INT":
input = self.numeric_input
msg += " {}: {}".format(prop.subtype, input)
context.workspace.status_text_set(msg)
def init_numeric(self, is_numeric):
self._numeric_input = {}
# TODO: not when iterating substates
self.state_data["is_numeric_edit"] = is_numeric
self._substate_index = 0
def init_substate(self):
prop_name = self.state.property
if prop_name:
prop = self.properties.rna_type.properties[prop_name]
self._substate_count = prop.array_length
self._stateprop = prop
else:
self._substate_count = None
self._stateprop = None
def iterate_substate(self):
i = self._substate_index
if i + 1 >= self._substate_count:
i = 0
else:
i += 1
self._substate_index = i
@property
def numeric_input(self):
return self._numeric_input.get(self._substate_index, "")
@numeric_input.setter
def numeric_input(self, value):
self._numeric_input[self._substate_index] = value
def check_event(self, event):
state = self.state
if (
event.type in ("LEFTMOUSE", "RET", "NUMPAD_ENTER")
and event.value == "PRESS"
):
return True
if self.state_index == 0 and not self.wait_for_input:
# Trigger the first state
return not self.state_data.get("is_numeric_edit", False)
if state.no_event:
return True
return False
@staticmethod
def is_numeric_input(event):
return event.type in (*numeric_events, "BACK_SPACE")
@staticmethod
def is_unit_input(event):
return event.type in (
"M",
"K",
"D",
"C",
"U",
"A",
"H",
"I",
"L",
"N",
"F",
"T",
"Y",
"U",
"R",
"E",
"G",
)
@staticmethod
def get_unit_value(event):
type = event.type
return type.lower()
@staticmethod
def get_value_from_event(event):
type = event.type
if type in ("ZERO", "NUMPAD_0"):
return "0"
if type in ("ONE", "NUMPAD_1"):
return "1"
if type in ("TWO", "NUMPAD_2"):
return "2"
if type in ("THREE", "NUMPAD_3"):
return "3"
if type in ("FOUR", "NUMPAD_4"):
return "4"
if type in ("FIVE", "NUMPAD_5"):
return "5"
if type in ("SIX", "NUMPAD_6"):
return "6"
if type in ("SEVEN", "NUMPAD_7"):
return "7"
if type in ("EIGHT", "NUMPAD_8"):
return "8"
if type in ("NINE", "NUMPAD_9"):
return "9"
if type in ("PERIOD", "NUMPAD_PERIOD"):
return "."
def evaluate_numeric_event(self, event):
type = event.type
if type == "BACK_SPACE":
input = self.numeric_input
if len(input):
self.numeric_input = input[:-1]
elif type in ("MINUS", "NUMPAD_MINUS"):
input = self.numeric_input
if input.startswith("-"):
input = input[1:]
else:
input = "-" + input
self.numeric_input = input
elif self.is_unit_input(event):
self.numeric_input += self.get_unit_value(event)
else:
self.numeric_input += self.get_value_from_event(event)
def is_in_previous_states(self, entity):
i = self.state_index - 1
while True:
if i < 0:
break
state = self.states[i]
if state.pointer and entity == getattr(self, state.pointer):
return True
i -= 1
return False
def prefill_state_props(self, context):
func = self.state.parse_selection
selected = context.scene.sketcher.entities.selected_entities
# Iterate states and try to prefill state props
while True:
result = None
state = self.state
coords = None
if not state.allow_prefill:
break
elif func: # Allow overwritting
result = func(self, selected)
elif state.pointer:
# TODO: Discard if too many entities are selected?
types = state.types
for i, e in enumerate(selected):
if type(e) in types:
result = selected.pop(i)
break
if result:
setattr(self, state.pointer, result)
self.state_data["is_existing_entity"] = True
if not self.next_state(context):
return {"FINISHED"}
continue
break
return {"RUNNING_MODAL"}
@property
def state_data(self):
return self._state_data.setdefault(self.state_index, {})
def get_func(self, state, name):
# fallback to operator method if function isn't specified by state
func = getattr(state, name, None)
if func:
return func
if hasattr(self, name):
return getattr(self, name)
return None
def invoke(self, context, event):
self._state_data.clear()
if hasattr(self, "init"):
self.init(context, event)
retval = {"RUNNING_MODAL"}
go_modal = True
if self.is_numeric_input(event):
self.init_numeric(True)
self.init_substate()
self.evaluate_numeric_event(event)
retval = {"RUNNING_MODAL"}
self.evaluate_state(context, event, False)
# NOTE: This allows to start the operator but waits for action (LMB event).
# Try to fill states based on selection only when this is True since it doesn't
# make senese to respect selection when the user interactivley starts the operator.
elif self.wait_for_input:
retval = self.prefill_state_props(context)
if retval == {"FINISHED"}:
go_modal = False
# NOTE: It might make sense to cancle Operator if no prop could be filled
# Otherwise it might not be obvious that an operator is running
# if self.state_index == 0:
# return self._end(context, False)
if not self.executed and self.check_props():
self.run_op(context)
self.executed = True
context.area.tag_redraw() # doesnt seem to work...
self.set_status_text(context)
if go_modal:
context.window_manager.modal_handler_add(self)
return retval
succeede = retval == {"FINISHED"}
if succeede:
# NOTE: It seems like there's no undo step pushed if an operator finishes from invoke
# could push an undo_step here however this causes duplicated constraints after redo,
# disable for now
# bpy.ops.ed.undo_push()
pass
return self._end(context, succeede)
def run_op(self, context):
if not hasattr(self, "main"):
raise NotImplementedError(
"StatefulOperators need to have a main method defined!"
)
retval = self.main(context)
self.executed = True
return retval
# Creates non-persistent data
def redo_states(self, context):
for i, state in enumerate(self.states):
if i > self.state_index:
# TODO: don't depend on active state, idealy it's possible to go back
break
if state.pointer:
state_data = self._state_data.get(i, {})
is_existing_entity = state_data["is_existing_entity"]
if state.property and not is_existing_entity:
state = self.states[i]
data = self._state_data.get(i, {})
create = self.get_func(state, "create_element")
entity = create(context, getattr(self, state.property), state, data)
setattr(self, state.pointer, entity)
def execute(self, context):
self.redo_states(context)
ok = self.main(context)
return self._end(context, ok)
# maybe allow to be modal again?
def get_numeric_value(self, context, coords):
state = self.state
prop_name = state.property
prop = self.properties.rna_type.properties[prop_name]
def parse_input(prop, input):
units = context.scene.unit_settings
unit = prop.unit
type = prop.type
if unit != "NONE":
try:
value = bpy.utils.units.to_value(units.system, unit, input)
except ValueError:
return prop.default
if type == "INT":
value = int(value)
elif type == "FLOAT":
value = float(input)
elif type == "INT":
value = int(input)
else:
value = prop.default
return value
size = max(1, self._substate_count)
def to_list(val):
if hasattr(val, "__getitem__"):
return list(val)
return [val,]
# TODO: Don't evaluate if not needed
position_cb = self.get_func(state, "state_func")
interactive_val = to_list(position_cb(context, coords))
storage = [None] * size
result = [None] * size
for sub_index in range(size):
num = None
input = self._numeric_input.get(sub_index)
if input:
num = parse_input(prop, input)
if num:
result[sub_index] = num
storage[sub_index] = num
else:
result[sub_index] = interactive_val[sub_index]
self.state_data["numeric_input"] = storage
if not self._substate_count:
return result[0]
return result
def modal(self, context, event):
state = self.state
event_triggered = self.check_event(event)
coords = Vector((event.mouse_region_x, event.mouse_region_y))
is_numeric_edit = self.state_data.get("is_numeric_edit", False)
is_numeric_event = event.value == "PRESS" and self.is_numeric_input(event)
if is_numeric_edit:
if self.is_unit_input(event) and event.value == "PRESS":
is_numeric_event = True
elif event.type == "TAB" and event.value == "PRESS":
self.iterate_substate()
self.set_status_text(context)
elif is_numeric_event:
# Initalize
self.init_numeric(True)
self.init_substate()
is_numeric_edit = True
if event.type in {"RIGHTMOUSE", "ESC"}:
return self._end(context, False)
# HACK: when calling ops.ed.undo() inside an operator a mousemove event
# is getting triggered. manually check if theres a mousemove...
mousemove_threshold = 0.1
is_mousemove = (coords - self._last_coords).length > mousemove_threshold
self._last_coords = coords
if not event_triggered:
if is_numeric_event:
pass
elif is_mousemove and is_numeric_edit:
event_triggered = False
pass
elif not state.interactive:
return {"PASS_THROUGH"}
elif not is_mousemove:
return {"PASS_THROUGH"}
# TODO: Disable numeric input when no state.property
if is_numeric_event:
self.evaluate_numeric_event(event)
self.set_status_text(context)
return self.evaluate_state(context, event, event_triggered)
def evaluate_state(self, context, event, triggered):
state = self.state
is_numeric = self.state_data.get("is_numeric_edit", False)
coords = Vector((event.mouse_region_x, event.mouse_region_y))
# Pick hovered element
hovered = None