Exemple #1
0
    def copy_mc_sequence(self, source, dest):
        ''' Mode 0 is copy the sequence to the root directory
            Mode 1 is copy the sequence to a named subdirectory '''

        if source != None:
            ext = ".mc"
            flist = self.matchfiles(os.path.dirname(source + "Frame"),ext)
            seqbase = os.path.splitext(source)[0]
            subbase = os.path.split(source)[0]
            nummc = float(len(flist))
            curmc = 0.0
            for f in flist:
                seq1 = f[len(seqbase)-1:]
                seqnum = seq1[:4]

                newdest = os.path.join(os.path.dirname(dest), f)
                self.psCopy( os.path.join(os.path.dirname(source),f) , newdest)
                lwsdk.command("StatusMsg {%.2f}Copying sequence ..." % (curmc / nummc))
                curmc += 1.0

                seq1 = flist[0][len(seqbase)-1:]
                seqnum = seq1[:4]
                lwsdk.command("StatusMsg Done copying sequences.")
            return dest + seqbase.strip() + seqnum + ext
            ftest.close()
        else:
            return -1
def process_surfaces(files, vertexGroups, materials):
    for k in range(len(vertexGroups)):
        shader = materials[k]['name']
        surface_funcs = lwsdk.LWSurfaceFuncs()
        surface = surface_funcs.first()
        while surface:
            if surface_funcs.name(surface) == shader:
                #print "\r"
                #print surface_funcs.name(surface)
                lwsdk.command('Surf_SetSurf ' + shader)
                createMaterial(files, vertexGroups, materials, shader)
                break
            surface = surface_funcs.next(surface)
Exemple #3
0
    def active_change(self, control, data):
        if not self._selected_camera:
            return

        self._camera_active[self._selected_camera_name] = (
            True if control.get_int() else False)

        # add/remove the RingTest plug-in

        if self._camera_active[self._selected_camera_name]:
            lwsdk.command("ApplyServer CustomObjHandler ComRingTest")
            self._controls[3].unghost()
            self._controls[4].unghost()
        else:
            lwsdk.command("RemoveServer CustomObjHandler 1")
            self._controls[3].ghost()
            self._controls[4].ghost()
Exemple #4
0
    def process(self, generic_access):
        #launch interface

        print("export_three_layout process()")

        lwsdk.command("StatusMsg export_three_layout")

        #lwsdk.command("LoadScene " + "E:/3Dstuff/Packaged Scenes/FirstAlphaConstruct10-19-12/Scenes/fivechairs.lws")

        mesh = lwsdk.LWMeshInfo()

        #lwsdk.command("SaveObject " + "E:/3Dstuff/Packaged Scenes/FirstAlphaConstruct10-19-12/Scenes/fivechairs.lwo")

        #item_info = lwsdk.LWItemInfo()
        #obj_info = lwsdk.LWObjectInfo()

        return lwsdk.AFUNC_OK
Exemple #5
0
    def radius_change(self, control, data):
        if not self._selected_camera:
            return

        self._camera_radii[self._selected_camera_name] = control.get_float()

        if self._camera_active[self._selected_camera_name]:
            # tell the ringtest.p plug-in to alter its radius

            ring_data = self._comring.encodeData(
                'd',
                (self._camera_radii[self._selected_camera_name] / 100.0, ))
            if ring_data:
                ring_code = int(lwsdk.itemid_to_str(self._selected_camera), 16)
                self._comring.ringMessage("ringtest_channel", ring_code,
                                          ring_data)
                self._comring.releaseData(ring_data)
                lwsdk.command("RefreshNow")
Exemple #6
0
    def camera_change(self, control, data):
        self._selected_camera = control.get_addr()

        if self._selected_camera:
            self._selected_camera_name = self._item_info.name(
                self._selected_camera)
            lwsdk.command("SelectItem %s" %
                          lwsdk.itemid_to_str(self._selected_camera))
            self._controls[2].unghost()

            if (not len(self._camera_active)) or (self._selected_camera_name
                                                  not in self._camera_active):
                self._controls[2].set_int(0)
                self._controls[3].ghost()
                self._controls[4].ghost()

            else:
                if (not len(self._camera_radii)) or (
                        self._selected_camera_name not in self._camera_radii):
                    self._camera_radii[self._selected_camera_name] = 100.0

                if (not len(self._camera_target)) or (
                        self._selected_camera_name not in self._camera_target):
                    self._camera_target[self._selected_camera_name] = False

                self._controls[2].set_int(1 if self._camera_active[
                    self._selected_camera_name] else 0)

                if self._camera_active[self._selected_camera_name]:
                    self._controls[3].unghost()
                    self._controls[4].unghost()

                    if len(self._camera_target) and (self._selected_camera_name
                                                     in self._camera_target):
                        self._controls[3].set_int(1 if self._camera_target[
                            self._selected_camera_name] else 0)
                    if len(self._camera_radii) and (self._selected_camera_name
                                                    in self._camera_radii):
                        self._controls[4].set_float(
                            self._camera_radii[self._selected_camera_name])
        else:
            self._controls[2].ghost()
            self._controls[3].ghost()
            self._controls[4].ghost()
    def process(self, generic_access):
        #launch interface
        
        print("export_three_layout process()")
        
        lwsdk.command("StatusMsg export_three_layout")
        
        #lwsdk.command("LoadScene " + "E:/3Dstuff/Packaged Scenes/FirstAlphaConstruct10-19-12/Scenes/fivechairs.lws")
        
        mesh = lwsdk.LWMeshInfo()
        
        
        #lwsdk.command("SaveObject " + "E:/3Dstuff/Packaged Scenes/FirstAlphaConstruct10-19-12/Scenes/fivechairs.lwo")
         
        #item_info = lwsdk.LWItemInfo()
        #obj_info = lwsdk.LWObjectInfo()
           

        return lwsdk.AFUNC_OK
    def panel_close_callback(self, panel, data):
        """ If the panel is closed by the user, let's destroy all Panel assets
        so we have a clean slate to recreate all assets in the inter_ui() method
        if the user chooses to open this plugin instance again.
        """
        # We better make sure the presets are stored and saved
        self.store_preset()

        # Calling destroy() here, crashes LightWave (v11.0), so I have it
        # commented out, and relies on only setting the variables to None.
        # self._ui.destroy(self._panel)
        self._panel = None
        self._ui = None
        self._controls = None

        # Perhaps it would be better to remove the plugin completely when
        # closing the window? I keep that line here, commented out, during dev
        # until I've decided. If I keep it, I need to add a method to find the
        # actual index in the Master Plugins list.
        lwsdk.command('RemoveServer MasterHandler 1')
Exemple #9
0
    def target_change(self, control, data):
        if not self._selected_camera:
            return

        self._camera_target[self._selected_camera_name] = (
            True if control.get_int() else False)

        if self._target_object:
            lwsdk.command("SelectItem %s" %
                          lwsdk.itemid_to_str(self._selected_camera))

            if self._camera_target[self._selected_camera_name]:
                lwsdk.command("TargetItem %s" %
                              lwsdk.itemid_to_str(self._target_object))
            else:
                lwsdk.command("TargetItem 0")

        # send some sample data to the ringtest.p plug-in
        # each time the target is changed.  this is just
        # dummy data

        strings = ("Falicitations!", "Salutations!", "Greetings!")
        floats = (6.6666, 7.7777, 8.8888, 9.9999, 0.0000)

        ring_data = self._comring.encodeData(('s:100#3', 'i', 'd', 'f#5'),
                                             (strings, 67832, 34.8765, floats))
        if ring_data:
            self._comring.ringMessage("ringtest_channel", 2, ring_data)
            self._comring.releaseData(ring_data)
Exemple #10
0
    def effector_change(self, control, data):
        self._target_object = control.get_addr()

        if self._target_object:
            # tell the ringtest.p plug-in it has a new target object

            ring_data = self._comring.encodeData('k', (self._target_object, ))
            if ring_data:
                self._comring.ringMessage("ringtest_channel", 1, ring_data)
                self._comring.releaseData(ring_data)

            if len(self._camera_target):
                for i in self._camera_target.keys():
                    if self._camera_target[i]:
                        lwsdk.command("SelectItemByName %s" % i)
                        lwsdk.command("TargetItem %s" %
                                      lwsdk.itemid_to_str(self._target_object))

                lwsdk.command("RefreshNow")
        else:
            # tell the ringtest.p plug-in it has no target object

            ring_data = self._comring.encodeData('k', (0, ))
            if ring_data:
                self._comring.ringMessage("ringtest_channel", 1, ring_data)
                self._comring.releaseData(ring_data)
