Files
2026-11-02 19:38:04 +01:00

965 lines
43 KiB
GDScript
Executable File

@tool
class_name PdMain
extends VBoxContainer
## Polydoodle main screen: toolbar | quad views (Top/Persp/Side/Front) | panel.
const VIEW2D := preload("res://addons/polydoodle/editor/pd_view2d.gd")
const VIEW3D := preload("res://addons/polydoodle/editor/pd_view3d.gd")
const TOOLBAR := preload("res://addons/polydoodle/editor/pd_toolbar.gd")
const PANEL := preload("res://addons/polydoodle/editor/pd_panel.gd")
const UVCANVAS := preload("res://addons/polydoodle/editor/pd_uvcanvas.gd")
var doc: PdDocument
var toolbar: PdToolbar
var panel: PdPanel
var view3d: PdView3D
var views2d: Array = [] # [top, side, front]
var status_label: Label
var hint_label: Label
var view_holder: Control
var _split: HSplitContainer # views | panel - width-clamped drags
var _fullscreen_view: Control = null
var _focused_view: Control = null
var _dlg: EditorFileDialog
var _file_dlg: EditorFileDialog # image import dialog
var _expand_syncing := false # guard while pushing pressed states out
# Texture Paint mode: 3D viewport on top, UV canvas below. The tool
# buttons live IN THE TOP TOOLBAR (the texture group replaces the
# modeling buttons); sliders and deeper options live in the right panel.
var uv_canvas: PdUVCanvas
var _last_canvas_size := Vector2.ZERO
var last_3d_mode: int = PdDocument.Mode.OBJECT # workspace memory
const PANEL_MIN_W := 240.0 # panel floor (also on the panel itself):
# SplitContainer refuses to shrink it below
const VIEW_MIN_W := 410.0 # hard floor for the quad views: must fit
# TWO columns of view3d's own 200px minimum
# width (+ gap) or view3d gets clamped wider
# than its allotted half and visually spills
# out of view_holder into the panel next to
# it. Was 300 (only 150/column) - too small
# for view3d's 200 floor, which is exactly
# what caused the 3D viewport / panel
# overlap when the panel was dragged wide.
func _init() -> void:
doc = PdDocument.new()
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
size_flags_horizontal = Control.SIZE_EXPAND_FILL
size_flags_vertical = Control.SIZE_EXPAND_FILL
add_theme_constant_override("separation", 4)
_build_ui()
doc.doc_changed.connect(_on_doc_changed)
doc.sel_changed.connect(_on_doc_changed)
doc.settings_changed.connect(_on_doc_changed)
doc.undo.version_changed.connect(_on_doc_changed)
doc.status_msg.connect(func(t: String): set_status(t))
doc.warning_msg.connect(show_toast)
_setup_autosave()
set_status("Welcome to Polydoodle - add a shape or switch to Draw mode and doodle one!")
hint_label.text = _hint_text()
func _build_ui() -> void:
toolbar = TOOLBAR.new()
toolbar.setup(doc)
toolbar.mode_requested.connect(_set_mode)
# the two-half workspace switch: left = 3D editor (restore the last
# 3D mode), right = texture editor
toolbar.workspace_requested.connect(func(tex: bool):
_set_mode(PdDocument.Mode.TEXTURE if tex else last_3d_mode))
toolbar.toggle_gizmo.connect(func(v: bool):
doc.set_gizmo(v)
_sync()
if v:
_warn_gizmo_target())
toolbar.toggle_snap.connect(func(v: bool): doc.set_snap(v))
toolbar.toggle_grid.connect(func(v: bool): doc.set_grid_visible(v))
toolbar.toggle_both_sides.connect(func(v: bool): doc.set_both_sides(v))
toolbar.draw_kind.connect(func(k: String): doc.set_draw_kind(k))
toolbar.add_shape.connect(func(kind: String):
doc.add_primitive(kind)
frame_selection())
toolbar.duplicate_requested.connect(func(): doc.duplicate_selected())
toolbar.delete_requested.connect(func(): doc.delete_selection())
toolbar.undo_requested.connect(doc.do_undo)
toolbar.redo_requested.connect(doc.do_redo)
toolbar.save_requested.connect(_save_project)
toolbar.load_requested.connect(_open_project)
toolbar.import_model_requested.connect(_import_model)
toolbar.export_requested.connect(_export)
toolbar.bg_changed.connect(func(c: Color): doc.set_bg(c))
# texture-editor toolbar group: submode + contextual tools
toolbar.tex_submode.connect(func(edit: bool): doc.set_tex_edit(edit))
toolbar.paint_tool_requested.connect(func(t: String): doc.set_paint_tool(t))
toolbar.uv_snap_requested.connect(func(v: bool): doc.set_uv_snap(v))
toolbar.rotate_uv_requested.connect(func(dir: int):
doc.rotate_uv_selected(doc.active_obj, dir))
toolbar.uv_tool_requested.connect(func(t: String):
doc.set_uv_tool(t))
toolbar.import_requested.connect(_import_image)
toolbar.detach_requested.connect(func():
doc.uv_detach_selected(doc.active_obj))
toolbar.reset_uvs_requested.connect(func():
doc.uv_reset_object(doc.active_obj))
# Scroll wrap: the toolbar's own minimum width must never push
# the layout wider than the main screen (that shoved the panel
# off-screen and stretched the viewports on smaller windows).
var tb_scroll := ScrollContainer.new()
tb_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_AUTO
tb_scroll.vertical_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
tb_scroll.size_flags_horizontal = Control.SIZE_EXPAND_FILL
toolbar.size_flags_horizontal = Control.SIZE_EXPAND_FILL
tb_scroll.add_child(toolbar)
add_child(tb_scroll)
var split := HSplitContainer.new()
split.size_flags_vertical = Control.SIZE_EXPAND_FILL
split.size_flags_horizontal = Control.SIZE_EXPAND_FILL
split.add_theme_constant_override("separation", 8)
_split = split
add_child(split)
# Classic quad view, same format as the earlier version:
# TOP (top-left) | PERSPECTIVE (top-right)
# SIDE (bottom-left) | FRONT (bottom-right)
view_holder = Control.new()
# engine-level floor: the splitter itself refuses to shrink the
# views below this, so the panel can never be dragged over them
view_holder.custom_minimum_size = Vector2(VIEW_MIN_W, 0)
view_holder.size_flags_vertical = Control.SIZE_EXPAND_FILL
view_holder.size_flags_horizontal = Control.SIZE_EXPAND_FILL
# belt-and-braces: even if some child ever reports a minimum size
# wider than its allotted quadrant, clip it here instead of letting
# it bleed into the panel next door.
view_holder.clip_contents = true
split.add_child(view_holder)
var v_top: PdView2D = VIEW2D.new()
v_top.setup(doc, self, 0)
view_holder.add_child(v_top)
views2d.append(v_top)
view3d = VIEW3D.new()
view3d.setup(doc, self)
view3d.custom_minimum_size = Vector2(200, 150)
view_holder.add_child(view3d)
var v_side: PdView2D = VIEW2D.new()
v_side.setup(doc, self, 2)
view_holder.add_child(v_side)
views2d.append(v_side)
var v_front: PdView2D = VIEW2D.new()
v_front.setup(doc, self, 1)
view_holder.add_child(v_front)
views2d.append(v_front)
for v in all_views():
v.focus_entered.connect(func(): _focused_view = v)
view_holder.resized.connect(_relayout_views)
# Texture-mode canvas (hidden until Texture mode). Its tools live
# in the toolbar; its settings live in the right panel.
uv_canvas = UVCANVAS.new()
uv_canvas.setup(doc, self)
view_holder.add_child(uv_canvas)
uv_canvas.visible = false
uv_canvas.focus_entered.connect(func(): _focused_view = uv_canvas)
panel = PANEL.new()
panel.setup(doc, self)
panel.custom_minimum_size = Vector2(240, 0)
split.add_child(panel)
var status := HBoxContainer.new()
status.add_theme_constant_override("separation", 10)
add_child(status)
hint_label = Label.new()
hint_label.text = ""
hint_label.add_theme_font_size_override("font_size", 11)
hint_label.add_theme_color_override("font_color", Color(1, 1, 1, 0.4))
hint_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
hint_label.clip_text = true
status.add_child(hint_label)
status_label = Label.new()
status_label.text = ""
status_label.add_theme_font_size_override("font_size", 11)
status_label.add_theme_color_override("font_color", Color(1, 1, 1, 0.55))
status_label.clip_text = true # long status text must not force width
status.add_child(status_label)
split.split_offset = -250
split.collapsed = false
_relayout_views.call_deferred()
_build_toast()
# -------------------------------------------------------------- toast ---
## A short notice that floats over the top of the main screen. It is a raised
## card in the plugin's own style (flat dark fill, darker bottom edge) and is
## sized from the real text metrics - no auto-wrapping label - so its height
## can never drift away from its content.
var _toast: PanelContainer
var _toast_label: Label
var _toast_tween: Tween
const TOAST_SECONDS := 3.8
const TOAST_FONT := 12
const TOAST_MAX_WIDTH := 560.0
const TOAST_MAX_LINES := 4
const TOAST_PAD_X := 14.0
func _build_toast() -> void:
_toast = PanelContainer.new()
_toast.top_level = true # floats over the layout
_toast.mouse_filter = Control.MOUSE_FILTER_IGNORE
_toast.clip_contents = true
_toast.z_index = 100
_toast.visible = false
var sb := StyleBoxFlat.new()
sb.bg_color = Color(0.215, 0.235, 0.285)
sb.set_corner_radius_all(5)
sb.border_width_bottom = 3 # darker lower edge: raised look
sb.border_color = Color(0.105, 0.115, 0.145)
sb.content_margin_left = TOAST_PAD_X
sb.content_margin_right = TOAST_PAD_X
sb.content_margin_top = 7
sb.content_margin_bottom = 10 # 7 of padding + the 3 px lower edge
_toast.add_theme_stylebox_override("panel", sb)
_toast_label = Label.new()
_toast_label.add_theme_font_size_override("font_size", TOAST_FONT)
_toast_label.add_theme_color_override("font_color", Color(1, 1, 1, 0.92))
_toast_label.mouse_filter = Control.MOUSE_FILTER_IGNORE
# the editor theme pads labels; the card does its own padding
_toast_label.add_theme_stylebox_override("normal", StyleBoxEmpty.new())
_toast.add_child(_toast_label)
add_child(_toast)
resized.connect(_place_toast)
visibility_changed.connect(func():
if not is_visible_in_tree() and _toast != null:
_toast.visible = false)
## Greedy word wrap using the font's real metrics. A word that cannot fit on
## a line by itself (a long file path, say) is broken across lines. At most
## `max_lines` lines are returned; the last one ends in "..." when cut.
func _wrap_text(text: String, font: Font, font_size: int, max_w: float,
max_lines := 1000) -> PackedStringArray:
var lines := PackedStringArray()
var cur := ""
for token in text.split(" ", false):
var word: String = token
while word.length() > 1 and font.get_string_size(word,
HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x > max_w:
var n := word.length()
while n > 1 and font.get_string_size(word.substr(0, n),
HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x > max_w:
n -= 1
if not cur.is_empty():
lines.append(cur)
cur = ""
lines.append(word.substr(0, n))
word = word.substr(n)
var cand: String = word if cur.is_empty() else cur + " " + word
if cur.is_empty() or font.get_string_size(cand,
HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x <= max_w:
cur = cand
else:
lines.append(cur)
cur = word
if not cur.is_empty():
lines.append(cur)
if lines.size() > max_lines:
lines.resize(max_lines)
var last := lines[max_lines - 1]
while last.length() > 1 and font.get_string_size(last + "...",
HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x > max_w:
last = last.substr(0, last.length() - 1)
lines[max_lines - 1] = last + "..."
return lines
func _place_toast() -> void:
if _toast == null or not _toast.visible:
return
var top := (toolbar.size.y if toolbar != null else 40.0) + 10.0
var x := clampf((size.x - _toast.size.x) * 0.5, 8.0,
maxf(8.0, size.x - _toast.size.x - 8.0))
_toast.global_position = global_position + Vector2(x, top)
## Show a notice. Replaces the previous one; fades out by itself.
func show_toast(text: String) -> void:
if _toast == null or text.is_empty() or not is_visible_in_tree():
return
var font := _toast_label.get_theme_font("font")
var card_w := clampf(size.x - 48.0, 200.0, TOAST_MAX_WIDTH)
var lines := _wrap_text(text, font, TOAST_FONT,
card_w - TOAST_PAD_X * 2.0, TOAST_MAX_LINES)
_toast_label.text = "\n".join(lines)
# explicit size from the text metrics: widest line + padding, one text
# row per line - the label never wraps by itself
var widest := 0.0
for l in lines:
widest = maxf(widest, font.get_string_size(l,
HORIZONTAL_ALIGNMENT_LEFT, -1, TOAST_FONT).x)
var sb := _toast.get_theme_stylebox("panel") as StyleBoxFlat
var gap := float(_toast_label.get_theme_constant("line_spacing"))
var card := Vector2(
minf(widest + TOAST_PAD_X * 2.0 + 2.0, card_w),
lines.size() * font.get_height(TOAST_FONT) + (lines.size() - 1) * gap
+ sb.content_margin_top + sb.content_margin_bottom)
_toast.custom_minimum_size = card
_toast.size = card
_toast.visible = true
_place_toast()
_toast.modulate.a = 1.0
if _toast_tween != null and _toast_tween.is_valid():
_toast_tween.kill()
_toast_tween = create_tween()
_toast_tween.tween_interval(TOAST_SECONDS)
_toast_tween.tween_property(_toast, "modulate:a", 0.0, 0.45)
_toast_tween.tween_callback(func(): _toast.visible = false)
# ------------------------------------------------------------- status ---
func set_status(text: String) -> void:
if status_label:
status_label.text = text
func _on_doc_changed() -> void:
_sync()
func _sync() -> void:
toolbar.sync_from_doc()
hint_label.text = _hint_text()
func _hint_text() -> String:
if not doc.hints_enabled:
return ""
return MODE_HINTS.get(doc.mode, "") + HINT_TAIL
func all_views() -> Array:
return [views2d[0], view3d, views2d[1], views2d[2]]
# ------------------------------------------------------ session ---
## SAVE SYSTEM: the document autosaves to user:// (debounced) and is
## restored when the editor reopens, so closing Godot and coming back
## brings the models back exactly as they were left.
var _autosave: Timer
func _setup_autosave() -> void:
_autosave = Timer.new()
_autosave.one_shot = true
_autosave.wait_time = 2.0
_autosave.timeout.connect(_autosave_now)
add_child(_autosave)
doc.doc_changed.connect(_kick_autosave)
doc.settings_changed.connect(_kick_autosave)
func _kick_autosave() -> void:
if _autosave != null:
_autosave.start()
func _autosave_now() -> void:
# never serialize from inside a live gesture: the pause that lets
# the timer fire would stall the drag mid-stroke. Retry when the
# gesture ends; skip entirely when nothing changed since last time.
if doc.gesture_depth > 0:
_autosave.start()
return
if not doc.session_dirty:
return
var err := PdIo.save_session(doc)
if err == OK:
doc.session_dirty = false
## Immediate flush (editor quit / plugin disable). Called by the plugin
## BEFORE the screen is freed.
func persist_session() -> void:
if _autosave != null and not _autosave.is_stopped():
_autosave.stop()
if not doc.session_dirty:
return
var err := PdIo.save_session(doc)
if err != OK:
push_warning("Polydoodle: session save failed: %s"
% error_string(err))
else:
doc.session_dirty = false
## Load the saved session (if any) into the fresh document at startup.
## Missing / corrupt file = silently start empty.
func restore_session() -> void:
var d := PdIo.load_session()
if d.is_empty():
return
var n := PdIo.apply_session(doc, d)
if n < 0:
return
var m := int(d.get("mode", PdDocument.Mode.OBJECT))
if m < 0 or m > PdDocument.Mode.TEXTURE:
m = PdDocument.Mode.OBJECT
if m == PdDocument.Mode.TEXTURE:
doc.set_tex_edit(bool(d.get("tex_edit", false)))
_set_mode(m)
doc.notify_doc()
doc.settings_changed.emit()
set_status("Session restored - %d object(s), right where you left them" % n)
frame_selection()
func _notification(what: int) -> void:
if what == NOTIFICATION_EXIT_TREE:
persist_session()
elif what == NOTIFICATION_PREDELETE:
if doc != null:
doc.release()
# ------------------------------------------------- in-viewport hints ---
## One-line contextual hints drawn INSIDE each viewport (small muted text
## at the bottom), so the editor teaches itself without reading the docs:
## with a face or vertex selected the viewport says "Right-click: options
## (extrude, delete...)", the texture canvas announces "wheel: scale ·
## right-click: rotate" while an image is being placed, and so on.
## kind: "3d" (perspective view), "2d" (orthographic views), "canvas"
## (texture canvas). The sticker hint itself is drawn by PdUVCanvas.
static func context_hint(doc: PdDocument, kind: String) -> String:
if doc == null or not doc.hints_enabled:
return ""
var empty_3d := "Ctrl+drag: rectangle select" if kind == "3d" \
else "drag empty space: box-select"
match doc.mode:
PdDocument.Mode.OBJECT:
if doc.sel_objs.is_empty():
return "Click a shape to select it · Shift+click: add · %s" % empty_3d
return "Drag: move · Right-click: options (duplicate, delete and more) · Ctrl+drag: rectangle select · Del: delete"
PdDocument.Mode.VERTEX:
if doc.sel_verts.is_empty():
return "Click a vertex to select it (Shift adds) · %s" % empty_3d
return "Drag: move · Right-click: options (merge, delete and more) · Del: delete"
PdDocument.Mode.EDGE:
if doc.sel_edges.is_empty():
return "Click an edge to select it (Shift adds) · %s" % empty_3d
return "Drag: move · Right-click: options (EXTRUDE edges, delete and more) · Del: delete"
PdDocument.Mode.FACE:
if doc.sel_faces.is_empty():
return "Click inside a face to select it (Shift adds) · %s" % empty_3d
return "Drag: move · Right-click: options (EXTRUDE faces, fill, delete and more) · Del: delete"
PdDocument.Mode.DRAW:
return "Drag to sketch a shape · Shift: square/circle · Right-click: cancel · pick the shape on the Draw button"
PdDocument.Mode.TEXTURE:
if kind == "canvas":
if doc.tex_edit:
return "Drag islands/edges/corners to move · Right-click: options (extrude, merge, delete and more) · Wheel: zoom · MMB: pan"
return "Drag: paint · Click an island to select it · Wheel: zoom · MMB: pan"
if doc.tex_edit:
return "Click a face to select it · Drag empty space: orbit"
return "Drag on the model: paint · the Eraser tool removes paint · Wheel: zoom"
return ""
# ------------------------------------------------------ texture strip ---
## Layout note: the texture tools live IN THE TOP TOOLBAR - the texture
## group replaces the modeling buttons when the texture editor is active,
## and the sliders/settings live in the right panel, so the canvas gets
## the full lower area.
func _relayout_views() -> void:
if view_holder == null:
return
var r := Rect2(Vector2.ZERO, view_holder.size)
var gap := 2.0
# ---- Texture Paint layout: 3D on top, texture canvas below (the
# canvas owns the full lower area - the tools live in the
# top toolbar)
if doc != null and doc.mode == PdDocument.Mode.TEXTURE \
and _fullscreen_view == null:
var gap2 := gap * 2.0
var avail := maxf(160.0, r.size.y - gap2)
var top_h := avail * 0.52
top_h = clampf(top_h, 90.0, avail - 90.0)
for v in views2d:
v.visible = false
view3d.visible = true
view3d.position = r.position
view3d.size = Vector2(r.size.x, top_h)
uv_canvas.visible = true
uv_canvas.position = Vector2(0, top_h + gap)
uv_canvas.size = Vector2(r.size.x, avail - top_h)
# refit the canvas when the layout resized it (a stale zoom
# made the atlas appear cut off after workspace switches)
_refit_canvas_if_resized()
return
if uv_canvas != null:
uv_canvas.visible = false
var half := (r.size - Vector2.ONE * gap) * 0.5
var vs := all_views()
if _fullscreen_view != null:
# one view alone fills the area. In the texture editor the
# expanded view can be the canvas itself.
var fsvs := vs.duplicate()
if doc != null and doc.mode == PdDocument.Mode.TEXTURE:
fsvs.append(uv_canvas)
for v in fsvs:
v.visible = v == _fullscreen_view
v.position = r.position
v.size = r.size
if _fullscreen_view == uv_canvas:
_refit_canvas_if_resized()
return
var pos := [Vector2.ZERO,
Vector2(r.size.x * 0.5 + gap * 0.5, 0.0),
Vector2(0.0, r.size.y * 0.5 + gap * 0.5),
Vector2(r.size.x * 0.5 + gap * 0.5, r.size.y * 0.5 + gap * 0.5)]
for i in vs.size():
vs[i].visible = true
vs[i].position = pos[i]
vs[i].size = half
## Re-fit the canvas zoom when the layout changed its size (shared by the
## normal texture layout and the expanded-canvas layout).
func _refit_canvas_if_resized() -> void:
if uv_canvas == null or not uv_canvas.visible:
return
if uv_canvas.size.distance_squared_to(_last_canvas_size) > 1.0:
_last_canvas_size = uv_canvas.size
uv_canvas.fit_view.call_deferred()
func _toggle_view_fullscreen() -> void:
if view_holder == null or views2d.size() < 3:
return
_toggle_expand(_focused_view if _focused_view != null else view3d)
## Expand/retract ONE viewport (corner button or Space): the
## expanded view alone fills the whole view area, pressing again retracts
## to the previous layout. Works for all six views: Top/Side/Front, the
## perspective 3D view and the texture canvas.
func _toggle_expand(v: Control) -> void:
if view_holder == null or v == null:
return
_fullscreen_view = null if _fullscreen_view == v else v
if _fullscreen_view == null:
set_status("View restored")
else:
set_status("View expanded - press the button again (or Space) to show all views")
_relayout_views()
_sync_expand_btns()
## Mirror the expanded state on every view's corner toggle button.
func _sync_expand_btns() -> void:
if _expand_syncing:
return
_expand_syncing = true
var all: Array = all_views()
if uv_canvas != null:
all.append(uv_canvas)
for v in all:
if v != null and "expand_btn" in v \
and v.expand_btn != null \
and is_instance_valid(v.expand_btn):
v.expand_btn.set_pressed_no_signal(
_fullscreen_view == v)
_expand_syncing = false
const HINT_TAIL := " · Space: expand focused view"
const MODE_HINTS := {
PdDocument.Mode.OBJECT: "Click: select · Drag: move · Shift+Click: multi-select · 2D: drag empty = box-select · 3D: drag empty = orbit · Ctrl+drag: rectangle multi-select · right-click: object menu · Ctrl+D: duplicate",
PdDocument.Mode.VERTEX: "Drag a vertex to move it · Shift+Click: add · 2D: drag empty = box-select · 3D: Ctrl+drag: rectangle select · right-click: merge / delete menu · Del: delete",
PdDocument.Mode.EDGE: "Click an edge, drag to move · Shift+Click: add · 3D: right-click: EXTRUDE edges / delete · Del: delete",
PdDocument.Mode.FACE: "Click inside a face, drag to move · Shift+Click: add · 3D: right-click: EXTRUDE face(s) / fill / delete · Del: delete",
PdDocument.Mode.DRAW: "Drag in ANY viewport to sketch - pick the shape from the dropdown on the Draw button · Shift: square/circle · Right-drag: pan · MMB or Alt+drag: orbit · Right-click: cancel",
PdDocument.Mode.TEXTURE: "Texture editor · tools: TOP TOOLBAR · sizes, color, resolution: RIGHT PANEL · full guide: the book button",
}
func _set_mode(m: int) -> void:
# workspace memory: remember the last 3D mode so the Texture
# Editor button and KEY_6 can toggle back to where the user was
if m != PdDocument.Mode.TEXTURE:
last_3d_mode = m
else:
_fullscreen_view = null
_sync_expand_btns()
doc.set_mode(m)
hint_label.text = _hint_text()
_relayout_views()
_sync()
## Toggle between the two workspaces (the toolbar split button, KEY_6).
func toggle_workspace() -> void:
if doc.mode == PdDocument.Mode.TEXTURE:
_set_mode(last_3d_mode)
else:
_set_mode(PdDocument.Mode.TEXTURE)
func frame_selection() -> void:
if doc.objects.is_empty():
doc.warn("Nothing to frame. The scene is empty - add a shape first.")
return
view3d.frame_selection()
# ---------------------------------------------------------- shortcuts ---
## G / S / R pick the Move / Scale / Rotate gizmo, Blender-style. The key
## for the kind that is ALREADY active hides the gizmo again - the exact
## semantics of the toolbar's [Move] [Scale] [Rotate] toggles.
func _gizmo_shortcut(kind: int) -> void:
if doc.gizmo_on and doc.gizmo_kind == kind:
doc.set_gizmo(false)
else:
doc.set_gizmo_kind(kind)
doc.set_gizmo(true)
_warn_gizmo_target()
func _warn_gizmo_target() -> void:
var hint := doc.gizmo_hint()
if hint != "":
doc.warn(hint)
func _shortcut_input(event: InputEvent) -> void:
if not visible:
return
var k := event as InputEventKey
if k == null or not k.pressed or k.echo:
return
var fo := get_viewport().gui_get_focus_owner()
if fo is LineEdit or fo is TextEdit or fo is SpinBox:
return
var ctrl := k.ctrl_pressed or k.meta_pressed
match k.keycode:
KEY_1: _set_mode(PdDocument.Mode.OBJECT); get_viewport().set_input_as_handled()
KEY_2: _set_mode(PdDocument.Mode.VERTEX); get_viewport().set_input_as_handled()
KEY_3: _set_mode(PdDocument.Mode.EDGE); get_viewport().set_input_as_handled()
KEY_4: _set_mode(PdDocument.Mode.FACE); get_viewport().set_input_as_handled()
KEY_5: _set_mode(PdDocument.Mode.DRAW); get_viewport().set_input_as_handled()
KEY_6: toggle_workspace(); get_viewport().set_input_as_handled()
KEY_G:
# 3D workspace: G/S/R pick the Move/Scale/Rotate
# gizmo (pressing the active kind's key hides the
# gizmo, same as the toolbar toggles). Texture
# workspace keeps G = gizmo visibility toggle.
if doc.mode == PdDocument.Mode.TEXTURE:
doc.set_gizmo(not doc.gizmo_on)
else:
_gizmo_shortcut(0)
get_viewport().set_input_as_handled()
KEY_S:
# 3D workspace: S = Scale gizmo; texture workspace
# keeps the snap toggle (T toggles snap everywhere).
if doc.mode == PdDocument.Mode.TEXTURE:
doc.set_snap(not doc.snap_enabled)
else:
_gizmo_shortcut(1)
get_viewport().set_input_as_handled()
KEY_T:
doc.set_snap(not doc.snap_enabled)
get_viewport().set_input_as_handled()
KEY_V:
doc.set_grid_visible(not doc.grid_visible)
get_viewport().set_input_as_handled()
KEY_B:
doc.set_both_sides(not doc.both_sides)
get_viewport().set_input_as_handled()
KEY_Z:
if ctrl:
if event.shift_pressed:
doc.do_redo()
else:
doc.do_undo()
get_viewport().set_input_as_handled()
KEY_Y:
if ctrl:
doc.do_redo()
get_viewport().set_input_as_handled()
KEY_D:
if ctrl:
doc.duplicate_selected()
get_viewport().set_input_as_handled()
KEY_A:
if ctrl:
doc.select_all()
get_viewport().set_input_as_handled()
KEY_DELETE, KEY_BACKSPACE:
doc.delete_selection()
get_viewport().set_input_as_handled()
KEY_F:
frame_selection()
get_viewport().set_input_as_handled()
KEY_R:
if doc.mode == PdDocument.Mode.TEXTURE and doc.tex_edit:
# UV editor: rotate the selected faces' UVs 90
# degrees (Shift = counter-clockwise)
doc.rotate_uv_selected(doc.active_obj,
-1 if k.shift_pressed else 1)
else:
# 3D workspace: R = Rotate gizmo
_gizmo_shortcut(2)
get_viewport().set_input_as_handled()
KEY_SPACE:
_toggle_view_fullscreen()
get_viewport().set_input_as_handled()
KEY_ESCAPE:
doc.clear_all_sel()
get_viewport().set_input_as_handled()
func _make_input_handled() -> void:
get_viewport().set_input_as_handled()
# ------------------------------------------------------------- export ---
func _file_dialog(save: bool, filters: PackedStringArray, cb: Callable, title: String,
access := EditorFileDialog.ACCESS_RESOURCES, start_dir := "res://") -> void:
if _dlg and is_instance_valid(_dlg):
_dlg.queue_free()
_dlg = EditorFileDialog.new()
_dlg.access = access
_dlg.file_mode = EditorFileDialog.FILE_MODE_SAVE_FILE if save \
else EditorFileDialog.FILE_MODE_OPEN_FILE
_dlg.filters = filters
_dlg.current_dir = start_dir
_dlg.title = title
_dlg.ok_button_text = "Save" if save else "Open"
EditorInterface.get_base_control().add_child(_dlg)
_dlg.file_selected.connect(cb)
_dlg.canceled.connect(func():
_dlg.queue_free()
_dlg = null)
_dlg.popup_centered(Vector2i(760, 460))
func _refresh_filesystem() -> void:
EditorInterface.get_resource_filesystem().scan()
func _save_project() -> void:
_file_dialog(true,
PackedStringArray(["*.pdoodle ; Polydoodle Project"]),
func(path: String):
var err := PdIo.save_project(doc, path)
if err == OK:
_refresh_filesystem()
set_status("Saved project to %s" % path if err == OK
else "Save failed: %s" % error_string(err)),
"Save Polydoodle Project")
var _importing := false
var _last_import_dir := ""
var _import_dlg: AcceptDialog = null
func _import_model() -> void:
if _importing:
set_status("A model import is already running")
return
var start := _last_import_dir
if start.is_empty() or not DirAccess.dir_exists_absolute(start):
start = ProjectSettings.globalize_path("res://")
_file_dialog(false, PdImport.dialog_filters(),
func(path: String):
_last_import_dir = path.get_base_dir()
_run_import(path),
"Import 3D Model", EditorFileDialog.ACCESS_FILESYSTEM, start)
func _run_import(path: String) -> void:
if _importing:
set_status("A model import is already running")
return
_importing = true
path = ProjectSettings.localize_path(path)
var opts := {"textures": true, "merge": true, "fit": true}
var progress := func(f: float, text: String):
set_status("%s... %d%%" % [text, int(f * 100.0)])
var model: Dictionary = await PdImport.load_model(path, opts, self,
progress)
if not is_instance_valid(self) or not is_inside_tree():
return
if not model["ok"]:
_importing = false
_import_report("Import failed", String(model["error"]), [])
return
var res: Dictionary = await PdImport.build(model, opts, self, progress)
if not is_instance_valid(self) or not is_inside_tree():
return
_importing = false
if not res["ok"]:
_import_report("Import failed", String(res["error"]), [])
return
var objs: Array = res["objects"]
doc.add_imported_objects(objs, path.get_file().get_basename())
frame_selection()
set_status("Imported %s: %d objects, %d faces" % [
path.get_file(), objs.size(), int(res["faces"])])
var notes: Array = res["warnings"]
if not notes.is_empty():
_import_report("Import notes",
"%s was imported with notes:" % path.get_file(), notes)
func _import_report(title: String, text: String, notes: Array) -> void:
set_status(text)
var font := get_theme_font("font", "Label")
var fsize := get_theme_font_size("font_size", "Label")
var win := get_window().size
# the dialog never takes more than ~70% of the editor window; the text
# is trimmed to the lines that fit so nothing is ever clipped
var max_w := clampf(win.x * 0.6, 300.0, 520.0)
var max_h := int(win.y * 0.7)
var line_h := font.get_height(fsize) + 3.0
var capacity := maxi(4, int((max_h - 110.0) / line_h))
var out := PackedStringArray()
out.append_array(_wrap_text(text, font, fsize, max_w, mini(4, capacity)))
var shown := 0
for n in notes:
var item := _wrap_text(String(n), font, fsize, max_w - 14.0, 2)
if out.size() + item.size() >= capacity:
out.append("- ... and %d more" % (notes.size() - shown))
break
for k in item.size():
out.append(("- " if k == 0 else " ") + item[k])
shown += 1
if is_instance_valid(_import_dlg):
_import_dlg.queue_free()
var dlg := AcceptDialog.new()
dlg.title = title
dlg.dialog_text = "\n".join(out)
dlg.dialog_autowrap = false # wrapped above, so the size is exact
dlg.exclusive = false
dlg.min_size = Vector2i(320, 0)
dlg.max_size = Vector2i(int(max_w) + 90, max_h)
dlg.confirmed.connect(dlg.queue_free)
dlg.canceled.connect(dlg.queue_free)
_import_dlg = dlg
add_child(dlg)
dlg.popup_centered()
## Image import for the texture editor: the picked image floats on the
## canvas as a sticker (move / wheel-scale / click places). Placement is
## alpha-blended into the atlas and undoable; afterwards the texels can
## be painted over or erased like any other paint.
func _import_image() -> void:
if doc.active() == null:
doc.warn("Select a shape first, then import an image onto its texture.")
return
_file_dialog(false,
PackedStringArray(["*.png,*.jpg,*.jpeg,*.webp,*.bmp,*.tga ; Images"]),
func(path: String):
var img := Image.load_from_file(path)
if img == null or img.is_empty():
doc.warn("Could not load image: %s" % path)
return
uv_canvas.begin_sticker(img),
"Import Image to Texture")
func _open_project() -> void:
_file_dialog(false,
PackedStringArray(["*.pdoodle ; Polydoodle Project"]),
func(path: String):
var d := PdIo.load_project(path)
if d == null:
set_status("Could not open %s" % path)
return
# copy loaded doc contents into our live doc
doc.restore_snapshot(d.snapshot())
doc.bg_color = d.bg_color
doc.grid_size = d.grid_size
doc.grid_visible = d.grid_visible
doc.snap_enabled = d.snap_enabled
doc.gizmo_on = d.gizmo_on
doc.draw_free = d.draw_free
doc.draw_kind = d.draw_kind
doc.paint_color = d.paint_color
doc.paint_tool = d.paint_tool
doc.brush_size = d.brush_size
doc.pixel_size = d.pixel_size
doc.recent_colors = d.recent_colors
doc.both_sides = d.both_sides
doc.view_shading = d.view_shading
doc.uv_snap = d.uv_snap
doc.tex_filter = d.tex_filter
doc.pixel_px = d.pixel_px
doc.gizmo_kind = d.gizmo_kind
doc.brush_opacity = d.brush_opacity
doc.brush_smooth = d.brush_smooth
doc.face_lock = d.face_lock
doc.inset_dist = d.inset_dist
doc.hints_enabled = d.hints_enabled
doc.show_checker = d.show_checker
doc.export_checker = d.export_checker
d.release()
doc.notify_doc()
doc.settings_changed.emit()
set_status("Opened %s" % path)
frame_selection(),
"Open Polydoodle Project")
func _export_result(err: Error, ok_text: String) -> void:
if err == OK:
_refresh_filesystem()
set_status(ok_text)
else:
doc.warn("Export failed: %s. Check that the folder is writable." % error_string(err))
func _export(kind: String) -> void:
if doc.exportable_count() == 0:
if doc.objects.is_empty():
doc.warn("Nothing to export. The scene is empty - add a shape first.")
else:
doc.warn("Nothing to export. Every shape is hidden - show one (eye icon in the hierarchy).")
return
match kind:
"tres":
_file_dialog(true, PackedStringArray(["*.tres ; Godot Mesh"]),
func(path: String):
_export_result(PdIo.save_mesh_tres(doc, path), "Exported mesh to %s" % path),
"Export Mesh (.tres)")
"tscn":
_file_dialog(true, PackedStringArray(["*.tscn ; Godot Scene"]),
func(path: String):
_export_result(PdIo.save_scene_tscn(doc, path), "Exported scene to %s" % path),
"Export Scene (.tscn)")
"obj":
_file_dialog(true, PackedStringArray(["*.obj ; Wavefront OBJ"]),
func(path: String):
_export_result(PdIo.write_obj(doc, path), "Exported OBJ to %s" % path),
"Export OBJ")
"scene":
var msg := PdIo.add_to_scene(doc)
if msg.begins_with("Open or") or msg.begins_with("Nothing"):
doc.warn(msg)
else:
set_status(msg)