Exemplo n.º 1
0
    def poll(self, context):
        """

        Args:
          context: 

        Returns:

        """
        result = False
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose
        root = None
        # TODO delete me?
        # print("modelfile: ("+modelsPosesColl[bpy.data.images[activeModelPoseIndex].name].model_file+")")
        if context.scene.objects.active != None:
            root = sUtils.getRoot(context.scene.objects.active)
        try:
            if (
                not root
                or not sUtils.isRoot(root)
                or bpy.data.images[activeModelPoseIndex].name in modelsPosesColl.keys()
                and modelsPosesColl[bpy.data.images[activeModelPoseIndex].name].model_file != ''
                and len(bpy.context.selected_objects) == 0
                or modelsPosesColl[bpy.data.images[activeModelPoseIndex].name].robot_name
                != root["model/name"]
            ):
                result = True
        except KeyError:
            result = False
        return result
Exemplo n.º 2
0
Arquivo: io.py Projeto: snrkiwi/phobos
 def poll(self, context):
     modelsPosesColl = bUtils.getPhobosPreferences().models_poses
     activeModelPoseIndex = bpy.context.scene.active_ModelPose
     return (context.selected_objects and context.active_object and sUtils.isRoot(context.active_object) and
             bpy.data.images[activeModelPoseIndex].name in modelsPosesColl.keys() and
             modelsPosesColl[bpy.data.images[activeModelPoseIndex].name].robot_name == context.active_object['modelname'] and
             modelsPosesColl[bpy.data.images[activeModelPoseIndex].name].type == 'robot_pose')
Exemplo n.º 3
0
    def execute(self, context):
        """

        Args:
          context: 

        Returns:

        """
        root = sUtils.getRoot(context.selected_objects[0])

        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose
        selected_robot = modelsPosesColl[bpy.data.images[activeModelPoseIndex].name]

        objectlist = sUtils.getChildren(root, selected_only=True, include_hidden=False)
        sUtils.selectObjects([root] + objectlist, clear=True, active=0)
        models.loadPose(selected_robot.robot_name, selected_robot.label)
        parameter = self.decimate_ratio
        if self.decimate_type == 'UNSUBDIV':
            parameter = self.decimate_iteration
        elif self.decimate_type == 'DISSOLVE':
            parameter = self.decimate_angle_limit
        exporter.bakeModel(
            objectlist,
            root['model/name'],
            selected_robot.label,
            decimate_type=self.decimate_type,
            decimate_parameter=parameter,
        )
        sUtils.selectObjects([root] + objectlist, clear=True, active=0)
        bpy.ops.scene.reload_models_and_poses_operator()
        return {'FINISHED'}
Exemplo n.º 4
0
    def execute(self, context):
        """

        Args:
          context:

        Returns:

        """
        loadModelsAndPoses()
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        for model_pose in modelsPosesColl:
            if model_pose.name not in bpy.data.images.keys():
                if model_pose.type == 'robot_name':
                    bpy.data.images.new(model_pose.name, 0, 0)
                elif 'robot_pose':
                    if model_pose.preview != '':
                        if os.path.split(model_pose.preview
                                         )[-1] in bpy.data.images.keys():
                            bpy.data.images[os.path.split(
                                model_pose.preview)[-1]].reload()
                        im = bpy.data.images.load(model_pose.preview)
                        model_pose.name = im.name
                        # im.name = model_pose.name
                        im.gl_load(0, bgl.GL_LINEAR, bgl.GL_LINEAR)
                    else:
                        bpy.data.images.new(model_pose.name, 0, 0)
            else:
                bpy.data.images[model_pose.name].reload()
                bpy.data.images[model_pose.name].gl_load(
                    0, bgl.GL_LINEAR, bgl.GL_LINEAR)
        return {'FINISHED'}
Exemplo n.º 5
0
    def poll(self, context):
        """

        Args:
          context:

        Returns:

        """
        result = False
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose
        root = None
        # TODO delete me?
        # print("modelfile: ("+modelsPosesColl[bpy.data.images[activeModelPoseIndex].name].model_file+")")
        if context.view_layer.objects.active != None:
            root = sUtils.getRoot(context.view_layer.objects.active)
        try:
            if (not root or not sUtils.isRoot(root)
                    or bpy.data.images[activeModelPoseIndex].name
                    in modelsPosesColl.keys()
                    and modelsPosesColl[bpy.data.images[activeModelPoseIndex].
                                        name].model_file != ''
                    and len(bpy.context.selected_objects) == 0
                    or modelsPosesColl[bpy.data.images[activeModelPoseIndex].
                                       name].robot_name != root["model/name"]):
                result = True
        except KeyError:
            result = False
        return result
