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

oscurart_meshes.py « oscurart_tools - git.blender.org/blender-addons.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f6ba46ff9b476d4b155740998980f243ed02a4b3 (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
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
# ##### 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 #####

# <pep8 compliant>

import bpy
from bpy.types import Operator
from bpy.props import (
        IntProperty,
        BoolProperty,
        FloatProperty,
        EnumProperty,
        )
import os
import bmesh
import time
import blf
from bpy_extras.view3d_utils import location_3d_to_region_2d

C = bpy.context
D = bpy.data


# -----------------------------RECONST---------------------------

def defReconst(self, OFFSET):
    bpy.ops.object.mode_set(mode='EDIT', toggle=False)
    bpy.context.tool_settings.mesh_select_mode = (True, True, True)
    ob = bpy.context.active_object
    bm = bmesh.from_edit_mesh(ob.data)
    bm.select_flush(False)
    for vertice in bm.verts[:]:
        if abs(vertice.co[0]) < OFFSET:
            vertice.co[0] = 0
    for vertice in bm.verts[:]:
        if vertice.co[0] < 0:
            bm.verts.remove(vertice)
            bmesh.update_edit_mesh(ob.data)
    mod = ob.modifiers.new("Mirror", "MIRROR")
    uv = ob.data.uv_textures.new(name="SYMMETRICAL")
    for v in bm.faces:
        v.select = 1
    bmesh.update_edit_mesh(ob.data)
    ob.data.uv_textures.active = ob.data.uv_textures['SYMMETRICAL']
    bpy.ops.uv.unwrap(
        method='ANGLE_BASED',
        fill_holes=True,
        correct_aspect=False,
        use_subsurf_data=0)
    bpy.ops.object.mode_set(mode="OBJECT", toggle=False)
    bpy.ops.object.modifier_apply(apply_as='DATA', modifier="Mirror")
    bpy.ops.object.mode_set(mode="EDIT", toggle=False)
    bm = bmesh.from_edit_mesh(ob.data)
    bm.select_flush(0)
    uv = ob.data.uv_textures.new(name="ASYMMETRICAL")
    ob.data.uv_textures.active = ob.data.uv_textures['ASYMMETRICAL']
    bpy.ops.uv.unwrap(
        method='ANGLE_BASED',
        fill_holes=True,
        correct_aspect=False,
        use_subsurf_data=0)


class reConst(Operator):
    """Erase vertices bellow cero X position value and rebuilds the symmetry. """
    """It also creates two uv channels, one symmetrical and one asymmetrical"""
    bl_idname = "mesh.reconst_osc"
    bl_label = "ReConst Mesh"
    bl_options = {"REGISTER", "UNDO"}

    OFFSET = FloatProperty(
            name="Offset",
            default=0.001,
            min=-0,
            max=0.1
            )

    @classmethod
    def poll(cls, context):
        return (context.active_object is not None and
                context.active_object.type == 'MESH')

    def execute(self, context):
        defReconst(self, self.OFFSET)
        return {'FINISHED'}


# -----------------------------------SELECT LEFT---------------------

def side(self, nombre, offset):

    bpy.ops.object.mode_set(mode="EDIT", toggle=0)
    OBJECT = bpy.context.active_object
    ODATA = bmesh.from_edit_mesh(OBJECT.data)
    bpy.context.tool_settings.mesh_select_mode = (True, False, False)
    for VERTICE in ODATA.verts[:]:
        VERTICE.select = False
    if nombre is False:
        for VERTICES in ODATA.verts[:]:
            if VERTICES.co[0] < (offset):
                VERTICES.select = 1
    else:
        for VERTICES in ODATA.verts[:]:
            if VERTICES.co[0] > (offset):
                VERTICES.select = 1
    ODATA.select_flush(False)
    bpy.ops.object.mode_set(mode="EDIT", toggle=0)


class SelectMenor(Operator):
    """Selects the vetex with an N position value on the X axis"""
    bl_idname = "mesh.select_side_osc"
    bl_label = "Select Side"
    bl_options = {"REGISTER", "UNDO"}

    @classmethod
    def poll(cls, context):
        return (context.active_object is not None and
                context.active_object.type == 'MESH')

    side = BoolProperty(
            name="Greater than zero",
            default=False
            )
    offset = FloatProperty(
            name="Offset",
            default=0
            )

    def execute(self, context):

        side(self, self.side, self.offset)

        return {'FINISHED'}


# -------------------------RESYM VG----------------------------------


class resymVertexGroups(Operator):
    bl_idname = "mesh.resym_vertex_weights_osc"
    bl_label = "Resym Vertex Weights"
    bl_description = ("Copies the symetrical weight value of the vertices on the X axys\n"
                      "(It needs the XML map and the Active Object is not in Edit mode)")
    bl_options = {"REGISTER", "UNDO"}

    @classmethod
    def poll(cls, context):
        obj = context.active_object
        return obj is not None and obj.mode != "EDIT"

    def execute(self, context):
        ob = bpy.context.object
        actgr = ob.vertex_groups.active if ob else None
        if not actgr:
            self.report({'WARNING'},
                        "Object doesn't have active Vertex groups. Operation Cancelled")
            return {"CANCELLED"}

        with open("%s_%s_SYM_TEMPLATE.xml" % (os.path.join(os.path.dirname(bpy.data.filepath),
                                              bpy.context.scene.name), bpy.context.object.name)) as file:
            actind = ob.vertex_groups.active_index
            ls = eval(file.read())
            wdict = {left: actgr.weight(right) for left, right in ls.items()
                     for group in ob.data.vertices[right].groups if group.group == actind}
            actgr.remove(
                [vert.index for vert in ob.data.vertices if vert.co[0] <= 0])
            for ind, weight in wdict.items():
                actgr.add([ind], weight, 'REPLACE')
            bpy.context.object.data.update()

        return {'FINISHED'}


# --------------------------- RESYM MESH-------------------------


def reSymSave(self, quality):

    bpy.ops.object.mode_set(mode='OBJECT')

    object = bpy.context.object

    rdqual = quality
    rd = lambda x: round(x, rdqual)
    absol = lambda x: (abs(x[0]), x[1], x[2])

    inddict = {
            tuple(map(rd, vert.co[:])): vert.index for vert in object.data.vertices[:]
            }
    reldict = {inddict[vert]: inddict.get(absol(vert), inddict[vert])
               for vert in inddict if vert[0] <= 0}

    ENTFILEPATH = "%s_%s_SYM_TEMPLATE.xml" % (
        os.path.join(os.path.dirname(bpy.data.filepath),
                     bpy.context.scene.name),
        bpy.context.object.name)

    with open(ENTFILEPATH, mode="w") as file:
        file.writelines(str(reldict))
        reldict.clear()


def reSymMesh(self, SELECTED, SIDE):
    bpy.ops.object.mode_set(mode='EDIT')
    ENTFILEPATH = "%s_%s_SYM_TEMPLATE.xml" % (
        os.path.join(os.path.dirname(bpy.data.filepath),
                     bpy.context.scene.name),
        bpy.context.object.name)
    with open(ENTFILEPATH, mode="r") as file:
        SYMAP = eval(file.readlines()[0])
        bm = bmesh.from_edit_mesh(bpy.context.object.data)
        object = bpy.context.object

        def MAME(SYMAP):
            bm.verts.ensure_lookup_table()
            if SELECTED:
                for vert in SYMAP:
                    if bm.verts[SYMAP[vert]].select:
                        bm.verts[vert].co = (-1 * bm.verts[SYMAP[vert]].co[0],
                                             bm.verts[SYMAP[vert]].co[1],
                                             bm.verts[SYMAP[vert]].co[2])
            else:
                for vert in SYMAP:
                    bm.verts[vert].co = (-1 * bm.verts[SYMAP[vert]].co[0],
                                         bm.verts[SYMAP[vert]].co[1],
                                         bm.verts[SYMAP[vert]].co[2])
            bmesh.update_edit_mesh(object.data)

        def MEMA(SYMAP):
            bm.verts.ensure_lookup_table()
            if SELECTED:
                for vert in SYMAP:
                    if bm.verts[vert].select:
                        bm.verts[SYMAP[vert]].co = (-1 * bm.verts[vert].co[0],
                                                    bm.verts[vert].co[1],
                                                    bm.verts[vert].co[2])
            else:
                for vert in SYMAP:
                    bm.verts[SYMAP[vert]].co = (-1 * bm.verts[vert].co[0],
                                                bm.verts[vert].co[1],
                                                bm.verts[vert].co[2])
            bmesh.update_edit_mesh(object.data)

        if SIDE == "+-":
            MAME(SYMAP)
        else:
            MEMA(SYMAP)


class OscResymSave(Operator):
    """Creates a file on disk that saves the info of every vertex but in simmetry, """ \
    """this info its going to be later used by “Resym Mesh” and “Resym Vertex Weights”"""
    bl_idname = "mesh.resym_save_map"
    bl_label = "Resym save XML Map"
    bl_options = {"REGISTER", "UNDO"}

    @classmethod
    def poll(cls, context):
        return (context.active_object is not None and
                context.active_object.type == 'MESH')

    quality = IntProperty(
            default=4,
            name="Quality"
            )

    def execute(self, context):
        reSymSave(self, self.quality)
        return {'FINISHED'}


class OscResymMesh(Operator):
    """Copies the symetrical position of the vertices on the X axys. It needs the XML map"""
    bl_idname = "mesh.resym_mesh"
    bl_label = "Resym save Apply XML"
    bl_options = {"REGISTER", "UNDO"}

    @classmethod
    def poll(cls, context):
        return context.active_object is not None

    selected = BoolProperty(
            default=False,
            name="Only Selected"
            )
    side = EnumProperty(
            name="Side:",
            description="Select Side",
            items=(('+-', "+X to -X", "+X to -X"),
                   ('-+', "-X to +X", "-X to +X")),
            default='+-',
            )

    def execute(self, context):
        reSymMesh(self, self.selected, self.side)
        return {'FINISHED'}


# -------------------------- OBJECT TO MESH ------------------------------

def DefOscObjectToMesh():
    ACTOBJ = bpy.context.object
    MESH = ACTOBJ.to_mesh(
        scene=bpy.context.scene,
        apply_modifiers=True,
        settings="RENDER",
        calc_tessface=True)
    OBJECT = bpy.data.objects.new(("%s_Freeze") % (ACTOBJ.name), MESH)
    bpy.context.scene.objects.link(OBJECT)


class OscObjectToMesh(Operator):
    """It creates a copy of the final state of the object as it being see in the viewport"""
    bl_idname = "mesh.object_to_mesh_osc"
    bl_label = "Object To Mesh"

    @classmethod
    def poll(cls, context):
        return (context.active_object is not None and
                context.active_object.type in
                {'MESH', 'META', 'CURVE', 'SURFACE'})

    def execute(self, context):
        print("Active type object is", context.object.type)
        DefOscObjectToMesh()

        return {'FINISHED'}


# ----------------------------- OVERLAP UV -------------------------------


def DefOscOverlapUv(valpresicion):
    inicio = time.time()
    mode = bpy.context.object.mode
    bpy.ops.object.mode_set(mode='OBJECT', toggle=False)

    rd = valpresicion
    ob = bpy.context.object
    absco = lambda x: (abs(round(x[0], rd)), round(x[1], rd), round(x[2], rd))
    rounder = lambda x: (round(x[0], rd), round(x[1], rd), round(x[2], rd))

    # vertice a vertex
    vertvertex = {}
    for vert in ob.data.loops:
        vertvertex.setdefault(vert.vertex_index, []).append(vert.index)

    vertexvert = {}
    for vertex in ob.data.loops:
        vertexvert[vertex.index] = vertex.vertex_index

    # posicion de cada vertice y cada face
    vertloc = {rounder(vert.co[:]): vert for vert in ob.data.vertices}
    faceloc = {rounder(poly.center[:]): poly for poly in ob.data.polygons}

    # relativo de cada vertice y cada face
    verteqind = {vert.index: vertloc.get(
                 absco(co),
                 vertloc[co]).index for co,
                 vert in vertloc.items() if co[0] <= 0}
    polyeq = {face: faceloc.get(
              absco(center),
              faceloc[center]) for center,
              face in faceloc.items() if center[0] <= 0}

    # loops in faces
    lif = {poly: [i for i in poly.loop_indices] for poly in ob.data.polygons}

    # acomoda
    for l, r in polyeq.items():
        if l.select:
            for lloop in lif[l]:
                for rloop in lif[r]:
                    if (verteqind[vertexvert[lloop]] == vertexvert[rloop] and
                            ob.data.uv_layers.active.data[rloop].select):

                        ob.data.uv_layers.active.data[
                            lloop].uv = ob.data.uv_layers.active.data[
                                rloop].uv

    bpy.ops.object.mode_set(mode=mode, toggle=False)

    print("Time elapsed: %4s seconds" % (time.time() - inicio))


class OscOverlapUv(Operator):
    """Overlaps the uvs on one side of the model symmetry plane. """ \
    """Useful to get more detail on fixed resolution bitmaps"""
    bl_idname = "mesh.overlap_uv_faces"
    bl_label = "Overlap Uvs"
    bl_options = {"REGISTER", "UNDO"}

    @classmethod
    def poll(cls, context):
        return (context.active_object is not None and
                context.active_object.type == 'MESH')

    presicion = IntProperty(
            default=4,
            min=1,
            max=10,
            name="precision"
            )

    def execute(self, context):
        DefOscOverlapUv(self.presicion)
        return {'FINISHED'}


# ------------------ PRINT VERTICES ----------------------

def dibuja_callback(self, context):
    font_id = 0
    bm = bmesh.from_edit_mesh(bpy.context.object.data)
    for v in bm.verts:
        cord = location_3d_to_region_2d(
            context.region,
            context.space_data.region_3d,
            self.matr * v.co)
        blf.position(font_id, cord[0], cord[1], 0)
        blf.size(font_id, self.tsize, 72)
        blf.draw(font_id, str(v.index))


class ModalIndexOperator(Operator):
    """Allow to visualize the index number for vertices in the viewport"""
    bl_idname = "view3d.modal_operator"
    bl_label = "Print Vertices"

    @classmethod
    def poll(cls, context):
        return (context.active_object is not None and
                context.active_object.type == 'MESH')

    def modal(self, context, event):
        context.area.tag_redraw()
        if event.type == 'MOUSEMOVE':
            self.x = event.mouse_region_x
            self.matr = context.object.matrix_world
        elif event.type == 'LEFTMOUSE':
            bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
            return {'FINISHED'}
        elif event.type == 'PAGE_UP':
            self.tsize += 1
        elif event.type == 'PAGE_DOWN':
            self.tsize -= 1
        elif event.type in {'RIGHTMOUSE', 'ESC', 'TAB'}:
            bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
            context.area.header_text_set()
            return {'CANCELLED'}

        return {'PASS_THROUGH'}

    def invoke(self, context, event):
        if context.area.type == "VIEW_3D":
            context.area.header_text_set("Esc: exit, PageUP/Down: text size")
            bpy.ops.object.mode_set(mode="EDIT")
            self.tsize = 20
            args = (self, context)
            self._handle = bpy.types.SpaceView3D.draw_handler_add(
                dibuja_callback, args, "WINDOW", "POST_PIXEL")
            context.window_manager.modal_handler_add(self)
            return{'RUNNING_MODAL'}
        else:
            self.report({"WARNING"}, "Is not a 3D Space")
            return {'CANCELLED'}


# -------------------------- SELECT DOUBLES

def SelDoubles(self, context):
    bm = bmesh.from_edit_mesh(bpy.context.object.data)

    for v in bm.verts:
        v.select = 0

    dictloc = {}

    rd = lambda x: (round(x[0], 4), round(x[1], 4), round(x[2], 4))

    for vert in bm.verts:
        dictloc.setdefault(rd(vert.co), []).append(vert.index)

    for loc, ind in dictloc.items():
        if len(ind) > 1:
            for v in ind:
                bm.verts[v].select = 1

    bpy.context.scene.objects.active = bpy.context.scene.objects.active


class SelectDoubles(Operator):
    """Selects duplicated vertex without merge them"""
    bl_idname = "mesh.select_doubles"
    bl_label = "Select Doubles"
    bl_options = {"REGISTER", "UNDO"}

    @classmethod
    def poll(cls, context):
        return (context.active_object is not None and
                context.active_object.type == 'MESH' and
                context.active_object.mode == "EDIT")

    def execute(self, context):
        SelDoubles(self, context)
        return {'FINISHED'}


# -------------------------- SELECT DOUBLES

def defLatticeMirror(self, context):

    ob = bpy.context.object
    u = ob.data.points_u
    v = ob.data.points_v
    w = ob.data.points_w
    total = u * v * w

    # guardo indices a cada punto
    libIndex = {point: index for point, index in zip(bpy.context.object.data.points, range(0, total))}

    # guardo puntos seleccionados
    selectionPoint = [libIndex[i] for i in ob.data.points if i.select]

    for point in selectionPoint:
        rango = list(range(int(point / u) * u, int(point / u) * u + (u)))
        rango.reverse()
        indPorcion = range(int(point / u) * u, int(point / u) * u + (u)).index(point)
        ob.data.points[rango[indPorcion]].co_deform.x = -ob.data.points[point].co_deform.x
        ob.data.points[rango[indPorcion]].co_deform.y = ob.data.points[point].co_deform.y
        ob.data.points[rango[indPorcion]].co_deform.z = ob.data.points[point].co_deform.z


class LatticeMirror(Operator):
    """Mirror Lattice"""
    bl_idname = "lattice.mirror_selected"
    bl_label = "Mirror Lattice"
    bl_options = {"REGISTER", "UNDO"}

    @classmethod
    def poll(cls, context):
        return (context.active_object is not None and
                context.active_object.type == 'LATTICE' and
                context.active_object.mode == "EDIT")

    def execute(self, context):
        defLatticeMirror(self, context)
        return {'FINISHED'}