Beispiel #1
0
def main():
    scn = Scene.GetCurrent()
    ob = scn.objects.active

    if not ob or ob.type != 'Mesh':
        Draw.PupMenu('Error, no active mesh object, aborting.')
        return

    me = ob.getData(mesh=1)
    act_group = me.activeGroup

    PREF_NAME = Draw.Create(act_group + '_copy')
    PREF_SEL_ONLY = Draw.Create(0)

    pup_block= [\
    ('', PREF_NAME, 0, 31, 'Name of group copy.'),\
    ('Only Selected', PREF_SEL_ONLY, 'Only include selected faces in the new grop.'),\
    ]

    if not Draw.PupBlock('New Name...', pup_block):
        return
    PREF_NAME = PREF_NAME.val
    PREF_SEL_ONLY = PREF_SEL_ONLY.val
    copy_act_vgroup(me, PREF_NAME, PREF_SEL_ONLY)

    try:
        me.activeGroup = PREF_NAME
    except:
        pass
Beispiel #2
0
def main():
    scn = Scene.GetCurrent()
    if not scn.objects.context:
        return

    PREF_LOC = Draw.Create(0.0)
    PREF_SIZE = Draw.Create(0.0)
    PREF_ROT = Draw.Create(0.0)
    PREF_LINK_AXIS = Draw.Create(0)
    PREF_X_AXIS = Draw.Create(1)
    PREF_Y_AXIS = Draw.Create(1)
    PREF_Z_AXIS = Draw.Create(1)

    pup_block = [\
    ('loc:', PREF_LOC, 0.0, 100.0, 'Amount to randomize the location'),\
    ('size:', PREF_SIZE, 0.0, 100.0,  'Amount to randomize the size'),\
    ('rot:', PREF_ROT, 0.0, 360.0, 'Amount to randomize the rotation'),\
    '',\
    ('Link Axis', PREF_LINK_AXIS, 'Use the same random value for each objects XYZ'),\
    ('X Axis', PREF_X_AXIS, 'Enable X axis randomization'),\
    ('Y Axis', PREF_Y_AXIS, 'Enable Y axis randomization'),\
    ('Z Axis', PREF_Z_AXIS, 'Enable Z axis randomization'),\
    ]

    if not Draw.PupBlock('Object Randomize', pup_block):
        return

    randomize(scn.objects.context, PREF_LOC.val, PREF_SIZE.val, PREF_ROT.val,
              PREF_LINK_AXIS.val, PREF_X_AXIS.val, PREF_Y_AXIS.val,
              PREF_Z_AXIS.val)
Beispiel #3
0
def x3d_export_ui(filename):
    if not filename.endswith(extension):
        filename += extension
    #if _safeOverwrite and sys.exists(filename):
    #	result = Draw.PupMenu("File Already Exists, Overwrite?%t|Yes%x1|No%x0")
    #if(result != 1):
    #	return

    # Get user options
    EXPORT_APPLY_MODIFIERS = Draw.Create(1)
    EXPORT_TRI = Draw.Create(0)
    EXPORT_GZIP = Draw.Create(filename.lower().endswith('.x3dz'))

    # Get USER Options
    pup_block = [\
    ('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data from each object.'),\
    ('Triangulate', EXPORT_TRI, 'Triangulate quads.'),\
    ('Compress', EXPORT_GZIP, 'GZip the resulting file, requires a full python install'),\
    ]

    if not Draw.PupBlock('Export...', pup_block):
        return

    Blender.Window.EditMode(0)
    Blender.Window.WaitCursor(1)

    x3d_export(filename,\
     EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val,\
     EXPORT_TRI = EXPORT_TRI.val,\
     EXPORT_GZIP = EXPORT_GZIP.val\
    )

    Blender.Window.WaitCursor(0)
Beispiel #4
0
def read_ui(filename):

    global guiTable, IMPORT_VC, IMPORT_UV
    guiTable = {'VC': 1, 'UV': 1}

    for s in Window.GetScreenInfo():
        Window.QHandle(s['id'])

    IMPORT_VC = Draw.Create(guiTable['VC'])
    IMPORT_UV = Draw.Create(guiTable['UV'])

    # Get USER Options
    pup_block = [
        ('Import Options'),
        ('Vertex Color', IMPORT_VC, 'Import Vertex Colors if exist'),
        ('UV', IMPORT_UV, 'Import UV if exist'),
    ]

    if not Draw.PupBlock('Import...', pup_block):
        return

    Window.WaitCursor(1)

    guiTable['VC'] = IMPORT_VC.val
    guiTable['UV'] = IMPORT_UV.val

    read_main(filename)

    Window.WaitCursor(0)
Beispiel #5
0
def main():
	scn= Scene.GetCurrent()
	ob= scn.objects.active
	
	if not ob or ob.type != 'Mesh':
		Draw.PupMenu('Error, no active mesh object, aborting.')
		return
	
	me= ob.getData(mesh=1)
	
	PREF_MAXDIST= Draw.Create(0.0)
	PREF_STRENGTH= Draw.Create(1.0)
	PREF_MODE= Draw.Create(0)
	PREF_ITERATIONS= Draw.Create(1)
	
	pup_block= [\
	('Bleed Dist:', PREF_MAXDIST, 0.0, 1.0, 'Set a distance limit for bleeding.'),\
	('Bleed Strength:', PREF_STRENGTH, 0.01, 1.0, 'Bleed strength between adjacent verts weight. 1:full, 0:None'),\
	('Iterations', PREF_ITERATIONS, 1, 20, 'Number of times to run the blending calculation.'),\
	('Contract (Shrink)', PREF_MODE, 'Shrink instead of growing.'),\
	]
	
	if not Draw.PupBlock('Grow/Shrink...', pup_block):
		return
	
	actWeightNormalize(me, PREF_MODE.val, PREF_MAXDIST.val, PREF_STRENGTH.val, PREF_ITERATIONS.val)
Beispiel #6
0
def main():
    scn = Scene.GetCurrent()
    ob = scn.objects.active

    if not ob or ob.type != 'Mesh':
        Draw.PupMenu('Error, no active mesh object, aborting.')
        return

    me = ob.getData(mesh=1)

    PREF_PEAKWEIGHT = Draw.Create(1.0)
    PREF_ACTIVE_ONLY = Draw.Create(1)
    PREF_KEEP_PROPORTION = Draw.Create(1)
    PREF_ARMATURE_ONLY = Draw.Create(0)

    pup_block= [\
    ('Peak Weight:', PREF_PEAKWEIGHT, 0.01, 1.0, 'Upper weight for normalizing.'),\
    ('Active Only', PREF_ACTIVE_ONLY, 'Only Normalize groups that have matching bones in an armature (when an armature is used).'),\
    ('Proportional', PREF_KEEP_PROPORTION, 'Scale other weights so verts (Keep weights with other groups in proportion).'),\
    ('Armature Only', PREF_ARMATURE_ONLY, 'Only Normalize groups that have matching bones in an armature (when an armature is used).'),\
    ]

    if not Draw.PupBlock('Clean Selected Meshes...', pup_block):
        return

    actWeightNormalize(me, ob, PREF_PEAKWEIGHT.val, PREF_ACTIVE_ONLY.val,
                       PREF_ARMATURE_ONLY.val, PREF_KEEP_PROPORTION.val)
def write_ui(filename):

    global guiTable, EXPORT_MOD, EXPORT_MTL, EXPORT_UV, EXPORT_VC, EXPORT_SELO, EXPORT_UVI, EXPORT_VG2SG
    guiTable = {
        'MOD': 1,
        'MTL': 1,
        'UV': 1,
        'VC': 1,
        'SELO': 1,
        'UVI': 0,
        'VG2SG': 1,
        'RECENTER': 0
    }

    EXPORT_MOD = Draw.Create(guiTable['MOD'])
    EXPORT_MTL = Draw.Create(guiTable['MTL'])
    EXPORT_UV = Draw.Create(guiTable['UV'])
    EXPORT_VC = Draw.Create(guiTable['VC'])
    EXPORT_SELO = Draw.Create(guiTable['SELO'])
    EXPORT_VG2SG = Draw.Create(guiTable['VG2SG'])
    EXPORT_REC = Draw.Create(guiTable['RECENTER'])

    # Get USER Options
    pup_block = [
        ('Mesh Options...'),
        ('Apply Modifiers', EXPORT_MOD,
         'Use modified mesh data from each object.'),
        ('Materials', EXPORT_MTL, 'Export Materials.'),
        ('Face UV', EXPORT_UV, 'Export texface UV coords.'),
        ('Vertex Colors', EXPORT_VC, 'Export vertex colors'), ('Context...'),
        ('Selection Only', EXPORT_SELO,
         'Only export objects in visible selection, else export all mesh object.'
         ), ('Bonus...'),
        ('VertGr. as SmoothGr.', EXPORT_VG2SG,
         'Make SmoothGroups by VertGroups. See doc.'),
        ('Center Objects', EXPORT_REC,
         'Center ALL objects to World-Grid-Origin-Center-Point-(0,0,0). ;)')
    ]

    if not Draw.PupBlock('Export...', pup_block):
        return

    Window.WaitCursor(1)

    guiTable['MOD'] = EXPORT_MOD.val
    guiTable['MTL'] = EXPORT_MTL.val
    guiTable['UV'] = EXPORT_UV.val
    guiTable['VC'] = EXPORT_VC.val
    guiTable['SELO'] = EXPORT_SELO.val
    guiTable['VG2SG'] = EXPORT_VG2SG.val
    guiTable['RECENTER'] = EXPORT_REC.val

    if not filename.lower().endswith('.ase'):
        filename += '.ase'

    write(filename)

    Window.WaitCursor(0)
Beispiel #8
0
def main():
    scn = bpy.data.scenes.active
    ob_sel = list(scn.objects.context)

    PREF_KEEP_ASPECT = False

    # Error Checking
    if len(ob_sel) < 2:
        Draw.PupMenu("Error%t|Select 2 mesh objects")
        return

    me_ob = scn.objects.active

    if not me_ob:
        Draw.PupMenu("Error%t|No active mesh selected.")

    try:
        ob_sel.remove(me_ob)
    except:
        pass

    if me_ob.type != 'Mesh':
        Draw.PupMenu(
            "Error%t|Active Object must be a mesh to write billboard images too"
        )
        return

    me_data = me_ob.getData(mesh=1)

    for f in me_data.faces:
        if len(f) != 4:
            Draw.PupMenu("Error%t|Active mesh must have only quads")
            return

    # Get user input
    block = [\
    'Image Pixel Size',\
    ("Packed Size: ", PREF_RES, 128, 2048, "Pixel width and height to render the billboard to"),\
    ("Tile Size: ", PREF_TILE_RES, 64, 1024, "Pixel  width and height for each tile to render to"),\
    'Render Settings',\
    ("Pack Final", PREF_IMG_PACK , "Pack the image for each face into images into a single image"),\
    ("Oversampling", PREF_AA , "Higher quality woth extra sampling"),\
    ("Alpha Clipping", PREF_ALPHA , "Render empty areas as transparent"),\
    ("Cam ZOffset: ", PREF_Z_OFFSET, 0.1, 100, "Distance to place the camera away from the quad when rendering")\
    ]

    if not Draw.PupBlock("Billboard Render", block):
        return

    # Set globals
    GLOBALS['ob_sel'] = ob_sel
    GLOBALS['me_ob'] = me_ob
    GLOBALS['me_data'] = me_data

    Blender.Window.FileSelector(save_billboard, 'SAVE BILLBOARD',
                                Blender.sys.makename(ext='.png'))