Exemple #11
0
    def process(self, ga):
        self._item_info = lwsdk.LWItemInfo()

        instance_null = lwsdk.find_object_by_name("InstanceNull",
                                                  self._item_info)
        if not instance_null:
            return lwsdk.AFUNC_OK

        instance_null_id = lwsdk.itemid_to_str(instance_null)
        lwsdk.command("SelectItem %s" % instance_null_id)

        server_name = self._item_info.server(instance_null, "InstancerHandler",
                                             1)
        if not server_name:
            print >> sys.stderr, 'No Instancer server found for object "InstanceNull"!'
            return lwsdk.AFUNC_OK

        server_flags = self._item_info.serverFlags(instance_null,
                                                   "InstancerHandler", 1)
        if (server_flags & lwsdk.LWSRVF_DISABLED):
            lwsdk.command("EnableServer InstancerHandler 0 1")
        else:
            lwsdk.command("EnableServer InstancerHandler 0 0")

        return lwsdk.AFUNC_OK
Exemple #12
0
    def copy_sequence(self, source, sourcename, dest, mode):
        ''' Mode 0 is copy the sequence to the root directory
            Mode 1 is copy the sequence to a named subdirectory '''

        if source != None:
            seqbase = os.path.splitext(os.path.basename(sourcename.replace('(sequence)','') ) )[0]
            ext = os.path.splitext(source)[1]
            flist = self.matchfiles(os.path.dirname(source),ext)
            subbase = os.path.split(source)[0]

            numimgs = float(len(flist))
            curimg = 0.0
            for f in flist:
                seq1 = f[len(seqbase)-1:]
                seqnum = seq1[:4]
                if mode == 1:
                    newdest = os.path.join(dest, seqbase[:-2], seqbase.strip() + seqnum + ext)
                else:
                    newdest = dest + seqbase.strip() + seqnum + ext
                self.psCopy( os.path.join(os.path.dirname(source),f) , newdest)
                lwsdk.command("StatusMsg {%.2f}Copying sequence ..." % (curimg / numimgs))
                curimg += 1.0
            if mode == 1:
                seq1 = flist[0][len(seqbase)-1:]
                seqnum = seq1[:4]
                lwsdk.command("StatusMsg Done copying sequences.")
                return os.path.join(dest, seqbase[:-2], seqbase.strip() + seqnum + ext)
            else:
                seq1 = flist[0][len(seqbase)-1:]
                seqnum = seq1[:4]
                lwsdk.command("StatusMsg Done copying sequences.")
                return dest + seqbase.strip() + seqnum + ext
        else:
            return -1
 def rotateAllObjects(self, sign):
     lwsdk.command("SelectAllObjects")
     
     # using pcore
     #print >>sys.stderr, "NumObjects= %d"%pcore.LWObjectFuncs().numObjects()
     #for oo in range(0, pcore.LWObjectFuncs().numObjects()):
         #print >>sys.stderr, "NumObjects= %d"%pcore.LWObjectFuncs().maxLayers(oo)
     #numLayer = pcore.LWObjectFuncs().maxLayers(0)
     
     lwsdk.command("FirstItem")
     if len(lwsdk.LWInterfaceInfo().selected_items()) == 0:
         return
     firstItemID = lwsdk.LWInterfaceInfo().selected_items()[0]
     if (firstItemID == None):
         return
     for l in range(0, 50000):
         if (sign == 1.0):
             lwsdk.command("AddRotation 0 -90 0")
         else:
             lwsdk.command("AddRotation 0 90 0")
         lwsdk.command("NextItem")
         itemID = lwsdk.LWInterfaceInfo().selected_items()[0]
         if (itemID == firstItemID):
             break
Exemple #14
0
    def tool_up(self, event):
        if (self._handle >= 0) and self._moved:
            new_bones = deepcopy(self._bones)

            # Make sure ParentInPlace is OFF
            pip = ((lwsdk.LWInterfaceInfo().generalFlags & lwsdk.LWGENF_PARENTINPLACE) == lwsdk.LWGENF_PARENTINPLACE)
            if pip:
                lwsdk.command("ParentInPlace")

            for bone in self._bones:
                new_bones.append(self.split_bone(bone, self._frac))

            if pip:
                lwsdk.command("ParentInPlace")

            for i in range(len(new_bones)):
                if i == 0:
                    lwsdk.command("SelectItem %s" % lwsdk.itemid_to_str(new_bones[i].id))
                else:
                    lwsdk.command("AddToSelection %s" % lwsdk.itemid_to_str(new_bones[i].id))

        self._handle = -1
    def process(self, ga):
        self._item_info = lwsdk.LWItemInfo()

        instance_null = lwsdk.find_object_by_name("InstanceNull", self._item_info)
        if not instance_null:
            return lwsdk.AFUNC_OK

        instance_null_id = lwsdk.itemid_to_str(instance_null)
        lwsdk.command("SelectItem %s" % instance_null_id)

        server_name = self._item_info.server(instance_null, "InstancerHandler", 1);
        if not server_name:
            print >>sys.stderr, 'No Instancer server found for object "InstanceNull"!'
            return lwsdk.AFUNC_OK

        server_flags = self._item_info.serverFlags(instance_null, "InstancerHandler", 1);
        if (server_flags & lwsdk.LWSRVF_DISABLED):
            lwsdk.command("EnableServer InstancerHandler 0 1")
        else:
            lwsdk.command("EnableServer InstancerHandler 0 0")

        return lwsdk.AFUNC_OK
 def process(self, ga):
   lwsdk.command('AddNull ODCopy')
   lwsdk.command('ModCommand_OD_LWPasteFromExternal Layout')
   return lwsdk.AFUNC_OK
Exemple #17
0
    def split_bone(self, bone, split):
        cur_time = lwsdk.LWTimeInfo().time;
        pos = self._item_info.param(bone.id, lwsdk.LWIP_W_POSITION, cur_time)
        rest_pos = Vector(self._bone_info.restParam(bone.id, lwsdk.LWIP_POSITION))
        rest_rot = Vector(self._bone_info.restParam(bone.id, lwsdk.LWIP_ROTATION))
        rest_rot *= math.pi / 180.0
        rest_len = bone.restlength

        # Clone the existing bone
        # Make the new bone the parent, existing bone the child

        lwsdk.command("SelectItem %s" % lwsdk.itemid_to_str(bone.id))
        lwsdk.command("Clone 1")

        selected_items = lwsdk.LWInterfaceInfo().selected_items()
        new_bone = PyBone(selected_items[0],
                        self._item_info.parent(selected_items[0]),
                        self._bone_info.type(selected_items[0]),
                        self._bone_info.restLength(selected_items[0]))

        # Make new bone child of original parent
        lwsdk.command("ParentItem %s" % lwsdk.itemid_to_str(bone.parent))

        # Motion options corrections:
        # - Don't copy over the goal
        lwsdk.command("GoalItem 0")

        if new_bone.type == lwsdk.LWBONETYPE_ZAXIS:
            temp_vector = Vector(0,0,1)
            split_pos = temp_vector * (rest_len * split)

            # Make new bone shorter to the split
            lwsdk.command("BoneRestLength %g" % (rest_len * split))

            # Make corrections to existing bone
            # - Parent it to the new bone
            # - Place at the split position
            # - Shorten it to the remainder of original length
            # - Reset scale and rotation (as those are now done by new bone)

            lwsdk.command("SelectItem %s" % lwsdk.itemid_to_str(bone.id))
            lwsdk.command("ParentItem %s" % lwsdk.itemid_to_str(new_bone.id))

            # Set positions
            self.set_vec_chan_to_value(bone.id, 0, split_pos)
            lwsdk.command("PivotPosition 0 0 0")
            lwsdk.command("BoneRestPosition %s" % str(split_pos))

            lwsdk.command("BoneRestLength %g" % (rest_len * (1-split)))

            # Set rotations
            self.set_vec_chan_to_value(bone.id, 3, Vector(0,0,0))
            lwsdk.command("PivotRotation 0 0 0")
            lwsdk.command("BoneRestRotation 0 0 0")

            # Set scales
            self.set_vec_chan_to_value(bone.id, 6, Vector(1,1,1));

            lwsdk.command("DirtyMotion")
            lwsdk.command("UpdateMotion")

            # Move children to take into account shortened bone
            child_id = self._item_info.firstChild(bone.id)
            while child_id:
                lwsdk.command("SelectItem %s" % lwsdk.itemid_to_str(child_id))
                self.add_value_to_vec_chan(child_id, 0, -split_pos);
                if self._item_info.type(child_id) == lwsdk.LWI_BONE:
                    child_pos = Vector(self._bone_info.restParam(child_id, lwsdk.LWIP_POSITION))
                    child_pos -= split_pos;
                    lwsdk.command("BoneRestPosition %s" % str(child_pos))

                lwsdk.command("DirtyMotion")
                lwsdk.command("UpdateMotion")

                child_id = self._item_info.nextChild(bone.id, child_id)
        else:
            axispos, axis = self.get_world_bone_axis(bone)

            # Move new bone to split position
            new_rest_pos = rest_pos * split
            lwsdk.command("BoneRestPosition %s" % str(new_rest_pos))
            # newPos = split * pos
            self.mul_value_to_vec_chan(new_bone.id, 0, split)
            lwsdk.command("BoneRestRotation 0 0 0")
            self.set_vec_chan_to_value(new_bone.id, 3, Vector(0,0,0))
            self.set_vec_chan_to_value(new_bone.id, 6, Vector(1,1,1))

            lwsdk.command("DirtyMotion")
            lwsdk.command("UpdateMotion")

            # Make corrections to existing bone
            # - Parent it to the new bone
            lwsdk.command("SelectItem %s" % lwsdk.itemid_to_str(bone.id))
            lwsdk.command("ParentItem %s" % lwsdk.itemid_to_str(new_bone.id))

            # - Correct place to account for new bone parent
            #   New bone parent has no rotation and unit scale,
            #   so only difference is a position offset
            new_rest_pos = rest_pos * (1.0 - split)
            lwsdk.command("BoneRestPosition %s" % str(new_rest_pos))
            # newPos = (1.0 - split) * pos
            self.mul_value_to_vec_chan(bone.id, 0, 1.0 - split)

            lwsdk.command("DirtyMotion")
            lwsdk.command("UpdateMotion")

        return new_bone
    def FreezeAllObjects(self):
        # Now Freeze is asked during upload => no more warning!
        #ok = lwsdk.LWMessageFuncs().okCancel("Sketchfab warning", "With 'Freeze' enabled, the scene can be modified. This option is only usefull for subpatch.", "Do you want to 'Freeze' the scene?")
        #if ok == 0:
        #    return

        lwsdk.command("SelectAllObjects")
        
        lwsdk.command("FirstItem")
        if len(lwsdk.LWInterfaceInfo().selected_items()) == 0:
            return
        firstItemID = lwsdk.LWInterfaceInfo().selected_items()[0]
        if (firstItemID == None):
            return
        nameCount = 0
        for l in range(0, 50000):
            tmpFileName = os.path.join(self._SketchFabTempDataFolder, "tmp%d.lwo"%nameCount)
            nameCount = nameCount+1
            if os.path.isfile(tmpFileName):
                os.remove(tmpFileName)
            lwsdk.command("SaveTransformed "+tmpFileName)
            lwsdk.command("Generic_Reset_All")
            lwsdk.command("ReplaceWithObject "+tmpFileName)

            lwsdk.command("NextItem")
            if os.path.isfile(tmpFileName):
                os.remove(tmpFileName)
            itemID = lwsdk.LWInterfaceInfo().selected_items()[0]
            if (itemID == firstItemID):
                break
