-
Notifications
You must be signed in to change notification settings - Fork 3
/
panel.py
520 lines (424 loc) · 19.9 KB
/
panel.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
# copyright (c) 2018- polygoniq xyz s.r.o.
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import bpy
import enum
import math
import mathutils
import typing
import logging
import random
from . import mapr
from . import polib
from . import hatchery
from . import browser
from . import asset_registry
from . import preferences
from . import blend_maintenance
from . import convert_selection
logger = logging.getLogger(f"polygoniq.{__name__}")
class EngonPanelMixin:
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "polygoniq"
MODULE_CLASSES: typing.List[typing.Any] = []
@polib.log_helpers_bpy.logged_operator
class SnapToGround(bpy.types.Operator):
bl_idname = "engon.snap_to_ground_bpy"
bl_label = "Snap to Ground"
bl_description = "Put selected assets as close to the ground as possible"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT' and len(context.selected_objects) > 0
def execute(self, context):
# We have no way to know which objects are part of ground so we ray-cast all of them except
# what's selected. The objects that the user wants to snap to ground are the selected objects.
# Since we are going to be moving all of those we can't do self-collisions.
objects_to_snap = polib.asset_pack_bpy.filter_out_descendants_from_objects(
context.selected_objects
)
objects_to_snap_hierarchy = set()
for obj in objects_to_snap:
objects_to_snap_hierarchy.update(polib.asset_pack_bpy.get_hierarchy(obj))
ground_objects = [
obj
for obj in context.visible_objects
if obj.type == 'MESH' and obj not in objects_to_snap_hierarchy
]
if len(ground_objects) == 0:
logger.warning("Ground object not found")
self.report(
{'WARNING'},
"Ground object was not found, make sure there is "
"another object under the selected objects",
)
return {'FINISHED'}
snapped_objects_names = []
no_ground_object_names = []
wrong_type_object_names = []
for obj in objects_to_snap:
is_snapped = False
if polib.asset_pack_bpy.is_polygoniq_object(obj, lambda x: x == "traffiq"):
logger.info(f"Determined that {obj.name} is a traffiq asset.")
# if editable car is selected with all its child objects -> skip these child objects
if polib.asset_pack_bpy.is_traffiq_asset_part(
obj, polib.asset_pack_bpy.TraffiqAssetPart.Wheel
):
continue
if polib.asset_pack_bpy.is_traffiq_asset_part(
obj, polib.asset_pack_bpy.TraffiqAssetPart.Brake
):
continue
if polib.asset_pack_bpy.is_traffiq_asset_part(
obj, polib.asset_pack_bpy.TraffiqAssetPart.Lights
):
continue
root_object, body, lights, wheels, brakes = (
polib.asset_pack_bpy.decompose_traffiq_vehicle(obj)
)
if root_object is not None: # traffiq behavior
logger.debug(
f"Was able to decompose {obj.name} as if it was a traffiq vehicle. "
f"Snapping to ground using the traffiq behavior."
)
if len(wheels) > 0:
logger.info(
f"Using {len(wheels)} separate wheels to determine final rotation..."
)
is_snapped = polib.snap_to_ground_bpy.snap_to_ground_separate_wheels(
obj, root_object, wheels, ground_objects
)
else:
logger.info(
f"No wheels present in this asset, using snap normal to determine "
f"final rotation..."
)
is_snapped = polib.snap_to_ground_bpy.snap_to_ground_adjust_rotation(
obj, root_object, ground_objects
)
elif polib.asset_pack_bpy.is_polygoniq_object(obj, lambda x: x == "botaniq"):
logger.info(
f"Determined that {obj.name} is a botaniq asset. Going to snap without "
f"adjusting rotation."
)
if obj.type == 'MESH':
is_snapped = polib.snap_to_ground_bpy.snap_to_ground_no_rotation(
obj, obj, ground_objects
)
elif obj.type == 'EMPTY' and obj.instance_type == 'COLLECTION':
collection = obj.instance_collection
if len(collection.objects) >= 1:
for collection_object in collection.objects:
if collection_object.type == 'MESH':
is_snapped = polib.snap_to_ground_bpy.snap_to_ground_no_rotation(
obj, collection_object, ground_objects
)
break
else:
wrong_type_object_names.append(obj.name)
continue
else: # generic behavior
logger.info(
f"Determined that {obj.name} is a generic asset. Going to snap with "
f"adjustment to rotation."
)
if obj.type == 'MESH':
is_snapped = polib.snap_to_ground_bpy.snap_to_ground_adjust_rotation(
obj, obj, ground_objects
)
elif obj.type == 'EMPTY' and obj.instance_type == 'COLLECTION':
collection = obj.instance_collection
if len(collection.objects) >= 1:
for collection_object in collection.objects:
if collection_object.type == 'MESH':
is_snapped = (
polib.snap_to_ground_bpy.snap_to_ground_adjust_rotation(
obj, collection_object, ground_objects
)
)
break
else:
wrong_type_object_names.append(obj.name)
continue
if is_snapped:
snapped_objects_names.append(obj.name)
else:
no_ground_object_names.append(obj.name)
if len(no_ground_object_names + wrong_type_object_names) > 0:
problems = []
if len(no_ground_object_names) > 0:
problems.append(
"Ground object was not found, make sure there is another object under "
"the selected objects"
)
if len(wrong_type_object_names) > 0:
problems.append("This object type can not be snapped")
message = (
f"{len(no_ground_object_names) + len(wrong_type_object_names)}"
f" object(s) were not snapped to the ground"
)
logger.warning(
f"{message}. "
f"Ground object was not found: {no_ground_object_names}, "
f"Object type can not be snapped: {wrong_type_object_names}."
)
problems_string = ". ".join(problems)
self.report({'WARNING'}, f"{message}. Encountered issues: {problems_string}")
logger.info(f"Snapped the following objects to the ground: {snapped_objects_names}")
return {'FINISHED'}
MODULE_CLASSES.append(SnapToGround)
@polib.log_helpers_bpy.logged_operator
class RandomizeTransform(bpy.types.Operator):
bl_idname = "engon.randomize_transform"
bl_label = "Random Transform"
bl_description = "Randomize Scale and Rotation of Selected Objects"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context: bpy.types.Context):
return context.mode == 'OBJECT' and len(context.selected_objects) > 0
def execute(self, context):
selected_objects_names = [obj.name for obj in context.selected_objects]
logger.info(f"Working on selected objects: {selected_objects_names}")
bpy.ops.object.randomize_transform(
random_seed=random.randint(0, 10000),
use_loc=False,
rot=(0.0349066, 0.0349066, 3.14159),
scale=(1.1, 1.1, 1.1),
scale_even=True,
)
return {'FINISHED'}
MODULE_CLASSES.append(RandomizeTransform)
@polib.log_helpers_bpy.logged_operator
class ResetTransform(bpy.types.Operator):
bl_idname = "engon.reset_transform"
bl_label = "Reset Transform"
bl_description = "Reset Rotation and Scale of Selected Objects to (0,0,0)"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context: bpy.types.Context):
return context.mode == 'OBJECT' and len(context.selected_objects) > 0
def execute(self, context):
selected_objects_names = [obj.name for obj in context.selected_objects]
logger.info(f"Working on selected objects: {selected_objects_names}")
bpy.ops.object.rotation_clear()
bpy.ops.object.scale_clear()
return {'FINISHED'}
MODULE_CLASSES.append(ResetTransform)
@polib.log_helpers_bpy.logged_operator
class SpreadObjects(bpy.types.Operator):
bl_idname = "engon.spread_objects"
bl_label = "Spread Objects"
bl_description = "Spreads selected objects into a grid"
bl_options = {'REGISTER', 'UNDO'}
class DistributionType(enum.Enum):
LINE = "Line"
ROWS = "Rows"
SQUARE_GRID = "Square Grid"
distribution_type: bpy.props.EnumProperty(
name="Distribution Type",
description="How to spread the objects",
items=[
(DistributionType.LINE.value, DistributionType.LINE.value, "Spread assets in one line"),
(
DistributionType.ROWS.value,
DistributionType.ROWS.value,
"Spread assets in rows and colums",
),
(
DistributionType.SQUARE_GRID.value,
DistributionType.SQUARE_GRID.value,
"Spread assets in grid",
),
],
default=DistributionType.LINE.value,
)
use_bounding_box_for_offset: bpy.props.BoolProperty(
name="Use Bounding Box for Offset",
description="If enabled, each objects bounding box is used in addition to the fixed "
"X, Y Offset. Otherwise just the fixed X and Y offset is used",
default=True,
)
column_x_offset: bpy.props.FloatProperty(name="X Offset", default=0.1, min=0.0)
row_y_offset: bpy.props.FloatProperty(name="Y Offset", default=0.1, min=0.0)
automatic_square_grid: bpy.props.BoolProperty(
name="Automatic Square Grid",
description="If enabled, the number of objects in one row is automatically calculated to "
"make the grid close to a square",
default=True,
)
objects_in_a_row: bpy.props.IntProperty(
name="Objects in a Row",
description="How many objects are there in one row of the grid. Only used if Automatic "
"Square Grid is disabled",
default=10,
min=1,
)
@classmethod
def poll(cls, context: bpy.types.Context):
# at least two objects required to do anything useful
return len(context.selected_objects) >= 2
def invoke(self, context: bpy.types.Context, event: bpy.types.Event):
return context.window_manager.invoke_props_dialog(self, width=300)
def draw(self, context):
layout = self.layout
row = layout.row(align=False)
row.prop(self, "use_bounding_box_for_offset", text="")
row.label(text="Use Bounding Box for Offset")
row = layout.row(align=False)
row.prop(self, "column_x_offset", text="X Offset")
row.prop(self, "row_y_offset", text="Y Offset")
row = layout.row(align=False)
row.label(text="Distribution Type")
row.prop(self, "distribution_type", text="")
if self.distribution_type == self.DistributionType.ROWS.value:
row = layout.row(align=False)
row.prop(self, "objects_in_a_row", text="")
def execute(self, context: bpy.types.Context):
if self.distribution_type == self.DistributionType.LINE.value:
row_size = len(context.selected_objects)
elif self.distribution_type == self.DistributionType.ROWS.value:
row_size = self.objects_in_a_row
elif self.distribution_type == self.DistributionType.SQUARE_GRID.value:
row_size = math.ceil(math.sqrt(len(context.selected_objects)))
else:
raise ValueError("Invalid distribution option")
number_of_rows = math.ceil(len(context.selected_objects) / row_size)
cursor_location = bpy.context.scene.cursor.location
current_row_y = cursor_location.y
selected_objects_sorted = sorted(context.selected_objects, key=lambda obj: obj.name)
for i in range(number_of_rows):
current_column_x = cursor_location.x
objects_in_row = selected_objects_sorted[i * row_size : (i + 1) * row_size]
# we need to build up a future_row_y based on placed bounding boxes if using offset
# by bounding boxes. if fixed offset is used this will just stay at current_row_y
future_row_y = current_row_y
for obj in objects_in_row:
obj.matrix_world.translation = mathutils.Vector((0.0, 0.0, 0.0))
bbox_at_origin = hatchery.bounding_box.AlignedBox()
bbox_at_origin.extend_by_object(obj)
if not bbox_at_origin.is_valid():
bbox_at_origin.extend_by_point(mathutils.Vector((0.0, 0.0, 0.0)))
obj.matrix_world.translation = mathutils.Vector(
(current_column_x, current_row_y, cursor_location[2])
)
if self.use_bounding_box_for_offset:
min_offset = bbox_at_origin.min
min_offset[2] = 0.0
obj.matrix_world.translation -= min_offset
bbox_placed = hatchery.bounding_box.AlignedBox()
bbox_placed.extend_by_object(obj)
if not bbox_placed.is_valid():
bbox_placed.extend_by_point(obj.location)
current_column_x = bbox_placed.max.x
future_row_y = max(future_row_y, bbox_placed.max.y)
current_column_x += self.column_x_offset
current_row_y = future_row_y + self.row_y_offset
return {'FINISHED'}
MODULE_CLASSES.append(SpreadObjects)
@polib.log_helpers_bpy.logged_panel
class EngonPanel(EngonPanelMixin, bpy.types.Panel):
bl_idname = "VIEW_3D_PT_engon"
bl_label = "engon"
bl_category = "polygoniq"
bl_order = 0
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
def draw_header(self, context: bpy.types.Context) -> None:
self.layout.template_icon(
icon_value=polib.ui_bpy.icon_manager.get_polygoniq_addon_icon_id("engon")
)
def draw_header_preset(self, context: bpy.types.Context) -> None:
self.layout.operator(
browser.browser.MAPR_BrowserOpenAssetPacksPreferences.bl_idname,
text="",
icon='SETTINGS',
)
polib.ui_bpy.draw_doc_button(
self.layout, __package__, rel_url="panels/engon/panel_overview"
)
def draw(self, context: bpy.types.Context):
polib.ui_bpy.draw_conflicting_addons(
self.layout, __package__, preferences.CONFLICTING_ADDONS
)
prefs = preferences.prefs_utils.get_preferences(context)
mapr_prefs = prefs.browser_preferences
what_is_new_prefs = prefs.what_is_new_preferences
col = self.layout.column(align=True)
row = col.row(align=True)
row.scale_y = 1.5
if browser.browser.MAPR_BrowserChooseArea.is_running:
row.label(text="Select area with mouse!", icon='RESTRICT_SELECT_ON')
else:
new_packs = browser.what_is_new.get_updated_asset_packs(context)
is_something_new = what_is_new_prefs.display_what_is_new and len(new_packs) > 0
row.operator(
browser.browser.MAPR_BrowserChooseArea.bl_idname,
text="Browse NEW Assets" if is_something_new else "Browse Assets",
icon='OUTLINER_OB_LIGHT' if is_something_new else 'RESTRICT_SELECT_OFF',
)
row.operator(browser.browser.MAPR_BrowserOpen.bl_idname, text="", icon='WINDOW')
if mapr_prefs.prefs_hijacked:
row = row.row(align=True)
row.scale_x = 1.2
row.alert = True
row.operator(browser.browser.MAPR_BrowserClose.bl_idname, text="", icon='PANEL_CLOSE')
col.separator()
col.label(text="Convert selection:")
row = polib.ui_bpy.scaled_row(col, 1.5, align=True)
row.operator(convert_selection.MakeSelectionLinked.bl_idname, text="Linked", icon='LINKED')
row.operator(
convert_selection.MakeSelectionEditable.bl_idname, text="Editable", icon='MESH_DATA'
)
row.prop(
mapr_prefs.spawn_options, "remove_duplicates", text="", toggle=1, icon='FULLSCREEN_EXIT'
)
col.separator()
col.label(text="Transform selection:")
row = polib.ui_bpy.scaled_row(col, 1.5, align=True)
row.operator(SnapToGround.bl_idname, text="Ground", icon='IMPORT')
row.operator(RandomizeTransform.bl_idname, text="Random", icon='ORIENTATION_GIMBAL')
row.operator(ResetTransform.bl_idname, text="", icon='LOOP_BACK')
col.separator()
row = col.row()
row.operator(SpreadObjects.bl_idname, icon='IMGDISPLAY')
MODULE_CLASSES.append(EngonPanel)
@polib.log_helpers_bpy.logged_panel
class MaintenancePanel(EngonPanelMixin, bpy.types.Panel):
bl_idname = "VIEW_3D_PT_engon_migrator"
bl_parent_id = EngonPanel.bl_idname
bl_label = ".blend maintenance"
bl_options = {'DEFAULT_CLOSED'}
# We want to display the maintenance sub-panel last, as it won't be a frequently used feature
bl_order = 99
def draw_header(self, context: bpy.types.Context):
self.layout.label(text="", icon='BLENDER')
def draw(self, context: bpy.types.Context):
layout = self.layout
col = layout.column(align=True)
col.operator(blend_maintenance.migrator.RemoveDuplicates.bl_idname, icon='FULLSCREEN_EXIT')
col.operator(blend_maintenance.migrator.FindMissingFiles.bl_idname, icon='ZOOM_ALL')
col.operator(blend_maintenance.migrator.MigrateLibraryPaths.bl_idname, icon='SHADERFX')
col.operator(blend_maintenance.migrator.MigrateFromMaterialiq4.bl_idname, icon='SHADERFX')
MODULE_CLASSES.append(MaintenancePanel)
def register():
for cls in MODULE_CLASSES:
bpy.utils.register_class(cls)
def unregister():
for cls in reversed(MODULE_CLASSES):
bpy.utils.unregister_class(cls)