Beispiel #9
0
def show_popup():
    pup_block = [
        ('Selection Only', export_selection_only,
         'Only export objects in visible selection. Else export whole scene.'),
        ('Rotate +Z to +Y', export_rotate_z_to_y,
         'Rotate such that +Z axis (Blender up) becomes +Y (VRML up).'),
        ('Compress', export_compressed,
         'Generate a .wrz file (normal VRML compressed by gzip).')
    ]
    return Draw.PupBlock('Export VRML 97...', pup_block)
def button_event(evt):  # Вызывает функции для формирования таблицы и ввода
    global allPoints
    if evt == 1:  # 1 – идентификатор кнопки вызова
        x = Draw.Create(0)
        y = Draw.Create(0)  # Создание кнопок с начальными данными
        block = []  # Данные для формирования таблицы
        block.append(
            ("X= ", x, 0, 400))  #Ввод с ограничением границ и типа данных
        block.append(("Y= ", y, 0, 600))
        retVal = Draw.PupBlock("Line coords", block)  # Создание таблицы
        allPoints.append(x.val)
        allPoints.append(y.val)  # Извлечение данных
        print "data", allPoints
        Draw.Redraw(1)
        return
Beispiel #11
0
def button_event(evt):
    global x2, y2, r1
    if evt == 1:
        x = Draw.Create(x2)
        y = Draw.Create(y2)
        r = Draw.Create(r1)
        block = []
        block.append(("X= ", x, 0, 400))
        block.append(("Y= ", y, 0, 600))
        block.append(("R= ", r, 0, 600))
        retVal = Draw.PupBlock("Line coords and radius", block)
        x2 = x.val
        y2 = y.val
        r1 = r.val
        Draw.Redraw(1)
        return
Beispiel #12
0
def main():
	sce= bpy.data.scenes.active
	ob= sce.objects.active
	
	if not ob or ob.type != 'Mesh':
		Draw.PupMenu('Error, no active mesh object, aborting.')
		return
	
	me= ob.getData(mesh=1)
	
	PREF_BLUR_ITERATIONS= Draw.Create(1)	
	PREF_BLUR_RADIUS= Draw.Create(0.05)
	PREF_MIN_EDLEN= Draw.Create(0.01)
	PREF_CLAMP_CONCAVE= Draw.Create(90)
	PREF_CLAMP_CONVEX= Draw.Create(20)
	PREF_SHADOW_ONLY= Draw.Create(0)
	PREF_SEL_ONLY= Draw.Create(0)	
	pup_block= [\
	'Post AO Blur',\
	('  Iterations:', PREF_BLUR_ITERATIONS, 0, 40, 'Number times to blur the colors. (higher blurs more)'),\
	('  Blur Radius:', PREF_BLUR_RADIUS, 0.01, 40.0, 'How much distance effects blur transfur (higher blurs more).'),\
	('  Min EdgeLen:', PREF_MIN_EDLEN, 0.00001, 1.0, 'Minimim edge length to blur (very low values can cause errors).'),\
	'Angle Clipping',\
	('  Highlight Angle:', PREF_CLAMP_CONVEX, 0, 180, 'Less then 180 limits the angle used in the tonal range.'),\
	('  Shadow Angle:', PREF_CLAMP_CONCAVE, 0, 180, 'Less then 180 limits the angle used in the tonal range.'),\
	('Shadow Only', PREF_SHADOW_ONLY, 'Dont calculate highlights for convex areas.'),\
	('Sel Faces Only', PREF_SEL_ONLY, 'Only apply to UV/Face selected faces (mix vpain/uvface select).'),\
	]
	
	if not Draw.PupBlock('SelfShadow...', pup_block):
		return
	
	PREF_BLUR_ITERATIONS= PREF_BLUR_ITERATIONS.val
	PREF_BLUR_RADIUS= PREF_BLUR_RADIUS.val
	PREF_MIN_EDLEN= PREF_MIN_EDLEN.val
	PREF_CLAMP_CONCAVE= PREF_CLAMP_CONCAVE.val
	PREF_CLAMP_CONVEX= PREF_CLAMP_CONVEX.val
	PREF_SHADOW_ONLY= PREF_SHADOW_ONLY.val
	PREF_SEL_ONLY= PREF_SEL_ONLY.val
	
	if not me.vertexColors:
		me.vertexColors= 1
	
	t= sys.time()
	vertexFakeAO(me, PREF_BLUR_ITERATIONS, PREF_BLUR_RADIUS, PREF_MIN_EDLEN, PREF_CLAMP_CONCAVE, PREF_CLAMP_CONVEX, PREF_SHADOW_ONLY, PREF_SEL_ONLY)
	print 'done in %.6f' % (sys.time()-t)
Beispiel #13
0
def button_event(evt):
    if evt == 1:
        global yes

        global xy0
        global xy1
        global point0
        global point1
        global mddl

        global a
        global b

        X0 = Draw.Create(0)
        Y0 = Draw.Create(0)
        X1 = Draw.Create(0)
        Y1 = Draw.Create(0)
        A = Draw.Create(0)
        B = Draw.Create(0)

        block = []
        block.append(("X1= ", X0, 0, 1000))
        block.append(("Y1= ", Y0, 0, 1000))
        block.append(("X2= ", X1, 0, 1000))
        block.append(("Y2= ", Y1, 0, 1000))
        block.append(("A= ", A, -1000, 1000))
        block.append(("B= ", B, -1000, 1000))
        retVal = Draw.PupBlock("LINE'S POINTS", block)

        xy0[0] = X0.val
        xy0[1] = Y0.val
        xy1[0] = X1.val
        xy1[1] = Y1.val
        a = A.val
        b = B.val

        #LINE
        point0[0] = 1
        point0[1] = a * point0[0] + b

        point1[1] = 1000
        point1[0] = (point1[1] - b) / a

        yes = 1
        return
def main():
    sce = bpy.data.scenes.active
    ob = sce.objects.active

    if not ob or ob.type != 'Mesh':
        Draw.PupMenu('Error, no active mesh object, aborting.')
        return

    me = ob.getData(mesh=1)

    PREF_BLUR_ITERATIONS = Draw.Create(1)
    PREF_BLUR_STRENGTH = Draw.Create(0.5)
    PREF_CLAMP_CONCAVE = Draw.Create(90)
    PREF_CLAMP_CONVEX = Draw.Create(20)
    PREF_SHADOW_ONLY = Draw.Create(0)
    PREF_SEL_ONLY = Draw.Create(0)
    pup_block= [\
    'Post AO Blur',\
    ('Strength:', PREF_BLUR_STRENGTH, 0, 1, 'Blur strength per iteration'),\
    ('Iterations:', PREF_BLUR_ITERATIONS, 0, 40, 'Number times to blur the colors. (higher blurs more)'),\
    'Angle Clipping',\
    ('Highlight Angle:', PREF_CLAMP_CONVEX, 0, 180, 'Less then 180 limits the angle used in the tonal range.'),\
    ('Shadow Angle:', PREF_CLAMP_CONCAVE, 0, 180, 'Less then 180 limits the angle used in the tonal range.'),\
    ('Shadow Only', PREF_SHADOW_ONLY, 'Dont calculate highlights for convex areas.'),\
    ('Sel Faces Only', PREF_SEL_ONLY, 'Only apply to UV/Face selected faces (mix vpain/uvface select).'),\
    ]

    if not Draw.PupBlock('SelfShadow...', pup_block):
        return

    if not me.vertexColors:
        me.vertexColors = 1

    t = sys.time()
    vertexFakeAO(me, PREF_BLUR_ITERATIONS.val, \
         PREF_BLUR_STRENGTH.val, \
         PREF_CLAMP_CONCAVE.val, \
         PREF_CLAMP_CONVEX.val, \
         PREF_SHADOW_ONLY.val, \
         PREF_SEL_ONLY.val)

    if ob.modifiers:
        me.update()

    print 'done in %.6f' % (sys.time() - t)
Beispiel #15
0
def main():
	THICK = Draw.Create(0.02)

	if not Draw.PupBlock('Cube wireframe', [\
        ('Thick:', THICK, 0.0001, 10, 'Thickness of the skinned edges'),\

        ]):
                return

	# Gets the current scene, there can be many scenes in 1 blend file.
	sce = bpy.data.scenes.active
	
	# Get the active object, there can only ever be 1
	# and the active object is always the editmode object.
	ob_act = sce.objects.active
	
	if not ob_act or ob_act.type != 'Mesh':
		BPyMessages.Error_NoMeshActive()
		return 
	
	
	# Saves the editmode state and go's out of 
	# editmode if its enabled, we cant make
	# changes to the mesh data while in editmode.
	is_editmode = Window.EditMode()
	if is_editmode: Window.EditMode(0)
	
	Window.WaitCursor(1)
	me = ob_act.getData(mesh=1) # old NMesh api is default
	t = sys.time()
	
	# Run the mesh editing function
	create_wired_mesh(me, THICK.val/2.0)

	ob_act.select(False)
	
	# Restore editmode if it was enabled
	if is_editmode: Window.EditMode(1)

	# Timing the script is a good way to be aware on any speed hits when scripting
	print 'My Script finished in %.2f seconds' % (sys.time()-t)
	Window.WaitCursor(0)
def main():
    scn = Scene.GetCurrent()
    ob = scn.objects.active

    if not ob or ob.type != 'Mesh':
        Draw.PupMenu('Error, no active mesh object, aborting.')
        return

    me = ob.getData(mesh=1)

    PREF_TOLERENCE = Draw.Create(0.1)

    pup_block= [\
    ('Tolerence:', PREF_TOLERENCE, 0.01, 1.0, 'Tolerence for selecting faces of the same weight.'),\
    ]

    if not Draw.PupBlock('Select Same Weight...', pup_block):
        return

    PREF_TOLERENCE = PREF_TOLERENCE.val

    selSameWeights(me, PREF_TOLERENCE)
