Beispiel #1
0
    def on_draw(self):
        imgui.create_context()

        imgui.new_frame()

        imgui.begin("FrameBuffer", True)
        fbs = [
            o for o in gc.get_referrers(FrameBuffer)
            if isinstance(o, FrameBuffer)
        ]
        gl.glClearColor(0, 0, 0, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        clicked, self.current_framebuffer = imgui.combo(
            "FrameBuffer", self.current_framebuffer, [str(fb) for fb in fbs])

        fb = fbs[self.current_framebuffer]
        w, h = fb.size
        for name, tex in fb.textures.items():
            imgui.text(name)
            imgui.image(tex.name, 200, 200 * h / w)
        imgui.end()

        imgui.render()
        imgui.end_frame()

        data = imgui.get_draw_data()
        if data:
            self.imgui_renderer.render(imgui.get_draw_data())
    def update(self):
        bitmap = self._renderer.bitmap
        if bitmap is None:
            return

        imgui.begin("Tiny Renderer")

        imgui.image(bitmap.get_texture_id(), bitmap.get_width(),
                    bitmap.get_height())
        imgui.end()

        imgui.begin("Rendering")
        _, self._render_mode = imgui.combo("Rendering Mode", self._render_mode,
                                           self._render_mode_captions)
        _, self._light_mode = imgui.combo("Lighting Mode", self._light_mode,
                                          self._light_mode_captions)

        imgui.separator()
        if imgui.button("Render"):
            t = time.time()
            self.on_click_render()
            self._time_to_render = time.time() - t

        imgui.label_text("", f"Time to render: {self._time_to_render: .2f}s")
        imgui.separator()

        imgui.end()
Beispiel #3
0
async def show_pleple_window(name, plot_info, multi_resolution_signals,
                             plot_gl_resources, plot_gl_canvas) -> IMGui[None]:
    with window(name):
        window_width, window_height = im.get_content_region_available()
        window_width, window_height = int(window_width), int(window_height)

        if (window_width, window_height) != (plot_gl_canvas.width_px,
                                             plot_gl_canvas.height_px):
            print("\t### resizing canvas  {} -> {}".format(
                (plot_gl_canvas.width_px, plot_gl_canvas.height_px),
                (window_width, window_height)),
                  flush=True)
            del plot_gl_canvas
            plot_gl_canvas = aplt.init_plot_canvas(window_width, window_height)
            await emit(___new_canvas_(plot_gl_canvas))

        canvas_width = plot_gl_canvas.width_px
        canvas_height = plot_gl_canvas.height_px

        should_redraw = True
        if should_redraw:
            aplt.draw_plot_to_canvas_multires(
                plot_gl_canvas,
                plot_info,
                multi_resolution_signals,
                plot_gl_resources,
                line_color=aplt.WHITE,
                background_color=aplt.TRANSPARENT_BLACK)

        im.image(plot_gl_canvas.texture_id,
                 canvas_width,
                 canvas_height,
                 uv0=(0, 1),
                 uv1=(1, 0))
Beispiel #4
0
    def render_timeline(self):
        imgui.begin("timeline")
        tstamp = self.frame['tstamp']
        if imgui.button("<"):
            self.playing = False
            if self.i > 0:
                self.loadframe(self.i - 1)
        imgui.same_line()
        if self.playing:
            if (self.i == len(self.ts) - 1) or imgui.button("stop"):
                self.playing = False
            elif time.time() >= self.ts[self.i + 1] - self.t0:
                self.nextframe()
        elif imgui.button("play"):
            self.playing = True
            self.t0 = tstamp - time.time()
        imgui.same_line()
        if imgui.button(">"):
            self.playing = False
            self.nextframe()
        tsfrac = tstamp - int(tstamp)
        tstring = time.strftime(
            "%H:%M:%S.", time.localtime(tstamp)) + "%02d" % (tsfrac * 100)
        imgui.same_line()
        imgui.text(tstring)

        w = imgui.get_window_width()
        imgui.image(self.frametexid, w, 480 * w / 640)

        changed, i = imgui.slider_int("frame", self.i, 0,
                                      self.scanner.num_frames() - 1)
        if changed:
            self.playing = False
            self.loadframe(i)
        imgui.end()
Beispiel #5
0
    def render_ui(self):
        """Render the UI"""
        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.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

        # Create window with the framebuffer image
        imgui.begin("Custom window with Image", True)
        # Create an image control by passing in the OpenGL texture ID (glo)
        # and pass in the image size as well.
        # The texture needs to he registered using register_texture for this to work
        imgui.image(self.fbo.color_attachments[0].glo, *self.fbo.size)
        imgui.end()

        imgui.render()
        self.imgui.render(imgui.get_draw_data())
Beispiel #6
0
    def render_timeline(self):
        imgui.begin("timeline")
        tstamp = self.frame['tstamp']
        if imgui.button("<"):
            self.playing = False
            if self.i > 0:
                self.loadframe(self.i - 1)
        imgui.same_line()
        if self.playing:
            if (self.i
                    == self.scanner.num_frames() - 1) or imgui.button("stop"):
                self.playing = False
            elif time.time() >= self.ts[self.i + 1] - self.t0:
                self.nextframe()
        elif imgui.button("play"):
            self.playing = True
            self.t0 = tstamp - time.time()
        imgui.same_line()
        if imgui.button(">"):
            self.playing = False
            self.nextframe()
        tsfrac = tstamp - int(tstamp)
        tstring = time.strftime(
            "%H:%M:%S.", time.localtime(tstamp)) + "%02d" % (tsfrac * 100)
        imgui.same_line()
        imgui.text(tstring)

        w = imgui.get_window_width()
        if self.show_frontview:
            imgui.image(self.fronttexid, w, w / 2)  # 2:1 aspect for front view
        else:  # 4:3 aspect
            imgui.image(self.frametexid, w, 3 * w / 4)

        if self.acts is not None:
            imgui.plot_lines("activations", self.acts)

        nCtrlAngles = (len(self.controlstate[self.i]) - 14) // 3
        cc = self.controlstate[self.i][-nCtrlAngles:]
        imgui.plot_lines("control costs", np.clip(cc, 0, 100))

        # make a histogram of expected cone locations
        if self.acts is not None:
            hist = np.zeros(len(self.acts) * 2, np.float32)
            np.add.at(hist, self.frame['c0'], 1)
            np.add.at(hist, self.frame['c1'], -1)
            hist = np.cumsum(hist)
            hist = hist[:len(self.acts)] + hist[-len(self.acts):]
            imgui.plot_lines("expected cone locations", hist)

        changed, i = imgui.slider_int("frame", self.i, 0,
                                      self.scanner.num_frames() - 1)
        if changed:
            self.playing = False
            self.loadframe(i)
        imgui.end()
Beispiel #7
0
    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()
Beispiel #8
0
 def draw(self):
     imgui.begin("Example: tooltip")
     imgui.button("Click me!")
     if imgui.is_item_hovered():
         imgui.begin_tooltip()
         imgui.text("This button is clickable.")
         imgui.text("This button has full window tooltip.")
         texture_id = imgui.get_io().fonts.texture_id
         imgui.image(texture_id, 512, 64, border_color=(1, 0, 0, 1))
         imgui.end_tooltip()
     imgui.end()
Beispiel #9
0
 def vanilla_view_props(self):
     # Vanilla Render View
     expanded0, visible = imgui.collapsing_header(
         'Raw Scene', self.GUI_STATE.renderprop.isvisible)
     if expanded0:
         imgui.image(self.GUI_STATE.renderprop.img, 256, 256, (0, 1),
                     (1, 0), border_color=(0.5, 0.3, 0.2, 1.0))
         changed, self.GUI_STATE.renderprop.gamma = imgui.input_float(
             ' : Gamma', self.GUI_STATE.renderprop.gamma)
         # self.SHADER.frame_shader.attach()
         self.SHADER.frame_shader.putDataInUniformLocation(
             'gamma', self.GUI_STATE.renderprop.gamma)
Beispiel #10
0
    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("Image example")
        imgui.image(self.texture.glo, *self.texture.size)
        imgui.end()

        imgui.end_frame()

        imgui.render()

        self.renderer.render(imgui.get_draw_data())
Beispiel #11
0
def zoomtip(imtex, imdim, mag=1.0):
    if imgui.is_item_hovered():
        w, h = imgui.get_window_size()
        h = imdim[0] * w / imdim[1]
        rectmin = imgui.get_item_rect_min()
        mousepos = imgui.get_mouse_pos()
        u = float(mousepos[0] - rectmin[0]) / w
        v = float(mousepos[1] - rectmin[1]) / h
        imgui.begin_tooltip()
        tw = 32. / imdim[1] / mag
        th = 32. / imdim[0] / mag
        imgui.image(imtex, 64, 64, uv0=(u - tw, v - th), uv1=(u + tw, v + th))
        dl = imgui.get_window_draw_list()
        rm = imgui.get_item_rect_min()
        col = imgui.get_color_u32_rgba(1, 1, 0, 1)
        dl.add_line(rm[0], rm[1] + 32, rm[0] + 64, rm[1] + 32, col)
        dl.add_line(rm[0] + 32, rm[1], rm[0] + 32, rm[1] + 64, col)
        imgui.end()
Beispiel #12
0
    def Vplan(self):
        w, h = imgui.get_window_size()
        h = self.V.shape[1] * w / self.V.shape[2]
        _, self.lookstep = imgui.slider_float("lookahead step",
                                              self.lookstep,
                                              0,
                                              1,
                                              power=1.5)
        imgui.image(self.Vtex[int(48 * self.car.theta / np.pi % 96)], w, h)
        shots = []
        c = self.car
        bestk = None
        for i in range(50):
            k, v, c = self.bestkv(c, self.lookstep)
            if bestk is None:
                bestk = k
            shots.append([c.x, c.y])
        self.shots = np.array([shots])

        return bestk
Beispiel #13
0
def drawMagnifiedRegion(lowerLeft, size, magFactor):
    global g_screenCaptureTexture
    glBindBuffer(GL_PIXEL_PACK_BUFFER, 0)
    glPixelStorei(GL_PACK_ALIGNMENT, 1)
    pixel_data = glReadPixels(lowerLeft[0], lowerLeft[1], size[0], size[1],
                              GL_BGR, GL_UNSIGNED_BYTE)

    if not g_screenCaptureTexture:
        g_screenCaptureTexture = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, g_screenCaptureTexture)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    glBindTexture(GL_TEXTURE_2D, g_screenCaptureTexture)
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, size[0], size[1], 0, GL_BGR,
                 GL_UNSIGNED_BYTE, pixel_data)
    glBindTexture(GL_TEXTURE_2D, 0)

    imgui.image(g_screenCaptureTexture, size[0] * magFactor,
                size[1] * magFactor, (0, 1), (1, 0), (1, 1, 1, 1),
                (1, 1, 1, 1))
