Example #1
0
def compileMechanismList():
    """TODO Missing documentation"""
    from bpy.types import WindowManager
    from bpy.props import EnumProperty

    # DOCU missing some docstring

    global mechanismpreviewcollection

    log("Compiling mechanism list from local library...", "INFO")

    try:
        phobosconfig = bUtils.getPhobosConfigPath()
    except KeyError:
        log('Can not create mechanism preview. Phobos not registered.',
            'DEBUG')
        return

    imagefolderpath = os.path.join(phobosconfig, 'images', 'mechanisms')
    if imagefolderpath == '' or not os.path.exists(imagefolderpath):
        log('Visual mechanism representations could not be found.')
        return

    # read in mechanism thumbnails
    mechanismpreviewcollection = bpy.utils.previews.new()
    enum_items = []
    defaultimagepath = os.path.join(imagefolderpath, 'undefined.png')
    defaultpreview = mechanismpreviewcollection.load('undefined',
                                                     defaultimagepath, 'IMAGE')

    i = 1
    for mechanism in defs.definitions['submechanisms']:
        size = len(defs.definitions['submechanisms'][mechanism]['joints']
                   ['spanningtree'])
        imagepath = os.path.join(imagefolderpath, mechanism + '.png')
        if not (os.path.exists(imagepath) and os.path.isfile(imagepath)):
            log("No preview found, using default.", 'DEBUG')
            enum_items.append((mechanism, mechanism + ' [{0}] '.format(size),
                               "", defaultpreview.icon_id, i))
        else:
            log("Adding mechanism preview: " + imagepath, 'DEBUG')
            preview = mechanismpreviewcollection.load(mechanism, imagepath,
                                                      'IMAGE')
            enum_items.append((mechanism, mechanism + '[ {0}]'.format(size),
                               "", preview.icon_id, i))
        i += 1
    mechanismpreviewcollection.enum_items = enum_items

    # reregister the enumproperty to ensure new items are displayed
    WindowManager.mechanismpreview = EnumProperty(
        items=getMechanismListForEnumProperty, name='Mechanism')
Example #2
0
def importResources(restuple, filepath=None):
    """Accepts an iterable of iterables describing resource objects to import. For instance,
    reslist=(('joint', 'continuous'), ('interface', 'default', 'bidirectional'))
    would import the resource objects named 'joint_continuous' and
    'interface_default_bidirectional'.

    Args:
      restuple: iterable of iterables containing import objects
      filepath: path to file from which to load resource (Default value = None)
    Returns(tuple of bpy.types.Object): imported objects

    Returns:

    """
    currentscene = bpy.context.scene.name
    bUtils.switchToScene('resources')
    # avoid importing the same objects multiple times
    imported_objects = [
        nUtils.stripNamespaceFromName(obj.name)
        for obj in bpy.data.scenes['resources'].objects
    ]
    requested_objects = ['_'.join(resource) for resource in restuple]
    new_objects = [
        obj for obj in requested_objects if obj not in imported_objects
    ]

    # if no filepath is provided, use the path from the preferences
    if not filepath:
        filepath = os.path.join(bUtils.getPhobosConfigPath(), 'resources',
                                'resources.blend')
        print(filepath)

    # import new objects from resources.blend
    if new_objects:
        with bpy.data.libraries.load(filepath) as (data_from, data_to):
            objects = [{
                'name': name
            } for name in new_objects if name in data_from.objects]
            if objects:
                bpy.ops.wm.append(directory=filepath + "/Object/",
                                  files=objects)
            else:
                log('Resource objects could not be imported.', 'ERROR')
                bUtils.switchToScene(currentscene)
                return None
    objects = bpy.context.selected_objects
    for obj in objects:
        nUtils.addNamespace(obj, 'resource')
    bUtils.switchToScene(currentscene)
    return objects
Example #3
0
def compileMechanismList():
    """TODO Missing documentation"""
    from bpy.types import WindowManager
    from bpy.props import EnumProperty

    # DOCU missing some docstring

    global mechanismpreviewcollection

    log("Compiling mechanism list from local library...", "INFO")

    imagefolderpath = os.path.join(bUtils.getPhobosConfigPath(), 'images', 'mechanisms')
    if imagefolderpath == '' or not os.path.exists(imagefolderpath):
        log('Visual mechanism representations could not be found.')
        return

    # read in mechanism thumbnails
    mechanismpreviewcollection = bpy.utils.previews.new()
    enum_items = []
    defaultimagepath = os.path.join(imagefolderpath, 'undefined.png')
    defaultpreview = mechanismpreviewcollection.load('undefined', defaultimagepath, 'IMAGE')

    i = 1
    for mechanism in defs.definitions['submechanisms']:
        size = len(defs.definitions['submechanisms'][mechanism]['joints']['spanningtree'])
        imagepath = os.path.join(imagefolderpath, mechanism + '.png')
        if not (os.path.exists(imagepath) and os.path.isfile(imagepath)):
            log("No preview found, using default.", 'DEBUG')
            enum_items.append(
                (mechanism, mechanism + ' [{0}] '.format(size), "", defaultpreview.icon_id, i)
            )
        else:
            log("Adding mechanism preview: " + imagepath, 'DEBUG')
            preview = mechanismpreviewcollection.load(mechanism, imagepath, 'IMAGE')
            enum_items.append(
                (mechanism, mechanism + '[ {0}]'.format(size), "", preview.icon_id, i)
            )
        i += 1
    mechanismpreviewcollection.enum_items = enum_items

    # reregister the enumproperty to ensure new items are displayed
    WindowManager.mechanismpreview = EnumProperty(
        items=getMechanismListForEnumProperty, name='Mechanism'
    )