def createMaterial(files, vertexGroups, materials, surf):
    textures = getMaterialTypes(files)
    """
	textures: {
	'NP0002_00_Body':    {'NP0002_00_Body_C', 'NP0002_00_Body_A', 'NP0002_00_Body_N'},
	'NP0002_00_Eye':     {'NP0002_00_Eye_C'},
	'NP0002_00_Eyelash': {'NP0002_00_Head_N', 'NP0002_00_Head_C'},
	'NP0002_00_Hair':    {'NP0002_00_Hair_C', 'NP0002_00_Hair_A', 'NP0002_00_Hair_N'},
	'NP0002_00_Head':    {'NP0002_00_Head_N', 'NP0002_00_Head_C'},
	'NP0002_00_Mouth':   set(),
	'NP0002_00_Skin':    {'NP0002_00_Body_C', 'NP0002_00_Body_N'}
	}
	"""

    texture_list = textures[surf]

    NodeBuild = []
    NodeBuild.append("{ Surface\n")
    NodeBuild.append("  \"Default\"\n")
    NodeBuild.append("  SmoothingAngle 1.5625\n")
    NodeBuild.append("  CompatibilityVersion 77b\n")
    NodeBuild.append("  { Nodes\n")
    NodeBuild.append("    { Root\n")
    NodeBuild.append("      Location 0 0\n")
    NodeBuild.append("      Zoom 1\n")
    NodeBuild.append("      Disabled 1\n")
    NodeBuild.append("    }\n")
    NodeBuild.append("    Version 1\n")
    NodeBuild.append("    { Nodes\n")
    NodeBuild.append("      Server \"Surface\"\n")
    NodeBuild.append("      { Tag\n")
    NodeBuild.append("        RealName \"Surface\"\n")
    NodeBuild.append("        Name \"Surface\"\n")
    NodeBuild.append("        Coordinates -1890 -561\n")
    NodeBuild.append("        Mode 1\n")
    NodeBuild.append("        Selected 0\n")
    NodeBuild.append("        { Data\n")
    NodeBuild.append("        }\n")
    NodeBuild.append("        Preview \"\"\n")
    NodeBuild.append("      }\n")
    NodeBuild.append("      Server \"Input\"\n")
    NodeBuild.append("      { Tag\n")
    NodeBuild.append("        RealName \"Input\"\n")
    NodeBuild.append("        Name \"Input\"\n")
    NodeBuild.append("        Coordinates 0 -289\n")
    NodeBuild.append("        Mode 0\n")
    NodeBuild.append("        Selected 0\n")
    NodeBuild.append("        { Data\n")
    NodeBuild.append("        }\n")
    NodeBuild.append("        Preview \"Item ID\"\n")
    NodeBuild.append("      }\n")

    # Add material node
    if 'head' in surf.lower() or 'skin' in surf.lower():
        NodeBuild.append("      Server \"Skin\"\n")
        NodeBuild.append("      { Tag\n")
        NodeBuild.append("        RealName \"Skin\"\n")
        NodeBuild.append("        Name \"Skin (1)\"\n")
        NodeBuild.append("        Coordinates -1260 -480\n")
        '''
		NodeBuild.append("        { Data\n")
		NodeBuild.append("          { Attributes\n")
		NodeBuild.append("            { Metadata\n")
		NodeBuild.append("              Version 1\n")
		NodeBuild.append("              Enumerations 0\n")
		NodeBuild.append("              { AttributeData\n")
		
		#color
		NodeBuild.append("                { Attr\n")
		NodeBuild.append("                  Name \"Epidermis Color\"\n")
		NodeBuild.append("                  Flags 0\n")
		NodeBuild.append("                  Tag \"ENVELOPE\" \"On\"\n")
		NodeBuild.append("                  Tag \"FORMAT\" \"Color\"\n")
		NodeBuild.append("                  Tag \"NodeInputID\" \"\"\n")
		NodeBuild.append("                  { Value\n")
		NodeBuild.append("                    \"vparam3\"\n")
		NodeBuild.append("                    { Value\n")
		NodeBuild.append("                      3\n")
		NodeBuild.append("                      0.9881 0.9098 0.7685\n")
		NodeBuild.append("                    }\n")
		NodeBuild.append("                  }\n")
		NodeBuild.append("                }\n")
		'''
    else:
        NodeBuild.append("      Server \"Principled BSDF\"\n")
        NodeBuild.append("      { Tag\n")
        NodeBuild.append("        RealName \"Principled BSDF\"\n")
        NodeBuild.append("        Name \"Principled BSDF (1)\"\n")
        NodeBuild.append("        Coordinates -894 -393\n")

        NodeBuild.append("        { Data\n")
        NodeBuild.append("          { Attributes\n")
        NodeBuild.append("            { Metadata\n")
        NodeBuild.append("              Version 1\n")
        NodeBuild.append("              Enumerations 0\n")
        NodeBuild.append("              { AttributeData\n")

        #color
        NodeBuild.append("                { Attr\n")
        NodeBuild.append("                  Name \"Color\"\n")
        NodeBuild.append("                  Flags 0\n")
        NodeBuild.append("                  Tag \"ENVELOPE\" \"On\"\n")
        NodeBuild.append("                  Tag \"FORMAT\" \"Percent\"\n")
        NodeBuild.append("                  Tag \"NodeInputID\" \"\"\n")
        NodeBuild.append("                  { Value\n")
        NodeBuild.append("                    \"vparam3\"\n")
        NodeBuild.append("                    { Value\n")
        NodeBuild.append("                      3\n")
        NodeBuild.append("                      0.5 0.5 0.5\n")
        NodeBuild.append("                    }\n")
        NodeBuild.append("                  }\n")
        NodeBuild.append("                }\n")

        #specular
        NodeBuild.append("                { Attr\n")
        NodeBuild.append("                  Name \"Specular\"\n")
        NodeBuild.append("                  Flags 0\n")
        NodeBuild.append("                  Tag \"ENVELOPE\" \"On\"\n")
        NodeBuild.append("                  Tag \"FORMAT\" \"Percent\"\n")
        NodeBuild.append("                  Tag \"NodeInputID\" \"\"\n")
        NodeBuild.append("                  { Value\n")
        NodeBuild.append("                    \"vparam\"\n")
        NodeBuild.append("                    { Value\n")
        NodeBuild.append("                      1\n")
        NodeBuild.append("                      0\n")
        NodeBuild.append("                    }\n")
        NodeBuild.append("                  }\n")
        NodeBuild.append("                }\n")

        #roughness
        NodeBuild.append("                { Attr\n")
        NodeBuild.append("                  Name \"Roughness\"\n")
        NodeBuild.append("                  Flags 0\n")
        NodeBuild.append("                  Tag \"ENVELOPE\" \"On\"\n")
        NodeBuild.append("                  Tag \"FORMAT\" \"Percent\"\n")
        NodeBuild.append("                  Tag \"NodeInputID\" \"\"\n")
        NodeBuild.append("                  { Value\n")
        NodeBuild.append("                    \"vparam\"\n")
        NodeBuild.append("                    { Value\n")
        NodeBuild.append("                      1\n")
        NodeBuild.append("                      1\n")
        NodeBuild.append("                    }\n")
        NodeBuild.append("                  }\n")
        NodeBuild.append("                }\n")

    #close
    NodeBuild.append("              }\n")
    NodeBuild.append("            }\n")
    NodeBuild.append("          }\n")
    NodeBuild.append("        }\n")
    NodeBuild.append("        Preview \"Material\"\n")
    NodeBuild.append("      }\n")

    for t in texture_list:
        loc = (0, 0)
        the_file = ""
        UVMap = lwsdk.LWObjectFuncs().vmapName(lwsdk.LWVMAP_TXUV, 0)

        if t[-2:] == '_C':
            the_file = files.data['tex_dir'] + "\\" + t + ".png"
            loc = CoordinateList["Color"]

            Server = "      Server \"Image\"\n"
            RealName = "        RealName \"Image\"\n"
            Name = "        Name \"Image (1)\"\n"

        elif t[-2:] == '_N':
            the_file = files.data['tex_dir'] + "\\" + t + ".png"
            loc = CoordinateList["Normal"]

            Server = "      Server \"NormalMap\"\n"
            RealName = "        RealName \"NormalMap\"\n"
            Name = "        Name \"NormalMap (1)\"\n"

        elif t[-2:] == '_A':
            the_file = files.data['tex_dir'] + "\\" + t + ".png"
            loc = CoordinateList["Alpha"]

            Server = "      Server \"Image\"\n"
            RealName = "        RealName \"Image\"\n"
            Name = "        Name \"Image (2)\"\n"

        elif t[-2:] == '_O':
            the_file = files.data['tex_dir'] + "\\" + t + ".png"
            loc = CoordinateList["Opacity"]
            if UV_count > 1:
                UVMap = lwsdk.LWObjectFuncs().vmapName(lwsdk.LWVMAP_TXUV, 1)

            Server = "      Server \"Image\"\n"
            RealName = "        RealName \"Image\"\n"
            Name = "        Name \"Image (3)\"\n"

        NodeBuild.append(Server)
        NodeBuild.append("      { Tag\n")
        NodeBuild.append(RealName)
        NodeBuild.append(Name)
        NodeBuild.append("        Coordinates " + loc + "\n")
        NodeBuild.append("        { Data\n")

        if t[-2:] == '_A':
            NodeBuild.append("          InvertColor 1\n")

        NodeBuild.append("          { Image\n")

        if os.path.exists(the_file):
            NodeBuild.append("            { Clip\n")
            NodeBuild.append("              { Still\n")
            NodeBuild.append("                \"" + the_file + "\"\n")
            NodeBuild.append("              }\n")
            NodeBuild.append("            }\n")

        NodeBuild.append("          }\n")
        NodeBuild.append("          Mapping 5\n")
        NodeBuild.append("          UV \"" + UVMap + "\"\n")
        NodeBuild.append("        }\n")
        NodeBuild.append("      }\n")
    NodeBuild.append("    }\n")

    #make them there connections
    NodeBuild.append("    { Connections\n")
    NodeBuild.append("      NodeName \"Surface\"\n")
    NodeBuild.append("      InputName \"Material\"\n")
    if 'head' in surf.lower() or 'skin' in surf.lower():
        NodeBuild.append("      InputNodeName \"Skin (1)\"\n")
    else:
        NodeBuild.append("      InputNodeName \"Principled BSDF (1)\"\n")
    NodeBuild.append("      InputOutputName \"Material\"\n")

    for t in texture_list:
        if t[-2:] == '_A':
            NodeBuild.append("      NodeName \"Surface\"\n")
            NodeBuild.append("      InputName \"Clip\"\n")
            NodeBuild.append("      InputNodeName \"Image (2)\"\n")
            NodeBuild.append("      InputOutputName \"Color\"\n")
        elif t[-2:] == '_C':
            if 'head' in surf.lower() or 'skin' in surf.lower():
                NodeBuild.append("      NodeName \"Skin (1)\"\n")
                NodeBuild.append("      InputName \"Epidermis Color\"\n")
                NodeBuild.append("      InputNodeName \"Image (1)\"\n")
                NodeBuild.append("      InputOutputName \"Color\"\n")

                NodeBuild.append("      NodeName \"Skin (1)\"\n")
                NodeBuild.append("      InputName \"Dermis Color\"\n")
                NodeBuild.append("      InputNodeName \"Image (1)\"\n")
                NodeBuild.append("      InputOutputName \"Color\"\n")
            else:
                NodeBuild.append("      NodeName \"Principled BSDF (1)\"\n")
                NodeBuild.append("      InputName \"Color\"\n")
                NodeBuild.append("      InputNodeName \"Image (1)\"\n")
                NodeBuild.append("      InputOutputName \"Color\"\n")
        elif t[-2:] == '_N':
            if 'head' in surf.lower() or 'skin' in surf.lower():
                NodeBuild.append("      NodeName \"Skin (1)\"\n")
            else:
                NodeBuild.append("      NodeName \"Principled BSDF (1)\"\n")  #
            NodeBuild.append("      InputName \"Normal\"\n")
            NodeBuild.append("      InputNodeName \"NormalMap (1)\"\n")
            NodeBuild.append("      InputOutputName \"Normal\"\n")
        elif t[-2:] == '_O':
            NodeBuild.append("      NodeName \"Image (1)\"\n")
            NodeBuild.append("      InputName \"Opacity\"\n")
            NodeBuild.append("      InputNodeName \"Image (3)\"\n")
            NodeBuild.append("      InputOutputName \"Color\"\n")

    # End connections segment
    NodeBuild.append("      }\n")
    NodeBuild.append("    }\n")
    NodeBuild.append("}\n")

    # Complete the node build by putting it together
    NodeBuild = "".join(NodeBuild)

    f = NamedTemporaryFile(mode='w+', delete=False)
    f.write(NodeBuild)
    f.close()

    lwsdk.command("Surf_LoadText \"" + f.name + "\"")
    os.unlink(f.name)  # delete the file
    def uploadScene(self):
        self.updateTempFolder()
        if self._isMacOSX == False:
            # fix zip problem: on efface tout => comme a la 1ere execution!  (sauf pour APIKey : load+save) 
            self.loadAPIKey()
            try:
                shutil.rmtree(self._SketchFabTempFolder)
                self._SketchFabTempFolder = ""
            except Exception:
                a = 0
            if (os.path.isfile(self._SketchFabTempFolder)):
                print >>sys.stderr, "ERROR BAD ERASE FOLDER!"
            self.updateTempFolder()
            self.saveAPIKey()

        # ------- 1 - define and maybe create the temp folder + install uploader executable
        self.updateTempFolder()
        uploader_installed = self.install_uploader()
        
        if uploader_installed == False:
            self.displayReturnMsg("Failed to install "+self._SketchFabUploaderAppPath)
            return

                    
        # *** define export path: ********
        # fix locking and empty zip with SceneCounter
        scene_path=os.path.join(self._SketchFabTempDataFolder, "scene%d"%self._SceneCounter)
        archive_path = os.path.join(self._SketchFabTempDataFolder, "scene%d.zip"%self._SceneCounter)
        self._SceneCounter = self._SceneCounter+1

        #remove all previously added zip files:
        try:
            shutil.rmtree(self._SketchFabTempDataFolder)
        except Exception:
            a = 0

        if not os.path.exists(scene_path):
            os.makedirs(scene_path)
            if self._isMacOSX: # avoid file rights issue
                os.system("chmod a+w "+scene_path)

        # make valid title:
        if self._title == "":
            self._title = "NoName"

        # ------- 2 - save OBJ/DAE/FBX file
        # 2.1 : prepare the scene: freeze/rotate/detectNGon subpatch
        if self.DetectNGons() == False:
            return
        hasSubPatch = self.DetectSubPatch()
        if hasSubPatch:
            freeze = lwsdk.LWMessageFuncs().yesNo("Sketchfab warning", "Warning: The scene contains SubPatches", "Do you want to freeze them?")
            if (freeze):
                self.FreezeAllObjects()
                #lwsdk.LWMessageFuncs().yesNo("Sketchfab info", "Mesh Freezing Successful.", "")
                #lwsdk.LWMessageFuncs().info("Sketchfab info", "Mesh Freezing Successful.") # depends on user defined alert level
                self.displayMsg("Mesh Freezing Successful.")
            else:
                self.displayMsg("Base cage will then be uploaded.")
            
        if (self._rotate):
            self.rotateAllObjects(1)

        # 2.2: export
        useFBX = True
        if useFBX: # use FBX
            fbxFilename = os.path.join(scene_path, "scene.fbx")
            fbxFilename = fbxFilename.replace('\\', '/')
            #lwcmd = "Generic_ExportFBXCommand '" + fbxFilename + "'"
            lwcmd = "Generic_ExportFBXCommand '" + fbxFilename + "' FBX201100"
            lwcmd = lwcmd  + " True True False True"   # bExportCameras bExportLights bExportMorphs bExportModels
            lwcmd = lwcmd  + " False True True"   # bExportAnimations bExportMaterials bEmbedMedia
            lwcmd = lwcmd  + " False"   # False(ASCII) sAnimLayerName

            # options order: Filename sFBXVersion bExportCameras bExportLights bExportMorphs bExportModels bExportAnimations bExportMaterials bEmbedMedia bType sAnimLayerName
            # sFBXVersion: The version to be written. Valid versions: 'FBX201200', 'FBX201100', 'FBX201000', 'FBX200900', 'FBX200611'
            # bExportCameras: "True" or "False"
            # bExportLights: "True" or "False"
            # bExportMorphs: "True" or "False"
            # bExportModels: "True" or "False"
            # bExportAnimations: "True" or "False"
            # bExportMaterials: "True" or "False"
            # bEmbedMedia: "True" or "False"
            # bType: "True" for ASCII, "False" for binary FBX format
            # sAnimLayerName: The name to give the FBX Animation Layer
            # test script: 
            #import lwsdk
            #lwsdk.command("Generic_ExportFBXCommand 'C:/Dev/test_lw_export.fbx' FBX201100 True True False True False True True False")
            #lwsdk.command("Generic_ExportFBXCommand 'C:/Dev/test_lw_export.fbx' FBX201100 True True False True False True True True") ASCII version!

            logForDebug("Execute Command: "+lwcmd)
            
            lwsdk.command(lwcmd)
            
        else:
            lwcmd = "SaveObject " + os.path.join(scene_path, "scene.lwo")
            logForDebug("Execute Command: "+lwcmd)
            lwsdk.command(lwcmd)
        
        # 2.3: restore rotation
        if (self._rotate):
            self.rotateAllObjects(-1)


        # ------- 3 - compress the file
        if os.path.isfile(archive_path):
            os.remove(archive_path)
        logForDebug("Creating "+archive_path)
        filelist = os.listdir(scene_path)
        archive = zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED)
        saveCWD = os.getcwd()
        os.chdir(scene_path)
        for f in filelist:
            archive.write(f)
            logForDebug("  Add in Zip: "+f)
        archive.close()
        filelist = None
        os.chdir(saveCWD)

        # 3.1 - delete exported scene: le but est d'eviter des problemes de droit sur le Mac
                #os.system("rm -rf "+scene_path)
            #try:
                #shutil.rmtree(self._SketchFabTempDataFolder)
            #except Exception:
                #a = 0
        if self._isMacOSX: # avoid file rights issue
            os.system("chmod a+w "+archive_path)
                
        # ------- 4 - upload archive
        zipSize = os.path.getsize( archive_path )
        self.startWaiting(zipSize)
        
        # 5.1 : write settings text file
        returnmsg_path = os.path.join(self._SketchFabTempDataFolder, "returnmsg.txt")
        
        # clean strings: no newline:
        self._APIKey = self._APIKey.strip('\n')
        self._title = self._title.strip('\n')
        self._description = self._description.strip('\n')
        self._password = self._password.strip('\n')
        
        useCURL = self._isMacOSX

        if useCURL:
            logForDebug("TEST USING CURL !!!")
            if self._isMacOSX:
                cmd = '/usr/bin/curl -k -X POST https://api.sketchfab.com/v1/models'
            else:
                thisScriptFilePath = os.path.realpath(__file__)
                thisScriptFolder = os.path.dirname(thisScriptFilePath)
                #os.chdir(thisScriptFolder)
                #cmd = 'curl' + ' -k -X POST https://api.sketchfab.com/v1/models'
                cmd = 'C:/Dev/curl -k -X POST https://api.sketchfab.com/v1/models'
            cmd = cmd + ' -F "fileModel=@' + archive_path + '"'
            cmd = cmd + ' -F "filenameModel=scene0.zip"'
            cmd = cmd + ' -F "title='+self._title+'"'
            cmd = cmd + ' -F "description='+self._description+'"'
            cmd = cmd + ' -F "tags='+self._tags+' lightwave"'
            cmd = cmd + ' -F "source=lightwave-exporter"'
            if self._private:
                cmd = cmd + ' -F "private=1"'
                cmd = cmd + ' -F "password='******'"'
            cmd = cmd + ' -F "token=' + self._APIKey + '"'
            #cmd = cmd + ' --progress-bar' 
            cmd = cmd + ' -s'   # silent mode
            #cmd = cmd + ' 2> "' + returnmsg_path + '"'
            cmd = cmd + ' -o "' + returnmsg_path + '"'
            logForDebug(cmd)

        else:  # --------------- USE my uploader app 
            settingsFileName = os.path.join(self._SketchFabTempDataFolder, "settings.txt")
            settings_file = open(settingsFileName, 'w')
            settings_file.write(self._APIKey+"\n")
            settings_file.write(self._title+"\n")
            settings_file.write(self._description+"\n")
            settings_file.write(self._tags+"\n")
            if self._private:
                settings_file.write("true\n")
            else:
                settings_file.write("false\n")
            settings_file.write(self._password+"\n")
            settings_file.write(archive_path+"\n")
            settings_file.write(returnmsg_path+"\n")
            settings_file.close()
            logForDebug("settings file :"+settingsFileName)
            if self._isMacOSX: # avoid file rights issue
                os.system("chmod a+w "+settingsFileName)
            
            cmd = self._SketchFabUploaderAppPath+" -s "+settingsFileName


        if self._isMacOSX or useCURL:
            logForDebug("os.system("+cmd+")")
            ret = os.system(cmd)
            logForDebug("  returns:")
            try:
                logForDebug(ret)
            except:
                print >>sys.stderr, "Exception in logForDebug(ret)!" 

        elif True: #windows : NB subprocess.call is not working on MacOSX!
            logForDebug("subprocess.call:"+cmd)
            subprocess.call(cmd, shell=False)
        else:
            logForDebug("POPEN... ")
            p = subprocess.Popen((self._SketchFabUploaderAppPath, "-s", settingsFileName))
            p.wait
        
        # read result:
        if useCURL:
            if ret==0:
                # extract errormsg:
                errormsg = ""
                if os.path.exists(returnmsg_path):
                    logForDebug("curl out file exists ")
                    returnmsg_file = open(returnmsg_path, "r")
                    lines = returnmsg_file.readlines()
                    returnmsg_file.close()
                    if (len(lines) > 0):
                        errormsg = lines[0]
                        if errormsg.find('"success": true') != -1:
                            errormsg = ""


                if errormsg=="":
                    self.displayReturnMsg("Sketchfab upload success!")
                else:
                    self.displayReturnMsg("Sketchfab upload error:"+errormsg)
            else:
                self.displayReturnMsg("Sketchfab upload error! (%d)"%ret)
        else:
            if os.path.isfile(returnmsg_path):
                returnmsg_file = open(returnmsg_path, "r")
                lines = returnmsg_file.readlines()
                returnmsg_file.close()
                if self._isMacOSX: # avoid file rights issue
                    os.system("chmod a+w "+returnmsg_path)
                if (len(lines) > 0):
                    #logForDebug("INFO: Sketchfab:"+lines[0])
                    #lwsdk.LWMessageFuncs().info('Sketchfab:'+lines[0], None)
                    self.displayReturnMsg(lines[0])
            else:
                logForDebug("NO RETURN MSG .txt")
                lwsdk.LWMessageFuncs().info("Sketchfab: No Returned message!", None)
                
            
        self.endWaiting()
