def writeDatablock(bus, pluginModule, pluginName, propGroup, overrideParams):
    o = bus['output']
    scene = bus['scene']
    camera = bus['camera']

    VRayCamera = camera.data.vray
    CameraStereoscopic = VRayCamera.CameraStereoscopic

    # XXX: Some code is broken in VRayStereoscopicSettings
    # Export it only if we are use CameraStereoscopic to calculate views
    #
    if not CameraStereoscopic.use:
        return

    cam = bpy.data.objects.get(CameraStereoscopic.LeftCam)
    if cam:
        overrideParams['left_camera'] = LibUtils.CleanString(cam.name)

    cam = bpy.data.objects.get(CameraStereoscopic.RightCam)
    if cam:
        overrideParams['right_camera'] = LibUtils.CleanString(cam.name)

    # NOTE: Shademap is currently broken
    overrideParams['sm_mode'] = 0
    overrideParams['shademap_file'] = None

    return ExportUtils.WritePluginCustom(bus, pluginModule, pluginName,
                                         propGroup, overrideParams)
Ejemplo n.º 2
0
def vray_draw_light_shape():
    if not bpy.context:
        return
    ob = bpy.context.active_object
    if not ob:
        return
    if ob.type not in {'LAMP'}:
        return

    la = ob.data

    VRayLight = LibUtils.GetLightPropGroup(la)

    bgl.glEnable(bgl.GL_POINT_SMOOTH)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

    col = lamp_color if VRayLight.enabled else lamp_color_off
    bgl.glColor4f(*col)

    if la.type == 'POINT':
        if la.vray.omni_type == 'SPHERE':
            vray_draw_light_sphere_shape(ob)
    elif la.type == 'SUN':
        if la.vray.direct_type == 'DIRECT':
            vray_draw_light_direct_shape(ob)

    # Reset draw
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
    def draw(self, context):
        layout = self.layout

        ob = context.object
        lamp = context.lamp
        space = context.space_data

        if ob:
            layout.template_ID(ob, 'data')
        elif lamp:
            layout.template_ID(space, 'pin_id')

        VRayLight = lamp.vray

        layout.separator()
        layout.prop(lamp, 'type', expand=True)

        lightSubTypeAttr = LibUtils.LampSubType[lamp.type]
        if lightSubTypeAttr is not None:
            layout.prop(VRayLight, lightSubTypeAttr, expand=True)

        lightPluginName = LibUtils.GetLightPluginName(lamp)
        lightPropGroup = getattr(VRayLight, lightPluginName)

        layout.separator()
        classes.NtreeWidget(layout, VRayLight, "Lamp Tree",
                            "vray.add_nodetree_light", 'LAMP')

        layout.separator()
        classes.DrawPluginUI(context, layout, VRayLight, lightPropGroup,
                             lightPluginName,
                             PLUGINS['LIGHT'][lightPluginName])

        layout.separator()

        if lamp.type == 'AREA':
            layout.prop(VRayLight.LightRectangle, 'is_disc')
            if VRayLight.LightRectangle.is_disc:
                split = layout.split()
                col = split.column()
                col.prop(lamp, 'size')
            else:
                layout.prop(lamp, 'shape', expand=True)
                split = layout.split()
                if lamp.shape == 'SQUARE':
                    col = split.column()
                    col.prop(lamp, 'size')
                else:
                    row = split.row(align=True)
                    row.prop(lamp, 'size', text="X")
                    row.prop(lamp, 'size_y', text="Y")

        elif lamp.type == 'SPOT':
            split = layout.split()
            col = split.column()
            col.prop(lamp, "show_cone")
            if VRayLight.spot_type == 'SPOT':
                col.prop(lamp, 'spot_size', text="Size")
                col.prop(lamp, 'spot_blend', text="Blend")
