def get(name,
        type='auto',
        directory=None,
        default=None,
        doedit='auto',
        description=None,
        editor='visual',
        world=None,
        frame=None):
    """Retrieve a resource of the given name from the current resources
    directory.  Resources may be of type Config, Configs, IKGoal, Hold,
    Stance, MultiPath, LinearPath, etc. (see Klampt/Modeling/Resources.h for
    a complete list; not all are supported in the Python API).  They can
    also be edited using RobotPose.

    If the resource does not already exist, an edit prompt will be
    shown, and the result from the prompt will be saved to disk under the
    given name.

    Arguments:
        - name: the resource name.  If type='auto', this is assumed to have
          a suffix of a file of the desired type.  The name can also be
          nested of the form 'group/subgroup/name.type'.
        - type: the resource type, or 'auto' to determine it automatically.
        - directory: the search directory.  If None, uses the current
          resource directory.
        - default: the default value if the resource does not exist on disk.
          If None, some arbitrary default value will be inferred.
        - doedit: if 'auto', if the resource does not exist on disk, an
          edit prompt will be displayed.  If False, an RuntimeError will be
          raised if the resource does not exist on disk.  If True, the
          user will be given an edit prompt to optionally edit the resource
          before this call returns.
        - description: an optional text description of the resource, for use
          in the edit prompt.
        - editor: either 'visual' or 'console', determining whether to use the
          visual OpenGL or console editor.
        - world: for a visual editor, this world will be shown along with
          the item to edit.  If this is a string it points to a file
          that will be loaded for the world (e.g., a world XML file, or a
          robot file).
        - frame: for rigid transforms / rotations / points, the reference
          frame for the visual editor.  This is an element of se3, or an
          ObjectModel, or a RobotModelLink, or a string indicating a named
          rigid element of the world.
          """
    if name == None:
        if doedit == False:
            raise RuntimeError(
                "Can't get() an anonymous resource without launching editor")
        success, newvalue = edit(name,
                                 value=default,
                                 type=type,
                                 description=description,
                                 editor=editor,
                                 world=world,
                                 frame=frame)
        if not success:
            print "Cancel pressed, returning None"
            return None
        else:
            print "Ok pressed, returning anonymous resource"
            return newvalue
    if directory == None:
        directory = getDirectory()
    if type == 'auto':
        type = filenameToType(name)
    value = None
    try:
        fn = os.path.join(directory, name)
        if type == 'xml':
            raise NotImplementedError("TODO: load xml files from Python API")
        elif type == 'json':
            f = open(fn, 'r')
            text = ''.join(f.readlines())
            f.close()
            value = loader.fromJson(text, type=type)
        else:
            value = loader.load(type, fn)
        if value == None:
            raise IOError
        if doedit == True:
            success, newvalue = edit(name,
                                     value=value,
                                     type=type,
                                     description=description,
                                     editor=editor,
                                     world=world,
                                     frame=frame)
            if success:
                print "Ok pressed, saving resource to", name
                value = newvalue
                set(name, value, type=type, directory=directory)
            else:
                print "Cancel pressed, not saving resource to disk"
            return value
        return value
    except IOError:
        if doedit != False:
            print "Resource", fn, "does not exist, launching editor..."
            success, newvalue = edit(name,
                                     value=default,
                                     type=type,
                                     description=description,
                                     editor=editor,
                                     world=world,
                                     frame=frame)
            if success:
                print "Ok pressed, saving resource to", name
                value = newvalue
                set(name, value=value, type=type, directory=directory)
            else:
                print "Cancel pressed, not saving resource to disk"
            return value
        else:
            raise RuntimeError("Resource " + name + " does not exist")
    return
def console_edit(name, value, type, description=None, world=None, frame=None):
    print "*********************************************************"
    print
    print "Editing resource", name, "of type", type
    print
    if description != None:
        print description
        print
    if frame != None:
        if isinstance(frame, (RigidObjectModel, RobotModelLink)):
            print "Reference frame:", frame.getName()
        else:
            print "Reference frame:", frame
        print
    print "*********************************************************"
    print "Current value:", value
    print "Do you wish to change it? (y/n/q) >",
    choice = ''
    while choice not in ['y', 'n', 'q']:
        choice = raw_input()[0].lower()
        if choice not in ['y', 'n', 'q']:
            print "Please enter y/n/q indicating yes/no/quit."
            print ">",
    if choice == 'y':
        print "Enter the new desired value below.  You may use native text,"
        print "JSON strings, or file(fn) to indicate a file name."
        print "New value >",
        data = raw_input()
        if data.startswith('{') or data.startswith('['):
            jsonobj = json.loads(data)
            try:
                obj = loader.fromJson(jsonobj, type)
                return True, obj
            except Exception:
                print "Error loading from JSON, press enter to continue..."
                raw_input()
                return False, value
        elif data.startswith('file('):
            try:
                obj = get(data[5:-1], type, doedit=False)
                if obj == None:
                    return False, value
                return True, obj
            except Exception:
                print "Error loading from file, press enter to continue..."
                raw_input()
                return False, value
        else:
            try:
                obj = loader.read(type, data)
                return True, obj
            except Exception:
                print "Error loading from text, press enter to continue..."
                raw_input()
                return False, value
    elif choice == 'n':
        print "Using current value."
        print "*********************************************************"
        return False, value
    elif choice == 'q':
        return False, None