Beispiel #17
0
def main():
    scn = Scene.GetCurrent()
    ob = scn.objects.active

    if not ob or ob.type != 'Mesh':
        Draw.PupMenu('Error, no active mesh object, aborting.')
        return

    me = ob.getData(mesh=1)

    PREF_PEAKWEIGHT = Draw.Create(0.001)
    PREF_KEEP_SINGLE = Draw.Create(1)
    PREF_OTHER_GROUPS = Draw.Create(0)

    pup_block= [\
    ('Peak Weight:', PREF_PEAKWEIGHT, 0.005, 1.0, 'Remove verts from groups below this weight.'),\
    ('All Other Groups', PREF_OTHER_GROUPS, 'Clean all groups, not just the current one.'),\
    ('Keep Single User', PREF_KEEP_SINGLE, 'Keep verts in at least 1 group.'),\
    ]

    if not Draw.PupBlock('Clean Selected Meshes...', pup_block):
        return

    rem_count = weightClean(me, PREF_PEAKWEIGHT.val, PREF_KEEP_SINGLE.val,
                            PREF_OTHER_GROUPS.val)

    # Run on entire blend file. usefull sometimes but dont let users do it.
    '''
	rem_count = 0
	for ob in Object.Get():
		if ob.type != 'Mesh':
			continue
		me= ob.getData(mesh=1)
		
		rem_count += weightClean(me, PREF_PEAKWEIGHT.val, PREF_KEEP_SINGLE.val, PREF_OTHER_GROUPS.val)
	'''
    Draw.PupMenu('Removed %i verts from groups' % rem_count)
Beispiel #18
0
def write_ui(filename):
    if filename.lower().endswith('.svg'): filename = filename[:-4]

    PREF_SEP= Draw.Create(0)
    PREF_SCALE= Draw.Create(90)
    PREF_SPACE= Draw.Create(2.0)

    block = [\
        ("Separate Files", PREF_SEP, "Export each view axis as a seperate file"),\
        ("Space: ", PREF_SPACE, 0.0, 10.0, "Space between views in blender units"),\
        ("Scale: ", PREF_SCALE, 10, 100000, "Scale, 1200 is a good default")]

    if not Draw.PupBlock("Export SVG", block):
        return

    edges = []
    bounds = collect_edges(edges)

    if PREF_SEP.val:
        writexy(edges, bounds, filename + '_XY.svg', PREF_SCALE.val, PREF_SPACE.val)
        writexz(edges, bounds, filename + '_XZ.svg', PREF_SCALE.val, PREF_SPACE.val)
        writeyz(edges, bounds, filename + '_YZ.svg', PREF_SCALE.val, PREF_SPACE.val)

    writeall(edges, bounds, filename + '.svg', PREF_SCALE.val, PREF_SPACE.val)
Beispiel #19
0
        h.delRegion(image)
        h.panelimage().makeCurrent()
    elif r == 2:
        maxx = 2**int(log(image.size[0], 2))
        maxy = 2**int(log(image.size[1], 2))
        xoff = Draw.Create(0)
        yoff = Draw.Create(0)
        width = Draw.Create(min(maxx, 1024))
        height = Draw.Create(min(maxy, 1024))
        block = []
        block.append(('Left:', xoff, 0, image.size[0]))
        block.append(('Bottom:', yoff, 0, image.size[1]))
        block.append(('Width:', width, 0, maxx))
        block.append(('Height:', height, 0, maxy))

        while Draw.PupBlock('Create new region', block):
            if not width.val or not height.val or 2**int(
                    log(width.val, 2)) != width.val or 2**int(
                        log(height.val, 2)) != height.val:
                if isinstance(block[-1], tuple): block.extend(['', ''])
                block[-2] = 'Width & Height must'
                block[-1] = 'be powers of 2'
            elif xoff.val + width.val > image.size[0]:
                if isinstance(block[-1], tuple): block.extend(['', ''])
                block[-2] = 'Left + Width must'
                block[-1] = 'be less than %d' % image.size[0]
            elif yoff.val + height.val > image.size[1]:
                if isinstance(block[-1], tuple): block.extend(['', ''])
                block[-2] = 'Bottom + Height must'
                block[-1] = 'be less than %d' % image.size[1]
            else:
Beispiel #20
0
def edit_extern(image=None):

    if not image:
        image = Image.GetCurrent()

    if not image:  # Image is None
        Draw.PupMenu('ERROR: You must select an active Image.')
        return
    if image.packed:
        Draw.PupMenu('ERROR: Image is packed, unpack before editing.')
        return

    imageFileName = sys.expandpath(image.filename)

    if not sys.exists(imageFileName):
        Draw.PupMenu('ERROR: Image path does not exist.')
        return

    pupblock = [imageFileName.split('/')[-1].split('\\')[-1]]

    new_text = False
    try:
        appstring = Registry.GetKey('ExternalImageEditor', True)
        appstring = appstring['path']

        # for ZanQdo if he removed the path from the textbox totaly. ;) - Cam
        if not appstring or appstring.find('%f') == -1:
            new_text = True
    except:
        new_text = True

    if new_text:
        pupblock.append('first time, set path.')
        if platform == 'win32':
            appstring = 'start "" /B "%f"'
        elif platform == 'darwin':
            appstring = 'open "%f"'
        else:
            appstring = 'gimp-remote "%f"'

    appstring_but = Draw.Create(appstring)
    save_default_but = Draw.Create(0)

    pupblock.append(
        ('editor: ', appstring_but, 0, 48,
         'Path to application, %f will be replaced with the image path.'))
    pupblock.append(('Set Default', save_default_but,
                     'Store this path in the blender registry.'))

    # Only configure if Shift is held,
    if Blender.Window.GetKeyQualifiers() & Blender.Window.Qual.SHIFT:
        if not Draw.PupBlock('External Image Editor...', pupblock):
            return

    appstring = appstring_but.val
    save_default = save_default_but.val

    if save_default:
        Registry.SetKey('ExternalImageEditor', {'path': appstring}, True)

    if appstring.find('%f') == -1:
        Draw.PupMenu(
            'ERROR: The comment you entered did not contain the filename ("%f")'
        )
        return

    # -------------------------------

    appstring = appstring.replace('%f', imageFileName)
    print '\tediting image with command "%s"' % appstring
    os.system(appstring)
def main():

    sce = Scene.GetCurrent()

    ob_act = sce.objects.active

    if not ob_act:
        Draw.PupMenu("Error%t|no active object")
        return

    objects = list(sce.objects.context)

    try:
        objects.remove(ob_act)
    except:
        pass

    if not objects:
        Draw.PupMenu("Error%t|no objects selected")
        return

    curframe = Blender.Get('curframe')

    FRAME_START = Draw.Create(Blender.Get('staframe'))
    FRAME_END = Draw.Create(Blender.Get('endframe'))

    # Get USER Options
    pup_block= [\
    ('Start:', FRAME_START, 1, 300000, 'Use the active objects position starting at this frame'),\
    ('End:', FRAME_END, 1, 300000, 'Use the active objects position starting at this frame'),\
    ]

    if not Draw.PupBlock('Set timeoffset...', pup_block):
        return

    FRAME_START = FRAME_START.val
    FRAME_END = FRAME_END.val

    if FRAME_START >= FRAME_END:
        Draw.PupMenu("Error%t|frames are not valid")

    # Ok - all error checking
    locls_act = []
    for f in xrange((FRAME_END - FRAME_START)):
        i = FRAME_START + f
        Blender.Set('curframe', i)
        locls_act.append(ob_act.matrixWorld.translationPart())

    for ob in objects:
        loc = ob.matrixWorld.translationPart()
        best_frame = -1
        best_dist = 100000000
        for i, loc_act in enumerate(locls_act):
            dist = (loc_act - loc).length
            if dist < best_dist:
                best_dist = dist
                best_frame = i + FRAME_START

        ob.timeOffset = float(best_frame)

    # Set the original frame
    Blender.Set('curframe', curframe)
Beispiel #22
0
	cam = Camera.New('persp', 'TCam')
	camob = scn.objects.new(cam)
	scn.objects.camera = camob
	camob.setLocation(Window.GetCursorPos())

if camob:
	
	target = scn.objects.new('Empty', (camob.name + '.target'))
	matrix = camob.getMatrix()
	tvect = Mathutils.Vector([0,0,-10])
	targetv = tvect*matrix
	target.setLocation(targetv)
	
	cam = camob.data
	#cam.drawLimits = 1
	cam.drawSize = 2.0
	campos = Mathutils.Vector([camob.dloc[0],camob.dloc[1],camob.dloc[2]])
	dofdistv = campos-targetv
	dofdist = dofdistv.length
	#cam.dofDist = dofdist
	cam.clipEnd = 1500
	const = camob.constraints.append(Constraint.Type.TRACKTO)
	const[Constraint.Settings.TARGET] = target
	const[Constraint.Settings.TRACK] = Constraint.Settings.TRACKNEGZ
	const[Constraint.Settings.UP] = Constraint.Settings.UPY
	scn.update()
else:
	block = []
	block.append("")
	msg = Draw.PupBlock("No Camera in Scene !!", block)