Exemplo n.º 6
0
    def execute(self, context):
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose
        if bpy.data.images[activeModelPoseIndex].name in modelsPosesColl.keys(
        ):
            activeModelPose = modelsPosesColl[
                bpy.data.images[activeModelPoseIndex].name]
            if activeModelPose.type != "robot_name":
                # show on view_3d
                root = None
                if context.scene.objects.active != None:
                    root = sUtils.getRoot(context.scene.objects.active)
                if not bpy.context.scene.preview_visible and \
                        (bpy.data.images[activeModelPoseIndex].type == 'IMAGE') and \
                        (root is None or not sUtils.isRoot(root) or not (modelsPosesColl[bpy.data.images[activeModelPoseIndex].name] != root["modelname"]) or len(bpy.context.selected_objects) == 0):
                    bpy.ops.view3d.draw_preview_operator()
                    bpy.context.scene.preview_visible = True

            else:
                activeModelPose.hide = not activeModelPose.hide
                if activeModelPose.hide:
                    activeModelPose.icon = "RIGHTARROW"
                else:
                    activeModelPose.icon = "DOWNARROW_HLT"
                for modelPose in modelsPosesColl:
                    if (modelPose.type != "robot_name") and (
                            modelPose.parent == activeModelPose.name):
                        modelPose.hide = activeModelPose.hide

        return {'FINISHED'}
Exemplo n.º 7
0
    def execute(self, context):
        """

        Args:
          context: 

        Returns:

        """
        loadModelsAndPoses()
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        for model_pose in modelsPosesColl:
            if model_pose.name not in bpy.data.images.keys():
                if model_pose.type == 'robot_name':
                    bpy.data.images.new(model_pose.name, 0, 0)
                elif 'robot_pose':
                    if model_pose.preview != '':
                        if os.path.split(model_pose.preview)[-1] in bpy.data.images.keys():
                            bpy.data.images[os.path.split(model_pose.preview)[-1]].reload()
                        im = bpy.data.images.load(model_pose.preview)
                        model_pose.name = im.name
                        # im.name = model_pose.name
                        im.gl_load(0, bgl.GL_LINEAR, bgl.GL_LINEAR)
                    else:
                        bpy.data.images.new(model_pose.name, 0, 0)
            else:
                bpy.data.images[model_pose.name].reload()
                bpy.data.images[model_pose.name].gl_load(0, bgl.GL_LINEAR, bgl.GL_LINEAR)
        return {'FINISHED'}
Exemplo n.º 8
0
    def execute(self, context):
        root = sUtils.getRoot(context.selected_objects[0])

        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose
        selected_robot = modelsPosesColl[
            bpy.data.images[activeModelPoseIndex].name]

        objectlist = sUtils.getChildren(root,
                                        selected_only=True,
                                        include_hidden=False)
        sUtils.selectObjects([root] + objectlist, clear=True, active=0)
        models.loadPose(selected_robot.robot_name, selected_robot.label)
        parameter = self.decimate_ratio
        if self.decimate_type == 'UNSUBDIV':
            parameter = self.decimate_iteration
        elif self.decimate_type == 'DISSOLVE':
            parameter = self.decimate_angle_limit
        exporter.bakeModel(objectlist,
                           root['modelname'],
                           selected_robot.label,
                           decimate_type=self.decimate_type,
                           decimate_parameter=parameter)
        sUtils.selectObjects([root] + objectlist, clear=True, active=0)
        bpy.ops.scene.reload_models_and_poses_operator()
        return {'FINISHED'}