Beispiel #14
0
    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()
Beispiel #15
0
    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: tooltip")
        imgui.button("Click me!")
        if imgui.is_item_hovered():
            imgui.begin_tooltip()
            imgui.text("This button is clickable.")
            imgui.text("This button has full window tooltip.")
            texture_id = imgui.get_io().fonts.texture_id
            imgui.image(texture_id, 512, 64, border_color=(1, 0, 0, 1))
            imgui.end_tooltip()
        imgui.end()

        imgui.end_frame()

        imgui.render()

        self.renderer.render(imgui.get_draw_data())
Beispiel #16
0
    def update(dt, field_texture):
        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.show_test_window()

        imgui.begin("Custom window", True)
        imgui.image(field_texture.id,
                    field_texture.width,
                    field_texture.height,
                    border_color=(1, 0, 0, 1))
        imgui.end()
Beispiel #17
0
    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())
Beispiel #18
0
def main():
    loadFlightData()

    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()

        # get the style object and edit the object to make it look decent with GLFW
        style = imgui.get_style()
        style.window_rounding = 0
        style.frame_rounding = 0

        #create the main ImGuI frame to then use to display the actual GUI on
        imgui.new_frame()

        flags = imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_COLLAPSE | imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_MENU_BAR

        imgui.set_next_window_size(window_width, window_height)
        imgui.set_next_window_position(0, 0)

        # Start the beginning of the ImGui window, drone flight logger being an ID
        imgui.begin("Drone Flight Logger", False, flags=flags)

        if imgui.button("Add new Flight"):
            imgui.open_popup("test")

        imgui.same_line()

        imgui.text("Total Flight Time: " + str(flights.getTotalFlightTime()) +
                   "h")

        imgui.same_line()

        imgui.text("| Total Batteries Used: " +
                   str(flights.getTotalBatteriesUsed()))

        # Main Menu Bar Code
        mainMenuBar()

        # create a child window in the inital window to divide the window up so there can be a preview on the left
        imgui.begin_child("flight_selector",
                          width=window_width / 5 * 2,
                          border=True)

        # loop through all flights and assign flight as the key value
        for flight in flights.getFlights():
            # get the flight data based off the flight name
            flight_data = flights.getFlights()[flight]
            # if the flight location is in the List variable of currently selected locations show it
            if currentSelectedLocations[flight_data.getLocationName()]:
                # flight drop down code, passing in the flight name and flight data
                flightDropDown(flight, flight_data)

        imgui.end_child()

        imgui.same_line()

        # create the preview sidepane of the main window
        imgui.begin_child("flight_info", border=True)

        # if there is the key preview in currentviewingflightdata show the image. Done this way as I will eventually add in the flight location and other stats to the sidepane as well
        if "preview" in currentViewingFlightData:
            imgui.image(currentViewingFlightData["preview"]['image'],
                        currentViewingFlightData["preview"]['width'] / 6,
                        currentViewingFlightData["preview"]['height'] / 6)

        imgui.end_child()

        if imgui.begin_popup_modal("test")[0]:
            addNewFlightData["date"] = imgui.input_text(
                "Flight date", addNewFlightData["date"], 2046)[1]
            addNewFlightData["batteries_used"] = imgui.input_int(
                'Batteries used', addNewFlightData["batteries_used"])[1]
            addNewFlightData["flight_time"] = imgui.input_int(
                'Flight time in minutes', addNewFlightData["flight_time"])[1]
            addNewFlightData["location_name"] = imgui.input_text(
                "Flight location", addNewFlightData["location_name"], 2046)[1]
            addNewFlightData["copyFromFolder"] = imgui.input_text(
                "Folder with new flight media",
                addNewFlightData["copyFromFolder"], 2046)[1]

            if imgui.button("test"):
                handleAddNewFlight()
                imgui.close_current_popup()

            # imgui.text("Select an option:")
            # imgui.separator()
            # imgui.selectable("One")
            # imgui.selectable("Two")
            # imgui.selectable("Three")
            imgui.end_popup()

        imgui.end()

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Beispiel #19
0
def main():

    # Theme Index
    THEME_INDEX = 2

    # window visible params
    bShowInfoPopUp = False
    bShowFiles = True
    bShowParsePdf = True
    bShowParserStatics = True

    bShowImg = False
    bShowTestWindow = True

    #delete cache files
    if os.path.isfile('ParseResult.log'):
        os.remove('ParseResult.log')
    if os.path.isfile('ManualFiles.log'):
        os.remove('ManualFiles.log')
    if os.path.isfile('Cluster.png'):
        os.remove('Cluster.png')

    pygame.init()
    size = 1280, 720  # 720p
    # size = 1920, 1080 # 1080p

    pygame.display.set_mode(
        size, pygame.DOUBLEBUF | pygame.OPENGL | pygame.RESIZABLE)
    pygame.display.set_caption("PDF成績單解析器")

    clock = pygame.time.Clock()

    favicon = pygame.image.load('asset\\Logo.png')
    pygame.display.set_icon(favicon)

    imgui.create_context()

    impl = PygameRenderer()

    io = imgui.get_io()
    smallfont = io.fonts.add_font_from_file_ttf(
        "asset\\NotoSansTC-Black.otf", 12,
        io.fonts.get_glyph_ranges_chinese_full())
    normalfont = io.fonts.add_font_from_file_ttf(
        "asset\\NotoSansTC-Black.otf", 16,
        io.fonts.get_glyph_ranges_chinese_full())
    largefont = io.fonts.add_font_from_file_ttf(
        "asset\\NotoSansTC-Black.otf", 28,
        io.fonts.get_glyph_ranges_chinese_full())
    io.fonts.add_font_default()
    impl.refresh_font_texture()
    io.display_size = size

    style = imgui.get_style()
    if THEME_INDEX == 1:
        GF.SetCustomStyle1(style)
    elif THEME_INDEX == 2:
        GF.SetCustomStyle2(style)
    elif THEME_INDEX == 3:
        GF.SetCustomStyle3(style)

    CV = 0
    MV = 200
    while 1:
        clock.tick(30)  # fixed 15 fps

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # remove cache here
                sys.exit()
            if event.type == pygame.VIDEORESIZE:
                print('resize is triggered!')

            # shortcut bindings
            if event.type == pygame.KEYDOWN:
                if event.mod == pygame.KMOD_LCTRL and event.key == pygame.K_q:
                    sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_F1:
                    GF.OpenHelper()

            impl.process_event(event)
        imgui.push_style_var(imgui.STYLE_FRAME_PADDING, (10, 12.5))
        imgui.new_frame()

        # Main menu region
        if imgui.begin_main_menu_bar():
            with imgui.font(normalfont):
                if imgui.begin_menu("設定", True):
                    if imgui.begin_menu(label="主題", enabled=True):
                        if THEME_INDEX == 1:
                            imgui.menu_item("默認", None, True, True)
                        else:
                            c, _ = imgui.menu_item("默認", None, False, True)
                            if c:
                                GF.SetCustomStyle1(style)
                                THEME_INDEX = 1
                        if THEME_INDEX == 2:
                            imgui.menu_item("CorporateGrey", None, True, True)
                        else:
                            c, _ = imgui.menu_item("CorporateGrey", None,
                                                   False, True)
                            if c:
                                GF.SetCustomStyle2(style)
                                THEME_INDEX = 2
                        if THEME_INDEX == 3:
                            imgui.menu_item("Light", None, True, True)
                        else:
                            c, _ = imgui.menu_item("Light", None, False, True)
                            if c:
                                GF.SetCustomStyle3(style)
                                THEME_INDEX = 3
                        imgui.end_menu()

                    clicked_quit, selected_quit = imgui.menu_item(
                        "Quit", "L-Ctrl + Q", False, True)
                    if clicked_quit:
                        sys.exit()
                    imgui.end_menu()

                if imgui.begin_menu("視窗", True):
                    if not bShowFiles:
                        F, _ = imgui.menu_item(label="選擇目錄",
                                               shortcut=None,
                                               selected=False,
                                               enabled=True)
                    else:
                        F, _ = imgui.menu_item(label="選擇目錄",
                                               shortcut=None,
                                               selected=True,
                                               enabled=True)
                    if F:
                        bShowFiles = not bShowFiles
                    if not bShowParsePdf:
                        o, _ = imgui.menu_item(label="解析成績單",
                                               shortcut=None,
                                               selected=False,
                                               enabled=True)
                    else:
                        o, _ = imgui.menu_item(label="解析成績單",
                                               shortcut=None,
                                               selected=True,
                                               enabled=True)
                    if o:
                        bShowParsePdf = not bShowParsePdf
                    if not bShowParserStatics:
                        r, _ = imgui.menu_item(label="解析結果",
                                               shortcut=None,
                                               selected=False,
                                               enabled=True)
                    else:
                        r, _ = imgui.menu_item(label="解析結果",
                                               shortcut=None,
                                               selected=True,
                                               enabled=True)
                    if r:
                        bShowParserStatics = not bShowParserStatics

                    imgui.end_menu()

                if imgui.begin_menu("資訊", True):
                    I, _ = imgui.menu_item("關於",
                                           None,
                                           selected=False,
                                           enabled=True)
                    h, _ = imgui.menu_item("幫助",
                                           shortcut="F1",
                                           selected=False,
                                           enabled=True)
                    if I:
                        bShowInfoPopUp = True

                    if h:
                        GF.OpenHelper()

                    imgui.end_menu()

            #imgui.pop_style_var(1)
            imgui.end_main_menu_bar()

        # Conditional windows
        if bShowFiles:
            imgui.set_next_window_position(0, 35, imgui.ONCE)
            imgui.set_next_window_size(230, 685, imgui.ONCE)
            with imgui.font(normalfont):
                bFileWindow = imgui.begin("選擇目錄",
                                          True,
                                          flags=imgui.WINDOW_NO_RESIZE
                                          | imgui.WINDOW_NO_MOVE
                                          | imgui.WINDOW_NO_COLLAPSE)
                if not bFileWindow[1]:
                    bShowFiles = False
                GE.FileWindow()
                imgui.end()

        if bShowParsePdf:
            imgui.set_next_window_position(230, 35, imgui.ONCE)
            imgui.set_next_window_size(450, 685, imgui.ONCE)
            with imgui.font(normalfont):
                bParsePdf = imgui.begin("解析成績單", True)
                if not bParsePdf[1]:
                    bShowParsePdf = False
                GE.ParsePdfWidget()
                imgui.end()

        if bShowParserStatics:
            imgui.set_next_window_position(680, 35, imgui.ONCE)
            imgui.set_next_window_size(600, 685, imgui.ONCE)
            with imgui.font(normalfont):
                bParserStats = imgui.begin("解析結果", True)
                if not bParserStats[1]:
                    bShowParserStatics = False
                GE.ParserStaticsWidget()
                if os.path.isfile('Cluster.png'):
                    img_info = GF.loadImage('Cluster.png')
                    imgui.image(img_info[0], img_info[1], img_info[2])
                imgui.end()

        if (bShowInfoPopUp):
            imgui.open_popup("資訊")

        imgui.set_next_window_size(600, 300)
        imgui.font(normalfont)
        if imgui.begin_popup_modal(title="資訊", visible=True, flags=0)[0]:
            GE.ProgramInfoPopup()
            imgui.separator()
            bShowInfoPopUp = False
            imgui.end_popup()

        if THEME_INDEX == 1:
            gl.glClearColor(0.1, 0.1, 0.1, 1)  # for default theme
        elif THEME_INDEX == 2:
            gl.glClearColor(0.45, 0.55, 0.6, 1)  # for light theme
        elif THEME_INDEX == 3:
            gl.glClearColor(0.25, 0.25, 0.25, 1.00)

        imgui.pop_style_var()
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        imgui.render()
        impl.render(imgui.get_draw_data())
        pygame.display.flip()

        CV += 1