def main():
    global USER_FILL_HOLES
    global USER_FILL_HOLES_QUALITY
    global USER_STRETCH_ASPECT
    global USER_ISLAND_MARGIN

    objects = bpy.data.scenes.active.objects

    # we can will tag them later.
    obList = [ob for ob in objects.context if ob.type == 'Mesh']

    # Face select object may not be selected.
    ob = objects.active
    if ob and ob.sel == 0 and ob.type == 'Mesh':
        # Add to the list
        obList = [ob]
    del objects

    if not obList:
        Draw.PupMenu('error, no selected mesh objects')
        return

    # Create the variables.
    USER_PROJECTION_LIMIT = Draw.Create(66)
    USER_ONLY_SELECTED_FACES = Draw.Create(1)
    USER_SHARE_SPACE = Draw.Create(1)  # Only for hole filling.
    USER_STRETCH_ASPECT = Draw.Create(1)  # Only for hole filling.
    USER_ISLAND_MARGIN = Draw.Create(0.0)  # Only for hole filling.
    USER_FILL_HOLES = Draw.Create(0)
    USER_FILL_HOLES_QUALITY = Draw.Create(50)  # Only for hole filling.
    USER_VIEW_INIT = Draw.Create(0)  # Only for hole filling.
    USER_AREA_WEIGHT = Draw.Create(1)  # Only for hole filling.


    pup_block = [\
    'Projection',\
    ('Angle Limit:', USER_PROJECTION_LIMIT, 1, 89, 'lower for more projection groups, higher for less distortion.'),\
    ('Selected Faces Only', USER_ONLY_SELECTED_FACES, 'Use only selected faces from all selected meshes.'),\
    ('Init from view', USER_VIEW_INIT, 'The first projection will be from the view vector.'),\
    ('Area Weight', USER_AREA_WEIGHT, 'Weight projections vector by face area.'),\
    '',\
    '',\
    '',\
    'UV Layout',\
    ('Share Tex Space', USER_SHARE_SPACE, 'Objects Share texture space, map all objects into 1 uvmap.'),\
    ('Stretch to bounds', USER_STRETCH_ASPECT, 'Stretch the final output to texture bounds.'),\
    ('Island Margin:', USER_ISLAND_MARGIN, 0.0, 0.5, 'Margin to reduce bleed from adjacent islands.'),\
    'Fill in empty areas',\
    ('Fill Holes', USER_FILL_HOLES, 'Fill in empty areas reduced texture waistage (slow).'),\
    ('Fill Quality:', USER_FILL_HOLES_QUALITY, 1, 100, 'Depends on fill holes, how tightly to fill UV holes, (higher is slower)'),\
    ]

    # Reuse variable
    if len(obList) == 1:
        ob = "Unwrap %i Selected Mesh"
    else:
        ob = "Unwrap %i Selected Meshes"

    # HACK, loop until mouse is lifted.
    '''
	while Window.GetMouseButtons() != 0:
		sys.sleep(10)
	'''

    if not Draw.PupBlock(ob % len(obList), pup_block):
        return
    del ob

    # Convert from being button types
    USER_PROJECTION_LIMIT = USER_PROJECTION_LIMIT.val
    USER_ONLY_SELECTED_FACES = USER_ONLY_SELECTED_FACES.val
    USER_SHARE_SPACE = USER_SHARE_SPACE.val
    USER_STRETCH_ASPECT = USER_STRETCH_ASPECT.val
    USER_ISLAND_MARGIN = USER_ISLAND_MARGIN.val
    USER_FILL_HOLES = USER_FILL_HOLES.val
    USER_FILL_HOLES_QUALITY = USER_FILL_HOLES_QUALITY.val
    USER_VIEW_INIT = USER_VIEW_INIT.val
    USER_AREA_WEIGHT = USER_AREA_WEIGHT.val

    USER_PROJECTION_LIMIT_CONVERTED = cos(USER_PROJECTION_LIMIT * DEG_TO_RAD)
    USER_PROJECTION_LIMIT_HALF_CONVERTED = cos(
        (USER_PROJECTION_LIMIT / 2) * DEG_TO_RAD)

    # Toggle Edit mode
    is_editmode = Window.EditMode()
    if is_editmode:
        Window.EditMode(0)
    # Assume face select mode! an annoying hack to toggle face select mode because Mesh dosent like faceSelectMode.

    if USER_SHARE_SPACE:
        # Sort by data name so we get consistant results
        try:
            obList.sort(key=lambda ob: ob.getData(name_only=1))
        except:
            obList.sort(lambda ob1, ob2: cmp(ob1.getData(name_only=1),
                                             ob2.getData(name_only=1)))

        collected_islandList = []

    Window.WaitCursor(1)

    time1 = sys.time()

    # Tag as False se we dont operate on teh same mesh twice.
    bpy.data.meshes.tag = False

    for ob in obList:
        me = ob.getData(mesh=1)

        if me.tag or me.lib:
            continue

        # Tag as used
        me.tag = True

        if not me.faceUV:  # Mesh has no UV Coords, dont bother.
            me.faceUV = True

        if USER_ONLY_SELECTED_FACES:
            meshFaces = [thickface(f) for f in me.faces if f.sel]
        else:
            meshFaces = map(thickface, me.faces)

        if not meshFaces:
            continue

        Window.DrawProgressBar(
            0.1, 'SmartProj UV Unwrapper, mapping "%s", %i faces.' %
            (me.name, len(meshFaces)))

        # =======
        # Generate a projection list from face normals, this is ment to be smart :)

        # make a list of face props that are in sync with meshFaces
        # Make a Face List that is sorted by area.
        # meshFaces = []

        # meshFaces.sort( lambda a, b: cmp(b.area , a.area) ) # Biggest first.
        try:
            meshFaces.sort(key=lambda a: -a.area)
        except:
            meshFaces.sort(lambda a, b: cmp(b.area, a.area))

        # remove all zero area faces
        while meshFaces and meshFaces[-1].area <= SMALL_NUM:
            # Set their UV's to 0,0
            for uv in meshFaces[-1].uv:
                uv.zero()
            meshFaces.pop()

        # Smallest first is slightly more efficient, but if the user cancels early then its better we work on the larger data.

        # Generate Projection Vecs
        # 0d is   1.0
        # 180 IS -0.59846

        # Initialize projectVecs
        if USER_VIEW_INIT:
            # Generate Projection
            projectVecs = [
                Vector(Window.GetViewVector()) *
                ob.matrixWorld.copy().invert().rotationPart()
            ]  # We add to this allong the way
        else:
            projectVecs = []

        newProjectVec = meshFaces[0].no
        newProjectMeshFaces = []  # Popping stuffs it up.

        # Predent that the most unique angke is ages away to start the loop off
        mostUniqueAngle = -1.0

        # This is popped
        tempMeshFaces = meshFaces[:]

        # This while only gathers projection vecs, faces are assigned later on.
        while 1:
            # If theres none there then start with the largest face

            # add all the faces that are close.
            for fIdx in xrange(len(tempMeshFaces) - 1, -1, -1):
                # Use half the angle limit so we dont overweight faces towards this
                # normal and hog all the faces.
                if newProjectVec.dot(tempMeshFaces[fIdx].no
                                     ) > USER_PROJECTION_LIMIT_HALF_CONVERTED:
                    newProjectMeshFaces.append(tempMeshFaces.pop(fIdx))

            # Add the average of all these faces normals as a projectionVec
            averageVec = Vector(0, 0, 0)
            if USER_AREA_WEIGHT:
                for fprop in newProjectMeshFaces:
                    averageVec += (fprop.no * fprop.area)
            else:
                for fprop in newProjectMeshFaces:
                    averageVec += fprop.no

            if averageVec.x != 0 or averageVec.y != 0 or averageVec.z != 0:  # Avoid NAN
                projectVecs.append(averageVec.normalize())

            # Get the next vec!
            # Pick the face thats most different to all existing angles :)
            mostUniqueAngle = 1.0  # 1.0 is 0d. no difference.
            mostUniqueIndex = 0  # dummy

            for fIdx in xrange(len(tempMeshFaces) - 1, -1, -1):
                angleDifference = -1.0  # 180d difference.

                # Get the closest vec angle we are to.
                for p in projectVecs:
                    temp_angle_diff = p.dot(tempMeshFaces[fIdx].no)

                    if angleDifference < temp_angle_diff:
                        angleDifference = temp_angle_diff

                if angleDifference < mostUniqueAngle:
                    # We have a new most different angle
                    mostUniqueIndex = fIdx
                    mostUniqueAngle = angleDifference

            if mostUniqueAngle < USER_PROJECTION_LIMIT_CONVERTED:
                #print 'adding', mostUniqueAngle, USER_PROJECTION_LIMIT, len(newProjectMeshFaces)
                # Now weight the vector to all its faces, will give a more direct projection
                # if the face its self was not representive of the normal from surrounding faces.

                newProjectVec = tempMeshFaces[mostUniqueIndex].no
                newProjectMeshFaces = [tempMeshFaces.pop(mostUniqueIndex)]

            else:
                if len(projectVecs) >= 1:  # Must have at least 2 projections
                    break

        # If there are only zero area faces then its possible
        # there are no projectionVecs
        if not len(projectVecs):
            Draw.PupMenu(
                'error, no projection vecs where generated, 0 area faces can cause this.'
            )
            return

        faceProjectionGroupList = [[] for i in xrange(len(projectVecs))]

        # MAP and Arrange # We know there are 3 or 4 faces here

        for fIdx in xrange(len(meshFaces) - 1, -1, -1):
            fvec = meshFaces[fIdx].no
            i = len(projectVecs)

            # Initialize first
            bestAng = fvec.dot(projectVecs[0])
            bestAngIdx = 0

            # Cycle through the remaining, first alredy done
            while i - 1:
                i -= 1

                newAng = fvec.dot(projectVecs[i])
                if newAng > bestAng:  # Reverse logic for dotvecs
                    bestAng = newAng
                    bestAngIdx = i

            # Store the area for later use.
            faceProjectionGroupList[bestAngIdx].append(meshFaces[fIdx])

        # Cull faceProjectionGroupList,

        # Now faceProjectionGroupList is full of faces that face match the project Vecs list
        for i in xrange(len(projectVecs)):
            # Account for projectVecs having no faces.
            if not faceProjectionGroupList[i]:
                continue

            # Make a projection matrix from a unit length vector.
            MatProj = VectoMat(projectVecs[i])

            # Get the faces UV's from the projected vertex.
            for f in faceProjectionGroupList[i]:
                f_uv = f.uv
                for j, v in enumerate(f.v):
                    f_uv[j][:] = (MatProj * v.co)[:2]

        if USER_SHARE_SPACE:
            # Should we collect and pack later?
            islandList = getUvIslands(faceProjectionGroupList, me)
            collected_islandList.extend(islandList)

        else:
            # Should we pack the islands for this 1 object?
            islandList = getUvIslands(faceProjectionGroupList, me)
            packIslands(islandList)

        # update the mesh here if we need to.

    # We want to pack all in 1 go, so pack now
    if USER_SHARE_SPACE:
        Window.DrawProgressBar(0.9, "Box Packing for all objects...")
        packIslands(collected_islandList)

    print "Smart Projection time: %.2f" % (sys.time() - time1)
    # Window.DrawProgressBar(0.9, "Smart Projections done, time: %.2f sec." % (sys.time() - time1))

    if is_editmode:
        Window.EditMode(1)

    Window.DrawProgressBar(1.0, "")
    Window.WaitCursor(0)
    Window.RedrawAll()
