Beispiel #1
0
def main():
    print "Checking model"

    #Check model units
    if rs.UnitSystem() != 8:
        rs.MessageBox("Your model is not in inches.", 16)
        print "Unit warning"

    #Check bad objects
    rs.Command('-_SelBadObjects ')
    objs = rs.SelectedObjects()
    if len(objs) > 0:
        message = "You have {} bad objects. Use SelBadObjects to delete them.".format(
            len(objs))
        rs.MessageBox(message, 16)
    rs.UnselectAllObjects()

    #SelDup
    rs.Command('-_SelDup ')
    objs = rs.SelectedObjects()
    if len(objs) > 0:
        message = "You have {} duplicate objects. Use SelDup to delete them.".format(
            len(objs))
        rs.MessageBox(message, 16)
    rs.UnselectAllObjects()

    #SelSmall
    rs.Command('-_SelSmall .01 ')
    objs = rs.SelectedObjects()
    if len(objs) > 0:
        message = "You have {} tiny objects. Use SelSmall to delete them.".format(
            len(objs))
        rs.MessageBox(message, 16)
    rs.UnselectAllObjects()
Beispiel #2
0
def set_robot_base_plane():
    robot_ip = ROBOT_IP
    #robot_ip = "192.168.10.43"

    rs.MessageBox("move robot to base plane origin, press OK when there", 0)
    data = c.listen_to_robot(robot_ip)
    pose = data['pose']
    pt_1 = rg.Point3d(pose[0] * 1000, pose[1] * 1000, pose[2] * 1000)
    print pt_1
    rs.MessageBox(
        "move robot to base plane positive x direction, press OK when there",
        0)
    data = c.listen_to_robot(robot_ip)
    pose = data['pose']
    pt_2 = rg.Point3d(pose[0] * 1000, pose[1] * 1000, pose[2] * 1000)
    print pt_2
    rs.MessageBox(
        "move robot to base plane positive y direction, press OK when there",
        0)
    data = c.listen_to_robot(robot_ip)
    pose = data['pose']
    pt_3 = rg.Point3d(pose[0] * 1000, pose[1] * 1000, pose[2] * 1000)
    print pt_3

    robot_base = rg.Plane(pt_1, pt_2 - pt_1, pt_3 - pt_1)
    text_file = open("robot_base.txt", "w")
    text_file.write(
        str(robot_base.Origin) + "," + str(robot_base.XAxis) + "," +
        str(robot_base.YAxis))
    text_file.close()
Beispiel #3
0
def makeEngraves(tool_id, operation, z_pos, obj):

    #restore view cplane
    p1 = rs.WorldXYPlane()
    rs.ViewCPlane(None, p1)
            
    subtracts = []        
        
    # return [sweepVolume(obj, tool_id, z_pos)]
    
    subcurves = rs.ExplodeCurves(obj, False)
    if subcurves:
        rs.DeleteObject(obj)
        for crv in subcurves:
            volumes = sweepVolume(crv, tool_id, z_pos)
            if not volumes or len(volumes) < 1:
                rs.MessageBox('Error with %s, %s, %s' % (tool_id, operation, z_pos))
            for vol in volumes:
                subtracts.append( vol )
    else:
        volumes = sweepVolume(obj, tool_id, z_pos)
        if not volumes or len(volumes) < 1:
            rs.MessageBox('Error with %s, %s, %s' % (tool_id, operation, z_pos))
        for vol in volumes:
            subtracts.append( vol )                
    
    return subtracts
Beispiel #4
0
 def __is_emotion_valid(self, e):
     if e in self.system_emotion_dict:
         return True
     else:
         if e:
             user_response = rs.MessageBox(
                 "Word '" + e + "' not found. Would you like to add '" + e +
                 "' to the dictionary?", 4 | 0)
             if user_response == 6:  #user says 'yes'
                 rs.MessageBox(
                     "'" + e +
                     "' added to dictionary. Neutral object created to reflect '"
                     + e + "'; add its emotive components using sliders.")
                 neutral_emotion_breakdown = {
                     "sadness": 0,
                     "trust": 0,
                     "anger": 0,
                     "surprise": 0,
                     "joy": 0,
                     "fear": 0,
                     "anticipation": 0,
                     "disgust": 0
                 }
                 emotive_script_ui_helper.modify_user_dictionary(
                     None, e, neutral_emotion_breakdown)
                 emotive_script_ui_helper.add_to_system_dictionary(
                     e, neutral_emotion_breakdown)
                 return True
         return False
