def __init__(self): """Initialize the game, and create game resources""" pygame.init() self.music = Music() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Save the City") self.statistics_image = pygame.image.load('resources/stats.png') # Reading the score from disk # d = shelve.open('resources/high_score') # score = d['saved_score'] # Create an instance to store game statistics- # -and create a scoreboard. self.stats = GameStats(self, 0) self.sb = Scoreboard(self) self.materials = Materials(self, self.settings.difficulty_level) self.worker = Worker(self) # Cooldown for collecting resources self.last = pygame.time.get_ticks() self.cooldown = 0 # List for obtained values self.obtained_list = [False, False, False, False, False] # Make the play button self.play_button = Button(self, "Play") self.show = None
def __init__(self, game): self.game = game # allows access to the whole game object self.sleep_time = 0.05 self.backpos = (0.03 * self.game.sx, 0.93 * self.game.sy) self.hback = 0.08 * self.game.sx self.vback = 0.05 * self.game.sy # The specifications of the grid self.reference = 0.9 * min([self.game.sx, self.game.sy]) self.game_unit = self.reference / 100 # the in-game units, instead of pixels self.xcoord = 0.5 * (max([self.game.sx, self.game.sy]) - self.reference) self.ycoord = 0.05 * self.reference # ----------------------------------------------------------------------------------------- # THE MAIN GRAPHICS OBJECTS WILL BE STORED self.laser = Laser(self) self.materials = Materials(self, self.laser) # ----------------------------------------------------------------------------------------- # Auxillary utilities # ----------------------------------------------------------------------------------------- self.score_displayed = False self.score_window = (0.31 * self.game.sx, 0.30 * self.game.sy) self.score_size = (0.56 * self.reference, 0.45 * self.reference) self.score = 0
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowTitle("NeutronPy") #We'll be using GridLayout so each pyqt instances such as Beamline, Materials, ImageViewer, Spectrum #can be displayed in their corresponding position as we desire layout = QGridLayout() #Creating an instance of these classes for our window #Robust so we can create multiply main.py windows for different operations in the future #TODO: Robustness to create new separate main windows for other imaging experiments beamline = Beamline() materials = Materials() imageviewer = ImageViewerWindow() spectrum = Spectrum(beamline, materials, imageviewer) #Defining where these instances go on the grid layout.addWidget(beamline, 0, 4, 1, 1) layout.addWidget(materials, 2, 2, 1, 3) layout.addWidget(spectrum, 0, 2, 2, 2) layout.addWidget(imageviewer, 0, 0, 3, 2) #Preset height and width height = 800 width = 1550 self.setMinimumSize(width, height) widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget)
def __init__(self, input): # Store input parameters and check them self.input = input self.input.checkInputs() # Define geometry based on geometry input type if input.geometry == 'slab': self.geo = SlabGeometry(self) elif input.geometry == 'cylindrical': self.geo = CylindricalGeometry(self) else: self.geo = SphericalGeometry(self) # Initialize material handler now that geometry is initialized self.mat = Materials(self) # Initialize field variables self.fields = Fields(self) # Time step self.timeSteps = [] # Initialize the radiation and hydro problems self.hydro = LagrangianHydro(self) self.radPredictor = LagrangianRadiationPredictor(self) self.radCorrector = LagrangianRadiationCorrector(self)
def set_equations(self, conf_equations=None, user=None, keep_solvers=False, make_virtual=False): """ Set equations of the problem using the `equations` problem description entry. Fields and Regions have to be already set. """ conf_equations = get_default(conf_equations, self.conf.get_default_attr('equations', None)) self.set_variables() variables = Variables.from_conf(self.conf_variables, self.fields) self.set_materials() materials = Materials.from_conf(self.conf_materials, self.functions) self.integrals = self.get_integrals() equations = Equations.from_conf(conf_equations, variables, self.domain.regions, materials, self.integrals, user=user, make_virtual=make_virtual) self.equations = equations if not keep_solvers: self.solvers = None
def set_equations(self, conf_equations=None, user=None, keep_solvers=False, make_virtual=False): """ Set equations of the problem using the `equations` problem description entry. Fields and Regions have to be already set. """ conf_equations = get_default(conf_equations, self.conf.get('equations', None)) self.set_variables() variables = Variables.from_conf(self.conf_variables, self.fields) self.set_materials() materials = Materials.from_conf(self.conf_materials, self.functions) self.integrals = self.get_integrals() equations = Equations.from_conf(conf_equations, variables, self.domain.regions, materials, self.integrals, user=user) self.equations = equations if not keep_solvers: self.solvers = None
def set_regions(self, conf_regions=None, conf_materials=None, funmod=None): conf_regions = get_default(conf_regions, self.conf.regions) conf_materials = get_default(conf_materials, self.conf.materials) funmod = get_default(funmod, self.conf.funmod) self.domain.create_regions(conf_regions, funmod) materials = Materials.from_conf(conf_materials) materials.setup_regions(self.domain.regions) self.materials = materials
def create_materials(self, mat_names=None): """ Create materials with names in `mat_names`. Their definitions have to be present in `self.conf.materials`. Notes ----- This method does not change `self.equations`, so it should not have any side effects. """ if mat_names is not None: conf_materials = self.select_materials(mat_names, only_conf=True) else: conf_materials = self.conf.materials materials = Materials.from_conf(conf_materials, self.functions) return materials
class RadPydro: def __init__(self, input): # Store input parameters and check them self.input = input self.input.checkInputs() # Define geometry based on geometry input type if input.geometry == 'slab': self.geo = SlabGeometry(self) elif input.geometry == 'cylindrical': self.geo = CylindricalGeometry(self) else: self.geo = SphericalGeometry(self) # Initialize material handler now that geometry is initialized self.mat = Materials(self) # Initialize field variables self.fields = Fields(self) # Time parameters self.timeSteps = [] self.time = 0. self.timeStep_num = 0 self.Tf = input.Tf # Initialize hydro problem self.hydro = LagrangianHydro(self) # Initialize radiation problem (if used) self.radPredictor = LagrangianRadiationPredictor(self) self.radCorrector = LagrangianRadiationCorrector(self) # Init storage for energies in conservation check self.kinetic_energy = [] self.internal_energy = [] self.radiation_energy = [] self.radiation_leakage = [] self.work_energy = [] self.total_energy = [] # Compute initial energies for each kinetic = 0 internal = 0 radiation = 0 for i in range(self.geo.N + 1): kinetic += 1 / 2 * self.mat.m_half[i] * self.fields.u_IC[i]**2 if i < self.geo.N: internal += self.mat.m[i] * self.fields.e_IC[i] radiation += self.mat.m[i] * self.fields.E_IC[ i] / self.fields.rho_IC[i] total = kinetic + internal + radiation self.kinetic_energy.append(kinetic) self.internal_energy.append(internal) self.radiation_energy.append(radiation) self.radiation_leakage.append(0) self.work_energy.append(0) self.total_energy.append(total) self.total_radiation_leakage = 0 self.total_work_energy = 0 def computeTimeStep(self): dr = self.geo.dr u = self.fields.u F_c = self.input.CoFactor relEFactor = self.input.relEFactor c_s = (self.mat.gamma * self.fields.P / self.fields.rho)**(1 / 2) E_k = (self.fields.E + self.fields.E_old) / 2 dE_k = np.zeros(self.geo.N) if len(self.timeSteps) == 0: dE_k = E_k else: dE_k = abs( (self.fields.E - self.fields.E_old) / self.timeSteps[-1]) u_center = np.zeros(self.geo.N) for i in range(self.geo.N): u_center = abs((u[i] + u[i + 1]) / 2) dt_E = min(relEFactor * E_k / dE_k) dt_u = min(dr * F_c / u_center) dt_cs = min(dr * F_c / c_s) self.timeSteps.append(min(self.input.maxTimeStep, dt_E, dt_u, dt_cs)) def run(self): if self.input.running_mode == 'hydro': self.runHydro() elif self.input.running_mode == 'rad': self.runRad() elif self.input.running_mode == 'radhydro': self.runRadHydro() def runHydro(self): while self.time < self.input.T_final: # Compute time step size for this time step self.computeTimeStep() # Update time and time step number self.time += self.timeSteps[-1] self.timeStep_num += 1 print('=========================================================') print('Starting time step %i, time = %.3e' \ % (self.timeStep_num, self.time)) print( '=========================================================\n') # Add artificial viscosity for this time step self.fields.addArtificialViscosity() # Predictor step self.hydro.recomputeVelocity(True) self.geo.moveMesh(True) self.hydro.recomputeDensity(True) self.hydro.recomputeInternalEnergy(True) self.fields.recomputeTemperature(True) self.fields.recomputePressure(True) # Corrector step self.hydro.recomputeVelocity(False) self.geo.moveMesh(False) self.hydro.recomputeDensity(False) self.hydro.recomputeInternalEnergy(False) self.fields.recomputeTemperature(False) self.fields.recomputePressure(False) # Energy conservation check energy_diff = self.recomputeEnergyConservation() print('Energy conservation check: ', energy_diff, '\n') # Copy to old containers for next time step self.fields.stepFields() self.geo.stepGeometry() def runRad(self): while self.time < self.input.T_final: # Compute time step size for this time step self.computeTimeStep() # Update time and time step number self.time += self.timeSteps[-1] self.timeStep_num += 1 print('=========================================================') print('Starting time step %i, time = %.3e' \ % (self.timeStep_num, self.time)) print( '=========================================================\n') # Predictor step self.radPredictor.recomputeRadiationEnergy() self.radPredictor.recomputeInternalEnergy() self.fields.recomputeTemperature(True) self.fields.recomputePressure(True) # Corrector step self.radCorrector.recomputeRadiationEnergy() self.radCorrector.recomputeInternalEnergy() self.fields.recomputeTemperature(False) self.fields.recomputePressure(False) # Energy conservation check energy_diff = self.recomputeEnergyConservation() print('Energy conservation check: ', energy_diff, '\n') # Copy to old containers for next time step self.fields.stepFields() def runRadHydro(self): while self.time < self.input.T_final: # Compute time step size for this time step self.computeTimeStep() # Update time and time step number self.time += self.timeSteps[-1] self.timeStep_num += 1 print('=========================================================') print('Starting time step %i, time = %.3e' \ % (self.timeStep_num, self.time)) print( '=========================================================\n') # Add artificial viscosity for this time step self.fields.addArtificialViscosity() # Predictor step self.hydro.recomputeVelocity(True) self.geo.moveMesh(True) self.hydro.recomputeDensity(True) self.radPredictor.recomputeRadiationEnergy() self.radPredictor.recomputeInternalEnergy() self.fields.recomputeTemperature(True) self.fields.recomputePressure(True) # Corrector step self.hydro.recomputeVelocity(False) self.geo.moveMesh(False) self.hydro.recomputeDensity(False) self.radCorrector.recomputeRadiationEnergy() self.radCorrector.recomputeInternalEnergy() self.fields.recomputeTemperature(False) self.fields.recomputePressure(False) # Energy conservation check energy_diff = self.recomputeEnergyConservation() print('Energy conservation check: ', energy_diff, '\n') # Copy to old containers for next time step self.fields.stepFields() self.geo.stepGeometry() def recomputeEnergyConservation(self): kinetic_energy = self.kinetic_energy internal_energy = self.internal_energy radiation_energy = self.radiation_energy radiation_leakage = self.radiation_leakage work_energy = self.work_energy total_energy = self.total_energy c = self.input.c dt = self.timeSteps[-1] m = self.mat.m m_half = self.mat.m_half u = self.fields.u e = self.fields.e E = self.fields.E rho = self.fields.rho A_k = (self.geo.A + self.geo.A_old) / 2 A_pk = (self.geo.A_p + self.geo.A_old) / 2 dr_k = (self.geo.dr + self.geo.dr_old) / 2 dr_pk = (self.geo.dr_p + self.geo.dr_old) / 2 E_k = (self.fields.E + self.fields.E_old) / 2 E_pk = (self.fields.E_p + self.fields.E_old) / 2 T_k = (self.fields.T + self.fields.T_old) / 2 T_pk = (self.fields.T_p + self.fields.T_old) / 2 rho_k = (self.fields.rho + self.fields.rho_old) / 2 rho_pk = (self.fields.rho_p + self.fields.rho_old) / 2 u_k = (self.fields.u + self.fields.u_old) / 2 P_pk = (self.fields.P_p + self.fields.P_old) / 2 # Recomputing kappa_t at the cell edges and cell centers self.mat.recomputeKappa_t(T_pk) kappa_t_pk_edge = self.mat.kappa_t self.mat.recomputeKappa_a(T_pk) kappa_t_pk_center = self.mat.kappa_a + self.mat.kappa_s # Setting up boundary parameters for the radiation terms # in the momentum equation if self.input.rad_L is 'source': E_bL_k = self.fields.E_bL E_bL_pk = self.fields.E_bL else: E_bL_k = E_k[0] E_bL_pk = E_pk[0] if self.input.rad_R is 'source': E_bR_k = self.fields.E_bR E_bR_pk = self.fields.E_bR else: E_bR_k = E_k[-1] E_bR_pk = E_pk[-1] # Compute the boundary radiation energies in the momentum eqn coeff_E_L = 3 * rho_pk[0] * dr_pk[0] * kappa_t_pk_center[0] coeff_E_R = 3 * rho_pk[-1] * dr_pk[-1] * kappa_t_pk_center[-1] E_L = (coeff_E_L * E_bL_pk + 4 * E_pk[0]) / (coeff_E_L + 4) E_R = (coeff_E_R * E_bR_pk + 4 * E_pk[-1]) / (coeff_E_R + 4) # Compute radiation flux at boundaries coeff_F_L = -2 * c / (3 * rho_k[0] * dr_k[0] * kappa_t_pk_edge[0] + 4) coeff_F_R = -2 * c / (3 * rho_k[-1] * dr_k[-1] * kappa_t_pk_edge[-1] + 4) F_L = coeff_F_L * (E_k[0] - E_bL_k) F_R = coeff_F_R * (E_bR_k - E_k[-1]) # Setting up boundary parameters for the pressure boundary values if self.input.hydro_L is 'P': P_bL_pk = self.fields.P_L else: P_bL_pk = P_pk[0] + 1 / 3 * (E_pk[0] - E_L) if self.input.hydro_R is 'P': P_bR_pk = self.fields.P_R else: P_bR_pk = P_pk[-1] + 1 / 3 * (E_pk[-1] - E_R) # Compute kinetic, internal, and radiation energies for this timestep kinetic, internal, radiation = 0, 0, 0 for i in range(self.geo.N + 1): kinetic += 1 / 2 * m_half[i] * u[i]**2 if i < self.geo.N: internal += m[i] * e[i] radiation += m[i] * E[i] / rho[i] # Compute radiation leakage leakage = (A_k[-1] * F_R - A_k[0] * F_L) * dt # Compute compressive work work = (A_pk[-1] * 1 / 3 * E_R * u_k[-1] - A_pk[0] * 1 / 3 * E_L * u_k[0]) * dt work += (A_pk[-1] * P_bR_pk * u_k[-1] - A_pk[0] * P_bL_pk * u_k[0]) * dt # Compute total energy total = kinetic + internal + radiation + leakage + work # Compute energy final - initial energies dKE = kinetic - kinetic_energy[0] dIE = internal - internal_energy[0] dRE = radiation - radiation_energy[0] # Compute energy losses from pressure work, drift, and leakage total_work = self.total_work_energy + work total_leak = self.total_radiation_leakage + leakage # Update loss terms from pressure work, drift, and leakage self.total_work_energy += work self.total_radiation_leakage += leakage # Append to storage kinetic_energy.append(kinetic) internal_energy.append(internal) radiation_energy.append(radiation) radiation_leakage.append(leakage) work_energy.append(work) total_energy.append(total) return dKE + dIE + dRE + total_work + total_leak
class Graphics: # ------------------------------------------------------------------------------------------------- def __init__(self, game): self.game = game # allows access to the whole game object self.sleep_time = 0.05 self.backpos = (0.03 * self.game.sx, 0.93 * self.game.sy) self.hback = 0.08 * self.game.sx self.vback = 0.05 * self.game.sy # The specifications of the grid self.reference = 0.9 * min([self.game.sx, self.game.sy]) self.game_unit = self.reference / 100 # the in-game units, instead of pixels self.xcoord = 0.5 * (max([self.game.sx, self.game.sy]) - self.reference) self.ycoord = 0.05 * self.reference # ----------------------------------------------------------------------------------------- # THE MAIN GRAPHICS OBJECTS WILL BE STORED self.laser = Laser(self) self.materials = Materials(self, self.laser) # ----------------------------------------------------------------------------------------- # Auxillary utilities # ----------------------------------------------------------------------------------------- self.score_displayed = False self.score_window = (0.31 * self.game.sx, 0.30 * self.game.sy) self.score_size = (0.56 * self.reference, 0.45 * self.reference) self.score = 0 def buttons(self, ): def hoverclick(pos, h, v): click = pg.mouse.get_pressed() mx, my = pg.mouse.get_pos() if (mx > pos[0] and mx < pos[0] + h) and (my > pos[1] and my < pos[1] + v): if click[0] == 1: return True if self.game.interface.submitted == False: if hoverclick(self.backpos, self.hback, self.vback): self.game.mode = "interface" time.sleep(3 * self.sleep_time) if self.game.interface.submitted == True: if hoverclick(self.backpos, self.hback, self.vback): self.game.mode = "interface" self.materials.init_level(self.materials.level) self.laser.reset() self.game.interface.reset() self.laser.finished = False self.score_displayed = False self.score = 0 time.sleep(3 * self.sleep_time) def draw_buttons(self, ): mx, my = pg.mouse.get_pos() def command_button(string, pos, h, v, mx, my, game, font=20): buttonfont = pygame.font.Font('freesansbold.ttf', 18) # font if (mx > pos[0] and mx < pos[0] + h) and (my > pos[1] and my < pos[1] + v): button = buttonfont.render(string, True, BLUE, None) else: button = buttonfont.render(string, True, WHITE, None) buttonRect = button.get_rect() buttonRect.width = h buttonRect.height = v buttonRect.center = (pos[0] + 0.55 * h, pos[1] + 0.7 * v) pg.draw.rect(game.display, DBLUE, (pos[0], pos[1], h, v), 1) game.display.blit(button, buttonRect) if self.game.interface.submitted == False: command_button("BACK", self.backpos, self.hback, self.vback, mx, my, self.game) if self.game.interface.submitted == True: command_button("RESTART", self.backpos, self.hback, self.vback, mx, my, self.game) def measure(self, ): # Allows the player to check coordinates using the mouse when clicking. mx, my = pg.mouse.get_pos() # position to be displayed dx = int(mx / self.game_unit) dy = int(my / self.game_unit) if pg.mouse.get_pressed()[0] == 1: measurefont = pygame.font.Font('freesansbold.ttf', 10) measure = measurefont.render(f"{dx}, {dy}", True, WHITE, None) measureRect = measure.get_rect() measureRect.center = (mx, my) self.game.display.blit(measure, measureRect) def draw_grid(self, ): # dimensions of the grid dependent on the smallest dimension of the game itself. # y # ------------------------------ # | ----------- | # | | | | | # | | + | | smaller distance # | | | | | # | ----------- | # ------------------------------x pg.draw.rect( self.game.display, WHITE, (self.xcoord, self.ycoord, self.reference, self.reference), 2) def info(self, ): # Displays vital information for the player. # - The state and parameters of the laser # - Their current score # - The score they have to beat # - The amount of energy the laser has left pass def game_finished(self, ): # displays score if finished. if self.score_displayed == True: pg.draw.rect(self.game.display, BLACK, (self.score_window[0], self.score_window[1], self.score_size[0], self.score_size[1]), 0) pg.draw.rect(self.game.display, GREEN, (self.score_window[0], self.score_window[1], self.score_size[0], self.score_size[1]), 2) scorefont = pygame.font.Font('freesansbold.ttf', 19) # font score = scorefont.render(f'Score: {self.score}', True, GREEN, BLACK) scoreRect = score.get_rect() scoreRect.width = 50 scoreRect.height = 30 scoreRect.center = (0.46 * self.game.sx, 0.40 * self.game.sy) def command_button(string, pos, h, v, mx, my, game, font=20): buttonfont = pygame.font.Font('freesansbold.ttf', 18) # font if (mx > pos[0] and mx < pos[0] + h) and (my > pos[1] and my < pos[1] + v): button = buttonfont.render(string, True, BLUE, None) else: button = buttonfont.render(string, True, WHITE, None) buttonRect = button.get_rect() buttonRect.width = h buttonRect.height = v buttonRect.center = (pos[0] + 0.55 * h, pos[1] + 0.7 * v) game.display.blit(button, buttonRect) def hoverclick(pos, h, v): click = pg.mouse.get_pressed() mx, my = pg.mouse.get_pos() if (mx > pos[0] and mx < pos[0] + h) and (my > pos[1] and my < pos[1] + v): if click[0] == 1: return True mx, my = pg.mouse.get_pos() h = 0.1 * self.game.sx v = 0.04 * self.game.sx subpos = (0.46 * self.game.sx, 0.50 * self.game.sy) retpos = (0.46 * self.game.sx, 0.57 * self.game.sy) command_button("Submit", subpos, h, v, mx, my, self.game) command_button("Levels", retpos, h, v, mx, my, self.game) # return to menu if hoverclick(retpos, h, v) == True: self.game.mode = "menu" self.laser.reset() self.game.interface.reset() self.laser.finished = False self.score_displayed = False self.score = 0 time.sleep(3 * self.sleep_time) if hoverclick(subpos, h, v) == True: file_open = f".highscores/.lvl{self.materials.level}" print(file_open) with open(file_open, 'a') as f: datestr = date.today().strftime("%d/%m/%y") f.write(f"\n{datestr}\t{self.score}") self.game.mode = "menu" self.laser.reset() self.game.interface.reset() self.laser.finished = False self.score_displayed = False self.score = 0 time.sleep(3 * self.sleep_time) self.game.display.blit(score, scoreRect) else: size = np.shape(self.materials.matpix)[0] for i in range(size): for j in range(size): if (self.materials.matpix[i, j, :] == RED).all(): self.score += 20 if (self.materials.matpix[i, j, :].all() == ORANGE).all(): self.score -= 1 self.score_displayed = True # ------------------------------------------------------------------------------------------ # LEAD FUNCTIONS # ------------------------------------------------------------------------------------------ def UpdateGraphics(self, ): self.buttons() if self.game.interface.submitted == True and self.laser.finished == False: self.laser.update_laser() def DrawGraphics(self, ): self.game.display.fill(DBLUE) self.draw_grid() self.draw_buttons() # drawing materials self.materials.draw_material() self.laser.draw_laser() self.measure() if self.laser.finished == True: self.game_finished()
def __init__(self): self.wline = None self.wrect = None self.wcirc = None self.warc = None self.wpolygon = None self.wpolyline = None self.wrslot = None self.wdrillrect = None self.wdrillcirc = None self.wdrillline = None self.wgrid = None self.wdiamonds = None self.whatch = None self.modified = False wx.Frame.__init__(self, None, size=(480, 800), title="G Code Generators - Main Menu") self.Bind(wx.EVT_CLOSE, self.onClose) self.SetBackgroundColour("white") self.settings = Settings(self, cmdFolder) self.tools = Tools("tools.json") self.toolList = self.tools.getTools() if self.settings.tool not in self.toolList: self.settings.tool = self.toolList[0] self.settings.setModified() self.toolInfo = self.tools.getTool(self.settings.tool) self.images = Images(os.path.join(cmdFolder, "images")) self.materials = Materials() self.materialList = self.materials.getMaterials() if self.settings.material not in self.materialList: self.settings.material = self.materialList[0] self.settings.setModified() self.speedInfo = self.tools.getToolSpeeds(self.settings.tool, self.settings.material) self.CreateStatusBar() menuBar = wx.MenuBar() self.menuFile = wx.Menu() self.menuFile.Append(MENU_FILE_VIEW, "&View", "View a G Code File") self.menuFile.Append(MENU_FILE_MERGE, "&Merge", "Merge G Code Files") menuBar.Append(self.menuFile, "&File") self.menuOpts = wx.Menu() self.menuOpts.Append(MENU_OPTS_ANNOTATE, "&Annotate", "Annotate G Code", wx.ITEM_CHECK) self.menuOpts.Append(MENU_OPTS_ADD_SPEED, "A&dd Speed Term", "Default setting for add speed term", wx.ITEM_CHECK) self.menuOpts.Append(MENU_OPTS_METRIC, "&Metric", "Use Metric Measurement System", wx.ITEM_CHECK) menuBar.Append(self.menuOpts, "&Options") self.menuMaterials = wx.Menu() mx = 0 for m in self.materialList: mid = MENU_MATERIALS_BASE + mx self.menuMaterials.Append(mid, m, "Material: {}".format(m), wx.ITEM_RADIO) if m == self.settings.material: self.menuMaterials.Check(mid, True) self.Bind(wx.EVT_MENU, self.onMenuMaterials, id=mid) mx += 1 menuBar.Append(self.menuMaterials, "&Material") self.menuTools = wx.Menu() tx = 0 for t in self.toolList: tinfo = self.tools.getTool(t) tid = MENU_TOOLS_BASE + tx self.menuTools.Append(tid, t, "{}".format(tinfo["name"]), wx.ITEM_RADIO) if t == self.settings.tool: self.menuTools.Check(tid, True) self.Bind(wx.EVT_MENU, self.onMenuTools, id=tid) tx += 1 menuBar.Append(self.menuTools, "&Tool") self.SetMenuBar(menuBar) self.Bind(wx.EVT_MENU, self.onMenuFileView, id=MENU_FILE_VIEW) self.Bind(wx.EVT_MENU, self.onMenuFileMerge, id=MENU_FILE_MERGE) self.Bind(wx.EVT_MENU, self.onMenuOptsAnnotate, id=MENU_OPTS_ANNOTATE) self.Bind(wx.EVT_MENU, self.onMenuOptsAddSpeed, id=MENU_OPTS_ADD_SPEED) self.Bind(wx.EVT_MENU, self.onMenuOptsMetric, id=MENU_OPTS_METRIC) self.menuOpts.Check(MENU_OPTS_ANNOTATE, self.settings.annotate) self.menuOpts.Check(MENU_OPTS_ADD_SPEED, self.settings.addspeed) self.menuOpts.Check(MENU_OPTS_METRIC, self.settings.metric) sizer = wx.BoxSizer(wx.HORIZONTAL) msizer = wx.BoxSizer(wx.VERTICAL) boxCont = wx.StaticBox(self, wx.ID_ANY, " Contours ") topBorder = boxCont.GetBordersForSizer()[0] bsizer = wx.BoxSizer(wx.VERTICAL) bsizer.AddSpacer(topBorder) szContours = wx.BoxSizer(wx.HORIZONTAL) szContours.AddSpacer(10) self.bLine = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourline, size=BTNDIM) self.bLine.SetToolTip("Generate G Code for a straight line") szContours.Add(self.bLine) self.Bind(wx.EVT_BUTTON, self.bLinePressed, self.bLine) self.bRect = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourrectangle, size=BTNDIM) self.bRect.SetToolTip("Generate G Code for a rectangle") szContours.Add(self.bRect) self.Bind(wx.EVT_BUTTON, self.bRectPressed, self.bRect) self.bCirc = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourcircle, size=BTNDIM) self.bCirc.SetToolTip("Generate G Code for a circle") szContours.Add(self.bCirc) self.Bind(wx.EVT_BUTTON, self.bCircPressed, self.bCirc) self.bArc = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourarc, size=BTNDIM) self.bArc.SetToolTip("Generate G Code for an arc") szContours.Add(self.bArc) self.Bind(wx.EVT_BUTTON, self.bArcPressed, self.bArc) self.bPolygon = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourpolygon, size=BTNDIM) self.bPolygon.SetToolTip("Generate G Code for a regular polygon") szContours.Add(self.bPolygon) self.Bind(wx.EVT_BUTTON, self.bPolygonPressed, self.bPolygon) self.bPolyline = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourpolyline, size=BTNDIM) self.bPolyline.SetToolTip("Generate G Code for an open or close path") szContours.Add(self.bPolyline) self.Bind(wx.EVT_BUTTON, self.bPolylinePressed, self.bPolyline) self.bRSlot = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourroundedslot, size=BTNDIM) self.bRSlot.SetToolTip("Generate G Code for a rounded slot") szContours.Add(self.bRSlot) self.Bind(wx.EVT_BUTTON, self.bRSlotPressed, self.bRSlot) szContours.AddSpacer(10) bsizer.Add(szContours) bsizer.AddSpacer(10) boxCont.SetSizer(bsizer) msizer.Add(boxCont, weightSingle, wx.EXPAND | wx.ALL, 10) boxDrills = wx.StaticBox(self, wx.ID_ANY, " Drills ") topBorder = boxDrills.GetBordersForSizer()[0] bsizer = wx.BoxSizer(wx.VERTICAL) bsizer.AddSpacer(topBorder) szDrills = wx.BoxSizer(wx.HORIZONTAL) szDrills.AddSpacer(10) self.bDrillRect = wx.BitmapButton(boxDrills, wx.ID_ANY, self.images.pngDrillrectangle, size=BTNDIM) self.bDrillRect.SetToolTip( "Generate G Code for a rectangular drill pattern") szDrills.Add(self.bDrillRect) self.Bind(wx.EVT_BUTTON, self.bDrillRectPressed, self.bDrillRect) self.bDrillCirc = wx.BitmapButton(boxDrills, wx.ID_ANY, self.images.pngDrillcircle, size=BTNDIM) self.bDrillCirc.SetToolTip( "Generate G Code for a circular drill pattern") szDrills.Add(self.bDrillCirc) self.Bind(wx.EVT_BUTTON, self.bDrillCircPressed, self.bDrillCirc) self.bDrillLine = wx.BitmapButton(boxDrills, wx.ID_ANY, self.images.pngDrilllinear, size=BTNDIM) self.bDrillLine.SetToolTip( "Generate G Code for a linear drill pattern") szDrills.Add(self.bDrillLine) self.Bind(wx.EVT_BUTTON, self.bDrillLinePressed, self.bDrillLine) bsizer.Add(szDrills) bsizer.AddSpacer(10) boxDrills.SetSizer(bsizer) msizer.Add(boxDrills, weightSingle, wx.EXPAND | wx.ALL, 10) boxCarve = wx.StaticBox(self, wx.ID_ANY, " Carvings ") topBorder = boxCarve.GetBordersForSizer()[0] bsizer = wx.BoxSizer(wx.VERTICAL) bsizer.AddSpacer(topBorder) szCarving = wx.BoxSizer(wx.HORIZONTAL) szCarving.AddSpacer(10) self.bGrid = wx.BitmapButton(boxCarve, wx.ID_ANY, self.images.pngCarvegrid, size=BTNDIM) self.bGrid.SetToolTip("Generate G Code for a grid pattern") szCarving.Add(self.bGrid) self.Bind(wx.EVT_BUTTON, self.bGridPressed, self.bGrid) self.bDiamonds = wx.BitmapButton(boxCarve, wx.ID_ANY, self.images.pngCarvediamond, size=BTNDIM) self.bDiamonds.SetToolTip("Generate G Code for a diamond pattern") szCarving.Add(self.bDiamonds) self.Bind(wx.EVT_BUTTON, self.bDiamondPressed, self.bDiamonds) self.bHatch = wx.BitmapButton(boxCarve, wx.ID_ANY, self.images.pngCarvehatch, size=BTNDIM) self.bHatch.SetToolTip("Generate G Code for a cross-hatch pattern") szCarving.Add(self.bHatch) self.Bind(wx.EVT_BUTTON, self.bHatchPressed, self.bHatch) bsizer.Add(szCarving) bsizer.AddSpacer(10) boxCarve.SetSizer(bsizer) msizer.Add(boxCarve, weightSingle, wx.EXPAND | wx.ALL, 10) sizer.Add(msizer) sizer.AddSpacer(10) self.SetSizer(sizer) self.Layout() self.Fit()
class MainFrame(wx.Frame): def __init__(self): self.wline = None self.wrect = None self.wcirc = None self.warc = None self.wpolygon = None self.wpolyline = None self.wrslot = None self.wdrillrect = None self.wdrillcirc = None self.wdrillline = None self.wgrid = None self.wdiamonds = None self.whatch = None self.modified = False wx.Frame.__init__(self, None, size=(480, 800), title="G Code Generators - Main Menu") self.Bind(wx.EVT_CLOSE, self.onClose) self.SetBackgroundColour("white") self.settings = Settings(self, cmdFolder) self.tools = Tools("tools.json") self.toolList = self.tools.getTools() if self.settings.tool not in self.toolList: self.settings.tool = self.toolList[0] self.settings.setModified() self.toolInfo = self.tools.getTool(self.settings.tool) self.images = Images(os.path.join(cmdFolder, "images")) self.materials = Materials() self.materialList = self.materials.getMaterials() if self.settings.material not in self.materialList: self.settings.material = self.materialList[0] self.settings.setModified() self.speedInfo = self.tools.getToolSpeeds(self.settings.tool, self.settings.material) self.CreateStatusBar() menuBar = wx.MenuBar() self.menuFile = wx.Menu() self.menuFile.Append(MENU_FILE_VIEW, "&View", "View a G Code File") self.menuFile.Append(MENU_FILE_MERGE, "&Merge", "Merge G Code Files") menuBar.Append(self.menuFile, "&File") self.menuOpts = wx.Menu() self.menuOpts.Append(MENU_OPTS_ANNOTATE, "&Annotate", "Annotate G Code", wx.ITEM_CHECK) self.menuOpts.Append(MENU_OPTS_ADD_SPEED, "A&dd Speed Term", "Default setting for add speed term", wx.ITEM_CHECK) self.menuOpts.Append(MENU_OPTS_METRIC, "&Metric", "Use Metric Measurement System", wx.ITEM_CHECK) menuBar.Append(self.menuOpts, "&Options") self.menuMaterials = wx.Menu() mx = 0 for m in self.materialList: mid = MENU_MATERIALS_BASE + mx self.menuMaterials.Append(mid, m, "Material: {}".format(m), wx.ITEM_RADIO) if m == self.settings.material: self.menuMaterials.Check(mid, True) self.Bind(wx.EVT_MENU, self.onMenuMaterials, id=mid) mx += 1 menuBar.Append(self.menuMaterials, "&Material") self.menuTools = wx.Menu() tx = 0 for t in self.toolList: tinfo = self.tools.getTool(t) tid = MENU_TOOLS_BASE + tx self.menuTools.Append(tid, t, "{}".format(tinfo["name"]), wx.ITEM_RADIO) if t == self.settings.tool: self.menuTools.Check(tid, True) self.Bind(wx.EVT_MENU, self.onMenuTools, id=tid) tx += 1 menuBar.Append(self.menuTools, "&Tool") self.SetMenuBar(menuBar) self.Bind(wx.EVT_MENU, self.onMenuFileView, id=MENU_FILE_VIEW) self.Bind(wx.EVT_MENU, self.onMenuFileMerge, id=MENU_FILE_MERGE) self.Bind(wx.EVT_MENU, self.onMenuOptsAnnotate, id=MENU_OPTS_ANNOTATE) self.Bind(wx.EVT_MENU, self.onMenuOptsAddSpeed, id=MENU_OPTS_ADD_SPEED) self.Bind(wx.EVT_MENU, self.onMenuOptsMetric, id=MENU_OPTS_METRIC) self.menuOpts.Check(MENU_OPTS_ANNOTATE, self.settings.annotate) self.menuOpts.Check(MENU_OPTS_ADD_SPEED, self.settings.addspeed) self.menuOpts.Check(MENU_OPTS_METRIC, self.settings.metric) sizer = wx.BoxSizer(wx.HORIZONTAL) msizer = wx.BoxSizer(wx.VERTICAL) boxCont = wx.StaticBox(self, wx.ID_ANY, " Contours ") topBorder = boxCont.GetBordersForSizer()[0] bsizer = wx.BoxSizer(wx.VERTICAL) bsizer.AddSpacer(topBorder) szContours = wx.BoxSizer(wx.HORIZONTAL) szContours.AddSpacer(10) self.bLine = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourline, size=BTNDIM) self.bLine.SetToolTip("Generate G Code for a straight line") szContours.Add(self.bLine) self.Bind(wx.EVT_BUTTON, self.bLinePressed, self.bLine) self.bRect = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourrectangle, size=BTNDIM) self.bRect.SetToolTip("Generate G Code for a rectangle") szContours.Add(self.bRect) self.Bind(wx.EVT_BUTTON, self.bRectPressed, self.bRect) self.bCirc = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourcircle, size=BTNDIM) self.bCirc.SetToolTip("Generate G Code for a circle") szContours.Add(self.bCirc) self.Bind(wx.EVT_BUTTON, self.bCircPressed, self.bCirc) self.bArc = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourarc, size=BTNDIM) self.bArc.SetToolTip("Generate G Code for an arc") szContours.Add(self.bArc) self.Bind(wx.EVT_BUTTON, self.bArcPressed, self.bArc) self.bPolygon = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourpolygon, size=BTNDIM) self.bPolygon.SetToolTip("Generate G Code for a regular polygon") szContours.Add(self.bPolygon) self.Bind(wx.EVT_BUTTON, self.bPolygonPressed, self.bPolygon) self.bPolyline = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourpolyline, size=BTNDIM) self.bPolyline.SetToolTip("Generate G Code for an open or close path") szContours.Add(self.bPolyline) self.Bind(wx.EVT_BUTTON, self.bPolylinePressed, self.bPolyline) self.bRSlot = wx.BitmapButton(boxCont, wx.ID_ANY, self.images.pngContourroundedslot, size=BTNDIM) self.bRSlot.SetToolTip("Generate G Code for a rounded slot") szContours.Add(self.bRSlot) self.Bind(wx.EVT_BUTTON, self.bRSlotPressed, self.bRSlot) szContours.AddSpacer(10) bsizer.Add(szContours) bsizer.AddSpacer(10) boxCont.SetSizer(bsizer) msizer.Add(boxCont, weightSingle, wx.EXPAND | wx.ALL, 10) boxDrills = wx.StaticBox(self, wx.ID_ANY, " Drills ") topBorder = boxDrills.GetBordersForSizer()[0] bsizer = wx.BoxSizer(wx.VERTICAL) bsizer.AddSpacer(topBorder) szDrills = wx.BoxSizer(wx.HORIZONTAL) szDrills.AddSpacer(10) self.bDrillRect = wx.BitmapButton(boxDrills, wx.ID_ANY, self.images.pngDrillrectangle, size=BTNDIM) self.bDrillRect.SetToolTip( "Generate G Code for a rectangular drill pattern") szDrills.Add(self.bDrillRect) self.Bind(wx.EVT_BUTTON, self.bDrillRectPressed, self.bDrillRect) self.bDrillCirc = wx.BitmapButton(boxDrills, wx.ID_ANY, self.images.pngDrillcircle, size=BTNDIM) self.bDrillCirc.SetToolTip( "Generate G Code for a circular drill pattern") szDrills.Add(self.bDrillCirc) self.Bind(wx.EVT_BUTTON, self.bDrillCircPressed, self.bDrillCirc) self.bDrillLine = wx.BitmapButton(boxDrills, wx.ID_ANY, self.images.pngDrilllinear, size=BTNDIM) self.bDrillLine.SetToolTip( "Generate G Code for a linear drill pattern") szDrills.Add(self.bDrillLine) self.Bind(wx.EVT_BUTTON, self.bDrillLinePressed, self.bDrillLine) bsizer.Add(szDrills) bsizer.AddSpacer(10) boxDrills.SetSizer(bsizer) msizer.Add(boxDrills, weightSingle, wx.EXPAND | wx.ALL, 10) boxCarve = wx.StaticBox(self, wx.ID_ANY, " Carvings ") topBorder = boxCarve.GetBordersForSizer()[0] bsizer = wx.BoxSizer(wx.VERTICAL) bsizer.AddSpacer(topBorder) szCarving = wx.BoxSizer(wx.HORIZONTAL) szCarving.AddSpacer(10) self.bGrid = wx.BitmapButton(boxCarve, wx.ID_ANY, self.images.pngCarvegrid, size=BTNDIM) self.bGrid.SetToolTip("Generate G Code for a grid pattern") szCarving.Add(self.bGrid) self.Bind(wx.EVT_BUTTON, self.bGridPressed, self.bGrid) self.bDiamonds = wx.BitmapButton(boxCarve, wx.ID_ANY, self.images.pngCarvediamond, size=BTNDIM) self.bDiamonds.SetToolTip("Generate G Code for a diamond pattern") szCarving.Add(self.bDiamonds) self.Bind(wx.EVT_BUTTON, self.bDiamondPressed, self.bDiamonds) self.bHatch = wx.BitmapButton(boxCarve, wx.ID_ANY, self.images.pngCarvehatch, size=BTNDIM) self.bHatch.SetToolTip("Generate G Code for a cross-hatch pattern") szCarving.Add(self.bHatch) self.Bind(wx.EVT_BUTTON, self.bHatchPressed, self.bHatch) bsizer.Add(szCarving) bsizer.AddSpacer(10) boxCarve.SetSizer(bsizer) msizer.Add(boxCarve, weightSingle, wx.EXPAND | wx.ALL, 10) sizer.Add(msizer) sizer.AddSpacer(10) self.SetSizer(sizer) self.Layout() self.Fit() def onMenuFileView(self, _): dlg = wx.FileDialog(self, message="Choose a file", defaultDir=self.settings.lastloaddir, defaultFile="", wildcard=wildcard, style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_PREVIEW) if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() return path = dlg.GetPath() dlg.Destroy() pdir = os.path.split(path)[0] if pdir != self.settings.lastloaddir: self.settings.lastloaddir = pdir self.settings.setModified() with open(path, "r") as fp: glines = fp.readlines() vwrDlg = NCViewer(self, path, self.settings) vwrDlg.loadGCode(glines) vwrDlg.ShowModal() vwrDlg.Destroy() def onMenuFileMerge(self, _): dlg = FileMergeDialog(self) dlg.ShowModal() dlg.Destroy() def onMenuOptsAnnotate(self, _): self.settings.annotate = self.menuOpts.IsChecked(MENU_OPTS_ANNOTATE) self.settings.setModified() def onMenuOptsAddSpeed(self, _): self.settings.addspeed = self.menuOpts.IsChecked(MENU_OPTS_ADD_SPEED) self.settings.setModified() def onMenuOptsMetric(self, _): self.settings.metric = self.menuOpts.IsChecked(MENU_OPTS_METRIC) self.settings.setModified() def onMenuMaterials(self, evt): self.settings.material = self.menuMaterials.GetLabel(evt.GetId()) self.settings.setModified() self.speedInfo = self.tools.getToolSpeeds(self.settings.tool, self.settings.material) def onMenuTools(self, evt): self.settings.tool = self.menuTools.GetLabel(evt.GetId()) self.settings.setModified() self.toolInfo = self.tools.getTool(self.settings.tool) self.speedInfo = self.tools.getToolSpeeds(self.settings.tool, self.settings.material) def onClose(self, _): if not self.closeIfOkay(self.wline): return self.wline = None if not self.closeIfOkay(self.wrect): return self.wrect = None if not self.closeIfOkay(self.wcirc): return self.wcirc = None if not self.closeIfOkay(self.warc): return self.warc = None if not self.closeIfOkay(self.wpolygon): return self.wpolygon = None if not self.closeIfOkay(self.wpolyline): return self.wpolyline = None if not self.closeIfOkay(self.wrslot): return self.wrslot = None if not self.closeIfOkay(self.wdrillrect): return self.wdrillrect = None if not self.closeIfOkay(self.wdrillcirc): return self.wdrillcirc = None if not self.closeIfOkay(self.wdrillline): return self.wdrillline = None if not self.closeIfOkay(self.wgrid): return self.wgrid = None if not self.closeIfOkay(self.wdiamonds): return self.wdiamonds = None if not self.closeIfOkay(self.whatch): return self.whatch = None self.settings.cleanUp() self.Destroy() def closeIfOkay(self, w): if w is None: return True if w.okToClose(): w.Destroy() return True return False def bLinePressed(self, _): if self.wline: self.wline.SetFocus() else: self.wline = line.MainFrame(self.toolInfo, self.speedInfo, self) self.wline.Bind(wx.EVT_CLOSE, self.lineClose) self.wline.Show() def lineClose(self, _): if self.closeIfOkay(self.wline): self.wline = None def bRectPressed(self, _): if self.wrect: self.wrect.SetFocus() else: self.wrect = rect.MainFrame(self.toolInfo, self.speedInfo, self) self.wrect.Bind(wx.EVT_CLOSE, self.rectClose) self.wrect.Show() def rectClose(self, _): if self.closeIfOkay(self.wrect): self.wrect = None def bCircPressed(self, _): if self.wcirc: self.wcirc.SetFocus() else: self.wcirc = circ.MainFrame(self.toolInfo, self.speedInfo, self) self.wcirc.Bind(wx.EVT_CLOSE, self.circClose) self.wcirc.Show() def circClose(self, _): if self.closeIfOkay(self.wcirc): self.wcirc = None def bArcPressed(self, _): if self.warc: self.warc.SetFocus() else: self.warc = arc.MainFrame(self.toolInfo, self.speedInfo, self) self.warc.Bind(wx.EVT_CLOSE, self.arcClose) self.warc.Show() def arcClose(self, _): if self.closeIfOkay(self.warc): self.warc = None def bPolygonPressed(self, _): if self.wpolygon: self.wpolygon.SetFocus() else: self.wpolygon = polygon.MainFrame(self.toolInfo, self.speedInfo, self) self.wpolygon.Bind(wx.EVT_CLOSE, self.polygonClose) self.wpolygon.Show() def polygonClose(self, _): if self.closeIfOkay(self.wpolygon): self.wpolygon = None def bPolylinePressed(self, _): if self.wpolyline: self.wpolyline.SetFocus() else: self.wpolyline = polyline.MainFrame(self.toolInfo, self.speedInfo, self) self.wpolyline.Bind(wx.EVT_CLOSE, self.polylineClose) self.wpolyline.Show() def polylineClose(self, _): if self.closeIfOkay(self.wpolyline): self.wpolyline = None def bRSlotPressed(self, _): if self.wrslot: self.wrslot.SetFocus() else: self.wrslot = rslot.MainFrame(self.toolInfo, self.speedInfo, self) self.wrslot.Bind(wx.EVT_CLOSE, self.rslotClose) self.wrslot.Show() def rslotClose(self, _): if self.closeIfOkay(self.wrslot): self.wrslot = None def bDrillRectPressed(self, _): if self.wdrillrect: self.wdrillrect.SetFocus() else: self.wdrillrect = drillrect.MainFrame(self.toolInfo, self.speedInfo, self) self.wdrillrect.Bind(wx.EVT_CLOSE, self.drillrectClose) self.wdrillrect.Show() def drillrectClose(self, _): if self.closeIfOkay(self.wdrillrect): self.wdrillrect = None def bDrillCircPressed(self, _): if self.wdrillcirc: self.wdrillcirc.SetFocus() else: self.wdrillcirc = drillcirc.MainFrame(self.toolInfo, self.speedInfo, self) self.wdrillcirc.Bind(wx.EVT_CLOSE, self.drillcircClose) self.wdrillcirc.Show() def drillcircClose(self, _): if self.closeIfOkay(self.wdrillcirc): self.wdrillcirc = None def bDrillLinePressed(self, _): if self.wdrillline: self.wdrillline.SetFocus() else: self.wdrillline = drillline.MainFrame(self.toolInfo, self.speedInfo, self) self.wdrillline.Bind(wx.EVT_CLOSE, self.drilllineClose) self.wdrillline.Show() def drilllineClose(self, _): if self.closeIfOkay(self.wdrillline): self.wdrillline = None def bGridPressed(self, _): if self.wgrid: self.wgrid.SetFocus() else: self.wgrid = grid.MainFrame(self.toolInfo, self.speedInfo, self) self.wgrid.Bind(wx.EVT_CLOSE, self.gridClose) self.wgrid.Show() def gridClose(self, _): if self.closeIfOkay(self.wgrid): self.wgrid = None def bDiamondPressed(self, _): if self.wdiamonds: self.wdiamonds.SetFocus() else: self.wdiamonds = diamonds.MainFrame(self.toolInfo, self.speedInfo, self) self.wdiamonds.Bind(wx.EVT_CLOSE, self.diamondsClose) self.wdiamonds.Show() def diamondsClose(self, _): if self.closeIfOkay(self.wdiamonds): self.wdiamonds = None def bHatchPressed(self, _): if self.whatch: self.whatch.SetFocus() else: self.whatch = hatch.MainFrame(self.toolInfo, self.speedInfo, self) self.whatch.Bind(wx.EVT_CLOSE, self.hatchClose) self.whatch.Show() def hatchClose(self, _): if self.closeIfOkay(self.whatch): self.whatch = None
size=(53.3, 38.7) ) space.add_subject(detector) collimator = SiemensSymbiaTSeriesLEHR( coordinates=(detector.coordinates[0], detector.coordinates[1], detector.size[2] + 0.5), size=detector.size[:2] ) space.add_subject(collimator) source = efg3( coordinates=phantom.coordinates, activity=300*10**6, ) materials = Materials(materials, max_energy=source.energy) materials.table = np.array([7, 7, 7, 10, 32, 82]) for angle in angles: phantom.rotate((0., angle, 0.)) source.rotate((0., angle, 0.)) modeling = Modeling( space, source, materials, stop_time=0.1, particles_number=10**6, flow_number=2, file_name=f'efg3_full_angle {round(angle*180/np.pi, 1)} deg.hdf',
def save(): filename = 'office_' + time.strftime('%Y-%m-%d_%H-%M-%S') + '.blend' bpy.ops.wm.save_as_mainfile(filepath=filename, check_existing=False, copy=True) print("Office saved as %s", filename) print("Now you can generate another environment again!\n") class Office: def __init__(self, ogF): self.officeGrammarFile = ogF self.officeGrammar = Grammar(self.officeGrammarFile) self.proceduralMachine = ProceduralGeometry( self.officeGrammar.roomsL, self.officeGrammar.roomsR, self.officeGrammar.noise, self.officeGrammar.meeting, self.officeGrammar.bathroom) def makeOffice(self, sub): officeGrammarStr = self.officeGrammar.deriveString(sub) self.proceduralMachine.generateGeometry(officeGrammarStr) #Procedurally generate office environment clearScene() #Remove everything Materials().generateNewMaterials() #Generate materials office = Office("grammar.grammar") #Set grammars office.makeOffice( 4) #Start generating office with n (from 1 to 4) levels of detail save() #saves result in a new blend file
def __init__(self, input): # Store input parameters and check them self.input = input self.input.checkInputs() # Define geometry based on geometry input type if input.geometry == 'slab': self.geo = SlabGeometry(self) elif input.geometry == 'cylindrical': self.geo = CylindricalGeometry(self) else: self.geo = SphericalGeometry(self) # Initialize material handler now that geometry is initialized self.mat = Materials(self) # Initialize field variables self.fields = Fields(self) # Time parameters self.timeSteps = [] self.time = 0. self.timeStep_num = 0 self.Tf = input.Tf # Initialize hydro problem self.hydro = LagrangianHydro(self) # Initialize radiation problem (if used) self.radPredictor = LagrangianRadiationPredictor(self) self.radCorrector = LagrangianRadiationCorrector(self) # Init storage for energies in conservation check self.kinetic_energy = [] self.internal_energy = [] self.radiation_energy = [] self.radiation_leakage = [] self.work_energy = [] self.total_energy = [] # Compute initial energies for each kinetic = 0 internal = 0 radiation = 0 for i in range(self.geo.N + 1): kinetic += 1 / 2 * self.mat.m_half[i] * self.fields.u_IC[i]**2 if i < self.geo.N: internal += self.mat.m[i] * self.fields.e_IC[i] radiation += self.mat.m[i] * self.fields.E_IC[ i] / self.fields.rho_IC[i] total = kinetic + internal + radiation self.kinetic_energy.append(kinetic) self.internal_energy.append(internal) self.radiation_energy.append(radiation) self.radiation_leakage.append(0) self.work_energy.append(0) self.total_energy.append(total) self.total_radiation_leakage = 0 self.total_work_energy = 0
class SaveTheCity: """Overall class to manage game assets and behavior.""" def __init__(self): """Initialize the game, and create game resources""" pygame.init() self.music = Music() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Save the City") self.statistics_image = pygame.image.load('resources/stats.png') # Reading the score from disk # d = shelve.open('resources/high_score') # score = d['saved_score'] # Create an instance to store game statistics- # -and create a scoreboard. self.stats = GameStats(self, 0) self.sb = Scoreboard(self) self.materials = Materials(self, self.settings.difficulty_level) self.worker = Worker(self) # Cooldown for collecting resources self.last = pygame.time.get_ticks() self.cooldown = 0 # List for obtained values self.obtained_list = [False, False, False, False, False] # Make the play button self.play_button = Button(self, "Play") self.show = None def run_game(self): """Start the main loop for the game.""" while True: self._check_events() if self.stats.game_active: self.worker.update() self.music.start_music() else: self.music.stop_music() self._update_screen() def _check_events(self): """Respond to keypress and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: # d = shelve.open('resources/high_score') # d['saved_score'] = self.stats.high_score # d.close() sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == self.materials.LENGTH_EVENT: if self.stats.game_active: # Only updates if the game is active self.materials.update() elif event.type == self.materials.DIFFICULTY_EVENT: if self.stats.game_active: self.materials.increase_difficulty() elif event.type == self.settings.POINT_EVENT: if self.stats.game_active: self.settings.increase_speed() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._check_play_button(mouse_pos) def _check_play_button(self, mouse_pos): """Start a new game when the player clicks play.""" button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: # Reset the game settings. # self.settings.initialize_dynamic_settings() # Reset the game statistics. self.stats.reset_stats() self.sb.prep_score() self.sb.prep_level() self.materials.reset_difficulty() self.materials.reset_lengths() self.stats.game_active = True # Hide the mouse cursor pygame.mouse.set_visible(False) def _start_game(self): """Start a new game after the player hits the p key""" # Reset the game statistics. if not self.stats.game_active: self.stats.reset_stats() self.materials.reset_lengths() self.stats.game_active = True # Hide the mouse cursor pygame.mouse.set_visible(False) def _check_keydown_events(self, event): if event.key == pygame.K_RIGHT: self.worker.moving_right = True if event.key == pygame.K_LEFT: self.worker.moving_left = True if event.key == pygame.K_UP: self.worker.moving_up = True if event.key == pygame.K_DOWN: self.worker.moving_down = True if event.key == pygame.K_q: sys.exit() if event.key == pygame.K_p: self._start_game() if event.key == pygame.K_h: self.show = True def _check_keyup_events(self, event): if event.key == pygame.K_RIGHT: self.worker.moving_right = False if event.key == pygame.K_LEFT: self.worker.moving_left = False if event.key == pygame.K_UP: self.worker.moving_up = False if event.key == pygame.K_DOWN: self.worker.moving_down = False if event.key == pygame.K_h: self.show = False def _check_health(self): """Checks to see if any lengths are 0, and checks if the workers health is 0""" if min(self.materials.lengths) <= 0: for i in range(0, len(self.materials.lengths)): self.materials.lengths[i] = 0 self.stats.game_active = False pygame.mouse.set_visible(True) def _update_screen(self): """Update images on the screen, and flip to the new screen.""" self.screen.blit(self.settings.background, (0, 0)) # Blit static images self.materials.blit_static() self._check_collision() self._check_resource() self.materials.blit_rects() self.worker.blitme() self._check_health() self.sb.level_update() # Draw the score and level information: self.sb.display_static_text() self.sb.show_score() if self.show: self.screen.blit(self.statistics_image, (380, 220)) # Draw the play button if the game is inactive. if not self.stats.game_active: self.play_button.draw_button() pygame.display.flip() def _check_collision(self): """Check for a collision between the player and the resource blocks and give the resource to the player""" now = pygame.time.get_ticks() if now - self.last >= self.cooldown: self.last = now if not (any(self.obtained_list)): if self.worker.rect.colliderect(WATER_RECT): self.obtained_list[0] = True self.music.pop_sound_effect() if self.worker.rect.colliderect(FOOD_RECT): self.obtained_list[1] = True self.music.pop_sound_effect() if self.worker.rect.colliderect(PRODUCT_RECT): self.obtained_list[2] = True self.music.pop_sound_effect() if self.worker.rect.colliderect(MEDICINE_RECT): self.obtained_list[3] = True self.music.pop_sound_effect() if self.worker.rect.colliderect(GEAR_RECT): self.obtained_list[4] = True self.music.pop_sound_effect() def _check_resource(self): """Check to see if the player is touching the block, and if he has a resource""" if RESIDENTIAL_RECT.contains(self.worker.rect): if self.obtained_list[0]: self.obtained_list[0] = False self.music.thunk_sound_effect() if self.materials.lengths[0] <= 270: self.materials.lengths[0] += 50 else: self.materials.lengths[0] = 320 self.stats.score += self.settings.points_list[0] self.sb.prep_score() self.sb.check_high_score() if self.obtained_list[1]: self.obtained_list[1] = False self.music.thunk_sound_effect() if self.materials.lengths[1] <= 270: self.materials.lengths[1] += 50 else: self.materials.lengths[1] = 320 self.stats.score += self.settings.points_list[1] self.sb.prep_score() self.sb.check_high_score() if self.obtained_list[2]: self.obtained_list[2] = False self.music.thunk_sound_effect() if self.materials.lengths[2] <= 270: self.materials.lengths[2] += 50 else: self.materials.lengths[2] = 320 self.stats.score += self.settings.points_list[2] self.sb.prep_score() self.sb.check_high_score() if self.obtained_list[3]: self.obtained_list[3] = False self.music.thunk_sound_effect() if self.materials.lengths[3] <= 270: self.materials.lengths[3] += 50 else: self.materials.lengths[3] = 320 self.stats.score += self.settings.points_list[3] self.sb.prep_score() self.sb.check_high_score() if self.obtained_list[4]: self.obtained_list[4] = False self.music.thunk_sound_effect() if self.materials.lengths[4] <= 270: self.materials.lengths[4] += 50 else: self.materials.lengths[4] = 320 self.stats.score += self.settings.points_list[4] self.sb.prep_score() self.sb.check_high_score()
def create_evaluable(self, expression, try_equations=True, auto_init=False, preserve_caches=False, copy_materials=True, integrals=None, ebcs=None, epbcs=None, lcbcs=None, ts=None, functions=None, mode='eval', var_dict=None, strip_variables=True, extra_args=None, verbose=True, **kwargs): """ Create evaluable object (equations and corresponding variables) from the `expression` string. Convenience function calling :func:`create_evaluable() <sfepy.discrete.evaluate.create_evaluable()>` with defaults provided by the Problem instance `self`. The evaluable can be repeatedly evaluated by calling :func:`eval_equations() <sfepy.discrete.evaluate.eval_equations()>`, e.g. for different values of variables. Parameters ---------- expression : str The expression to evaluate. try_equations : bool Try to get variables from `self.equations`. If this fails, variables can either be provided in `var_dict`, as keyword arguments, or are created automatically according to the expression. auto_init : bool Set values of all variables to all zeros. preserve_caches : bool If True, do not invalidate evaluate caches of variables. copy_materials : bool Work with a copy of `self.equations.materials` instead of reusing them. Safe but can be slow. integrals : Integrals instance, optional The integrals to be used. Automatically created as needed if not given. ebcs : Conditions instance, optional The essential (Dirichlet) boundary conditions for 'weak' mode. If not given, `self.ebcs` are used. epbcs : Conditions instance, optional The periodic boundary conditions for 'weak' mode. If not given, `self.epbcs` are used. lcbcs : Conditions instance, optional The linear combination boundary conditions for 'weak' mode. If not given, `self.lcbcs` are used. ts : TimeStepper instance, optional The time stepper. If not given, `self.ts` is used. functions : Functions instance, optional The user functions for boundary conditions, materials etc. If not given, `self.functions` are used. mode : one of 'eval', 'el_avg', 'qp', 'weak' The evaluation mode - 'weak' means the finite element assembling, 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. var_dict : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. Use this if the name of a variable conflicts with one of the parameters of this method. strip_variables : bool If False, the variables in `var_dict` or `kwargs` not present in the expression are added to the actual variables as a context. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. **kwargs : keyword arguments Additional variables can be passed as keyword arguments, see `var_dict`. Returns ------- equations : Equations instance The equations that can be evaluated. variables : Variables instance The corresponding variables. Set their values and use :func:`eval_equations() <sfepy.discrete.evaluate.eval_equations()>`. Examples -------- `problem` is Problem instance. >>> out = problem.create_evaluable('dq_state_in_volume_qp.i1.Omega(u)') >>> equations, variables = out `vec` is a vector of coefficients compatible with the field of 'u' - let's use all ones. >>> vec = nm.ones((variables['u'].n_dof,), dtype=nm.float64) >>> variables['u'].set_data(vec) >>> vec_qp = eval_equations(equations, variables, mode='qp') Try another vector: >>> vec = 3 * nm.ones((variables['u'].n_dof,), dtype=nm.float64) >>> variables['u'].set_data(vec) >>> vec_qp = eval_equations(equations, variables, mode='qp') """ from sfepy.discrete.equations import get_expression_arg_names variables = get_default(var_dict, {}) var_context = get_default(var_dict, {}) if try_equations and self.equations is not None: # Make a copy, so that possible variable caches are preserved. for key, var in self.equations.variables.as_dict().iteritems(): if key in variables: continue var = var.copy(name=key) if not preserve_caches: var.clear_evaluate_cache() variables[key] = var elif var_dict is None: possible_var_names = get_expression_arg_names(expression) variables = self.create_variables(possible_var_names) materials = self.get_materials() if materials is not None: if copy_materials: materials = materials.semideep_copy() else: materials = Materials(objs=materials._objs) else: possible_mat_names = get_expression_arg_names(expression) materials = self.create_materials(possible_mat_names) _kwargs = copy(kwargs) for key, val in kwargs.iteritems(): if isinstance(val, Variable): if val.name != key: msg = 'inconsistent variable name! (%s == %s)' \ % (val.name, key) raise ValueError(msg) var_context[key] = variables[key] = val.copy(name=key) _kwargs.pop(key) elif isinstance(val, Material): if val.name != key: msg = 'inconsistent material name! (%s == %s)' \ % (val.name, key) raise ValueError(msg) materials[val.name] = val _kwargs.pop(key) kwargs = _kwargs ebcs = get_default(ebcs, self.ebcs) epbcs = get_default(epbcs, self.epbcs) lcbcs = get_default(lcbcs, self.lcbcs) ts = get_default(ts, self.get_timestepper()) functions = get_default(functions, self.functions) integrals = get_default(integrals, self.get_integrals()) out = create_evaluable(expression, self.fields, materials, variables.itervalues(), integrals, ebcs=ebcs, epbcs=epbcs, lcbcs=lcbcs, ts=ts, functions=functions, auto_init=auto_init, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) if not strip_variables: variables = out[1] variables.extend([var for var in var_context.itervalues() if var not in variables]) equations = out[0] mode = 'update' if not copy_materials else 'normal' equations.time_update_materials(self.ts, mode=mode, problem=self, verbose=verbose) return out
def main(): angles = np.linspace(-np.pi/4, 3*np.pi/4, 32) projection_time = 15 pause_time = 1. materials = { 'Compounds and mixtures/Air, Dry (near sea level)': 0, 'Compounds and mixtures/Lung': 1, 'Compounds and mixtures/Tissue, Soft (ICRU-44)': 2, 'Compounds and mixtures/B-100 Bone-Equivalent Plastic': 3, 'Compounds and mixtures/Sodium Iodide': 4, 'Elemental media/Pb': 5, } space = Space( size=(51.2, 40., 60.), material=0 ) detector = SiemensSymbiaTSeries3_8( coordinates=(0., 0., 0), size=space.size[:2] ) collimator = SiemensSymbiaTSeriesLEHR( coordinates=(detector.coordinates[0], detector.coordinates[1], detector.size[2] + 0.5), size=detector.size[:2] ) phantom = ae3cut( coordinates=(collimator.coordinates[0], collimator.coordinates[1], collimator.size[2]), ) source = SourceManager().efg3cut( coordinates=phantom.coordinates, activity=300*10**6, ) space.add_subject(phantom) space.add_subject(detector) space.add_subject(collimator) materials = Materials(materials, max_energy=source.energy) materials.table = np.array([7, 7, 7, 10, 32, 82]) for angle in angles: phantom.rotate((0., angle, 0.)) source.rotate((0., angle, 0.)) modeling = Modeling( space, source, materials, stop_time=source.timer + projection_time, particles_number=10**8, flow_number=8, file_name=f'efg3cut/{round(np.rad2deg(angle), 1)} deg.hdf', iteraction_buffer=10**4, subject=detector ) modeling.start() modeling.join() source.set_state(source.timer + pause_time)
def lose_materials(self, material): losed = {} m = material.materials_list() k = random.randint(1, 3) names = random.choices(m, k=k) for i in names: amount = random.randrange(-50, -1) losed[i] = amount # zmienic morale return losed def injure_person(self, person, injure_kind): # zmienic morale pass if __name__ == '__main__': from materials import Materials m = Materials() e = Event() znaleziono = e.found_materials(m) print(znaleziono) m.materials_change(znaleziono) print(m.materials_status()) stracono = e.lose_materials(m) print(stracono) m.materials_change(stracono) print(m.materials_status())