Example #4
0
def importResources(restuple, filepath=None):
    """Accepts an iterable of iterables describing resource objects to import. For instance,
    reslist=(('joint', 'continuous'), ('interface', 'default', 'bidirectional'))
    would import the resource objects named 'joint_continuous' and
    'interface_default_bidirectional'.

    Args:
      restuple: iterable of iterables containing import objects
      filepath: path to file from which to load resource (Default value = None)
    Returns(tuple of bpy.types.Object): imported objects

    Returns:

    """
    currentscene = bpy.context.scene.name
    bUtils.switchToScene('resources')
    # avoid importing the same objects multiple times
    imported_objects = [
        nUtils.stripNamespaceFromName(obj.name) for obj in bpy.data.scenes['resources'].objects
    ]
    requested_objects = ['_'.join(resource) for resource in restuple]
    new_objects = [obj for obj in requested_objects if obj not in imported_objects]

    # if no filepath is provided, use the path from the preferences
    if not filepath:
        filepath = os.path.join(bUtils.getPhobosConfigPath(), 'resources', 'resources.blend')
        print(filepath)

    # import new objects from resources.blend
    if new_objects:
        with bpy.data.libraries.load(filepath) as (data_from, data_to):
            objects = [{'name': name} for name in new_objects if name in data_from.objects]
            if objects:
                bpy.ops.wm.append(directory=filepath + "/Object/", files=objects)
            else:
                log('Resource objects could not be imported.', 'ERROR')
                bUtils.switchToScene(currentscene)
                return None
    objects = bpy.context.selected_objects
    for obj in objects:
        nUtils.addNamespace(obj, 'resource')
    bUtils.switchToScene(currentscene)
    return objects
Example #5
0
def compileModelList():
    """TODO Missing documentation"""
    from bpy.props import EnumProperty
    from bpy.types import WindowManager

    # DOCU missing some docstring
    log("Compiling model list from local library...", "INFO")

    # clear old preview collections
    for previews in model_previews.values():
        bpy.utils.previews.remove(previews)
    model_previews.clear()
    model_data.clear()

    try:
        rootpath = bUtils.getPhobosConfigPath().modelsfolder
    except KeyError:
        log('Can not create mechanism preview. Phobos not registered.',
            'DEBUG')
        return

    if rootpath == '' or not os.path.exists(rootpath):
        log('Model library folder does not exist.')
        return

    # parse the model folder
    i = 0
    for category in os.listdir(rootpath):
        categorypath = os.path.join(rootpath, category)
        # skip all non folders
        if not os.path.isdir(categorypath):
            continue

        # initialise new dictionaries
        model_data[category] = {}
        newpreviewcollection = bpy.utils.previews.new()
        enum_items = []

        # parse category folder
        for modelname in os.listdir(categorypath):
            modelpath = os.path.join(categorypath, modelname)

            # check for valid blender savefile in the model folder
            if os.path.exists(
                    os.path.join(modelpath, 'blender', modelname + '.blend')):
                model_data[category][modelname] = {'path': modelpath}

                # use existing thumbnail if available
                if os.path.exists(os.path.join(modelpath, 'thumbnails')):
                    previewpath = os.path.join(modelpath, 'thumbnails',
                                               modelname + '.png')
                    preview = newpreviewcollection.load(
                        modelname, previewpath, 'IMAGE')
                # otherwise create one from the blend file
                else:
                    previewpath = os.path.join(modelpath, 'blender',
                                               modelname + '.blend')
                    preview = newpreviewcollection.load(
                        modelname, previewpath, 'BLEND')
                log("Adding model to preview: " + previewpath, 'DEBUG')
                enum_items.append(
                    (modelname, modelname, "", preview.icon_id, i))
                i += 1
                categories.add(category)
        # save the category
        newpreviewcollection.enum_items = enum_items
        model_previews[category] = newpreviewcollection
        log("Finished parsing model folder. Imported {0} models.".format(i),
            'INFO')