Exemple #21
0
    def process(self, ga):
        item_info = lwsdk.LWItemInfo()
        object_info = lwsdk.LWObjectInfo()
        instancer_funcs = lwsdk.LWItemInstancerFuncs()
        instance_info = lwsdk.LWItemInstanceInfo()
        interface_info = lwsdk.LWInterfaceInfo()

        current_time = interface_info.curTime
        autokey_is_on = ((interface_info.generalFlags & lwsdk.LWGENF_AUTOKEY)
                         != 0)

        selected_item = interface_info.selected_items()[0]
        selected_item_id = lwsdk.itemid_to_str(selected_item)

        # find the Instancer that owns the selected object
        found_instancer = None
        obj = item_info.first(lwsdk.LWI_OBJECT, None)
        while obj and (not found_instancer):
            instancer = object_info.instancer(obj)
            if instancer:
                instance = instancer_funcs.first(instancer)
                while instance and (not found_instancer):
                    if instance_info.item(instance) == selected_item:
                        # found it!
                        found_instancer = instancer
                        break
                    instance = instancer_funcs.next(instancer, instance)
            obj = item_info.next(obj)

        if not found_instancer:
            print >> sys.stderr, 'Object "%s" is NOT instanced!' % item_info.name(
                selected_item)
            return lwsdk.AFUNC_OK

        instances = []
        instance = instancer_funcs.first(found_instancer)
        while instance:
            if instance_info.item(instance) == selected_item:
                instances.append(instance)
            instance = instancer_funcs.next(found_instancer, instance)

        # values used for progress
        current_index = 1.0
        target_index = len(instances) * 1.0

        for instance in instances:
            pos = instance_info.pos(instance, 0)
            # Note: InstanceInfo.rotation() returns radians!
            rot = instance_info.rotation(instance, 0)
            scl = instance_info.scale(instance, 0)

            lwsdk.command("SelectItem %s" % selected_item_id)
            lwsdk.command("Clone 1")

            lwsdk.command("Position %s" % str(pos))
            # Note: Rotation expects degrees!
            lwsdk.command("Rotation %s" % str(Vector.to_degrees(rot)))
            lwsdk.command("Scale %s" % str(scl))
            if not autokey_is_on:
                lwsdk.command("CreateKey %f" % current_time)

            lwsdk.command("StatusMsg {%f}Baking instances..." %
                          (current_index / target_index))
            current_index += 1.0

        lwsdk.command("SelectItem %s" % selected_item_id)

        lwsdk.command("StatusMsg Baking complete.")

        return lwsdk.AFUNC_OK
    def apply(self):
        """ Apply selected preset. """
        row = self._controls[0].get_int()
        name = Presets.get_name(row)

        # Reference part of the definitions dictionary
        tabs = Presets.definitions['tabs']
        # Get the selected presets dict to read settings from
        settings = Presets.user['presets'][name]

        # Loop tabs
        for tab in tabs:
            # Loop sections in tab
            for k, v in tabs[tab].iteritems():
                # If section is enabled, apply the commands in the section
                if settings[k] == True:

                    # Loop commands in section
                    for ctl in v['controls']:
                        # Create and set command line
                        val = settings[ctl['command']]

                        if self.gi_tab_logic(settings, ctl['command']) == False:
                            continue

                        if self.fx_tab_logic(settings, ctl['command'], val) == False:
                            continue

                        if self.cam_tab_logic(settings, ctl['command']) == False:
                            continue

                        try:
                            mode = ctl['mode']
                        except:
                            mode = False

                        if ctl['type'] == 'percent':
                            val = val / 100

                        if ctl['type'] == 'minirgb':
                            val = '%(r)s %(g)s %(b)s' % \
                            {'r': val[0] / 255.0, \
                             'g': val[1] / 255.0, \
                             'b': val[2] / 255.0}

                        if ctl['command'] == 'ResolutionMultiplier':
                            # Resolution Converter
                            res = [0.25, 0.5, 1, 2, 4]
                            val = res[val]

                        # Handle buttons that just toggles their state which can
                        # not by command be set to a specific state.
                        if mode == 'toggle':
                            scene = lwsdk.LWSceneInfo()
                            render_flag = getattr(lwsdk, ctl['flag'])
                            if render_flag & scene.renderOpts > 0:
                                button_state = True
                            else:
                                button_state = False

                            if val != button_state:
                                lwsdk.command(ctl['command'])
                        else:
                            lwsdk.command(ctl['command'] + ' ' + str(val))

                        if ctl['command'] == 'EnableRadiosity' and val == False:
                            break
