Ejemplo n.º 1
0
 def __init__(self, name, pos=imgui.Vec2(0, 0)):
     self.id = None
     self.name = name
     self.pos = pos
     self.size = imgui.Vec2(0, 0)
     self.inputs = {}
     self.outputs = {}
Ejemplo n.º 2
0
def ImGuiLister_ShowStandalone():
    ImGuiImageLister.window_size = imgui.Vec2(1000, 800)
    ImGuiImageLister.position = imgui.Vec2(0, 0)
    ImGuiImageLister.opened = True
    ImGuiImageLister.max_size = True

    run(_none_gui_loop, Params(win_title="ImGuiLister", windowed_full_screen=True))
Ejemplo n.º 3
0
 def __init__(self):
     self.images_info = OrderedDict()
     self.current_image = ""
     self.opened = False
     self.never_shown = True
     self.listbox_width = 240
     self.position = imgui.Vec2(500, 50)
     self.window_size = imgui.Vec2(1000, 800)
     self.max_size = False
Ejemplo n.º 4
0
def image_size_fit_in_gui(image_size, gui_size, can_make_bigger=False):
    # type: (imgui.Vec2, imgui.Vec2, bool) -> imgui.Vec2
    if image_size.x <= gui_size.x and image_size.y <= gui_size.y and not can_make_bigger:
        return image_size
    else:
        k_item = image_size.x / image_size.y
        k_gui = gui_size.x / gui_size.y
        if k_item > k_gui:
            return imgui.Vec2(gui_size.x,
                              image_size.y / image_size.x * gui_size.x)
        else:
            return imgui.Vec2(image_size.x / image_size.y * gui_size.y,
                              gui_size.y)
Ejemplo n.º 5
0
def example_mosaic(iggraph):
    # Example
    node_load_image = iggraph.create_node("Load Image", imgui.Vec2(200,100))
    node_load_image2 = iggraph.create_node("Load Image", imgui.Vec2(200,500))
    node_relative_coord = iggraph.create_node("Relative Coords", imgui.Vec2(400,400))
    node_pixel_color = iggraph.create_node("Pixel Color", imgui.Vec2(600,400))
    node_colorize_image = iggraph.create_node("Colorize Image", imgui.Vec2(800,400))
    node_grid = iggraph.create_node("Grid Rectangles", imgui.Vec2(400,50))
    node_for_each = iggraph.create_node("For Each Loop", imgui.Vec2(600,100))
    node_draw_image = iggraph.create_node("Draw Image", imgui.Vec2(600,300))
    node_grid.inputs["number of horizontal cells"].value = 10
    node_grid.inputs["number of vertical cells"].value = 20
    node_load_image.inputs["url"].url = "c:\\tmp\\rainbow.jpg"
    iggraph.links.append(NodeLink(node_load_image.outputs["loaded image"], node_grid.inputs["source image"]))
    iggraph.links.append(NodeLink(node_grid.outputs["cells"], node_for_each.inputs["List to iterate"]))
    iggraph.links.append(NodeLink(node_load_image.outputs["loaded image"], node_for_each.inputs["Input1"]))
    iggraph.links.append(NodeLink(node_for_each.outputs["Element"], node_relative_coord.inputs["rectangle"]))
    iggraph.links.append(NodeLink(node_relative_coord.outputs["coords"], node_pixel_color.inputs["coords"]))
    iggraph.links.append(NodeLink(node_load_image.outputs["loaded image"], node_pixel_color.inputs["image"]))
    iggraph.links.append(NodeLink(node_pixel_color.outputs["pixel color"], node_colorize_image.inputs["white"]))
    iggraph.links.append(NodeLink(node_load_image2.outputs["loaded image"], node_colorize_image.inputs["source image"]))
    iggraph.links.append(NodeLink(node_for_each.outputs["Element"], node_draw_image.inputs["coordinates"]))
    iggraph.links.append(NodeLink(node_for_each.outputs["Output1"], node_draw_image.inputs["source image"]))
    iggraph.links.append(NodeLink(node_colorize_image.outputs["colorized image"], node_draw_image.inputs["image to past"]))
    iggraph.links.append(NodeLink(node_draw_image.outputs["composed image"], node_for_each.inputs["Input1"]))
Ejemplo n.º 6
0
 def from_json(self, json):
     json_input_parameters = json["inputs"]
     for input_name in self.inputs:
         parameter_json = json_input_parameters[input_name]
         self.inputs[input_name].from_json(parameter_json)
     json_output_parameters = json["outputs"]
     for output_name in self.outputs:
         parameter_json = json_output_parameters[output_name]
         self.outputs[output_name].from_json(parameter_json)
     pos = imgui.Vec2(json["pos"]["x"], json["pos"]["y"])
     self.pos = pos
     size = imgui.Vec2(json["size"]["x"], json["size"]["y"])
     self.size = size
     self.id = json["id"]
Ejemplo n.º 7
0
def mouse_position_last_image():
    io = imgui.get_io()
    mouse = io.mouse_pos
    rect_min = imgui.get_item_rect_min()
    mouse_relative = imgui.Vec2(mouse.x - rect_min.x, mouse.y - rect_min.y)
    if not _is_in_last_image(mouse_relative):
        return None
    else:
        return mouse_relative
Ejemplo n.º 8
0
 def get_output_slot_pos(self, parameter):
     slot_no = 0
     for output_parameter in self.outputs:
         if output_parameter == parameter.id:
             break
         slot_no = slot_no + 1
     return imgui.Vec2(
         self.pos.x + self.size.x, self.pos.y + self.size.y *
         ((slot_no + 1) / (len(self.outputs) + 1)))