Exemplo n.º 9
0
def deriveEntity(root, outpath):
    """Derives the dictionary for a SMURF entity from the phobos model dictionary.
    
    # TODO savetosubfolder is not a parameter

    Args:
      root(bpy.types.Object): The smurf root object.
      outpath(str): The path to export the smurf to.
      savetosubfolder(bool): If True the export path has a subfolder for this smurf entity.

    Returns:
      : dict - An entry for the scenes entitiesList

    """
    entitypose = models.deriveObjectPose(root)
    entity = models.initObjectProperties(root, 'entity',
                                         ['link', 'joint', 'motor'])
    if 'parent' not in entity and 'joint/type' in root and root[
            'joint/type'] == 'fixed':
        entity['parent'] = 'world'
    entity["position"] = entitypose["translation"]
    entity["rotation"] = entitypose["rotation_quaternion"]

    # check model data if entity is a reference
    # FIXME: this part is broken but not used at the moment anyways
    if "isReference" in entity:
        entity.pop("isReference")
        bpy.ops.scene.reload_models_and_poses_operator()
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        for robot_model in modelsPosesColl:
            if (root["model/name"]
                    == robot_model.robot_name) and (root["entity/pose"]
                                                    == robot_model.label):
                pass
        entity['file'] = os.path.join(
            os.path.relpath(robot_model.path, outpath),
            root["name"] + ".smurf")
        """
        with open(os.path.join(os.path.dirname(defs.__file__), "RobotLib.yml"), "r") as f:
            robots = yaml.load(f.read())
            sourcepath = robots[smurf["model/name"]]
            for filename in os.listdir(sourcepath):
                fullpath = os.path.join(sourcepath, filename)
                if os.path.isfile(fullpath):
                    shutil.copy2(fullpath, os.path.join(smurf_outpath, filename))
                else:
                    # remove old folders to prevent errors in copytree
                    shutil.rmtree(os.path.join(smurf_outpath, filename), True)
                    shutil.copytree(fullpath, os.path.join(smurf_outpath, filename))
        """
    else:
        modelpath = os.path.join(outpath, root['model/name'], 'smurf')
        # TODO why the spacing between the paths?
        log("Scene paths: " + outpath + ' ' + modelpath, "DEBUG")
        entity['file'] = os.path.join(
            os.path.relpath(modelpath, os.path.dirname(outpath)),
            root['model/name'] + ".smurf")
    return entity
Exemplo n.º 10
0
def deriveEntity(root, outpath):
    """Derives the dictionary for a SMURF entity from the phobos model dictionary.
    
    # TODO savetosubfolder is not a parameter

    Args:
      root(bpy.types.Object): The smurf root object.
      outpath(str): The path to export the smurf to.
      savetosubfolder(bool): If True the export path has a subfolder for this smurf entity.

    Returns:
      : dict - An entry for the scenes entitiesList

    """
    entitypose = models.deriveObjectPose(root)
    entity = models.initObjectProperties(root, 'entity', ['link', 'joint', 'motor'])
    if 'parent' not in entity and 'joint/type' in root and root['joint/type'] == 'fixed':
        entity['parent'] = 'world'
    entity["position"] = entitypose["translation"]
    entity["rotation"] = entitypose["rotation_quaternion"]

    # check model data if entity is a reference
    # FIXME: this part is broken but not used at the moment anyways
    if "isReference" in entity:
        entity.pop("isReference")
        bpy.ops.scene.reload_models_and_poses_operator()
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        for robot_model in modelsPosesColl:
            if (root["model/name"] == robot_model.robot_name) and (
                root["entity/pose"] == robot_model.label
            ):
                pass
        entity['file'] = os.path.join(
            os.path.relpath(robot_model.path, outpath), root["name"] + ".smurf"
        )
        """
        with open(os.path.join(os.path.dirname(defs.__file__), "RobotLib.yml"), "r") as f:
            robots = yaml.load(f.read())
            sourcepath = robots[smurf["model/name"]]
            for filename in os.listdir(sourcepath):
                fullpath = os.path.join(sourcepath, filename)
                if os.path.isfile(fullpath):
                    shutil.copy2(fullpath, os.path.join(smurf_outpath, filename))
                else:
                    # remove old folders to prevent errors in copytree
                    shutil.rmtree(os.path.join(smurf_outpath, filename), True)
                    shutil.copytree(fullpath, os.path.join(smurf_outpath, filename))
        """
    else:
        modelpath = os.path.join(outpath, root['model/name'], 'smurf')
        # TODO why the spacing between the paths?
        log("Scene paths: " + outpath + ' ' + modelpath, "DEBUG")
        entity['file'] = os.path.join(
            os.path.relpath(modelpath, os.path.dirname(outpath)), root['model/name'] + ".smurf"
        )
    return entity
Exemplo n.º 11
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()

    rootpath = bUtils.getPhobosPreferences().modelsfolder
    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')