Beispiel #24
0
def main():
    scn = Scene.GetCurrent()
    act_ob = scn.objects.active
    if not act_ob or act_ob.type != 'Mesh':
        BPyMessages.Error_NoMeshActive()
        return

    act_me = act_ob.getData(mesh=1)

    if act_me.multires:
        BPyMessages.Error_NoMeshMultiresEdit()
        return

    act_group = act_me.activeGroup
    if not act_group: act_group = ''

    # Defaults
    PREF_REDUX = Draw.Create(0.5)
    PREF_BOUNDRY_WEIGHT = Draw.Create(5.0)
    PREF_REM_DOUBLES = Draw.Create(1)
    PREF_FACE_AREA_WEIGHT = Draw.Create(1.0)
    PREF_FACE_TRIANGULATE = Draw.Create(1)

    VGROUP_INF_ENABLE = Draw.Create(0)
    VGROUP_INF_REDUX = Draw.Create(act_group)
    VGROUP_INF_WEIGHT = Draw.Create(10.0)

    PREF_DO_UV = Draw.Create(1)
    PREF_DO_VCOL = Draw.Create(1)
    PREF_DO_WEIGHTS = Draw.Create(1)
    PREF_OTHER_SEL_OBS = Draw.Create(0)

    pup_block = [\
    ('Poly Reduce:', PREF_REDUX, 0.05, 0.95, 'Scale the meshes poly count by this value.'),\
    ('Boundry Weight:', PREF_BOUNDRY_WEIGHT, 0.0, 20.0, 'Weight boundry verts by this scale, 0.0 for no boundry weighting.'),\
    ('Area Weight:', PREF_FACE_AREA_WEIGHT, 0.0, 20.0, 'Collapse edges effecting lower area faces first.'),\
    ('Triangulate', PREF_FACE_TRIANGULATE, 'Convert quads to tris before reduction, for more choices of edges to collapse.'),\
    '',\
    ('VGroup Weighting', VGROUP_INF_ENABLE, 'Use a vertex group to influence the reduction, higher weights for higher quality '),\
    ('vgroup name: ', VGROUP_INF_REDUX, 0, 32, 'The name of the vertex group to use for the weight map'),\
    ('vgroup mult: ', VGROUP_INF_WEIGHT, 0.0, 100.0, 'How much to make the weight effect the reduction'),\
    ('Other Selected Obs', PREF_OTHER_SEL_OBS, 'reduce other selected objects.'),\
    '',\
    '',\
    '',\
    ('UV Coords', PREF_DO_UV, 'Interpolate UV Coords.'),\
    ('Vert Colors', PREF_DO_VCOL, 'Interpolate Vertex Colors'),\
    ('Vert Weights', PREF_DO_WEIGHTS, 'Interpolate Vertex Weights'),\
    ('Remove Doubles', PREF_REM_DOUBLES, 'Remove doubles before reducing to avoid boundry tearing.'),\
    ]

    if not Draw.PupBlock("Poly Reducer", pup_block):
        return

    PREF_REDUX = PREF_REDUX.val
    PREF_BOUNDRY_WEIGHT = PREF_BOUNDRY_WEIGHT.val
    PREF_REM_DOUBLES = PREF_REM_DOUBLES.val
    PREF_FACE_AREA_WEIGHT = PREF_FACE_AREA_WEIGHT.val
    PREF_FACE_TRIANGULATE = PREF_FACE_TRIANGULATE.val

    VGROUP_INF_ENABLE = VGROUP_INF_ENABLE.val
    VGROUP_INF_WEIGHT = VGROUP_INF_WEIGHT.val

    if VGROUP_INF_ENABLE and VGROUP_INF_WEIGHT:
        VGROUP_INF_REDUX = VGROUP_INF_REDUX.val
    else:
        VGROUP_INF_WEIGHT = 0.0
        VGROUP_INF_REDUX = None

    PREF_DO_UV = PREF_DO_UV.val
    PREF_DO_VCOL = PREF_DO_VCOL.val
    PREF_DO_WEIGHTS = PREF_DO_WEIGHTS.val
    PREF_OTHER_SEL_OBS = PREF_OTHER_SEL_OBS.val

    t = sys.time()

    is_editmode = Window.EditMode()  # Exit Editmode.
    if is_editmode: Window.EditMode(0)
    Window.WaitCursor(1)
    print 'reducing:', act_ob.name, act_ob.getData(1)
    BPyMesh.redux(act_ob, PREF_REDUX, PREF_BOUNDRY_WEIGHT, PREF_REM_DOUBLES,
                  PREF_FACE_AREA_WEIGHT, PREF_FACE_TRIANGULATE, PREF_DO_UV,
                  PREF_DO_VCOL, PREF_DO_WEIGHTS, VGROUP_INF_REDUX,
                  VGROUP_INF_WEIGHT)

    if PREF_OTHER_SEL_OBS:
        for ob in scn.objects.context:
            if ob.type == 'Mesh' and ob != act_ob:
                print 'reducing:', ob.name, ob.getData(1)
                BPyMesh.redux(ob, PREF_REDUX, PREF_BOUNDRY_WEIGHT,
                              PREF_REM_DOUBLES, PREF_FACE_AREA_WEIGHT,
                              PREF_FACE_TRIANGULATE, PREF_DO_UV, PREF_DO_VCOL,
                              PREF_DO_WEIGHTS, VGROUP_INF_REDUX,
                              VGROUP_INF_WEIGHT)
                Window.RedrawAll()

    if is_editmode: Window.EditMode(1)
    Window.WaitCursor(0)
    Window.RedrawAll()

    print 'Reduction done in %.6f sec.' % (sys.time() - t)
Beispiel #25
0
def main():
    scn = Scene.GetCurrent()
    act_ob = scn.getActiveObject()
    if act_ob.getType() != 'Mesh':
        act_ob = None

    sel = [
        ob for ob in Object.GetSelected() if ob.getType() == 'Mesh'
        if ob != act_ob
    ]
    if not sel and not act_ob:
        Draw.PupMenu('Error, select a mesh as your active object')
        return

    # Defaults
    PREF_EDITMESH_ONLY = Draw.Create(1)
    PREF_MIRROR_LOCATION = Draw.Create(1)
    PREF_XMID_SNAP = Draw.Create(1)
    PREF_MAX_DIST = Draw.Create(0.02)
    PREF_XZERO_THRESH = Draw.Create(0.002)

    #PREF_MODE= Draw.Create(0) # THIS IS TOOO CONFUSING, HAVE 2 BUTTONS AND MAKE THE MODE FROM THEM.
    PREF_MODE_L2R = Draw.Create(1)
    PREF_MODE_R2L = Draw.Create(0)

    PREF_SEL_ONLY = Draw.Create(1)
    PREF_EDGE_USERS = Draw.Create(0)
    # Weights
    PREF_MIRROR_WEIGHTS = Draw.Create(0)
    PREF_FLIP_NAMES = Draw.Create(1)
    PREF_CREATE_FLIP_NAMES = Draw.Create(1)

    pup_block = [\
    ('EditMesh Only', PREF_EDITMESH_ONLY, 'If disabled, will mirror all selected meshes.'),\
    'Left (-), Right (+)',\
    ('Left > Right', PREF_MODE_L2R, 'Copy from the Left to Right of the mesh. Enable Both for a mid loc/weight.'),\
    ('Right > Left', PREF_MODE_R2L, 'Copy from the Right to Left of the mesh. Enable Both for a mid loc/weight.'),\
    '',\
    ('MaxDist:', PREF_MAX_DIST, 0.0, 1.0, 'Generate interpolated verts so closer vert weights can be copied.'),\
    ('XZero limit:', PREF_XZERO_THRESH, 0.0, 1.0, 'Mirror verts above this distance from the middle, else lock to X/zero.'),\
    ('Sel Verts Only', PREF_SEL_ONLY, 'Only mirror selected verts. Else try and mirror all'),\
    ('Edge Users', PREF_EDGE_USERS, 'Only match up verts that have the same number of edge users.'),\
    'Location Prefs',\
    ('Mirror Location', PREF_MIRROR_LOCATION, 'Mirror vertex locations.'),\
    ('XMidSnap Verts', PREF_XMID_SNAP, 'Snap middle verts to X Zero (uses XZero limit)'),\
    'Weight Prefs',\
    ('Mirror Weights', PREF_MIRROR_WEIGHTS, 'Mirror vertex locations.'),\
    ('Flip Groups', PREF_FLIP_NAMES, 'Mirror flip names.'),\
    ('New Flip Groups', PREF_CREATE_FLIP_NAMES, 'Make new groups for flipped names.'),\
    ]

    if not Draw.PupBlock("X Mirror mesh tool", pup_block):
        return

    # WORK OUT THE MODE 0
    # PREF_MODE, 0:middle, 1: Left. 2:Right.
    PREF_MODE_R2L = PREF_MODE_R2L.val
    PREF_MODE_L2R = PREF_MODE_L2R.val

    if PREF_MODE_R2L and PREF_MODE_L2R:
        PREF_MODE = 0  # Middle
    elif not PREF_MODE_R2L and PREF_MODE_L2R:
        PREF_MODE = 1  # Left to Right
    elif PREF_MODE_R2L and not PREF_MODE_L2R:
        PREF_MODE = 2  # Right to Left
    else:  # Neither Selected. Do middle anyway
        PREF_MODE = 0

    PREF_EDITMESH_ONLY = PREF_EDITMESH_ONLY.val
    PREF_MIRROR_LOCATION = PREF_MIRROR_LOCATION.val
    PREF_XMID_SNAP = PREF_XMID_SNAP.val
    PREF_MAX_DIST = PREF_MAX_DIST.val
    PREF_XZERO_THRESH = PREF_XZERO_THRESH.val
    PREF_SEL_ONLY = PREF_SEL_ONLY.val
    PREF_EDGE_USERS = PREF_EDGE_USERS.val
    # weights
    PREF_MIRROR_WEIGHTS = PREF_MIRROR_WEIGHTS.val
    PREF_FLIP_NAMES = PREF_FLIP_NAMES.val
    PREF_CREATE_FLIP_NAMES = PREF_CREATE_FLIP_NAMES.val

    t = sys.time()

    is_editmode = Window.EditMode()  # Exit Editmode.
    if is_editmode: Window.EditMode(0)
    Mesh.Mode(Mesh.SelectModes['VERTEX'])
    Window.WaitCursor(1)

    if act_ob:
        mesh_mirror(act_ob.getData(mesh=1), PREF_MIRROR_LOCATION,
                    PREF_XMID_SNAP, PREF_MAX_DIST, PREF_XZERO_THRESH,
                    PREF_MODE, PREF_SEL_ONLY, PREF_EDGE_USERS,
                    PREF_MIRROR_WEIGHTS, PREF_FLIP_NAMES,
                    PREF_CREATE_FLIP_NAMES)
    if (not PREF_EDITMESH_ONLY) and sel:
        for ob in sel:
            mesh_mirror(ob.getData(mesh=1), PREF_MIRROR_LOCATION,
                        PREF_XMID_SNAP, PREF_MAX_DIST, PREF_XZERO_THRESH,
                        PREF_MODE, PREF_SEL_ONLY, PREF_EDGE_USERS,
                        PREF_MIRROR_WEIGHTS, PREF_FLIP_NAMES,
                        PREF_CREATE_FLIP_NAMES)

    if is_editmode: Window.EditMode(1)
    Window.WaitCursor(0)
    Window.DrawProgressBar(1.0, '')
    Window.RedrawAll()

    print 'Mirror done in %.6f sec.' % (sys.time() - t)