Exemple #23
0
    def process(self, generic_access):
        #launch interface

        ui = lwsdk.LWPanels()
        panel = ui.create('Package Scene')
        panel.setw(750)

        # The consolidate option doesn't move anything, but grabs all assets and puts them in the content structure
        # you're currently using

        self.consolidate_check = panel.bool_ctl("Consolidate files only")
        self.consolidate_check.move(150, self.consolidate_check.y() )
        self.consolidate_check.set_event(self.consolidate_active )

        # The panel.dir_ctl() call creates a requester in which you'll choose the destination folder

        self.target_folder = panel.dir_ctl("Destination folder:", 98)
        self.target_folder.set_event(self.refresh_items)
        self.preserve_check = panel.bool_ctl("Preserve Existing Structure")

        # Subfolders are folders that go below the Objects, Scenes, and Images folders, should they be needed.

        self.asset_string = panel.str_ctl("Subfolder:", 72)
        self.asset_string.set_event(self.refresh_items)

        # This gives the user the option of whether to copy complete image sequences or not.
        # If the user opts not to copy the sequences, only the first image of the sequence will be copied

        self.imseq_check = panel.bool_ctl("Copy Image Sequences")
        self.imseq_check.set_event(self.imseq_active)

        # This selection box gives the user the option to either consolidate all images (including sequences)
        # into the target Images directory, or to have subfolders created for image sequences to keep
        # them neat and tidy

        self.imsub_list = []
        self.imsub_list.append("Root Images folder")
        self.imsub_list.append("Sequence-named subfolder")
        self.imsub_choice = panel.hchoice_ctl("Image sequence destination:", self.imsub_list)
        self.imseq_active(self, self.imseq_active)

        # This displays the eventual path destinations for the individual asset types

        self.sc_string = panel.dir_ctl("Scenes path:", 98)
        self.ob_string = panel.dir_ctl("Objects path:", 98)
        self.im_string = panel.dir_ctl("Images path:", 98)
        self.dyn_string = panel.dir_ctl("Dynamics path:", 98)
        self.ies_string = panel.dir_ctl("Photometric lights path:",98)
        self.rad_string = panel.dir_ctl("Radiosity Cache path:",98)
        self.vert_string = panel.dir_ctl("Vertex Cache path:",98)

        self.radsave_check = panel.bool_ctl("Copy Radiosity cache file")
        self.radsave_check.set_event(self.radcache_active)
        self.radcache_active(self, self.radcache_active)
        self.radsave_check.set_int(1)
        self.rad_string.unghost()
        self.reload_check = panel.bool_ctl("Reload Original Scene")

        panel.align_controls_vertical([self.consolidate_check,
                                       self.target_folder,
                                       self.preserve_check,
                                       self.asset_string,
                                       self.imseq_check,
                                       self.imsub_choice,
                                       self.sc_string,
                                       self.ob_string,
                                       self.im_string,
                                       self.dyn_string,
                                       self.ies_string,
                                       self.rad_string,
                                       self.vert_string,
                                       self.radsave_check,
                                       self.reload_check])

        self.target_folder.set_str(self.content_dir)
        self.refresh_items(None,None)
        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        #end interface ------------------------------------------------------------------------

        #getting values ------------------------------------------------------------------------

        self.consolidate = self.consolidate_check.get_int()

        self.target_dir = self.target_folder.get_str()
        self.preserve = self.preserve_check.get_int()
        self.asset_str = self.asset_string.get_str()

        self.imseq = self.imseq_check.get_int()
        self.imsub = self.imsub_choice.get_int()

        self.ob_dir = self.ob_string.get_str()
        self.sc_dir = self.sc_string.get_str()
        self.im_dir = self.im_string.get_str()
        self.dyn_dir = self.dyn_string.get_str()
        self.ies_dir = self.ies_string.get_str()
        self.rad_dir = self.rad_string.get_str()
        self.vert_dir = self.vert_string.get_str()
        self.radsave = self.radsave_check.get_int()

        self.reload = self.reload_check.get_int()
        
        #end getting values ------------------------------------------------------------------------

        self.comring.ringAttach(self.RINGNAME,self,self.comring_event)
        data = self.comring.encodeData("s:512#2",(self.content_dir, self.target_dir));
        self.comring.ringMessage(self.RINGNAME,1,data); # event #1 would be "copy to new content"
        #self.comring.ringDetatch(self.RINGNAME)

        #begin image processing ------------------------------------------------------------------------
        if self.images.first() != None:  # there are images to be worked on
            if self.consolidate == True:
                asset_str = ""

                self.target_dir = self.content_dir
                self.ob_dir = self.consol_string("Objects")
                self.sc_dir = self.consol_string("Scenes")
                self.im_dir = self.consol_string("Images")
                self.dyn_dir = self.consol_string("Dynamics")
                self.ies_dir = self.consol_string("Lights")
                self.rad_dir = self.consol_string("Radiosity")
                self.vert_dir = self.consol_string("VertCache")

            for currentImage in self.imageMasterList:            
                #construct new path
                currentfile = self.images.filename(currentImage,0)  #current filename from the big list
                currentname = self.images.name(currentImage)
                if self.content_dir in currentfile:
                    validContent = True
                else:
                    validContent = False