Beispiel #5
0
def turn(board, mask, grid):
    test = True
    textdot_id = rs.GetObject("", rs.filter.textdot)
    for x in range(len(grid)):
        for y in range(len(grid)):
            if grid[x][y] == textdot_id:
                i, j = x, y
    rs.EnableRedraw(False)
    if board[i][j] == 'Mine':
        destroy_grid((i, j), grid)
        rs.TextDotText(textdot_id, board[i][j])
        rs.MessageBox("Game over! :(", title='Rhino Minesweeper')
        test = False
    elif board[i][j] == 0:
        board_copy = [row[:] for row in board]
        cells_test = cells_0(i, j, board_copy, [])
        for x, y in cells_test:
            if not mask[x][y]:
                if board[x][y] == 0:
                    rs.DeleteObject(grid[x][y])
                else:
                    rs.TextDotText(grid[x][y], board[x][y])
            mask[x][y] = True
    else:
        rs.TextDotText(textdot_id, board[i][j])
        mask[i][j] = True
    rs.EnableRedraw(True)
    if test and check_mask(mask):
        rs.MessageBox("You win!", title='Rhino Minesweeper')
        return False
    else:
        return test
Beispiel #6
0
def Run(xNum, yNum):
    if xNum is None:
        rs.MessageBox("No number provided for x")
        return
    if yNum is None:
        rs.MessageBox("No number provided for y")
        return

    rs.EnableRedraw(False)
    boxes = []
    for i in range(xNum):
        for n in range(yNum):
            points = []
            for s in range(2):
                for t in range(4):
                    x = math.cos(math.radians(45 + 90 * t)) * math.sqrt(2)
                    y = math.sin(math.radians(45 + 90 * t)) * math.sqrt(2)
                    z = -1 + 2 * s
                    point = geo.Point3d(x, y, z)
                    points.append(point)
            box = rs.AddBox(points)

            box = rs.RotateObject(box, geo.Point3d(0, 0, 0),
                                  90 / (xNum - 1) * i, geo.Vector3d.ZAxis)
            box = rs.RotateObject(box, geo.Point3d(0, 0, 0),
                                  90 / (yNum - 1) * n, geo.Vector3d.XAxis)

            box = rs.MoveObject(box, geo.Vector3d(4 * i, 4 * n, 0))
            boxes.append(box)
    rs.EnableRedraw(True)

    return boxes