Ejemplo n.º 4
0
def CreateNode(ntree, nodeType, nodeName=None, unique=True):
    nodeLabel = nodeName

    if nodeName is None:
        nodeName = LibUtils.GetUUID()

    if nodeName in ntree.nodes:
        if not unique:
            return ntree.nodes[nodeName]
        else:
            nodeName = LibUtils.GetUUID() + nodeName

    node = ntree.nodes.new(nodeType)
    node.name = nodeName
    node.label = nodeLabel

    return node
Ejemplo n.º 5
0
class VRayPropGroupMultiBake(bpy.types.PropertyGroup):
    work_mode = bpy.props.EnumProperty(name="Mode",
                                       description="Bake mode",
                                       items=(
                                           ('SELECTION', "Selection",
                                            "Bake selected objects"),
                                           ('LIST', "List",
                                            "Bake objects from list"),
                                       ),
                                       default='SELECTION')

    uv_map = bpy.props.EnumProperty(
        name="UV Map",
        description="UV map to use",
        items=(
            ('UV_DEFAULT', "Default", "Use first found UV map"),
            ('UV_VRAYBAKE', "\"VRayBake\"", "Use map with name \"VRayBake\""),
            ('UV_NEW_SMART', "Add UV Map: Smart UV Project",
             "Add \"Smart UV Project\" projection (adds \"VRayBakeSmart\")"),
            ('UV_NEW_LM', "Add UV Map: Lightmap Pack",
             "Add \"Lightmap Pack\" projection (adds \"VRayBakeLightmap\")"),
        ),
        default='UV_DEFAULT')

    output_dirpath = bpy.props.StringProperty(
        name="Directory Path",
        subtype='DIR_PATH',
        default="//bake_$F",
        description="Output directory (Variables: %s; $O - Object name)" %
        LibUtils.FormatVariablesDesc())

    output_filename = bpy.props.StringProperty(
        name="File Name",
        default="bake_$O",
        description="Output filename (Variables: %s; $O - Object name)" %
        LibUtils.FormatVariablesDesc())

    smart_uv = bpy.props.PointerProperty(
        type=VRayPropGroupMultiBakeSmartUVProject, )

    lightmap_uv = bpy.props.PointerProperty(
        type=VRayPropGroupMultiBakeLightmapPackProject, )

    list_items = bpy.props.CollectionProperty(type=VRayBatchBakeItem)

    list_item_selected = bpy.props.IntProperty(default=-1, min=-1, max=100)
Ejemplo n.º 6
0
def writeCamera(bus, camera, tm):
	o = bus['output']

	camName = LibUtils.CleanString(camera.name)

	o.set('CAMERA', 'RenderView', camName)
	o.writeHeader()
	o.writeAttibute("transform", tm)
	o.writeFooter()
Ejemplo n.º 7
0
    def execute(self, context):
        listAttr = LibUtils.GetPropGroup(self.list_parent, self.list_attr)
        if listAttr.list_item_selected <= 0:
            return {'CANCELLED'}

        listAttr.list_items.move(listAttr.list_item_selected,
                                 listAttr.list_item_selected - 1)
        listAttr.list_item_selected -= 1

        return {'FINISHED'}
