def test_remote_client(): # Receivers room_light = light.Light('room') garage_light = light.Light('garage') garage_door = door.Door('garage', garage_light) # Commands room_light_on = light.LightOn(room_light) room_light_off = light.LightOff(room_light) garage_door_open = door.DoorOpen(garage_door) garage_door_close = door.DoorClose(garage_door) party_on = MacroCommand([room_light_on, garage_door_open]) party_off = MacroCommand([room_light_off, garage_door_close]) # Invoker capacity = 4 remote = Remote(capacity) remote.set_command(0, room_light_on, room_light_off) remote.set_command(1, garage_door_open, garage_door_close) remote.set_command(2, party_on, party_off) # Execute for i in range(capacity): print(f'\nbutton number #{i}') remote.on_button_was_pushed(i) remote.off_button_was_pushed(i) remote.undo()
def __init__(self): self.object = bpy.data.scenes['Scene'].render self.camera = cam.Camera(self.object) self.cutter = ctt.Cutter() self.light1 = lt.Light('area_light_1') self.light2 = lt.Light('area_light_2')
def __init__(self): for i in range(1, 1 + max(self.no_tube, self.no_bulb, self.no_night)): if (i <= self.no_tube): self.tubes['tube' + str(i)] = lt.Light(8, 130) if (i <= self.no_bulb): self.bulbs['bulb' + str(i)] = lt.Light(5, 80) if (i <= self.no_night): self.nights['night' + str(i)] = lt.Light(1, 10) #self.fig = plt.figure() #self.ax1 = self.fig.add_subplot(1,1,1) #initialize graph '''plt.ion() #turn on interactive mode
def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.light = light.Light() self.lightDisplay.setText(self.light.show()) self.lightSwitch.released.connect(self.toggle)
def __init__(self, width, height): pygame.init() if (width == 0 or height == 0): self.canvas = pygame.display \ .set_mode( (width, height), pygame.NOFRAME | pygame.FULLSCREEN) else: self.canvas = pygame.display.set_mode((width, height), pygame.SRCALPHA) self.canvas.fill((40, 40, 40, 0)) # Sets the width and height screen_details = pygame.display.Info() self.width = screen_details.current_w self.height = screen_details.current_h self.yaw, self.pitch = 0, 0 pygame.mouse.set_visible(False) self.engine = engine.Engine(self.canvas) self.engine.load_model("teapot.obj", "teapot") directional_light_kwargs = { 'color': (255, 0, 0), 'direction': [0, 0, -1], 'intensity': 0.9, 'type': 'directional' } directional_light = light.Light(**directional_light_kwargs) self.engine.load_light(directional_light, identifier="directional_light") ambient_light_kwargs = { 'color': (255, 255, 255), 'intensity': 0.2, 'type': 'ambient' } ambient_light = light.Light(**ambient_light_kwargs) self.engine.load_light(ambient_light, identifier="ambient_light") specular_light_kwargs = { 'color': (255, 255, 255), 'intensity': 0.5, 'type': 'specular', 'direction': [0, 0, -1], 'strength': 32 } specular_light = light.Light(**specular_light_kwargs) self.engine.load_light(specular_light, identifier="specular_light")
def __init__(self, width, height): self.width = width self.height = height self.walls = walls.Walls(self.width, self.height) self.door = door.Door(0.10 * self.width, 20 * self.height, self.width / 7, self.height / 5, 112, 95, 54) #self.tv = tv.TV() self.light = light.Light(0.75 * self.width, 0.66 * self.height, (1. / 8.) * self.height) return
def __init__(self, floor, x, y): animations = { 'run': ('sprites/scientist/run', 4, 0.25), 'idle': ('sprites/scientist/idle', 4, 1) } default_animation = 'idle' sounds = {} Entity.__init__(self, floor, False, animations, default_animation, sounds, 48, 48, x, y, 21, (200, 64, 255, 255)) self.max_orb_power = 10000.0 self.orb_power = 10000.0 self.sprite.opacity = 180 self.light = light.Light(self.floor, 100, 64, self.orb_power, self.x, self.y)
def slave_index(self, message): """ return the index of the slave in self.slaves If the a slave is not found a new one is created with his state list(int) : message send by the slave """ id_slave = message[1] i = self._slave_index(id_slave) if i == -1: print("création du slave {}".format(id_slave)) self.slaves.append(light.Light(id_slave)) #must be from a presence or a pairing message if message[2] == usartcomm.PRESENCE: self.slaves[i].status = message[3] self.slaves[i].power = message[4] elif message[2] == usartcomm.DEMAND_PAIRING: self.slaves[i].status = 2 else: print("Message not conform, Light not initilised") return i
def lightswitch(request, action): s7conn = getS7Conn() if action == "all_off": if not light.AllOff(s7conn): raise Http404 return HttpResponse() idInt = 0 try: idInt = int(request.REQUEST["id"]) except: raise Http404 l = light.Light("", idInt, s7conn) if action == "toggle": print("Light %d toggled by %s" % (l.getID(), request.META.get('REMOTE_ADDR'))) if not l.toggleLight(): raise Http404 elif action == "toggle_motion": if not l.toggleMotion(): raise Http404 elif action == "toggle_blink": if not l.toggleBlinkOnAlarm(): raise Http404 elif action == "timeout": timeout = 0 try: timeout = int(request.REQUEST["timeout"]) except: raise Http404 l.setTimeout(timeout) else: raise Http404 return HttpResponse()
#!/usr/bin/python import RPi.GPIO as GPIO import importlib, time import light # sudo python /home/Gclightshow/dev/lightshowLoop.py & importlib.import_module("light") GPIO.cleanup() #set GPIO as the numbers of pins GPIO.setmode(GPIO.BOARD) #set up pins pinList = [11, 12, 13, 15, 16, 18, 22, 7] for i in pinList: GPIO.setup(i, GPIO.OUT) GPIO.output(i, True) light1 = light.Light(pinList[0], "1") light2 = light.Light(pinList[1], "2") light3 = light.Light(pinList[7], "3") light4 = light.Light(pinList[6], "4") light5 = light.Light(pinList[5], "5") light6 = light.Light(pinList[4], "6") light7 = light.Light(pinList[3], "7") light8 = light.Light(pinList[2], "8") #set up pin array lightTa = [light3, light4, light5, light6, light7, light8] #create light show array object with correct GPIO out pins lightShow1 = light.LightShow(1, lightTa, [1, 1, 1, .5, .25]) try: for x in range(0, 1000): lightShow1.gcBlink() time.sleep(2)
clip_far=10000.0, resolution=resolution) mat_grey = material.Material(diffuse_reflectance=torch.from_numpy( np.array([0.5, 0.5, 0.5], dtype=np.float32))) mat_black = material.Material(diffuse_reflectance=torch.from_numpy( np.array([0.0, 0.0, 0.0], dtype=np.float32))) materials = [mat_grey, mat_black] # plane_vertices, plane_indices=generate_plane([32, 32]) # shape_plane=shape.Shape(plane_vertices,plane_indices,None,None,0) indices, vertices, uvs, normals = load_obj.load_obj( 'results/heightfield_gan/model.obj') indices = Variable(torch.from_numpy(indices.astype(np.int64))) vertices = Variable(torch.from_numpy(vertices)) normals = compute_vertex_normal(vertices, indices) shape_plane = shape.Shape(vertices, indices, None, normals, 0) light_vertices=Variable(torch.from_numpy(\ np.array([[-0.1,50,-0.1],[-0.1,50,0.1],[0.1,50,-0.1],[0.1,50,0.1]],dtype=np.float32))) light_indices=torch.from_numpy(\ np.array([[0,2,1],[1,2,3]],dtype=np.int32)) shape_light = shape.Shape(light_vertices, light_indices, None, None, 1) shapes = [shape_plane, shape_light] light_intensity=torch.from_numpy(\ np.array([100000,100000,100000],dtype=np.float32)) light = light.Light(1, light_intensity) lights = [light] render = render_pytorch.RenderFunction.apply args = render_pytorch.RenderFunction.serialize_scene(\ cam,materials,shapes,lights,resolution,4,1) img = render(random.randint(0, 1048576), *args) image.imwrite(img.data.numpy(), 'results/heightfield_gan/test.exr')
np.array([[0, 1, 2], [1, 3, 2]], dtype=np.int32)) shape_green_reflector = shape.Shape(green_reflector_vertices, green_reflector_indices, None, None, 2) light_translation=Variable(torch.from_numpy(\ np.array([0.0,5.0,-2.0],dtype=np.float32)), requires_grad=True) light_rotation=Variable(torch.from_numpy(\ np.array([2.5,0.0,0.0], dtype=np.float32)), requires_grad=True) light_vertices=Variable(torch.from_numpy(\ np.array([[-0.1,0,-0.1],[-0.1,0,0.1],[0.1,0,-0.1],[0.1,0,0.1]],dtype=np.float32))) light_indices=torch.from_numpy(\ np.array([[0,2,1],[1,2,3]],dtype=np.int32)) shape_light = shape.Shape(light_vertices, light_indices, None, None, 3) shapes = [shape_floor, shape_red_reflector, shape_green_reflector, shape_light] light_intensity=torch.from_numpy(\ np.array([10000,10000,10000],dtype=np.float32)) light = light.Light(3, light_intensity) lights = [light] optimizer = torch.optim.Adam([light_rotation], lr=1e-2) for t in range(100): print('iteration:', t) print('light_rotation', light_rotation) light_rotation_matrix = transform.torch_rotate_matrix(light_rotation) shape_light.vertices = light_vertices @ torch.t( light_rotation_matrix) + light_translation args = render_pytorch.RenderFunction.serialize_scene( cam, materials, shapes, lights, resolution, 4, 32) # To apply our Function, we use Function.apply method. We alias this as 'render'. render = render_pytorch.RenderFunction.apply
np.array([[0, 1, 2], [1, 3, 2]], dtype=np.int32)) shape_floor = shape.Shape(floor_vertices, floor_indices, None, None, 0) blocker_vertices=Variable(torch.from_numpy(\ np.array([[-0.5,3.0,-0.5],[-0.5,3.0,0.5],[0.5,3.0,-0.5],[0.5,3.0,0.5]],dtype=np.float32))) blocker_indices = torch.from_numpy( np.array([[0, 1, 2], [1, 3, 2]], dtype=np.int32)) shape_blocker = shape.Shape(blocker_vertices, blocker_indices, None, None, 0) light_vertices=Variable(torch.from_numpy(\ np.array([[-0.1,5,-0.1],[-0.1,5,0.1],[0.1,5,-0.1],[0.1,5,0.1]],dtype=np.float32))) light_indices=torch.from_numpy(\ np.array([[0,2,1],[1,2,3]],dtype=np.int32)) shape_light = shape.Shape(light_vertices, light_indices, None, None, 1) shapes = [shape_floor, shape_blocker, shape_light] light_intensity=torch.from_numpy(\ np.array([1000,1000,1000],dtype=np.float32)) light = light.Light(2, light_intensity) lights = [light] args = render_pytorch.RenderFunction.serialize_scene(cam, materials, shapes, lights, resolution, 256, 1) render = render_pytorch.RenderFunction.apply img = render(0, *args) image.imwrite(img.data.numpy(), 'test/results/test_shadow/target.exr') image.imwrite(img.data.numpy(), 'test/results/test_shadow/target.png') target = Variable( torch.from_numpy(image.imread('test/results/test_shadow/target.exr'))) shape_blocker.vertices=Variable(torch.from_numpy(\ np.array([[-0.2,3.5,-0.8],[-0.8,3.0,0.3],[0.4,2.8,-0.8],[0.3,3.2,1.0]],dtype=np.float32)), requires_grad=True) args = render_pytorch.RenderFunction.serialize_scene(cam, materials, shapes,
def __init__(self, title, ok_text, ranking, results=False, choosevessel=False): refresh_ranking() # light_pos = V3(0, 1000, -1000) light_m = V3(20, 20, 20) light_M = V3(200, 200, 200) self.light = light.Light(light_pos, light_m, light_M) self.viewport = pygame.Surface((400, int(parameters.H * 0.6))) self.viewport_color = (200, 200, 200) self.viewport.fill(self.viewport_color) self.viewport_rect = pygame.Rect((0, 0), self.viewport.get_size()) self.viewport_rect.centerx = parameters.W // 2 + 100 self.viewport_rect.centery = parameters.H // 2 self.cam = camera.Camera(self.viewport, fov=512, d=2, objs=[]) self.screen = thorpy.get_screen() self.displayed_vessel = None self.i = 0 # if results: ranking[0].points += 1 ranking[0].money += 300 + (parameters.NPLAYERS - ranking[0].ranking) * 100 ranking[2].points -= 1 ranking[2].money += 100 ranking[1].money += 200 if ranking[2].points < 0: ranking[2].points = 0 # self.trophy = None if choosevessel: self.e_players = [] def other_vessel(): self.vessels[0] = create_vessel(parameters.HERO_COLOR) self.vessels[0].set_pos(V3(0, -1 * 4.5, 20)) self.vessels[0].move(V3(0, 4, 0)) self.displayed_vessel = self.vessels[0] #replace self.ve new_ve = get_vessel_element(self.vessels[0]) self.e_bckgr.replace_element(self.ve, new_ve) thorpy.functions.refresh_current_menu() self.ve = new_ve self.e_bckgr.unblit_and_reblit() b = thorpy.make_button("Generate another vessel", other_vessel) c = thorpy.make_button("Done", thorpy.functions.quit_menu_func) self.e_players.append(b) self.e_players.append(c) from main import create_vessel self.vessels = [create_vessel(parameters.HERO_COLOR)] self.displayed_vessel = self.vessels[0].get_copy() self.ve = get_vessel_element(self.vessels[0]) self.e_players.append(self.ve) else: if results: self.e_players = [ p.get_element(str(i + 1) + ") ") for i, p in enumerate(ranking) ] else: self.e_players = [ p.get_element() for i, p in enumerate(ranking) ] self.vessels = [p.vessel.get_copy() for p in ranking] if results: import core3d from light import Material self.trophy = core3d.Object3D("trophy1.stl") self.trophy.set_color(Material((255, 215, 0))) ## self.trophy.set_color((255,255,0)) self.trophy.set_pos(V3(5., -0 * 4.5 - 0.2, 15)) self.trophy.rotate_around_center_z(90.) self.trophy.rotate_around_center_x(-65.) self.trophy.move(V3(0, 4, 0)) self.background = thorpy.load_image("background1.jpg") self.background = thorpy.get_resized_image( self.background, (parameters.W, parameters.H // 2), type_=max) self.e_bckgr = thorpy.Background.make(image=self.background, elements=self.e_players) # vw, vh = self.viewport_rect.size self.e_viewport_frame = thorpy.Element() painter = thorpy.painterstyle.ClassicFrame((vw + 3, vh + 3), color=self.viewport_color, pressed=True) self.e_viewport_frame.set_painter(painter) self.e_viewport_frame.finish() self.e_viewport_frame.set_center(self.viewport_rect.center) # reaction = thorpy.ConstantReaction(thorpy.THORPY_EVENT, self.refresh_display, {"id": thorpy.constants.EVENT_TIME}) self.e_bckgr.add_reaction(reaction) if not choosevessel: for i, v in enumerate(self.vessels): pos = self.e_players[i].get_fus_rect().center v.set_pos(V3(0, -i * 4.5, 20)) v.move(V3(0, 4, 0)) else: self.vessels[0].set_pos(V3(0, -1 * 4.5, 20)) self.vessels[0].move(V3(0, 4, 0)) # self.displayed_vessel.set_pos(V3(0, -1 * 4.5, 20)) self.displayed_vessel.move(V3(0, 4, 0)) # thorpy.store(self.e_bckgr, gap=40) for e in self.e_players: e.stick_to(self.viewport_rect, "left", "right", align=False) e.move((-5, 0)) self.e_title = get_etitle(title) if not choosevessel: self.e_ok = get_eok(ok_text) self.e_bckgr.add_elements( [self.e_viewport_frame, self.e_title, self.e_ok]) else: self.e_bckgr.add_elements([self.e_viewport_frame, self.e_title]) self.goback = False def return_garage(): self.derotate() self.goback = True thorpy.functions.quit_menu_func() if not results and not choosevessel: self.e_back = thorpy.make_button("Return to garage", return_garage) self.e_back.stick_to(self.e_ok, "left", "right") self.e_back.move((-20, 0)) self.e_bckgr.add_elements([self.e_back]) if not results: reaction = thorpy.Reaction(pygame.MOUSEMOTION, self.mousemotion) self.e_bckgr.add_reaction(reaction) m = thorpy.Menu(self.e_bckgr) m.play()
def __init__(self): ## if not parameters.canonic_vessels: ## get_all_parts() self.vessel = parameters.player.vessel.get_copy() self.ovessel = parameters.player.vessel self.screen = thorpy.get_screen() # light_pos = V3(0,1000,-1000) light_m = V3(20,20,20) light_M = V3(200,200,200) self.light = light.Light(light_pos, light_m, light_M) # self.e_bckgr = thorpy.Background.make((255,255,255)) self.vessel.set_pos(parameters.GARAGE_POS) reaction = thorpy.ConstantReaction(thorpy.THORPY_EVENT, self.refresh_display, {"id":thorpy.constants.EVENT_TIME}) self.e_bckgr.add_reaction(reaction) reaction = thorpy.Reaction(pygame.MOUSEMOTION, self.mousemotion) self.e_bckgr.add_reaction(reaction) # self.viewport = pygame.Surface((400,400)) self.viewport_color = (200,200,200) self.viewport_rect = pygame.Rect((0,0),self.viewport.get_size()) self.viewport_rect.right = parameters.W - 20 self.viewport_rect.centery = parameters.H//2 self.cam = camera.Camera(self.viewport, fov=512, d=2, objs=[]) # # # self.e_ok = thorpy.make_button("Go to next race", func=thorpy.functions.quit_menu_func) self.e_ok.set_main_color((0,255,0)) self.e_ok.set_font_size(thorpy.style.FONT_SIZE+3) self.e_ok.scale_to_title() # # def refresh_repair(): damages = str(round(100.*(1. - self.ovessel.life/self.ovessel.max_life))) self.e_damage.set_text("Vessel damages: " + damages + "%") self.e_money.set_text("Money: "+str(parameters.player.money)+" $") def choice_repair(): cost = (self.ovessel.max_life - self.ovessel.life)*300 if cost <= parameters.player.money: if thorpy.launch_binary_choice("Are you sure? This will cost "+\ str(cost)+"$"): self.ovessel.life = self.ovessel.max_life parameters.player.money -= cost refresh_repair() elif thorpy.launch_binary_choice("Repairing costs "+str(cost)+\ " $. You don't have enough money.\n"+\ "Do you want to use all your money for"+\ " repairing as much as possible?"): #(after_repair - self.ovessel.life)*300 = money #==> after_repair = money/300 + self.ovessel.life repaired = int(parameters.player.money/300. + self.ovessel.life) parameters.player.money -= (repaired - self.ovessel.life)*300 self.ovessel.life = repaired refresh_repair() self.e_bckgr.blit() self.refresh_display() pygame.display.flip() self.e_repair = thorpy.make_button("Repair vessel",choice_repair) # damages = str(round(100.*(1. - self.ovessel.life/self.ovessel.max_life))) self.e_damage = thorpy.make_text("Vessel damages: " + damages + "%") self.e_ranking = thorpy.make_button("See rankings", launch_rankings, {"garage":self}) ## self.e_ranking = get_rankings_box() def quit_forever(): if thorpy.launch_binary_choice("Are you sure ?"): thorpy.functions.quit_func() else: self.e_bckgr.unblit_and_reblit() self.e_menu = thorpy.make_button("Stop career and die (forever)", func=quit_forever) self.e_menu.set_main_color((255,0,0)) self.e_menu.set_font_size(thorpy.style.FONT_SIZE-2) self.e_menu.scale_to_title() # vw,vh = self.viewport_rect.size self.e_viewport_frame = thorpy.Element() painter = thorpy.painterstyle.ClassicFrame((vw+3,vh+3), color=self.viewport_color, pressed=True) self.e_viewport_frame.set_painter(painter) self.e_viewport_frame.finish() self.e_viewport_frame.set_center(self.viewport_rect.center) # import hud fuel = str(round(100*self.ovessel.engine.fuel/self.ovessel.engine.max_fuel)) self.e_fuel = hud.LifeBar("Fuel: "+fuel+" %",text_color=(255,0,0),size=(100,30)) self.e_fuel.set_life(self.ovessel.engine.fuel/self.ovessel.engine.max_fuel) def refresh_refuel(): life = self.ovessel.engine.fuel / self.ovessel.engine.max_fuel self.e_fuel.set_life(life) self.e_fuel.set_text("Fuel: "+str(round(life*100))+" %") self.e_money.set_text("Money: "+str(parameters.player.money)+" $") def choice_refuel(): cost = (self.ovessel.engine.max_fuel - self.ovessel.engine.fuel)//2 if cost <= parameters.player.money: if thorpy.launch_binary_choice("Are you sure? This will cost "+\ str(cost)+"$"): self.ovessel.engine.fuel = self.ovessel.engine.max_fuel parameters.player.money -= cost refresh_refuel() ## self.e_fuel.set_life(1.) ## self.e_fuel.set_life_text("Fuel: 100 %") ## parameters.player.money -= cost ## self.e_money.set_text("Money: "+str(parameters.player.money)+" $") ## self.ovessel.engine.fuel = self.ovessel.engine.max_fuel elif thorpy.launch_binary_choice("Refueling costs "+str(cost)+" $. You don't have enough money.\n"+\ "Do you want to spend all your money to refuel as much as possible?"): #cost = (newfuel - fuel)//2 ==> 2*cost + fuel = newfuel self.ovessel.engine.fuel += 2*parameters.player.money parameters.player.money = 0 refresh_refuel() ## thorpy.launch_blocking_alert("Refueling costs "+str(cost)+" $. You don't have enough money.") self.e_bckgr.blit() self.refresh_display() pygame.display.flip() self.e_refuel = thorpy.make_button("Refuel",choice_refuel) self.e_money = thorpy.make_text("Money: "+str(parameters.player.money)+" $", thorpy.style.TITLE_FONT_SIZE,(255,0,0)) self.e_money.stick_to("screen","top","top") self.e_money.move((0,30)) # self.e_box = thorpy.Box.make([self.e_damage,self.e_repair, thorpy.Line.make(100,"h"),self.e_fuel, self.e_refuel, thorpy.Line.make(100,"h"), self.e_ranking,self.e_ok]) self.e_bckgr.add_elements([self.e_box,self.e_menu]) thorpy.store(self.e_bckgr, x = 200) self.e_skills = get_vessel_element(parameters.player.vessel) self.e_bckgr.add_elements([self.e_viewport_frame,self.e_money, self.e_skills]) self.e_menu.move((0,30)) self.e_skills.stick_to(self.e_viewport_frame, "left", "right") self.i = 0
def show_position(self): print('Blyat') class TestApp(App): def build(self): Builder.load_file("intro.kv") return Intro() if __name__ == '__main__': Trace = [] BMW = car.MyCar(0) JP2 = light.Light(10, 5, (200, 30), 'Jp2') Trace.append(JP2) Smikolaja = light.Light(15, 10, (400, 30), "SM") Trace.append(Smikolaja) Trace[0].start() Trace[1].start() TestApp().run() #TestApp.show_time(Trace[0]) #print('trace0', Trace[0].green_time, Trace[0].red_time) #print('trace1', Trace[1].green_time, Trace[1].red_time) #os.system('cls') #BMW.pass_lights(Trace[0])
# server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') detectors_tree = load_xml_file(options.detFile) opt_tree = load_xml_file(options.goalFile) program_tree = load_xml_file(options.phasesFile) lights_2_opt = [] id_controllers = [] i = 0 for light_opt in options.lights: obj = light.Light(light_opt, detectors_tree, opt_tree, program_tree) lights_2_opt.append(obj) if options.executionType < 3: id_controllers.append(options.executionType) else: id_controllers.append(i) i += 1 test = lightConfig.LightConfig(lights_2_opt, id_controllers) for test_light in lights_2_opt: test_light.control.print_version() # this is the normal way of using traci. sumo is started as a # subprocess and then the python script connects and runs sumoProcess = subprocess.Popen([
def parse_shape(node, material_dict, shape_id): if node.attrib['type'] == 'obj' or node.attrib['type'] == 'serialized': to_world = np.identity(4, dtype=np.float32) serialized_shape_id = 0 mat_id = -1 light_intensity = None filename = '' for child in node: if 'name' in child.attrib: if child.attrib['name'] == 'filename': filename = child.attrib['value'] elif child.attrib['name'] == 'toWorld': to_world = parse_transform(child) elif child.attrib['name'] == 'shapeIndex': serialized_shape_id = int(child.attrib['value']) if child.tag == 'ref': mat_id = material_dict[child.attrib['id']] elif child.tag == 'emitter': for grandchild in child: if grandchild.attrib['name'] == 'radiance': light_intensity = parse_vector( grandchild.attrib['value']) if light_intensity.shape[0] == 1: light_intensity = np.array([ light_intensity[0], light_intensity[0], light_intensity[0] ], dtype=np.float32) light_intensity = Variable( torch.from_numpy(light_intensity)) if node.attrib['type'] == 'obj': indices, vertices, uvs, normals = load_obj.load_obj(filename) else: assert (node.attrib['type'] == 'serialized') indices, vertices, uvs, normals = \ load_serialized.load_serialized(filename, serialized_shape_id) if uvs.shape[0] == 0: uvs = None if normals.shape[0] == 0: normals = None # Transform the vertices and normals vertices = \ np.concatenate(\ (vertices, np.ones((vertices.shape[0], 1), dtype=np.float32)), 1) vertices = vertices @ np.transpose(to_world) vertices = vertices / vertices[:, 3:4] vertices = vertices[:, 0:3] if normals is not None: normals = normals @ (np.linalg.inv(np.transpose(to_world))[:3, :3]) assert (vertices is not None) assert (indices is not None) lgt = None if light_intensity is not None: lgt = light.Light(shape_id, light_intensity) vertices = Variable(torch.from_numpy(vertices)) indices = Variable(torch.from_numpy(indices)) if uvs is not None: uvs = Variable(torch.from_numpy(uvs)) if normals is not None: normals = Variable(torch.from_numpy(normals)) return shape.Shape(vertices, indices, uvs, normals, mat_id), lgt elif node.attrib['type'] == 'rectangle': indices = np.array([[0, 2, 1], [1, 2, 3]]) vertices = np.array([[-1, -1, 0], [-1, 1, 0], [1, -1, 0], [1, 1, 0]], dtype=np.float32) uvs = None normals = None to_world = np.identity(4, dtype=np.float32) mat_id = -1 light_intensity = None for child in node: if 'name' in child.attrib: if child.attrib['name'] == 'toWorld': to_world = parse_transform(child) if child.tag == 'ref': mat_id = material_dict[child.attrib['id']] elif child.tag == 'emitter': for grandchild in child: if grandchild.attrib['name'] == 'radiance': light_intensity = parse_vector( grandchild.attrib['value']) if light_intensity.shape[0] == 1: light_intensity = np.array([ light_intensity[0], light_intensity[0], light_intensity[0] ], dtype=np.float32) light_intensity = Variable( torch.from_numpy(light_intensity)) # Transform the vertices vertices = \ np.concatenate(\ (vertices, np.ones((vertices.shape[0], 1), dtype=np.float32)), 1) vertices = vertices @ np.transpose(to_world) vertices = vertices / vertices[:, 3:4] vertices = vertices[:, 0:3] if normals is not None: normals = normals @ (np.linalg.inv(np.transpose(to_world))[:3, :3]) assert (vertices is not None) assert (indices is not None) lgt = None if light_intensity is not None: lgt = light.Light(shape_id, light_intensity) vertices = Variable(torch.from_numpy(vertices)) indices = Variable(torch.from_numpy(indices)) if uvs is not None: uvs = Variable(torch.from_numpy(uvs)) if normals is not None: normals = Variable(torch.from_numpy(normals)) return shape.Shape(vertices, indices, uvs, normals, mat_id), lgt else: assert (False)
import light light_obj = light.Light(7, "output") light_obj.high()
* Website : www.magice.co * Update : Sangyun.Kwon 2019-03-24 New release ********************************************************************** ''' from django.shortcuts import render_to_response #from driver import stream from django.http import HttpResponse import os from remote_control.driver import camera, esc_1060, stream import pickle import light import ts import threading li = light.Light() import httplib, urllib import time import smbus bus = smbus.SMBus(1) global dat dat = 0x48 key = 'NKP3ZABMT8W2YD8O' global flag flag = True def thermometer(): global flag while True:
'%(asctime)s %(filename)s->%(funcName)s():%(lineno)d %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=config.log_level, # filename="log.txt" ) #################################################################### # Code # #################################################################### logging.info("Starting configuration") ## LEDs Configuration strip = init_leds_strip() strip.begin() disp = display.Screen(strip) top_light = light.Light(strip, top_offset=29) ## Buttons configuration register_buttons(top_light, disp) logging.info("Installing handlers") signal.signal(signal.SIGTERM, exit_handler) signal.signal(signal.SIGINT, exit_handler) config.scheduler = Scheduler() # Starting boot routine config.scheduler.set_screen_thread( DisplayScrollingMessage(screen=disp, message="BOOOOOOOE", duration=2)) config.scheduler.set_light_thread(Loading(top_light)) time.sleep(1)
class ICan: """ Main class of the iCan application that packages the high level logic of the device. Public Methods: checkOrientation() """ # SENSORS lidSensor = lid.Lid() cameraSensor = camera.Camera('/tmp/trash.jpg') # ACTUATORS/OUTPUT lightOutput = light.Light(21) trapdoorOutput = trapdoor.Trapdoor() # CLOUD SERVICES AND APIs storageService = s3.S3() databaseService = database.ICanItems() weatherService = local_weather.LocalWeather() recognitionService = image_recognition.ImageRecognition() predictionService = prediction.Prediction() notificationService = notification.Notification() # How long to wait to be in "steady" state (seconds) WAIT_TIME = 3 # How often readings are taken from the accelerometer (seconds) READING_INTERVAL = 0.2 recentOpenStates = None # Take a photo only after the can was just opened and closed (and in steady state) photoRecentlyTaken = True def __init__(self): # Store recent history of states in tuples (horizontal, vertical) initialState = (False, False) maxLength = int(self.WAIT_TIME / self.READING_INTERVAL) self.recentOpenStates = deque(maxLength * [initialState], maxLength) def checkOrientation(self): """ Checks the current orientation of the lid, take a photo and process it. :return: """ horizontal = self.lidSensor.isHorizontal() vertical = self.lidSensor.isVertical() print 'H: ', horizontal print 'V: ', vertical self.recentOpenStates.append((horizontal, vertical)) if self.isReadyToTakePhoto() and not self.photoRecentlyTaken: print 'Taking photo now . . . ' fileName = self.getFileName() self.cameraSensor.setImagePath(fileName) self.cameraSensor.takePhoto() link = self.uploadPhoto(fileName) identifiers = self.recognitionService.getImageIdentifiers(fileName) targetPrediction = self.predictionService.getTrashPrediction(identifiers) print identifiers print targetPrediction # Fallback in case nothing is recognized in the image by recognition service if len(identifiers) == 0: identifiers = ['trash'] targetPrediction = 'trash' self.saveToDatabase(identifiers, targetPrediction, link) self.respondToPrediction(identifiers, targetPrediction) self.photoRecentlyTaken = True if vertical and not horizontal: # Lid is open self.lightOutput.turnOn() self.photoRecentlyTaken = False else: self.lightOutput.turnOff() def saveToDatabase(self, identifiers, targetPrediction, link): """ Save the record of identification to the database. :param identifiers: List of identifier strings from the image recognition service :param targetPrediction: String prediction from the prediction service :param link: Public URL to the image :return: Response to save request from the database """ return self.databaseService.addRecord({ 'item_name': ", ".join(identifiers), 'recyclable': (targetPrediction == 'recyclable'), 'compostable': (targetPrediction == 'compostable'), 'timestamp': int(time()), 'temperature': self.weatherService.getCurrentTemperature(), 'image': link, 'user_feedback': False, }) def getFileName(self): """ Return the pseudo unique filename of the next photo to be taken. :return: Absolute path to the file as a string """ timestamp = time() name = 'trash_' + str(timestamp) + '.jpg' path = '/tmp/' return path + name def isReadyToTakePhoto(self): """ Return if the iCan is ready to take a photo based on current state and previous states. If the lid as been closed for the entire duration of the waiting period, then it is time to take a photo. :return: Boolean on whether the iCan is ready to take a photo """ # Check if the queue of states shows it has been closed # for the entire waiting period closedState = (True, False) return self.recentOpenStates.count(closedState) == self.recentOpenStates.maxlen def uploadPhoto(self, fileName): """ Upload given file to cloud storage, write the link to a file and return it :param fileName: Absolute path to file :return: URL to the file on cloud storage """ # Write the public link to a local file link = self.storageService.uploadData(fileName) with open('/tmp/photos.txt', 'a') as photosFile: photosFile.write(link + "\n") print 'URL: ' + link return link def respondToPrediction(self, identifiers, targetPrediction): """ React to the prediction by either opening the trapdoor or sending a notification. :param identifiers: List of string identifiers from Image Recognition Service :param targetPrediction: Prediction of 'trash', 'compostable', 'recyclable', etc. from the ML model :type targetPrediction: str """ if targetPrediction == 'trash': print 'Down the hatch!' self.trapdoorOutput.open() print 'Waiting . . . ' sleep(2) self.trapdoorOutput.close() else: print 'Sending Notification' identifiersList = ', '.join(identifiers[:3]) message = 'iCan has detected an item that is: ' + identifiersList message = message + "\nCategory " + targetPrediction.upper() self.notificationService.sendNotification(message) def cleanUp(self): """ Clean up any used I/O pins and close any connections if needed. :return: None """ self.trapdoorOutput.cleanUp() self.lightOutput.cleanUp()
def __init__(self, game, num): self.game = game self.num = num self.tm = 0 self.tmu = 0 self.tmv = num * 16 self.state = STATE_INTRO if self.num <= 0: self.state = STATE_DEMO elif self.num == MAX_STAGE_NUM + 1: self.tm = 1 self.tmu = 0 self.tmv = 0 self.state = STATE_GAME_COMPLETE self.solid_rects = [ [0, 0, 160, 16], # [x, y, w, h] [0, 16, 8, 128], [152, 16, 8, 128], [0, 136, 160, 8] ] self.slopes = [] # [x, y] self.pockets = [] # [x, y, w, h] self.lights = [] # Light objects self.spinners = [] # Spinner objects self.en_spawn_locs_topleft = [] # [[x,y],[x,y],[x,y]...] self.en_spawn_locs_topright = [] # [[x,y],[x,y],[x,y]...] self.en_spawn_locs_bottomleft = [] # [[x,y],[x,y],[x,y]...] self.en_spawn_locs_bottomright = [] # [[x,y],[x,y],[x,y]...] if self.state != STATE_GAME_COMPLETE: for yc in range(HEIGHT_TILES): y = self.tmv + yc for xc in range(WIDTH_TILES): x = self.tmu + xc tile = pyxel.tilemap(self.tm).get(x, y) if tile == POST_TILE: self.solid_rects.append([xc*8 + 8, yc*8 + 16, 8, 8]) elif tile in SLOPE_TILES: self.slopes.append([xc*8 + 8, yc*8 + 16]) elif tile == LIGHT_TILE: self.lights.append(light.Light(xc*8 + 8, yc*8 + 16)) if tile == POCKET_TILE_NW: if x < self.tmu + WIDTH_TILES-1 and y < self.tmv + HEIGHT_TILES-1: if pyxel.tilemap(self.tm).get(x+1, y) == POCKET_TILE_NE and\ pyxel.tilemap(self.tm).get(x+1, y+1) == POCKET_TILE_SE and\ pyxel.tilemap(self.tm).get(x, y+1) == POCKET_TILE_SW: self.pockets.append([xc*8 + 8, yc*8 + 16, 16, 16]) if tile != POST_TILE and \ xc > 0 and \ xc < WIDTH_TILES-1 and \ yc > 0 and \ yc < HEIGHT_TILES-1 and \ (xc < 5 or xc > WIDTH_TILES-6) and \ (yc < 5 or yc > HEIGHT_TILES-6): loc = [xc*8 + 8 + 4, yc*8 + 16 + 4] if xc < 9: if yc < 7: self.en_spawn_locs_topleft.append(loc) else: self.en_spawn_locs_bottomleft.append(loc) else: if yc < 7: self.en_spawn_locs_topright.append(loc) else: self.en_spawn_locs_bottomright.append(loc) #print(self.pockets) num_spinners = 0 stage_diff_name = stagedata.STAGE_DIFFICULTY[self.num] for i in range(len(spinner.TYPES)): en_qty = stagedata.ENEMIES[stage_diff_name][stagedata.SPINNER_KEY][i] for sq in range(en_qty): loc = self.get_random_spawn_loc(-1) self.spinners.append(spinner.Spinner(loc[0], loc[1], i)) self.player = player.Player(75,75)#(12, 20) if self.state == STATE_GAME_COMPLETE: self.player.state = player.STATE_GAME_COMPLETE audio.play_music(audio.MUS_IN_GAME, True) else: if self.state != STATE_DEMO: audio.play_music(audio.MUS_START, False) self.pause_menu = PauseMenu(self) self.stage_over_ticks = 0 self.next_stage_flash_num = 0
def load(self): # 3D Model Loader # load_model = models.Models("CornellBox-Original.obj") # self.create_model(load_model, glm.vec3(0.0, 0.0, -2.0)) # First Scene: FOUR SPHERE # self.primitives.append(sphere.Sphere(glm.vec3(0.0, 0.0, 0.0), 0.2)) # self.primitives.append(sphere.Sphere(glm.vec3(-0.5, 0.0, -1.0), 0.2)) # self.primitives.append(sphere.Sphere(glm.vec3(0.0, -0.5, -2.0), 0.2)) # self.primitives.append(sphere.Sphere(glm.vec3(0.0, 0.5, -3.0), 0.2)) # Second Scene: TRIFORCE # self.primitives.append(triangle.Triangle(glm.vec3(0.0, 0.6, -2.0), glm.vec3(-0.2, 0.3, -2.0), glm.vec3(0.2, 0.3, -2.0))) # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -2.0), glm.vec3(-0.4, 0.0, -2.0), glm.vec3(0.0, 0.0, -2.0))) # self.primitives.append(triangle.Triangle(glm.vec3(0.2, 0.3, -2.0), glm.vec3(0.0, 0.0, -2.0), glm.vec3(0.4, 0.0, -2.0))) # Third Scene: THE WIZARD # self.primitives.append(sphere.Sphere(glm.vec3(0.0, 0.5, -3.0), 0.2)) # self.primitives.append(triangle.Triangle(glm.vec3(0.0, 1.0, -0.5), glm.vec3(-1.0, -2.0, -3.0), glm.vec3(1.0, -2.0, -3.0))) # Forth Scene: TRIANGLES # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -1.0), glm.vec3(-0.4, 0.0, -1.0), glm.vec3(0.0, 0.0, -1.0))) # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -1.5), glm.vec3(-0.4, 0.0, -1.5), glm.vec3(0.0, 0.0, -1.5))) # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -2.0), glm.vec3(-0.4, 0.0, -2.0), glm.vec3(0.0, 0.0, -2.0))) # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -2.5), glm.vec3(-0.4, 0.0, -2.5), glm.vec3(0.0, 0.0, -2.5))) # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -3.0), glm.vec3(-0.4, 0.0, -3.0), glm.vec3(0.0, 0.0, -3.0))) # Pathtracer Scene: CORNELL BOX WITH SPHERES # BACK self.primitives.append( triangle.Triangle( glm.vec3(1.2, -1.2, -2.5), glm.vec3(-1.2, 1.2, -2.5), glm.vec3(-1.2, -1.2, -2.5), diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68)))) self.primitives.append( triangle.Triangle( glm.vec3(1.2, -1.2, -2.5), glm.vec3(1.2, 1.2, -2.5), glm.vec3(-1.2, 1.2, -2.5), diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68)))) # FLOOR self.primitives.append( triangle.Triangle( glm.vec3(-1.2, -1.2, -2.5), glm.vec3(1.2, -1.2, -2.5), glm.vec3(-1.2, -1.0, -1.0), diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68)))) self.primitives.append( triangle.Triangle( glm.vec3(-1.2, -1.0, -1.0), glm.vec3(1.2, -1.2, -2.5), glm.vec3(1.2, -1.0, -1.0), diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68)))) # LEFT WALL self.primitives.append( triangle.Triangle( glm.vec3(-1.2, -1.2, -2.5), glm.vec3(-1.2, -1.0, -1.0), glm.vec3(-1.2, 1.2, -2.5), diffuse.Diffuse(brdf=glm.vec3(0.14, 0.45, 0.091)))) self.primitives.append( triangle.Triangle( glm.vec3(-1.2, 1.2, -2.5), glm.vec3(-1.2, -1.0, -1.0), glm.vec3(-1.2, 1.2, -1.0), diffuse.Diffuse(brdf=glm.vec3(0.14, 0.45, 0.091)))) # RIGHT WALL self.primitives.append( triangle.Triangle( glm.vec3(1.2, 1.2, -1.0), glm.vec3(1.2, -1.0, -1.0), glm.vec3(1.2, 1.2, -2.5), diffuse.Diffuse(brdf=glm.vec3(0.63, 0.065, 0.05)))) self.primitives.append( triangle.Triangle( glm.vec3(1.2, 1.2, -2.5), glm.vec3(1.2, -1.0, -1.0), glm.vec3(1.2, -1.2, -2.5), diffuse.Diffuse(brdf=glm.vec3(0.63, 0.065, 0.05)))) # CEILING self.primitives.append( triangle.Triangle( glm.vec3(-1.2, 1.2, -1.0), glm.vec3(-1.2, 1.2, -2.5), glm.vec3(1.2, 1.2, -2.5), diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68)))) self.primitives.append( triangle.Triangle( glm.vec3(1.2, 1.2, -2.5), glm.vec3(1.2, 1.2, -1.0), glm.vec3(-1.2, 1.2, -1.0), diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68)))) # LIGHT self.primitives.append( triangle.Triangle( glm.vec3(-0.5, 1.19, -1.5), glm.vec3(-0.5, 1.19, -2.0), glm.vec3(0.5, 1.19, -2.0), light.Light(emittance=glm.vec3(30.0, 30.0, 30.0)))) self.primitives.append( triangle.Triangle( glm.vec3(0.5, 1.19, -2.0), glm.vec3(0.5, 1.19, -1.5), glm.vec3(-0.5, 1.19, -1.5), light.Light(emittance=glm.vec3(30.0, 30.0, 30.0)))) # SPHERES self.primitives.append( sphere.Sphere(glm.vec3(-0.5, -0.65, -1.5), 0.4, mirror.Mirror())) self.primitives.append( sphere.Sphere(glm.vec3(0.6, -0.65, -1.8), 0.4, diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68))))
import light l = light.Light() l.setup() l.turnOff() l.destroy()