#Run()
	def ConfirmDup(dir, nam, height, line, switch, extension):
		print("■start confirmdup■")
		
		# 平面図の確認
		def Planduplicate(dire, name, num_plan, exte):
			result = []
			for i in num_plan:
				if i > 0:
					i = "+" + str(i)
				result.append(os.path.exists(str(dire) + str(name) + "_plan_" + str(i) + "." + str(exte)))
			return result

		# 断面図の確認
		def SecDuplicate(dire, name, num_sec, exte):
			result = []
			for i in range(len(num_sec)):
				result.append(os.path.exists(str(dire) + str(name) + "_section_" + str(i) + "." + str(exte)))
			return result

		# 配置図の確認
		def RoofDuplicate(dire, name, exte):
			result = []
			result.append(os.path.exists(str(dire) + str(name) + "_roof" + "." + str(exte)))
			return result

		dup_p = []# ダブリがある場合はTrue、ない場合はFalseが格納されるリスト
		dup_s = []
		dup_r = []
		if switch == 0 or switch == 2:# モードが平面図のみor両方のとき
			dup_p.extend(Planduplicate(dir, nam, height, extension))
		if switch == 1 or switch == 2:# モードが断面図のみor両方のとき
			dup_s.extend(SecDuplicate(dir, nam, line, extension))
		dup_r.extend(RoofDuplicate(dir, nam, extension))

		if True in dup_p or True in dup_s or True in dup_r:# 一個でも重複する場合
			print("duplicate files" + " p = " + str(dup_p.count(True)) + " s = " + str(dup_s.count(True)) + " r = " + str(dup_r.count(True)))
			if switch == 0 or switch == 1 or switch == 2:
				ans = rs.MessageBox("同じ名前のファイルが存在します  平面図:" + str(dup_p.count(True)) + "枚 " + "断面図:" + str(dup_s.count(True)) + "枚  上書きしますか?", 4, "ファイルの重複")
				if ans == int(6):# Massageboxのはいは6で返却される
					duplicate = True
					print("overwriting")
				else:
					rs.MessageBox("作図をキャンセルしました")
					duplicate = False
					print("canceled writing")
			elif switch == 3:
				ans = rs.MessageBox("同じ名前のファイルが存在します  上書きしますか?", 4, "ファイルの重複")
				if ans == int(6):# Massageboxのはいは6で返却される
					duplicate = True
					print("overwriting")
				else:
					rs.MessageBox("作図をキャンセルしました")
					duplicate = False
					print("canceled writing")
		else:
			duplicate = True
			print("no duplicate")
		print("■end confirmdup■")
		return duplicate# 重複が存在しないor上書きする場合はTrueで返却
Beispiel #8
0
def timeTilHappyHour():
    now = datetime.datetime.now()
    hour = str(datetime.time(now.hour, now.minute, now.second))

    list = hour.split(":")
    if (17 - int(list[0]) < 0):
        rs.MessageBox("ITS HAPPY HOUR!!!!! \nHead to the bar for a drink!")
    else:
        rs.MessageBox(
            "Only {} hours, {} minutes, and {} seconds, until happy hour!".
            format(17 - int(list[0]), 59 - int(list[1]), 60 - int(list[2])))
def read_data(line):
    dataset = data_processing()
    if line == 0 or line + 1 > len(dataset):
        rs.MessageBox('DATA OVERFLOW!')
        return OVERFLOW
    if dataset[line][1] == '-1':
        rs.MessageBox('INVALID DATA:NO INPUT!')
        return ERROR

    boxdata = [[], [], [], line]
    for i in range(1, len(dataset[line])):
        if i <= 6: boxdata[0].append(float(dataset[line][i]))
        elif i <= 12: boxdata[1].append(float(dataset[line][i]))
        elif dataset[line][i]: boxdata[2].append(float(dataset[line][i]))
    #print boxdata
    return boxdata
Beispiel #10
0
def main():
    msg = "Select polysurface objects to export data"
    objs = rs.GetObjects(msg, 16, preselect=True)
    if not objs: return
    extrusions = []
    rs.UnselectAllObjects()
    for obj in objs:
        if rs.ObjectType(obj) == 1073741824:
            extrusions.append(obj)
    if len(extrusions) > 0:
        rs.SelectObjects(extrusions)
        resp = rs.MessageBox(
            "Selected objects will be converted to polysurfaces.\n Press OK to continue, Cancel to abort",
            1)
        if resp == 1:
            rs.Command("ConvertExtrusion _Enter")
            rs.UnselectAllObjects()
        else:
            return
    keys = [i.name for i in ATTRS if i.isEditable]
    makeDetail(keys, objs)
    details = []
    spec = dict([])
    ids = dict([])
    for obj in objs:
        detail = Detail(obj)
        details.append(detail)
    spec = Specification([], details)
    dialog = SpecDialog()
    dialog.setData(spec)
    rs.UnselectAllObjects()
    Rhino.UI.EtoExtensions.ShowSemiModal(dialog, Rhino.RhinoDoc.ActiveDoc,
                                         Rhino.UI.RhinoEtoApp.MainWindow)
