def onDrawGuiCallback(self, args): if self.visible: if imgui.begin("Combat Assist##combatassist_mainwindo", (450,300)): player = BigWorld.player() imgui.text("Combat script : ") selectedChanged, self.combatSelectedIndex = imgui.combo("##combatassist_combatcombo", self.combatSelectedIndex, combats.LOADED_COMBATS.keys()) if selectedChanged: combats.LOADED_COMBATS.keys()[self.combatSelectedIndex] self.combatRotationName = combats.LOADED_COMBATS.keys()[self.combatSelectedIndex] roplus.log("Using combat script : " + self.combatRotationName) imgui.sameLine() if imgui.button("Reload##grinder_reload_scripts", (imgui.getContentRegionAvail()[0], 24)): combats.reloadCombatModules() imgui.separator() if self.combatSelectedIndex == -1: imgui.text("Select a combat script first ...") else: if imgui.checkbox("Enable combat", self.rotationEnabled): self.rotationEnabled = not self.rotationEnabled if imgui.checkbox("Only attack in combat targets", self.combatCheck): self.combatCheck = not self.combatCheck if imgui.checkbox("Allow combat script to use movements", self.handleMovements): self.handleMovements = not self.handleMovements if imgui.checkbox("Automatically target attackers (Not implemented)", self.autoTargetEnemies): self.autoTargetEnemies = not self.autoTargetEnemies imgui.end()
def onUpdateUIOverlay(self, overlay): if imgui.collapsing_header("Settings"): if self.deviceFeatures.fillModeNonSolid: res, value = imgui.checkbox("Wireframe", self.wireframe) if res: overlay.updated = True self.wireframe = value self.buildCommandBuffers() if self.scene: res, value = imgui.checkbox("Attach Light", self.attachLight) if res: overlay.updated = True self.attachLight = value self.updateUniformBuffers() res, value = imgui.checkbox("Render single part", self.scene.renderSingleScenePart) if res: overlay.updated = True self.scene.renderSingleScenePart = value self.buildCommandBuffers() if self.scene.renderSingleScenePart: res, value = imgui.slider_int("Part to render", self.scene.scenePartIndex, 0, len(self.scene.meshes)) if res: overlay.updated = True self.scene.scenePartIndex = value self.buildCommandBuffers()
def draw(self): imgui.new_frame() imgui.set_next_window_position(16, 32, imgui.ONCE) imgui.set_next_window_size(512, 512, imgui.ONCE) imgui.begin("Example: checkboxes") # note: first element of return two-tuple notifies if there was a click # event in currently processed frame and second element is actual # checkbox state. _, self.checkbox1_enabled = imgui.checkbox("Checkbox 1", self.checkbox1_enabled) _, self.checkbox2_enabled = imgui.checkbox("Checkbox 2", self.checkbox2_enabled) imgui.text("Checkbox 1 state value: {}".format(self.checkbox1_enabled)) imgui.text("Checkbox 2 state value: {}".format(self.checkbox2_enabled)) imgui.end() imgui.end_frame() imgui.render() self.renderer.render(imgui.get_draw_data())
def _show_custom_context(self): # called from ui-node to add custom entries in nodes context menu # called only when that context menu is visible has_state = len(self.spec.initial_state) != 0 has_presets = len(self.spec.presets) != 0 if has_state: imgui.separator() if imgui.button("reset state"): self.reset_state(force=True) imgui.same_line() if imgui.button("randomize state"): self.randomize_state(force=True) changed, self.allow_state_randomization = imgui.checkbox( "allow state randomization", self.allow_state_randomization) if has_presets: imgui.separator() if imgui.button("default preset"): self.reset_preset(force=True) imgui.same_line() if imgui.button("random preset"): self.randomize_preset(force=True) imgui.same_line() if imgui.button("choose preset..."): imgui.open_popup("choose_preset") if imgui.begin_popup("choose_preset"): for name, values in self.spec.presets: if imgui.button(name): self.set_preset(values) imgui.end_popup() changed, self.allow_preset_randomization = imgui.checkbox( "allow preset randomization", self.allow_preset_randomization) if imgui.button("copy current as preset"): # copy only keys that are contained in (first) preset # TODO see how this behavior works keys = None if not has_presets else list( self.spec.presets[0][1].keys()) values = OrderedDict() for port_id, value in self.values.items(): if not is_input(port_id): continue name = port_name(port_id) if keys is not None and name not in keys: continue values[name] = value.value preset = ["name", values] clipboard.copy(json.dumps(preset))
def main(): window = impl_glfw_init() impl = GlfwRenderer(window) box1 = box2 = box3 = True while not glfw.window_should_close(window): glfw.poll_events() impl.process_inputs() imgui.new_frame() if imgui.begin_main_menu_bar(): if imgui.begin_menu("File", True): clicked_quit, selected_quit = imgui.menu_item( "Quit", 'Cmd+Q', False, True) if clicked_quit: exit(1) imgui.end_menu() imgui.end_main_menu_bar() imgui.begin("Scope Test") box1 = imgui.checkbox("Checkbox", box1)[1] with imgui.scope(2): imgui.new_line() imgui.text("Same name, different scope:") box2 = imgui.checkbox("Checkbox", box2)[1] imgui.new_line() imgui.text("Same name, same scope:") imgui.text("(This will not work right)") box3 = imgui.checkbox("Checkbox", box3)[1] imgui.end() gl.glClearColor(1., 1., 1., 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) imgui.render() glfw.swap_buffers(window) impl.shutdown() imgui.shutdown() glfw.terminate()
def draw(self): imgui.begin("Example: checkboxes") # note: first element of return two-tuple notifies if there was a click # event in currently processed frame and second element is actual # checkbox state. _, self.checkbox1_enabled = imgui.checkbox("Checkbox 1", self.checkbox1_enabled) _, self.checkbox2_enabled = imgui.checkbox("Checkbox 2", self.checkbox2_enabled) imgui.text("Checkbox 1 state value: {}".format(self.checkbox1_enabled)) imgui.text("Checkbox 2 state value: {}".format(self.checkbox2_enabled)) imgui.end()
def draw_plot_gui(self): if self.plot_gui: imgui.begin("Plot", False) imgui.columns(3, 'plot settings', border=True) imgui.text('x-axis:') for i in range(len(self.x_axis)): changed = imgui.radio_button(self.x_axis[i] + '##x', i == self.x_axis_index) if changed: if self.x_axis_index != i: self.reset_data() self.x_axis_index = i imgui.next_column() imgui.text('y-axis:') for i in range(len(self.y_axis)): changed, self.y_axis_on[i] = imgui.checkbox(self.y_axis[i] + '##y', self.y_axis_on[i]) if changed: self.reset_data() imgui.next_column() imgui.text('plot:') if imgui.button('add'): self.add_data() if imgui.button('reset'): self.reset_data() imgui.end()
def make_gui(self, width, height): imgui.begin("Lighting", True) ch, val = imgui.checkbox("Move sun", self._scene.time_enabled) if ch: self._scene.time_enabled = val ch, val = imgui.slider_float( "Roughness", self._scene.object.materials.values()[0].specular_tint, 0, 1 ) if ch: self._scene.object.materials.values()[0].specular_tint = val ch, val = imgui.slider_float( "Metallic", self._scene.object.materials.values()[0].metallic_tint, 0, 1 ) if ch: self._scene.object.materials.values()[0].metallic_tint = val ch, val = imgui.color_edit3( "Material colour", *self._scene.object.materials.values()[0].diffuse_tint ) if ch: self._scene.object.materials.values()[0].diffuse_tint = np.array(val) ch, val = imgui.color_edit3("Sun colour", *self._scene.sun_color) if ch: self._scene.sun_color = np.array(val) ch, val = imgui.slider_float("Sun intensity", self._scene.sun_intensity, 0, 100) if ch: self._scene.sun_intensity = val imgui.end()
def update(dt, keyStateMap, mouseDelta): global g_sunPosition global g_sunAngle global g_globalAmbientLight global g_sunLightColour global g_sunAngle global g_updateSun global g_viewTarget global g_viewPosition global g_followCamOffset global g_followCamLookOffset if g_updateSun: g_sunAngle += dt * 0.25 g_sunAngle = g_sunAngle % (2.0 * math.pi) g_sunPosition = lu.Mat3( lu.make_rotation_x(g_sunAngle)) * g_sunStartPosition g_sunLightColour = sampleKeyFrames( lu.dot(lu.normalize(g_sunPosition), vec3(0.0, 0.0, 1.0)), g_sunKeyFrames) g_globalAmbientLight = sampleKeyFrames( lu.dot(lu.normalize(g_sunPosition), vec3(0.0, 0.0, 1.0)), g_ambientKeyFrames) g_racer.update(dt, keyStateMap) # TODO 1.2: Make the camera look at the racer. Code for updating the camera should be done after the # racer, otherwise the offset will lag and it generally looks weird. if imgui.tree_node("Camera", imgui.TREE_NODE_DEFAULT_OPEN): _, g_followCamOffset = imgui.slider_float("FollowCamOffset ", g_followCamOffset, 2.0, 100.0) _, g_followCamLookOffset = imgui.slider_float("FollowCamLookOffset", g_followCamLookOffset, 0.0, 100.0) imgui.tree_pop() if imgui.tree_node("Racer", imgui.TREE_NODE_DEFAULT_OPEN): g_racer.drawUi() imgui.tree_pop() if imgui.tree_node("Terrain", imgui.TREE_NODE_DEFAULT_OPEN): g_terrain.drawUi() imgui.tree_pop() if imgui.tree_node("Lighting", imgui.TREE_NODE_DEFAULT_OPEN): _, g_globalAmbientLight = lu.imguiX_color_edit3_list( "GlobalAmbientLight", g_globalAmbientLight ) #, imgui.GuiColorEditFlags_Float);// | ImGuiColorEditFlags_HSV); _, g_sunLightColour = lu.imguiX_color_edit3_list( "SunLightColour", g_sunLightColour ) #, imgui.GuiColorEditFlags_Float);// | ImGuiColorEditFlags_HSV); _, g_sunAngle = imgui.slider_float("SunAngle", g_sunAngle, 0.0, 2.0 * math.pi) _, g_updateSun = imgui.checkbox("UpdateSun", g_updateSun) imgui.tree_pop()
def tests(self): imgui.begin("Test Window") imgui.text("Lorem ipsum") changed, self.checkbox = imgui.checkbox("Checkbox", self.checkbox) # imgui.core.checkbox if imgui.button("Test Circle", 100, 20): self.canvas.add_object(self.testCircle) if imgui.button("Test Ellipse", 100, 20): self.canvas.add_object(self.testEllipse) imgui.end()
def draw_layers_window(self, width, height): imgui.set_next_window_size(width / 6, height / 4) imgui.set_next_window_position(width * 5 / 6, height * 2 / 4) imgui.begin("Layers", flags=default_flags) _, self.show_grid = imgui.checkbox("Show Grid", self.show_grid) _, self.show_points = imgui.checkbox("Show Places", self.show_points) _, self.show_lines = imgui.checkbox("Show Connections", self.show_lines) _, self.point_size = imgui.slider_int("Point Size", self.point_size, min_value=1, max_value=6) clicked, self.font_scale = imgui.slider_float("Font Scale", self.font_scale, 0.1, 0.9, "%.1f") if clicked: self.update_font_scale(self.font_scale) imgui.end()
def drawUi(self): # height scale is read-only as it is not run-time changable (since we use it to compute normals at load-time) imgui.label_text("terrainHeightScale", "%0.2f" % self.heightScale) #_,self.heightScale = imgui.slider_float("terrainHeightScale", self.heightScale, 1.0, 100.0) _, self.textureXyScale = imgui.slider_float("terrainTextureXyScale", self.textureXyScale, 0.01, 10.0) _, self.renderWireFrame = imgui.checkbox("WireFrame", self.renderWireFrame)
def show(self, value, read_only): clicked, self.show_texture = imgui.checkbox("Show", self.show_texture) if not self.show_texture: return texture = value.value if texture is None: self.texture_aspect = None else: h, w, _ = texture.shape self.texture_aspect = w / h cursor_pos = imgui.get_cursor_screen_pos() imgui.set_next_window_size(500, 500, imgui.ONCE) imgui.set_next_window_size_constraints((0.0, 0.0), (float("inf"), float("inf")), self.window_size_callback) imgui.set_next_window_position(*imgui.get_io().mouse_pos, imgui.ONCE, pivot_x=0.5, pivot_y=0.5) expanded, opened = imgui.begin( "Texture of %s###%s%s" % (self.node.spec.name, id(self.node), id(self)), True, imgui.WINDOW_NO_SCROLLBAR) if not opened: self.show_texture = False if expanded: if texture is None: imgui.text("No texture associated") else: # [::-1] reverses list texture_size = texture.shape[:2][::-1] texture_aspect = texture_size[0] / texture_size[1] window_size = imgui.get_content_region_available() imgui.image(texture._handle, window_size[0], window_size[0] / texture_aspect) if imgui.is_item_hovered() and imgui.is_mouse_clicked(1): # little hack to have first context menu entry under cursor io = imgui.get_io() pos = io.mouse_pos io.mouse_pos = pos[0] - 20, pos[1] - 20 imgui.open_popup("context") io.mouse_pos = pos if imgui.begin_popup("context"): if imgui.menu_item("save")[0]: util.image.save_screenshot(texture.get()) imgui.menu_item("texture handle: %s" % texture._handle, None, False, False) imgui.menu_item("texture dtype: %s" % str(texture.dtype), None, False, False) imgui.menu_item("texture shape: %s" % str(texture.shape), None, False, False) imgui.end_popup() imgui.end()
def draw_btn_bar(self): # 按钮栏 utils.set_cursor_offset(6, 0) if imgui.button("clear"): print("清理") self.log_mgr.clear() imgui.same_line() # log等级 for idx, log_level in enumerate(self.log_level_lst): is_check = self.config.is_has_log_level(log_level) ret = imgui.checkbox(self.log_level[idx], is_check) imgui.same_line() if ret[1] == is_check: continue if ret[1]: self.config.add_log_level(log_level) else: self.config.remove_log_level(log_level) # 搜索框 imgui.same_line() old_text = self.config.get_string(EConfigKey.CONTENT_SEARCH_TEXT) imgui.push_item_width(240) imgui.push_id(EConfigKey.CONTENT_SEARCH_TEXT) ret = imgui.input_text("", old_text, 128) imgui.pop_id() if ret[0]: self.on_search_text_change(ret[1]) imgui.pop_item_width() imgui.same_line() utils.set_cursor_offset(-8, 0) if imgui.button("清空"): self.on_search_text_change("") # 是否固定到底部 imgui.same_line() is_to_bottom = self.config.get_bool( EConfigKey.CONTENT_SCROLL_TO_BOTTOM, True) ret = imgui.checkbox("bottom", is_to_bottom) if ret[1] != is_to_bottom: self.config.set_bool(EConfigKey.CONTENT_SCROLL_TO_BOTTOM, ret[1])
def update(world: World, g_renderingSystem: RenderingSystem, dt, keyStateMap, mouseDelta): if world.should_update_sun: world.sun_angle += dt * 0.25 world.sun_angle = world.sun_angle % (2.0 * math.pi) world.sun_position = lu.Mat3(lu.make_rotation_x( world.sun_angle)) * world.sun_start_position world.sunlight_color = sampleKeyFrames( lu.dot(lu.normalize(world.sun_position), vec3(0.0, 0.0, 1.0)), world.sun_keyframes) world.global_ambient_light = sampleKeyFrames( lu.dot(lu.normalize(world.sun_position), vec3(0.0, 0.0, 1.0)), world.ambient_keyframes) world.racer.update(dt, keyStateMap) world.view_position = world.racer.position - \ (world.racer.heading * world.follow_cam_offset) + \ [0, 0, world.follow_cam_offset] world.view_target = world.racer.position + vec3( 0, 0, world.follow_cam_look_offset) if imgui.tree_node("Camera", imgui.TREE_NODE_DEFAULT_OPEN): _, world.follow_cam_offset = imgui.slider_float( "FollowCamOffset ", world.follow_cam_offset, 2.0, 100.0) _, world.follow_cam_look_offset = imgui.slider_float( "FollowCamLookOffset", world.follow_cam_look_offset, 0.0, 100.0) imgui.tree_pop() if imgui.tree_node("Racer", imgui.TREE_NODE_DEFAULT_OPEN): world.racer.draw_ui() imgui.tree_pop() if imgui.tree_node("Terrain", imgui.TREE_NODE_DEFAULT_OPEN): world.terrain.draw_ui() imgui.tree_pop() if imgui.tree_node("Lighting", imgui.TREE_NODE_DEFAULT_OPEN): _, world.global_ambient_light = lu.imguiX_color_edit3_list( "GlobalAmbientLight", world.global_ambient_light ) # , imgui.GuiColorEditFlags_Float);// | ImGuiColorEditFlags_HSV); _, world.sunlight_color = lu.imguiX_color_edit3_list( "SunLightColour", world.sunlight_color ) # , imgui.GuiColorEditFlags_Float);// | ImGuiColorEditFlags_HSV); _, world.sun_angle = imgui.slider_float("SunAngle", world.sun_angle, 0.0, 2.0 * math.pi) _, world.should_update_sun = imgui.checkbox("UpdateSun", world.should_update_sun) imgui.tree_pop()
def draw_gui(self): imgui.begin('Controls') imgui.text('Framerate: {:.2f}'.format(self.io.framerate)) imgui.text('Vertices: {}'.format(self.vao.vertices)) _, self.gui['animate'] = imgui.checkbox('Animate', self.gui['animate']) _, self.gui['u_unwrap'] = imgui.drag_float('Unwrap', self.gui['u_unwrap'], 0.01, 0, 1) _, self.gui['u_separation'] = imgui.drag_float( 'Separation', self.gui['u_separation'], 0.01, 0, 1) cam_changed, self.gui['isolate'] = imgui.drag_float( 'Isolate', self.gui['isolate'], 0.01, 0, 1) _, self.gui['piece'] = imgui.drag_int2('Piece', *self.gui['piece'], 0.1, 0, num_pieces - 1) _, self.gui['num_pieces'] = imgui.drag_int('Num pieces', self.gui['num_pieces'], 0.1, 0) _, self.gui['layers'] = imgui.drag_int('Layers', self.gui['layers'], 0.1, 0) if self.gui['animate']: self.gui['u_unwrap'] = (np.sin(self.time()) + 1) / 2 # for some reason imgui isn't enforcing these minimums self.gui['layers'] = max(self.gui['layers'], 0) self.gui['num_pieces'] = max(self.gui['num_pieces'], 0) if cam_changed: cam_pos = self.gui['isolate'] * np.array(self.gui['cam_final']) \ + (1.0 - self.gui['isolate']) * np.array(self.gui['cam_init']) # look at middle of piece x_coord = self.gui['isolate'] * ( (self.gui['piece'][0] + self.gui['num_pieces'] / 2) / num_pieces - 0.5) # avoid some weird perspective stuff z_coord = self.gui['isolate'] * -.3 cam_pos[0] = x_coord self.camera['look_at'] = (x_coord, 0, z_coord) # update camera self.move_camera(cam_pos) self.update_camera() self.prog['m_mvp'].write(self.camera['mat']) imgui.end()
def menu(self): imgui.new_frame() #menu bar if imgui.begin_main_menu_bar(): if imgui.begin_menu("File", True): clicked_quit, selected_quit = imgui.menu_item( "Quit", 'Ctrl+Q', False, True) if clicked_quit: glfw.set_window_should_close(self.window, True) imgui.end_menu() imgui.end_main_menu_bar() imgui.show_test_window() imgui.begin("Demo window", True) imgui.text('ImGuiDemo') imgui.text_colored("* hold Left Mouse Button and drag to translate", 0.2, 1., 0.) imgui.text_colored("* use scroll wheel to zoom", 0.4, 1., 0.) imgui.text_colored("* press SPACE to toggle animation", 0.6, 1., 0.) changed, self.ui.animate = imgui.checkbox("Animate", self.ui.animate) changed, self.ui.gamma = imgui.slider_float("Gamma", self.ui.gamma, 0.3, 3.3) changed, self.ui.blue = imgui.slider_float("Blue", self.ui.blue, 0.0, 1.0) imgui.text("Animation Angle: {:0.2f}".format(self.ui.theta / (2.0 * np.pi) * 360.0)) changed, self.ui.speed = imgui.slider_float("Speed", self.ui.speed, 0.0, np.pi / 2.0) #transfer changed variables to shader programs self.quad['blue'] = self.ui.blue self.quad['gamma'] = self.ui.gamma imgui.end()
def draw(self): #imgui.set_next_window_position(288, 32, imgui.ONCE) imgui.set_next_window_position(self.window.width - 256 - 16, 32, imgui.ONCE) imgui.set_next_window_size(256, 256, imgui.ONCE) imgui.begin("Ship") # Rotation imgui.image(self.texture.glo, *self.texture.size) changed, self.rotation = imgui.drag_float( "Rotation", self.rotation, ) self.sprite.angle = self.rotation # Scale changed, self.scale = imgui.drag_float("Scale", self.scale, .1) self.sprite.scale = self.scale # Alpha changed, self.alpha = imgui.drag_int("Alpha", self.alpha, 1, 0, 255) self.sprite.alpha = self.alpha # Color _, self.color_enabled = imgui.checkbox("Tint", self.color_enabled) if self.color_enabled: changed, self.color = imgui.color_edit3("Color", *self.color) self.sprite.color = (int(self.color[0] * 255), int(self.color[1] * 255), int(self.color[2] * 255)) else: self.sprite.color = 255, 255, 255 if imgui.button("Reset"): self.reset() imgui.end() self.sprite.draw()
def draw_controls_window(self, width, height): imgui.set_next_window_size(width / 6, height / 4) imgui.set_next_window_position(width * 5 / 6, height * 1 / 4) imgui.begin("Controls", flags=default_flags) imgui.text("WASD to move around") imgui.text("Arrow Up/Down to zoom in/out") imgui.text("1-6 to change point size") if imgui.button("Stop" if self.simulation_active else "Start"): self.simulation_active = not self.simulation_active if imgui.button("Step"): self.update_sim() if imgui.button("Rollback"): # reset snapshot to the initial state when the inspector was created self.snapshot = copy.deepcopy(self.initial_state_snapshot) self.simulator.upload_all(self.snapshot.buffers) self.simulator.time = self.snapshot.time _, self.do_lockdown = imgui.checkbox("Lockdown", self.do_lockdown) if imgui.button("Hide Parameters" if self. show_parameters else "Show Parameters"): self.show_parameters = not self.show_parameters imgui.end()
def transformGuiOverlay(locationX, locationY, angle, color): # start new frame context imgui.new_frame() # open new window context imgui.begin("2D Transformations control", False, imgui.WINDOW_ALWAYS_AUTO_RESIZE) # draw text label inside of current window imgui.text("Configuration sliders") edited, locationX = imgui.slider_float("location X", locationX, -1.0, 1.0) edited, locationY = imgui.slider_float("location Y", locationY, -1.0, 1.0) edited, angle = imgui.slider_float("Angle", angle, -np.pi, np.pi) edited, color = imgui.color_edit3("Modulation Color", color[0], color[1], color[2]) if imgui.button("Random Modulation Color!"): color = (random.uniform(0.0, 1.0), random.uniform(0.0, 1.0), random.uniform(0.0, 1.0)) imgui.same_line() if imgui.button("White Modulation Color"): color = (1.0, 1.0, 1.0) global controller edited, checked = imgui.checkbox("wireframe", not controller.fillPolygon) if edited: controller.fillPolygon = not checked # close current window context imgui.end() # pass all drawing comands to the rendering pipeline # and close frame context imgui.render() imgui.end_frame() return locationX, locationY, angle, color
def draw(self): gui.new_frame() #gui.set_next_window_position(self.window.width - 256 - 16, 32, gui.ONCE) gui.set_next_window_size(512, 512, gui.ONCE) gui.begin("Framebuffer Example") # Rotation gui.image(self.texture.glo, *self.texture.size) changed, self.rotation = gui.drag_float( "Rotation", self.rotation, ) self.sprite.angle = self.rotation # Scale changed, self.scale = gui.drag_float( "Scale", self.scale, .1 ) self.sprite.scale = self.scale # Alpha changed, self.alpha = gui.drag_int( "Alpha", self.alpha, 1, 0, 255 ) self.sprite.alpha = self.alpha # Color _, self.color_enabled = gui.checkbox("Tint", self.color_enabled) if self.color_enabled: changed, self.color = gui.color_edit3("Color", *self.color) self.sprite.color = (int(self.color[0] * 255), int(self.color[1] * 255), int(self.color[2] * 255)) else: self.sprite.color = 255, 255, 255 if gui.button("Reset"): self.reset() fbtexture = self.offscreen.color_attachments[0] gui.image(fbtexture.glo, *FBSIZE) gui.end() self.offscreen.use() self.offscreen.clear((0, 0, 0, 0)) vp = arcade.get_viewport() arcade.set_viewport(0, FBSIZE[0], 0, FBSIZE[1]) prj = self.window.ctx.projection_2d self.window.ctx.projection_2d = (0, FBSIZE[0],FBSIZE[1],0) self.sprite.draw() arcade.draw_text("Simple line of text in 20 point", 0,0 , arcade.color.WHITE, 20) self.window.ctx.projection_2d = prj self.window.use() arcade.set_viewport(*vp) self.sprite.draw() gui.end_frame() gui.render() self.renderer.render(gui.get_draw_data())
def main(): useLiveCamera = True #gc.disable() # # transform to convert the image to tensor # transform = transforms.Compose([ # transforms.ToTensor() # ]) # # initialize the model # model = torchvision.models.detection.keypointrcnn_resnet50_fpn(pretrained=True, # num_keypoints=17) # # set the computation device # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # # load the modle on to the computation device and set to eval mode # model.to(device).eval() # initialize glfw if not glfw.init(): return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) #creating the window window = glfw.create_window(1600, 900, "PyGLFusion", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) imgui.create_context() impl = GlfwRenderer(window) # rendering glClearColor(0.2, 0.3, 0.2, 1.0) # positions texture coords quad = [ -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0 ] quad = np.array(quad, dtype=np.float32) indices = [0, 1, 2, 2, 3, 0] indices = np.array(indices, dtype=np.uint32) screenVertex_shader = (Path(__file__).parent / 'shaders/ScreenQuad.vert').read_text() screenFragment_shader = (Path(__file__).parent / 'shaders/ScreenQuad.frag').read_text() renderShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(screenVertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(screenFragment_shader, GL_FRAGMENT_SHADER)) # set up VAO and VBO for full screen quad drawing calls VAO = glGenVertexArrays(1) glBindVertexArray(VAO) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, 80, quad, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, 24, indices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) # shaders bilateralFilter_shader = (Path(__file__).parent / 'shaders/bilateralFilter.comp').read_text() bilateralFilterShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(bilateralFilter_shader, GL_COMPUTE_SHADER)) alignDepthColor_shader = (Path(__file__).parent / 'shaders/alignDepthColor.comp').read_text() alignDepthColorShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(alignDepthColor_shader, GL_COMPUTE_SHADER)) depthToVertex_shader = (Path(__file__).parent / 'shaders/depthToVertex.comp').read_text() depthToVertexShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(depthToVertex_shader, GL_COMPUTE_SHADER)) vertexToNormal_shader = (Path(__file__).parent / 'shaders/vertexToNormal.comp').read_text() vertexToNormalShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertexToNormal_shader, GL_COMPUTE_SHADER)) raycast_shader = (Path(__file__).parent / 'shaders/raycast.comp').read_text() raycastShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(raycast_shader, GL_COMPUTE_SHADER)) integrate_shader = (Path(__file__).parent / 'shaders/integrate.comp').read_text() integrateShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(integrate_shader, GL_COMPUTE_SHADER)) trackP2P_shader = (Path(__file__).parent / 'shaders/p2pTrack.comp').read_text() trackP2PShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(trackP2P_shader, GL_COMPUTE_SHADER)) reduceP2P_shader = (Path(__file__).parent / 'shaders/p2pReduce.comp').read_text() reduceP2PShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(reduceP2P_shader, GL_COMPUTE_SHADER)) trackP2V_shader = (Path(__file__).parent / 'shaders/p2vTrack.comp').read_text() trackP2VShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(trackP2V_shader, GL_COMPUTE_SHADER)) reduceP2V_shader = (Path(__file__).parent / 'shaders/p2vReduce.comp').read_text() reduceP2VShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(reduceP2V_shader, GL_COMPUTE_SHADER)) LDLT_shader = (Path(__file__).parent / 'shaders/LDLT.comp').read_text() LDLTShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(LDLT_shader, GL_COMPUTE_SHADER)) # Splatter globalMapUpdate_shader = (Path(__file__).parent / 'shaders/GlobalMapUpdate.comp').read_text() globalMapUpdateShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(globalMapUpdate_shader, GL_COMPUTE_SHADER)) indexMapGenVert_shader = (Path(__file__).parent / 'shaders/IndexMapGeneration.vert').read_text() indexMapGenFrag_shader = (Path(__file__).parent / 'shaders/IndexMapGeneration.frag').read_text() IndexMapGenerationShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(indexMapGenVert_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(indexMapGenFrag_shader, GL_FRAGMENT_SHADER)) SurfaceSplattingVert_shader = ( Path(__file__).parent / 'shaders/SurfaceSplatting.vert').read_text() SurfaceSplattingFrag_shader = ( Path(__file__).parent / 'shaders/SurfaceSplatting.frag').read_text() SurfaceSplattingShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(SurfaceSplattingVert_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(SurfaceSplattingFrag_shader, GL_FRAGMENT_SHADER)) UnnecessaryPointRemoval_shader = ( Path(__file__).parent / 'shaders/UnnecessaryPointRemoval.comp').read_text() UnnecessaryPointRemovalShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(UnnecessaryPointRemoval_shader, GL_COMPUTE_SHADER)) # P2V expm_shader = (Path(__file__).parent / 'shaders/expm.comp').read_text() expmShader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(expm_shader, GL_COMPUTE_SHADER)) d2c, c2d, K, invK, colK = camera.start(useLiveCamera) shaderDict = { 'renderShader': renderShader, 'bilateralFilterShader': bilateralFilterShader, 'alignDepthColorShader': alignDepthColorShader, 'depthToVertexShader': depthToVertexShader, 'vertexToNormalShader': vertexToNormalShader, 'raycastVolumeShader': raycastShader, 'integrateVolumeShader': integrateShader, 'trackP2PShader': trackP2PShader, 'reduceP2PShader': reduceP2PShader, 'trackP2VShader': trackP2VShader, 'reduceP2VShader': reduceP2VShader, 'LDLTShader': LDLTShader, 'globalMapUpdate': globalMapUpdateShader, 'indexMapGeneration': IndexMapGenerationShader, 'surfaceSplatting': SurfaceSplattingShader, 'unnecessaryPointRemoval': UnnecessaryPointRemovalShader, 'expm': expmShader } bufferDict = { 'p2pReduction': -1, 'p2pRedOut': -1, 'p2vReduction': -1, 'p2vRedOut': -1, 'test': -1, 'outBuf': -1, 'poseBuffer': -1, 'globalMap0': -1, 'globalMap1': -1, 'atomic0': -1, 'atomic1': -1 } textureDict = { 'rawColor': -1, 'lastColor': -1, 'nextColor': -1, 'rawDepth': -1, 'filteredDepth': -1, 'lastDepth': -1, 'nextDepth': -1, 'refVertex': -1, 'refNormal': -1, 'virtualVertex': -1, 'virtualNormal': -1, 'virtualDepth': -1, 'virtualColor': -1, 'mappingC2D': -1, 'mappingD2C': -1, 'xyLUT': -1, 'tracking': -1, 'volume': -1, 'indexMap': -1 } fboDict = {'indexMap': -1, 'virtualFrame': -1} # 'iters' : (2, 5, 10), fusionConfig = { 'volSize': (128, 128, 128), 'volDim': (1.0, 1.0, 1.0), 'iters': (2, 2, 2), 'initOffset': (0, 0, 0), 'maxWeight': 100.0, 'distThresh': 0.05, 'normThresh': 0.9, 'nearPlane': 0.1, 'farPlane': 4.0, 'maxMapSize': 5000000, 'c_stable': 10.0, 'sigma': 0.6 } cameraConfig = { 'depthWidth': 640, 'depthHeight': 576, 'colorWidth': 1920, 'colorHeight': 1080, 'd2c': d2c, 'c2d': c2d, 'depthScale': 0.001, 'K': K, 'invK': invK, 'colK': colK } textureDict = frame.generateTextures(textureDict, cameraConfig, fusionConfig) bufferDict = frame.generateBuffers(bufferDict, cameraConfig, fusionConfig) colorMat = np.zeros( (cameraConfig['colorHeight'], cameraConfig['colorWidth'], 3), dtype="uint8") useColorMat = False integrateFlag = True resetFlag = True initPose = glm.mat4() initPose[3, 0] = fusionConfig['volDim'][0] / 2.0 initPose[3, 1] = fusionConfig['volDim'][1] / 2.0 initPose[3, 2] = 0 blankResult = np.array([0, 0, 0, 0, 0, 0], dtype='float32') glBindBuffer(GL_SHADER_STORAGE_BUFFER, bufferDict['poseBuffer']) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, 16 * 4, glm.value_ptr(initPose)) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 16 * 4, 16 * 4, glm.value_ptr(glm.inverse(initPose))) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 16 * 4 * 2, 16 * 4, glm.value_ptr(glm.mat4(1.0))) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 16 * 4 * 3, 16 * 4, glm.value_ptr(glm.mat4(1.0))) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 16 * 4 * 4, 6 * 4, blankResult) glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0) mouseX, mouseY = 0, 0 clickedPoint3D = glm.vec4(fusionConfig['volDim'][0] / 2.0, fusionConfig['volDim'][1] / 2.0, 0, 0) sliderDim = fusionConfig['volDim'][0] #[32 64 128 256 512] currentSize = math.log2(fusionConfig['volSize'][0]) - 5 volumeStatsChanged = False currPose = initPose # splatter stuff frameCount = 0 fboDict = frame.generateFrameBuffers(fboDict, textureDict, cameraConfig) initAtomicCount = np.array([0], dtype='uint32') mapSize = np.array([0], dtype='uint32') glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, bufferDict['atomic0']) glBufferSubData(GL_ATOMIC_COUNTER_BUFFER, 0, 4, initAtomicCount) glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0) glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, bufferDict['atomic1']) glBufferSubData(GL_ATOMIC_COUNTER_BUFFER, 0, 4, initAtomicCount) glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0) # aa = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], dtype=torch.float32, device=torch.device('cuda')) # bb = torch.tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], dtype=torch.float32, device=torch.device('cuda')) # #setup pycuda gl interop needs to be after openGL is init # import pycuda.gl.autoinit # import pycuda.gl # cuda_gl = pycuda.gl # cuda_driver = pycuda.driver # from pycuda.compiler import SourceModule # import pycuda # pycuda_source_ssbo = cuda_gl.RegisteredBuffer(int(bufferDict['test']), cuda_gl.graphics_map_flags.NONE) # sm = SourceModule(""" # __global__ void simpleCopy(float *inputArray, float *outputArray) { # unsigned int x = blockIdx.x*blockDim.x + threadIdx.x; # outputArray[x] = inputArray[x]; # inputArray[x] = 8008.135f; # } # """) # cuda_function = sm.get_function("simpleCopy") # mappingObj = pycuda_source_ssbo.map() # data, size = mappingObj.device_ptr_and_size() # cuda_function(np.intp(aa.data_ptr()), np.intp(data), block=(8, 1, 1)) # mappingObj.unmap() # glBindBuffer(GL_SHADER_STORAGE_BUFFER, bufferDict['test']) # tee = glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, 32) # glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0) # teeData = np.frombuffer(tee, dtype=np.float32) # print(teeData) # modTensor = aa.cpu().data.numpy() # print(modTensor) #fusionConfig['initOffset'] = (initPose[3,0], initPose[3,1], initPose[3,2]) # LUTs #createXYLUT(k4a, textureDict, cameraConfig) <-- bug in this person.init() while not glfw.window_should_close(window): glfw.poll_events() impl.process_inputs() imgui.new_frame() sTime = time.perf_counter() try: capture = camera.getFrames(useLiveCamera) if capture.color is not None: #if useLiveCamera == False: #if k4a.configuration["color_format"] == ImageFormat.COLOR_MJPG: # colorMat = cv2.imdecode(capture.color, cv2.IMREAD_COLOR) # useColorMat = True glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, textureDict['rawColor']) glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, int(cameraConfig['colorWidth']), int(cameraConfig['colorHeight']), (GL_RGB, GL_RGBA)[useLiveCamera], GL_UNSIGNED_BYTE, (capture.color, colorMat)[useColorMat]) if capture.depth is not None: glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_2D, textureDict['rawDepth']) glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, int(cameraConfig['depthWidth']), int(cameraConfig['depthHeight']), GL_RED, GL_UNSIGNED_SHORT, capture.depth) except EOFError: break # #smallMat = cv2.pyrDown(colorMat) # start_time = time.time() # rotMat = cv2.flip(colorMat, 0) # pil_image = Image.fromarray(rotMat).convert('RGB') # image = transform(pil_image) # image = image.unsqueeze(0).to(device) # end_time = time.time() # print((end_time - start_time) * 1000.0) # with torch.no_grad(): # outputs = model(image) # output_image = utils.draw_keypoints(outputs, rotMat) # cv2.imshow('Face detection frame', output_image) # if cv2.waitKey(1) & 0xFF == ord('q'): # break person.getPose(textureDict, cameraConfig, capture.color) frame.bilateralFilter(shaderDict, textureDict, cameraConfig) frame.depthToVertex(shaderDict, textureDict, cameraConfig, fusionConfig) frame.alignDepthColor(shaderDict, textureDict, cameraConfig, fusionConfig) frame.vertexToNormal(shaderDict, textureDict, cameraConfig) frame.mipmapTextures(textureDict) #currPose = track.runP2P(shaderDict, textureDict, bufferDict, cameraConfig, fusionConfig, currPose, integrateFlag, resetFlag) currPose = track.runP2V(shaderDict, textureDict, bufferDict, cameraConfig, fusionConfig, currPose, integrateFlag, resetFlag) #mapSize = track.runSplatter(shaderDict, textureDict, bufferDict, fboDict, cameraConfig, fusionConfig, mapSize, frameCount, integrateFlag, resetFlag) frameCount += 1 if resetFlag == True: resetFlag = False integrateFlag = True imgui.begin("Menu", True) if imgui.button("Reset"): fusionConfig['volSize'] = (1 << (currentSize + 5), 1 << (currentSize + 5), 1 << (currentSize + 5)) fusionConfig['volDim'] = (sliderDim, sliderDim, sliderDim) currPose, integrateFlag, resetFlag = track.reset( textureDict, bufferDict, cameraConfig, fusionConfig, clickedPoint3D) volumeStatsChanged = False if imgui.button("Integrate"): integrateFlag = not integrateFlag imgui.same_line() imgui.checkbox("", integrateFlag) changedDim, sliderDim = imgui.slider_float("dim", sliderDim, min_value=0.01, max_value=5.0) clickedSize, currentSize = imgui.combo( "size", currentSize, ["32", "64", "128", "256", "512"]) if imgui.is_mouse_clicked(): if not imgui.is_any_item_active(): mouseX, mouseY = imgui.get_mouse_pos() w, h = glfw.get_framebuffer_size(window) xPos = ((mouseX % int(w / 3)) / (w / 3) * cameraConfig['depthWidth']) yPos = (mouseY / (h)) * cameraConfig['depthHeight'] clickedDepth = capture.depth[ int(yPos + 0.5), int(xPos + 0.5)] * cameraConfig['depthScale'] clickedPoint3D = clickedDepth * ( cameraConfig['invK'] * glm.vec4(xPos, yPos, 1.0, 0.0)) volumeStatsChanged = True if changedDim or clickedSize: volumeStatsChanged = True imgui.end() graphics.render(VAO, window, shaderDict, textureDict) imgui.render() impl.render(imgui.get_draw_data()) eTime = time.perf_counter() #print((eTime-sTime) * 1000, mapSize[0]) glfw.swap_buffers(window) glfw.terminate() if useLiveCamera == True: camera.stop()
motors[pin].speed = 0 pin_values[pin] = 0 imgui.end() imgui.begin(rov_type) if rov_type == "Hex ROV": rov_pins = hex_rov_pins elif rov_type == "Tank Steering ROV": rov_pins = tank_rov_pins else: print(rov_type) raise ValueError changed1, local_input = imgui.checkbox("Local Input", local_input) changed2, local_motors = imgui.checkbox("Local Motors", (not local_input) or local_motors) changed3, local_camera = imgui.checkbox("Local Camera", local_camera) if any([changed1, changed2, changed3]): assemble_motor_objects() assemble_controller() changed = False for motor in [ "Front Left Motor", "Front Right Motor", "Back Left Motor", "Back Right Motor" ]:
def main(): pygame.init() size = 800, 600 screen = pygame.display.set_mode(size, pygame.DOUBLEBUF | pygame.OPENGL) io = imgui.get_io() io.fonts.add_font_default() io.display_size = size renderer = PygameRenderer() clock = pygame.time.Clock() ## Test ####### # Setup OpenGL for 2D rendering glEnable(GL_TEXTURE_2D) glClearColor(0.0, 0.0, 0.0, 0.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0.0, size[0], size[1], 0.0) # Important glMatrixMode(GL_MODELVIEW) # new pygame.Surface test = pygame.Surface((300, 300)) test_x = 100 test_y = 100 test.fill((255, 0, 0)) tex_id = None # pygame surface to OpenGL tex ix, iy = test.get_width(), test.get_height() image = pygame.image.tostring(test, "RGBA", True) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) tex_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, tex_id) glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) ############### while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit() renderer.process_event(event) # Start frame imgui.new_frame() if imgui.begin_main_menu_bar(): if imgui.begin_menu("File", True): clicked_quit, selected_quit = imgui.menu_item( "Quit", 'Cmd+Q', False, True ) if clicked_quit: exit(1) imgui.end_menu() imgui.end_main_menu_bar() global cb_another, w_closable, dg_val if imgui.begin("Main window")[1]: imgui.begin_child("aaa", 300 , -10, border=False) imgui.begin_group() imgui.text("Toggle") _, cb_another = imgui.checkbox("Another Window", cb_another) imgui.text("Another Window state = {}".format(cb_another)) w_closable = cb_another imgui.end_group() imgui.begin_group() imgui.text("Example: drag float") changed, test_x = imgui.drag_float( "test_x", test_x, ) changed, test_y = imgui.drag_float( "test_y", test_y, ) imgui.text("Changed: {}, x: {:.2f} y: {:.2f}".format(changed, test_x, test_y)) imgui.end_group() imgui.end_child() imgui.end() # Disable perm if w_closable: _, w_closable = imgui.begin("Another window", False) # return (collapse, state) imgui.text("Bar") imgui.text_colored("Eggs", 0.2, 1., 0.) imgui.text("AAAA") imgui.end() # Clean screen glClearColor(0.5, 0.5, 0.5, 1) glClear(GL_COLOR_BUFFER_BIT) ## Draw ########## x = test_x y = test_y w = test.get_width() h = test.get_height() # Prepare the matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslatef(x, y, 0.0) # shift to (x, y) glBindTexture(GL_TEXTURE_2D, tex_id) # Actual draw glBegin(GL_QUADS) glTexCoord2f(0.0, 1.0); glVertex3f(0.0, 0.0, 0.0) # Left top glTexCoord2f(1.0, 1.0); glVertex3f(w, 0.0, 0.0) # Right top glTexCoord2f(1.0, 0.0); glVertex3f(w, h, 0.0) # Right bottom glTexCoord2f(0.0, 0.0); glVertex3f(0.0, h, 0.0) # Left bottom glEnd() ################## imgui.render() pygame.display.flip() clock.tick(60)
def update(self): # return done, value do_return = False recipe = '' if self.extra_font: imgui.push_font(self.extra_font) width = 750 height = 250 imgui.set_next_window_size(width, height) imgui.set_next_window_position(self.center_x - width // 2, self.center_y - height // 2) imgui.push_style_var(imgui.STYLE_ALPHA, self.alpha) imgui.begin('Drop', False, flags=self.flags) self.left_label('ID:') xx, self.id = imgui.input_text('\n', self.id, 128) self.tooltip_help('Participant ID/Name') self.add_space(3) self.left_label('Español:') _, self.spanish = imgui.checkbox('', self.spanish) self.tooltip_help('Spanish text for subsequent instructions') self.add_space(3) self.left_label('Recipe:') # current filenames recipe_names = [] recipe_short = [] for file in glob.glob('recipes/**/*.toml', recursive=True): if (os.path.sep + 'defaults' + os.path.sep) not in file: recipe_names.append(file) recipe_short.append(os.path.relpath(file, 'recipes')) changed, self.current_recipe = imgui.combo(' ', self.current_recipe, recipe_short) self.tooltip_help( 'Available recipes (TOML files) in the recipe directory') imgui.same_line() imgui.button('Preview') if imgui.is_item_hovered() and recipe_names: with open(recipe_names[self.current_recipe], 'r') as f: prev = f.read() # width in characters, height in number of newlines if prev: wid = len( max(open(recipe_names[self.current_recipe], 'r'), key=len)) # TODO: need to be careful of newline char?? hei = prev.count('\n') + 1 else: wid = 10 hei = 1 fac = 0.6 font_size = imgui.get_font_size() * fac wid = int(wid * font_size / 2) # get something like pix hei = int(hei * font_size) # if height is >= half the window height, turn to scroll val = hei if hei >= self.center_y: val = self.center_y imgui.begin_tooltip() imgui.begin_child('region', wid, val) imgui.set_scroll_y(imgui.get_scroll_y() - imgui.get_io().mouse_wheel * 30) imgui.set_window_font_scale(fac) imgui.text(prev) imgui.end_child() imgui.end_tooltip() imgui.set_item_default_focus() # imgui.set_tooltip(prev) self.add_space(3) if imgui.button('Ok'): do_return = True if imgui.get_io().keys_down[imgui.KEY_ENTER]: do_return = True imgui.pop_style_var(1) imgui.end() if self.extra_font: imgui.pop_font() # disallow depending on current state if not self.id: do_return = False try: recipe = recipe_names[self.current_recipe] except IndexError: do_return = False if not os.path.isdir(self.recipe_dir): do_return = False # no need to validate data dir, we'll create it data = { 'id': self.id, 'recipe': recipe, 'spanish': 'es' if self.spanish else 'en' } return do_return, data
def show_ui(self): _, self.enabled = imgui.checkbox( f'Enable##{self.ui_index}'.format(self.ui_index), self.enabled)
# set for comparison on the next frame time_at_beginning_of_previous_frame = glfw.get_time() if not animation_paused: animation_time += 1.0 / 60.0 * animation_time_multiplier # Poll for and process events glfw.poll_events() impl.process_inputs() imgui.new_frame() imgui.set_next_window_bg_alpha(0.05) imgui.begin("Time", True) clicked_animation_paused, animation_paused = imgui.checkbox( "Pause", animation_paused) clicked_camera, camera.r = imgui.slider_float("Camera Radius", camera.r, 10, 1000.0) clicked_animation_time_multiplier, animation_time_multiplier = imgui.slider_float( "Sim Speed", animation_time_multiplier, 0.1, 10.0) if imgui.button("Restart"): animation_time = 0.0 if imgui.tree_node("From World Space, Against Arrows, Read Bottom Up", imgui.TREE_NODE_DEFAULT_OPEN): if imgui.tree_node("Paddle 1->World", imgui.TREE_NODE_DEFAULT_OPEN): imgui.text("f_paddle1_to_world(x) = ") imgui.text(" = (") imgui.same_line() if highlighted_button("T", 5, animation_time): animation_time = 5.0
def make_gui(self, width, height): imgui.begin("Lighting", True) imgui.collapsing_header("Shadows") imgui.indent() ch, val = imgui.checkbox("Render Shadows", self.scene.shadowsEnabled) if ch: self.scene.shadowsEnabled = val if not val: self.scene.shadows.clear() ch, val = imgui.slider_float("Shadow Strength", self.lightingStage.shadowStrength, 0, 1) if ch: self.lightingStage.shadowStrength = val ch, val = imgui.slider_int("Shadows Update Frequency", self.scene.shadows.exponent, 1, 10) if ch: self.scene.shadows.exponent = val ch, val = imgui.slider_float("Shadows range", self.scene.shadows.rng, 0.01, 20) if ch: self.scene.shadows.rng = val imgui.unindent() imgui.collapsing_header("Ambient Occlusion") imgui.indent() ch, val = imgui.slider_float("Occlusion Strength", self.lightingStage.occlusionStrength, 0, 1) if ch: self.lightingStage.occlusionStrength = val ch, val = imgui.slider_float( "SSAO blur radius", self.lightingStage.SSAOBlurAmount, 0, 0.01, display_format="%.4f", ) if ch: self.lightingStage.SSAOBlurAmount = val ch, val = imgui.slider_int("SSAO Samples", self.lightingStage.SSAOSamples, 0, 20) if ch: self.lightingStage.SSAOSamples = val ch, val = imgui.slider_float("SSAO Radius", self.lightingStage.SSAORadius, 0, 2) if ch: self.lightingStage.SSAORadius = val ch, val = imgui.slider_float("SSAO Min Cutoff", self.lightingStage.SSAOMin, 0, 1) if ch: self.lightingStage.SSAOMin = val ch, val = imgui.slider_float("SSAO Max Cutoff", self.lightingStage.SSAOMax, 0, 1) if ch: self.lightingStage.SSAOMax = val imgui.unindent() imgui.collapsing_header("Raytracing") imgui.indent() ch, val = imgui.slider_int("Raytrace Count", self.lightingStage.raytraceCount, 0, 100) if ch: self.lightingStage.raytraceCount = val ch, val = imgui.slider_float("Raytrace Strength", self.lightingStage.raytraceStrength, 0, 1) if ch: self.lightingStage.raytraceStrength = val imgui.unindent() imgui.collapsing_header("Other") imgui.indent() ch, val = imgui.slider_float("Ambient light strength", self.lightingStage.ambientStrength, 0, 1) if ch: self.lightingStage.ambientStrength = val ch, val = imgui.slider_float("Sun Intesnity", self.lightingStage.sunIntensity, 0, 1) if ch: self.lightingStage.sunIntensity = val ch, val = imgui.slider_float("Specularity", self.lightingStage.specularity, 1, 10000, power=10) if ch: self.lightingStage.specularity = val imgui.unindent() imgui.end()
def rom_list(collections, console_selected, prefix='A', checkbox_extract=False): # clear both buffers imguihelper.clear() _nx.gfx_set_mode(TILED_DOUBLE) clear_terminal() imguihelper.initialize() renderer = NXRenderer() # TODO fetcing indicator roms = fetch_roms(collections[console_selected], prefix) # create collection rom folder directory = "Roms" parent_dir = "sdmc:/" path = os.path.join(parent_dir, directory, console_selected) try: os.makedirs(path, exist_ok=True) except OSError as error: print("Directory '%s' can not be created" % path) os.chdir(path) dir_content = os.listdir() while True: renderer.handleinputs() imgui.new_frame() width, height = renderer.io.display_size imgui.set_next_window_size(width, height) imgui.set_next_window_position(0, 0) imgui.begin("", flags=imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_SAVED_SETTINGS) imgui.begin_group() imgui.push_style_color(imgui.COLOR_BUTTON, *MENU_BUTTON_COLOR_SELECTED) if imgui.button("< Back", width=70, height=50): main(collections) imgui.pop_style_color(1) imgui.same_line(spacing=50) _, checkbox_extract = imgui.checkbox("EXTRACT .ZIP AFTER DOWNLOAD", checkbox_extract) imgui.text("Collection: " + console_selected) imgui.new_line() for letter in '#' + string.ascii_uppercase: button_color = MENU_BUTTON_COLOR_SELECTED if prefix == letter else MENU_BUTTON_COLOR imgui.same_line() imgui.push_style_color(imgui.COLOR_BUTTON, *button_color) if imgui.button(letter, width=28, height=28): rom_list(collections, console_selected, letter, checkbox_extract) imgui.pop_style_color(1) imgui.new_line() imgui.begin_child("region", -0, -0, border=True) for rom in roms: folder_name = os.path.splitext(rom['title'])[0] is_downloaded = any(x in dir_content for x in [rom['title'], folder_name]) button_color = ROM_COLOR_DOWNLOADED if is_downloaded else ROM_COLOR imgui.push_style_color(imgui.COLOR_BUTTON, *button_color) if imgui.button(rom['title'] + " " + rom['size'], width=1240, height=30): download(rom, console_selected, checkbox_extract) imgui.pop_style_color(1) imgui.end_child() imgui.end_group() imgui.end() imgui.render() renderer.render() renderer.shutdown()
def render_plugins_ui(window): "Draw UI windows for all plugins active for the current drawing." if not window.drawing: return drawing = window.drawing deactivated = set() for name, args in window.drawing.active_plugins.items(): plugin, sig = window.plugins[name] _, opened = imgui.begin(f"{ name } ##{ drawing.path or drawing.uuid }", True) if not opened: deactivated.add(name) imgui.columns(2) for param_name, param_sig in islice(sig.items(), 4, None): if param_sig.annotation == inspect._empty: continue imgui.text(param_name) imgui.next_column() default_value = args.get(param_name) if default_value is not None: value = default_value else: value = param_sig.default label = f"##{param_name}_val" if param_sig.annotation == int: changed, args[param_name] = imgui.drag_int(label, value) elif param_sig.annotation == float: changed, args[param_name] = imgui.drag_float(label, value) elif param_sig.annotation == str: changed, args[param_name] = imgui.input_text(label, value, 20) elif param_sig.annotation == bool: changed, args[param_name] = imgui.checkbox(label, value) imgui.next_column() imgui.columns(1) texture_and_size = getattr(plugin, "texture", None) if texture_and_size: texture, size = texture_and_size w, h = size ww, wh = imgui.get_window_size() scale = max(1, (ww - 10) // w) imgui.image(texture.name, w * scale, h * scale, border_color=(1, 1, 1, 1)) if hasattr(plugin, "ui"): result = plugin.ui(oldpaint, imgui, window.drawing, window.brush, **args) if result: args.update(result) last_run = getattr(plugin, "last_run", 0) period = getattr(plugin, "period", None) t = time() # TODO I've seen more readable if-statements in my days... if callable(plugin) and ((period and t > last_run + period) or (not period and imgui.button("Execute"))): plugin.last_run = t try: result = plugin(oldpaint, imgui, window.drawing, window.brush, **args) if result: args.update(result) except Exception: # We don't want crappy plugins to ruin everything # Still probably probably possible to crash opengl though... logger.error(f"Plugin {name}: {format_exc()}") imgui.button("Help") if imgui.begin_popup_context_item("Help", mouse_button=0): if plugin.__doc__: imgui.text(inspect.cleandoc(plugin.__doc__)) else: imgui.text("No documentation available.") imgui.end_popup() imgui.end() for name in deactivated: window.drawing.active_plugins.pop(name, None)
def onDrawGuiCallback(self, *args, **kw): if self.window_visable: try: if imgui.begin('AutoLoot {0} - {1}##Entity_mainwindow'.format(autoloot.__version__, autoloot.__author__), (600,350)): # button bar if imgui.checkbox('Enable Auto-Loot', self.enabled_auto_loot): self.enabled_auto_loot = not self.enabled_auto_loot if imgui.collapsingHeader('Available Loot ({0} items)'.format(len(self.bot.items))): imgui.columns(4) for item in self.bot.items: if not item: continue imgui.text(item.roleName) imgui.nextColumn() if item.__module__ == 'DroppedItem': try: imgui.text('Lootable' if item._checkPickItem(self.bot.p) else 'Not Lootable') except AttributeError: imgui.text('Not _checkPickItem') else: imgui.text('Openable?') imgui.nextColumn() imgui.text('{0}'.format(self.bot.p.position.distTo(item.position))) imgui.nextColumn() if imgui.button('Go To {0}##NavToEntity'.format(item.__module__)): nav.moveToEntityPathFind(item) imgui.nextColumn() imgui.separator() imgui.columns(1) if imgui.collapsingHeader('Debug All Entities'): for entity_name, entities in sorted(self.bot.entities.iteritems()): for entity in entities: imgui.columns(5) imgui.separator() imgui.text('{0}'.format(entity_name)) imgui.nextColumn() imgui.text('{0}'.format(entity.id)) imgui.nextColumn() if entity_name == 'DroppedItem' and hasattr(entity, '_checkPickItem') and entity._checkPickItem(self.bot.p): imgui.text('{0}'.format('Lootable')) elif not entity_name == 'DroppedItem': imgui.text('No Data Available') else: imgui.text('Not your Loot!') imgui.nextColumn() if entity and hasattr(entity, 'position') and self.bot.p and hasattr(self.bot.p, 'position'): imgui.text('{0}'.format(self.bot.p.position.distTo(entity.position))) else: imgui.text('No Position Information') imgui.nextColumn() if imgui.button('NavToEntity##NavToEntity'): nav.moveToEntityPathFind(entity) imgui.nextColumn() imgui.columns(1) imgui.end() except Exception: import traceback for line in traceback.format_exc().splitlines(): roplus.log(line) self.window_visable = False