Welcome to mirror list, hosted at ThFree Co, Russian Federation.

blender_icons_geom.py « datafiles « release - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b95baf3419ef57f2b8e2726e38c87c93b94f5600 (plain)
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
# SPDX-License-Identifier: Apache-2.0

"""
Example Usage
=============

Command line::

   ./blender.bin \
       icon_file.blend --background --python ./release/datafiles/blender_icons_geom.py -- \
       --output-dir=./release/datafiles/blender_icons_geom

Icon Format
===========

This is a simple binary format (all bytes, so no endian).

The header is 8 bytes:

:0..3: ``VCO``: identifier.
:4: ``0``: icon file version.
:5: icon size-x.
:6: icon size-y.
:7: icon start-x.
:8: icon start-y.

Icon width and height are for icons that don't use the full byte range
(so we don't get bad alignment for 48 pixel grid for eg).

Start values are currently unused.

After the header, the remaining length of the data defines the geometry size.

:6 bytes each: triangle (XY) locations.
:12 bytes each: triangle (RGBA) locations.

All coordinates are written, then all colors.

Since this is a binary format which isn't intended for general use
the ``.dat`` file extension should be used.
"""

# This script writes out geometry-icons.
import bpy

# Generic functions

OBJECTS_TYPES_MESH_COMPATIBLE = {'CURVE', 'MESH'}


def area_tri_signed_2x_v2(v1, v2, v3):
    return (v1[0] - v2[0]) * (v2[1] - v3[1]) + (v1[1] - v2[1]) * (v3[0] - v2[0])


class TriMesh:
    """
    Triangulate, may apply other changes here too.
    """
    __slots__ = ("object", "mesh")

    def __init__(self, ob):
        self.object = ob
        self.mesh = None

    def __enter__(self):
        self.mesh = self._tri_copy_from_object(self.object)
        return self.mesh

    def __exit__(self, *args):
        bpy.data.meshes.remove(self.mesh)

    @staticmethod
    def _tri_copy_from_object(ob):
        import bmesh
        assert(ob.type in OBJECTS_TYPES_MESH_COMPATIBLE)
        bm = bmesh.new()
        bm.from_mesh(ob.to_mesh())
        bmesh.ops.triangulate(bm, faces=bm.faces)
        me = bpy.data.meshes.new(ob.name + ".copy")
        bm.to_mesh(me)
        bm.free()
        ob.to_mesh_clear()
        return me


def object_material_colors(ob):
    material_colors = []
    color_default = (1.0, 1.0, 1.0, 1.0)
    for slot in ob.material_slots:
        material = slot.material
        color = color_default
        if material is not None and material.use_nodes:
            node_tree = material.node_tree
            if node_tree is not None:
                color = next((
                    node.outputs[0].default_value[:]
                    for node in node_tree.nodes
                    if node.type == 'RGB'
                ), color_default)
        if min(color) < 0.0 or max(color) > 1.0:
            print(f"Material: {material.name!r} has color out of 0..1 range {color!r}")
            color = tuple(max(min(c, 1.0), 0.0) for c in color)
        material_colors.append(color)
    return material_colors


def object_child_map(objects):
    objects_children = {}
    for ob in objects:
        ob_parent = ob.parent
        # Get the root.
        if ob_parent is not None:
            while ob_parent and ob_parent.parent:
                ob_parent = ob_parent.parent
        if ob_parent is not None:
            objects_children.setdefault(ob_parent, []).append(ob)
    for ob_all in objects_children.values():
        ob_all.sort(key=lambda ob: ob.name)
    return objects_children


def mesh_data_lists_from_mesh(me, material_colors):
    me_loops = me.loops[:]
    me_loops_color = me.attributes.active_color.data[:]
    me_verts = me.vertices[:]
    me_polys = me.polygons[:]

    tris_data = []

    for p in me_polys:
        # Note, all faces are handled, backfacing/zero area is checked just before writing.
        material_index = p.material_index
        if material_index < len(material_colors):
            base_color = material_colors[p.material_index]
        else:
            base_color = (1.0, 1.0, 1.0, 1.0)

        l_sta = p.loop_start
        l_len = p.loop_total
        loops_poly = me_loops[l_sta:l_sta + l_len]
        color_poly = me_loops_color[l_sta:l_sta + l_len]
        i0 = 0
        i1 = 1

        # we only write tris now
        assert(len(loops_poly) == 3)

        for i2 in range(2, l_len):
            l0 = loops_poly[i0]
            l1 = loops_poly[i1]
            l2 = loops_poly[i2]

            c0 = color_poly[i0]
            c1 = color_poly[i1]
            c2 = color_poly[i2]

            v0 = me_verts[l0.vertex_index]
            v1 = me_verts[l1.vertex_index]
            v2 = me_verts[l2.vertex_index]

            tris_data.append((
                # float depth
                p.center.z,
                # XY coords.
                (
                    v0.co.xy[:],
                    v1.co.xy[:],
                    v2.co.xy[:],
                ),
                # RGBA color in sRGB color space.
                (
                    color_multiply_and_from_linear_to_srgb(base_color, c0),
                    color_multiply_and_from_linear_to_srgb(base_color, c1),
                    color_multiply_and_from_linear_to_srgb(base_color, c2),
                ),
            ))
            i1 = i2
    return tris_data