Ejemplo n.º 9
0
 def _show_image(self):
     if self.current_image in self.images_info:
         imgui.begin_group()
         if imgui.button("X"):
             self.images_info.pop(self.current_image)
             self.current_image = ""
         else:
             image_info = self.images_info[self.current_image]
             if image_info.additional_legend != "":
                 imgui.same_line()
                 imgui.text(image_info.additional_legend)
             img = image_info.image
             image_size = imgui.Vec2(img.shape[1], img.shape[0])
             image_size = image_size_fit_in_gui(image_size,
                                                self._max_image_size(),
                                                can_make_bigger=True)
             imgui_cv.image_explorer(
                 img,
                 title=self.current_image,
                 width=int(round(image_size.x)),
                 height=int(round(image_size.y)),
                 image_adjustments=image_info.image_adjustments)
         imgui.end_group()
Ejemplo n.º 10
0
async def draw() -> Eff[[ACTIONS], None]:
    global state

    im.show_metrics_window()
    im.show_test_window()

    # ------------------------
    # t_flags = 0
    # t_flags = (
    # 	  im.WINDOW_NO_TITLE_BAR
    # 	| im.WINDOW_NO_MOVE
    # 	| im.WINDOW_NO_RESIZE
    # 	| im.WINDOW_NO_COLLAPSE
    # 	| im.WINDOW_NO_FOCUS_ON_APPEARING
    # 	| im.WINDOW_NO_BRING_TO_FRONT_ON_FOCUS
    # )
    # with window(name="test", flags=t_flags):
    # 	im.button("bloop")
    # 	pos = util.point_offset(im.get_window_position(), im.Vec2(40, 80))
    # 	im.set_next_window_position(pos.x, pos.y)
    # 	with window(name="a window"):
    # 		im.text("I'm a window")

    # 	top_left = im.get_item_rect_min()
    # 	size = im.get_item_rect_size()
    # 	bottom_right = util.point_offset(top_left, size)
    # 	im.text('TL: '+str(top_left))
    # 	im.text('BR: '+str(bottom_right))
    # 	util.add_rect(im.get_window_draw_list(), util.Rect(top_left, bottom_right), (1.,1.,1.,1.))

    debug_log("test_drew", False)
    with window("test") as (expanded, _):
        only_draw_if(expanded)

        debug_log("test_drew", True)  # only_draw_if didn't abort, overwrite
        US = ui['settings']

        opts = ['first', 'second', 'third']
        default_state = ('no_selection', None)

        US.setdefault('selectable_state', default_state)
        US.setdefault('selectable_added', [])
        if not im.is_window_focused():
            US['selectable_state'] = default_state

        changed, selection_changed, selectable_state = double_click_listbox(
            US['selectable_state'], opts)
        if changed:
            US['selectable_state'] = selectable_state

        o_ix = selectable_state[1]
        im.text_colored(
            "[ {!s:<10} ] {}".format(opts[o_ix] if o_ix is not None else "---",
                                     "(!)" if selection_changed else ""),
            *(0.3, 0.8, 0.5))
        im.text("")
        im.text("{!r:<5} {!r:<5} {}".format(changed, selection_changed,
                                            selectable_state))

        if selectable_state[0] == 'double_clicked':
            US['selectable_added'].append(opts[selectable_state[1]])
        im.text(str(US['selectable_added']))

        c = im.is_mouse_clicked()
        dc = im.is_mouse_double_clicked()
        im.text("{!r:<5} {!r:<5} {!r:<5}".format(c, dc, c and dc))
        im.text("focused: " + repr(im.is_window_focused()))

    with window(name="signals"):
        if im.button("load example"):
            await emit(FileAction.Load(filename=example_file_path))

        if len(state.data.signals) > 0:

            def right_pad(s: str, limit: int) -> str:
                n_spaces = max(0, limit - len(s))
                return s + (' ' * n_spaces)

            for sig_id, sig_name in sorted(state.data.signal_names.items(),
                                           key=lambda pair: pair[1]):
                im.text_colored(right_pad(sig_name, 5), 0.2, 0.8, 1)
                im.same_line()
                signal = state.data.signals[sig_id]
                im.text(str(signal))
        else:
            im.text("No signals loaded")

    # -------------------------
    # with window(name="modules"):
    # 	modules = sorted(
    #		rlu.all_modules(dir=pathlib.Path.cwd()),
    #		key=lambda mod: (getattr(mod, '__reload_incarnation__', -1), mod.__name__)
    #	)
    # 	for mod in modules:
    # 		incarnation_text = str(getattr(mod, '__reload_incarnation__', '-'))
    # 		im.text("{mod}[{inc}]".format(mod=mod.__name__, inc=incarnation_text))

    with window(name="settings"):
        ui_settings = ui['settings']
        changed, move = im.checkbox("move plots",
                                    ui_settings['plot_window_movable'])
        if changed:
            ui_settings['plot_window_movable'] = move

        # im.same_line()
        changed, option = str_combo(
            "resample", ui_settings['plot_resample_function'],
            ['numpy_interp', 'scipy_zoom', 'crude_downsample'])
        if changed:
            ui_settings['plot_resample_function'] = option

        # im.same_line()
        changed, option = str_combo("plots", ui_settings['plot_draw_function'],
                                    ['imgui', 'manual'])
        if changed:
            ui_settings['plot_draw_function'] = option

        changed, val = im.slider_float('filter_slider_power',
                                       ui_settings['filter_slider_power'],
                                       min_value=1.,
                                       max_value=5.,
                                       power=1.0)
        if changed:
            ui_settings['filter_slider_power'] = val

        if im.button("reload"):
            await emit(AppRunnerAction.Reload())

        # im.same_line()
        # im.button("bla bla bla")

        # im.same_line()
        # im.button("ple ple ple")

        im.text("state | ")

        im.same_line()
        if im.button("dump##state"):
            await emit(AppStateAction.SaveState)

        im.same_line()
        if im.button("load##state"):
            await emit(AppStateAction.LoadState)

        im.same_line()
        if im.button("reset##state"):
            await emit(AppStateAction.ResetState)

        im.text("history | ")

        im.same_line()
        if im.button("dump##history"):
            await emit(AppStateAction.SaveUserActionHistory)

        im.same_line()
        if im.button("load##history"):
            await emit(AppStateAction.LoadUserActionHistory)

        im.same_line()
        if im.button("reset##history"):
            await emit(AppStateAction.ResetUserActionHistory)

        im.same_line()
        if im.button("run##history"):
            await emit(AppStateAction.RunHistory)

    # TODO: Window positions can theoretically be accessed
    # after being drawn using internal APIs.
    # See:
    #	imgui_internal.h > ImGuiWindow (search "struct IMGUI_API ImGuiWindow")
    #	imgui.cpp        > ImGui::GetCurrentContext()
    #
    # (sort-of pseudocode example)
    #
    # foo_id = None
    #
    # with window("foo"):
    # 	foo_id = GetCurrentWindow().ID
    # 	...
    #
    # ...
    #
    # with window("accessing other windows"):
    # 	windows = imgui.GetCurrentContext().Windows
    # 	foo_win = windows[ windows.find(lambda win: win.ID = foo_id) ]
    # 	im.text( "pos:{}, size:{}".format(foo_win.Pos, foo_win.Size) )

    # ----------------------------
    # await ng.graph_window(state.graph)

    prev_color_window_background = im.get_style().color(
        im.COLOR_WINDOW_BACKGROUND)

    im.set_next_window_position(0, 100)
    with color({im.COLOR_WINDOW_BACKGROUND: (0., 0., 0., 0.05)}), \
      window(name="nodes",
       flags = (
          im.WINDOW_NO_TITLE_BAR
        # | im.WINDOW_NO_MOVE
        # | im.WINDOW_NO_RESIZE
        | im.WINDOW_NO_COLLAPSE
        | im.WINDOW_NO_FOCUS_ON_APPEARING
        | im.WINDOW_NO_BRING_TO_FRONT_ON_FOCUS
       )
      ):
        box_positions = {}
        inputs = ng.get_inputs(state.graph, state.data.box_outputs)

        with color({im.COLOR_WINDOW_BACKGROUND: prev_color_window_background}):

            # source boxes
            for (id_, box_state) in state.source_boxes.items():
                pos = await signal_source_window(box_state, state.data.signals,
                                                 state.data.signal_names)
                box_positions[id_] = pos

            # filter boxes
            for (id_, box_state) in state.filter_boxes.items():
                pos = await filter_box_window(box_state,
                                              ui_settings=ui_settings)
                box_positions[id_] = pos

            # signal plot 1
            for (id_, box_state) in state.plots.items():
                pos = await signal_plot_window(box_state,
                                               inputs[id_],
                                               ui_settings=ui_settings)
                box_positions[id_] = pos

        # connections between boxes
        link_selection = state.link_selection

        prev_cursor_screen_pos = im.get_cursor_screen_position()

        # get slot coords and draw slots
        with color({im.COLOR_CHECK_MARK: (0, 0, 0, 100 / 255)}):
            draw_list = im.get_window_draw_list()
            SPACING = 20.
            slot_center_positions = {}

            for (id_, position) in box_positions.items():
                node = state.graph.nodes[id_]

                left_x = position.top_left.x
                right_x = position.bottom_right.x
                top_y = position.top_left.y

                for slot_ix in range(node.n_inputs):
                    pos = im.Vec2(left_x - 20 - 3,
                                  top_y + 30 + slot_ix * SPACING)
                    im.set_cursor_screen_position(pos)

                    slot = ng.InputSlotId(id_, slot_ix)
                    was_selected = (slot == link_selection.dst_slot)

                    changed, selected = im.checkbox(
                        "##in{}{}".format(id_, slot_ix), was_selected)
                    if changed:
                        await emit(LinkSelectionAction.ClickInput(slot))

                    center_pos = util.rect_center(
                        util.get_item_rect())  # bounding rect of prev widget
                    slot_center_positions[('in', id_, slot_ix)] = center_pos

                for slot_ix in range(node.n_outputs):
                    pos = im.Vec2(right_x + 3, top_y + 30 + slot_ix * SPACING)
                    im.set_cursor_screen_position(pos)

                    slot = ng.OutputSlotId(id_, slot_ix)
                    was_selected = (slot == link_selection.src_slot)

                    changed, selected = im.checkbox(
                        "##out{}{}".format(id_, slot_ix), was_selected)
                    if changed:
                        await emit(LinkSelectionAction.ClickOutput(slot))

                    center_pos = util.rect_center(
                        util.get_item_rect())  # bounding rect of prev widget
                    slot_center_positions[('out', id_, slot_ix)] = center_pos

        # end drawing slots

        # draw links
        for (src, dst) in state.graph.links:
            src_pos = slot_center_positions[('out', src.node_id, src.ix)]
            dst_pos = slot_center_positions[('in', dst.node_id, dst.ix)]
            draw_list.add_line(*src_pos,
                               *dst_pos,
                               col=im.get_color_u32_rgba(0.5, 0.5, 0.5, 1.),
                               thickness=2.)

        im.set_cursor_screen_position(prev_cursor_screen_pos)
    # end nodes window

    im.show_style_editor()