def console_edit(name,value,type,description=None,world=None,frame=None):
    print "*********************************************************"
    print 
    print "Editing resource",name,"of type",type
    print
    if description!=None:
        print description
        print
    if frame!=None:
        if isinstance(frame,(RigidObjectModel,RobotModelLink)):
            print "Reference frame:",frame.getName()
        else:
            print "Reference frame:",frame
        print
    print "*********************************************************"
    print "Current value:",value
    print "Do you wish to change it? (y/n/q) >",
    choice = ''
    while choice not in ['y','n','q']:
        choice = raw_input()[0].lower()
        if choice not in ['y','n','q']:
            print "Please enter y/n/q indicating yes/no/quit."
            print ">",
    if choice=='y':
        print "Enter the new desired value below.  You may use native text,"
        print "JSON strings, or file(fn) to indicate a file name."
        print "New value >",
        data = raw_input()
        if data.startswith('{') or data.startswith('['):
            jsonobj = json.loads(data)
            try:
                obj = loader.fromJson(jsonobj,type)
                return True,obj
            except Exception:
                print "Error loading from JSON, press enter to continue..."
                raw_input()
                return False,value
        elif data.startswith('file('):
            try:
                obj = get(data[5:-1],type,doedit=False)
                if obj==None:
                    return False,value
                return True,obj
            except Exception:
                print "Error loading from file, press enter to continue..."
                raw_input()
                return False,value
        else:
            try:
                obj = loader.read(type,data)
                return True,obj
            except Exception:
                print "Error loading from text, press enter to continue..."
                raw_input()
                return False,value
    elif choice=='n':
        print "Using current value."
        print "*********************************************************"
        return False,value
    elif choice=='q':
        return False,None
def get(name,type='auto',directory=None,default=None,doedit='auto',description=None,editor='visual',world=None,frame=None):
    """Retrieve a resource of the given name from the current resources
    directory.  Resources may be of type Config, Configs, IKGoal, Hold,
    Stance, MultiPath, LinearPath, etc. (see Klampt/Modeling/Resources.h for
    a complete list; not all are supported in the Python API).  They can
    also be edited using RobotPose.

    If the resource does not already exist, an edit prompt will be
    shown, and the result from the prompt will be saved to disk under the
    given name.

    Arguments:
        - name: the resource name.  If type='auto', this is assumed to have
          a suffix of a file of the desired type.  The name can also be
          nested of the form 'group/subgroup/name.type'.
        - type: the resource type, or 'auto' to determine it automatically.
        - directory: the search directory.  If None, uses the current
          resource directory.
        - default: the default value if the resource does not exist on disk.
          If None, some arbitrary default value will be inferred.
        - doedit: if 'auto', if the resource does not exist on disk, an
          edit prompt will be displayed.  If False, an RuntimeError will be
          raised if the resource does not exist on disk.  If True, the
          user will be given an edit prompt to optionally edit the resource
          before this call returns.
        - description: an optional text description of the resource, for use
          in the edit prompt.
        - editor: either 'visual' or 'console', determining whether to use the
          visual OpenGL or console editor.
        - world: for a visual editor, this world will be shown along with
          the item to edit.  If this is a string it points to a file
          that will be loaded for the world (e.g., a world XML file, or a
          robot file).
        - frame: for rigid transforms / rotations / points, the reference
          frame for the visual editor.  This is an element of se3, or an
          ObjectModel, or a RobotModelLink, or a string indicating a named
          rigid element of the world.
          """
    if name==None:
        if doedit==False:
            raise RuntimeError("Can't get() an anonymous resource without launching editor")
        success,newvalue = edit(name,value=default,type=type,description=description,editor=editor,world=world,frame=frame)
        if not success:
            print "Cancel pressed, returning None"
            return None
        else:
            print "Ok pressed, returning anonymous resource"
            return newvalue
    if directory==None:
        directory = getDirectory()
    if type == 'auto':
        type = filenameToType(name)
    value = None
    try:
        fn = os.path.join(directory,name)
        if type == 'xml':
            raise NotImplementedError("TODO: load xml files from Python API")
        elif type == 'json':
            f = open(fn,'r')
            text = ''.join(f.readlines())
            f.close()
            value = loader.fromJson(text,type=type)
        else:
            value = loader.load(type,fn)
        if value==None:
            raise IOError
        if doedit==True:
            success,newvalue = edit(name,value=value,type=type,description=description,editor=editor,world=world,frame=frame)
            if success:
                print "Ok pressed, saving resource to",name
                value = newvalue
                set(name,value,type=type,directory=directory)
            else:
                print "Cancel pressed, not saving resource to disk"
            return value
        return value
    except IOError:
        if doedit!=False:
            print "Resource",fn,"does not exist, launching editor..."
            success,newvalue = edit(name,value=default,type=type,description=description,editor=editor,world=world,frame=frame)
            if success:
                print "Ok pressed, saving resource to",name
                value = newvalue
                set(name,value=value,type=type,directory=directory)
            else:
                print "Cancel pressed, not saving resource to disk"
            return value
        else:
            raise RuntimeError("Resource "+name+" does not exist")
    return