Ejemplo n.º 8
0
    def execute(self, context):
        preset_menu_class = getattr(bpy.types, self.preset_menu)
        preset_type = preset_menu_class.preset_subdir

        presetSubdir = PathUtils.CreateDirectory(os.path.join(SysUtils.GetUserConfigDir(), "presets"))
        exportPath   = PathUtils.CreateDirectory(os.path.join(presetSubdir, preset_type))

        presetName = preset_menu_class.bl_label if self.remove_active else self.name

        fileName = "%s.vrscene" % LibUtils.CleanString(bpy.path.display_name(presetName))

        outputFilepath = os.path.normpath(os.path.join(exportPath, fileName))

        if self.remove_active:
            # NOTE: Remove function is locked to user config directory,
            # so system settings are safe

            debug.PrintInfo('Removing preset file: "%s"' % outputFilepath)
            if not os.path.exists(outputFilepath):
                return {'CANCELLED'}
            try:
                os.remove(outputFilepath)
            except:
                debug.PrintError('Error removing preset file: "%s"!' % outputFilepath)

            # Set default menu name
            preset_menu_class.bl_label = bpy.path.display_name(preset_type)

        else:
            bus = {
                'output' : VRayStream.VRaySimplePluginExporter(outputFilepath),
                'scene'  : context.scene,
                'camera' : context.scene.camera,
                'preview' : False,
            }

            pluginPresetIDs = None
            if preset_type == 'global':
                pluginPresetIDs = (pID for pID in sorted(PLUGINS['SETTINGS']))
            else:
                pluginPresetIDs = PresetTypePlugins[preset_type]

            for pluginID in pluginPresetIDs:
                pluginModule = PLUGINS_ID.get(pluginID)
                if pluginModule is None:
                    continue

                if not hasattr(context.scene.vray, pluginID):
                    continue

                propGroup = getattr(context.scene.vray, pluginID)

                ExportUtils.WritePlugin(bus, pluginModule, pluginID.lower(), propGroup, {})

        return {'FINISHED'}
Ejemplo n.º 9
0
def AddLampNodeTree(lamp):
    VRayLight = lamp.vray

    nt = bpy.data.node_groups.new(lamp.name, type='VRayNodeTreeLight')
    nt.use_fake_user = True

    lightPluginName = LibUtils.GetLightPluginName(lamp)

    nt.nodes.new('VRayNode%s' % lightPluginName)
    NodesTools.deselectNodes(nt)

    VRayLight.ntree = nt
Ejemplo n.º 10
0
def DrawListWidget(layout,
                   parentID,
                   propGroupPath,
                   listType,
                   defItemName,
                   itemAddOp='DEFAULT',
                   itemRenderFunc=None):
    listPropGroup = LibUtils.GetPropGroup(parentID, propGroupPath)

    row = layout.row()
    row.template_list(listType,
                      "",
                      listPropGroup,
                      'list_items',
                      listPropGroup,
                      'list_item_selected',
                      rows=5)

    col = row.column()
    sub = col.row()
    subsub = sub.column(align=True)
    if itemAddOp in {'DEFAULT'}:
        op = subsub.operator('vray.ui_list_item_add', icon="ZOOMIN", text="")
        op.list_parent = parentID
        op.list_attr = propGroupPath
        op.def_item_name = defItemName
    else:
        subsub.operator(itemAddOp, icon="ZOOMIN", text="")

    sub = col.row()
    op = subsub.operator('vray.ui_list_item_del', icon="ZOOMOUT", text="")
    op.list_parent = parentID
    op.list_attr = propGroupPath
    subsub = sub.column(align=True)
    op = subsub.operator("vray.ui_list_item_up", icon='MOVE_UP_VEC', text="")
    op.list_parent = parentID
    op.list_attr = propGroupPath
    op = subsub.operator("vray.ui_list_item_down",
                         icon='MOVE_DOWN_VEC',
                         text="")
    op.list_parent = parentID
    op.list_attr = propGroupPath

    if itemRenderFunc:
        if listPropGroup.list_item_selected >= 0 and len(
                listPropGroup.list_items) > 0:
            listItem = listPropGroup.list_items[
                listPropGroup.list_item_selected]

            layout.separator()
            itemRenderFunc(layout, listItem)