Exemplo n.º 12
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()

    rootpath = bUtils.getPhobosPreferences().modelsfolder
    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')
Exemplo n.º 13
0
Arquivo: io.py Projeto: snrkiwi/phobos
    def invoke(self, context, event):
        wm = context.window_manager
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose

        selected_robot = modelsPosesColl[
            bpy.data.images[activeModelPoseIndex].name]
        if selected_robot.model_file != '':
            return wm.invoke_props_dialog(self, width=300, height=100)
        else:
            return {"CANCELLED"}
Exemplo n.º 14
0
    def execute(self, context):
        """

        Args:
          context:

        Returns:

        """
        log("Import robot bake", "INFO")
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose
        selected_robot = modelsPosesColl[
            bpy.data.images[activeModelPoseIndex].name]
        if selected_robot.type != "robot_name":
            if os.path.splitext(selected_robot.model_file)[-1] == ".obj":
                bpy.ops.import_scene.obj(
                    filepath=selected_robot.model_file,
                    axis_forward='-Z',
                    axis_up='Y',
                    filter_glob="*.obj;*.mtl",
                    use_edges=True,
                    use_smooth_groups=True,
                    use_split_objects=True,
                    use_split_groups=True,
                    use_groups_as_vgroups=False,
                    use_image_search=True,
                    split_mode='ON',
                    global_clamp_size=0,
                )
            elif os.path.splitext(selected_robot.model_file)[-1] == ".stl":
                bpy.ops.import_mesh.stl(
                    filepath=selected_robot.model_file,
                    axis_forward='Y',
                    axis_up='Z',
                    filter_glob="*.stl",
                    files=[],
                    directory="",
                    global_scale=1,
                    use_scene_unit=True,
                    use_facet_normal=False,
                )
            robot_obj = bpy.context.selected_objects[0]
            bpy.context.view_layer.objects.active = robot_obj
            robot_obj.name = self.obj_name
            robot_obj["model/name"] = selected_robot.robot_name
            robot_obj["entity/name"] = self.obj_name
            robot_obj["entity/type"] = "smurf"
            robot_obj["entity/pose"] = selected_robot.label
            robot_obj["entity/isReference"] = True
            robot_obj.phobostype = 'entity'
        return {'FINISHED'}
Exemplo n.º 15
0
    def invoke(self, context, event):
        """

        Args:
          context:
          event:

        Returns:

        """
        self.filepath = bUtils.getPhobosPreferences().modelsfolder
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}
Exemplo n.º 16
0
    def invoke(self, context, event):
        """

        Args:
          context: 
          event: 

        Returns:

        """
        self.filepath = bUtils.getPhobosPreferences().modelsfolder
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}
Exemplo n.º 17
0
    def execute(self, context):
        """

        Args:
          context: 

        Returns:

        """
        log("Import robot bake", "INFO")
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose
        selected_robot = modelsPosesColl[bpy.data.images[activeModelPoseIndex].name]
        if selected_robot.type != "robot_name":
            if os.path.splitext(selected_robot.model_file)[-1] == ".obj":
                bpy.ops.import_scene.obj(
                    filepath=selected_robot.model_file,
                    axis_forward='-Z',
                    axis_up='Y',
                    filter_glob="*.obj;*.mtl",
                    use_edges=True,
                    use_smooth_groups=True,
                    use_split_objects=True,
                    use_split_groups=True,
                    use_groups_as_vgroups=False,
                    use_image_search=True,
                    split_mode='ON',
                    global_clamp_size=0,
                )
            elif os.path.splitext(selected_robot.model_file)[-1] == ".stl":
                bpy.ops.import_mesh.stl(
                    filepath=selected_robot.model_file,
                    axis_forward='Y',
                    axis_up='Z',
                    filter_glob="*.stl",
                    files=[],
                    directory="",
                    global_scale=1,
                    use_scene_unit=True,
                    use_facet_normal=False,
                )
            robot_obj = bpy.context.selected_objects[0]
            bpy.context.scene.objects.active = robot_obj
            robot_obj.name = self.obj_name
            robot_obj["model/name"] = selected_robot.robot_name
            robot_obj["entity/name"] = self.obj_name
            robot_obj["entity/type"] = "smurf"
            robot_obj["entity/pose"] = selected_robot.label
            robot_obj["entity/isReference"] = True
            robot_obj.phobostype = 'entity'
        return {'FINISHED'}
