b2m.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import bpy
  2. import socket
  3. import os
  4. import sys
  5. import json
  6. from bpy.app.handlers import persistent
  7. print('\n\n\n\n\n======================== INIT BLENDER SESSION ============================')
  8. home = os.path.expanduser('~')
  9. includepath = os.path.join(home, 'Documents', 'lab', 'm2b')
  10. # /// SETTINGS
  11. OBJ_FILE = ''
  12. # disable splash
  13. bpy.context.user_preferences.view.show_splash = False
  14. def get_sceneinfo():
  15. """Check if last argument is a file
  16. """
  17. arg = sys.argv[-1]
  18. print('> CMD LINE ARG:', arg)
  19. if 'blend' in arg:
  20. basepath = os.path.dirname(arg)
  21. uuid = os.path.basename(arg)
  22. uuid = os.path.splitext(uuid)[0]
  23. jsonfile = os.path.join(basepath, uuid + '.json')
  24. with open(jsonfile) as conffile:
  25. conf_data = json.load(conffile)
  26. print(conf_data)
  27. return conf_data
  28. elif 'json' in arg:
  29. with open(arg) as conffile:
  30. conf_data = json.load(conffile)
  31. return conf_data
  32. def import_obj(fp):
  33. old_state = list(bpy.context.scene.objects)
  34. bpy.ops.import_scene.obj(filepath=fp)
  35. new_state = list(bpy.context.scene.objects)
  36. return set(new_state) - set(old_state)
  37. def setup_scene():
  38. print('> SETTING UP SCENE')
  39. print('> texture:', TEXTURE)
  40. for object in bpy.data.objects:
  41. if object.name == 'Cube':
  42. object.select = True
  43. bpy.ops.object.delete()
  44. new_items = import_obj(OBJ_FILE)
  45. for object in bpy.context.scene.objects:
  46. object.select = False
  47. scn = bpy.context.scene
  48. scn.render.engine = 'CYCLES'
  49. mat = bpy.data.materials.new('MayaTexture')
  50. mat.use_nodes = True
  51. texnode = mat.node_tree.nodes.new(type="ShaderNodeTexImage")
  52. mat.node_tree.links.new(texnode.outputs['Color'], mat.node_tree.nodes['Diffuse BSDF'].inputs['Color'])
  53. if os.path.isfile(str(TEXTURE)):
  54. texnode.image = bpy.data.images.load(TEXTURE)
  55. for item in new_items:
  56. if item.type == 'MESH':
  57. ob = item
  58. mesh = ob.data
  59. mesh.materials.append(mat)
  60. item.select = True
  61. bpy.context.scene.objects.active = item
  62. preview_texture(TEXTURE)
  63. print('SAVING AS', BLEND)
  64. bpy.ops.wm.save_as_mainfile(filepath=BLEND, check_existing=False)
  65. def update_maya():
  66. print('MSG > MAYA', PORT)
  67. host = '127.0.0.1'
  68. port = PORT
  69. message = 'import sys;sys.path.append("' + includepath + '");import m2b;m2b.update("' + UUID + '")'
  70. maya = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  71. maya.connect((host, port))
  72. msg = bytes(message, 'UTF-8')
  73. try:
  74. print('sending')
  75. maya.send(msg)
  76. except:
  77. print('failed')
  78. print(msg)
  79. finally:
  80. print('closed')
  81. maya.close()
  82. def deselect():
  83. for object in bpy.context.scene.objects:
  84. object.select = False
  85. def preview_texture(image):
  86. print('> PREVIEW TEXTURE GENERATION', TEXTURE)
  87. for area in bpy.data.screens['Default'].areas:
  88. if area.type == 'VIEW_3D':
  89. for space in area.spaces:
  90. if space.type == 'VIEW_3D':
  91. space.viewport_shade = 'TEXTURED'
  92. space.show_textured_solid = True
  93. deselect()
  94. mat = bpy.data.materials.new('TexMat')
  95. def export():
  96. selection = bpy.context.selected_objects
  97. deselect()
  98. for object in bpy.context.scene.objects:
  99. if not object.hide_render:
  100. object.select = True
  101. bpy.ops.export_scene.obj(filepath=OBJ_FILE,
  102. use_materials=False,
  103. use_blen_objects=False,
  104. use_selection=True)
  105. # restore selection
  106. for object in bpy.context.scene.objects:
  107. object.select = False
  108. if object in selection:
  109. object.select = True
  110. update_maya()
  111. @persistent
  112. def save_handler(dummy):
  113. export()
  114. class BlenderBridge(object):
  115. def __init__(self):
  116. self.handler = save_handler
  117. info = get_sceneinfo()
  118. if info is not None:
  119. OBJ_FILE = info['obj']
  120. TEXTURE = info['tex']
  121. BLEND = info['blend']
  122. UUID = info['uuid']
  123. PORT = info['port']
  124. if os.path.isfile(BLEND):
  125. print('> matching blend file found. using that.')
  126. else:
  127. setup_scene()
  128. if len(bpy.app.handlers.save_post) < 1:
  129. bpy.app.handlers.save_post.append(save_handler)