Ejemplo n.º 11
0
    def execute(self, context):
        VRayExporter = context.scene.vray.Exporter

        selectedNodeTree = VRayExporter.ntreeListIndex
        if selectedNodeTree == -1:
            return {'CANCELLED'}

        ntree = bpy.data.node_groups[selectedNodeTree]

        outputNode = NodesExport.GetOutputNode(ntree)
        if not outputNode:
            return {'CANCELLED'}

        exportPath = BlenderUtils.GetFullFilepath(
            VRayExporter.ntreeExportDirectory)
        exportPath = PathUtils.CreateDirectory(exportPath)

        fileName = "%s.vrscene" % LibUtils.CleanString(ntree.name)

        outputFilepath = os.path.normpath(os.path.join(exportPath, fileName))

        debug.PrintInfo('Exporting "%s" to: "%s"' %
                        (ntree.name, outputFilepath))

        o = VRayStream.VRaySimplePluginExporter(outputFilepath)

        exporter = _vray_for_blender.init(
            engine=0,
            context=bpy.context.as_pointer(),
            scene=bpy.context.scene.as_pointer(),
            data=bpy.data.as_pointer(),
            mainFile=o.output,
            objectFile=o.output,
            envFile=o.output,
            geometryFile=o.output,
            lightsFile=o.output,
            materialFile=o.output,
            textureFile=o.output,
            drSharePath="",
        )

        for sock in outputNode.inputs:
            conNode = NodesExport.GetConnectedNode(ntree, sock)
            if conNode:
                _vray_for_blender.exportNode(ntree.as_pointer(),
                                             conNode.as_pointer(),
                                             sock.as_pointer())

        _vray_for_blender.exit(exporter)

        return {'FINISHED'}
Ejemplo n.º 12
0
    def execute(self, context):
        listAttr = LibUtils.GetPropGroup(self.list_parent, self.list_attr)

        if listAttr.list_item_selected >= 0:
            listAttr.list_items.remove(listAttr.list_item_selected)
            listAttr.list_item_selected -= 1

        if len(listAttr.list_items):
            if listAttr.list_item_selected < 0:
                listAttr.list_item_selected = 0
        else:
            listAttr.list_item_selected = -1

        return {'FINISHED'}
Ejemplo n.º 13
0
    def draw(self, context):
        wide_ui = context.region.width > classes.narrowui

        layout = self.layout

        split = layout.split()
        col = split.column()

        if bpy.data.lamps:
            for lamp in bpy.data.lamps:
                VRayLight = lamp.vray
                VRayScene = context.scene.vray

                lightPluginName = LibUtils.GetLightPluginName(lamp)

                lightPropGroup = getattr(VRayLight, lightPluginName)

                sub_t = col.row()
                sub_t.label(text=" %s" % lamp.name, icon='LAMP_%s' % lamp.type)

                if lightPluginName == 'SunLight':
                    sub = col.row()
                    sub.prop(lightPropGroup, 'enabled', text="")

                    r = sub.row()
                    r.scale_x = 0.4
                    r.prop(lightPropGroup, 'filter_color', text="")

                    sub.prop(lightPropGroup, 'intensity_multiplier', text="")
                    sub.prop(lightPropGroup, 'shadow_subdivs', text="")

                else:
                    sub = col.row()
                    sub.prop(lightPropGroup, 'enabled', text="")
                    sub.prop(lightPropGroup, 'color', text="")

                    if hasattr(lightPropGroup, 'intensity'):
                        sub.prop(lightPropGroup, 'intensity', text="")
                    if hasattr(lightPropGroup, 'power'):
                        sub.prop(lightPropGroup, 'power', text="")
                    if hasattr(lightPropGroup, 'subdivs'):
                        sub.prop(lightPropGroup, 'subdivs', text="")
                    if hasattr(lightPropGroup, 'shadowSubdivs'):
                        sub.prop(lightPropGroup, 'shadowSubdivs', text="")
        else:
            col.label(text="Nothing in bpy.data.lamps...")