# sequence section ----
                if '(sequence)' in currentname and self.imseq == True:              #is a sequence and wants to copy it
                    if validContent == True and self.preserve == 1:                 #wants to preserve, and has a chance
                        #target is the destination content + original directory
                        image_target = os.path.join(self.target_dir,os.path.dirname(currentfile).replace(self.content_dir,'').strip('\\/') )   
                    else:                                                           #don't want to preserve or can't
                        image_target = self.im_dir                                  #not valid content directory, can't preserve
                    
                    first_image = self.copy_sequence(currentfile, currentname, image_target, self.imsub)    # process and copy sequence
                    self.images.replace(currentImage, first_image)

# image section ----------
                else:                                                               #not a sequence
                    if validContent == True and self.preserve == 1:                 #wants to preserve, and has a chance
                        #target is the destination content + original directory
                        image_target = os.path.join(self.target_dir,os.path.dirname(currentfile).replace(self.content_dir,'').strip('\\/') )
                    else:
                        image_target = self.make_content_target(currentfile,self.im_dir)    #get the destination target path
                        self.psCopy(currentfile, image_target)                          #copy, making directories if necessary
                        self.images.replace(currentImage, image_target)                 #replace old image with new
        else:  # no images loaded
            pass # "No Images to copy"

# end image processing -----------------------------

        lwsdk.command("ContentDirectory " + self.target_dir)