Ejemplo n.º 11
0
import imgui

imgui.create_context()

io = imgui.get_io()
texWidth, texHeight, fontData = io.fonts.get_tex_data_as_rgba32()

io.display_size = imgui.Vec2(100, 200)
imgui.new_frame()
imgui.render()
imgui.new_frame()
imgui.begin(
    'Vulkan Example', None, imgui.WINDOW_ALWAYS_AUTO_RESIZE
    | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE)
imgui.text_unformatted('yeah!!!')
imgui.text('yeah!!!')
imgui.text('yeah!!!')
imgui.end()
imgui.render()
imDrawData = imgui.get_draw_data()

# repeat ?
imgui.new_frame()
imgui.render()
imgui.new_frame()
imgui.begin(
    'Vulkan Example', None, imgui.WINDOW_ALWAYS_AUTO_RESIZE
    | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE)
imgui.text_unformatted('yeah!!!')
imgui.text('yeah!!!')
imgui.text('yeah!!!')
Ejemplo n.º 12
0
 def viewport_center_original_image(self):  # -> imgui.Vec2:
     center = np.array([[self.current_viewport_size().width / 2.],
                        [self.current_viewport_size().height / 2.], [1.]])
     center_original = np.dot(
         numpy.linalg.inv(self.zoom_info.affine_transform), center)
     return imgui.Vec2(center_original[0, 0], center_original[1, 0])