Ejemplo n.º 14
0
    def submitCmd(self):
        VRayPreferences = bpy.context.user_preferences.addons[
            'vb30'].preferences

        cmd = [VRayPreferences.vray_cloud_binary, "job", "submit"]

        cmd.append("--project")
        cmd.append(self.project)

        cmd.append("--name")
        cmd.append(LibUtils.FormatName(self.name))

        cmd.append("--sceneFile")
        cmd.append(self.sceneFile)

        cmd.append("--renderMode")
        cmd.append(self.renderMode)

        cmd.append("--width")
        cmd.append(str(self.width))

        cmd.append("--height")
        cmd.append(str(self.height))

        if self.animation:
            cmd.append("--animation")

            cmd.append("--frameRange")
            cmd.append(self.frameRange)

            cmd.append("--frameStep")
            cmd.append(str(self.frameStep))

        if self.ignoreWarnings:
            cmd.append("--ignoreWarnings")

        return cmd
Ejemplo n.º 15
0
 def execute(self, context):
     listAttr = LibUtils.GetPropGroup(self.list_parent, self.list_attr)
     listAttr.list_items.add()
     listAttr.list_items[-1].name = self.def_item_name
     listAttr.list_item_selected = len(listAttr.list_items) - 1
     return {'FINISHED'}
Ejemplo n.º 16
0
def CreateFakeName():
    return ".VRayFakeTexture@%s" % LibUtils.GetUUID()
Ejemplo n.º 17
0
    def execute(self, context):
        if not self.asset_name:
            self.report({'ERROR'}, "Asset name is not set!")
            return {'CANCELLED'}

        presetsPath       = PathUtils.CreateDirectory(os.path.join(SysUtils.GetUserConfigDir(), "presets"))
        userNodeAssetPath = PathUtils.CreateDirectory(os.path.join(presetsPath, self.asset_type))

        fileName = "%s.vrscene" % LibUtils.CleanString(bpy.path.display_name(self.asset_name))

        outputFilepath = os.path.normpath(os.path.join(userNodeAssetPath, fileName))

        # Create exporter (output)
        o = VRayStream.VRaySimplePluginExporter(outputFilepath)

        exporter = _vray_for_blender.init(
            engine  = 0,
            context = bpy.context.as_pointer(),
            scene   = bpy.context.scene.as_pointer(),
            data    = bpy.data.as_pointer(),

            mainFile     = o.output,
            objectFile   = o.output,
            envFile      = o.output,
            geometryFile = o.output,
            lightsFile   = o.output,
            materialFile = o.output,
            textureFile  = o.output,

            drSharePath = "",
        )

        # Get selected nodes
        ntree        = context.space_data.edit_tree
        selectedNode = context.selected_nodes[0]

        if selectedNode.bl_idname == 'VRayNodeRenderChannels':
            pluginNames = []

            for inSock in selectedNode.inputs:
                pluginNames.append(NodesExport.WriteConnectedNode(None, ntree, inSock))

            pluginName = "List(%s)" % ",".join(pluginNames)

        else:
            if selectedNode.bl_idname == 'VRayNodeOutputMaterial':
                selectedNode = NodesExport.GetConnectedNode(ntree, selectedNode.inputs['Material'])

            pluginName = _vray_for_blender.exportNode(
                ntree.as_pointer(),
                selectedNode.as_pointer(),
                None
            )

        # Write fake Asset node
        o.set('MAIN', 'Asset', self.asset_type.capitalize())
        o.writeHeader()
        o.writeAttibute(self.asset_type, pluginName)
        o.writeFooter()
        o.done()

        _vray_for_blender.exit(exporter)

        return {'FINISHED'}