Beispiel #20
0
 def draw(self):
     imgui.begin(self.title)
     imgui.image(self.texture.glo, *self.texture.size)
     imgui.end()
Beispiel #21
0
 def draw(self):
     imgui.begin("Sprite")
     imgui.image(self.texture.glo, *self.texture.size)
     imgui.end()
Beispiel #22
0
def display_parameter(parameter, editable):
    global slider_indexes
    if parameter.type == "List":
        if len(parameter.list) == 0:
            imgui.text("Empty list")
        else:
            if parameter.id not in slider_indexes:
                slider_indexes[parameter.id] = 0
            changed, values = imgui.slider_int("index", slider_indexes[parameter.id], 0, len(parameter.list)-1)
            if changed:
                slider_indexes[parameter.id] = values
            display_parameter(parameter.list[slider_indexes[parameter.id]], editable)
    if parameter.type == "Image":
        if parameter.image:
            image_to_texture = get_gl_texture(parameter.image, parameter.timestamp)
            # imgui.image(image_texture, image_width, image_height)
            window_width = 256 # imgui.get_window_width()
            display_width = 0
            display_height = 0
            image_width = image_to_texture.gl_widh
            image_height = image_to_texture.gl_height
            if image_width >= image_height:
                display_width = window_width
                display_height = image_height / (image_width/float(display_width))
            else:
                display_height = window_width
                display_width = image_width / (image_height/float(display_height))
            imgui.image(image_to_texture.gl_texture, display_width, display_height)
            imgui.text("width: " + str(parameter.image.width))
            imgui.text("height: " + str(parameter.image.height))
        else:
            imgui.text("No image available - run workflow or connect an image source")
    elif parameter.type == "Rectangle":
        if editable:
            changed, value = imgui.input_float("Left", parameter.left)
            if changed:
                parameter.left = value
            changed, value = imgui.input_float("Top", parameter.top)
            if changed:
                parameter.top = value
            changed, value = imgui.input_float("Right", parameter.right)
            if changed:
                parameter.right = value
            changed, value = imgui.input_float("Bottom", parameter.bottom)
            if changed:
                parameter.left = value
        else:
            imgui.text("Left: " + str(parameter.left))
            imgui.text("Top: " + str(parameter.top))
            imgui.text("Right: " + str(parameter.right))
            imgui.text("Bottom: " + str(parameter.bottom))
    elif parameter.type == "Coordinates":
        if editable:
            changed, value = imgui.input_float("x", parameter.x)
            if changed:
                parameter.x = value
            changed, value = imgui.input_float("y", parameter.y)
            if changed:
                parameter.y = value
        else:
            imgui.text("x: " + str(parameter.x))
            imgui.text("y: " + str(parameter.y))
    elif parameter.type == "Integer": # to do change to "number"
        if editable:
            changed, value = imgui.input_int("Value", parameter.value)
            if changed:
                parameter.value = value
        else:
            imgui.text("Value: " + str(parameter.value))
    elif parameter.type == "Color":
        changed, color = imgui.color_edit4(parameter.id, parameter.r, parameter.g, parameter.b, parameter.a)
        if editable and changed:
            parameter.r = color[0]
            parameter.g = color[1]
            parameter.b = color[2]
            parameter.a = color[3]
    elif parameter.type == "URL":
        changed, textval = imgui.input_text(parameter.id, parameter.url, 1024)
        if editable and changed:
            parameter.url = textval
        if editable:
            if imgui.button("browse..."):
                root = tk.Tk()
                root.withdraw()
                file_path = filedialog.askopenfilename()
                if file_path:
                    parameter.url = file_path
    elif parameter.type == "Text":
        changed, textval = imgui.input_text(parameter.id, parameter.text, 1024)
        if editable and changed:
            parameter.text = textval