def file_callback(filename):

    if not filename.lower().endswith('.submesh'):
        filename += '.submesh'

    scn = bpy.data.scenes.active
    ob = scn.objects.active
    if not ob:
        Blender.Draw.PupMenu('Error%t|Select 1 active object')
        return

    file = open(filename, 'wb')

    EXPORT_APPLY_MODIFIERS = Draw.Create(1)
    EXPORT_NORMALS = Draw.Create(1)
    EXPORT_UV = Draw.Create(1)
    EXPORT_COLORS = Draw.Create(1)
    #EXPORT_EDGES = Draw.Create(0)

    pup_block = [\
    ('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data.'),\
    ('Normals', EXPORT_NORMALS, 'Export vertex normal data.'),\
    ('UVs', EXPORT_UV, 'Export texface UV coords.'),\
    ('Colors', EXPORT_COLORS, 'Export vertex Colors.'),\
	#('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\
    ]

    if not Draw.PupBlock('Export...', pup_block):
        return

    is_editmode = Blender.Window.EditMode()
    if is_editmode:
        Blender.Window.EditMode(0, '', 0)

    Window.WaitCursor(1)

    EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val
    EXPORT_NORMALS = EXPORT_NORMALS.val
    EXPORT_UV = EXPORT_UV.val
    EXPORT_COLORS = EXPORT_COLORS.val
    #EXPORT_EDGES = EXPORT_EDGES.val

    mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, False,
                                     scn)

    if not mesh:
        Blender.Draw.PupMenu(
            'Error%t|Could not get mesh data from active object')
        return

    mesh.transform(ob.matrixWorld)

    faceUV = mesh.faceUV
    vertexUV = mesh.vertexUV
    vertexColors = mesh.vertexColors

    if (not faceUV) and (not vertexUV): EXPORT_UV = False
    if not vertexColors: EXPORT_COLORS = False

    if not EXPORT_UV: faceUV = vertexUV = False
    if not EXPORT_COLORS: vertexColors = False

    # incase
    color = uvcoord = uvcoord_key = normal = normal_key = None

    verts = []  # list of dictionaries
    # vdict = {} # (index, normal, uv) -> new index
    vdict = [{} for i in xrange(len(mesh.verts))]
    vert_count = 0
    for i, f in enumerate(mesh.faces):
        smooth = f.smooth
        if not smooth:
            normal = tuple(f.no)
            normal_key = rvec3d(normal)

        if faceUV: uv = f.uv
        if vertexColors: col = f.col
        for j, v in enumerate(f):
            if smooth:
                normal = tuple(v.no)
                normal_key = rvec3d(normal)

            if faceUV:
                uvcoord = uv[j][0], 1.0 - uv[j][1]
                uvcoord_key = rvec2d(uvcoord)
            elif vertexUV:
                uvcoord = v.uvco[0], 1.0 - v.uvco[1]
                uvcoord_key = rvec2d(uvcoord)

            if vertexColors: color = col[j].r, col[j].g, col[j].b

            key = normal_key, uvcoord_key, color

            vdict_local = vdict[v.index]

            if (not vdict_local) or (not vdict_local.has_key(key)):
                vdict_local[key] = vert_count
                verts.append((tuple(v.co), normal, uvcoord, color))
                vert_count += 1

    file.write('SUBMESHTEXT0001\n')
    file.write(
        '#Created by Blender3D %s - www.blender.org, source file: %s\n' %
        (Blender.Get('version'),
         Blender.Get('filename').split('/')[-1].split('\\')[-1]))

    #file.write('element vertex %d\n' % len(verts))
    file.write('vertex format: position:3,texture0:2,normal:3\n')
    file.write('vertex count: %d\n' % len(verts))

    for i, v in enumerate(verts):
        file.write('[%.6f,%.6f,%.6f]' % v[0])  # co
        #if EXPORT_UV:
        file.write(' [%.6f,%.6f]' % v[2])  # uv
        #if EXPORT_NORMALS:
        file.write(' [%.6f,%.6f,%.6f]' % v[1])  # no

        #if EXPORT_COLORS:
        #	file.write('%u %u %u' % v[3]) # col
        file.write('\n')

    triangles = []
    for (i, f) in enumerate(mesh.faces):
        #file.write('%d ' % len(f))
        smooth = f.smooth
        if not smooth: no = rvec3d(f.no)

        if faceUV: uv = f.uv
        if vertexColors: col = f.col

        if (len(f) == 3):
            triangle = []
            for j, v in enumerate(f):
                if f.smooth: normal = rvec3d(v.no)
                else: normal = no
                if faceUV: uvcoord = rvec2d((uv[j][0], 1.0 - uv[j][1]))
                elif vertexUV: uvcoord = rvec2d((v.uvco[0], 1.0 - v.uvco[1]))
                if vertexColors: color = col[j].r, col[j].g, col[j].b

                triangle += [vdict[v.index][normal, uvcoord, color]]
            triangles += [triangle]
            #file.write('%d ' % vdict[v.index][normal, uvcoord, color])
            #file.write('\n')
        else:
            x = []
            for j, v in enumerate(f):
                if f.smooth: normal = rvec3d(v.no)
                else: normal = no
                if faceUV: uvcoord = rvec2d((uv[j][0], 1.0 - uv[j][1]))
                elif vertexUV: uvcoord = rvec2d((v.uvco[0], 1.0 - v.uvco[1]))
                if vertexColors: color = col[j].r, col[j].g, col[j].b

                #file.write('%d ' % vdict[v.index][normal, uvcoord, color])
                x += [vdict[v.index][normal, uvcoord, color]]
            triangles += [[x[1], x[2], x[0]]]
            triangles += [[x[2], x[3], x[0]]]
            #file.write('[%d,%d,%d]\n'%())
            #file.write('[%d,%d,%d]\n'%(x[1],x[2],x[3]))

    file.write('triangle count: %d\n' % len(triangles))
    for (i, f) in enumerate(triangles):
        file.write('[%d,' % f[0])
        file.write('%d,' % f[1])
        file.write('%d]\n' % f[2])

    file.close()

    if is_editmode:
        Blender.Window.EditMode(1, '', 0)
Beispiel #27
0
def dxf_export_ui(filepath):
	global	ONLYSELECTED,\
	POLYLINES,\
	ONLYFACES,\
	POLYFACES,\
	FLATTEN,\
	HIDDEN_MODE,\
	SCALE_FACTOR

	print '\n\nDXF-Export %s -----------------------' %__version__
	#filepath = 'blend_test.dxf'
	# Dont overwrite
	if not BPyMessages.Warning_SaveOver(filepath):
		print 'Aborted by user: nothing exported'
		return
	#test():return


	PREF_ONLYSELECTED= Draw.Create(ONLYSELECTED)
	PREF_POLYLINES= Draw.Create(POLYLINES)
	PREF_ONLYFACES= Draw.Create(ONLYFACES)
	PREF_POLYFACES= Draw.Create(POLYFACES)
	PREF_FLATTEN= Draw.Create(FLATTEN)
	PREF_HIDDEN_MODE= Draw.Create(HIDDEN_MODE)
	PREF_SCALE_FACTOR= Draw.Create(SCALE_FACTOR)
	PREF_HELP= Draw.Create(0)
	block = [\
	("only selected", PREF_ONLYSELECTED, "export only selected geometry"),\
	("global Scale:", PREF_SCALE_FACTOR, 0.001, 1000, "set global Scale factor for exporting geometry"),\
	("only faces", PREF_ONLYFACES, "from mesh-objects export only faces, otherwise only edges"),\
	("write POLYFACE", PREF_POLYFACES, "export mesh to POLYFACE, otherwise to 3DFACEs"),\
	("write POLYLINEs", PREF_POLYLINES, "export curve to POLYLINE, otherwise to LINEs"),\
	("3D-View to Flat", PREF_FLATTEN, "flatten geometry according current 3d-View"),\
	("Hidden Mode", PREF_HIDDEN_MODE, "filter out hidden lines"),\
	#(''),\
	("online Help", PREF_HELP, "calls DXF-Exporter Manual Page on Wiki.Blender.org"),\
	]
	
	if not Draw.PupBlock("DXF-Exporter %s" %__version__[:10], block): return

	if PREF_HELP.val!=0:
		try:
			import webbrowser
			webbrowser.open('http://wiki.blender.org/index.php?title=Scripts/Manual/Export/autodesk_dxf')
		except:
			Draw.PupMenu('DXF Exporter: %t|no connection to manual-page on Blender-Wiki!	try:|\
http://wiki.blender.org/index.php?title=Scripts/Manual/Export/autodesk_dxf')
		return

	ONLYSELECTED = PREF_ONLYSELECTED.val
	POLYLINES = PREF_POLYLINES.val
	ONLYFACES = PREF_ONLYFACES.val
	POLYFACES = PREF_POLYFACES.val
	FLATTEN = PREF_FLATTEN.val
	HIDDEN_MODE = PREF_HIDDEN_MODE.val
	SCALE_FACTOR = PREF_SCALE_FACTOR.val

	sce = Scene.GetCurrent()
	if ONLYSELECTED: sel_group = sce.objects.selected
	else: sel_group = sce.objects

	if sel_group: do_export(sel_group, filepath)
	else:
		print "Abort: selection was empty, no object to export!"
		Draw.PupMenu('DXF Exporter:   nothing exported!|empty selection!')
