materials.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from collections import namedtuple
  2. from utils.xml import StringToTree, FileToTree, subelement, TreeToFile, prettyPrint
  3. class Brdf(object):
  4. def __init__(self, reflect, alpha, ior=1.0):
  5. self.reflect= reflect
  6. self.alpha = alpha
  7. self.ior = ior
  8. def materialsAsXml(materials):
  9. tree = StringToTree('<root/>')
  10. for matname, m in materials.items():
  11. e = subelement(tree.getroot(), 'brdf', attribs={'type': 'basic', 'name': matname})
  12. reflect, alpha, ior = m.reflect, m.alpha, m.ior
  13. subelement(e, 'reflect', attribs={'value': reflect})
  14. subelement(e, 'alpha', attribs={'value': alpha})
  15. subelement(e, 'ior', attribs={'value': ior})
  16. return tree
  17. def loadMaterialsFromTree(tree):
  18. materials = {}
  19. for e in tree.getroot().xpath('brdf'):
  20. try:
  21. reflect = float(e.xpath('string(reflect/@value)'))
  22. alpha = float(e.xpath('string(alpha/@value)'))
  23. ior = float(e.xpath('string(ior/@value)'))
  24. except Exception:
  25. print 'cannot load material %s' % e.attrib.get('name')
  26. reflect, alpha, ior = 0.5, 0.5, 1.0
  27. materials[e.attrib['name']] = Brdf(reflect, alpha, ior)
  28. return materials
  29. def loadMaterialsFromString(materialsxml):
  30. return loadMaterialsFromTree(StringToTree(materialsxml))
  31. def loadMaterials(materials_file):
  32. return loadMaterialsFromTree(FileToTree(materials_file))