Exemplo n.º 18
0
    def execute(self, context):
        """

        Args:
          context: 

        Returns:

        """
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose
        if bpy.data.images[activeModelPoseIndex].name in modelsPosesColl.keys():
            activeModelPose = modelsPosesColl[bpy.data.images[activeModelPoseIndex].name]
            if activeModelPose.type != "robot_name":
                # show on view_3d
                root = None
                if context.scene.objects.active != None:
                    root = sUtils.getRoot(context.scene.objects.active)
                if (
                    not bpy.context.scene.preview_visible
                    and (bpy.data.images[activeModelPoseIndex].type == 'IMAGE')
                    and (
                        root is None
                        or not sUtils.isRoot(root)
                        or not (
                            modelsPosesColl[bpy.data.images[activeModelPoseIndex].name]
                            != root["model/name"]
                        )
                        or len(bpy.context.selected_objects) == 0
                    )
                ):
                    bpy.ops.view3d.draw_preview_operator()
                    bpy.context.scene.preview_visible = True

            else:
                activeModelPose.hide = not activeModelPose.hide
                if activeModelPose.hide:
                    activeModelPose.icon = "RIGHTARROW"
                else:
                    activeModelPose.icon = "DOWNARROW_HLT"
                for modelPose in modelsPosesColl:
                    if (modelPose.type != "robot_name") and (
                        modelPose.parent == activeModelPose.name
                    ):
                        modelPose.hide = activeModelPose.hide

        return {'FINISHED'}
Exemplo n.º 19
0
    def invoke(self, context, event):
        """

        Args:
          context: 
          event: 

        Returns:

        """
        wm = context.window_manager
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose

        selected_robot = modelsPosesColl[bpy.data.images[activeModelPoseIndex].name]
        if selected_robot.model_file != '':
            return wm.invoke_props_dialog(self, width=300, height=100)
        else:
            return {"CANCELLED"}
Exemplo n.º 20
0
    def poll(self, context):
        """

        Args:
          context: 

        Returns:

        """
        modelsPosesColl = bUtils.getPhobosPreferences().models_poses
        activeModelPoseIndex = bpy.context.scene.active_ModelPose
        return (
            context.selected_objects
            and context.active_object
            and sUtils.isRoot(context.active_object)
            and bpy.data.images[activeModelPoseIndex].name in modelsPosesColl.keys()
            and modelsPosesColl[bpy.data.images[activeModelPoseIndex].name].robot_name
            == context.active_object['model/name']
            and modelsPosesColl[bpy.data.images[activeModelPoseIndex].name].type == 'robot_pose'
        )
Exemplo n.º 21
0
def draw_preview_callback(self):
    """TODO Missing documentation"""

    # Search for View_3d window
    area = None
    if bpy.context.area.type != 'VIEW_3D':
        return bpy.context.area
    else:
        for oWindow in bpy.context.window_manager.windows:
            oScreen = oWindow.screen
            for oArea in oScreen.areas:
                if oArea.type == 'VIEW_3D':
                    area = oArea

    modelsPosesColl = bUtils.getPhobosPreferences().models_poses
    activeModelPoseIndex = bpy.context.scene.active_ModelPose

    if (len(modelsPosesColl) > 0) and area:

        # Draw a textured quad
        area_widths = [
            region.width for region in bpy.context.area.regions if region.type == 'WINDOW'
        ]
        area_heights = [
            region.height for region in bpy.context.area.regions if region.type == 'WINDOW'
        ]
        if (len(area_widths) > 0) and (len(area_heights) > 0):

            active_preview = modelsPosesColl[bpy.data.images[activeModelPoseIndex].name]
            im = bpy.data.images[activeModelPoseIndex]

            view_width = area_widths[0]
            view_height = area_heights[0]
            tex_start_x = 50
            tex_end_x = view_width - 50
            tex_start_y = 50
            tex_end_y = view_height - 50
            if im.size[0] < view_width:
                diff = int((view_width - im.size[0]) / 2)
                tex_start_x = diff
                tex_end_x = diff + im.size[0]
            if im.size[1] < view_height:
                diff = int((view_height - im.size[1]) / 2)
                tex_start_y = diff
                tex_end_y = diff + im.size[1]

            # Draw information
            font_id = 0  # XXX, need to find out how best to get this.
            blf.position(font_id, tex_start_x, tex_end_y + 20, 0)
            blf.size(font_id, 20, 72)
            blf.draw(font_id, active_preview.label)

            tex = im.bindcode
            bgl.glEnable(bgl.GL_TEXTURE_2D)
            # if using blender 2.77 change tex to tex[0]
            bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)

            # Background
            bgl.glEnable(bgl.GL_BLEND)

            bgl.glBegin(bgl.GL_QUADS)
            bgl.glColor4f(0, 0, 0, 0.3)
            bgl.glVertex2i(0, 0)
            bgl.glVertex2i(0, view_height)
            bgl.glVertex2i(view_width, view_height)
            bgl.glVertex2i(view_width, 0)

            # Draw Image
            bgl.glColor4f(1, 1, 1, 1)
            bgl.glTexCoord2f(0, 0)
            bgl.glVertex2i(int(tex_start_x), int(tex_start_y))
            bgl.glTexCoord2f(0, 1)
            bgl.glVertex2i(int(tex_start_x), int(tex_end_y))
            bgl.glTexCoord2f(1, 1)
            bgl.glVertex2i(int(tex_end_x), int(tex_end_y))
            bgl.glTexCoord2f(1, 0)
            bgl.glVertex2i(int(tex_end_x), int(tex_start_y))
            bgl.glEnd()

            # restore opengl defaults
            bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
            bgl.glDisable(bgl.GL_QUADS)
            bgl.glDisable(bgl.GL_BLEND)
            bgl.glDisable(bgl.GL_TEXTURE_2D)