Beispiel #28
0
def write_ui(filename):
	
	if not filename.lower().endswith('.obj'):
		filename += '.obj'
	
	if not BPyMessages.Warning_SaveOver(filename):
		return
	
	EXPORT_APPLY_MODIFIERS = Draw.Create(1)
	EXPORT_ROTX90 = Draw.Create(1)
	EXPORT_TRI = Draw.Create(1)
	EXPORT_EDGES = Draw.Create(1)
	EXPORT_NORMALS = Draw.Create(1)
	EXPORT_NORMALS_HQ = Draw.Create(1)
	EXPORT_UV = Draw.Create(1)
	EXPORT_MTL = Draw.Create(1)
	EXPORT_SEL_ONLY = Draw.Create(1)
	EXPORT_ALL_SCENES = Draw.Create(0)
	EXPORT_ANIMATION = Draw.Create(0)
	EXPORT_COPY_IMAGES = Draw.Create(0)
	EXPORT_BLEN_OBS = Draw.Create(1)
	EXPORT_GROUP_BY_OB = Draw.Create(1)
	EXPORT_GROUP_BY_MAT = Draw.Create(0)
	EXPORT_MORPH_TARGET = Draw.Create(0)
	EXPORT_VERTEX_GROUPS = Draw.Create(1)
	EXPORT_ARMATURE = Draw.Create(1)
	
	# removed too many options are bad!
	
	# Get USER Options
	pup_block = [\
	('Context...'),\
	('Selection Only', EXPORT_SEL_ONLY, 'Only export objects in visible selection. Else export whole scene.'),\
	('All Scenes', EXPORT_ALL_SCENES, 'Each scene as a separate OBJ file.'),\
	('Animation', EXPORT_ANIMATION, 'Each frame as a numbered OBJ file.'),\
	('Object Prefs...'),\
	('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data from each object. May break vert order for morph targets.'),\
	('Rotate X90', EXPORT_ROTX90 , 'Rotate on export so Blenders UP is translated into OBJs UP'),\
	('Morph Target', EXPORT_MORPH_TARGET, 'Keep vert and face order, disables some other options.'),\
	('Extra Data...'),\
	('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\
	('Normals', EXPORT_NORMALS, 'Export vertex normal data (Ignored on import).'),\
	('High Quality Normals', EXPORT_NORMALS_HQ, 'Calculate high quality normals for rendering.'),\
	('UVs', EXPORT_UV, 'Export texface UV coords.'),\
	('Materials', EXPORT_MTL, 'Write a separate MTL file with the OBJ.'),\
	('Copy Images', EXPORT_COPY_IMAGES, 'Copy image files to the export directory, never overwrite.'),\
	('Triangulate', EXPORT_TRI, 'Triangulate quads.'),\
	('Grouping...'),\
	('Objects', EXPORT_BLEN_OBS, 'Export blender objects as "OBJ objects".'),\
	('Object Groups', EXPORT_GROUP_BY_OB, 'Export blender objects as "OBJ Groups".'),\
	('Material Groups', EXPORT_GROUP_BY_MAT, 'Group by materials.'),\
	('Vertex Groups', EXPORT_VERTEX_GROUPS, 'Add influences & Weights.'),\
	('Armature', EXPORT_ARMATURE, 'Export Armature'),\
	]
	
	if not Draw.PupBlock('Export...', pup_block):
		return
	
	if EXPORT_MORPH_TARGET.val:
		EXPORT_BLEN_OBS.val = False
		EXPORT_GROUP_BY_OB.val = False
		EXPORT_GROUP_BY_MAT.val = False
		EXPORT_GROUP_BY_MAT.val = False
		EXPORT_APPLY_MODIFIERS.val = False
	
	Window.EditMode(0)
	Window.WaitCursor(1)
	
	EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val
	EXPORT_ROTX90 = EXPORT_ROTX90.val
	EXPORT_TRI = EXPORT_TRI.val
	EXPORT_EDGES = EXPORT_EDGES.val
	EXPORT_NORMALS = EXPORT_NORMALS.val
	EXPORT_NORMALS_HQ = EXPORT_NORMALS_HQ.val
	EXPORT_UV = EXPORT_UV.val
	EXPORT_MTL = EXPORT_MTL.val
	EXPORT_SEL_ONLY = EXPORT_SEL_ONLY.val
	EXPORT_ALL_SCENES = EXPORT_ALL_SCENES.val
	EXPORT_ANIMATION = EXPORT_ANIMATION.val
	EXPORT_COPY_IMAGES = EXPORT_COPY_IMAGES.val
	EXPORT_BLEN_OBS = EXPORT_BLEN_OBS.val
	EXPORT_GROUP_BY_OB = EXPORT_GROUP_BY_OB.val
	EXPORT_GROUP_BY_MAT = EXPORT_GROUP_BY_MAT.val
	EXPORT_MORPH_TARGET = EXPORT_MORPH_TARGET.val
	EXPORT_VERTEX_GROUPS = EXPORT_VERTEX_GROUPS.val
	EXPORT_ARMATURE = EXPORT_ARMATURE.val
	
	
	
	base_name, ext = splitExt(filename)
	context_name = [base_name, '', '', ext] # basename, scene_name, framenumber, extension
	
	# Use the options to export the data using write()
	# def write(filename, objects, EXPORT_EDGES=False, EXPORT_NORMALS=False, EXPORT_MTL=True, EXPORT_COPY_IMAGES=False, EXPORT_APPLY_MODIFIERS=True):
	orig_scene = Scene.GetCurrent()
	if EXPORT_ALL_SCENES:
		export_scenes = Scene.Get()
	else:
		export_scenes = [orig_scene]
	
	# Export all scenes.
	for scn in export_scenes:
		scn.makeCurrent() # If alredy current, this is not slow.
		context = scn.getRenderingContext()
		orig_frame = Blender.Get('curframe')
		
		if EXPORT_ALL_SCENES: # Add scene name into the context_name
			context_name[1] = '_%s' % BPySys.cleanName(scn.name) # WARNING, its possible that this could cause a collision. we could fix if were feeling parranoied.
		
		# Export an animation?
		if EXPORT_ANIMATION:
			scene_frames = xrange(context.startFrame(), context.endFrame()+1) # up to and including the end frame.
		else:
			scene_frames = [orig_frame] # Dont export an animation.
		
		# Loop through all frames in the scene and export.
		for frame in scene_frames:
			if EXPORT_ANIMATION: # Add frame to the filename.
				context_name[2] = '_%.6d' % frame
			
			Blender.Set('curframe', frame)
			if EXPORT_SEL_ONLY:
				export_objects = scn.objects.context
			else:   
				export_objects = scn.objects
			
			full_path= ''.join(context_name)
			
			# erm... bit of a problem here, this can overwrite files when exporting frames. not too bad.
			# EXPORT THE FILE.
			write(full_path, export_objects,\
			EXPORT_TRI, EXPORT_EDGES, EXPORT_NORMALS,\
			EXPORT_NORMALS_HQ, EXPORT_UV, EXPORT_MTL,\
			EXPORT_COPY_IMAGES, EXPORT_APPLY_MODIFIERS,\
			EXPORT_ROTX90, EXPORT_BLEN_OBS,\
			EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_MORPH_TARGET, EXPORT_ARMATURE)
		
		Blender.Set('curframe', orig_frame)
	
	# Restore old active scene.
	orig_scene.makeCurrent()
	Window.WaitCursor(0)
def file_callback(filename):

    if not filename.lower().endswith('.ctm'):
        filename += '.ctm'

    # Get object mesh from the selected object
    scn = bpy.data.scenes.active
    ob = scn.objects.active
    if not ob:
        Blender.Draw.PupMenu('Error%t|Select 1 active object')
        return
    mesh = BPyMesh.getMeshFromObject(ob, None, False, False, scn)
    if not mesh:
        Blender.Draw.PupMenu(
            'Error%t|Could not get mesh data from active object')
        return

    # Check which mesh properties are present...
    hasVertexUV = mesh.vertexUV or mesh.faceUV
    hasVertexColors = mesh.vertexColors

    # Show a GUI for the export settings
    pupBlock = []
    EXPORT_APPLY_MODIFIERS = Draw.Create(1)
    pupBlock.append(('Apply Modifiers', EXPORT_APPLY_MODIFIERS,
                     'Use transformed mesh data.'))
    EXPORT_NORMALS = Draw.Create(1)
    pupBlock.append(('Normals', EXPORT_NORMALS, 'Export vertex normal data.'))
    if hasVertexUV:
        EXPORT_UV = Draw.Create(1)
        pupBlock.append(('UVs', EXPORT_UV, 'Export texface UV coords.'))
    if hasVertexColors:
        EXPORT_COLORS = Draw.Create(1)
        pupBlock.append(('Colors', EXPORT_COLORS, 'Export vertex Colors.'))
    EXPORT_MG2 = Draw.Create(0)
    pupBlock.append(
        ('Fixed Point', EXPORT_MG2,
         'Use limited precision algorithm (MG2 method = better compression).'))
    if not Draw.PupBlock('Export...', pupBlock):
        return

    # Adjust export settings according to GUI selections
    EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val
    EXPORT_NORMALS = EXPORT_NORMALS.val
    if hasVertexUV:
        EXPORT_UV = EXPORT_UV.val
    else:
        EXPORT_UV = False
    if hasVertexColors:
        EXPORT_COLORS = EXPORT_COLORS.val
    else:
        EXPORT_COLORS = False
    EXPORT_MG2 = EXPORT_MG2.val

    # If the user wants to export MG2, then show another GUI...
    if EXPORT_MG2:
        pupBlock = []
        EXPORT_VPREC = Draw.Create(0.01)
        pupBlock.append(('Vertex', EXPORT_VPREC, 0.0001, 1.0,
                         'Relative vertex precision (fixed point).'))
        if EXPORT_NORMALS:
            EXPORT_NPREC = Draw.Create(1.0 / 256.0)
            pupBlock.append(('Normal', EXPORT_NPREC, 0.0001, 1.0,
                             'Normal precision (fixed point).'))
        if EXPORT_UV:
            EXPORT_UVPREC = Draw.Create(1.0 / 1024.0)
            pupBlock.append(('UV', EXPORT_UVPREC, 0.0001, 1.0,
                             'UV precision (fixed point).'))
        if EXPORT_COLORS:
            EXPORT_CPREC = Draw.Create(1.0 / 256.0)
            pupBlock.append(('Color', EXPORT_CPREC, 0.0001, 1.0,
                             'Color precision (fixed point).'))
        if not Draw.PupBlock('Fixed point precision...', pupBlock):
            return

    # Adjust export settings according to GUI selections
    if EXPORT_MG2:
        EXPORT_VPREC = EXPORT_VPREC.val
    else:
        EXPORT_VPREC = 0.1
    if EXPORT_MG2 and EXPORT_NORMALS:
        EXPORT_NPREC = EXPORT_NPREC.val
    else:
        EXPORT_NPREC = 0.1
    if EXPORT_MG2 and EXPORT_UV:
        EXPORT_UVPREC = EXPORT_UVPREC.val
    else:
        EXPORT_UVPREC = 0.1
    if EXPORT_MG2 and EXPORT_COLORS:
        EXPORT_CPREC = EXPORT_CPREC.val
    else:
        EXPORT_CPREC = 0.1

    is_editmode = Blender.Window.EditMode()
    if is_editmode:
        Blender.Window.EditMode(0, '', 0)
    Window.WaitCursor(1)
    try:
        # Get the mesh, again, if we wanted modifiers (from GUI selection)
        if EXPORT_APPLY_MODIFIERS:
            mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS,
                                             False, scn)
            if not mesh:
                Blender.Draw.PupMenu(
                    'Error%t|Could not get mesh data from active object')
                return
            mesh.transform(ob.matrixWorld, True)

        # Count triangles (quads count as two triangles)
        triangleCount = 0
        for f in mesh.faces:
            if len(f.v) == 4:
                triangleCount += 2
            else:
                triangleCount += 1

        # Extract indices from the Blender mesh (quads are split into two triangles)
        pindices = cast((c_int * 3 * triangleCount)(), POINTER(c_int))
        i = 0
        for f in mesh.faces:
            pindices[i] = c_int(f.v[0].index)
            pindices[i + 1] = c_int(f.v[1].index)
            pindices[i + 2] = c_int(f.v[2].index)
            i += 3
            if len(f.v) == 4:
                pindices[i] = c_int(f.v[0].index)
                pindices[i + 1] = c_int(f.v[2].index)
                pindices[i + 2] = c_int(f.v[3].index)
                i += 3

        # Extract vertex array from the Blender mesh
        vertexCount = len(mesh.verts)
        pvertices = cast((c_float * 3 * vertexCount)(), POINTER(c_float))
        i = 0
        for v in mesh.verts:
            pvertices[i] = c_float(v.co.x)
            pvertices[i + 1] = c_float(v.co.y)
            pvertices[i + 2] = c_float(v.co.z)
            i += 3

        # Extract normals
        if EXPORT_NORMALS:
            pnormals = cast((c_float * 3 * vertexCount)(), POINTER(c_float))
            i = 0
            for v in mesh.verts:
                pnormals[i] = c_float(v.no.x)
                pnormals[i + 1] = c_float(v.no.y)
                pnormals[i + 2] = c_float(v.no.z)
                i += 3
        else:
            pnormals = POINTER(c_float)()

        # Extract UVs
        if EXPORT_UV:
            ptexCoords = cast((c_float * 2 * vertexCount)(), POINTER(c_float))
            if mesh.faceUV:
                for f in mesh.faces:
                    for j, v in enumerate(f.v):
                        k = v.index
                        if k < vertexCount:
                            uv = f.uv[j]
                            ptexCoords[k * 2] = uv[0]
                            ptexCoords[k * 2 + 1] = uv[1]
            else:
                i = 0
                for v in mesh.verts:
                    ptexCoords[i] = c_float(v.uvco[0])
                    ptexCoords[i + 1] = c_float(v.uvco[1])
                    i += 2
        else:
            ptexCoords = POINTER(c_float)()

        # Extract colors
        if EXPORT_COLORS:
            pcolors = cast((c_float * 4 * vertexCount)(), POINTER(c_float))
            for f in mesh.faces:
                for j, v in enumerate(f.v):
                    k = v.index
                    if k < vertexCount:
                        col = f.col[j]
                        pcolors[k * 4] = col.r / 255.0
                        pcolors[k * 4 + 1] = col.g / 255.0
                        pcolors[k * 4 + 2] = col.b / 255.0
                        pcolors[k * 4 + 3] = 1.0
        else:
            pcolors = POINTER(c_float)()

        # Load the OpenCTM shared library
        if os.name == 'nt':
            libHDL = WinDLL('openctm.dll')
        else:
            libName = find_library('openctm')
            if not libName:
                Blender.Draw.PupMenu(
                    'Could not find the OpenCTM shared library')
                return
            libHDL = CDLL(libName)
        if not libHDL:
            Blender.Draw.PupMenu('Could not open the OpenCTM shared library')
            return

        # Get all the functions from the shared library that we need
        ctmNewContext = libHDL.ctmNewContext
        ctmNewContext.argtypes = [c_int]
        ctmNewContext.restype = c_void_p
        ctmFreeContext = libHDL.ctmFreeContext
        ctmFreeContext.argtypes = [c_void_p]
        ctmGetError = libHDL.ctmGetError
        ctmGetError.argtypes = [c_void_p]
        ctmGetError.restype = c_int
        ctmErrorString = libHDL.ctmErrorString
        ctmErrorString.argtypes = [c_int]
        ctmErrorString.restype = c_char_p
        ctmFileComment = libHDL.ctmFileComment
        ctmFileComment.argtypes = [c_void_p, c_char_p]
        ctmDefineMesh = libHDL.ctmDefineMesh
        ctmDefineMesh.argtypes = [
            c_void_p,
            POINTER(c_float), c_int,
            POINTER(c_int), c_int,
            POINTER(c_float)
        ]
        ctmSave = libHDL.ctmSave
        ctmSave.argtypes = [c_void_p, c_char_p]
        ctmAddUVMap = libHDL.ctmAddUVMap
        ctmAddUVMap.argtypes = [c_void_p, POINTER(c_float), c_char_p, c_char_p]
        ctmAddUVMap.restype = c_int
        ctmAddAttribMap = libHDL.ctmAddAttribMap
        ctmAddAttribMap.argtypes = [c_void_p, POINTER(c_float), c_char_p]
        ctmAddAttribMap.restype = c_int
        ctmCompressionMethod = libHDL.ctmCompressionMethod
        ctmCompressionMethod.argtypes = [c_void_p, c_int]
        ctmVertexPrecisionRel = libHDL.ctmVertexPrecisionRel
        ctmVertexPrecisionRel.argtypes = [c_void_p, c_float]
        ctmNormalPrecision = libHDL.ctmNormalPrecision
        ctmNormalPrecision.argtypes = [c_void_p, c_float]
        ctmUVCoordPrecision = libHDL.ctmUVCoordPrecision
        ctmUVCoordPrecision.argtypes = [c_void_p, c_int, c_float]
        ctmAttribPrecision = libHDL.ctmAttribPrecision
        ctmAttribPrecision.argtypes = [c_void_p, c_int, c_float]

        # Create an OpenCTM context
        ctm = ctmNewContext(0x0102)  # CTM_EXPORT
        try:
            # Set the file comment
            ctmFileComment(
                ctm,
                c_char_p('%s - created by Blender %s (www.blender.org)' %
                         (ob.getName(), Blender.Get('version'))))

            # Define the mesh
            ctmDefineMesh(ctm, pvertices, c_int(vertexCount), pindices,
                          c_int(triangleCount), pnormals)

            # Add UV coordinates?
            if EXPORT_UV:
                tm = ctmAddUVMap(ctm, ptexCoords, c_char_p(), c_char_p())
                if EXPORT_MG2:
                    ctmUVCoordPrecision(ctm, tm, EXPORT_UVPREC)

            # Add colors?
            if EXPORT_COLORS:
                cm = ctmAddAttribMap(ctm, pcolors, c_char_p('Color'))
                if EXPORT_MG2:
                    ctmAttribPrecision(ctm, cm, EXPORT_CPREC)

            # Set compression method
            if EXPORT_MG2:
                ctmCompressionMethod(ctm, 0x0203)  # CTM_METHOD_MG2
                ctmVertexPrecisionRel(ctm, EXPORT_VPREC)
                if EXPORT_NORMALS:
                    ctmNormalPrecision(ctm, EXPORT_NPREC)

            else:
                ctmCompressionMethod(ctm, 0x0202)  # CTM_METHOD_MG1

            # Save the file
            ctmSave(ctm, c_char_p(filename))

            # Check for errors
            e = ctmGetError(ctm)
            if e != 0:
                s = ctmErrorString(e)
                Blender.Draw.PupMenu('Error%t|Could not save the file: ' + s)

        finally:
            # Free the OpenCTM context
            ctmFreeContext(ctm)

    finally:
        Window.WaitCursor(0)
        if is_editmode:
            Blender.Window.EditMode(1, '', 0)
Beispiel #30
0
def main():

    NAME_DATA = Draw.Create('')
    NAME_INGROUP = Draw.Create('')
    NAME_DUPGROUP = Draw.Create('')
    NAME_IMAGE = Draw.Create('')
    NAME_MATERIAL = Draw.Create('')
    NAME_TEXTURE = Draw.Create('')

    PREF_CASESENS = Draw.Create(False)
    PREF_PART_MATCH = Draw.Create(True)

    # Get USER Options
    pup_block= [\
    ('ObData:', NAME_DATA, 0, 32, 'Match with the objects data name'),\
    ('InGroup:', NAME_INGROUP, 0, 32, 'Match with the group name to find one of its objects'),\
    ('DupGroup:', NAME_DUPGROUP, 0, 32, 'Match with the group name to find an object that instances this group'),\
    ('Image:', NAME_IMAGE, 0, 32, 'Match with the image name to find an object that uses this image'),\
    ('Material:', NAME_MATERIAL, 0, 32, 'Match with the material name to find an object that uses this material'),\
    ('Texture:', NAME_TEXTURE, 0, 32, 'Match with the texture name to find an object that uses this texture'),\
    ('Case Sensitive', PREF_CASESENS, 'Do a case sensitive comparison?'),\
    ('Partial Match', PREF_PART_MATCH, 'Match when only a part of the text is in the data name'),\
    ]

    if not Draw.PupBlock('Find object using dataname...', pup_block):
        return

    NAME_DATA = NAME_DATA.val
    NAME_INGROUP = NAME_INGROUP.val
    NAME_DUPGROUP = NAME_DUPGROUP.val
    NAME_IMAGE = NAME_IMAGE.val
    NAME_MATERIAL = NAME_MATERIAL.val
    NAME_TEXTURE = NAME_TEXTURE.val

    PREF_CASESENS = PREF_CASESENS.val
    PREF_PART_MATCH = PREF_PART_MATCH.val

    if not PREF_CASESENS:
        NAME_DATA = NAME_DATA.lower()
        NAME_INGROUP = NAME_INGROUP.lower()
        NAME_DUPGROUP = NAME_DUPGROUP.lower()
        NAME_IMAGE = NAME_IMAGE.lower()
        NAME_MATERIAL = NAME_MATERIAL.lower()
        NAME_TEXTURE = NAME_TEXTURE.lower()

    def activate(ob, scn):
        bpy.data.scenes.active = scn
        scn.objects.selected = []
        scn.Layers = ob.Layers & (1 << 20) - 1
        ob.sel = 1

    def name_cmp(name_search, name_found):
        if name_found == None: return False
        if not PREF_CASESENS: name_found = name_found.lower()
        if PREF_PART_MATCH:
            if name_search in name_found:
                # print name_found, name_search
                return True
        else:
            if name_found == name_search:
                # print name_found, name_search
                return True

        return False

    if NAME_INGROUP:
        # Best we speed this up.
        bpy.data.objects.tag = False

        ok = False
        for group in bpy.data.groups:
            if name_cmp(NAME_INGROUP, group.name):
                for ob in group.objects:
                    ob.tag = True
                    ok = True
        if not ok:
            Draw.PupMenu('No Objects Found')
            return

    for scn in bpy.data.scenes:
        for ob in scn.objects:
            if NAME_DATA:
                if name_cmp(NAME_DATA, ob.getData(1)):
                    activate(ob, scn)
                    return
            if NAME_INGROUP:
                # Crap and slow but not much we can do about that
                '''
				for group in bpy.data.groups:
					if name_cmp(NAME_INGROUP, group.name):
						for ob_group in group.objects:
							if ob == ob_group:
								activate(ob, scn)
								return
				'''
                # Use speedup, this is in a group whos name matches.
                if ob.tag:
                    activate(ob, scn)
                    return

            if NAME_DUPGROUP:
                if ob.DupGroup and name_cmp(NAME_DUPGROUP, ob.DupGroup.name):
                    activate(ob, scn)
                    return

            if NAME_IMAGE:
                for img in get_object_images(ob):
                    if name_cmp(NAME_IMAGE, img.name) or name_cmp(
                            NAME_IMAGE,
                            img.filename.split('\\')[-1].split('/')[-1]):
                        activate(ob, scn)
                        return
            if NAME_MATERIAL or NAME_TEXTURE:
                try:
                    materials = ob.getData(mesh=1).materials
                except:
                    materials = []

                # Add object materials
                materials.extend(ob.getMaterials())

                for mat in materials:
                    if mat:
                        if NAME_MATERIAL:
                            if name_cmp(NAME_MATERIAL, mat.name):
                                activate(ob, scn)
                                return
                        if NAME_TEXTURE:
                            for mtex in mat.getTextures():
                                if mtex:
                                    tex = mtex.tex
                                    if tex:
                                        if name_cmp(NAME_TEXTURE, tex.name):
                                            activate(ob, scn)
                                            return

    Draw.PupMenu('No Objects Found')