Beispiel #23
0
def render_plugins_ui(drawing):
    "Draw UI windows for all plugins active for the current drawing."

    # TODO there's an imgui related crash here somewhere preventing (at least) the
    # voxel plugin from being used in more than one drawing. For now: avoid that.

    if not drawing:
        return

    deactivated = set()

    for name, (plugin, sig, args) in drawing.plugins.items():
        _, opened = imgui.begin(f"{name} {id(drawing)}", True)
        if not opened:
            deactivated.add(name)
            imgui.end()
            continue
        imgui.columns(2)
        for param_name, param_sig in islice(sig.items(), 2, None):
            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))

        last_run = getattr(plugin, "last_run", 0)
        period = getattr(plugin, "period", None)
        t = time()
        if period and t > last_run + period or imgui.button("Execute"):
            plugin.last_run = last_run
            try:
                result = plugin(voxpaint, drawing, **args)
                if result:
                    args.update(result)
            except Exception:
                print_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:
        drawing.plugins.pop(name, None)
    def render(self):

        videowindow, self.open = imgui.begin("Video window {}".format(
            self.filename),
                                             self.open,
                                             flags=imgui.WINDOW_NO_SCROLLBAR)

        w, h = imgui.get_window_size()

        if imgui.APPEARING:
            imgui.set_window_size(400, 300)

        w, h = imgui.core.get_content_region_available()
        w = int(max(w, 0))
        h = int(max(h - 85, 0))

        if not self.open:
            imgui.end()
            self.terminate()
            return

        if self.ctx.update() and w > 0 and h > 0:

            gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.fbo)
            gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture)

            gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, w, h, 0, gl.GL_RGB,
                            gl.GL_UNSIGNED_BYTE, None)

            gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
            gl.glBindTexture(gl.GL_TEXTURE_2D, 0)

            self.ctx.render(flip_y=False,
                            opengl_fbo={
                                'w': w,
                                'h': h,
                                'fbo': self.fbo
                            })

        try:
            imgui.text("Filename: {} fbo: {} tex: {}".format(
                self.mpv.filename, self.fbo, self.texture))
        except:
            imgui.text("Filename: {} fbo: {} tex: {}".format(
                self.mpv.filename, self.fbo, self.texture))

        try:
            imgui.text("{0:.2f}s/{1:.2f}s ({2:.2f}s remaining)".format(
                self.mpv.time_pos, self.mpv.duration,
                self.mpv.playtime_remaining))
        except:
            imgui.text("Loading...")

        imgui.image(self.texture, w, h)

        imgui.push_item_width(-1)

        changed, values = imgui.slider_float("##Playback Percentage",
                                             *self.playbackPos,
                                             min_value=0.0,
                                             max_value=100.0,
                                             format="Playback Percentage %.0f",
                                             power=1.0)

        if changed and values:
            try:
                self.mpv.command('seek', values, 'absolute-percent')
            except:
                pass
            self.playbackPos = (values, )
        elif self.mpv.percent_pos:
            self.playbackPos = (self.mpv.percent_pos, )

        changed, values = imgui.slider_float("##Volume",
                                             *self.volume,
                                             min_value=0.0,
                                             max_value=100.0,
                                             format="Volume %.0f",
                                             power=1.0)

        if changed:
            self.mpv.volume = values
            self.volume = (values, )
        elif self.mpv.volume:
            self.volume = (self.mpv.volume, )

        imgui.end()