def color_multiply_and_from_linear_to_srgb(base_color, vertex_color):
    """
    Return the RGBA color in sRGB and byte format (0-255).

    base_color and vertex_color are expected in linear space.
    The final color is the product between the base color and the vertex color.
    """
    import mathutils
    color_linear = [c * b for c, b in zip(vertex_color.color, base_color)]
    color_srgb = mathutils.Color(color_linear[:3]).from_scene_linear_to_srgb()
    return tuple(round(c * 255) for c in (*color_srgb, color_linear[3]))


def mesh_data_lists_from_objects(ob_parent, ob_children):
    tris_data = []

    has_parent = False
    if ob_children:
        parent_matrix = ob_parent.matrix_world.copy()
        parent_matrix_inverted = parent_matrix.inverted()

    for ob in (ob_parent, *ob_children):
        with TriMesh(ob) as me:
            if has_parent:
                me.transform(parent_matrix_inverted @ ob.matrix_world)

            tris_data.extend(
                mesh_data_lists_from_mesh(
                    me,
                    object_material_colors(ob),
                )
            )
        has_parent = True
    return tris_data


def write_mesh_to_py(fh, ob, ob_children):

    def float_as_byte(f, axis_range):
        assert(axis_range <= 255)
        # -1..1 -> 0..255
        f = (f + 1.0) * 0.5
        f = round(f * axis_range)
        return min(max(f, 0), axis_range)

    def vert_as_byte_pair(v):
        return (
            float_as_byte(v[0], coords_range_align[0]),
            float_as_byte(v[1], coords_range_align[1]),
        )

    tris_data = mesh_data_lists_from_objects(ob, ob_children)

    # 100 levels of Z depth, round to avoid differences from precision error
    # causing different computers to write triangles in more or less random order.
    tris_data.sort(key=lambda data: int(data[0] * 100))

    if 0:
        # make as large as we can, keeping alignment
        def size_scale_up(size):
            assert(size != 0)
            while size * 2 <= 255:
                size *= 2
            return size

        coords_range = (
            size_scale_up(ob.get("size_x")) or 255,
            size_scale_up(ob.get("size_y")) or 255,
        )
    else:
        # disable for now
        coords_range = 255, 255

    # Pixel size needs to be increased since a pixel needs one extra geom coordinate,
    # if we're writing 32 pixel, align verts to 33.
    coords_range_align = tuple(min(c + 1, 255) for c in coords_range)

    print("Writing:", fh.name, coords_range)

    fw = fh.write

    # Header (version 0).
    fw(b'VCO\x00')
    # Width, Height
    fw(bytes(coords_range))
    # X, Y
    fw(bytes((0, 0)))

    # Once converted into bytes, the triangle might become zero area
    tri_skip = [False] * len(tris_data)
    for i, (_, tri_coords, _) in enumerate(tris_data):
        tri_coords_as_byte = [vert_as_byte_pair(vert) for vert in tri_coords]
        if area_tri_signed_2x_v2(*tri_coords_as_byte) <= 0:
            tri_skip[i] = True
            continue
        for vert_byte in tri_coords_as_byte:
            fw(bytes(vert_byte))
    for i, (_, _, tri_color) in enumerate(tris_data):
        if tri_skip[i]:
            continue
        for color in tri_color:
            fw(bytes(color))


def create_argparse():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--output-dir",
        dest="output_dir",
        default=".",
        type=str,
        metavar="DIR",
        required=False,
        help="Directory to write icons to.",
    )
    parser.add_argument(
        "--group",
        dest="group",
        default="",
        type=str,
        metavar="GROUP",
        required=False,
        help="Group name to export from (otherwise export all objects).",
    )
    return parser


def main():
    import os
    import sys
    parser = create_argparse()
    if "--" in sys.argv:
        argv = sys.argv[sys.argv.index("--") + 1:]
    else:
        argv = []
    args = parser.parse_args(argv)

    objects = []
    depsgraph = bpy.context.view_layer.depsgraph

    if args.group:
        group = bpy.data.collections.get(args.group)
        if group is None:
            print(f"Group {args.group!r} not found!")
            return
        objects_source = group.objects
        del group
    else:
        objects_source = bpy.data.objects

    for ob in objects_source:

        # Skip non-mesh objects
        if ob.type not in OBJECTS_TYPES_MESH_COMPATIBLE:
            continue

        ob_eval = ob.evaluated_get(depsgraph)
        name = ob_eval.name

        # Skip copies of objects
        if name.rpartition(".")[2].isdigit():
            continue

        if not ob_eval.data.attributes.active_color:
            print("Skipping:", name, "(no vertex colors)")
            continue

        objects.append((name, ob_eval))

    objects.sort(key=lambda a: a[0])

    objects_children = object_child_map(depsgraph.objects)

    for name, ob in objects:
        if ob.parent:
            continue
        filename = os.path.join(args.output_dir, name + ".dat")
        with open(filename, 'wb') as fh:
            write_mesh_to_py(fh, ob, objects_children.get(ob, []))


if __name__ == "__main__":
    main()