Exemplo n.º 22
0
def draw_preview_callback(self):

    # Search for View_3d window
    area = None
    if bpy.context.area.type != 'VIEW_3D':
        return bpy.context.area
    else:
        for oWindow in bpy.context.window_manager.windows:
            oScreen = oWindow.screen
            for oArea in oScreen.areas:
                if oArea.type == 'VIEW_3D':
                    area = oArea

    modelsPosesColl = bUtils.getPhobosPreferences().models_poses
    activeModelPoseIndex = bpy.context.scene.active_ModelPose

    if (len(modelsPosesColl) > 0) and area:

        # Draw a textured quad
        area_widths = [
            region.width for region in bpy.context.area.regions
            if region.type == 'WINDOW'
        ]
        area_heights = [
            region.height for region in bpy.context.area.regions
            if region.type == 'WINDOW'
        ]
        if (len(area_widths) > 0) and (len(area_heights) > 0):

            active_preview = modelsPosesColl[
                bpy.data.images[activeModelPoseIndex].name]
            im = bpy.data.images[activeModelPoseIndex]

            view_width = area_widths[0]
            view_height = area_heights[0]
            tex_start_x = 50
            tex_end_x = view_width - 50
            tex_start_y = 50
            tex_end_y = view_height - 50
            if im.size[0] < view_width:
                diff = int((view_width - im.size[0]) / 2)
                tex_start_x = diff
                tex_end_x = diff + im.size[0]
            if im.size[1] < view_height:
                diff = int((view_height - im.size[1]) / 2)
                tex_start_y = diff
                tex_end_y = diff + im.size[1]

            # Draw information
            font_id = 0  # XXX, need to find out how best to get this.
            blf.position(font_id, tex_start_x, tex_end_y + 20, 0)
            blf.size(font_id, 20, 72)
            blf.draw(font_id, active_preview.label)

            tex = im.bindcode
            bgl.glEnable(bgl.GL_TEXTURE_2D)
            # if using blender 2.77 change tex to tex[0]
            bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)

            # Background
            bgl.glEnable(bgl.GL_BLEND)

            bgl.glBegin(bgl.GL_QUADS)
            bgl.glColor4f(0, 0, 0, 0.3)
            bgl.glVertex2i(0, 0)
            bgl.glVertex2i(0, view_height)
            bgl.glVertex2i(view_width, view_height)
            bgl.glVertex2i(view_width, 0)

            # Draw Image
            bgl.glColor4f(1, 1, 1, 1)
            bgl.glTexCoord2f(0, 0)
            bgl.glVertex2i(int(tex_start_x), int(tex_start_y))
            bgl.glTexCoord2f(0, 1)
            bgl.glVertex2i(int(tex_start_x), int(tex_end_y))
            bgl.glTexCoord2f(1, 1)
            bgl.glVertex2i(int(tex_end_x), int(tex_end_y))
            bgl.glTexCoord2f(1, 0)
            bgl.glVertex2i(int(tex_end_x), int(tex_start_y))
            bgl.glEnd()

            # restore opengl defaults
            bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
            bgl.glDisable(bgl.GL_QUADS)
            bgl.glDisable(bgl.GL_BLEND)
            bgl.glDisable(bgl.GL_TEXTURE_2D)