Example #5
0
def get(name,type='auto',directory=None,default=None,doedit='auto',description=None,editor='visual',world=None,referenceObject=None,frame=None):
    """Retrieve a resource of the given name from the current resources
    directory.  If the resource does not already exist, an edit prompt will be
    shown, and the result from the prompt will be saved to disk under the
    given name.

    Resources may be of type Config, Configs, IKGoal, Hold,
    Stance, MultiPath, Trajectory/LinearPath, and ContactPoint, or any of
    the basic Klampt object types, geometry types, and math types.

    Resources can also be edited using RobotPose.

    Args:
        name (str): the resource name.  If type='auto', this is assumed to have
            a suffix of a file of the desired type.  The name can also be
            nested of the form 'group/subgroup/name.type'.
        type (str): the resource type, or 'auto' to determine it automatically.
        directory (str, optional): the search directory.  If None, uses the current
            resource directory.
        default (optional): the default value if the resource does not exist on disk.
            If None, some arbitrary default value will be inferred.
        doedit: if 'auto', if the resource does not exist on disk, an
            edit prompt will be displayed.  If False, an RuntimeError will be
            raised if the resource does not exist on disk.  If True, the
            user will be given an edit prompt to optionally edit the resource
            before this call returns.
        description (str, optional): an optional text description of the resource, for use
            in the edit prompt.
        editor (str): either 'visual' or 'console', determining whether to use the
            visual OpenGL or console editor.
        world (WorldModel, optional): for a visual editor, this world will be shown along with
            the item to edit.  If this is a string it points to a file
            that will be loaded for the world (e.g., a world XML file, or a
            robot file).
        referenceObject (optional): to give visual reference points, one or more RobotModels,
            ObjectModels, Geometry3D's, or RobotModelLink's may be designated to follow
            the edited object.  Currently works with Config's / Configs' / Trajectories /
            rigid transforms / rotations / points.
        frame (optional): for rigid transforms / rotations / points, the reference
          frame in which the quantity is represented.  This is an element of
          se3, or an ObjectModel, or a RobotModelLink, or a string indicating a
          named rigid element of the world.

    """
    if name==None:
        if doedit==False:
            raise RuntimeError("Can't get() an anonymous resource without launching editor")
        success,newvalue = edit(name,value=default,type=type,description=description,editor=editor,world=world,referenceObject=referenceObject,frame=frame)
        if not success:
            print "Cancel pressed, returning None"
            return None
        else:
            print "Ok pressed, returning anonymous resource"
            return newvalue
    if directory==None:
        directory = getDirectory()
    if type == 'auto':
        type = filenameToType(name)
    value = None
    try:
        fn = os.path.join(directory,name)
        try:
            if type == 'xml':
                value = WorldModel()
                res = value.readFile(fn)
                if not res:
                    try:
                        value = loader.load('MultiPath',fn)
                    except Exception as e:
                        raise
            elif type == 'json':
                f = open(fn,'r')
                text = ''.join(f.readlines())
                f.close()
                value = loader.fromJson(text,type=type)
            else:
                value = loader.load(type,fn)
        except IOError:
            raise
        except Exception,e:
            import traceback
            print "Unable to read object from file "+fn
            print "Traceback: "
            traceback.print_exc()
            raise IOError()
        if value==None:
            raise IOError("Unable to load from file "+fn)
        if doedit==True:
            success,newvalue = edit(name,value=value,type=type,description=description,editor=editor,world=world,referenceObject=referenceObject,frame=frame)
            if success:
                print "Ok pressed, saving resource to",name
                value = newvalue
                set(name,value,type=type,directory=directory)
            else:
                print "Cancel pressed, not saving resource to disk"
            return value
        return value