Beispiel #11
0
    def new_settings_button(self,sender,e,edit=False):
        
        while True:
            name = rs.StringBox (message=TXT["name"], default_value=None, title=TXT["nueva"])
            if name != "" and name not in self.machining_settings:
                break
        if name:
            machining_settings = {name:{}}
            for compensation in [key for key in INPUT_VALUES]:
                machining_settings[name][compensation] =  {}
                if self.user_data["selected_preset"]:
                    list_settings = rs.PropertyListBox([i for i in INPUT_VALUES[compensation]],[str(self.machining_settings[self.user_data["selected_preset"]][compensation][i]) for i in VARIABLE_NAMES[compensation]],compensation, "Configuracion de corte")
                else:
                    list_settings = rs.PropertyListBox([i for i in INPUT_VALUES[compensation]],[0 for i in INPUT_VALUES[compensation]],compensation, "Configuracion de corte")
                if list_settings:
                    for i in range(0,len(list_settings)):
                        machining_settings[name][compensation][VARIABLE_NAMES[compensation][i]] = self.validate_data(list_settings[i], VARIABLE_NAMES[compensation][i])
                else:
                    return
            persistant = rs.MessageBox(TXT["save_pers"], 4 | 256 | 64,TXT["database"])
            
            if persistant == 6:
                machining_settings[name]["persistant"] = False
            else:
                machining_settings[name]["persistant"] = True

            self.user_data["selected_preset"] = name
            w = self.form.panel.Controls.Find("preset", True)[0]
            w.Text = name
            self.machining_settings.update(machining_settings)
Beispiel #12
0
    def undo_button(self, sender, e):
        self.history = self.history[:self.design_history]

        if len(self.history) >= 1:
            self.design_history = self.design_history - 1
            self.drawn_emotion = self.history[self.design_history][0]
            self.current_emotion_label.Text = "Current emotion: " + self.drawn_emotion
            self.drawn = emotive_script_ui_helper.draw_emotion_object(
                self.object_id, self.drawn_emotion)

            p = self.form.panel
            for e in config.primary_emotions[1:]:
                p.Controls.Find(
                    "track_bar_" + e,
                    True)[0].Value = self.history[self.design_history][1][e]

            self.outpath = str(config.outpath_design_history +
                               str(self.design_history) + ".jpg")
            p.Controls.Find("history_image", True)[0].Load(self.outpath)
            p.Controls.Find("design_history_outpath", True)[0].Text = str(
                self.history[self.design_history - 1][0])
            p.Controls.Find("design_history_breakdown", True)[0].Text = str(
                self.history[self.design_history - 1][1])
            self.draw_emotion_helper(True)
        else:
            rs.MessageBox("You don't have a previous design to revert to")
Beispiel #13
0
    def write_code_button(self,sender,e):
        
        if self.spkmodel_objects:
            if self.user_data["save_path"]:
                gcode = IN_TEXT + ["(%s)"%self.user_data["selected_preset"],"(<%s>)"%self.time,"G0Z%sF%s" % (self.general_settings["sec_plane"],self.general_settings["feed_rapid"])]

                for rhinoobject in self.sorted_objects:
                    gcode += rhinoobject.gcode    
                gcode += OUT_TEXT

                time = vectors_from_gcode(gcode,preview=False,only_time=True)
                self.add_line("%s %s mins" % (TXT["time_txt"],time))
                
                f=open(self.user_data["save_path"],"w")
                f.write("\n".join(gcode))
                f.close()
            else:
                self.file_name_button(False,False)
                self.write_code_button(False, False)
            self.add_line(TXT["file_saved"])
            return True
        
        else:
            rs.MessageBox(TXT["error_generate"],0)
            return False
Beispiel #14
0
def importTools(filename):
    tool_table = {}
    invalid_lines = ''
    with open(filename) as fp:
        # read header
        line = fp.readline()
        # read first line
        line = fp.readline()
        cnt = 1
        while line:
            # print line
            m = re.search('(\d\d.\d\d)\t' + '(.+)\t' + '(.+)', line)
            if m and len(m.groups()) >= 3:
                tool_table[m.group(1)] = {"TNM": m.group(2), "DIA": m.group(3)}
            else:
                invalid_lines += line + '\n'

            line = fp.readline()
            cnt += 1

        if len(invalid_lines) > 0:
            rs.MessageBox(
                'lines could not be read, please check the tool table file:\n'
                + invalid_lines + '')
            return False

        return tool_table