Exemplo n.º 23
0
def loadModelsAndPoses():
    """TODO Missing documentation"""
    # DOCU add some docstring
    if bUtils.getPhobosPreferences().modelsfolder:
        modelsfolder = os.path.abspath(
            bUtils.getPhobosPreferences().modelsfolder)
    else:
        modelsfolder = ''
    modelsPosesColl = bUtils.getPhobosPreferences().models_poses
    robots_found = []
    print(modelsfolder)
    for root, dirs, files in os.walk(modelsfolder):
        for file in files:
            if os.path.splitext(file)[-1] == '.smurf':
                robots_found.append(os.path.join(root, file))
    robots_dict = dict()
    for robot in robots_found:
        with open(robot, 'r') as robot_smurf:
            robot_yml = json.loads(robot_smurf)
            model_name = robot_yml["modelname"]
            robot_files = robot_yml["files"]
            for file in robot_files:
                if file.split('_')[-1] == "poses.yml":
                    if model_name not in robots_dict:
                        robots_dict[model_name] = []
                    with open(os.path.join(os.path.dirname(robot),
                                           file)) as poses:
                        poses_yml = json.loads(poses)
                        for pose in poses_yml['poses']:
                            robots_dict[model_name].append(
                                {"posename": pose['name']})
                            robots_dict[model_name][-1][
                                "robotpath"] = os.path.dirname(robot)

    modelsPosesColl.clear()
    for model_name in robots_dict.keys():
        item = modelsPosesColl.add()
        item.robot_name = model_name
        item.name = model_name
        item.label = model_name
        item.type = "robot_name"
        if item.hide:
            item.icon = "RIGHTARROW"
        else:
            item.icon = "DOWNARROW_HLT"
        current_parent = item.name
        for pose in robots_dict[model_name]:
            item = modelsPosesColl.add()
            item.parent = current_parent
            item.name = model_name + '_' + pose["posename"]
            item.label = pose["posename"]
            item.path = pose["robotpath"]
            item.type = "robot_pose"
            item.robot_name = model_name
            item.icon = "X_VEC"
            search_path = pose["robotpath"]
            if os.path.split(search_path)[-1] == "smurf":
                search_path = os.path.dirname(search_path)
            for file in glob.glob(search_path + "/**/" + model_name + "_" +
                                  pose['posename'] +
                                  ".*") + glob.glob(search_path + "/" +
                                                    model_name + "_" +
                                                    pose['posename'] + ".*"):
                if (os.path.splitext(file)[-1].lower()
                        == ".stl") or (os.path.splitext(file)[-1].lower()
                                       == ".obj"):
                    item.model_file = os.path.join(search_path, file)
                if os.path.splitext(file)[-1].lower() == ".png":
                    item.preview = os.path.join(search_path, file)
                    item.name = os.path.split(file)[-1]