# begin object processing ---------------------------------------------

#get object list

        item_info = lwsdk.LWItemInfo()
        obj_info = lwsdk.LWObjectInfo()

        objlist = []
        myobj = item_info.first( lwsdk.LWI_OBJECT, lwsdk.LWITEM_NULL )
        if myobj != lwsdk.LWITEM_NULL:
            objlist.append( myobj )
            while myobj != lwsdk.LWITEM_NULL:
                myobj = item_info.next( myobj )
                if myobj != lwsdk.LWITEM_NULL:
                    objlist.append( myobj )
#get destination path

            for obj in objlist:
                #if item_info.name( obj ) != obj_info.filename( obj ):   # probably isn't a null object
                if obj_info.numPoints( obj ) != 1 and obj_info.numPolygons( obj ) != 0:
                    if self.preserve == True and os.path.dirname(obj_info.filename( obj )) != self.content_dir and self.content_dir in obj_info.filename( obj ):   # valid and can preserve
                        ob_path = obj_info.filename( obj ).replace(self.content_dir,'')
                        new_path = os.path.join(self.ob_dir, ob_path)
                    else:
                        new_path = os.path.join(self.ob_dir, os.path.basename(obj_info.filename( obj )))
                    try:
                        os.makedirs( os.path.dirname(new_path) )
                    except:
                        try:
                            os.makedirs( os.path.dirname(new_path) + os.sep )
                        except:
                            myerr = sys.exc_value
#save object to new path
                    if os.path.lexists( os.path.dirname(new_path) ) == True:
                        lwsdk.command("SelectByName " + item_info.name( obj ))
                        lwsdk.command("SaveObject " + new_path)
                else:
                    pass # "Must be null"

# end object processing ------------------