Beispiel #15
0
    def message_box(key=None, buttons=0):

        settings = RVsettings()
        title = settings.name + " " + settings.version

        if not key in RVinfo.messages: return None
        return rs.MessageBox(RVinfo.messages[key], buttons, title)
Beispiel #16
0
def checkCurvePosition(objs):
    layers = []
    for obj in objs:
        if rs.IsCurve(obj):
            if not isCurveOnCPlane(obj):
                # print "Curve {} not on Cplane".format(obj)
                rs.SelectObject(obj)
                appendLayer(layers, obj)

        elif rs.IsPoint(obj):
            if not isPointOnCplane(obj):
                # print "Curve {} not on Cplane".format(obj)
                rs.SelectObject(obj)
                appendLayer(layers, obj)
        else:
            print "object {} is not a curve or point".format(obj)

    # when an object is found on > 0 layers, prompt for proceed
    if len(layers) > 0:
        msg = "there were curves found on layers:\n"
        for layer in layers:
            msg = msg + "- " + layer + " \n"

        if rs.MessageBox(msg, 1) != 1:
            return False

    # else
    return True
Beispiel #17
0
    def index_code_button(self,sender,e):
        
        if self.spkmodel_objects:
            if self.user_data["save_path"]:
                
                f=open(self.user_data["save_path"],"r")
                previus_gcode = f.read()
                total_time =  float(previus_gcode[previus_gcode.index("<")+1:previus_gcode.index(">")]) + self.time
                
                previus_gcode = previus_gcode[:previus_gcode.index("<")] + "<%s>" %str(total_time) + previus_gcode[previus_gcode.index(">")+1:]
                
                if "(ending)" in previus_gcode:
                    previus_gcode = previus_gcode[:previus_gcode.index("(ending")]
                f.close()
                
                gcode = []

 
                for rhinoobject in self.sorted_objects:
                    gcode += rhinoobject.gcode
                gcode += OUT_TEXT
                
                f=open(self.user_data["save_path"],"w")
                f.write(previus_gcode + "(%s)\n%s\n" % (self.user_data["selected_preset"],"(None)" if not self.user_data["index_pause"] else "!") + "\n".join(gcode))
                f.close()
            else:
                self.file_name_button(False,False)
            
            
            self.form.panel.Controls.Find("gcode_text", True)[0].Text = "Tiempo actualizado: %s mins" % str(int(total_time))
            self.add_line("Archivo indexado")
        else:
            rs.MessageBox(TXT["error_generate"],0)
Beispiel #18
0
def checkCurvePosition(objs):
    layers = []
    selection = []
    for obj in objs:
        if rs.IsCurve(obj):
            if not isCurveOnCPlane(obj):
                # print "Curve {} not on Cplane".format(obj)
                selection.append(obj)
                appendLayer(layers, obj)

        elif rs.IsPoint(obj):
            if not isPointOnCplane(obj):
                # print "Curve {} not on Cplane".format(obj)
                rs.SelectObject(obj)
                appendLayer(layers, obj)
        else:
            print "object {} is not a curve or point. {}".format(
                obj, rs.ObjectType(obj))

    if len(selection) > 0:
        rs.SelectObjects(selection)

    # when an object is found on > 0 layers, prompt for proceed
    if len(layers) > 0:
        msg = "there were non-planar or elevated curves found on layers:\n"
        for layer in layers:
            msg = msg + "- " + layer + " \n"

        msg = msg + '\n Do you want to proceed?'

        if rs.MessageBox(msg, 1) != 1:
            return False

    # else
    return True
Beispiel #19
0
 def delete_settings_button(self,sender,e):
     if self.user_data["selected_preset"]:
         if rs.MessageBox("Delete %s" % self.user_data["selected_preset"], 4 | 32) == 6:
             w =self.form.panel.Controls.Find("preset", True)[0]
             w.Text = "%s %s" % (self.user_data["selected_preset"],TXT["del"])
             del self.machining_settings[self.user_data["selected_preset"]] 
             self.user_data["selected_preset"] = None