Ejemplo n.º 18
0
    def execute(self, context):
        VRayScene = context.scene.vray
        BatchBake = VRayScene.BatchBake
        VRayBake = VRayScene.BakeView

        # Copy selection
        selection = [ob for ob in context.selected_objects]

        formatDict = LibUtils.GetDefFormatDict()

        obList = None
        if BatchBake.work_mode == 'SELECTION':
            obList = selection
        elif BatchBake.work_mode == 'LIST':
            obList = [
                item.ob for item in BatchBake.list_items
                if item.use and item.ob
            ]

        numObjects = len(obList)

        # Backup some settings
        ValueBackup(VRayScene.SettingsOutput, 'img_dir')
        ValueBackup(VRayScene.SettingsOutput, 'img_file')
        ValueBackup(VRayScene.Exporter, 'autoclose')
        ValueBackup(VRayScene.Exporter, 'auto_save_render')

        if numObjects:
            VRayScene.Exporter.auto_save_render = True

            # We have to wait for render end
            # only if baking multiple objects
            if numObjects > 1:
                VRayScene.Exporter.wait = True
                VRayScene.Exporter.autoclose = True

            try:
                for ob in obList:
                    debug.PrintInfo("Baking: %s..." % ob.name)
                    VRayScene.Exporter.currentBakeObject = ob

                    # UV channel to use for baking
                    uv_channel = None

                    # Find UV map index
                    if BatchBake.uv_map == 'UV_DEFAULT':
                        if len(ob.data.uv_layers):
                            uv_channel = 0

                    elif BatchBake.uv_map == 'UV_VRAYBAKE':
                        uv_channel = GetUVChannelIndex(ob, "VRayBake")

                    # Add projection if need
                    elif BatchBake.uv_map.startswith('UV_NEW_'):
                        uvName = None
                        if BatchBake.uv_map == 'UV_NEW_SMART':
                            uvName = "VRayBakeSmart"
                        elif BatchBake.uv_map == 'UV_NEW_LM':
                            uvName = "VRayBakeLightmap"

                        uv_channel = GetUVChannelIndex(ob, uvName)
                        if uv_channel is None:
                            if ob.mode in {'EDIT'}:
                                bpy.ops.object.mode_set(mode='OBJECT')

                            bpy.ops.object.select_all(action='DESELECT')

                            ob.select = True
                            context.scene.objects.active = ob

                            if BatchBake.uv_map == 'UV_NEW_SMART':
                                bpy.ops.object.mode_set(mode='EDIT')
                                bpy.ops.mesh.select_all(action='SELECT')

                                layer = ob.data.uv_textures.new(name=uvName)
                                layer.active = True

                                bpy.ops.uv.smart_project(
                                    angle_limit=BatchBake.smart_uv.angle_limit,
                                    island_margin=BatchBake.smart_uv.
                                    island_margin,
                                    user_area_weight=BatchBake.smart_uv.
                                    user_area_weight,
                                )

                                bpy.ops.mesh.select_all(action='DESELECT')
                                bpy.ops.object.mode_set(mode='OBJECT')

                            elif BatchBake.uv_map == 'UV_NEW_LM':
                                bpy.ops.uv.lightmap_pack(
                                    PREF_CONTEXT='ALL_FACES',
                                    PREF_NEW_UVLAYER=True,
                                    PREF_BOX_DIV=BatchBake.lightmap_uv.
                                    PREF_BOX_DIV,
                                    PREF_MARGIN_DIV=BatchBake.lightmap_uv.
                                    PREF_MARGIN_DIV,
                                )
                                ob.data.uv_textures[-1].name = uvName

                            uv_channel = len(ob.data.uv_textures) - 1

                    if uv_channel is None:
                        debug.PrintError("UV Map is not found!")
                        continue

                    # Bake settings
                    VRayScene.BakeView.bake_node = ob.name
                    VRayScene.BakeView.uv_channel = uv_channel

                    # Setup vars
                    formatDict['$O'] = ("Object Name",
                                        LibUtils.CleanString(ob.name,
                                                             stripSigns=False))

                    # Render
                    VRayScene.SettingsOutput.img_file = LibUtils.FormatName(
                        BatchBake.output_filename, formatDict)
                    VRayScene.SettingsOutput.img_dir = LibUtils.FormatName(
                        BatchBake.output_dirpath, formatDict)

                    bpy.ops.render.render()

            except Exception as e:
                debug.PrintError("Erorr baking objects!")
                debug.ExceptionInfo(e)

        # Restore selection
        for ob in selection:
            ob.select = True

        RestoreSettings(context.scene)

        return {'FINISHED'}