# begin scene processing -----------------
        if self.preserve == 1 and self.content_dir in self.scene.filename and os.path.dirname(self.scene.filename) != self.content_dir:
            sc_sub = self.scene.filename.replace(self.content_dir,'')
            new_scene = os.path.join(self.sc_dir, sc_sub, self.scene.name)
        else:
            new_scene = os.path.join(self.sc_dir, self.scene.name)

        try:
            os.makedirs( os.path.dirname(new_scene) )
        except:
            try:
                os.makedirs( os.path.dirname(new_scene) + os.sep )
            except:
                myerr = sys.exc_value

        if os.path.lexists( os.path.dirname(new_scene) ) == True:
            tempdir = tempfile.mkdtemp()
            tempscene = os.path.join(tempdir, self.scene.name)
            lwsdk.command("SaveSceneCopy " + tempscene)

        infile = open(tempscene, "r")
        lines = infile.readlines()
        infile.close()

        outfile = open(new_scene, 'w')

        photo_on = False
        bdd_on = False
        mdd_on = False
        vert_on = False
        mddnode_on = False
        flock_on = False

        # scan scene for ancillary files
        for l in lines:
            l = l.replace('\n','')  # strip newline

            # 1. Get path
            # 2. Find old item
            # 3. Prepare new path
            # 4. Copy old item to new path
            # 5. Write new path to Scene file

            #process bdd files

            #if ".bdd" in l:  # l is the line out of the Scene file
            if "FX_Break" in l:     # l is the line out of the Scene file
                bdd_on = True   # Switch this on, since we've found a BDD line
                outfile.write(l + "\n")

            elif ".bdd" in l and bdd_on == True:
                bddunc = False  # Start out assuming it is NOT a UNC path
                if l.startswith("\\\\"):
                    bddunc = True       # If the line starts with at double-backslash, fair bet it's a UNC path
                ls = l.replace('\\','/')
                oldbddpath = os.path.join(self.content_dir, ls )
                if self.preserve == True:
                    if content_dir in oldbddpath:
                        preserve = True
                    else:
                        preserve = False
                if preserve == True and self.preserve == True:
                    newbddpath = os.path.join(self.target_dir, os.path.dirname(ls), os.path.basename(ls) )
                else:
                    newbddpath = os.path.join(self.dyn_dir, os.path.basename(ls) )
                self.psCopy(oldbddpath.replace('\\','/'), newbddpath.replace('\\','/') )
                if bddunc == True:
                    outfile.write( newbddpath + "\n")
                else:
                    outfile.write( l + "\n")

            elif "EndPlugin" in l and bdd_on == True:
                outfile.write(l + "\n")
                outfile.write("\n")
                bdd_on = False

            elif "FX_MotionDrive" in l:
                mdd_on = True
                outfile.write(l + "\n")
            elif ".mdd" in l and mdd_on == True:
                mdd_on = False
                l = l.replace('\\','/')
                oldmddpath = os.path.join(self.content_dir, l)
                if self.preserve == True:
                    newmddpath = os.path.join(self.target_dir, l)
                else:
                    newmddpath = os.path.join( self.dyn_dir, os.path.basename(l) )
                self.psCopy(oldmddpath, newmddpath)
                outfile.write( l + "\n" )

            elif "MD_Plug" in l:
                vert_on = True
                outfile.write( l + "\n" )

            elif ".mdd" in l and vert_on == True and mddnode_on == False:
                vertunc = False
                oldvertpath = os.path.join( self.content_dir, l.strip().replace('\"','') )
                if oldvertpath.startswith("\\\\"):
                    vertunc = True
                ls = l.strip().replace('\"','').split('\\/')
                newvertpath = os.path.join( self.vert_dir, os.path.basename(l.strip().replace('\"','') )  )
                if vertunc == True:
                    oldvertnorm = os.path.normpath(oldvertpath)
                    oldvertnorm = oldvertnorm.replace(r'\\\\',r'\\')
                    self.psCopy(oldvertnorm, newvertpath)
                else:
                    self.psCopy(oldvertpath, newvertpath)
                outline = '    \"' + self.strip_first_slash(newvertpath[len(self.target_dir):]) + '\"\n'
                outfile.write(outline)
                vert_on = False

            elif ".xml" in l and vert_on == True and mddnode_on == False:
                xmlunc = False
                oldvertpath = os.path.join( self.content_dir, l.strip().replace('\"','') )
                oldmc = os.path.splitext(oldvertpath)[0] + ".mc"
                if oldvertpath.startswith("\\\\"):
                    xmlunc = True
                ls = l.strip().replace('\"','').split('\\/')
                newvertpath = os.path.join( self.vert_dir, os.path.basename(l.strip().replace('\"','') )  )
                newmc = os.path.splitext(newvertpath)[0] + ".mc"
                if xmlunc == True:
                    oldvertnorm = os.path.normpath(oldvertpath)
                    oldvertnorm = oldvertnorm.replace(r'\\\\',r'\\')
                    oldmcnorm = os.path.normpath(oldmc)
                    oldmcnorm = oldmcnorm.replace(r'\\\\',r'\\')
                    self.psCopy(oldvertnorm, newvertpath)
                    self.psCopy(oldmcnorm, newmc)
                    self.copy_mc_sequence(oldmcnorm, newmc)
                else:
                    self.psCopy(oldvertpath, newvertpath)
                    self.psCopy(oldmc, newmc)
                    self.copy_mc_sequence(oldmc, newmc)
                outline = '    \"' + self.strip_first_slash(newvertpath[len(self.target_dir):]) + '\"\n'
                outfile.write(outline)
                vert_on = False

            elif "{ MDReader" in l:
                outfile.write( l + "\n" )

            elif "MDD_Node" in l:
                mddnode_on = True
                outfile.write( l + "\n")

            elif ".mdd" in l and mddnode_on == True and vert_on == False:
                mddnode_on = False
                l = l.replace('\\','/')
                oldvertpath = os.path.join( self.content_dir, l.strip().replace('\"','') )
                ls = l.strip().replace('\"','').split('\\/')
                newvertpath = os.path.join( self.vert_dir, os.path.basename(l.strip().replace('\"','') )  )
                self.psCopy(oldvertpath, newvertpath)
                outline = '\"' + self.strip_first_slash(newvertpath[len(self.target_dir):]) + '\"\n'
                outfile.write('        Filename ' + outline )

            # Process Particle FX files
            elif ".pfx" in l:
                pfxunc = False
                lsplit = l.split(None,5)
                ls = os.path.normpath(lsplit[5])
                if ls.startswith("\\\\"):    #UNC path
                    pfxunc = True
                if '\\' in ls or '/' in ls:  # this section is for the Mac, if it's having trouble
                    lsp = ls.split('\\')     # dealing with backslashes
                    ls = lsp[-1]
                oldpfxpath = os.path.join( self.content_dir,lsplit[5] )

                if self.content_dir in oldpfxpath:
                    preserve = True
                else:
                    preserve = False

                if preserve == 1 and self.preserve == 1:
                    newpfxpath = os.path.join(self.target_dir,lsplit[5])
                else:
                    newpfxpath = os.path.join(self.dyn_dir, os.path.basename(ls) )
                psCopySource = oldpfxpath.replace('\\','/')
                psCopyDest = newpfxpath.replace('\\','/')
                self.psCopy(psCopySource, psCopyDest)

                lsplit[5] = newpfxpath

                outline = ' '.join(lsplit)
                outfile.write(" " + outline + "\n")

            # Process IES Lights
            elif "Plugin LightHandler" in l and "PhotometricLight" in l:
                outfile.write("Plugin LightHandler 1 PhotometricLight\n")
                photo_on = True

            elif photo_on == True and "File \"" in l:
                oldiespath = l[8:-1]
                if oldiespath[:1] == ":":
                    oldiespath = os.sep + oldiespath[1:]
                newiespath = os.path.join(self.ies_dir, os.path.basename(oldiespath))
                if newiespath[:1] == ":":
                    newiespath = os.sep + newiespath[1:] 
                outfile.write('  File \"' + self.strip_first_slash(newiespath) + '\"\n')
                self.psCopy(oldiespath, newiespath)
                photo_on = False

            # Process Radiosity Cache files
            elif "RadiosityCacheFilePath" in l and self.radsave == True:
                l = l.split(None,1)[1]
                oldradpath_drive = os.path.splitdrive(l)[0]
                oldradpath_path = os.path.dirname(os.path.splitdrive(l)[1])
                oldradpath_file = os.path.basename(l)
                if oldradpath_drive != None:
                    oldradpath = os.path.join(oldradpath_drive, oldradpath_path, oldradpath_file).replace('\\','/')
                    if oldradpath[:1] == ":":
                        oldradpath = os.sep + oldradpath[1:]
                else:
                    oldradpath = os.path.join(self.content_dir, l)
                newradpath = os.path.join(self.rad_dir, oldradpath_file).replace('\\','/')
                if newradpath[:1] == ":":
                    newradpath = os.sep + newradpath[1:]
                self.psCopy(oldradpath, newradpath )
                outfile.write('RadiosityCacheFilePath ' + self.strip_first_slash(newradpath) + "\n")

            #Copy flocking cache data
            elif "FlockMaster" in l:
                outfile.write(l + "\n")
                flock_on = True
                flock_count = 1

            elif flock_on == True and flock_count == 1:
                outfile.write(l + "\n")
                flock_count = flock_count + 1

            elif flock_on == True and flock_count == 2:
                flock_count = flock_count + 1
                flockunc = False
                lsplit = l.replace("\"",'')
                ls = os.path.normpath(lsplit)
                if ls.startswith("\\\\"):
                    flockunc = True
                if '\\' in ls or '/' in ls:
                    lsp = ls.split('\\')
                    ls = lsp[-1]
                oldflockpath = os.path.join( self.content_dir, lsplit)
                if self.preserve == True:
                    if self.content_dir in oldflockpath:
                        preserve = True
                    else:
                        preserve = False
                if self.preserve == True and preserve == True:
                    newflockpath = os.path.join(self.dyn_dir, ls)
                else:
                    newflockpath = os.path.join(self.dyn_dir, os.path.basename(ls))
                psCopySource = os.path.normpath(oldflockpath)
                psCopyDest = os.path.normpath(newflockpath)
                self.psCopy(psCopySource, psCopyDest)
                newflockwrite = '\"' + newflockpath.replace('\\','\\\\') + '\"'

            elif flock_on == True and "EndPlugin" in l:
                flock_on = False
                outfile.write(l + "\n")

            else:   #if nothing matched, just pass the line right through to the new scene
                outfile.write( l + "\n")

        # copy over Bullet dynamics cache file
        if os.path.lexists(os.path.join( self.content_dir, "Dynamics") ):
            dynasource = os.path.join( self.content_dir, "Dynamics", self.scene.name[:-4]) + ".dynacache"
            dynadest = os.path.join( self.dyn_dir, os.path.basename( dynasource ) )
            self.psCopy(dynasource, dynadest)

        outfile.close()

        self.psCopy(tempscene, new_scene)
        if self.reload == True:
            lwsdk.command("LoadScene " + self.scene.filename)
        else:
            lwsdk.command("LoadScene " + new_scene)

        os.remove(tempscene)
        os.rmdir(tempdir)

        return lwsdk.AFUNC_OK
    def process(self, ga):
        item_info = lwsdk.LWItemInfo()
        object_info = lwsdk.LWObjectInfo()
        instancer_funcs = lwsdk.LWItemInstancerFuncs()
        instance_info = lwsdk.LWItemInstanceInfo()
        interface_info = lwsdk.LWInterfaceInfo()

        current_time = interface_info.curTime
        autokey_is_on = ((interface_info.generalFlags & lwsdk.LWGENF_AUTOKEY) != 0)

        selected_item = interface_info.selected_items()[0]
        selected_item_id = lwsdk.itemid_to_str(selected_item)

        # find the Instancer that owns the selected object
        found_instancer = None
        obj = item_info.first(lwsdk.LWI_OBJECT, None)
        while obj and (not found_instancer):
            instancer = object_info.instancer(obj)
            if instancer:
                instance = instancer_funcs.first(instancer)
                while instance and (not found_instancer):
                    if instance_info.item(instance) == selected_item:
                        # found it!
                        found_instancer = instancer
                        break
                    instance = instancer_funcs.next(instancer, instance)
            obj = item_info.next(obj)

        if not found_instancer:
            print >>sys.stderr, 'Object "%s" is NOT instanced!' % item_info.name(selected_item)
            return lwsdk.AFUNC_OK

        instances = []
        instance = instancer_funcs.first(found_instancer)
        while instance:
            if instance_info.item(instance) == selected_item:
                instances.append(instance)
            instance = instancer_funcs.next(found_instancer, instance)

        # values used for progress
        current_index = 1.0
        target_index = len(instances) * 1.0

        for instance in instances:
            pos = instance_info.pos(instance, 0)
            # Note: InstanceInfo.rotation() returns radians!
            rot = instance_info.rotation(instance, 0)
            scl = instance_info.scale(instance, 0)

            lwsdk.command("SelectItem %s" % selected_item_id)
            lwsdk.command("Clone 1")

            lwsdk.command("Position %s" % str(pos))
            # Note: Rotation expects degrees!
            lwsdk.command("Rotation %s" % str(Vector.to_degrees(rot)))
            lwsdk.command("Scale %s" % str(scl))
            if not autokey_is_on:
                lwsdk.command("CreateKey %f" % current_time)

            lwsdk.command("StatusMsg {%f}Baking instances..." % (current_index / target_index))
            current_index += 1.0

        lwsdk.command("SelectItem %s" % selected_item_id)

        lwsdk.command("StatusMsg Baking complete.")

        return lwsdk.AFUNC_OK