Beispiel #20
0
def ShowRL():
    try:

        def scale():
            system = rs.UnitSystem()
            if system == 2 or system == 3 or system == 4:
                scaleFactorDict = {2: 0.001, 3: 0.01, 4: 1}
                scaleFactor = scaleFactorDict[system]
                return scaleFactor

            if system != 2 or system != 3 or system != 4:
                return None

        if scale() == None:
            rs.MessageBox(
                "This tool is can only be used in mm, cm or m model units")
            return None

        point = rs.GetPoint('Select point')

        if point:
            pointZ = point.Z
        pointZ = pointZ * scale()
        rs.AddTextDot('+RL ' + str(round(pointZ, 3)), point)

        # Copy RL to Clipboard
        RL = str(round(pointZ, 3))
        rs.ClipboardText(RL)

    except:
        print("Failed to execute")
        rs.EnableRedraw(True)
        return
Beispiel #21
0
def Height():
    try:

        pt01 = rs.GetPoint('Select first point to measure from')
        pt02 = rs.GetPoint('Select second point to measure to')

        if pt02:

            pt01Z = pt01.Z
            pt02Z = pt02.Z

            height = abs(pt01Z - pt02Z)
            height = round(height, 3)

            rs.ClipboardText(height)

            rs.MessageBox(
                height,
                buttons=0,
                title="Height difference - Value copied to clipboard")

    except:
        print("Failed to execute")
        rs.EnableRedraw(True)
        return
Beispiel #22
0
    def getLayerName(self):

        if ("Clamex horizontaal"
                in self.cbb_operation.Text) or ('6.0.000.1'
                                                in self.cbb_tool.Text):
            self.cbb_operation.Text = "Clamex horizontaal"
            self.cbb_tool.Text = '6.0.000.1 -'

        if ("Clamex verticaal"
                in self.cbb_operation.Text) or ('6.0.000.1'
                                                in self.cbb_tool.Text):
            self.cbb_operation.Text = "Clamex verticaal"
            self.cbb_tool.Text = '6.1.000.1 -'

        if ("Saw X"
                in self.cbb_operation.Text) or ("Saw Y"
                                                in self.cbb_operation.Text):
            self.cbb_operation.Text = "Clamex verticaal"
            self.cbb_tool.Text = '7.0.000.1 -'

        if ("Drill" in self.cbb_operation.Text
                and self.cbb_tool.Text[:2] != '5.'):
            rs.MessageBox('Please select a Drill')
            return ""

        if self.cb_depth.Checked:
            layername = '{} {} d{}'.format(self.cbb_tool.Text,
                                           self.cbb_operation.Text,
                                           self.sb_height.Value)
        else:
            layername = '{} {} +{}'.format(self.cbb_tool.Text,
                                           self.cbb_operation.Text,
                                           self.sb_height.Value)

        return layername
def CreateShortcut():
    """
    Create a shortcut to the current document
    NOTE!! This function only runs on Windows
    """
    if (not rs.IsRunningOnWindows()):
        rs.MessageBox("CreateShortcut.py only runs on Windows", 48,
                      "Script Error")
        return

    # Get the document name and path
    name = rs.DocumentName()
    path = rs.DocumentPath()

    # Get the Windows Scripting Host's Shell object
    objShell = System.Activator.CreateInstance(
        System.Type.GetTypeFromProgID("WScript.Shell"))
    # Get the desktop folder
    desktop = objShell.SpecialFolders("Desktop")
    # Make a new shortcut
    ShellLink = objShell.CreateShortcut(desktop + "\\" + name + ".lnk")
    ShellLink.TargetPath = Path.Combine(path, name)
    ShellLink.WindowStyle = 1
    ShellLink.IconLocation = rs.ExeFolder() + "Rhino4.exe, 0"
    ShellLink.Description = "Shortcut to " + name
    ShellLink.WorkingDirectory = path
    ShellLink.Save()