Ejemplo n.º 19
0
def proxy_save_materials():

    #scene > node tools > path same than proxy export path
    GeomMeshFile = bpy.context.object.data.vray.GeomMeshFile
    outputDirpath = BlenderUtils.GetFullFilepath(GeomMeshFile.dirpath)
    bpy.context.scene.vray.Exporter.ntreeExportDirectory = PathUtils.CreateDirectory(
        outputDirpath)

    print()
    print("outputDirpath:", outputDirpath)
    print()

    o = bpy.context.object

    filenames = []
    nodenames = []
    proxyname = o.data.vray.GeomMeshFile.filename

    #change node names
    for i, mat in enumerate(o.data.materials):

        nodename = mat.vray.ntree.name
        nodenames.append(nodename)

        #get Material Output, check node type and change node name for later material slot order
        nodeindex = nodes_iterate(mat, True)
        mat.vray.ntree.nodes[nodeindex].name = SLOT + str(i)

        #print (i)
        #print (mat.name)
        #print ("nodename:", nodename)
        #mat.vray.ntree.name = proxyname + "_ProxyMat_" + mat.name + "_slot_" + str(i)

        #not sure about this
        #mat.vray.ntree.name = proxyname + SLOT + str(i)

        #print ("new nodename:",mat.vray.ntree.name)

        filenames.append(
            os.path.join(
                outputDirpath,
                LibUtils.CleanString(mat.vray.ntree.name) + '.vrscene'))

    #save nodes
    print("Saving...")
    for mat in o.data.materials:

        nodename = mat.vray.ntree.name
        print("Saving nodename:", nodename)
        i = bpy.data.node_groups.find(nodename)
        bpy.context.scene.vray.Exporter.ntreeListIndex = i
        bpy.ops.vray.export_nodetree()

    #change node names back to original
    for i, mat in enumerate(o.data.materials):
        mat.vray.ntree.name = nodenames[i]

    #print filenames

    for name in filenames:
        print("Filename:", name)

    proxy_files_join(outputDirpath, filenames, proxyname)

    print(len(o.data.materials), ": materials saved")
