-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbmesh-to-map.py
492 lines (370 loc) · 15.1 KB
/
bmesh-to-map.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
bl_info = {
"name": "BMesh Map",
"author": "Cubiest, Benjamin Lösch",
"version": (1, 4, 1),
"blender": (3, 3, 0),
"description": "Export your mesh as a RAW heightmap",
"doc_url": "https://github.com/cubiest/bmesh-to-raw/blob/main/docs/README.md",
"category": "Object",
}
import bpy, math, struct
from bpy import context
class MTR_PT_ExportSetting(bpy.types.PropertyGroup):
MESH_BOTTOM: bpy.props.StringProperty(default="?") # NOTE: not gonna use FloatProperty, because Blender starts rounding if panel width is too narrow
MESH_TOP: bpy.props.StringProperty(default="?")
EXPORT_RAW_FILE_PATH: bpy.props.StringProperty(name="Filename", subtype='FILE_PATH')
EXPORT_EXR_FILE_PATH: bpy.props.StringProperty(name="Filename", subtype='FILE_PATH')
EXPORT_ERROR: bpy.props.BoolProperty() # is True if last execution failed or `object.stat_mesh` found an error
EXPORT_INVERT_Y: bpy.props.BoolProperty(name="Invert Y-axis")
EXPORT_INVERT_X: bpy.props.BoolProperty(name="Invert X-axis")
EXPORT_BIT_DEPTH: bpy.props.EnumProperty(
name="Bit Depth",
default="out.32",
items=[
(
"out.32", "32-bit", "32-bit unsigned integer",
),
(
"out.24", "24-bit", "24-bit unsigned integer",
),
(
"out.16", "16-bit", "16-bit unsigned integer",
),
],
)
EXPORT_LITTLE_ENDIAN: bpy.props.BoolProperty(name="Little Endian", default=True)
OBJ_PROP_FULL_NAME: bpy.props.StringProperty()
OBJ_PROP_RES: bpy.props.StringProperty()
OBJ_PROP_BOTTOM: bpy.props.StringProperty()
OBJ_PROP_TOP: bpy.props.StringProperty()
class MTR_StatMesh(bpy.types.Operator):
bl_label = "Get mesh's heightmap info and check for errors"
bl_idname = "object.stat_mesh"
bl_description = "Updates selected object's stats and checks its validity"
def execute(self, context):
result = fullcheck(self, context)
global_settings = context.scene.MTR_ExportProperties
global_settings.OBJ_PROP_RES = str(result[1])
global_settings.OBJ_PROP_BOTTOM = str(result[4])
global_settings.OBJ_PROP_TOP = str(result[5])
global_settings.MESH_BOTTOM = global_settings.OBJ_PROP_BOTTOM
global_settings.MESH_TOP = global_settings.OBJ_PROP_TOP
global_settings.EXPORT_ERROR = not result[0]
return {'FINISHED'}
class MTR_PT_ExportRawPanel(bpy.types.Panel):
"""BMesh Map"""
bl_label = "RAW Export"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'BMesh Map'
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT' or context.mode == 'EDIT_MESH' or context.mode == 'SCULPT'
def draw(self, context):
layout = self.layout
global_settings = context.scene.MTR_ExportProperties
name = context.active_object.name
res = "?"
if context.active_object.name == global_settings.OBJ_PROP_FULL_NAME:
res = global_settings.OBJ_PROP_RES
res = f"Res: {res}x{res}"
col = layout.column()
col.label(text="Stats:")
col.operator("object.stat_mesh", text="Get Status", icon='FILE_REFRESH')
box = col.box()
box.label(text="Name: " + name)
box.label(text=res)
row = box.row()
row.label(text="Min-Max:")
minmax_row = row.column().row()
minmax_row.enabled = False
minmax_row.prop(global_settings, "MESH_BOTTOM", text="")
minmax_row.prop(global_settings, "MESH_TOP", text="")
col.separator() # close box
col.label(text="Export:")
box = col.box()
if global_settings.EXPORT_ERROR:
box.alert = global_settings.EXPORT_ERROR
box.prop(global_settings, "EXPORT_RAW_FILE_PATH")
box.prop(global_settings, "EXPORT_INVERT_Y")
box.prop(global_settings, "EXPORT_INVERT_X")
box.prop(global_settings, "EXPORT_BIT_DEPTH")
box.prop(global_settings, "EXPORT_LITTLE_ENDIAN")
box.operator("object.mesh_to_raw", text="Export", icon='EXPORT')
col.separator() # close box
col.label(text="ver " + get_version())
class MTR_MeshToRaw(bpy.types.Operator):
bl_idname = "object.mesh_to_raw"
bl_label = "RAW Export"
bl_description = "Exports selected object as a RAW file"
def execute(self, context):
result = fullcheck(self, context)
if not result[0]:
context.scene.MTR_ExportProperties.EXPORT_ERROR = True
return {'CANCELLED'}
global_settings = context.scene.MTR_ExportProperties
res = result[1]
bottom = result[4]
top = result[5]
max_val = 0.0
if global_settings.EXPORT_BIT_DEPTH == "out.32":
max_val = 4294967295.0
elif global_settings.EXPORT_BIT_DEPTH == "out.24":
max_val = 16777215.0
elif global_settings.EXPORT_BIT_DEPTH == "out.16":
max_val = 65535.0
if max_val <= 0.0001:
show_error_msg(self, "Corrupt settings: cannot get bit depth for export")
return {'CANCELLED'}
h_scale = max_val / (top - bottom)
positions = result[2]
heights = result[3]
heightmap = [[0 for x in range(res)] for y in range(res)] # integers
max_val_int = round_int(max_val)
for i in range(res*res):
pos = positions[i]
x = int(pos[0])
y = (res-1) - int(pos[1])
h = round_int((heights[i] - bottom) * h_scale)
# This should no happen, because we round to 4 decimal places in fullcheck(), but just to be on the safe side:
if h > max_val_int:
h = max_val_int
heightmap[x][y] = h
flattend_heightmap = flatten_heightmap(heightmap, res, global_settings.EXPORT_INVERT_Y, global_settings.EXPORT_INVERT_X)
b_out = bytes(0)
if global_settings.EXPORT_BIT_DEPTH == "out.32":
order = list()
if global_settings.EXPORT_LITTLE_ENDIAN:
order = [0, 8, 16, 24]
else:
order = [24, 16, 8, 0]
out = list()
for h in flattend_heightmap:
for i in order:
out.append((h >> i) & 0xff)
b_out = bytes(out) # unsigned 32-bit-integer
elif global_settings.EXPORT_BIT_DEPTH == "out.24":
order = list()
if global_settings.EXPORT_LITTLE_ENDIAN:
order = [0, 8, 16]
else:
order = [16, 8, 0]
out = list()
for h in flattend_heightmap:
for i in order:
out.append((h >> i) & 0xff)
b_out = bytes(out) # unsigned 24-bit-integer
elif global_settings.EXPORT_BIT_DEPTH == "out.16":
format = ""
if global_settings.EXPORT_LITTLE_ENDIAN:
format = f"<{res*res}H"
else:
format = f">{res*res}H"
b_out = struct.pack(format, *flattend_heightmap) # ushort (aka unsigned 16-bit-integer)
e_file = global_settings.EXPORT_RAW_FILE_PATH
if e_file == "":
global_settings.EXPORT_ERROR = True
show_error_msg(self, "Export path is undefined")
return {'CANCELLED'}
if bpy.path.basename(e_file) == "":
global_settings.EXPORT_ERROR = True
show_error_msg(self, "Please specify a filename")
return {'CANCELLED'}
e_file = bpy.path.ensure_ext(e_file, ".raw")
export_path = bpy.path.abspath(e_file)
export = open(export_path, 'bw') # open in binary-write mode
export.write(b_out)
export.close()
global_settings.EXPORT_ERROR = False
show_info_msg(self, "Export done")
return {'FINISHED'}
class MTR_PT_ExportExrPanel(bpy.types.Panel):
"""BMesh Map"""
bl_label = "EXR Export"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'BMesh Map'
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT' or context.mode == 'EDIT_MESH' or context.mode == 'SCULPT'
def draw(self, context):
layout = self.layout
global_settings = context.scene.MTR_ExportProperties
name = context.active_object.name
res = "?"
if context.active_object.name == global_settings.OBJ_PROP_FULL_NAME:
res = global_settings.OBJ_PROP_RES
res = f"Res: {res}x{res}"
col = layout.column()
col.label(text="Stats:")
col.operator("object.stat_mesh", text="Get Status", icon='FILE_REFRESH')
box = col.box()
box.label(text="Name: " + name)
box.label(text=res)
col.separator() # close box
col.label(text="Export:")
box = col.box()
if global_settings.EXPORT_ERROR:
box.alert = global_settings.EXPORT_ERROR
box.prop(global_settings, "EXPORT_EXR_FILE_PATH")
box.prop(global_settings, "EXPORT_INVERT_Y")
box.prop(global_settings, "EXPORT_INVERT_X")
box.operator("object.mesh_to_exr", text="Export", icon='EXPORT')
col.separator() # close box
col.label(text="ver " + get_version())
class MTR_MeshToEXR(bpy.types.Operator):
bl_idname = "object.mesh_to_exr"
bl_label = "OpenEXR Export"
bl_description = "Exports selected object as an OpenEXR file"
def execute(self, context):
result = fullcheck(self, context)
if not result[0]:
context.scene.MTR_ExportProperties.EXPORT_ERROR = True
return {'CANCELLED'}
res = result[1]
# NOTE:
# float_buffer sets data to 32-bit floats and allows range greater than 0..1,
# afterwards, changing to 16-bit is not possible
heightmap_img = bpy.data.images.new("heightmap", res, res, float_buffer=True, is_data=True)
heightmap_img.file_format = 'OPEN_EXR'
heights = result[3]
global_settings = context.scene.MTR_ExportProperties
positions = result[2]
heightmap = [[0.0 for x in range(res)] for y in range(res)] # floats
for i in range(res*res):
pos = positions[i]
x = int(pos[0])
y = int(pos[1])
heightmap[x][y] = heights[i]
heights = flatten_heightmap(heightmap, res, global_settings.EXPORT_INVERT_Y, global_settings.EXPORT_INVERT_X) # flush
pixels = list()
for i in range(res*res):
pixels.extend((heights[i], 0.0, 0.0, 1.0))
heightmap_img.pixels = pixels
e_file = global_settings.EXPORT_EXR_FILE_PATH
if e_file == "":
global_settings.EXPORT_ERROR = True
show_error_msg(self, "Export path is undefined")
return {'CANCELLED'}
if bpy.path.basename(e_file) == "":
global_settings.EXPORT_ERROR = True
show_error_msg(self, "Please specify a filename")
return {'CANCELLED'}
heightmap_img.filepath_raw = bpy.path.ensure_ext(e_file, ".exr")
heightmap_img.save()
global_settings.EXPORT_ERROR = False
show_info_msg(self, "Export done")
return {'FINISHED'}
def get_version():
version = ""
for v in bl_info["version"]:
version += str(v) + "."
if version.endswith("."):
version = version[:-1]
return version
# fullcheck returns a tuple defined as follows
# - bool: is True if no errors were found
# - int: Mesh resolution
# - list: positions, or empty on error
# - list: heights (rounded to 4 decimal places), or empty on error
# - float: lowest height value, or 0.0 on error
# - float: highest height value, or 0.0 on error
def fullcheck(self, context):
global_settings = context.scene.MTR_ExportProperties
obj = context.active_object
global_settings.OBJ_PROP_FULL_NAME = obj.name_full
res = int(math.sqrt(len(obj.data.vertices)))
positions = list() # Vector2
heights = list() # float
# data is of type bpy.types.Mesh
for v in obj.data.vertices: # bpy.types.MeshVertex
positions.append(v.co.to_2d()) # mathutils.Vector
heights.append(v.co[2])
ok = precheck(self, obj, res, positions)
if not ok:
return (False, res, [], [], 0.0, 0.0)
bottom = round_decimals(heights[0])
top = bottom
for i in range(len(heights)):
h = heights[i]
h = round_decimals(h, 4)
heights[i] = h
if h > top:
top = h
elif h < bottom:
bottom = h
return (True, res, positions, heights, bottom, top)
def precheck(self, obj, res, positions):
if not is_power_of_2(res-1):
show_error_msg(self, f"Mesh resolution is not power of 2 + 1: got {res}")
return False
width = int(obj.dimensions[0])
depth = int(obj.dimensions[1])
if width != depth:
show_error_msg(self, f"Dimensions are not equal: got {width}x{depth}")
return False
if not is_power_of_2(width):
show_error_msg(self, f"Dimensions are not power of 2: got {width}")
return False
for i in range(len(positions)):
pos = positions[i]
x = int(pos[0])
y = int(pos[1])
if x < 0 or y < 0 or x >= res or y >= res:
show_error_msg(self, f"Position ({x}, {y}) is out-of-bounds [0, {res - 1}]")
return False
return True
def show_error_msg(self, txt):
msg = (txt)
self.report({'ERROR'}, msg)
def show_info_msg(self, txt):
msg = (txt)
self.report({'INFO'}, msg)
# formula taken from: https://stackoverflow.com/a/57025941 (© @tomerikoo)
def is_power_of_2(n):
return (n & (n-1) == 0) and n != 0
def round_int(v):
return math.floor(v + 0.5)
def round_decimals(v, dec=0):
mul = 10 ** dec
return math.floor(v * mul + 0.5) / mul
# flatten_heightmap changes 2-d heightmap array to a 1-d version.
# inverts height infos on x- and/or y-axis upon request.
def flatten_heightmap(heightmap, res, invert_y, invert_x):
y_start = 0
y_stop = res
y_step = 1
x_start = 0
x_stop = res
x_step = 1
if invert_y:
y_start = res-1
y_stop = -1
y_step = -1
if invert_x:
x_start = res-1
x_stop = -1
x_step = -1
flattend_heightmap = list()
for y in range(y_start, y_stop, y_step):
for x in range(x_start, x_stop, x_step):
flattend_heightmap.append(heightmap[x][y])
return flattend_heightmap
def register():
bpy.utils.register_class(MTR_PT_ExportSetting)
bpy.utils.register_class(MTR_StatMesh)
bpy.utils.register_class(MTR_MeshToRaw)
bpy.utils.register_class(MTR_PT_ExportRawPanel)
bpy.utils.register_class(MTR_MeshToEXR)
bpy.utils.register_class(MTR_PT_ExportExrPanel)
bpy.types.Scene.MTR_ExportProperties = bpy.props.PointerProperty(type=MTR_PT_ExportSetting)
def unregister():
bpy.utils.unregister_class(MTR_PT_ExportExrPanel)
bpy.utils.unregister_class(MTR_MeshToEXR)
bpy.utils.unregister_class(MTR_PT_ExportRawPanel)
bpy.utils.unregister_class(MTR_MeshToRaw)
bpy.utils.unregister_class(MTR_StatMesh)
bpy.utils.unregister_class(MTR_PT_ExportSetting)
del bpy.types.Scene.MTR_ExportProperties
if __name__ == "__main__":
register()