Ejemplo n.º 13
0
 def actual_window_startup_size(self):
     if self.max_size:
         display_size = imgui.get_io().display_size
         return imgui.Vec2(display_size.x - 40, display_size.y - 20)
     else:
         return self.window_size
Ejemplo n.º 14
0
def add(vect1, vect2):
    res = imgui.Vec2(vect1.x + vect2.x, vect1.y + vect2.y)
    return res
Ejemplo n.º 15
0
def sub(vect1, vect2):
    res = imgui.Vec2(vect1.x - vect2.x, vect1.y - vect2.y)
    return res
Ejemplo n.º 16
0
def main():
    global width_library
    global width_shematic
    global width_context
    global height_window

    global previous_key_callback
    global selected_link
    global selected_node
    global iggraph
    global node_library
    global debug_is_mouse_dragging
    
    global show_debug_window

    # states -------------------------
    
    scrolling = imgui.Vec2(0, 0)

    iggraph = IGGraph(node_library)

    # iggraph.reset()

    node_hovered_in_scene = -1
    parameter_link_start = None
    selected_parameter = None

    io_hovered = None 
    io_anchors_width_not_hovered = 10
    io_anchors_width_hovered = 15 
    right_splitter_is_active = False
    left_splitter_is_active = False
    
    image_width = 0
    image_height = 0
    image_texture = None

    # states -------------------------

    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)
    io = imgui.get_io()
    previous_key_callback = glfw.set_key_callback(window,key_event)
    init_textures()

    assign_parameter_colors(node_library)

    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_new, selected_new = imgui.menu_item(
                    "New", 'Cmd+N', False, True
                )
                if clicked_new:
                    iggraph = IGGraph(node_library)
                clicked_load, selected_load = imgui.menu_item(
                    "Load", 'Cmd+L', False, True
                )
                if clicked_load:
                    root = tk.Tk()
                    root.withdraw()
                    filename = filedialog.askopenfilename()
                    if filename :
                        f=open(filename)
                        iggraph.from_json(json.load(f))
                        f.close()
                clicked_save, selected_save = imgui.menu_item(
                    "Save", 'Cmd+S', False, True
                )
                if clicked_save:
                    iggraph.reset()
                    graph_json = iggraph.to_json()
                    text2save = json.dumps(graph_json, indent=4, sort_keys=True)
                    root = tk.Tk()
                    root.withdraw()
                    f = filedialog.asksaveasfile(mode='w', defaultextension=".json")
                    if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
                        return
                    f.write(text2save)
                    f.close()
                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True
                )
                if clicked_quit:
                    exit(0)
                imgui.end_menu()
            if imgui.begin_menu("Debug", True):
                show_debug_window_clicked,  show_debug_window_selected = imgui.menu_item(
                    "Show Debug window", 'Cmd+D', show_debug_window, True
                )
                if show_debug_window_clicked:
                    show_debug_window = not show_debug_window
                catch_exceptions_clicked,  catch_exceptions_selected = imgui.menu_item(
                    "Catch Exceptions", '', iggraph.catch_exceptions, True
                )
                if catch_exceptions_clicked:
                    iggraph.catch_exceptions = not iggraph.catch_exceptions
                imgui.separator()
                imgui.menu_item(
                    "Examples", '', False, False
                )
                show_example_mosaic_clicked,  show_example_mosaic_selected = imgui.menu_item(
                    "Mosaic", '', False, True
                )
                if show_example_mosaic_clicked:
                    example_mosaic(iggraph)
                imgui.end_menu()
            imgui.end_main_menu_bar()

        height_window = io.display_size.y - 18  # imgui.get_cursor_pos_y()

        imgui.push_style_var(imgui.STYLE_ITEM_SPACING, imgui.Vec2(0,0))
        imgui.set_next_window_size(io.display_size.x, height_window)
        imgui.set_next_window_position(0, 18)
        imgui.push_style_var(imgui.STYLE_WINDOW_ROUNDING, 0)
        imgui.begin("Splitter test", False, imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_BRING_TO_FRONT_ON_FOCUS)
        imgui.pop_style_var()
        imgui.pop_style_var()

        width_shematic = io.display_size.x - separator_width  - width_context - separator_width - width_library

        # ==============================================================================
        # Library
        # ==============================================================================

        imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0)
        imgui.begin_child("Library", width_library, 0, True)
        for node_name in node_library.nodes:
            if imgui.button(node_name, width_library):
                iggraph.create_node(node_name)
        imgui.end_child()
        imgui.pop_style_var()

        imgui.same_line()
        imgui.button("left_splitter", separator_width, height_window - 20)
        left_splitter_is_active = imgui.is_item_active()
        if (left_splitter_is_active):
            width_library += io.mouse_delta.x
            scrolling = imgui.Vec2(scrolling.x - io.mouse_delta.x, scrolling.y)
        if (imgui.is_item_hovered()):
            imgui.set_mouse_cursor(imgui.MOUSE_CURSOR_RESIZE_EW)
        
        imgui.same_line()

        # ==============================================================================
        # Shematic
        # ==============================================================================
        imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0)
        imgui.begin_child("shematic", width_shematic, 0, True)

        if show_inputs_popup(iggraph):
            imgui.open_popup("Outputs")
        show_outputs_popup(iggraph)

        # create our child canvas
        if iggraph.get_state() == iggraph.STATE_IDLE:
            imgui.text("status: edit | ")
        elif iggraph.get_state() == iggraph.STATE_RUNNING:
            imgui.text("status: run  | ")
        imgui.same_line()
        if iggraph.get_state() == iggraph.STATE_IDLE:
            if imgui.button("run"):
                #TODO if not running
                iggraph.set_state(iggraph.STATE_RUNNING)
                iggraph.prepare_to_run()
                imgui.open_popup("User Input")
            imgui.same_line()
            if imgui.button("run one step"):
                iggraph.set_state(iggraph.STATE_RUNNING)
                iggraph.prepare_to_run()
                iggraph.run_one_step()
        elif iggraph.get_state() == iggraph.STATE_RUNNING:
            if imgui.button("stop running"):
                iggraph.reset()
                iggraph.set_state(iggraph.STATE_IDLE)
            imgui.same_line()
            if imgui.button("run one step"):
                iggraph.set_state(iggraph.STATE_RUNNING)
                iggraph.run_one_step()
        # imgui.same_line(imgui.get_window_width() - 100)
        imgui.push_style_var(imgui.STYLE_FRAME_PADDING, imgui.Vec2(1, 1))
        imgui.push_style_var(imgui.STYLE_WINDOW_PADDING, imgui.Vec2(0, 0))
        imgui.begin_child("scrolling_region", 0, 0, True, imgui.WINDOW_NO_SCROLLBAR | imgui.WINDOW_NO_MOVE)
        imgui.pop_style_var()
        imgui.pop_style_var()
        imgui.push_item_width(120.0)

        offset = add(imgui.get_cursor_screen_pos(), scrolling)
        draw_list = imgui.get_window_draw_list()

        # Display links
        draw_list.channels_split(2)
        draw_list.channels_set_current(0)
        for link in iggraph.links:
            draw_link_param_to_param(draw_list, offset, link.output_parameter, link.input_parameter, selected_link == link)

        # Display nodes
        parameter_link_end = None
        one_parameter_hovered = False
        one_node_moving_active = False
        for node in iggraph.nodes:
            imgui.push_id(str(node.id))
            node_rect_min = add(offset, node.pos)
            draw_list.channels_set_current(1) # foreground
            old_any_active = imgui.is_any_item_active()

            #display node content first
            # todo
            test = add(node_rect_min, NODE_WINDOW_PADDING)
            imgui.set_cursor_screen_position(add(node_rect_min, NODE_WINDOW_PADDING))
            imgui.begin_group()
            imgui.text("")
            imgui.text(node.name)
            imgui.text("")
            imgui.end_group()

            # save size
            node_widgets_active = False # (not old_any_active and imgui.is_any_item_active())
            node.size = add( add( imgui.get_item_rect_size(), NODE_WINDOW_PADDING) , NODE_WINDOW_PADDING)
            node_rect_max = add(node.size, node_rect_min) 
            
            #display node box
            draw_list.channels_set_current(0) # background
            imgui.set_cursor_screen_position(node_rect_min)
            imgui.invisible_button(str(node.id), node.size.x, node.size.y)
            if imgui.is_item_hovered():
                node_hovered_in_scene = node.id
            else:
                node_hovered_in_scene = None
            node_moving_active = imgui.is_item_active()
            use_hovered_color = node_hovered_in_scene or selected_node == node
            draw_list.add_rect_filled(node_rect_min.x, node_rect_min.y, node_rect_max.x, node_rect_max.y, get_node_color(node, iggraph, use_hovered_color), 5)
            if node_hovered_in_scene and iggraph.is_error(node):
                imgui.begin_tooltip()
                imgui.text(iggraph.error_nodes[node])
                imgui.end_tooltip()

            # input parameters
            for parameter_name in node.inputs:
                parameter = node.inputs[parameter_name]
                center = node.get_intput_slot_pos(parameter)
                center_with_offset = add(offset, center)
                if io_hovered == parameter:
                    io_anchors_width = io_anchors_width_hovered
                else:
                    io_anchors_width = io_anchors_width_not_hovered
                imgui.set_cursor_pos(imgui.Vec2(center.x-io_anchors_width/2, center.y-io_anchors_width/2))
                imgui.push_id(str(str(node.id) + "input" + parameter.id))
                if (imgui.invisible_button("input", io_anchors_width, io_anchors_width)):
                    selected_parameter = parameter
                # imgui.is_item_hovered() does not work when dragging
                is_hovering = ((io.mouse_pos.x-offset.x>center.x-io_anchors_width/2) and 
                               (io.mouse_pos.x-offset.x<center.x+io_anchors_width/2) and
                               (io.mouse_pos.y-offset.y>center.y-io_anchors_width/2) and
                               (io.mouse_pos.y-offset.y<center.y+io_anchors_width/2))
                if is_hovering:
                    io_hovered = parameter
                    one_parameter_hovered = True
                    imgui.begin_tooltip()
                    imgui.text(parameter_name)
                    imgui.end_tooltip()
                if is_hovering and imgui.is_mouse_released(0):
                    parameter_link_end = parameter
                imgui.pop_id()
                draw_list.add_circle_filled(center_with_offset.x, center_with_offset.y, io_anchors_width/2, get_parameter_color(parameter))

            # output parameters
            for parameter_name in node.outputs:
                parameter = node.outputs[parameter_name]
                center = node.get_output_slot_pos(parameter)
                center_with_offset = add(offset, center)
                if io_hovered == parameter:
                    io_anchors_width = io_anchors_width_hovered
                else:
                    io_anchors_width = io_anchors_width_not_hovered
                imgui.set_cursor_pos(imgui.Vec2(center.x-io_anchors_width/2, center.y-io_anchors_width/2))
                imgui.push_id(str(str(node.id) + "output" + parameter.id))
                if (imgui.invisible_button("output", io_anchors_width, io_anchors_width)):
                    selected_parameter = parameter
                is_hovering = ((io.mouse_pos.x-offset.x>center.x-io_anchors_width/2) and 
                    (io.mouse_pos.x-offset.x<center.x+io_anchors_width/2) and
                    (io.mouse_pos.y-offset.y>center.y-io_anchors_width/2) and
                    (io.mouse_pos.y-offset.y<center.y+io_anchors_width/2))
                if is_hovering:
                    io_hovered = parameter
                    one_parameter_hovered = True
                    imgui.begin_tooltip()
                    imgui.text(parameter_name)
                    imgui.end_tooltip()
                draw_list.add_circle_filled(center_with_offset.x, center_with_offset.y, io_anchors_width/2, get_parameter_color(parameter))
                imgui.pop_id()
                # cannot use imgui.is_item_active, seems buggy with the scroll
                if is_hovering and imgui.is_mouse_down(0):
                    parameter_link_start = parameter

            if node_widgets_active or node_moving_active:
                selected_node = node
                one_node_moving_active = True
            if node_moving_active and imgui.is_mouse_dragging(0) and node.id==selected_node.id:
               node.pos = add(node.pos, io.mouse_delta)

            debug_is_mouse_dragging = imgui.is_mouse_dragging(0)

            imgui.pop_id()
        draw_list.channels_merge()
        if not one_parameter_hovered:
            io_hovered = None

        # scrolling
        mouse_is_in_schematic = (io.mouse_pos.x > width_library) and\
                                (io.mouse_pos.x < (width_library + width_shematic)) and\
                                (io.mouse_pos.y < height_window) and\
                                (io.mouse_pos.y > 18)
        if not one_node_moving_active and\
           not parameter_link_start and\
           imgui.is_mouse_dragging(0) and\
           mouse_is_in_schematic and\
           not left_splitter_is_active and\
           not right_splitter_is_active and\
           imgui.is_window_focused():
            scroll_offset = imgui.Vec2(io.mouse_delta.x, io.mouse_delta.y)
            scrolling = add(scrolling, scroll_offset)
        # link creation
        if parameter_link_start and parameter_link_end:
            iggraph.add_link(parameter_link_start, parameter_link_end)
        # creating link
        elif parameter_link_start and imgui.is_mouse_dragging(0):
            draw_link_param_to_point(draw_list, offset, parameter_link_start, io.mouse_pos.x, io.mouse_pos.y, True)
        # mouse release
        if imgui.is_mouse_released(0):
            parameter_link_start = None

        imgui.pop_item_width()
        imgui.end_child()

        # mouse click on the scene
        if imgui.is_mouse_clicked(0):
            mouse_pos = imgui.get_mouse_pos()
            local_mouse_pos = imgui.Vec2(mouse_pos.x - offset.x, mouse_pos.y - offset.y)
            selected_link = None
            for link in iggraph.links:
                start_node = link.output_parameter.owner
                start_pos = start_node.get_output_slot_pos(link.output_parameter)
                end_node = link.input_parameter.owner
                end_pos = end_node.get_intput_slot_pos(link.input_parameter)
                distance_mouse_start = math.sqrt(((local_mouse_pos.x-start_pos.x)**2) + ((local_mouse_pos.y-start_pos.y)**2))
                distance_mouse_end = math.sqrt(((local_mouse_pos.x-end_pos.x)**2) + ((local_mouse_pos.y-end_pos.y)**2))
                distance_start_end = math.sqrt(((start_pos.x-end_pos.x)**2) + ((start_pos.y-end_pos.y)**2))
                if ((distance_mouse_start + distance_mouse_end) - distance_start_end) < 0.1:
                    selected_link = link
                
        imgui.end_child()
        imgui.pop_style_var()

        imgui.same_line()
        imgui.button("right_splitter", separator_width, height_window - 20)
        right_splitter_is_active = imgui.is_item_active()
        if (right_splitter_is_active):
            width_context -= io.mouse_delta.x
        if (imgui.is_item_hovered()):
            imgui.set_mouse_cursor(imgui.MOUSE_CURSOR_RESIZE_EW)

        # ==============================================================================
        # Context
        # ==============================================================================

        imgui.same_line()
        imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0)
        imgui.begin_child("child3", width_context, 0, True);
        if selected_node:
            if selected_node.handle_dynamic_parameters():
                if imgui.button("add parameter"):
                    selected_node.add_dynamic_parameter()
            if imgui.tree_node("Inputs"):
                for parameter_name in selected_node.inputs:
                    parameter = selected_node.inputs[parameter_name]
                    if imgui.tree_node(parameter.id):
                        display_parameter(parameter, True)
                        imgui.tree_pop()
                imgui.tree_pop()
            if imgui.tree_node("Output"):
                for parameter_name in selected_node.outputs:
                    parameter = selected_node.outputs[parameter_name]
                    if imgui.tree_node(parameter.id):
                        display_parameter(parameter, False)
                        imgui.tree_pop()
                imgui.tree_pop()
        imgui.end_child()
        imgui.pop_style_var()

        # 
        imgui.end()

        # ==============================================================================
        # Debug Window
        # ==============================================================================
        if show_debug_window:
            debug_window_expanded, show_debug_window = imgui.begin("Debug", True)
            if parameter_link_start:
                imgui.text("parameter_link_start: " + parameter_link_start.id)
            else:
                imgui.text("parameter_link_start: " + "None")
            if selected_parameter:
                imgui.text("selected_parameter: " + selected_parameter.id)
            else:
                imgui.text("selected_parameter: " + "None")
            imgui.text("is_mouse_dragging: " + str(debug_is_mouse_dragging))
            imgui.text("mouse: (" + str(io.mouse_pos.x) + ", " + str(io.mouse_pos.y) + ")")
            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()
