예제 #1
0
파일: urdf.py 프로젝트: stpulleyking/phobos
def importUrdf(filepath):
    """This function parses the whole URDF representation of the model and builds the model dictionary from it.
    The created model is stored in the model value of the parser and the URDF file is specified by the filepath
    given to the Parser.

    :return: Nothing.

    Args:
      filepath:

    Returns:

    """
    model = {}
    # TODO delete me?
    #element_order = {'links': [], 'joints': [], 'viscol': {}, 'materials': []}
    log("Parsing URDF model from " + filepath, "INFO")
    # TODO filepath consistency?
    tree = ET.parse(filepath)
    # TODO comment needed?
    root = tree.getroot()  #[0]
    model["name"] = root.attrib["name"]
    if 'version' in root.attrib:
        model["version"] = root.attrib['version']

    # parse links
    links = {}
    log("Parsing links...", "INFO")
    for link in root.iter('link'):
        links[link.attrib['name']] = parseLink(link, filepath)
        # TODO delete me?
        #element_order['links'].append(links.attrib['name'])
        #viscol_order = {'visual': [], 'collision': []}
    model['links'] = links

    # parse joints
    joints = {}
    log("Parsing joints...", "INFO")
    for joint in root.iter('joint'):
        # this is needed as there are "joint" tags e.g. in transmission
        if joint.find('parent') is not None:
            newjoint, pose = parseJoint(joint)
            # TODO delete me?
            #element_order['joints'].append(joint.attrib['name'])
            model['links'][newjoint['child']]['pose'] = pose
            joints[newjoint['name']] = newjoint
    model['joints'] = joints

    # find any links that still have no pose (most likely because they had no parent)
    for link in links:
        if 'pose' not in links[link]:
            links[link]['pose'] = parsePose(None)

    # write parent-child information to links
    log("Writing parent-child information to links...", "INFO")
    for j in model['joints']:
        joint = model['joints'][j]
        parentlink = model['links'][joint['parent']]
        childlink = model['links'][joint['child']]
        childlink['parent'] = joint['parent']
        parentlink['children'].append(joint['child'])

    # parse materials
    log("Parsing materials..", 'INFO')
    materiallist = []
    for material in root.iter('material'):
        newmaterial = {a: material.attrib[a] for a in material.attrib}
        color = material.find('color')
        if color is not None:
            newmaterial['color'] = gUtils.parse_text(color.attrib['rgba'])
            materiallist.append(newmaterial)  # simply overwrite duplicates
    for m in materiallist:
        materials.createMaterial(m['name'], tuple(m['color'][0:3]), (1, 1, 1),
                                 m['color'][-1])
    model['materials'] = {m['name']: m for m in materiallist}
    # TODO delete me?
    #element_order['materials'].append(m['name'])
    return model
예제 #2
0
파일: models.py 프로젝트: hwiedDFKI/phobos
def buildModelFromDictionary(model):
    """Creates the Blender representation of the imported model, using a model dictionary.

    Args:
      model(dict): model representation of the imported model

    Returns:

    """
    log("Creating Blender model...", 'INFO', prefix='\n' + '-' * 25 + '\n')

    log("  Initializing materials... ({} total)".format(len(model['materials'])), 'INFO')
    for mat in model['materials']:
        matmodel.createMaterial(model['materials'][mat], logging=True, adjust=True)
        # ['name'], tuple(mat['color'][0:3]), (1, 1, 1), mat['color'][-1])

    newobjects = []
    log("  Creating links... ({} total)".format(len(model['links'])), 'INFO')
    for lnk in model['links']:
        link = model['links'][lnk]
        model['links'][lnk]['object'] = linkmodel.createLink(link)
        newobjects.append(model['links'][lnk]['object'])
        newobjects.extend(model['links'][lnk]['object'].children)

    log("Setting parent-child relationships", 'INFO', prefix='\n')
    bUtils.toggleLayer('link', True)
    for lnk in model['links']:
        parent = model['links'][lnk]

        log("Children for link " + parent['name'] + ":\n" + '\n'.join(parent['children']), 'DEBUG')
        for chi in parent['children']:
            child = model['links'][chi]
            child['object'].matrix_world = parent['object'].matrix_world
            eUtils.parentObjectsTo(child['object'], parent['object'])

    # set transformations
    log("Transforming links...  ({} total)".format(len(model['links'])), 'INFO', prefix='\n')
    for lnk in model['links']:
        if 'parent' not in model['links'][lnk]:
            root = model['links'][lnk]
            break
    linkmodel.setLinkTransformations(model, root)

    log("Creating joints... ({} total)".format(len(model['joints'])), 'INFO', prefix='\n')
    for j in model['joints']:
        joint = model['joints'][j]
        jointmodel.createJoint(joint, links=model['links'])

    log("Assigning model name: {}".format(model['name']), 'INFO')
    rootlink = sUtils.getRoot(bpy.data.objects[root['object'].name])
    if 'name' not in model:
        log("Model name not specified in URDF. Make sure to define it thereafter.", 'WARNING')
    else:
        rootlink['model/name'] = model['name']
    rootlink.location = (0, 0, 0)

    # TODO make sure this works
    log("Creating sensors...", 'INFO')
    if 'sensors' in model and model['sensors']:
        for sen in model['sensors']:
            sensormodel.createSensor(model['sensors'][sen], model['sensors'][sen]['parent'])
    else:
        log("  No sensors in model.", 'INFO')

    # TODO make sure this works
    log("Creating motors...", 'INFO')
    if 'motors' in model and model['motors']:
        for motor in model['motors']:
            eUtils.setProperties(
                model['joints'][model['motors'][motor]['joint']],
                model['motors'][motor],
                category='motor',
            )
    else:
        log("  No motors in model.", 'INFO')

    # TODO make sure this works
    log("Creating groups...", 'INFO')
    if 'groups' in model and model['groups']:
        for group in model['groups']:
            createGroup(model['groups'][group])
    else:
        log("  No kinematic groups in model.", 'INFO')

    # TODO make sure this works
    log("Creating chains...", 'INFO')
    if 'chains' in model and model['chains']:
        for ch in model['chains']:
            createChain(model['chains'][ch])
    else:
        log("  No kinematic chains in model.", 'INFO')

    # TODO make sure this works
    log("Creating lights...", 'INFO')
    if 'lights' in model and model['lights']:
        for light in model['lights']:
            lightmodel.createLight(model['lights'][light])
    else:
        log("  No lights in model.", 'INFO')

    # display new objects after import
    sUtils.selectObjects(newobjects, clear=True, active=0)
    eUtils.sortObjectsToLayers(newobjects)
    for obj in newobjects:
        bUtils.setObjectLayersActive(obj, extendlayers=True)
    bpy.ops.object.mode_set(mode='OBJECT')
    bpy.ops.view3d.view_selected()

    # update the scene
    bUtils.update()