Exemplo n.º 24
0
def parseLink(link, urdffilepath):
    """Parses a URDF link xml definition.

    Args:
      link(xml.etree.ElementTree.ElementTree): xml representation of the link
      urdffilepath(str): path of originating urdf file (for filename handling)

    Returns:
      : dict -- model representation of the link

    """
    newlink = {a: link.attrib[a] for a in link.attrib}
    newlink['children'] = []
    inertial = parseInertial(link)
    if inertial:
        newlink['inertial'] = inertial

    for objtype in ['visual', 'collision']:
        log('   Parsing ' + objtype + ' elements...', 'DEBUG')
        newlink[objtype] = {}
        for xmlelement in link.iter(objtype):
            # generate name for visual/collision representation
            if 'name' not in xmlelement.attrib:
                elementname = objtype + '_' + str(len(
                    newlink[objtype])) + '_' + newlink['name']
            else:
                elementname = xmlelement.attrib['name']

            # assign values to element dictionary
            elementdict = {a: xmlelement.attrib[a] for a in xmlelement.attrib}
            elementdict['name'] = elementname
            elementdict['pose'] = parsePose(xmlelement.find('origin'))

            # gather material
            material = xmlelement.find('material')
            if material is not None:
                elementdict['material'] = material.attrib['name']

            # objects without geometry skip the last part
            geometry = xmlelement.find('geometry')
            if geometry is None:
                newlink[objtype][elementname] = elementdict
                continue

            # gather geometry information for visual/collision
            elementdict['geometry'] = {
                a: gUtils.parse_text(geometry[0].attrib[a])
                for a in geometry[0].attrib
            }
            elementdict['geometry']['type'] = geometry[0].tag

            # gather mesh information
            if geometry[0].tag == 'mesh':
                # interpret filename

                filename = geometry[0].attrib['filename']

                # Some URDFs use rospack "package://" or "urdf/package://"
                # We'll assume the package root is in Phobos models dir
                filename = filename.split('package://')[-1]
                phobos_models = bUtils.getPhobosPreferences().modelsfolder
                filepath = path.join(phobos_models, filename)
                elementdict['geometry']['filename'] = filepath
                log(
                    "Filepath for {element} mesh: {path}".format(
                        element=elementname, path=filepath), 'DEBUG')

                # read scale
                if 'scale' in geometry[0].attrib:
                    elementdict['geometry']['scale'] = gUtils.parse_text(
                        geometry[0].attrib['scale'])
                else:
                    elementdict['geometry']['scale'] = [1.0, 1.0, 1.0]
            newlink[objtype][elementname] = elementdict

    if newlink == {}:
        log("Link information for " + newlink['name'] + " is empty.",
            'WARNING')
    return newlink
Exemplo n.º 25
0
def loadModelsAndPoses():
    """TODO Missing documentation"""
    # DOCU add some docstring
    if bUtils.getPhobosPreferences().modelsfolder:
        modelsfolder = os.path.abspath(bUtils.getPhobosPreferences().modelsfolder)
    else:
        modelsfolder = ''
    modelsPosesColl = bUtils.getPhobosPreferences().models_poses
    robots_found = []
    print(modelsfolder)
    for root, dirs, files in os.walk(modelsfolder):
        for file in files:
            if os.path.splitext(file)[-1] == '.smurf':
                robots_found.append(os.path.join(root, file))
    robots_dict = dict()
    for robot in robots_found:
        with open(robot, 'r') as robot_smurf:
            robot_yml = yaml.load(robot_smurf)
            model_name = robot_yml["modelname"]
            robot_files = robot_yml["files"]
            for file in robot_files:
                if file.split('_')[-1] == "poses.yml":
                    if model_name not in robots_dict:
                        robots_dict[model_name] = []
                    with open(os.path.join(os.path.dirname(robot), file)) as poses:
                        poses_yml = yaml.load(poses)
                        for pose in poses_yml['poses']:
                            robots_dict[model_name].append({"posename": pose['name']})
                            robots_dict[model_name][-1]["robotpath"] = os.path.dirname(robot)

    modelsPosesColl.clear()
    for model_name in robots_dict.keys():
        item = modelsPosesColl.add()
        item.robot_name = model_name
        item.name = model_name
        item.label = model_name
        item.type = "robot_name"
        if item.hide:
            item.icon = "RIGHTARROW"
        else:
            item.icon = "DOWNARROW_HLT"
        current_parent = item.name
        for pose in robots_dict[model_name]:
            item = modelsPosesColl.add()
            item.parent = current_parent
            item.name = model_name + '_' + pose["posename"]
            item.label = pose["posename"]
            item.path = pose["robotpath"]
            item.type = "robot_pose"
            item.robot_name = model_name
            item.icon = "X_VEC"
            search_path = pose["robotpath"]
            if os.path.split(search_path)[-1] == "smurf":
                search_path = os.path.dirname(search_path)
            for file in glob.glob(
                search_path + "/**/" + model_name + "_" + pose['posename'] + ".*"
            ) + glob.glob(search_path + "/" + model_name + "_" + pose['posename'] + ".*"):
                if (os.path.splitext(file)[-1].lower() == ".stl") or (
                    os.path.splitext(file)[-1].lower() == ".obj"
                ):
                    item.model_file = os.path.join(search_path, file)
                if os.path.splitext(file)[-1].lower() == ".png":
                    item.preview = os.path.join(search_path, file)
                    item.name = os.path.split(file)[-1]