Ejemplo n.º 17
0
def image_explorer_impl(im, title=""):
    # type: (ImageWithZoomInfo, str) -> None
    """
    :return: imgui.Vec2 (mouse_location_original_image) or None (if not on image)
    """

    if im.image.size == 0:
        imgui.text("empty image !")
        return imgui.Vec2(0, 0)

    zoomed_image = im.zoomed_image()

    if not im.hide_buttons:
        _display_zoom_or_pan_buttons(im)
        if title != "":
            imgui.same_line()
            imgui.text("     " + title)
    mouse_location = imgui_cv.image(zoomed_image,
                                    image_adjustments=im.image_adjustments)
    mouse_location_original_image = None
    viewport_center_original_image = im.viewport_center_original_image()

    if not im.hide_buttons and mouse_location is not None:
        mouse_drag_button = 0
        is_mouse_dragging = imgui.is_mouse_dragging(
            mouse_drag_button) and imgui.is_item_hovered()
        drag_delta = imgui.get_mouse_drag_delta(mouse_drag_button)

        mouse_location_original_image = im.zoom_info.mouse_location_original_image(
            mouse_location)

        # Handle dragging / zoom or pan
        if not is_mouse_dragging:
            im.zoom_info.last_delta = imgui.Vec2(0, 0)
        if is_mouse_dragging:
            drag_delta_delta = imgui.Vec2(
                drag_delta.x - im.zoom_info.last_delta.x,
                drag_delta.y - im.zoom_info.last_delta.y)

            if im.zoom_info.zoom_or_pan == ZoomOrPan.Zoom:
                k = 1.03
                if drag_delta.y < 0:
                    zoom_ratio = k
                else:
                    zoom_ratio = 1. / k
                im.zoom_info.affine_transform = np.dot(
                    im.zoom_info.affine_transform,
                    compute_zoom_matrix(mouse_location_original_image,
                                        zoom_ratio))

            if im.zoom_info.zoom_or_pan == ZoomOrPan.Pan:
                im.zoom_info.affine_transform = np.dot(
                    im.zoom_info.affine_transform,
                    compute_pan_matrix(drag_delta_delta,
                                       im.zoom_info.affine_transform[0, 0]))

            im.zoom_info.last_delta = drag_delta

    # Zoom & Pan buttons

    def perform_zoom(ratio):
        im.zoom_info.affine_transform = np.dot(
            im.zoom_info.affine_transform,
            compute_zoom_matrix(viewport_center_original_image, ratio))

    import functools
    perform_zoom_plus = functools.partial(perform_zoom, 1.25)
    perform_zoom_minus = functools.partial(perform_zoom, 1. / 1.25)

    def perform_scale_one():
        im.zoom_info.set_scale_one(SizePixel.from_image(im.image),
                                   im.current_viewport_size())

    def perform_full_view():
        im.zoom_info.set_full_view(SizePixel.from_image(im.image),
                                   im.current_viewport_size())

    def perform_force_viewport_size():
        im.set_force_viewport_size(True)

    def perform_reset_viewport_size():
        im.set_force_viewport_size(False)

    def perform_hide_buttons():
        im.hide_buttons = True

    def perform_show_buttons():
        im.hide_buttons = False

    def show_zoom_button(name, action, same_line=True):
        if imgui.small_button(imgui_ext.make_unique_label(name)):
            action()
        if same_line:
            imgui.same_line()

    if im.hide_buttons:
        show_zoom_button("+", perform_show_buttons, False)
        imgui.same_line()
        imgui.text(title)
    else:
        show_zoom_button("-", perform_hide_buttons)
    if not im.hide_buttons:
        show_zoom_button("zoom +", perform_zoom_plus)
        show_zoom_button("zoom -", perform_zoom_minus)
        if im.can_show_big_viewport():
            show_zoom_button("scale 1", perform_scale_one)
        if im.is_not_full_view():
            show_zoom_button("full view", perform_full_view)
        if not im.show_adjustments:
            if imgui.small_button(imgui_ext.make_unique_label("Adjust")):
                im.show_adjustments = True
        # adjustments
        if im.show_adjustments:
            imgui.new_line()
            imgui.text("Adjust:")
            imgui.same_line()
            imgui.push_item_width(80)
            # noinspection PyArgumentList
            changed, im.image_adjustments.factor = imgui.slider_float(
                imgui_ext.make_unique_label("k"),
                im.image_adjustments.factor,
                0.,
                32.,
                display_format="%.3f",
                power=5.)
            imgui.same_line()
            imgui.push_item_width(80)
            changed, im.image_adjustments.delta = imgui.slider_float(
                imgui_ext.make_unique_label("delta"),
                im.image_adjustments.delta,
                0.,
                255.,
                display_format="%.3f",
                power=5.)
            imgui.same_line()
            if not im.image_adjustments.is_none():
                if imgui.small_button(imgui_ext.make_unique_label("reset")):
                    im.image_adjustments = imgui_cv.ImageAdjustments()
            imgui.same_line()
            if imgui.small_button(imgui_ext.make_unique_label("hide adjust")):
                im.show_adjustments = False
        # Show image info
        image_type_msg = str(im.image.dtype) + str(im.image.shape)
        zoom = im.zoom_info.affine_transform[0, 0]
        import math
        if not _is_close(zoom, 1):
            zoom_msg = "Zoom:{0:.2f} ".format(zoom)
        else:
            zoom_msg = ""
        msg = zoom_msg + image_type_msg
        imgui.text(msg)

        if im.can_show_big_viewport():
            imgui.same_line()
            if im.get_force_viewport_size():
                show_zoom_button("reset viewport", perform_reset_viewport_size)
            else:
                show_zoom_button("fit viewport", perform_force_viewport_size)
            imgui.new_line()
        # Save button
        # imgui.same_line()
        imgui.push_item_width(60)
        changed, im.filename = imgui.input_text(
            imgui_ext.make_unique_label(""), im.filename, 1000)
        imgui.same_line()
        if imgui.small_button(imgui_ext.make_unique_label("save")):
            cv2.imwrite(im.filename, im.image)
        # Show pixel color info
        if mouse_location is not None:
            color = zoomed_image[int(round(mouse_location.y)),
                                 int(round(mouse_location.x))]

            mouse2 = np.array([[mouse_location.x], [mouse_location.y], [1.]])
            pt_original = np.dot(
                numpy.linalg.inv(im.zoom_info.affine_transform), mouse2)
            position_msg = "({0},{1})".format(int(round(pt_original[0, 0])),
                                              int(round(pt_original[1, 0])))
            imgui.text(position_msg + " " + color_msg(color))
        else:
            imgui.text("")

    return mouse_location_original_image