Ejemplo n.º 20
0
    def execute(self, context):
        sce = context.scene

        # Use current active object UI for initial settings
        ob = bpy.context.object
        selection = bpy.context.selected_objects
        oneObject = len(selection)

        GeomMeshFile = ob.data.vray.GeomMeshFile

        # Create output path
        outputIsRelative = BlenderUtils.IsPathRelative(GeomMeshFile.dirpath)

        outputDirpath = BlenderUtils.GetFullFilepath(GeomMeshFile.dirpath)
        outputDirpath = PathUtils.CreateDirectory(outputDirpath)

        # Create tmp export file
        vrsceneFilepath = os.path.join(tempfile.gettempdir(), "vrmesh.vrscene")
        vrsceneFile = open(vrsceneFilepath, 'w')

        # Settings
        frames = None
        frameStart = 1
        frameStep = 1
        if GeomMeshFile.animation not in {'NONE'}:
            if GeomMeshFile.animation == 'MANUAL':
                frameStart = GeomMeshFile.frame_start
                frames = (frameStart, GeomMeshFile.frame_end, 1)
            else:
                frameStart = sce.frame_start
                frameStep = sce.frame_step
                frames = (sce.frame_start, sce.frame_end, sce.frame_step)

        applyTm = GeomMeshFile.apply_transforms
        useVelocity = GeomMeshFile.add_velocity

        # Export objects meshes and generate nodes name list
        obPluginNames = []
        o = VRayStream.VRaySimplePluginExporter(outputFile=vrsceneFile)

        exporter = _vray_for_blender.init(
            engine=0,
            context=bpy.context.as_pointer(),
            scene=sce.as_pointer(),
            data=bpy.data.as_pointer(),
            mainFile=o.output,
            objectFile=o.output,
            envFile=o.output,
            geometryFile=o.output,
            lightsFile=o.output,
            materialFile=o.output,
            textureFile=o.output,
            drSharePath="",
        )

        _vray_for_blender.initAnimation(True, frameStart, 1)

        _vray_for_blender.setFrame(frameStart)

        for ob in selection:
            if ob.type in BlenderUtils.NonGeometryTypes:
                continue
            nodeName = None
            if not frames:
                nodeName = ExportMeshSample(o, ob)
            else:
                sce = bpy.context.scene
                frame_current = sce.frame_current
                for f in range(frames[0], frames[1] + frames[2], frames[2]):
                    bpy.context.scene.frame_set(f)
                    _vray_for_blender.setFrame(f)
                    nodeName = ExportMeshSample(o, ob)
                    _vray_for_blender.clearCache()
                sce.frame_set(frame_current)
            obPluginNames.append([ob, nodeName])
        o.done()
        vrsceneFile.close()

        _vray_for_blender.clearFrames()
        _vray_for_blender.exit(exporter)

        # Launch the generator tool
        err = None
        for ob, nodeName in obPluginNames:
            vrmeshName = LibUtils.CleanString(ob.name)
            if oneObject and GeomMeshFile.filename:
                vrmeshName = GeomMeshFile.filename
            vrmeshName += ".vrmesh"
            vrmeshFilepath = os.path.join(outputDirpath, vrmeshName)

            err = LaunchPly2Vrmesh(vrsceneFilepath, vrmeshFilepath, nodeName,
                                   frames, applyTm, useVelocity)
            if err is not None:
                break

            if GeomMeshFile.proxy_attach_mode != 'NONE':
                attachOb = ob

                if GeomMeshFile.proxy_attach_mode == 'NEW':
                    newName = '%s@VRayProxy' % ob.name
                    newMesh = bpy.data.meshes.new(newName)
                    attachOb = bpy.data.objects.new(newName, newMesh)

                    context.scene.objects.link(attachOb)

                BlenderUtils.SelectObject(attachOb)

                if GeomMeshFile.proxy_attach_mode == 'NEW':
                    for slot in ob.material_slots:
                        if slot and slot.material:
                            attachOb.data.materials.append(slot.material)
                            attachOb.material_slots[-1].link = 'OBJECT'
                            attachOb.material_slots[
                                -1].material = slot.material

                if GeomMeshFile.apply_transforms:
                    bpy.ops.object.transform_apply(location=True,
                                                   rotation=True,
                                                   scale=True)
                else:
                    attachOb.matrix_world = ob.matrix_world

                CreateProxyNodetree(attachOb, vrmeshFilepath, outputIsRelative)

                if GeomMeshFile.proxy_attach_mode in {'NEW', 'REPLACE'}:
                    LoadProxyPreviewMesh(attachOb, vrmeshFilepath,
                                         GeomMeshFile.anim_type,
                                         GeomMeshFile.anim_offset,
                                         GeomMeshFile.anim_speed,
                                         context.scene.frame_current - 1)

        # Remove temp export file
        os.remove(vrsceneFilepath)

        if err:
            self.report({'ERROR'},
                        "Error generating VRayProxy! Check system console!")
            debug.PrintError(err)
            return {'CANCELLED'}

        self.report({'INFO'}, "Done creating proxy!")

        return {'FINISHED'}
Ejemplo n.º 21
0
def GetNodeName(ntree, node):
    return LibUtils.CleanString("NT%sN%s" % (ntree.name, node.name))
def LightIsAmbient(lamp):
    if LibUtils.GetLightPluginName(lamp) in {'LightAmbientMax'}:
        return True
    return False