Beispiel #24
0
def main():

    try:
        check_output("python E:\python\gsheets\quickstart.py", shell=True)
        print 'tooltable updated'
    except:
        print 'NOT updated'

    tools = []

    with open('output.txt') as fp:
        # read header
        line = fp.readline()
        # read first line
        line = fp.readline()
        cnt = 1
        while line:
            list = line.split(',')
            # print cnt, list[1]

            tools.append(list[0] + " - " + list[1])

            line = fp.readline()
            cnt += 1

    tools = tuple(tools)

    form = AnnotateForm(tools)
    if (form.ShowDialog() == DialogResult.OK):
        #  this block of script is run if the user pressed the apply button
        layername = form.getLayerName()

        if layername != '':
            rs.AddLayer(name=layername, parent="CNC")
            rs.MessageBox(layername)
Beispiel #25
0
 def _make_labeled_shape_elements_dict(cls, initial_shape_frame_dict,
                                       rule_frame_pair_dict):
     """Receives:
         initial_shape_frame_dict
                         {str: guid}. A non-empty dictionary of initial 
                         shape names and frame instance guids
         rule_frame_pair_dict
                         {str: (guid, guid)}. A non-empty dictionary of 
                         rule names and frame instance guid pairs
     Returns:
         labeled_shape_elements_dict
                         {str: [guid, ...]}. A possibly empty dictionary of 
                         labeled shape names and lists of their element 
                         guids. The names are of labeled shapes with lists 
                         containing first the guid of the frame instance 
                         and then at least one element guid, i.e., 
                         non-empty labeled shapes. The exception is that a 
                         right labeled shape may be empty, in which case 
                         its list contains only the guid of the frame 
                         instance
     """
     labeled_shape_elements_dict = {}
     ill_formed_components = []
     for initial_shape in initial_shape_frame_dict:
         (frame_instance) = (initial_shape_frame_dict[initial_shape])
         elements = cls._get_elements(frame_instance)
         if elements == []:
             ill_formed_components.append(initial_shape)
         else:
             elements.insert(0, frame_instance)
             frame_and_elements = elements
             labeled_shape_elements_dict[initial_shape] = (
                 frame_and_elements)
     for rule in rule_frame_pair_dict:
         (left_frame, right_frame) = (rule_frame_pair_dict[rule])
         left_elements = cls._get_elements(left_frame)
         if left_elements == []:
             ill_formed_components.append(rule)
         else:
             left_shape = '%s_L' % rule
             right_shape = '%s_R' % rule
             right_elements = cls._get_elements(right_frame)
             left_elements.insert(0, left_frame)
             right_elements.insert(0, right_frame)
             left_frame_and_elements = left_elements
             right_frame_and_elements = right_elements
             labeled_shape_elements_dict[left_shape] = (
                 left_frame_and_elements)
             labeled_shape_elements_dict[right_shape] = (
                 right_frame_and_elements)
     if ill_formed_components:
         error_message = "%s %s" % (
             "The following initial shapes and rules were omitted",
             "because they contained inappropriate empty shapes")
         ill_formed_components_string = ',  '.join(ill_formed_components)
         total_message = "%s:\n\n%s" % (error_message,
                                        ill_formed_components_string)
         rs.MessageBox(total_message)
     return labeled_shape_elements_dict
	def Confirmfolder(dir):
		print("■start confirmfolder■")
		if os.path.exists(str(dir)):# 指定したフォルダが存在するか確認
			folder = True
			print("confirmedfolder")
		else:
			newfolder = rs.MessageBox("指定したフォルダが存在しません(" + str(dir) + ") フォルダを新規作成しますか?", 4, "フォルダの確認")
			if newfolder == int(6):# Massageboxのはいは6で返却される
				os.mkdir(str(dir))# 指定したディレクトリにフォルダを新規作成
				folder = True
				print("makingnewfolder")
			else:
				rs.MessageBox("作図をキャンセルしました")
				folder = False
				print("canceled writing")
		print("■end confirmfolder■")
		return folder# フォルダを作成orすでに存在したらTrueで返却
