def __init__(self, step=3, x=370, y=205, camera=graphics.CAMERA, shader=graphics.MATSH): shape = [[], [], []] self.wifi_lines = [] for x1 in range(-45, 45, step): s, c = sin(radians(x1)), cos(radians(x1)) shape[0].append((7 * s, 7 * c, 0.1)) shape[1].append((14 * s, 14 * c, 0.1)) shape[2].append((21 * s, 21 * c, 0.1)) self.wifi_lines.append( pi3d.Disk(radius=2, sides=7, z=0.1, rx=90, x=x, y=y, camera=camera)) self.wifi_lines[0].set_shader(shader) self.wifi_lines[0].set_material((1, 1, 1)) for x1 in range(3): self.wifi_lines.append( pi3d.Lines(vertices=shape[x1], line_width=3, x=x, y=y, strip=True)) self.wifi_lines[x1 + 1].set_shader(shader) self.wifi_lines[x1 + 1].set_material((1, 1, 1))
def __init__(self): self.DISPLAY = pi3d.Display.create(0, 0, w=preview_W, h=preview_H, layer=1, frames_per_second=max_fps) self.DISPLAY.set_background(0.0, 0.0, 0.0, 0.0) # transparent self.keybd = pi3d.Keyboard() self.txtshader = pi3d.Shader("uv_flat") self.linshader = pi3d.Shader('mat_flat') self.CAMERA = pi3d.Camera(is_3d=False) self.font = pi3d.Font("fonts/FreeMono.ttf", font_size=30, color=(0, 255, 0, 255)) # blue green 1.0 alpha self.model_path = "/home/pi/python-tflite-source/edgetpu/test_data/mobilenet_ssd_v2_face_quant_postprocess_edgetpu.tflite" self.engine = edgetpu.detection.engine.DetectionEngine(self.model_path) self.camera = PiCamera() self.camera.resolution = (320, 320) self.camera.framerate = 24 #self.rawCapture = PiRGBArray(self.camera, size=(320, 320)) self.rawCapture = bytearray(self.camera.resolution[0] * self.camera.resolution[1] * 3) self.camera.start_preview(fullscreen=False, layer=0, window=(0, 0, 320, 320)) time.sleep(2) #camera warm-up self.stream = io.BytesIO() #self.stream = self.camera.capture_continuous(self.rawCapture, format="bgr", use_video_port=True) self.frame = None self.frame_buf_val = None self.output = None self.stopped = False self.max_obj = 10 self.X_OFF = np.array([0, 0, -1, -1, 0, 0, 1, 1]) self.Y_OFF = np.array([-1, -1, 0, 0, 1, 1, 0, 0]) self.X_IX = np.array([0, 1, 1, 1, 1, 0, 0, 0]) self.Y_IX = np.array([0, 0, 0, 1, 1, 1, 1, 0]) self.verts = [[0.0, 0.0, 1.0] for i in range(8 * self.max_obj) ] # need a vertex for each end of each side self.bbox = pi3d.Lines(vertices=self.verts, material=(1.0, 0.8, 0.05), closed=False, strip=False, line_width=4) self.bbox.set_shader(self.linshader)
def __init__(self, textures, shader, radius, density, pos=[0.0, 0.0, 0.0], vel=[0.0, 0.0, 0.0], acc=[0.0, 0.0, 0.0], track_shader=None, light=None): """arguments generally self explanatory; textures is a list of Textures if more than one then a shell sphere is created with a slightly faster rotational speed, if track_shader is passed then a trace_shape is generated and drawn as points every 1200 call of the position_and_draw() method. The code for the track has been much improved in this version. It now uses a Lines object which has re_init() called every third frame. The Camera method relocate() is also used to make the code tidier. """ super(Planet, self).__init__(radius=radius, slices=24, sides=24, x=pos[0], y=pos[1], z=pos[2]) super(Planet, self).set_draw_details(shader, [textures[0]]) if light is not None: self.set_light(light) self.pos = np.array(pos) self.vel = np.array(vel) self.acc = np.array(acc) self.mass = math.pi * 4.0 / 3.0 * density * radius ** 3.0 self.rotation = -0.1 / radius self.shell = None if len(textures) > 1: # second Texture for 'shell' sphere self.shell = pi3d.Sphere(radius=radius*1.05, slices=24, sides=24) self.shell.set_draw_details(shader, [textures[1]]) if light is not None: self.shell.set_light(light) self.shell.rotation = self.rotation * 1.5 self.track_shader = track_shader if track_shader is not None: pts = np.tile(self.pos, (750, 1)) #start off all inside planet! self.track = pi3d.Lines(material=(0.0,1.0,1.0), vertices=pts) self.f = 0 # frame counter for trail self.t_v, self.t_n, self.t_t, self.t_f = [], [], [], [] self.t_len = 0
DISPLAY = pi3d.Display.create(preview_mid_X, preview_mid_Y, w=preview_W, h=preview_H, layer=1, frames_per_second=30, samples=4) DISPLAY.set_background(0.0, 0.0, 0.0, 0.0) # transparent keybd = pi3d.Keyboard() tracksh = pi3d.Shader("mat_flat") #vertices_lines = (line_1, line_4) #track_1 = pi3d.Lines(vertices=[(line_1),(line_4)], material=(1.0,0.0,1.0), z=1.0, line_width=4) #, closed= track_1 = pi3d.Lines(vertices=line_1, material=(1.0, 0.0, 1.0), z=1.0, line_width=4) #track_2 = pi3d.Lines(vertices=line_2, material=(1.0,0.2,1.0), z=1.0, line_width=4) track_3 = pi3d.Lines(vertices=line_3, material=(7.0, 0.4, 1.0), z=1.0, line_width=4) #track_4 = pi3d.Lines(vertices=line_4, material=(1.0,0.6,1.0), z=1.0, line_width=4) # , closed=True) track_1.set_shader(tracksh) #track_2.set_shader(tracksh) track_3.set_shader(tracksh) #track_4.set_shader(tracksh) #j = 0.0 while DISPLAY.loop_running():
def __init__(self, x_values, y_values, width, height, xpos=0, ypos=0, z=1.0, xmin=None, xmax=None, ymin=None, ymax=None, camera=None, shader=None, colorarray=[(0, 0, 1, 1, 1), (1, 0, 0, 1, 1), (0, 1, 0, 1, 1)]): """ Arguments: *x_values* 1D numpy array *y_values* 1 or 2D numpy array with size same as x_values in 2nd D draws a line graph or 3D numpy array with size same as x along axis=1 and last axis has 2 values. In this case the graph is drawn as vertical lines *width, height* as expected *font* pi3d.Font instance *title, line_width* as expected *axes_desc* tuple -> (x.axis.desc, y.axis.desc) *legend* tuple -> (y0.desc, y1.desc, y2.desc...) *xpos, ypos* offset relative to origin of display (centre) *xmin, xmax, ymin, ymax* override sampled values from init data *camera* if no other Shape to be drawn then a 2D Camera can be created here *shader* if no other Shape uses mat_flat shader then one will be created """ if len(y_values.shape) < 2: y_values.shape = (1, ) + y_values.shape if x_values.shape[0] != y_values.shape[1]: LOGGER.error('mismatched array lengths') return if camera is None: camera = pi3d.Camera(is_3d=False) if shader is None: shader = pi3d.Shader('mat_flat') # axes ########### axex, axey = width * 0.5, height * 0.5 # implies 10% margin all round # lines to represent data n = x_values.shape[-1] if xmin is None: xmin = x_values.min() if xmax is None: xmax = x_values.max() x_factor = (2.0 * axex) / (xmax - xmin) x_offset = xmin if ymin is None: ymin = y_values.min() if ymax is None: ymax = y_values.max() y_factor = (2.0 * axey) / (ymax - ymin) y_offset = ymin self.lines = [] for i in range(y_values.shape[0]): data = np.zeros((n, 3)) data[:, 0] = (x_values - x_offset) * x_factor - axex + xpos if len(y_values[i].shape) == 1: # i.e. normal line graph data[:, 1] = (y_values[i] - y_offset) * y_factor - axey + ypos strip = True else: # has to be pairs of values for separate line segments xx_vals = np.stack([data[:, 0], data[:, 0]], axis=1).ravel() # make x into pairs data = np.zeros((n * 2, 3)) data[:, 0] = xx_vals data[:, 1] = (y_values[i].ravel() - y_offset) * y_factor - axey + ypos strip = False data[:, 2] = z # z value rgb_val = colorarray[i] line = pi3d.Lines(vertices=data, line_width=rgb_val[4], z=(z - i * 0.01), strip=strip) line.set_shader(shader) j = i + 2 #rgb_val = tuple(int(i * 255) for i in colorarray[i]) # converting 0..1 -> 0 -255 line.set_material((rgb_val[0], rgb_val[1], rgb_val[2])) line.set_alpha(rgb_val[3]) self.lines.append(line) # scale factors for use in update() so add to self self.y_offset = y_offset self.y_factor = y_factor self.axey = axey self.ypos = ypos
import pi3d sys.path.insert(1, os.path.join(sys.path[0], '..')) text5 = pi3d.PointText(graphics.pointFont, graphics.CAMERA, max_chars=20, point_size=64) # slider5 Ammeter currents = pi3d.TextBlock(-350, 100, 0.1, 0.0, 15, data_obj=peripherals.eg_object, attr="relais1current", text_format="{:2.1f}A", size=0.99, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text5.add_text_block(currents) amperemeter = pi3d.ImageSprite(config.installpath + 'sprites/amperemeter.png', shader=graphics.SHADER, camera=graphics.CAMERA, w=400, h=400, x=0, y=0, z=2.0) ampereneedle = pi3d.Lines(camera=graphics.CAMERA, vertices=( (0, 0, 0), (0, 160, 0)), material=(1.0, 0.3, 0.0), line_width=5, x=0.0, y=-70.0, z=1.0) ampereneedle.set_shader(graphics.MATSH) def inloop(textchange=False, activity=False, offset=0): if offset != 0: offset = graphics.slider_change(amperemeter, offset) else: ampereneedle.rotateToZ( 50 - (peripherals.eg_object.relais1current * 20)) ampereneedle.draw() amperemeter.draw() text5.draw()
for x in range(0, IX - 1): i = (z * IX) + x idx.append([i, i + IX, i + IX + 1]) idx.append([i + IX + 1, i + 1, i]) s += 2 terrain = pi3d.Shape(None, None, "terrain", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0) terrain.buf = [] terrain.buf.append(pi3d.Buffer(terrain, verts, tex_coords, idx, None, True)) terrain.set_material((0.2, 0.3, 0.5)) terrain.set_shader(shader) axes = pi3d.Lines(vertices=[[2.0 * W, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 2.0 * HT, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 2.0 * D]], line_width=3, x=-W / 2.0, z=-D / 2.0) axes.set_shader(flatsh) mouserot = 0.0 # rotation of camera tilt = 15.0 # tilt of camera frame = 0 #key presses mymouse = pi3d.Mouse(restrict=False) mymouse.start() omx, omy = mymouse.position() xoff, yoff, zoff = 0, 0, 0
# Create Table TableModel = pi3d.Model(file_string='media/models/Pool_Table_8ft.obj', name='Table', sx=common.DIM_RATIO, sy=common.DIM_RATIO, sz=common.DIM_RATIO, light=light_source) TableModel.set_shader(TableShader) TableModel.set_normal_shine(Normtex, 500.0, Shinetex, 0.05, bump_factor=0.1) # Create Trajectories traject_list = [(i * 0.1, i * 0.1, i * 0.1) for i in range(500)] traject_empty_list = [(i * 0, i * 0, i * 0) for i in range(500)] tracksh = pi3d.Shader("mat_flat") track = pi3d.Lines(vertices=traject_list, material=(1.0, 0.0, 1.0), z=0, line_width=1) track.set_shader(tracksh) # Create Ball r_breaking = table.BilliardTable.r r_epsil_breaking = table.BilliardTable.r_epsil DIAMETER = r_epsil_breaking + r_epsil_breaking cue_ball = calculate.PoolBall( name="Cue_Ball", ball_index=0, state=calculate.STATIONARY_STATE, r=np.array([ 0, table.BilliardTable.bot_rail_r + DIAMETER * 10, table.BilliardTable.table_height + table.BilliardTable.r
ms = str(elapsed_ms) ms_txt = pi3d.String(camera=CAMERA, is_3d=False, font=font, string=ms, x=0, y=preview_H/2 - 30, z=1.0) ms_txt.set_shader(txtshader) fps = "00.0 fps" N = 10 fps_txt = pi3d.String(camera=CAMERA, is_3d=False, font=font, string=fps, x=0, y=preview_H/2 - 10, z=1.0) fps_txt.set_shader(txtshader) i = 0 last_tm = time.time() X_OFF = np.array([0, 0, -1, -1, 0, 0, 1, 1]) Y_OFF = np.array([-1, -1, 0, 0, 1, 1, 0, 0]) X_IX = np.array([0, 1, 1, 1, 1, 0, 0, 0]) Y_IX = np.array([0, 0, 0, 1, 1, 1, 1, 0]) verts = [[0.0, 0.0, 1.0] for i in range(8 * max_obj)] # need a vertex for each end of each side bbox = pi3d.Lines(vertices=verts, material=(1.0,0.8,0.05), closed=False, strip=False, line_width=4) bbox.set_shader(linshader) #global detection #def detection(input_val):# # global engine, max_obj # results = engine.DetectWithInputTensor(input_val, top_k=max_obj) # return results #global bbox_results #def bbox_results(results): # global mdl_dims, X_OFF, Y_OFF, X_IX, Y_IX, verts, bbox # if results: # num_obj = 0 # for obj in results: # num_obj = num_obj + 1
s.names)] # this will be a view of the full array, only for named stars label = pi3d.String(font=font, string='Sol', y=-250, is_3d=False, camera=CAM2D) label.set_shader(flatsh) t = threading.Thread(target=s.select_visible) # run in infinite loop t.daemon = True t.start() while not s.ready: # to ensure stars set up first time in select_visible time.sleep(0.1) ''' constelation lines ''' orion = [ 231, 44288, 52501, 100413, 52501, 42572, 62904, 55898, 71408, 59549, 17025, 5088, 42572, 5088, 17025, 81378, 14265, 14597, 14265, 81378, 51101, 76177 ] orion_line = pi3d.Lines(vertices=s.v[orion, :3]) orion_line.set_shader(matsh) ursamajor = [2982, 5454, 2934, 3178, 2982, 3144, 3324, 4284] ursamajor_line = pi3d.Lines(vertices=s.v[ursamajor, :3], material=(0.0, 0.2, 0.9)) ursamajor_line.set_shader(matsh) pi = [0, 667, 5187, 667, 31882, 7980, 31882, 9285] pi_line = pi3d.Lines(vertices=s.v[pi, :3], material=(0.87, 0.0, 0.67)) pi_line.set_shader(matsh) import starsystem as sm # tucked away in another file for tidyness! near_system = sm.StarSystem(sm.systems[0][0], sm.systems[0][1], sm.systems[0][2], s.v) mymouse = pi3d.Mouse(restrict=False) mymouse.start()
cub = [0]*num_cubes lin = [0]*num_cubes for i in range(num_cubes): val_x = 10*randint(-15,15) val_y = 10*randint(-10,10) val_z = 10*randint(-2,10) val_s = randint(10,25) col_r = randint(0,2) col_g = randint(0,2) col_b = randint(0,2) cub[i] = pi3d.Cuboid(x = val_x, y = val_y, z =val_z, w=val_s, h=val_s, d=val_s) cub[i].set_material((col_r, col_g, col_b)) lin[i] = pi3d.Lines(vertices = [(val_x,val_y,200), (val_x,val_y,val_z)], line_width =20) lin[i].set_material((col_r, col_g, col_b)) ##################################################### # sph[i] = pi3d.Sphere(x = val_x*20, y=val_y*20, z=val_z*20, radius= 10) mkeys = pi3d.Keyboard() x_t = 0 y_t = 0 z_t = -30 #IR Vars ir_x = [0]*2 ir_y = [0]*2 temp_x = [0]*2
background.set_material((0.0, 0.0, 0.0)) background.set_alpha(0.7) # default orientated in x,z plane so rotate ball = pi3d.Disk(radius=150, sides=24, z=2.5, rx=90, camera=graphics.CAMERA) ball.set_shader(graphics.MATSH) ball.set_material((1, 1, 1)) ball.set_alpha(0.6) # default orientated in x,z plane so rotate dot = pi3d.Disk(radius=8, sides=8, z=0.1, rx=90, camera=graphics.CAMERA) dot.set_shader(graphics.MATSH) dot.set_material((1, 0, 0)) dot.set_alpha(1) edge_line = pi3d.Lines(vertices=shape, line_width=5, strip=True) edge_line.set_shader(graphics.MATSH) edge_line.set_material((0.3, 0.1, 0)) edge_line.set_alpha(1) seps = [] seps.append((-400, 0, 2.5)) seps.append((400, 0, 2.5)) seps.append((0, 0, 2.5)) seps.append((0, 240, 2.5)) seps.append((00, -240, 2.5)) seperator = pi3d.Lines(vertices=seps, line_width=10, strip=True) seperator.set_shader(graphics.MATSH) seperator.set_material((1, 1, 1)) seperator.set_alpha(0.1)
w=preview_W, h=preview_H, layer=1, frames_per_second=max_fps) DISPLAY.set_background(0.0, 0.0, 0.0, 0.0) # transparent keybd = pi3d.Keyboard() txtshader = pi3d.Shader("uv_flat") linshader = pi3d.Shader('mat_flat') CAMERA = pi3d.Camera(is_3d=False) font = pi3d.Font("fonts/FreeMono.ttf", font_size=30, color=(0, 255, 0, 255)) # blue green 1.0 alpha Z = 1.0 bbox_vertices = [[-0.5, 0.5, Z], [0.5, 0.5, Z], [0.5, -0.5, Z], [-0.5, -0.5, Z]] # sides 1.0 x 1.0 bbox = pi3d.Lines(vertices=bbox_vertices, material=(1.0, 0.8, 0.05), closed=True, line_width=4) bbox.set_shader(linshader) fps = "00.00FPS" N = 10 fps_txt = pi3d.String(camera=CAMERA, is_3d=False, font=font, string=fps, x=0, y=preview_H / 2 - 10, z=1.0) fps_txt.set_shader(txtshader) elapsed_ms = 1 / 1000 ms = "00ms" ms_txt = pi3d.String(camera=CAMERA,
we_are_offline = pi3d.ImageSprite(offlineimg, shader) we_are_offline.position(0, 0, backplaneZ - 6) # "Pins" around the globe showing the Unobtanium mining operations # Each Pin is a tuple of a pi3d.Lines and a status pinGoodColor = (129 / 255, 220 / 255, 247 / 255) # Light Blue pinDestroyColor = (252 / 255, 28 / 255, 28 / 255) # Red GOOD = 0 BAD = 1 DESTROY = 2 pins = [] # Generate initial set of Pins for p in range(num_stations): pin = { 'line': pi3d.Lines(vertices=[(0.0, 0.0, 0.0), randomPoint(1.25)]), 'status': GOOD } pin['line'].set_material(pinGoodColor) pins.append(pin) # Speed of planet rotation rot = -0.15 #rot = -0.5 # listen for keystrokes mykeys = pi3d.Keyboard() # Start the background machine noise #os.system('omxplayer --no-osd --no-keys --loop machine.wav &') background = subprocess.Popen(
def __init__(self, x_values, y_values, width, height, font, title=None, line_width=2, axes_desc=None, legend=None, xpos=0, ypos=0, xmin=None, xmax=None, ymin=None, ymax=None, camera=None, shader=None): ''' Arguments: *x_values* 1D numpy array *y_values* 1 or 2D numpy array with size same as x_values in 2nd D draws a line graph or 3D numpy array with size same as x along axis=1 and last axis has 2 values. In this case the graph is drawn as vertical lines *width, height* as expected *font* pi3d.Font instance *title, line_width* as expected *axes_desc* tuple -> (x.axis.desc, y.axis.desc) *legend* tuple -> (y0.desc, y1.desc, y2.desc...) *xpos, ypos* offset relative to origin of display (centre) *xmin, xmax, ymin, ymax* override sampled values from init data *camera* if no other Shape to be drawn then a 2D Camera can be created here *shader* if no other Shape uses mat_flat shader then one will be created ''' if len(y_values.shape) < 2: y_values.shape = (1, ) + y_values.shape if x_values.shape[0] != y_values.shape[1]: LOGGER.error('mismatched array lengths') return if camera is None: camera = pi3d.Camera(is_3d=False) if shader is None: shader = pi3d.Shader('mat_flat') # title ########## point_size = max(min(48, int(height * 0.1)), 24) self.text = pi3d.PointText(font, camera, max_chars=400, point_size=point_size) if title is not None: title = pi3d.TextBlock(x=xpos, y=ypos + height / 2 - point_size + 5, z=0.1, rot=0.0, char_count=len(title) + 2, spacing='F', text_format=title, space=0.05, justify=0.5) self.text.add_text_block(title) # axes ########### axex, axey = width * 0.4, height * 0.4 # implies 10% margin all round self.axes = pi3d.Lines( vertices=[[axex, -axey - line_width, 0], [-axex - line_width, -axey - line_width, 0], [-axex - line_width, axey, 0]], x=xpos, y=ypos, z=5.0, line_width=line_width) self.axes.set_shader(shader) # lines to represent data n = x_values.shape[-1] if xmin is None: xmin = x_values.min() if xmax is None: xmax = x_values.max() x_factor = (2.0 * axex) / (xmax - xmin) x_offset = xmin if ymin is None: ymin = y_values.min() if ymax is None: ymax = y_values.max() y_factor = (2.0 * axey) / (ymax - ymin) y_offset = ymin self.lines = [] for i in range(y_values.shape[0]): data = np.zeros((n, 3)) data[:, 0] = (x_values - x_offset) * x_factor - axex + xpos if len(y_values[i].shape) == 1: # i.e. normal line graph data[:, 1] = (y_values[i] - y_offset) * y_factor - axey + ypos strip = True else: # has to be pairs of values for separate line segments xx_vals = np.stack([data[:, 0], data[:, 0]], axis=1).flatten() # make x into pairs data = np.zeros((n * 2, 3)) data[:, 0] = xx_vals data[:, 1] = (y_values[i].flatten() - y_offset) * y_factor - axey + ypos strip = False data[:, 2] = 4.0 # z value line = pi3d.Lines(vertices=data, line_width=line_width, strip=strip) line.set_shader(shader) j = i + 1 rgb_val = (0.913 * j % 1.0, 0.132 * j % 1.0, 0.484 * j % 1.0) line.set_material(rgb_val) self.lines.append(line) # axis values point_size *= 0.3 # first add the max and min vals vals = [(-axex + xpos, -axey + ypos - point_size, '{:.3g}'.format(xmin), 0.0), (axex + xpos, -axey + ypos - point_size, '{:.3g}'.format(xmax), 0.0), (-axex + xpos - point_size, -axey + ypos, '{:.3g}'.format(ymin), 90.0), (-axex + xpos - point_size, axey + ypos, '{:.3g}'.format(ymax), 90.0)] data = [ ] # use this to hold vertex positions for grid lines (called ticks) for val in self.tick_pos(xmin, xmax): x = (val - x_offset) * x_factor - axex vals.append((x + xpos, -axey + ypos - point_size, '{:.3g}'.format(val), 0.0)) data.extend([[x, -axey, 0], [x, axey, 0]]) # NB points in pairs to use GL_LINES option with strip=False below. for val in self.tick_pos(ymin, ymax): y = (val - y_offset) * y_factor - axey vals.append((-axex + xpos - point_size, y + ypos, '{:.3g}'.format(val), 90.0)) data.extend([[-axex, y, 0], [axex, y, 0]]) for val in vals: self.text.add_text_block( pi3d.TextBlock(val[0], val[1], 4.0, val[3], 8, size=0.7, text_format=val[2], spacing='F', space=0.05, justify=0.5)) self.ticks = pi3d.Lines(vertices=data, x=xpos, y=ypos, z=5.0, line_width=line_width, material=(0.5, 0.5, 0.5), strip=False) self.ticks.set_shader(shader) # axes descritions if axes_desc is not None: self.text.add_text_block( pi3d.TextBlock(xpos, ypos - 1.15 * axey, 4.0, 0.0, len(axes_desc[0]) + 2, size=0.7, text_format=axes_desc[0], spacing='F', space=0.05, justify=0.5)) self.text.add_text_block( pi3d.TextBlock(xpos - 1.15 * axex, ypos, 4.0, 90.0, len(axes_desc[1]) + 2, size=0.7, text_format=axes_desc[1], spacing='F', space=0.05, justify=0.5)) # legend ########## if legend is not None: if not hasattr(legend, '__iter__'): # single string, make into list legend = [legend] for i, lgd in enumerate(legend): self.text.add_text_block( pi3d.TextBlock( axex + xpos, axey + ypos - (i + 1) * point_size * 2.0, 4.0, 0.0, len(lgd) + 2, size=0.8, text_format=lgd, spacing='F', space=0.05, justify=1.0, colour=tuple(self.lines[i].buf[0].unib[3:6]) + (1.0, ))) # scale factors for use in update() so add to self self.y_offset = y_offset self.y_factor = y_factor self.axey = axey self.ypos = ypos
def init(): global snowline, rainline, seplines, degwind, weathericon, text, line global windneedle, acttemp, text, error #global baroneedle, linemin, linemax from pyowm.commons.enums import SubscriptionTypeEnum languagedict = { 'subscription_type': SubscriptionTypeEnum.FREE, 'language': config.OWMLANGUAGE, 'connection': { 'use_ssl': True, 'verify_ssl_certs': True, 'use_proxy': False, 'timeout_secs': 5 }, 'proxies': { 'http': 'http://*****:*****@host:port', 'https': 'socks5://user:pass@host:port' } } owm = pyowm.OWM(config.OWMKEY, config=languagedict) mgr = owm.weather_manager() place = mgr.weather_at_place(config.OWMCITY) weather = place.weather text.text_blocks = [] text._first_free_char = 0 if config.OWMLANGUAGE == 'de': # TODO this needs untangling from stuff in config weekdays = [ 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag' ] else: weekdays = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ] file_path = resource_filename( "shpi", "sprites/{}.png".format(weather.weather_icon_name)) if os.path.exists(file_path): weathericon = pi3d.ImageSprite(file_path, shader=graphics.SHADER, camera=graphics.CAMERA, w=150, h=150, z=2, x=-220) # else: # import urllib.request # urllib.request.urlretrieve("http://openweathermap.org/img/wn/" + weather.get_weather_icon_name( # ) + "@2x.png", "sprites/" + weather.get_weather_icon_name() + ".png") city = pi3d.TextBlock(-390, 180, 0.1, 0.0, 150, text_format=place.location.name, size=0.7, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(city) city = pi3d.TextBlock(-220, 80, 0.1, 0.0, 30, justify=0.5, text_format=weather.detailed_status, size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(city) acttemp = pi3d.TextBlock( -350, -50, 0.1, 0.0, 10, text_format=str(weather.temperature('celsius')['temp']) + u'°C', size=0.9, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(acttemp) sunriset = weather.sunrise_time(timeformat='date') + datetime.timedelta( hours=2) sunsett = weather.sunset_time(timeformat='date') + datetime.timedelta( hours=2) sunset = pi3d.TextBlock(50, 100, 0.1, 0.0, 20, text_format="{} {}:{:02d} {} {}:{:02d}".format( unichr(0xE041), sunriset.hour, sunriset.minute, unichr(0xE042), sunsett.hour, sunsett.minute), size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(sunset) barometer = pi3d.TextBlock(50, -50, 0.1, 0.0, 10, text_format=unichr(0xE00B) + ' ' + str(weather.pressure['press']) + ' hPa', size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(barometer) # baroneedle = pi3d.Triangle(camera=graphics.CAMERA, corners=( # (-2, 0, 0), (0, 7, 0), (2, 0, 0)), x=barometer.x+16, y=barometer.y - 6, z=0.1) # baroneedle.set_shader(graphics.MATSH) normalizedpressure = (weather.pressure['press'] - 950) if normalizedpressure < 0: normalizedpressure = 0 if normalizedpressure > 100: normalizedpressure = 100 green = 0.02 * (normalizedpressure) if green > 1: green = 1 red = 0.02 * (100 - normalizedpressure) if red > 1: red = 1 barometer.colouring.set_colour([red, green, 0, 1.0]) #baroneedle.set_material([red, green, 0]) #baroneedle.rotateToZ(100 - (normalizedpressure*2)) humidity = pi3d.TextBlock(50, 0, 0.1, 0.0, 10, text_format=unichr(0xE003) + ' ' + str(weather.humidity) + '%', size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(humidity) if 'speed' in weather.wind(): wind = pi3d.TextBlock(50, 50, 0.1, 0.0, 10, text_format=unichr(0xE040) + ' ' + str(weather.wind()['speed']) + 'm/s', size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(wind) if 'deg' in weather.wind(): degwind = True windneedle = pi3d.Triangle(camera=graphics.CAMERA, corners=((-3, 0, 0), (0, 15, 0), (3, 0, 0)), x=wind.x + 180, y=wind.y, z=0.1) windneedle.set_shader(graphics.MATSH) windneedle.set_material([1, 1, 1]) windneedle.rotateToZ(weather.wind()['deg']) else: degwind = False #fc = owm.three_hours_forecast(config.OWMCITY) f = mgr.forecast_at_place(config.OWMCITY, '3h').forecast step = 780 / (len(f)) actualy = -400 + step temp_max = [] temp_min = [] temp = [] seplinesarr = [] icons = [] rainarr = [] snowarr = [] maxdaytemp = -100 mindaytemp = 100 for weather in f: file_path = resource_filename( "shpi", "sprites/{}.png".format(weather.weather_icon_name)) if not os.path.exists(file_path): import urllib.request # TODO py2 py3 fix urllib.request.urlretrieve( "http://openweathermap.org/img/wn/" + weather.get_weather_icon_name() + "@2x.png", file_path) icons.append( pi3d.ImageSprite(file_path, shader=graphics.SHADER, camera=graphics.CAMERA, w=20, h=20, z=1, x=actualy, y=-220)) if weather.reference_time('iso')[11:16] == '00:00': seplinesarr.append([actualy, -50, 2]) seplinesarr.append([actualy, 50, 2]) seplinesarr.append([actualy, -50, 2]) # if weather.get_reference_time('iso')[11:16] == '12:00': day = weather.reference_time(timeformat='date').weekday() if actualy < 300: city = pi3d.TextBlock(actualy + 65, -100, 0.1, 0.0, 30, text_format=weekdays[day], justify=0.5, size=0.23, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(city) if actualy > -300: city = pi3d.TextBlock(actualy - 6 * step, -150, 0.1, 0.0, 30, text_format=str(round(maxdaytemp, 1)) + u'°C', size=0.25, spacing="F", space=0.05, colour=(1.0, 0.0, 0.0, 1.0)) text.add_text_block(city) city = pi3d.TextBlock(actualy - 6 * step, -210, 0.1, 0.0, 30, text_format=str(round(mindaytemp, 1)) + u'°C', size=0.25, spacing="F", space=0.05, colour=(0.0, 0.0, 1.0, 1.0)) text.add_text_block(city) maxdaytemp = -100 mindaytemp = 100 if '3h' in weather.snow: snowarr.append([actualy, (-50 + weather.snow['3h'] * 30), 2]) else: snowarr.append([actualy, -50, 2]) if '3h' in weather.rain: rainarr.append([actualy, (-50 + weather.rain['3h'] * 30), 2]) else: rainarr.append([actualy, -50, 2]) temperatures = weather.temperature(unit='celsius') if temperatures['temp_max'] > maxdaytemp: maxdaytemp = temperatures['temp_max'] if temperatures['temp_min'] < mindaytemp: mindaytemp = temperatures['temp_min'] temp_max.append([actualy, temperatures['temp_max'] * 3, 2]) temp_min.append([actualy, temperatures['temp_min'] * 3, 2]) temp.append([actualy, temperatures['temp'] * 3, 2]) actualy += step snowline = pi3d.Lines(vertices=snowarr, line_width=3, y=-180, strip=True) snowline.set_shader(graphics.MATSH) snowline.set_material((0.5, 0.5, 1)) snowline.set_alpha(0.7) rainline = pi3d.Lines(vertices=rainarr, line_width=3, y=-180, strip=True) rainline.set_shader(graphics.MATSH) rainline.set_material((0, 0, 1)) rainline.set_alpha(0.7) seplines = pi3d.Lines(vertices=seplinesarr, line_width=1, y=-180, strip=True) seplines.set_shader(graphics.MATSH) seplines.set_material((0, 0, 0)) seplines.set_alpha(0.9) line = pi3d.Lines(vertices=temp, line_width=2, y=-220, strip=True) line.set_shader(graphics.MATSH) line.set_material((0, 0, 0)) line.set_alpha(0.9)
import demo import pi3d, math, numpy as np import numpy.random display = pi3d.Display.create(x=50, y=350, w=800, h=600) CAMERA = pi3d.Camera(is_3d=False) matsh = pi3d.Shader('mat_flat') vertices = np.array([[-100.0, -100.0, 0.0], [-100.0, 100.0, 0.0], [100.0, 100.0, 0.0], [100.0, -100.0, 0.0]]) square = pi3d.Lines(camera=CAMERA, vertices=vertices, closed=True, material=(1.0, 0.8, 0.05), line_width=3) square.set_shader(matsh) t_mat = np.eye(3, dtype=np.float32) r_mat = np.eye(3, dtype=np.float32) s_mat = np.eye(3, dtype=np.float32) angle = 0 def refresh_vertices(shape, old_verts): new_verts = [] for v in old_verts: # One order new_v = t_mat @ r_mat @ s_mat @ np.array([v[0], v[1], 1.0]) new_verts.append(new_v) shape.re_init(pts=new_verts)
def init(): global seplines, degwind, weathericon, text, line, baroneedle, windneedle, linemin, linemax, acttemp, text, error try: owm = pyowm.OWM(API_key=config.owmkey, language=config.owmlanguage) place = owm.weather_at_place(config.owmcity) weather = place.get_weather() text.text_blocks = [] text._first_free_char = 0 if config.owmlanguage == 'de': weekdays = [ 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag' ] else: weekdays = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ] if not os.path.exists('sprites/' + weather.get_weather_icon_name() + '.png'): import urllib.request urllib.request.urlretrieve( "http://openweathermap.org/img/wn/" + weather.get_weather_icon_name() + "@2x.png", "sprites/" + weather.get_weather_icon_name() + ".png") weathericon = pi3d.ImageSprite(config.installpath + 'sprites/' + weather.get_weather_icon_name() + '.png', shader=graphics.SHADER, camera=graphics.CAMERA, w=150, h=150, z=2, x=-220) city = pi3d.TextBlock(-390, 180, 0.1, 0.0, 150, text_format=place.get_location().get_name(), size=0.7, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(city) city = pi3d.TextBlock(-220, 80, 0.1, 0.0, 30, justify=0.5, text_format=weather.get_detailed_status(), size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(city) acttemp = pi3d.TextBlock( -350, -50, 0.1, 0.0, 10, text_format=str(weather.get_temperature(unit='celsius')['temp']) + u'°C', size=0.9, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(acttemp) #acttemp = pi3d.FixedString(config.installpath + 'fonts/opensans.ttf', str(weather.get_temperature(unit='celsius')['temp']) + '°C' , font_size=42, shadow_radius=1,justify='L', color= (255,255,255,255),camera=graphics.CAMERA, shader=graphics.SHADER, f_type='SMOOTH') #acttemp.sprite.position(-210, -50, 1) sunriset = weather.get_sunrise_time( timeformat='date') + datetime.timedelta(hours=2) sunsett = weather.get_sunset_time( timeformat='date') + datetime.timedelta(hours=2) sunset = pi3d.TextBlock(50, 100, 0.1, 0.0, 20, text_format=unichr(0xE041) + " %s:%02d" % (sunriset.hour, sunriset.minute) + ' ' + unichr(0xE042) + " %s:%02d" % (sunsett.hour, sunsett.minute), size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(sunset) barometer = pi3d.TextBlock(50, -50, 0.1, 0.0, 10, text_format=unichr(0xE00B) + ' ' + str(weather.get_pressure()['press']) + ' hPa', size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(barometer) baroneedle = pi3d.Triangle(camera=graphics.CAMERA, corners=((-2, 0, 0), (0, 7, 0), (2, 0, 0)), x=barometer.x + 16, y=barometer.y - 6, z=0.1) baroneedle.set_shader(graphics.MATSH) normalizedpressure = (weather.get_pressure()['press'] - 950) if normalizedpressure < 0: normalizedpressure = 0 if normalizedpressure > 100: normalizedpressure = 100 green = 0.02 * (normalizedpressure) if green > 1: green = 1 red = 0.02 * (100 - normalizedpressure) if red > 1: red = 1 barometer.colouring.set_colour([red, green, 0, 1.0]) baroneedle.set_material([red, green, 0]) baroneedle.rotateToZ(100 - (normalizedpressure * 2)) humidity = pi3d.TextBlock(50, 0, 0.1, 0.0, 10, text_format=unichr(0xE003) + ' ' + str(weather.get_humidity()) + '%', size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(humidity) if 'speed' in weather.get_wind(): wind = pi3d.TextBlock(50, 50, 0.1, 0.0, 10, text_format=unichr(0xE040) + ' ' + str(weather.get_wind()['speed']) + 'm/s', size=0.3, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(wind) if 'deg' in weather.get_wind(): degwind = True windneedle = pi3d.Triangle(camera=graphics.CAMERA, corners=((-3, 0, 0), (0, 15, 0), (3, 0, 0)), x=wind.x + 180, y=wind.y, z=0.1) windneedle.set_shader(graphics.MATSH) windneedle.set_material([1, 1, 1]) windneedle.rotateToZ(weather.get_wind()['deg']) else: degwind = False fc = owm.three_hours_forecast(config.owmcity) f = fc.get_forecast() step = 780 / (len(f)) actualy = -400 + step temp_max = [] temp_min = [] temp = [] seplines = [] icons = [] maxdaytemp = -100 mindaytemp = 100 for weather in f: if not os.path.exists('sprites/' + weather.get_weather_icon_name() + '.png'): import urllib.request urllib.request.urlretrieve( "http://openweathermap.org/img/wn/" + weather.get_weather_icon_name() + "@2x.png", "sprites/" + weather.get_weather_icon_name() + ".png") icons.append( pi3d.ImageSprite('sprites/' + weather.get_weather_icon_name() + '.png', shader=graphics.SHADER, camera=graphics.CAMERA, w=20, h=20, z=1, x=actualy, y=-220)) if weather.get_reference_time('iso')[11:16] == '00:00': line = pi3d.Lines(vertices=[[actualy, -50, 2], [actualy, 50, 2]], line_width=1, y=-180, strip=True) line.set_shader(graphics.MATSH) line.set_material((0, 0, 0)) line.set_alpha(0.9) seplines.append(line) # if weather.get_reference_time('iso')[11:16] == '12:00': day = weather.get_reference_time(timeformat='date').weekday() if actualy < 300: city = pi3d.TextBlock(actualy + 65, -100, 0.1, 0.0, 30, text_format=weekdays[day], justify=0.5, size=0.23, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(city) if actualy > -300: city = pi3d.TextBlock( actualy - 6 * step, -150, 0.1, 0.0, 30, text_format=str(round(maxdaytemp, 1)) + u'°C', size=0.25, spacing="F", space=0.05, colour=(1.0, 0.0, 0.0, 1.0)) text.add_text_block(city) city = pi3d.TextBlock( actualy - 6 * step, -210, 0.1, 0.0, 30, text_format=str(round(mindaytemp, 1)) + u'°C', size=0.25, spacing="F", space=0.05, colour=(0.0, 0.0, 1.0, 1.0)) text.add_text_block(city) maxdaytemp = -100 mindaytemp = 100 if '3h' in weather.get_snow(): line = pi3d.Lines(vertices=[[ actualy, -50, 2 ], [actualy, (-50 + weather.get_snow()['3h'] * 30), 2]], line_width=3, y=-180, strip=True) line.set_shader(graphics.MATSH) line.set_material((0.5, 0.5, 1)) line.set_alpha(1) seplines.append(line) if '3h' in weather.get_rain(): line = pi3d.Lines(vertices=[[ actualy, -50, 2 ], [actualy, (-50 + weather.get_rain()['3h'] * 30), 2]], line_width=3, y=-180, strip=True) line.set_shader(graphics.MATSH) line.set_material((0, 0, 1)) line.set_alpha(1) seplines.append(line) temperatures = weather.get_temperature(unit='celsius') if temperatures['temp_max'] > maxdaytemp: maxdaytemp = temperatures['temp_max'] if temperatures['temp_min'] < mindaytemp: mindaytemp = temperatures['temp_min'] temp_max.append([actualy, temperatures['temp_max'] * 3, 2]) temp_min.append([actualy, temperatures['temp_min'] * 3, 2]) temp.append([actualy, temperatures['temp'] * 3, 2]) actualy += step lastvalue = 0 line = pi3d.Lines(vertices=temp, line_width=2, y=-220, strip=True) line.set_shader(graphics.MATSH) line.set_material((0, 0, 0)) line.set_alpha(0.9) #linemin = pi3d.Lines(vertices=temp_min, line_width=1,y=-220, strip=True) # linemin.set_shader(graphics.MATSH) # linemin.set_material((0,0,1)) # linemin.set_alpha(0.9) #linemax = pi3d.Lines(vertices=temp_max, line_width=1,y=-220, strip=True) # linemax.set_shader(graphics.MATSH) # linemax.set_material((1,0,0)) # linemax.set_alpha(0.9) except: error = pi3d.TextBlock(-390, 180, 0.1, 0.0, 150, text_format="OWM ERROR", size=0.7, spacing="F", space=0.05, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(error) error = True
y=110) storagearea.set_shader(graphics.MATSH) storagearea.set_material((0.0, 0.0, 1.0)) floorplan = pi3d.ImageSprite(config.installpath + 'sprites/floorplan.png', shader=graphics.SHADER, camera=graphics.CAMERA, w=539, h=450, x=0, y=0, z=2.0) doorneedle = pi3d.Lines(camera=graphics.CAMERA, vertices=((0, 0, 0), (60, 0, 0)), material=(1.0, 0.3, 0.0), line_width=20, x=-13.0, y=-220.0, z=1.0) doorneedle.set_shader(graphics.MATSH) windowneedle = pi3d.Lines(camera=graphics.CAMERA, vertices=((0, 0, 0), (45, 0, 0)), material=(0, 1, 0.0), line_width=10, x=-180.0, y=217.0, z=1.0) windowneedle.set_shader(graphics.MATSH) rotate = 0