Beispiel #25
0
 def draw(self):
     imgui.image(self.texture_id, self.width, self.height)
     print(self.texture_id)
Beispiel #26
0
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)
Beispiel #27
0
def main():
    pygame.init()

    size = 800, 600

    pygame.display.set_mode(size, pygame.DOUBLEBUF | pygame.OPENGL)
    pygame.display.set_caption("GBDev tool window")
    io = imgui.get_io()
    io.fonts.add_font_default()
    io.display_size = size

    renderer = PygameRenderer()

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            renderer.process_event(event)

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("Menu", True):
                open_gbtd, selected_none = imgui.menu_item("Open GBTD", None, False, True)
                open_gbtk, selected_none = imgui.menu_item("Open GBTK", None, False, True)
                
                export_json, selected_none = imgui.menu_item("Export Default Json", None, False, True)

                clicked_quit, selected_quit = imgui.menu_item("Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)
                if open_gbtd:
                    os.system("wine tools/GBTD/GBTD.EXE &")
                if open_gbtk:
                    os.system("wine tools/GBTK.exe &")
                if export_json:
                    tools.json2c.default_use()
                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.begin("Data", True)

        img_path = "data/img"
        onlyfiles = [f for f in listdir(img_path) if isfile(join(img_path, f))]
        #print(onlyfiles)
        for file in onlyfiles:
            imgui_image_menu(img_path+"/"+file)

        imgui.end()

        imgui.begin("Images", True)

        imgs_id = []
        for img_filename in onlyfiles:
            if img_filename.split(".")[-1] == "png":
                imgs_id.append((img_path+"/"+img_filename, img_manager.load_image(img_path+"/"+img_filename)))

        for img in imgs_id:
            img_size = img_manager.get_image_size(img[0])
            if img[1] is not 0 and img_size is not ():
                imgui.image(img[1], img_size[0]*2, img_size[1]*2, (0,1), (1,0))
                imgui.same_line()


        imgui.end()
        # note: cannot use screen.fill((1, 1, 1)) because pygame's screen
        #       does not support fill() on OpenGL sufraces
        gl.glClearColor(1, 1, 1, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        imgui.render()

        pygame.display.flip()