Beispiel #27
0
def ex3DS(objs):
    rs.MessageBox("Remember to check backfaces!")
    if objs is None:
        return
    rs.SelectObjects(objs)
    savePath = rs.SaveFileName("Save", "Autocad (*.dwg)|*.dwg||")
    rs.Command('! _-Export ' + str(savePath) +
               ' _Scheme _to3DSMax _Enter _Enter')
    print "Exported to {}".format(str(savePath))
    def start(self):
        """Starts the game"""
        self.create_board()
        self.get_player_symbol()

        # Who will start the game?
        if random.randint(0, 1):
            self.whose_move = self.ai_symbol

        while True:
            self.enter_move()
            if self.is_victory():
                message = "{} wins!".format(self.next_player(self.whose_move))
                rs.MessageBox(message, buttons=0, title="Tic Tac Toe")
                return
            if self.is_tie():
                rs.MessageBox("Tie!", buttons=0, title="Tic Tac Toe")
                return
Beispiel #29
0
def setCurveDir(objs):
    rs.UnselectAllObjects()
    count = 0
    count2 = 0

    for obj in objs:
        if rs.IsCurve(obj) and rs.IsCurveClosed(obj):

            # 1 = CW, -1 = CCW, 0 = N/A
            # -1 if the curve's orientation is counter-clockwise
            # 0 if unable to compute the curve's orientation
            if rs.ClosedCurveOrientation(obj) == 0:

                if DEBUG_FLIPCUVRVE:
                    rs.SelectObject(obj)
                    return False

                count2 += 1
            if rs.ClosedCurveOrientation(obj) == 1:
                rs.ReverseCurve(obj)
                count += 1

                if DEBUG_FLIPCUVRVE:
                    rs.SelectObject(obj)

                # normal = rs.CurveNormal(obj)
                # if normal and normal[2] < 0:
                # count += 1
                # rs.ReverseCurve(obj)
                # rs.SelectObject(obj)

    rs.EnableRedraw(True)
    rs.EnableRedraw(False)

    print "reversed curves  " + str(count) + " curves"

    if DEBUG_FLIPCUVRVE:
        rs.MessageBox("reversed curves  " + str(count) + " curves")

    if count2 > 0:
        rs.MessageBox("Curve direction of " + str(count) +
                      " curves could not be determined")

    return True
def exportNameOcc(_objs_ids):
    # extracting object names
    namesColumn = []
    if _objs_ids:
        for obj in _objs_ids:
            name = rs.ObjectName(obj)
            if name:
                namesColumn.append(name)
        if len(namesColumn) > 0:
            namesColumnU = set(namesColumn)
            namesColumnU = list(namesColumnU)

            # number of occurrences
            countColumn = []
            for nU in namesColumnU:
                number = namesColumn.count(nU)
                countColumn.append(number)

            mergedL = []
            for i in range(len(namesColumnU)):
                mergedL.append((countColumn[i], namesColumnU[i]))
            mergedL.sort(reverse=True)

            # exporting
            export = rs.GetInteger(
                "Export results to .csv file or just show them on the screen?   CSV(1),   Screen(0)",
                number=0,
                minimum=0,
                maximum=1)
            if export == 0:
                message = "Object name - No. of occurrences\n \n"
                for i in range(len(namesColumnU)):
                    print namesColumnU[i]
                    message += " %s - %i\n" % (mergedL[i][1], mergedL[i][0])
                rs.MessageBox(message, 0, "Results")
            else:
                filename = rs.SaveFileName("Save csv file", "*.csv||", None,
                                           "ObjectNamesOccurrences", "csv")
                file = open(filename, 'w')
                headerline = "Names, Occurrences\n"
                file.write(headerline)
                for i in range(len(namesColumnU)):
                    name = mergedL[i][1]
                    occ = mergedL[i][0]
                    line = "%s,%i \n" % (name, occ)
                    file.write(line)
                file.close()
                print "Done"

        else:
            print "You do not have named objects. Function terminated"
            return

    else:
        print "Your 3dm file is empty or you did not select objects. Function terminated"
        return