Ejemplo n.º 18
0
 def __init__(self):
     self.affine_transform = np.eye(3)
     self.zoom_or_pan = ZoomOrPan.Pan
     self.last_delta = imgui.Vec2(0., 0.)
Ejemplo n.º 19
0
 def _max_image_size(self):
     win_size = imgui.get_window_size()
     max_image_size = imgui.Vec2(win_size.x - (self.listbox_width + 40),
                                 win_size.y - 150)
     return max_image_size
Ejemplo n.º 20
0
 def mouse_location_original_image(self, mouse_location):  # -> imgui.Vec2:
     mouse2 = np.array([[mouse_location.x], [mouse_location.y], [1.]])
     pt_original = np.dot(numpy.linalg.inv(self.affine_transform), mouse2)
     return imgui.Vec2(pt_original[0, 0], pt_original[1, 0])
Ejemplo n.º 21
0
import glfw
import OpenGL.GL as gl
import tkinter as tk
from tkinter import filedialog
import imgui
import math 
from imgui.integrations.glfw import GlfwRenderer
from PIL import Image
from PIL import ImageOps
import numpy
from IGNode import *
from IGGraph import *
from IGLibrary import *
import json

NODE_WINDOW_PADDING = imgui.Vec2(8.0, 8.0)
previous_key_callback = None
selected_link = None
selected_node = None
node_library = IGLibrary()
iggraph = None
debug_is_mouse_dragging = False
show_debug_window = False
slider_indexes = {}

params_color_palette = [
(0.996,0.231,0.118),
(0.98,0.185,0.477),
(0.982,0.624,0.855),
(0.599,0.186,0.487),
(0.312,0.009,0.923),
Ejemplo n.º 22
0
 def create_node(self, node_name, pos=imgui.Vec2(0, 0)):
     new_node = self.node_library.create_node(node_name)
     new_node.id = self.generate_id()
     new_node.pos = pos
     self.nodes.append(new_node)
     return new_node