Compare commits

...
54 Commits
Author SHA1 Message Date
ausboss 2ec0c6c425 Merge pull request #404 from ausboss/release/v2.27.0
Release 2.27.0
2026-11-23 19:06:35 -06:00
ausboss 80d056fc55 Release 2.27.0 2026-11-23 18:54:17 -06:00
ausboss 84c346c250 Merge pull request #402 from ausboss/fix/callout-row-class
Callout: keep its styles off the shared card rows
2026-11-23 18:23:29 -06:00
ausboss 3fb2f028e3 Merge pull request #401 from ausboss/fix/grid-under-feet
Stand the 3D viewer's floor grid under the model
2026-11-23 18:22:37 -06:00
ausboss d9c5a9e758 Merge pull request #403 from ausboss/feat/clip-window
Clip window for App-mode forms, with min/max clip seconds
2026-11-23 18:22:20 -06:00
ausboss 04e4d71a73 Merge remote-tracking branch 'origin/main' into feat/clip-window
# Conflicts:
#	CHANGELOG.md
2026-11-23 18:21:16 -06:00
ausboss 5f6ba96174 Play the picked part of the video above the App mode clip window
The clip window now has a muted player over its strip that plays only the
part a run uses, on a loop; a drag shows the frame under the moving edge,
and a click pauses it. It plays only while it is on screen.

The form row is now refilled whenever it is empty while App mode is open
(a watcher instead of a few timed retries), so a slow reload no longer
leaves the row blank.
2026-11-23 18:18:04 -06:00
ausboss b1f9b9ab21 Keep a DOM widget in its App mode form row
The form moves a listed DOM widget (the clip window) into its row once,
as the row mounts. The graph's widget layer could take the element back
a moment later, so the row stayed empty after switching from the graph
or reopening the page in App mode. Move it back into the row after each
mode change.
2026-11-23 18:01:32 -06:00
ausboss 762b84886d Callout: keep its styles off the shared card rows
The Callout's stylesheet styled .ausboss-card-row, the class every widget
card row uses. Once a Callout was on the canvas, card rows became flex
rows: Workflow Switches cut its names to a letter or two and other cards
lost their column layout. The Callout's own classes are now
ausboss-callout-row, -block, -title and -icon, and a test fails if its CSS
styles a class widget_card.mjs owns.
2026-11-23 14:41:29 -06:00
ausboss 1321486537 Stand the 3D viewer's floor grid under the model
ComfyUI's grid lies at height 0, and TRELLIS 2 centres its models there,
so the grid ran through the middle of the person in Pause for Shot's
viewer. Each frame the grid now moves to the model's lowest point, the
floor the shadow already uses. While the viewer captures a run's
pictures the grid goes back to 0, so Load3D's image with the grid shown
is unchanged.
2026-11-23 13:36:22 -06:00
ausboss 6e3ced5f2d Merge pull request #380 from TWIISTED-STUDIOS/fix/media-picker-virtual-scroll-folders
Fix media picker 400-item limit with virtual scrolling and folder navigation
2026-11-23 12:52:14 -06:00
ausboss 841d82dff1 Changelog: media picker shows every file, in folders 2026-11-23 12:51:15 -06:00
ausboss 3d3a0d1a51 Merge remote-tracking branch 'origin/main' into media-picker-380 2026-11-23 12:51:03 -06:00
ausboss 515bb90afb Merge pull request #400 from ausboss/feat/viewer-ratio 2026-11-23 12:42:15 -06:00
ausboss e8df529c76 Document Pause for Shot and the 3D viewer extras 2026-11-23 11:21:37 -06:00
ausboss b40e19cf35 Show the paused model on every page with ComfyUI's newer 3D output
ComfyUI now names Preview 3D (Advanced)'s model in a "3d" list of
saved files instead of the older "result" list. Pause for Shot only
read the older shape, so it carried no model along and a page that did
not press Run showed the 360 with an empty viewer. Both shapes are read
now, in the node and on the page.
2026-11-23 11:21:37 -06:00
ausboss e40f1075b9 Add Pause for Shot and framing tools for the 3D viewer
Pause for Shot stops a run right after Preview 3D (Advanced) so the shot
can be framed on the model that run just made, then Continue carries on
with the camera exactly as the viewer shows it. A 360 picture wired in
shows behind the model while the run waits, and the backdrop output gives
the part of it the camera sees, with an optional floor shadow.

The 3D viewer also gets aspect ratio chips, Blender-style G/R/S keys for
moving the model, and a tidier toolbar layout.
2026-11-23 10:59:23 -06:00
ausboss c74c4877c3 Merge pull request #399 from ausboss/feat/moving-step-preview 2026-11-22 23:08:06 -06:00
ausboss 0a23673a5a Step preview: a video's step picture moves
For a run that shows its steps, the pack wraps ComfyUI's previewer for
video latents and, after each step, also sends about one frame per second
of the clip (16 at most) in an ausboss.step_frames message. Each frame is
made by the same previewer call ComfyUI makes for the first frame, one at
a time, so no extra memory or files are needed. The shared step overlay
loops them at the clip's own pace on Save Video, Save Image and Step
Preview. Frames skip steps when they would take more than a tenth of the
run (the tiny video decoder on a slow card).
2026-11-22 22:52:13 -06:00
ausboss 852af46786 Merge pull request #397 from ausboss/release/2.26.7
Release 2.26.7
2026-11-21 22:07:54 -06:00
ausboss 63790c2e10 Release 2.26.7 2026-11-21 22:07:00 -06:00
ausboss 2289ef77aa Merge pull request #395 from ausboss/fix/old-copy-warning 2026-11-21 21:02:15 -06:00
ausboss 7d09daeb39 Workflow Note: a missing AusBoss node offers an update in the Manager, not a GitHub clone 2026-11-21 20:44:51 -06:00
ausboss 7c61ae226d Workflow skill: clone into ausboss-nodes too 2026-11-21 20:07:17 -06:00
ausboss 52cb5d8493 README: clone into ausboss-nodes, the folder ComfyUI-Manager uses 2026-11-21 20:07:11 -06:00
ausboss bfa7c35a64 Say in the browser when an old copy of the pack loads instead of the new one 2026-11-21 20:02:28 -06:00
ausboss 916197fb28 Merge pull request #394 from ausboss/feat/lora-strength-links
LoRA Loader: set a row's strength with a wire
2026-11-21 16:39:12 -06:00
ausboss 286866fa0f LoRA Loader strength links: help page and changelog 2026-11-21 16:37:24 -06:00
ausboss a9fe941b03 LoRA Loader strength links: outline the whole linked box 2026-11-21 16:33:50 -06:00
ausboss f684af1273 LoRA Loader strength links: wires shown by default 2026-11-21 16:28:38 -06:00
ausboss 734e88af1f LoRA Loader strength links: Nodes 2.0 drop, Chinese labels, tests 2026-11-21 16:24:45 -06:00
ausboss a3a5cf2826 LoRA Loader: link a number wire to a row's strength 2026-11-21 16:15:09 -06:00
ausboss 2fa296fe89 Merge pull request #393 from ausboss/fix/saved-fallbacks-follow-run
Saved-fallback test follows run() into write() (#391)
2026-11-21 16:14:58 -06:00
ausboss 07461b5972 Merge pull request #392 from ausboss/feat/zh-node-faces
Show Chinese on node faces when ComfyUI's language is Chinese
2026-11-21 16:05:54 -06:00
ausboss 952f72bedf Saved-fallback test: follow run() into write() for H3 Prompt Writer (#391) 2026-11-21 15:40:53 -06:00
ausboss 3792649ae5 Merge pull request #390 from ausboss/fix/workflow-note-shared-folders
Workflow Note: find models in Stability Matrix's shared folders
2026-11-21 15:31:16 -06:00
ausboss 5b00d85094 Merge remote-tracking branch 'origin/main' into fix/workflow-note-shared-folders
# Conflicts:
#	CHANGELOG.md
2026-11-21 15:30:22 -06:00
ausboss 09b8c499e7 Merge pull request #389 from ausboss/fix/py310-tomllib
Load on Python 3.10, where tomllib does not exist
2026-11-21 15:30:11 -06:00
ausboss d2782a2a90 Show Chinese on node faces when ComfyUI's language is Chinese
Cards, panels, buttons, choices and tooltips follow Settings > Language through js/shared/i18n.mjs and the table in js/shared/i18n_zh.mjs. Text with no entry stays English; widget names and values are untouched. Adds the missing Chinese socket names for H3 Prompt Writer and a few other nodes.
2026-11-21 12:28:18 -06:00
ausboss 3ef50e0262 Workflow Note: find models in Stability Matrix's shared folders (#386)
A row in folder clip or unet was never checked: ComfyUI's /models/<folder>
list answers 404 for those old names, though it files them as
text_encoders and diffusion_models everywhere else. Stability Matrix uses
both. Rows now ask for the folder by the name ComfyUI lists it under.

The card also names the folders this install reads with a name of their
own (Stability Matrix's Data/Models/Lora, from extra_model_paths.yaml) under
the usual ComfyUI/models/<folder> heading, and a missing file's dot lists
every folder that was searched. Both come from ComfyUI's
/experiment/models; without it the card reads as before.

Fixes #386
2026-11-21 09:28:11 -06:00
ausboss f9cd259a3e Load on Python 3.10, where tomllib does not exist (#387)
__init__.py and the single-copy guard imported tomllib at the top, which
only exists from Python 3.11, so on a 3.10 install (some Stability Matrix
setups) the whole pack failed to import. Both now read pyproject.toml
through nodes/_pyproject.py: tomllib when it is there, the tomli backport
when installed, else a small reader for the plain name and version lines
of [project]. No new dependency.

Fixes #387
2026-11-21 09:23:56 -06:00
ausboss 9f3a6f2010 Media picker: open in the current pick's folder, pack icons, plain names inside a folder
The picker opened at the top level, so a pick in a subfolder was not shown
and the preview stayed empty. It now opens in that file's folder with the
file highlighted. Rows inside a folder show just the file name (a search
still shows the folder), the folder marks are drawn in the pack's style
instead of emoji, and the path line names the temp folder and drops the
trailing slash at the top level.
2026-11-20 22:54:53 -06:00
ausboss 2f31463af8 Merge main into fix/media-picker-virtual-scroll-folders 2026-11-20 22:39:48 -06:00
ausboss 9ab4365245 Merge pull request #385 from ausboss/fix/latent-size-chips-keep-default
Latent Size: ratio chips keep the current megapixels by default
2026-11-20 22:33:46 -06:00
ausboss 5dfbcdd99c Merge remote-tracking branch 'origin/main' into fix/latent-size-chips-keep-default
# Conflicts:
#	CHANGELOG.md
2026-11-20 22:33:13 -06:00
ausboss 20f860d5ff Merge pull request #382 from ausboss/feat/h3-full-prompt-tab
H3 Prompt Writer: a Full prompt tab to see and change the written prompt
2026-11-20 22:32:59 -06:00
ausboss 44edcc633c Latent Size: ratio chips keep the current megapixels by default
Fixes #377. The gear setting lived only in browser storage, so private
windows lost it every time. It now starts on; turning it off still brings
back the ~1MP jump.
2026-11-20 21:29:18 -06:00
ausboss c99425cef1 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/h3-full-prompt-tab
# Conflicts:
#	CHANGELOG.md
2026-11-20 21:26:03 -06:00
ausboss 743126d86f H3 Prompt Writer help: drop the reset-and-edit-again line 2026-11-20 15:42:37 -06:00
ausboss fb430afca1 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/h3-full-prompt-tab
# Conflicts:
#	CHANGELOG.md
2026-11-20 15:39:03 -06:00
ausboss a606d34b97 H3 Prompt Writer: a Full prompt tab to see and change the written prompt
The node gets two tabs. Simple is the card as before and stays the
default. Full prompt shows the prompt the node wrote on its last run, in a
box you can edit; when it holds an edit, that text is sent to H3 instead.
An amber dot on the tab, a note under the box and a line on the Simple tab
say an edit is being sent. Reset to written clears it.

- New optional `full_prompt` input, appended last, with a "" fallback for
  older saves. The node now returns the written prompt as ui output
  (`written_prompt`); `write` is unchanged and `run` wraps it.
- Widget card: `when` gets the node as well as the values, a panel row can
  grow, and `refreshByHand` lets a panel redraw the card.
- Fix: a hidden textarea or panel row stayed visible, because the later
  `display:block` rules for those rows beat `.hidden`.
2026-11-20 14:03:47 -06:00
TWIISTED-STUDIOS 6d1ca0055d Fix media picker scrolling and add folder navigation 2026-11-19 23:50:35 +00:00
ausboss 72543c0b35 Add a Clip length limits fold to the clip node face
min_seconds and max_seconds get a place on the face: a fold under Crop,
pad & resize, built like it and closed by default. The closed header shows
the limits ("5 – 8 s", "from 5 s", "up to 8 s" or "off"); open, it holds
Shortest and Longest as scrub inputs in seconds. Typing one past the other
moves the other along, so the shortest never sits above the longest.
2026-11-16 11:42:12 -06:00
ausboss b2afb6c7a7 Add a clip window for App-mode forms and min/max clip seconds
Video Crop + Rotate + Pad -> Clip gets two appended optional inputs,
min_seconds and max_seconds (0 = no limit). After the window is resolved
the run keeps its length inside them: a longer pick is cut, a shorter one
grows (the start moves back where the video ends first), and a video
shorter than the min is used whole. Fixed frames still wins. Both are in
IS_CHANGED, and nothing changes while both are 0.

The node's timeline obeys the limits (timeline_math.mjs limitClipSeconds
mirrors the backend rule), and a new hidden DOM widget, clip_window, shows
only the part of the video that gets used: a strip of pictures with a box
to drag and edges that stop at the limits. js/app_mode lends it to a form
that lists it; on the graph the node's face is unchanged.
2026-11-16 10:36:56 -06:00
94 changed files with 8276 additions and 156 deletions
+100
View File
@@ -2,6 +2,106 @@
All notable changes to ComfyUI-AusBoss are documented here.
## 2.27.0 - 2026-11-23
- **Video Crop + Rotate + Pad → Clip 🆎 can put a clip window in an App-mode
form.** List the node's `clip_window` field and the form shows the video,
playing only the part that gets used, over a strip of pictures with a box
over that part: drag the box to pick where the clip starts, drag an edge to
shorten it. Two new inputs, `min_seconds` and `max_seconds`, keep the clip's
length in a range; the edges stop there, on the node's timeline too, and a
run keeps to them. A video shorter than the minimum is used whole. Both are
0 (no limit) by default and are set in a new **Clip length limits** fold
under Crop, pad & resize, closed unless you open it.
- **New node: Pause for Shot 🆎.** It stops a run right after the 3D
viewer so you can frame your shot on the model that run just made, then
**Continue** carries on with the camera exactly as the viewer shows it.
Nothing before the pause runs again. Wire in a 360 picture and it shows
behind the model while you frame, and the node hands on the part of it
the camera sees, with an optional floor shadow under the model.
- **ComfyUI's 3D viewers get Blender keys, shape chips and a 360 strip.**
With the mouse over a viewer, G, R and S move, turn and size the model,
as in Blender. Preview 3D (Advanced) and Save 3D (Advanced) get the shape
chips from Latent Size above their width and height. Press N for a strip
that turns the 360 background and changes the model's light and colours.
The axis gizmo moves to the top-right corner, with zoom, pan and grid
tools under it.
- **The 3D viewer's floor grid is under the model's feet.** It used to run
through the middle of many models, such as a person built by TRELLIS 2.
Now it sits at the model's lowest point, where the floor shadow goes.
The pictures a run takes from the viewer stay exactly as before.
- **The step preview of a video now moves.** With **Preview steps** on in
Save Video, or a Step Preview node in the workflow, a video model such as
MiniMax H3 shows a few frames of the clip after each step, about one per
second, playing in a loop. You see the motion and the shots take shape,
not only the first frame, and can stop a clip that is going wrong. It
costs next to nothing: a 5 second H3 clip took 53.8 s with it, 53.6 s
with no step pictures at all.
- **The picture and video picker shows every file, in folders.** The list
used to stop at 400 files and ask you to type to narrow it. Now you can
scroll through all of them, open folders, and go back up with `..`.
Typing still searches every folder. The picker opens in the folder of the
file you picked, with that file highlighted. Thanks to TWIISTED-STUDIOS.
- **Switch names show in full again.** Workflow Switches cut its names down to
a letter or two ("Per…" for "Blur the person"), and other node cards lost
their row layout, once a Callout had been on the canvas. The Callout now
keeps its styles to its own cards.
## 2.26.7 - 2026-11-21
- **An old copy of the pack that keeps loading now says so in the browser.**
With an old git clone in `custom_nodes/ComfyUI-AusBoss` and a newer
Manager install in `custom_nodes/ausboss-nodes`, the old clone loads,
because copies from before 2.24.0 cannot step aside. Every node added
since, such as Edit Lock, then shows as missing, and updating does not
help. The newer copy now shows a message in ComfyUI that names the old
folder to delete. Before, the only sign was a line in the console.
- **Workflow Note: a missing AusBoss node asks for an update, not a GitHub
clone.** When a workflow needs an AusBoss node your version doesn't have,
the note's AusBoss row now shows **Update**. It opens ComfyUI-Manager's
updates list and says to restart afterwards. Before, the row showed
**Get it**, which opened GitHub, and cloning from there added a second
copy of the pack. **Detect from this workflow** now lists the pack as
AusBoss nodes with its Comfy Registry link, whatever folder it is in.
- **LoRA Loader: set a LoRA's strength with a wire.** Drag a number wire,
from a slider or a Float node, onto any row and that row's strength follows
it. The row's box turns dashed teal and shows the number coming in; click
it to find the source, or right-click the row to unlink. The CLIP strength
keeps its ratio to the model strength (#388).
- **Node faces show Chinese when ComfyUI's language is Chinese.** The
labels, buttons, choices and tooltips the pack draws on its nodes, such as
the cards on FlashVSR and Image Resize, H3 Prompt Writer, Workflow Switches
and the video and image crop faces, now follow Settings > Language
(Chinese, in Simplified characters). Reload the page after changing the language. Nothing
saved in a workflow changes, and text with no Chinese yet stays English.
H3 Prompt Writer's socket names are translated too.
- **H3 Prompt Writer: see and change the full prompt.** A new **Full
prompt** tab at the top of the node shows the prompt it wrote on its last
run. Edit it there, for example to take out one camera move, and H3 gets
your text as it is. An amber dot shows an edit is being sent, and **Reset
to written** goes back to the node's own prompt. The **Simple** tab works
as before and stays the default.
- **Latent Size's ratio chips keep your megapixels.** Clicking a ratio chip
now changes the shape at the size you set, instead of jumping back to about
one megapixel. The old jump is still in the gear: turn off **Chips keep
current budget**. The setting is kept in the browser, so a private window
forgot it every time; it now starts on.
- **The pack loads on Python 3.10 again.** On a 3.10 install, such as some
Stability Matrix setups, the whole pack failed to load with
`No module named 'tomllib'`. It now loads there with nothing extra to
install (#387).
- **Workflow Note finds models in Stability Matrix's shared folders.**
A row whose folder uses an old name, `clip` or `unet`, was never checked
("This install has no model folder") even with the file in place. Those
rows are now checked like `text_encoders` and `diffusion_models`, the
names ComfyUI files them under. When the install also reads a kind of
model from a folder with a different name, such as Stability Matrix's
`Data/Models/Lora`, the card names that folder under the usual one, so
you know where your files are found and where a new one can go (#386).
## 2.26.6 - 2026-11-20
- **Image Toolbox's help page says what happens with too many pieces.**
+7
View File
@@ -150,6 +150,13 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
- Category: `🆎 AusBoss/<Group>`. The emoji is safe here — categories reach
the frontend as JSON and are never printed to the console at import time.
- Every node gets `DESCRIPTION`, input `tooltip`s, and `OUTPUT_TOOLTIPS`.
- Words a node face draws itself (card labels, buttons, choices, tooltips)
are translated for a Chinese ComfyUI by `js/i18n/index.js`: add the English
text and its Chinese to `js/shared/i18n_zh.mjs`, or to `STAYS_ENGLISH` there
when it should not change. Text with no entry stays English, and a widget's
name and value are never translated. Never read a label back from the DOM
to decide something; keep that in state (the translator changes the text).
`tests/i18n.test.mjs` fails on a card word with no entry.
- IMAGE tensors are BHWC float batches; MASK is BHW. Return tuples always,
even for one output: `(value,)`.
- Console output at import time must stay ASCII — ComfyUI on Windows often
+17 -2
View File
@@ -38,12 +38,12 @@ In **ComfyUI-Manager**, open the Custom Nodes Manager, search for **AusBoss** an
```bash
cd ComfyUI/custom_nodes
git clone https://github.com/ausboss/ComfyUI-AusBoss.git
git clone https://github.com/ausboss/ComfyUI-AusBoss.git ausboss-nodes
```
Restart ComfyUI and search the node library for **AusBoss**.
Install it one way, not both. Manager puts the pack in `custom_nodes/ausboss-nodes` and a clone in `custom_nodes/ComfyUI-AusBoss`. They are the same pack, so if both folders are there, delete one. The console says which copy it skipped.
Clone into `ausboss-nodes`, the folder ComfyUI-Manager uses, so Manager sees the same copy and updates it instead of adding a second one. If you also have a `custom_nodes/ComfyUI-AusBoss` folder from an older clone, delete it: with two copies, an old one can keep loading after every update, and its newer nodes show as missing. ComfyUI shows a message naming the folder when this happens.
After an update, through Manager or `git pull`, restart ComfyUI and hard-refresh the browser with **Ctrl+Shift+R**. Otherwise the browser keeps the old JavaScript, and the pack warns you about it. Manager can install a version or two behind while the Comfy Registry reviews a new release. To get the newest one, pick it in Manager's version list, or update by hand: delete the pack's folder in `ComfyUI/custom_nodes` and clone the repository as shown above.
@@ -341,6 +341,21 @@ Here Krea 2 Outpaint takes a 16:9 photo to 4:5 in one pass. [Open the Krea 2 Out
The patch relies on ComfyUI's internal attention code. Its [help page](js/docs/AUSBOSS_NODES_Krea2OutpaintModelPatch.md) explains both setups and what happens without reference conditioning.
## 3D viewer
### Pause for Shot
Stops a run right after a **Preview 3D (Advanced)** viewer, so you can frame your shot on the model that run just made. Turn the camera, zoom, move the model, then press **Continue**: the run goes on with the shot exactly as the viewer shows it, and nothing before the pause runs again. **Stop** ends the run there. Wire a 360 picture into `panorama` and it shows behind the model while you frame, and `backdrop` hands on the part of it the camera sees, with an optional floor shadow. Set **Pause** to *run through* for runs nobody is watching.
### Extras in ComfyUI's 3D viewers
The pack also adds to ComfyUI's own 3D viewers, with no new node:
- **Shape chips** above the width and height of Preview 3D (Advanced) and Save 3D (Advanced): pick a shape and the frame follows.
- **Blender keys** with the mouse over a viewer: G move, R rotate, S scale, X / Y / Z to lock an axis, a typed number for an exact amount, the number keys for front, side and top views, and Home to frame the model.
- **Viewport tools** in the top-right corner: drag the axis gizmo to orbit, the magnifier to zoom, the hand to pan, and a grid switch.
- **A 360 strip** (press N, or the small 360 tab): spin and tip the model, turn, tilt and roll the 360 background, its brightness and blur, the light and the model's colours. The settings save with the workflow.
## Workflow utilities
Core ComfyUI has its own nodes for most of these jobs, and they work fine. These versions add the extras described under each one.
+16 -5
View File
@@ -11,7 +11,6 @@ of taking the whole pack down, so one broken node never hides the rest.
import importlib
import os
import tomllib
import traceback
# One entry per file in nodes/, kept alphabetical. The order has no
@@ -46,6 +45,7 @@ NODE_MODULES = [
"node_mask_by_name",
"node_mask_by_touch",
"node_math",
"node_pause_shot",
"node_prompt_variations",
"node_realign_to_source",
"node_refine_mask",
@@ -93,8 +93,10 @@ for _module_name in NODE_MODULES:
traceback.print_exc()
# Folder ComfyUI serves to the browser; every .js file in it is loaded as a
# frontend extension. Shared modules use .mjs so they are import-only.
WEB_DIRECTORY = None if _other_copy else "./js"
# frontend extension. Shared modules use .mjs so they are import-only. A copy
# that steps aside serves only the script that warns about it in the browser,
# since the console line alone is easy to miss.
WEB_DIRECTORY = "./web_second_copy" if _other_copy else "./js"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
@@ -102,9 +104,10 @@ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
def _read_version():
"""Version straight from pyproject.toml so it is never duplicated."""
try:
from .nodes._pyproject import read_project
pyproject = os.path.join(os.path.dirname(__file__), "pyproject.toml")
with open(pyproject, "rb") as f:
version = tomllib.load(f).get("project", {}).get("version")
version = read_project(pyproject).get("version")
return version if isinstance(version, str) and version.strip() else "unknown"
except Exception:
return "unknown"
@@ -144,6 +147,14 @@ def _print_second_copy():
if _other_copy:
_print_second_copy()
try:
from .nodes._single_copy import register_second_copy_notice, second_copy_notice
register_second_copy_notice(
second_copy_notice(os.path.dirname(__file__), _read_version(), _other_copy)
)
except Exception:
traceback.print_exc()
else:
try:
from .nodes._frontend_cache import register_frontend_cache_guard
+3 -3
View File
@@ -1,9 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.26.6">
<title>release: v2.26.6</title>
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.27.0">
<title>release: v2.27.0</title>
<path fill="#555" d="M0 0h48v20H0z"/>
<path fill="#00b4aa" d="M48 0h57v20H48z"/>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="24" y="14">release</text>
<text x="76.5" y="14">v2.26.6</text>
<text x="76.5" y="14">v2.27.0</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 425 B

After

Width:  |  Height:  |  Size: 425 B

+55 -2
View File
@@ -3,7 +3,7 @@
// js/shared/app_mode.mjs; this file watches which mode the open workflow is
// in and hands the fields over.
import { app } from "../../../scripts/app.js";
import { createAppModeSync, workflowMode } from "../shared/app_mode.mjs";
import { APP_MODE, appFields, createAppModeSync, formHostSelector, workflowMode } from "../shared/app_mode.mjs";
const sync = createAppModeSync({
find(nodeId, name) {
@@ -17,6 +17,57 @@ const sync = createAppModeSync({
},
});
function findWidget(nodeId, name) {
const graph = app.rootGraph ?? app.graph;
const node = graph?.getNodeById?.(/^\d+$/.test(nodeId) ? Number(nodeId) : nodeId);
return node?.widgets?.find((entry) => entry.name === name) ?? null;
}
// A DOM widget the form lists goes into its row, and back again if the
// graph's widget layer took it (see formHostSelector). Rows mount whenever
// the form draws, which can be well after the mode changes, so while a
// workflow is in App mode the page is watched and an empty row is filled
// on the next frame.
function rehomeDomWidgets() {
const workflow = app.extensionManager?.workflow?.activeWorkflow;
if (workflowMode(workflow) !== APP_MODE) return;
for (const { nodeId, widget: name } of appFields((app.rootGraph ?? app.graph)?.extra?.linearData)) {
const element = findWidget(nodeId, name)?.element;
if (!(element instanceof HTMLElement)) continue;
const host = document.querySelector(formHostSelector(nodeId, name));
if (!host || host.contains(element)) continue;
// Something that keeps taking it back: stop rather than fight.
const now = Date.now();
moves = moves.filter((at) => now - at < 3000);
if (moves.length >= 30) return;
moves.push(now);
host.replaceChildren(element);
}
}
let moves = [];
let watcher = null;
let framed = false;
function watchForm(on) {
if (!on) {
watcher?.disconnect();
watcher = null;
return;
}
if (!watcher) {
watcher = new MutationObserver(() => {
if (framed) return;
framed = true;
requestAnimationFrame(() => {
framed = false;
try { rehomeDomWidgets(); } catch (error) { console.warn("[AusBoss] App mode fields:", error); }
});
});
watcher.observe(document.body, { childList: true, subtree: true });
}
rehomeDomWidgets();
}
let queued = false;
// After the current task: a card hides its widgets in a microtask once the
// node has loaded, and the form's fields are shown after that.
@@ -27,7 +78,9 @@ function schedule() {
queued = false;
try {
const workflow = app.extensionManager?.workflow?.activeWorkflow;
sync(workflowMode(workflow), (app.rootGraph ?? app.graph)?.extra?.linearData);
const mode = workflowMode(workflow);
sync(mode, (app.rootGraph ?? app.graph)?.extra?.linearData);
watchForm(mode === APP_MODE);
} catch (error) {
console.warn("[AusBoss] App mode fields:", error);
}
+13 -13
View File
@@ -90,15 +90,15 @@ ${TILE_FACE_CSS}
.ausboss-callout-card[data-card]{background:#111818;border:1px solid #2e3c3b;}
.ausboss-callout-card[data-card] .ausboss-callout-inner{padding:.8em 1em;color:#d9e4e3;font-weight:400;line-height:1.45;}
.ausboss-callout-card[data-card] b{color:#f2f7f6;font-weight:650;}
.ausboss-card-block{margin:0 0 .85em;}
.ausboss-card-block:last-child{margin-bottom:0;}
.ausboss-card-block>*+*{margin-top:.3em;}
.ausboss-card-title{display:flex;align-items:center;gap:.4em;color:#f2f7f6;font-size:1.08em;font-weight:650;}
.ausboss-card-icon{flex:none;width:1em;height:1em;color:#c9d6d4;}
.ausboss-card-icon svg{display:block;width:100%;height:100%;}
.ausboss-card-row{display:flex;justify-content:space-between;align-items:baseline;gap:1em;}
.ausboss-card-row>span:last-child{flex:none;text-align:right;white-space:nowrap;}
.ausboss-card-row.is-mark,.ausboss-card-row.is-mark b{color:#6fe0d6;font-weight:500;}
.ausboss-callout-block{margin:0 0 .85em;}
.ausboss-callout-block:last-child{margin-bottom:0;}
.ausboss-callout-block>*+*{margin-top:.3em;}
.ausboss-callout-title{display:flex;align-items:center;gap:.4em;color:#f2f7f6;font-size:1.08em;font-weight:650;}
.ausboss-callout-icon{flex:none;width:1em;height:1em;color:#c9d6d4;}
.ausboss-callout-icon svg{display:block;width:100%;height:100%;}
.ausboss-callout-row{display:flex;justify-content:space-between;align-items:baseline;gap:1em;}
.ausboss-callout-row>span:last-child{flex:none;text-align:right;white-space:nowrap;}
.ausboss-callout-row.is-mark,.ausboss-callout-row.is-mark b{color:#6fe0d6;font-weight:500;}
.ausboss-card-small,.ausboss-card-small b{color:#93a6a4;}
.ausboss-card-small{font-size:.92em;}
.ausboss-callout-empty{color:#6f8987;font-size:14px;font-weight:400;}
@@ -185,7 +185,7 @@ const CARD_ICON_PATHS = {
const CARD_ICON_RING = new Set(["clock", "info", "check"]);
function cardIcon(kind) {
const span = el("span", "ausboss-card-icon");
const span = el("span", "ausboss-callout-icon");
const root = svg("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" });
if (CARD_ICON_RING.has(kind)) root.append(svg("circle", { cx: 12, cy: 12, r: 9 }));
for (const d of CARD_ICON_PATHS[kind] ?? []) root.append(svg("path", { d }));
@@ -326,17 +326,17 @@ function appendPieces(state, into, line) {
// An Info card: a title, rows of label and value, and small print.
function renderCard(state, blocks) {
for (const lines of blocks) {
const block = el("div", "ausboss-card-block");
const block = el("div", "ausboss-callout-block");
for (const line of lines) {
let row;
if (line.kind === "title") {
row = el("div", "ausboss-card-title");
row = el("div", "ausboss-callout-title");
if (line.icon) row.append(cardIcon(line.icon));
const words = el("span");
appendPieces(state, words, line.pieces);
row.append(words);
} else if (line.kind === "row") {
row = el("div", `ausboss-card-row${line.highlight ? " is-mark" : ""}`);
row = el("div", `ausboss-callout-row${line.highlight ? " is-mark" : ""}`);
for (const cell of line.cells) {
const side = el("span");
appendPieces(state, side, cell);
+19
View File
@@ -164,6 +164,17 @@ own, with blank lines around it, it is for the whole clip.
Already wrote H3's six parts yourself? Paste them in and they go through as
they are.
## See and change the full prompt
The **Full prompt** tab at the top of the node shows the prompt the node wrote
on its last run. To change one thing, such as taking out "A slow push in.",
edit it there and run again: H3 gets your text exactly as it is in the box. An
amber dot on the tab shows that an edit is being sent. **Reset to written**
throws the edit away and goes back to what the **Simple** tab writes.
While an edit is in place, changes on the Simple tab do nothing, because your
text is sent instead.
## What you can plug in
- **picture_1** to **picture_4**: your pictures.
@@ -224,6 +235,8 @@ as not plugged in.
- **Moments on the beat** (`cut_on_beat`, under **More**): moves each moment onto
the nearest beat of the song. Off keeps your own seconds.
- **Language** (`language`, under **More**): the language of the words in quotes.
- **Full prompt** (`full_prompt`, on the Full prompt tab): your own edit of the
finished prompt. Empty means the node's own prompt is sent.
## Tips
@@ -280,5 +293,11 @@ that sentence the picture's street came back halfway through on 2 of 2. With no
place in your lines H3 has nothing else to use, so it stayed in the picture's
place on 2 of 2.
The Full prompt tab is filled from the node's run, so it shows nothing until
the workflow has run once. The node still writes its own prompt on every run, a
model on `clip` included, so the tab can show it next to your edit and Reset can
go back to it. The last written prompt is kept with the node in a saved
workflow.
H3's own rewriter runs only on paid services, and the open model reads a prompt as
it is. This node does that job on your machine, with no model needed.
+24
View File
@@ -134,6 +134,30 @@ A group that a switch turns on and off shows the lock on its header
instead. The LoRAs in it keep plain grips, so each one is still yours to
turn on or off. Click the header's lock to take the group over.
## A strength set by a wire
To set one LoRA's strength from somewhere else, such as a slider, a Float
node or a sweep, drag that number's wire onto the row and let go. The row
under the pointer lights up teal while you aim; anywhere across the row
works. The wire runs to that row and its strength box turns dashed teal,
showing the number coming in. The bar behind the name follows it.
- **Click the dashed box** to jump to the node the number comes from.
- **Right-click the row → Unlink strength** to take the wire off. The row
goes back to the strength it had.
- The wire sets the model strength. The CLIP strength keeps the same ratio
to it, so a row at 1.0 / 0.5 fed 0.6 runs at 0.6 / 0.3.
- Gear menu → **Linked strength wires** shows the wire (the default), shows
it only while the pointer is on the loader or the number's node, or hides
it.
### Technical details
Each linked row has its own input, `strength_<row id>`, which exists only
while something is linked to that row. It takes FLOAT or INT. In an API
prompt, give a row's input the row's `id` from the `loras` text, for example
`"strength_ra1": 0.6`. A name that matches no row is ignored.
## Strength bars
Every named row paints a center-zero bar behind its name: teal grows right
+53
View File
@@ -0,0 +1,53 @@
# Pause for Shot 🆎
Stops the run right after the 3D viewer so you can frame your shot on the
model it just made. Turn the camera, zoom, spin the model, then press
**Continue**, on this node or on the bar over the viewer. The run goes on with
the shot exactly as the viewer shows it, and nothing before this node runs
again. **Stop** ends the run here.
## How to wire it
Put it between a **Preview 3D (Advanced)** viewer and the node that renders
the shot (such as Render Mesh): the viewer's `model_3d_info`, `camera_info`,
`width` and `height` go in, and the same four come out.
## A 360 behind the model
Wire a 360 picture (twice as wide as tall) into `panorama`. While the run
waits, the viewer shows it behind the model, and `backdrop` gives the part of
it the camera sees, at the shot's size. Put the shot on top of `backdrop` and
the model and its background can be treated apart, such as blurring one and
not the other.
**Shadow** on the viewer's Backdrop tab puts a soft shadow on the floor under
the model, so it stands on the 360 instead of floating in front of it. The
viewer shows it while you frame, and `backdrop` carries the same shadow.
Take the 360 out of the viewer while the run waits, and `backdrop` comes out
plain grey, the same as with no 360 wired in. What you see in the viewer is
what you get.
## Settings
- **Pause**: *wait for me* stops every run here. *run through* lets runs go
straight on with the camera as it was when you pressed Run, for runs nobody
is watching.
## Technical details
- Why it is needed: a run takes the camera from the moment Run is pressed. A
camera moved after that never reaches it, so without a pause you would press
Run a second time.
- Continue sends the viewer's camera, the model's turn and the size as
numbers to the pack's own route. Only a node that is waiting accepts it.
- Cancel in ComfyUI's queue ends a pause too. A page reloaded during a pause
shows the Continue bar again.
- Every open page gets the model to frame, not only the one that pressed Run:
ComfyUI sends a viewer's result only to that page, so the pause sends it
again to all of them.
- The floor grid and shadow sit at the lowest point the viewer finds. On
large models it checks a sample of points. The shadow covers the bottom
tenth of the model. Continue sends that patch with
the camera, and the backdrop is darkened along the same rays Render Mesh
casts, so the shadow lands where the model's feet are drawn.
+1 -1
View File
@@ -2,7 +2,7 @@
Pick a picture size by shape and megapixels, or by dragging. Use it in place of an Empty Latent node: it gives you the width, the height and a blank latent of that size.
- **Shape:** the left button selects landscape or portrait. Ratio chips follow that choice; square retains it for the next selection. Clicking a chip uses its generated size near one megapixel. Enable **Chips keep current budget** in the gear to retain the current area.
- **Shape:** the left button selects landscape or portrait. Ratio chips follow that choice; square retains it for the next selection. Clicking a chip changes the shape and keeps your current megapixels. To have a chip jump to its size near one megapixel instead, turn off **Chips keep current budget** in the gear.
- **Canvas:** drag a side to change one dimension; drag the corner to scale both. Shift frees the corner ratio, Alt removes snapping, and Escape cancels the drag. The bright readout shows the size, megapixels and ratio; an amber dot means the size is off the snap grid, which a typed size can be. Arrow keys nudge the focused canvas by the snap step, or by 8 px with Shift.
- **Size & budget:** scrub or type W, H, or MP. Typed dimensions are preserved exactly. The swap button exchanges dimensions. The **Sizes** chips are ready-made sizes for the current ratio, small to large. They show while the shape is one of the ratio chips; any other shape shows one greyed-out "custom" chip.
- **Gear:** set the **Snap step**, edit the **Ratio rail**, choose the **Latent family** (`latent`) and **Batch size** (`batch_size`), and hide the **Dot grid** or **MP cost curves**. **Snap step** (8, 16, 32 or 64; starts at 32) is the grid that drags, arrow keys and chips land on. The **Ratio rail** is the list of ratio chips, typed as `1:1, 21:9`. The display options apply to every Latent Size node in this browser; latent family and batch size (1 to 64) belong to this node.
+4 -3
View File
@@ -9,9 +9,10 @@ duration, shows a tall video whole, and has a **LOOP** control. `gif` and
`webp` are shown as pictures with just the file name, since a video player
cannot play either.
**Preview steps** above the player (`step_preview`, off by default) shows the clip's first frame in
the player while it is being made, one step at a time, with a **STOP**
button on the player. Stop a clip that is going wrong after the first steps
**Preview steps** above the player (`step_preview`, off by default) shows the clip in
the player while it is being made: after each step, about one frame per
second of the clip plays in a loop, with a **STOP** button on the player.
You see the motion take shape, not only the first frame. Stop a clip that is going wrong after the first steps
instead of waiting for the end; a stopped run saves nothing. The saved
video replaces the steps. The [Step Preview](AUSBOSS_NODES_StepPreview.md)
page has the details.
+18 -1
View File
@@ -9,6 +9,10 @@ Put it anywhere on the canvas. It needs no wires: it shows whichever sampler
in the workflow is making a picture right now, and the caption under the
picture says how far it is ("step 3 of 8").
For a video, the picture moves: after each step a few frames of the clip,
about one per second, play in a loop, so you can see the motion form and
stop a clip that is going wrong.
## The buttons
- **STOP**: stops this run now. Nothing after the sampler runs, so nothing
@@ -65,4 +69,17 @@ ComfyUI uses it.
it does whenever previews are turned on in ComfyUI. The node grows to
hold the picture and keeps the last step after the run.
- Runs queued from another workflow tab are not shown here.
- With video models the step picture is the clip's first frame.
- With a video model (H3, Wan, LTX and others), the step picture moves:
after each step the pack also sends about one frame per second of the
clip (16 at most), and they play in a loop at the clip's own pace. Each
frame is made by the same preview ComfyUI uses for the first frame, one
frame at a time, so it needs no extra memory and no extra files.
- Measured with MiniMax H3 (Pika, 6 steps, a 5 second clip) on one
desktop: 6.22 s a step with no step pictures, 6.35 s with the moving
ones; 53.6 s and 53.8 s for the whole run. With the quick preview the 7
frames of a step take about 1 ms to make, and each step sends about 20 KB.
- With the tiny video decoder (TAESD chosen and `taeh3` in
`models/vae_approx`) the frames are sharper and take longer, about 60 ms
each at 720p on that desktop. The frames never take more than a tenth of
the run's time: on a slower card some steps keep the frames they have
instead of making new ones.
@@ -9,6 +9,34 @@ fill-color bands around it for a **video outpaint**: the `mask` output marks the
bands (and rotation corners), ready for Crop For Inpaint or an in-context video
model that paints black regions.
## Clip window for App mode
In an App-mode form, this node can show a **clip window** instead of its whole
editor: the video, playing only the part that gets used on a loop, over a strip
of pictures from the video with a box over that part. Click the video to pause it. Drag
the box to pick where the clip starts; drag one of its edges to make it shorter
or longer. A line under it says what you picked, such as "8.0 s used, starting at
0:03". To put it in a form, list the field `clip_window` of this node, next to
its `video` field. On the graph the node looks the same as before: the clip
window only shows inside the form.
**Min seconds** and **max seconds** (`min_seconds`, `max_seconds`) keep the clip
inside a range, for example 5 to 8 seconds for a model that is only reliable
there. The edges stop at those lengths, in the form and on the node's own
timeline, and a run keeps to them too:
- a longer pick, or the whole video, is cut to the max;
- a shorter pick grows to the min, and where the video ends first the start
moves back instead;
- a video shorter than the min is used whole, with no error.
Set them in the **Clip length limits** fold, under Crop, pad & resize. It starts
closed; its header shows the limits (`5 – 8 s`, `from 5 s`, `up to 8 s`, or `off`).
Open it for **Shortest** and **Longest**. 0 means no limit, and both are 0 by
default, so older workflows run as before. Typing a Shortest above the Longest
moves the Longest up with it, and the other way round. An exact **Fixed frames**
count wins over them.
## Source and window
- **Inputs**: Pick an existing input video (the list plays the clip under the pointer, muted, and filters as you type), click **Load**, or drop a video file
@@ -164,7 +192,7 @@ The node performs no remote network requests and does not rewrite the source vid
## Connected timing inputs
Five optional sockets sit on the left, above the editor:
Optional timing inputs:
| Input | Meaning |
| --- | --- |
@@ -174,6 +202,7 @@ Five optional sockets sit on the left, above the editor:
| `fixed_frames` | Exact output frames from IN; the source must be long enough. Connected, it sets the length: Duration, Ends at and Frames for step aside. |
| `frame_load_cap` | Maximum frames after rate conversion and Every nth, before Frames for. 0 means unlimited. Connected, it sets the length in place of Duration. When the count is known, dragging the start stops at the last start that fits the kept frames. |
| `last_seconds` | Load only this many seconds from the end of the clip, or of the part before OUT. 0 loads all of it. Use it to carry on from a clip: a long clip then costs no more memory than a short one. |
| `min_seconds` / `max_seconds` | The shortest and longest the clip may be, in seconds; 0 is no limit. Applied after the window is worked out, so the start, Duration and the other inputs set the clip and these keep its length in range (see Clip window for App mode). |
Frame bounds use the source's frame-rate grid, independent of `force_rate`.
The footer labels **Source fps** separately from **Output fps**. A direct
+6
View File
@@ -68,6 +68,12 @@ answered on the same line as the button.
the ComfyUI server for its own model lists.
- **↻ check files** re-runs the check after you move files in. ComfyUI's own
**R** refresh triggers it as well.
- Launchers such as Stability Matrix keep models in shared folders of their
own, for example `Data/Models/Lora`. Files there count, and the card names
such a folder under the usual heading ("also read from ..."), so you can
see where your files are found and put new ones there. The old folder
names `clip` and `unet` are checked as `text_encoders` and
`diffusion_models`, the names ComfyUI uses for them.
- Folder `input` is for a sample image or clip shipped with the workflow: it
is looked for in `ComfyUI/input`.
- Clicking a file name copies it — handy for searching a loader's picker.
+1
View File
@@ -46,6 +46,7 @@ help panel.
| A prompt that picks from `{a\|b\|c}` choices on each run, by seed | Prompt Variations (`AUSBOSS_NODES_PromptVariations`) |
| Do maths on numbers | Math Expression (`AUSBOSS_NODES_MathExpression`) |
| Show text on the node, or the picture while it is made | Show Text (`AUSBOSS_NODES_ShowText`), Step Preview (`AUSBOSS_NODES_StepPreview`) |
| Stop a run after the 3D viewer to frame the shot on the new model, with a 360 behind it | Pause for Shot (`AUSBOSS_NODES_PauseShot`): [node help](../AUSBOSS_NODES_PauseShot.md) |
| Free graphics memory between steps | Free Memory (`AUSBOSS_NODES_FreeMemory`) |
| Time the whole run | Run Timer (`AUSBOSS_NODES_RunTimer`) |
| Turn parts of a workflow off and on | Workflow Switches (`AUSBOSS_NODES_WorkflowSwitches`): [its own agent guide](workflow_switches.md) |
+14
View File
@@ -0,0 +1,14 @@
// On a Chinese ComfyUI (Settings > Language), the pack's own node faces show
// Chinese. js/shared/i18n.mjs holds the rules, js/shared/i18n_zh.mjs the words.
// The language is read when the page loads, so a change in Settings shows
// after a reload.
import { app } from "../../../scripts/app.js";
import { chineseActive, followFaces, useLocaleSource } from "../shared/i18n.mjs";
app.registerExtension({
name: "ausboss.i18n",
async setup() {
useLocaleSource(() => app.ui?.settings?.getSettingValue?.("Comfy.Locale"));
if (chineseActive()) followFaces(document.body);
},
});
+81 -7
View File
@@ -10,6 +10,9 @@ import {
openSettingsMenu,
} from "../shared/settings_menu.mjs";
import { compactAction } from "../shared/panel_controls.mjs";
import {
STRENGTH_LINK_STYLES, WIRE_LOOKS, installStrengthLinks, sourceTitle, sourceValue, syncStrengthLinks, unlinkRow,
} from "./strength_links.mjs";
import { makeScrubInput } from "../shared/scrub_input.mjs";
import { isAppShortcut, keepKeyInField } from "../shared/canvas_passthrough.mjs";
import { resetUnknownValues } from "../shared/widget_card_math.mjs";
@@ -143,6 +146,14 @@ const SETTINGS_SCHEMA = [
hint: "Two strength boxes per row on this node. New nodes always start "
+ "unified.",
},
{
key: "strength_wires", label: "Linked strength wires", type: "choice",
options: WIRE_LOOKS, default: "shown",
hint: "A number wire dropped on a row sets that row's strength. shown: "
+ "the wire runs to the row. on hover: it shows while the pointer is on "
+ "this node or its source. hidden: never drawn; the row still says "
+ "what sets it.",
},
{
key: "strength_bars", label: "Strength bars", type: "toggle",
default: true,
@@ -223,7 +234,7 @@ function installStyles() {
if (document.getElementById("ausboss-lora-styles")) return;
const style = document.createElement("style");
style.id = "ausboss-lora-styles";
style.textContent = `
style.textContent = STRENGTH_LINK_STYLES + `
.ausboss-lora-panel, .ausboss-lora-panel *,
.ausboss-lora-pop, .ausboss-lora-pop *,
.ausboss-lora-hoverthumb { box-sizing: border-box; }
@@ -917,7 +928,11 @@ function strengthBox(state, index, key) {
input.dataset.ausbossStrength = key;
// A short name; the tooltip above stays as the longer description.
input.setAttribute("aria-label", key === "strength" ? "Model strength" : "CLIP strength");
input.__ausbossRead = () => state.rows[index]?.[key].toFixed(2) ?? "1.00";
input.__ausbossRead = () => {
const entry = linkedEntry(state, index);
if (entry) return sourceValue(entry)?.toFixed(2) ?? "link";
return state.rows[index]?.[key].toFixed(2) ?? "1.00";
};
input.__ausbossTint = () => state.rows[index] && applyRangeTint(input, state.rows[index], key);
ensureRange(state, state.rows[index].name);
@@ -931,6 +946,16 @@ function strengthBox(state, index, key) {
let drag = null;
input.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || !input.readOnly) return;
// A linked strength is set by its wire: a click shows where it comes from.
const entry = linkedEntry(state, index);
if (entry) {
event.preventDefault();
if (entry.source) {
app.canvas?.selectNode?.(entry.source);
app.canvas?.centerOnNode?.(entry.source);
}
return;
}
drag = { x: event.clientX, y: event.clientY, start: state.rows[index][key], scrubbed: false };
input.setPointerCapture(event.pointerId);
event.preventDefault();
@@ -1002,6 +1027,34 @@ function strengthBox(state, index, key) {
return box;
}
function linkedEntry(state, index) {
const row = state.rows[index];
return row ? state.linkedStrengths?.get(row.id) ?? null : null;
}
// Mark the rows a wire sets: the strength box shows the incoming number,
// and its tooltip names where it comes from.
function decorateStrengthLinks(state) {
if (state.disposed || state.box) return;
state.linkedStrengths = syncStrengthLinks(state);
for (const box of state.panel.querySelectorAll(".ausboss-lora-strengthbox")) {
const rowId = box.closest(".ausboss-lora-row")?.dataset.rowId;
const entry = rowId ? state.linkedStrengths.get(rowId) : null;
box.classList.toggle("linked", Boolean(entry));
const input = box.querySelector(".ausboss-lora-strength");
if (!input) continue;
input.title = entry
? `Set by "${sourceTitle(entry)}". Click to show it. Right-click the row to unlink.`
: input.dataset.baseTitle ?? "";
if (input.readOnly && input.__ausbossRead) input.value = input.__ausbossRead();
}
const signature = [...state.linkedStrengths].map(([id, entry]) => `${id}:${sourceValue(entry)}`).join("|");
if (signature !== state.linkSignature) {
state.linkSignature = signature;
decorateRows(state);
}
}
// ---------- picker ----------
// Width of the longest label in the picker's font. Remembered across opens,
@@ -1362,6 +1415,7 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
const open = anyFolderOpen(entries, currentFolds());
foldAll.hidden = !entries.some((entry) => entry.kind === "folder");
foldAll.textContent = open ? "Fold all" : "Open all";
foldAll.dataset.folds = open ? "1" : "";
foldAll.title = open ? "Fold every folder in this list" : "Open every folder in this list";
if (highlight >= 0) highlight = clampHighlight(highlight, options.length);
list.textContent = "";
@@ -1391,7 +1445,7 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
};
foldAll.addEventListener("click", () => {
toggleFolder(null, foldAll.textContent === "Fold all", "search");
toggleFolder(null, foldAll.dataset.folds === "1", "search");
});
search.addEventListener("input", () => { highlight = -1; searchCollapsed = new Set(); renderList(); });
search.addEventListener("keydown", (event) => {
@@ -1857,6 +1911,13 @@ function openRowMenu(state, index, event) {
commitRows(state, rows, { structural: true });
fitNode(state);
};
if (state.linkedStrengths?.has(row.id)) {
item("Unlink strength", () => {
unlinkRow(state, row.id);
decorateStrengthLinks(state);
});
menu.append(el("div", "ausboss-lora-menu-rule"));
}
item("Insert empty LoRA above", () => insertEmpty(index));
item("Insert empty LoRA below", () => insertEmpty(index + 1));
item("Move up", () => commitGroups(state, moveRowInStack(state.rows, index, -1)),
@@ -2383,7 +2444,12 @@ function renameOwnedGroup(state, from, to) {
// value update - the bar scale can change whenever any row's strength does.
function decorateRows(state) {
const showBars = state.settings?.strength_bars !== false;
const scale = strengthBarScale(state.rows);
// A linked row's bar shows the number coming in on its wire.
const shown = state.rows.map((row, index) => {
const value = sourceValue(linkedEntry(state, index));
return value === null ? row : { ...row, strength: value };
});
const scale = strengthBarScale(shown);
const dups = duplicateLoraKeys(state.rows);
state.panel.querySelectorAll(".ausboss-lora-name").forEach((button, index) => {
const row = state.rows[index];
@@ -2394,8 +2460,8 @@ function decorateRows(state) {
}
const notes = [row.name];
if (showBars) {
button.style.background = strengthBarBackground(row.strength, scale);
notes.push(`Model strength ${row.strength.toFixed(2)}; `
button.style.background = strengthBarBackground(shown[index].strength, scale);
notes.push(`Model strength ${shown[index].strength.toFixed(2)}; `
+ `bar edges are ±${scale.toFixed(2)}`);
} else {
button.style.background = "";
@@ -2440,6 +2506,7 @@ function updateRowValues(state) {
master.classList.toggle("mixed", overall === "mixed");
}
decorateRows(state);
decorateStrengthLinks(state);
}
// ---------- absorb the loader chain ----------
@@ -2921,7 +2988,7 @@ function renderRows(state) {
let nameDrag = null;
name.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || !row.name
|| state.settings?.name_scrub === false) return;
|| state.settings?.name_scrub === false || linkedEntry(state, index)) return;
nameDrag = { x: event.clientX, y: event.clientY,
start: state.rows[index].strength, scrubbed: false };
name.setPointerCapture(event.pointerId);
@@ -3013,6 +3080,7 @@ function renderRows(state) {
stack.append(actions);
body.append(stack);
decorateRows(state);
decorateStrengthLinks(state);
state.lockSignature = null;
refreshLocks(state);
// Names refit whenever the stack's box changes - the node was resized,
@@ -3144,6 +3212,7 @@ function ensureRedrawHook() {
if (state.node.graph !== shown) continue;
syncRows(state);
refreshLocks(state);
decorateStrengthLinks(state);
}
}, 250);
});
@@ -3249,6 +3318,7 @@ function watchBox(box) {
function unmountCard(state, { resize = true } = {}) {
liveCards.delete(state);
state.disposed = true;
state.unlinkStrengthWatch?.();
state.nameObserver?.disconnect();
closePopup();
try {
@@ -3342,6 +3412,10 @@ function mountCard(node, { box = null, separatorWidget = null, onMissingWidget =
panel.style.height = `calc(100% + ${reclaim}px)`;
}
if (!box) {
state.unlinkStrengthWatch = installStrengthLinks(state, app);
state.onStrengthLinks = () => decorateStrengthLinks(state);
}
renderRows(state);
refreshAvailable(state);
node.setSize?.([Math.max(336, node.size?.[0] || 336), node.computeSize?.()[1] || 220]);
+303
View File
@@ -0,0 +1,303 @@
// A row's strength can come in on a link: drag a number wire onto a row and
// let go. The link lands on a hidden input named strength_<row id> that sits
// on the node's left edge at that row's height. Nothing marks the spot until
// a number wire is dragged over the node: then the row under the pointer
// lights up. Once linked, the row's strength box shows the incoming value,
// and the wire is shown, shown on hover, or hidden (gear menu).
//
// How the input stays out of sight: the frontend treats an input that names
// a widget as a widget's socket. It leaves such a socket out of the node's
// height, draws it only while a link is dragged or hovered or once it is
// connected, and keeps the position it is given when no widget by that name
// exists. The socket is also drawn in a clear colour, so a linked row shows
// no dot. The frontend does not hit-test such a socket either, so the
// loader's getInputOnPos finds the row under a drop itself.
//
// The frontend also removes, when a workflow loads, every widget socket
// whose widget it cannot find. So the input is saved as a plain input and
// becomes a widget socket again once the workflow has loaded.
import { chainCallback } from "../shared/index.mjs";
const NAME = /^strength_[A-Za-z0-9_-]{1,64}$/;
const CLEAR = "rgba(0,0,0,0)";
// Where the hidden socket sits from the node's left edge, as the frontend
// places a widget's socket.
const SOCKET_X = 10;
const NUMBER_TYPES = new Set(["FLOAT", "INT"]);
export const WIRE_LOOKS = ["shown", "on hover", "hidden"];
// The canvas skips drawing a wire it is told is being dragged, shadow and
// all, so a hidden wire carries that mark. The mark is not saved.
export const rowInputName = (rowId) => `strength_${rowId}`;
export const isRowInput = (input) => typeof input?.name === "string" && NAME.test(input.name);
const rowIdOf = (input) => input.name.slice("strength_".length);
const states = new Set();
let watching = false;
let hoverTarget = null;
function canvasOf(app) {
return app?.canvas ?? null;
}
function clientPoint(app, x, y) {
const canvas = canvasOf(app);
const rect = canvas.canvas.getBoundingClientRect();
const scale = canvas.ds.scale || 1;
const [ox, oy] = canvas.ds.offset;
return [rect.left + (x + ox) * scale, rect.top + (y + oy) * scale];
}
function graphPoint(app, clientX, clientY) {
const canvas = canvasOf(app);
const rect = canvas.canvas.getBoundingClientRect();
const scale = canvas.ds.scale || 1;
const [ox, oy] = canvas.ds.offset;
return [(clientX - rect.left) / scale - ox, (clientY - rect.top) / scale - oy];
}
function linkOf(graph, id) {
if (id === null || id === undefined || !graph) return null;
return graph.links?.get?.(id) ?? graph.links?.[id] ?? graph._links?.get?.(id) ?? null;
}
function rowElements(state) {
return [...state.panel.querySelectorAll(".ausboss-lora-row")]
.filter((element) => !element.classList.contains("folded-away"));
}
function rowElement(state, rowId) {
return rowElements(state).find((element) => element.dataset.rowId === rowId) ?? null;
}
// The row under a point in client pixels: anywhere across the node's width,
// so a drop does not have to hit the strength box itself.
function rowAtClient(state, clientX, clientY) {
const node = state.node;
const app = state.app;
const [left] = clientPoint(app, node.pos[0], node.pos[1]);
const [right] = clientPoint(app, node.pos[0] + node.size[0], node.pos[1]);
if (clientX < left - 4 || clientX > right + 4) return null;
for (const element of rowElements(state)) {
const rect = element.getBoundingClientRect();
if (clientY >= rect.top - 3 && clientY <= rect.bottom + 3) return element;
}
return null;
}
function isNumberDrag(app) {
const connector = canvasOf(app)?.linkConnector;
if (!connector?.isConnecting) return false;
if (connector.state?.connectingTo && connector.state.connectingTo !== "input") return false;
const types = (connector.renderLinks ?? []).map((link) => String(link?.fromSlot?.type ?? ""));
return types.length > 0 && types.every((type) => type.split(",").some((part) => NUMBER_TYPES.has(part.trim())));
}
export function rowInputs(node) {
return (node.inputs ?? []).filter(isRowInput);
}
// {row id: {input, link, source}} for every row a link sets now.
export function linkedRows(node) {
const found = new Map();
for (const input of rowInputs(node)) {
const link = linkOf(node.graph, input.link);
if (!link) continue;
const source = node.graph?.getNodeById?.(link.origin_id) ?? null;
found.set(rowIdOf(input), { input, link, source });
}
return found;
}
// What a linked row shows: the source's own number when it has one in
// sight (a Float or Int node, a slider), else just that it is linked.
export function sourceValue(entry) {
const widgets = entry?.source?.widgets ?? [];
const widget = widgets.find((item) => item.name === "value") ?? widgets.find((item) => typeof item.value === "number");
return typeof widget?.value === "number" ? widget.value : null;
}
export function sourceTitle(entry) {
return String(entry?.source?.title || entry?.source?.type || "another node");
}
function placeInput(state, input) {
const element = rowElement(state, rowIdOf(input));
if (!element) return;
const rect = element.getBoundingClientRect();
const [, y] = graphPoint(state.app, 0, rect.top + rect.height / 2);
const pos = [SOCKET_X, Math.round((y - state.node.pos[1]) * 10) / 10];
if (input.pos?.[0] !== pos[0] || input.pos?.[1] !== pos[1]) input.pos = pos;
}
const HIDDEN = () => ({ label: " ", localized_name: " ", color_on: CLEAR, color_off: CLEAR });
function hideInput(input) {
Object.assign(input, HIDDEN());
if (!input.widget) input.widget = { name: input.name };
}
function ensureRowInput(state, rowId) {
const node = state.node;
const name = rowInputName(rowId);
let input = node.inputs?.find((item) => item.name === name);
if (!input) input = node.addInput(name, "FLOAT,INT", { ...HIDDEN(), widget: { name } });
placeInput(state, input);
return input;
}
export function unlinkRow(state, rowId) {
const node = state.node;
const index = (node.inputs ?? []).findIndex((input) => input.name === rowInputName(rowId));
if (index < 0) return;
node.removeInput(index);
node.setDirtyCanvas?.(true, true);
}
function wireHidden(state, entry) {
const look = state.settings?.strength_wires ?? "shown";
if (look === "hidden") return true;
return look === "on hover" && hoverTarget !== state.node && hoverTarget !== entry.source;
}
function setWireHidden(entry, hidden) {
const link = entry.link;
if (hidden === Boolean(link._dragging)) return false;
// A wire the user is moving keeps the mark the canvas gave it.
if (!hidden && link.__ausbossHidden !== true) return false;
link._dragging = hidden;
link.__ausbossHidden = hidden;
return true;
}
// Keep the hidden inputs in step with the rows: drop the ones nothing is
// linked to or whose row is gone, move each to its row, colour its wire.
// Returns the linked rows.
export function syncStrengthLinks(state) {
const node = state.node;
const connecting = canvasOf(state.app)?.linkConnector?.isConnecting;
// Rows not yet read from a workflow that is loading say nothing about
// which inputs are stale.
const rowsCurrent = state.widget && state.renderedValue === state.widget.value;
if (!connecting && rowsCurrent) {
const ids = new Set(state.rows.map((row) => row.id));
for (let index = (node.inputs?.length ?? 0) - 1; index >= 0; index -= 1) {
const input = node.inputs[index];
if (!isRowInput(input)) continue;
if (!ids.has(rowIdOf(input)) || !linkOf(node.graph, input.link)) node.removeInput(index);
}
}
for (const input of rowInputs(node)) placeInput(state, input);
const linked = linkedRows(node);
let changed = false;
for (const entry of linked.values()) {
if (setWireHidden(entry, wireHidden(state, entry))) changed = true;
}
if (changed) node.setDirtyCanvas?.(true, true);
return linked;
}
function paintTarget(element) {
for (const state of states) {
for (const row of state.panel.querySelectorAll(".ausboss-lora-row.link-target")) {
if (row !== element) row.classList.remove("link-target");
}
}
element?.classList.add("link-target");
}
function watchPointer(app) {
if (watching) return;
watching = true;
window.addEventListener("pointermove", (event) => {
let target = null;
let over = null;
for (const state of states) {
if (state.disposed) continue;
const node = state.node;
const [x, y] = graphPoint(app, event.clientX, event.clientY);
if (x >= node.pos[0] && x <= node.pos[0] + node.size[0] && y >= node.pos[1] - 30 && y <= node.pos[1] + node.size[1]) over = node;
if (!target && !state.box && !state.readOnly && isNumberDrag(app)) target = rowAtClient(state, event.clientX, event.clientY);
}
paintTarget(target);
if (!over) {
const [x, y] = graphPoint(app, event.clientX, event.clientY);
over = canvasOf(app)?.graph?.getNodeOnPos?.(x, y) ?? null;
}
if (over !== hoverTarget) {
hoverTarget = over;
for (const state of states) if (!state.disposed) syncStrengthLinks(state);
}
}, true);
// Nodes 2.0 finishes a link drag in its own pointerup handler and never asks
// the node which input is under the pointer. So there the drop on a row is
// made here, before that handler runs; it then finds the link made.
window.addEventListener("pointerup", (event) => {
if (globalThis.LiteGraph?.vueNodesMode && isNumberDrag(app)) {
for (const state of states) {
if (state.disposed || state.box || state.readOnly) continue;
const element = rowAtClient(state, event.clientX, event.clientY);
if (element?.dataset.rowId) {
dropOnRow(state, element.dataset.rowId, canvasOf(app).linkConnector);
break;
}
}
}
requestAnimationFrame(() => {
paintTarget(null);
for (const state of states) if (!state.disposed) state.onStrengthLinks?.();
});
}, true);
}
function dropOnRow(state, rowId, connector) {
const input = ensureRowInput(state, rowId);
for (const link of connector.renderLinks ?? []) {
if (link.node === state.node) continue;
link.connectToInput?.(state.node, input, connector.events);
}
}
export function installStrengthLinks(state, app) {
state.app = app;
states.add(state);
watchPointer(app);
const node = state.node;
// Saved as plain inputs (see the top of this file), hidden again on load.
chainCallback(node, "onSerialize", (data) => {
if (!Array.isArray(data?.inputs)) return;
data.inputs = data.inputs.map((input) => {
if (!isRowInput(input)) return input;
const { widget, ...plain } = input;
return plain;
});
});
const rehide = () => {
for (const input of rowInputs(node)) hideInput(input);
requestAnimationFrame(() => { if (!state.disposed) state.onStrengthLinks?.(); });
};
chainCallback(node, "onGraphConfigured", rehide);
chainCallback(node, "onConfigure", () => requestAnimationFrame(rehide));
const original = node.getInputOnPos;
node.getInputOnPos = function (pos) {
const found = typeof original === "function" ? original.call(this, pos) : undefined;
if (found && !isRowInput(found)) return found;
if (state.disposed || state.box || state.readOnly || !isNumberDrag(app)) return found;
const [clientX, clientY] = clientPoint(app, pos[0], pos[1]);
const element = rowAtClient(state, clientX, clientY);
if (!element?.dataset.rowId) return found;
return ensureRowInput(state, element.dataset.rowId);
};
return () => {
states.delete(state);
if (node.getInputOnPos !== original) delete node.getInputOnPos;
};
}
export const STRENGTH_LINK_STYLES = `
.ausboss-lora-row.link-target{outline:2px solid #00b4aa;outline-offset:-1px;background:rgba(0,180,170,.14);}
.ausboss-lora-strengthbox.linked{border-color:transparent;outline:2px dashed rgba(0,180,170,.7);outline-offset:-2px;}
.ausboss-lora-strengthbox.linked .ausboss-lora-strength{color:#5fe3d9;cursor:pointer;}
.ausboss-lora-strengthbox.linked .ausboss-lora-step{display:none;}
`;
+286
View File
@@ -0,0 +1,286 @@
// Pause for Shot 🆎: while a run waits on the node, a Continue bar shows on
// the node and over the 3D viewer it is wired to. Continue reads the viewer's
// camera, model turn and size as they are now and sends them to
// POST /ausboss/pause_shot/answer (nodes/node_pause_shot.py), which only
// accepts them while that node is waiting. The switch above the bar is the
// node's `pause` setting (js/widget_cards). When a 360 is wired into the
// node, the run hands it over as a temp picture and it goes behind the model
// as the viewer's panorama; Continue also sends the 360 strip's settings
// (js/viewer_pano), so the run's backdrop matches the viewer.
import { app } from "../../../scripts/app.js";
import { api } from "../../../scripts/api.js";
import { chainCallback, keepDomWidgetWidthAuto, showToast } from "../shared/index.mjs";
import { nodeByExecutionId } from "../shared/graph_ids.mjs";
import { compactAction, HINT_TYPE } from "../shared/panel_controls.mjs";
import { holdNodeMinWidth, pinVuePanelHeight } from "../shared/panel_layout.mjs";
import { FONT_UI, RADIUS_CONTROL, THEME as T } from "../shared/theme.mjs";
import { bottomButtons } from "../shared/viewer3d_layout.mjs";
const NODE_CLASS = "AUSBOSS_NODES_PauseShot";
const PANEL = "ausboss_pause_shot_panel";
const MIN_WIDTH = 260;
const PANEL_HEIGHT = 62;
function ensureCss() {
if (document.getElementById("ausboss-pause-shot-css")) return;
const style = document.createElement("style");
style.id = "ausboss-pause-shot-css";
style.textContent = `
.ausboss-pshot{box-sizing:border-box;overflow:hidden;display:flex;flex-direction:column;gap:6px;width:100%;height:100%;padding:6px 8px 8px;background:${T.card};border-radius:${RADIUS_CONTROL}px;font:400 12px/1.3 ${FONT_UI};color:${T.inkSoft}}
.ausboss-pshot-hint{${HINT_TYPE}}
.ausboss-pshot.waiting .ausboss-pshot-hint{color:${T.brandInk}}
.ausboss-pshot-row{display:flex;gap:6px;justify-content:flex-end}
.ausboss-pshot-row .ausboss-compact-action{height:26px;padding:0 12px}
.ausboss-pshot .go,.ausboss-pshot-over .go{background:${T.brand};color:${T.onBrand}}
.ausboss-pshot .go:hover:enabled,.ausboss-pshot-over .go:hover:enabled{background:${T.brand};color:${T.onBrand};filter:brightness(1.1)}
.ausboss-pshot:not(.waiting) .ausboss-pshot-row{visibility:hidden}
.ausboss-pshot-over{position:absolute;left:8px;bottom:8px;z-index:6;box-sizing:border-box;display:flex;align-items:center;gap:6px;height:32px;padding:0 4px 0 10px;border-radius:${RADIUS_CONTROL}px;background:${T.card};box-shadow:0 1px 6px rgba(0,0,0,.4);font:600 11px/1 ${FONT_UI};color:${T.brandInk};white-space:nowrap}
.ausboss-pshot-over .ausboss-compact-action{height:24px;padding:0 10px}
`;
document.head.append(style);
}
// The viewer wired to the pause: where its camera comes from.
function viewerOf(node) {
const slot = node.inputs?.findIndex((input) => input.name === "camera_info") ?? -1;
return slot >= 0 ? node.getInputNode?.(slot) ?? null : null;
}
// The viewer's shot as it is on screen right now.
async function readShot(viewer) {
const shot = {};
const state = viewer?.widgets?.find((widget) => widget.name === "viewport_state");
if (state?.serializeValue) {
const value = await state.serializeValue(viewer, viewer.widgets.indexOf(state));
if (value?.camera_info) shot.camera_info = value.camera_info;
if (Array.isArray(value?.model_3d_info)) shot.model_3d_info = value.model_3d_info;
}
const sky = viewer?.properties?.["AusBoss View"]?.sky;
if (sky && typeof sky === "object") shot.sky = sky;
// The 360 taken out of the viewer (its background image removed) leaves
// the backdrop grey, as with no 360 wired in.
const scene = viewerGizmo(viewer)?.__ausbossScene;
if (scene && !(scene.currentBackgroundType === "image" && scene.backgroundRenderMode === "panorama")) shot.panorama = false;
try {
const ground = viewerGizmo(viewer)?.__ausbossScene?.__ausbossGround?.();
if (ground) shot.ground = ground;
} catch {
// No shadow then.
}
for (const key of ["width", "height"]) {
const linked = viewer?.inputs?.find((input) => input.name === key)?.link != null;
const widget = viewer?.widgets?.find((w) => w.name === key);
if (!linked && Number.isFinite(Number(widget?.value))) shot[key] = Number(widget.value);
}
return shot;
}
// The viewer's gizmo box, found through the 360 strip (js/viewer_pano).
function viewerGizmo(viewer) {
if (!viewer) return null;
for (const box of document.querySelectorAll("div[data-ausboss-gizmo]")) {
if (box.__ausbossNode === viewer && box.parentElement) return box;
}
return null;
}
const viewerBox = (viewer) => viewerGizmo(viewer)?.parentElement ?? null;
// ComfyUI sends the viewer's model only to the page that pressed Run. The
// pause brings it along, so a page that did not start the run (another tab,
// a phone, a reload) shows the model too.
// ComfyUI names the model as {"result": ["model.glb [temp]", ...]}, or since
// its standard 3d output item as {"3d": [{filename, subfolder, type}]}.
const plainName = (text) => String(text ?? "").replace(/\s*\[[^\]]*\]$/, "").replaceAll("\\", "/");
function modelName(output) {
const first = output?.result?.[0];
if (typeof first === "string") return plainName(first);
const item = output?.["3d"]?.[0];
if (typeof item?.filename !== "string") return "";
return plainName(item.subfolder ? `${item.subfolder}/${item.filename}` : item.filename);
}
function showModel(viewer, shown) {
const name = modelName(shown?.output);
if (!viewer || !name || typeof viewer.onExecuted !== "function") return;
const last = plainName(viewer.properties?.["Last Time Model File"]);
if (last === name || last.endsWith(`/${name}`)) return;
viewer.onExecuted(shown.output);
}
// Put the run's 360 behind the model, as the viewer's panorama.
async function showPanorama(viewer, picture) {
const scene = viewerGizmo(viewer)?.__ausbossScene;
if (!scene?.setBackgroundImage || !picture?.filename) return false;
await scene.setBackgroundImage(`temp/${picture.filename}`);
scene.setBackgroundRenderMode?.("panorama");
scene.__ausbossViewport?.forceRender?.();
return true;
}
function buildPanel(node) {
ensureCss();
const root = document.createElement("div");
root.className = "ausboss-pshot";
const hint = document.createElement("div");
hint.className = "ausboss-pshot-hint";
const row = document.createElement("div");
row.className = "ausboss-pshot-row";
const stop = compactAction("Stop", "End the run here.");
const go = compactAction("Continue", "Go on with the shot as the viewer shows it now.");
go.classList.add("go");
row.append(stop, go);
root.append(hint, row);
const state = { waitingFor: null, over: null };
const idle = "A run waits here while you frame the shot.";
hint.textContent = idle;
const removeOver = () => { state.over?.remove(); state.over = null; };
const clear = () => {
state.waitingFor = null;
root.classList.remove("waiting");
hint.textContent = idle;
removeOver();
};
const answer = async (action) => {
const id = state.waitingFor;
if (!id) return;
const buttons = [go, stop, ...(state.over ? state.over.querySelectorAll("button") : [])];
buttons.forEach((button) => { button.disabled = true; });
try {
const body = { node: id, action };
if (action === "continue") body.shot = await readShot(viewerOf(node));
const response = await api.fetchApi("/ausboss/pause_shot/answer", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
if (!response.ok) {
const data = await response.json().catch(() => ({}));
showToast({ detail: data.error || "The pause could not be answered.", severity: "warn" });
if (response.status === 409) clear();
}
} catch {
showToast({ detail: "The pause could not be answered. Is ComfyUI still running?", severity: "warn" });
} finally {
buttons.forEach((button) => { button.disabled = false; });
}
};
go.addEventListener("click", () => answer("continue"));
stop.addEventListener("click", () => answer("stop"));
// The same Continue on the viewer, at its bottom-left corner on the line
// of the viewer's own bottom buttons, clear of the shot.
const placeOver = (host, over) => {
const line = bottomButtons(host);
if (!line) return;
over.style.bottom = `${line.bottom}px`;
over.style.height = `${line.height}px`;
};
const showOver = () => {
removeOver();
const host = viewerBox(viewerOf(node));
if (!host) return;
const over = document.createElement("div");
over.className = "ausboss-pshot-over";
const label = document.createElement("span");
label.textContent = "Frame your shot";
const overStop = compactAction("Stop", "End the run here.");
const overGo = compactAction("Continue", "Go on with the shot as the viewer shows it now.");
overGo.classList.add("go");
overStop.addEventListener("click", () => answer("stop"));
overGo.addEventListener("click", () => answer("continue"));
for (const type of ["pointerdown", "mousedown", "dblclick", "contextmenu"]) over.addEventListener(type, (event) => event.stopPropagation());
over.append(label, overStop, overGo);
host.append(over);
placeOver(host, over);
state.over = over;
};
const show = (detail) => {
state.waitingFor = String(detail.node);
root.classList.add("waiting");
hint.textContent = "Frame the shot in the viewer, then Continue.";
showOver();
const viewer = viewerOf(node);
try {
showModel(viewer, detail.viewer);
} catch {
// The viewer keeps what it has.
}
const panorama = detail.panorama;
const showIt = () => showPanorama(viewer, panorama).catch(() => false);
// After a reload, or before the viewer has drawn once, its panel is not
// there yet: keep looking for it while the pause waits.
if (!state.over || !viewerGizmo(viewer)) {
const id = state.waitingFor;
let tries = 0;
const retry = () => {
if (state.waitingFor !== id) return;
if (!state.over) showOver();
if (state.over && viewerGizmo(viewer)) { showIt(); return; }
// Quick at first, then slower for as long as the pause waits.
setTimeout(retry, (tries += 1) < 40 ? 750 : 2000);
};
setTimeout(retry, 750);
} else showIt();
node.setDirtyCanvas?.(true, true);
};
root.addEventListener("pointerdown", (event) => {
if (event.target.closest("button")) event.stopPropagation();
});
return { root, show, clear, isWaitingFor: (id) => state.waitingFor === String(id) };
}
function panelOf(detail) {
const node = nodeByExecutionId(app.rootGraph ?? app.graph, detail?.node);
return node?.__ausbossPauseShot ?? null;
}
// A page opened or reloaded while a run waits missed the event: ask.
async function showWaiting() {
try {
const response = await api.fetchApi("/ausboss/pause_shot/waiting");
if (!response.ok) return;
const { waiting } = await response.json();
for (const detail of Array.isArray(waiting) ? waiting : []) {
const panel = panelOf(detail);
if (panel && !panel.isWaitingFor(detail.node)) panel.show(detail);
}
} catch {
// Nothing to bring back.
}
}
app.registerExtension({
name: "ausboss.pause_shot",
afterConfigureGraph() { showWaiting(); },
setup() {
api.addEventListener("reconnected", () => showWaiting());
api.addEventListener("ausboss-pause-shot", (event) => panelOf(event.detail)?.show(event.detail));
api.addEventListener("ausboss-pause-shot-done", (event) => {
const panel = panelOf(event.detail);
if (panel?.isWaitingFor(event.detail?.node)) panel.clear();
});
},
beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData?.name !== NODE_CLASS) return;
chainCallback(nodeType.prototype, "onNodeCreated", function () {
const panel = buildPanel(this);
const widget = this.addDOMWidget(PANEL, PANEL, panel.root, { serialize: false, hideOnZoom: false });
keepDomWidgetWidthAuto(widget);
// Not saved with the workflow: saved values come back by position.
widget.serialize = false;
// A hint and two buttons: a constant height (tests/panel_guards.test.mjs,
// fixedByDesign).
widget.computeSize = (width) => [Math.max(MIN_WIDTH, Number(width || this.size?.[0] || MIN_WIDTH)), PANEL_HEIGHT];
pinVuePanelHeight(widget);
holdNodeMinWidth(widget, MIN_WIDTH);
widget.options.minNodeSize = [MIN_WIDTH, 60];
this.__ausbossPauseShot = panel;
});
chainCallback(nodeType.prototype, "onRemoved", function () {
this.__ausbossPauseShot?.clear();
});
},
});
+3 -3
View File
@@ -97,9 +97,9 @@ const SETTINGS_SCHEMA = [
},
{
key: "chips_keep_budget", label: "Chips keep current budget", type: "toggle",
default: false,
hint: "Ratio chips reshape at your current megapixels instead of jumping "
+ "to that ratio's ~1MP default size.",
default: true,
hint: "On: ratio chips keep your current megapixels. Off: a chip jumps "
+ "to that ratio's ~1MP size.",
},
{
key: "rail", label: "Ratio rail", type: "text",
+3 -3
View File
@@ -40,8 +40,8 @@ function getLoopEnabled(node) {
}
// The Preview steps switch: the hidden `step_preview` widget (the card hides it).
// On, the player shows each step of the clip's first frame while it is
// being made, and a STOP button joins the tools for the run.
// On, the player shows each step of the clip while it is being made (a few
// of its frames in a loop), and a STOP button joins the tools for the run.
function stepsOn(state) {
return state.stepsWidget?.value === true;
}
@@ -131,7 +131,7 @@ function buildPreview(node) {
loopButton.classList.add("ausboss-steps-loop");
const stopButton = makeToolButton("STOP", "Stop this run now. The next run in the queue still starts.");
stopButton.classList.add("ausboss-steps-stop");
const stepsButton = panelSwitch("Preview steps", "Show the clip's first frame here while it is being made, one step at a time, with a Stop button. Off by default.");
const stepsButton = panelSwitch("Preview steps", "Show the clip here while it is being made: after each step, a few of its frames play in a loop, with a Stop button. Off by default.");
tools.classList.add("ausboss-steps-tools");
tools.append(stopButton, loopButton);
stage.append(video, image, status, tools);
+11
View File
@@ -32,6 +32,17 @@ export function appFields(linearData) {
return fields;
}
// Where the form puts a DOM widget (a panel, the clip window): the empty
// host the form draws in that field's row. The form moves the widget's
// element into it once, as the row mounts, and the graph's own widget layer
// can take it back a moment later, which left the row empty. So the pack
// moves it in again (js/app_mode/). A selector, so it is testable here.
export function formHostSelector(nodeId, name) {
const id = String(nodeId).replace(/["\\]/g, "");
const field = String(name).replace(/["\\]/g, "");
return `[data-testid="app-mode-widget-item"][data-widget-key$=":${id}:${field}"] [data-widget-name="${field}"] div[node-type]`;
}
// find(nodeId, widgetName) -> { node, widget } or null
// changed(node) is called after a widget on that node changed visibility.
export function createAppModeSync({ find, changed = () => {} }) {
+190
View File
@@ -0,0 +1,190 @@
// The maths behind the 3D viewer's Blender keys (js/viewer_keys): G moves,
// R rotates and S scales the model while the mouse moves, the way Blender
// does it. Plain arrays [x, y, z]; nothing here touches the page, so it is
// tested on its own (tests/blender_transform.test.mjs).
export const AXES = Object.freeze({ x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] });
export const AXIS_NAMES = Object.freeze(["x", "y", "z"]);
export const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
export const add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
export const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
export const times = (a, k) => [a[0] * k, a[1] * k, a[2] * k];
export const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
export const length = (a) => Math.hypot(a[0], a[1], a[2]);
export const unit = (a) => { const n = length(a); return n > 1e-12 ? times(a, 1 / n) : [0, 0, 0]; };
/**
* Blender's axis lock. X locks to the world's X axis, X again to the
* model's own X, a third time unlocks. Shift+X locks to the plane that
* leaves X out (move or scale along the other two), with the same cycle.
*/
export function nextConstraint(current, axis, plane = false) {
const kind = plane ? "plane" : "axis";
if (!current || current.axis !== axis || current.kind !== kind) return { kind, axis, space: "global" };
if (current.space === "global") return { kind, axis, space: "local" };
return null;
}
/** Where a ray meets a plane, as a distance along the ray; null when it runs parallel. */
export function rayPlane(origin, dir, point, normal) {
const denom = dot(dir, normal);
if (Math.abs(denom) < 1e-9) return null;
return dot(sub(point, origin), normal) / denom;
}
export const along = (origin, dir, t) => add(origin, times(dir, t));
/**
* The spot on an axis line (through `point`, along unit `axis`) nearest a
* ray, as a distance along the axis. null when the axis points along the
* ray, where every spot is as near as any other.
*/
export function closestOnAxis(origin, dir, point, axis) {
const w = sub(point, origin);
const a = dot(axis, axis);
const b = dot(axis, dir);
const c = dot(dir, dir);
const denom = a * c - b * b;
if (Math.abs(denom) < 1e-9 * a * c) return null;
return (b * dot(dir, w) - c * dot(axis, w)) / denom;
}
/** The turn from screen point `a` to `b` around `center`, counter-clockwise positive, in (-pi, pi]. Screen y points down. */
export function screenTurn(center, a, b) {
const ax = a[0] - center[0], ay = center[1] - a[1];
const bx = b[0] - center[0], by = center[1] - b[1];
if (Math.hypot(ax, ay) < 1e-6 || Math.hypot(bx, by) < 1e-6) return 0;
return Math.atan2(ax * by - ay * bx, ax * bx + ay * by);
}
/** Round to the nearest step; a step of 0 leaves the value alone. */
export const snapTo = (value, step) => (step > 0 ? Math.round(value / step) * step : value);
/**
* A typed number as Blender takes it while a move runs: digits, one point,
* and a minus anywhere that flips the sign. null while nothing usable is typed.
*/
export function parseTyped(text) {
if (typeof text !== "string") return null;
const negative = (text.match(/-/g)?.length ?? 0) % 2 === 1;
const digits = text.replace(/-/g, "");
if (!/^\d*\.?\d*$/.test(digits) || !/\d/.test(digits)) return null;
const value = Number(digits);
return Number.isFinite(value) ? (negative ? -value : value) : null;
}
/** Edit the typed text with one key: a digit, ".", "-" (flip), or Backspace. */
export function typeKey(text, key) {
if (key === "Backspace") return text.slice(0, -1);
if (key === "-") return text.startsWith("-") ? text.slice(1) : `-${text}`;
if (key === ".") return text.includes(".") ? text : `${text}.`;
if (/^\d$/.test(key)) return text + key;
return text;
}
/** How fine Ctrl snapping is: Shift makes it ten times finer, as in Blender. */
export function snapStep(mode, precise) {
if (mode === "rotate") return precise ? 1 : 5; // degrees
return precise ? 0.01 : 0.1; // world units, or scale factor
}
/**
* The model's own axis that lies closest to a world axis, for scaling along
* a world axis: scale belongs to the model's own axes, so a turned model
* is scaled along the one that points most that way.
* `localAxes` are the model's three axes in world space.
*/
export function nearestLocalAxis(localAxes, worldAxis) {
let best = 0;
let score = -1;
localAxes.forEach((axis, i) => {
const s = Math.abs(dot(unit(axis), worldAxis));
if (s > score) { score = s; best = i; }
});
return best;
}
/** The scale factors on the model's own axes for a scale of `factor` under a lock. */
export function scaleFactors(factor, constraint, lockedIndex) {
if (!constraint) return [factor, factor, factor];
return [0, 1, 2].map((i) => {
const on = constraint.kind === "axis" ? i === lockedIndex : i !== lockedIndex;
return on ? factor : 1;
});
}
/** How far (screen px) the mouse must travel before the middle button picks an axis. */
export const PICK_PX = 8;
/**
* The mouse move that picks the axis for Blender's middle-button lock: the
* move since the middle button went down once it is long enough (hold and
* slide along an axis), else the move since G, R or S began (move, then
* click the middle button). null while neither is long enough; then a click
* waits for the mouse to move and picks from that.
*/
export function pickVector(start, press, now, min = PICK_PX) {
if (press) {
const held = [now[0] - press[0], now[1] - press[1]];
if (Math.hypot(held[0], held[1]) >= min) return held;
}
const whole = [now[0] - start[0], now[1] - start[1]];
return Math.hypot(whole[0], whole[1]) >= min ? whole : null;
}
/**
* Of the axes as drawn on screen (2D directions, any length), the one a
* mouse move runs most nearly along: Blender picks the axis line nearest
* the mouse's move. Axes shorter than `minLength` on screen (pointing at
* the camera) are left out; -1 when none is left or the move is empty.
*/
export function nearestScreenAxis(move, screenAxes, minLength = 1e-3) {
if (!move || Math.hypot(move[0], move[1]) < 1e-9) return -1;
let best = -1;
let score = Infinity;
screenAxes.forEach((d, i) => {
const n = Math.hypot(d[0], d[1]);
if (!(n >= minLength)) return;
// The move's distance from the axis line through the start.
const off = Math.abs(move[0] * d[1] - move[1] * d[0]) / n;
if (off < score - 1e-9) { score = off; best = i; }
});
return best;
}
/** The lock the middle button gives for the picked axis (Shift: the plane without it). */
export const autoConstraint = (axis, plane = false) => ({ kind: plane ? "plane" : "axis", axis, space: "global" });
/** Words for the lock, for the header line. */
export function constraintLabel(constraint) {
if (!constraint) return "";
const name = constraint.axis.toUpperCase();
const where = constraint.space === "local" ? "local" : "global";
if (constraint.kind === "plane") {
const others = AXIS_NAMES.filter((a) => a !== constraint.axis).map((a) => a.toUpperCase()).join("");
return `on ${where} ${others}`;
}
return `along ${where} ${name}`;
}
const num = (v, digits = 3) => (Math.abs(v) < 5e-7 ? 0 : v).toFixed(digits);
/**
* The amount in Blender's header words, without the lock: "D: 0.500 (0.500)"
* along a locked axis (`along` is the signed distance on it), "Dx: .. Dy: ..
* Dz: .. (length)" otherwise, "Rot: 45.0°", "Scale: 1.200" or "Scale X: ..
* Y: .. Z: ..". `value` is the move [x, y, z], the degrees, the factor, or
* [dx, dy] degrees for the trackball.
*/
export function readout(mode, value, constraint = null, along = null) {
if (mode === "grab") {
const size = num(length(value));
if (constraint?.kind === "axis" && along != null) return `D: ${num(along)} (${size})`;
return `Dx: ${num(value[0])} Dy: ${num(value[1])} Dz: ${num(value[2])} (${size})`;
}
if (mode === "trackball") return `Trackball: ${num(value[0], 1)}° ${num(value[1], 1)}°`;
if (mode === "rotate") return `Rot: ${num(value, 1)}°`;
if (constraint) return `Scale: ${num(value)}`;
return `Scale X: ${num(value)} Y: ${num(value)} Z: ${num(value)}`;
}
+433
View File
@@ -0,0 +1,433 @@
// The clip window: the part of the video a run uses, as one box on a strip
// of pictures from the video, under a player that plays only that part on a
// loop. Drag the box to pick where the clip starts; drag an edge to make it
// shorter or longer, never past min_seconds / max_seconds. While a drag is
// live the player shows the frame under the edge being moved. Made for an App-mode form, where it is the only control a
// person sees for the clip node: the node keeps it hidden on the graph and
// js/app_mode/ lends it to the form when the form lists it.
//
// It reads and writes the node's own values (start_seconds, max_frames,
// end_seconds), the way the node's timeline does, so both always agree. The
// arithmetic lives in timeline_math.mjs (clipWindowOf, dragClipWindow).
import { THEME, FONT_UI, RADIUS_CONTROL } from "./theme.mjs";
import { formatTimecode } from "./timecode.mjs";
import {
clipInfo,
clipWindowOf,
clipWindowValues,
dragClipWindow,
lengthLimits,
limitFrameRange,
loopPlayhead,
} from "./timeline_math.mjs";
const CSS_ID = "ausboss-clip-window-css-v2";
const EDGE_HIT_PX = 14;
const STRIP_HEIGHT = 58;
const PLAYER_MAX_HEIGHT = 240;
// Inputs that, when connected, set the clip on the graph instead.
const GRAPH_SET = ["start_seconds", "start_frame", "end_frame", "end_seconds", "fixed_frames", "frame_load_cap", "max_frames", "every_nth"];
function installCss() {
if (document.getElementById(CSS_ID)) return;
const style = document.createElement("style");
style.id = CSS_ID;
style.textContent = `
.ausboss-clip-window{display:flex;flex-direction:column;gap:6px;box-sizing:border-box;width:100%;min-width:0;overflow:hidden;padding:2px 0 4px;color:${THEME.inkSoft};font:13px ${FONT_UI}}
.ausboss-clip-window-head{display:flex;align-items:baseline;gap:6px;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:${THEME.label}}
.ausboss-clip-window-head b{color:${THEME.ink};font-weight:600}
.ausboss-clip-window-strip{position:relative;height:${STRIP_HEIGHT}px;margin:0 9px;border-radius:${RADIUS_CONTROL}px;background:${THEME.well};touch-action:none;user-select:none;cursor:pointer}
.ausboss-clip-window-strip.is-off{cursor:default}
.ausboss-clip-window-thumbs{position:absolute;inset:0;width:100%;height:100%;border-radius:${RADIUS_CONTROL}px;pointer-events:none}
.ausboss-clip-window-shade{position:absolute;top:0;bottom:0;background:rgba(8,9,10,.68);pointer-events:none}
.ausboss-clip-window-box{position:absolute;top:-3px;bottom:-3px;box-sizing:border-box;border:3px solid ${THEME.brand};border-radius:${RADIUS_CONTROL}px;cursor:grab;outline:none}
.ausboss-clip-window-box:focus-visible{box-shadow:0 0 0 2px ${THEME.ink}}
.ausboss-clip-window-strip.is-moving .ausboss-clip-window-box{cursor:grabbing}
.ausboss-clip-window-box[hidden]{display:none}
.ausboss-clip-window-edge{position:absolute;top:50%;width:9px;height:26px;margin-top:-13px;border-radius:3px;background:${THEME.brand};cursor:ew-resize}
.ausboss-clip-window-edge.start{left:-6px}
.ausboss-clip-window-edge.end{right:-6px}
.ausboss-clip-window-box.is-whole{cursor:default}
.ausboss-clip-window-box.is-whole .ausboss-clip-window-edge{display:none}
.ausboss-clip-window-empty{position:absolute;inset:0;display:grid;place-items:center;color:${THEME.faint};pointer-events:none}
.ausboss-clip-window-empty[hidden],.ausboss-clip-window-shade[hidden]{display:none}
.ausboss-clip-window-readout{color:${THEME.brandInk};font-weight:600;font-size:14px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ausboss-clip-window-hint{color:${THEME.faint};font-size:12px;line-height:1.4}
.ausboss-clip-window-hint.is-stop{color:${THEME.warnInk}}
.ausboss-clip-window-player{position:relative;width:100%;max-height:${PLAYER_MAX_HEIGHT}px;aspect-ratio:16/9;margin:0 auto;border-radius:${RADIUS_CONTROL}px;background:${THEME.well};overflow:hidden;cursor:pointer}
.ausboss-clip-window-player[hidden]{display:none}
.ausboss-clip-window-player video{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;pointer-events:none}
.ausboss-clip-window-play{position:absolute;left:50%;top:50%;width:46px;height:46px;margin:-23px 0 0 -23px;border-radius:50%;background:rgba(8,9,10,.62);pointer-events:none;opacity:0;transition:opacity .15s}
.ausboss-clip-window-play::after{content:"";position:absolute;left:18px;top:14px;border-style:solid;border-width:9px 0 9px 14px;border-color:transparent transparent transparent ${THEME.ink}}
.ausboss-clip-window-player.is-paused .ausboss-clip-window-play{opacity:1}
.ausboss-clip-window-playhead{position:absolute;top:0;bottom:0;width:2px;margin-left:-1px;background:${THEME.ink};box-shadow:0 0 0 1px rgba(8,9,10,.5);pointer-events:none}
.ausboss-clip-window-playhead[hidden]{display:none}
`;
document.head.append(style);
}
function el(tag, className = "", text = "") {
const item = document.createElement(tag);
if (className) item.className = className;
if (text) item.textContent = text;
return item;
}
const secondsText = (value) => String(Number((Number(value) || 0).toFixed(1)));
// A length in the readout keeps its tenth: "8.0 s used".
const lengthText = (value) => (Number(value) || 0).toFixed(1);
// options:
// get(name, fallback) / set(name, value) widget access
// driven(name) whether an input is linked
// number(name, fallback) a linked literal's value, null when only the run knows it
// outputRate() output fps, null when unknown
// metadata() the source's {fps, frame_count, duration}
// storyboard() {image, times, tileWidth, tileHeight} or null
// videoUrl() the source video for the player, "" for none
// onCommit() a drag settled (undo point)
export function mountClipWindow({ get, set, driven = () => false, number = (name, fallback) => get(name, fallback), outputRate = () => null, metadata, storyboard = () => null, videoUrl = () => "", onCommit }) {
installCss();
const root = el("div", "ausboss-clip-window");
const head = el("div", "ausboss-clip-window-head");
const strip = el("div", "ausboss-clip-window-strip");
const thumbs = el("canvas", "ausboss-clip-window-thumbs");
const shadeLeft = el("div", "ausboss-clip-window-shade");
const shadeRight = el("div", "ausboss-clip-window-shade");
const box = el("div", "ausboss-clip-window-box");
box.tabIndex = 0;
box.setAttribute("role", "slider");
box.setAttribute("aria-label", "Part of the video to use");
const edgeStart = el("span", "ausboss-clip-window-edge start");
const edgeEnd = el("span", "ausboss-clip-window-edge end");
box.append(edgeStart, edgeEnd);
const empty = el("div", "ausboss-clip-window-empty", "Choose a video first");
const playhead = el("div", "ausboss-clip-window-playhead");
playhead.hidden = true;
strip.append(thumbs, shadeLeft, shadeRight, box, playhead, empty);
const readout = el("div", "ausboss-clip-window-readout");
const hint = el("div", "ausboss-clip-window-hint");
// The player: muted, plays the picked part on a loop, a click pauses it.
const player = el("div", "ausboss-clip-window-player is-paused");
player.hidden = true;
player.title = "Click to play or pause";
const video = document.createElement("video");
video.muted = true;
video.playsInline = true;
video.preload = "auto";
video.disablePictureInPicture = true;
player.append(video, el("span", "ausboss-clip-window-play"));
root.append(player, head, strip, readout, hint);
const info = () => clipInfo(metadata());
const limits = () => lengthLimits(number("min_seconds", get("min_seconds", 0)) ?? 0, number("max_seconds", get("max_seconds", 0)) ?? 0);
const nth = () => Math.max(1, Math.trunc(Number(get("every_nth", 1)) || 1));
const rate = () => {
const known = outputRate?.();
if (known > 0) return known;
const clip = info();
return clip.fps > 0 ? clip.fps / nth() : 0;
};
// The clip is set on the graph (a connected input, or an exact Fixed
// frames count): the window shows nothing it cannot honour.
const setOnGraph = () => GRAPH_SET.some((name) => driven(name)) || Number(get("fixed_frames", 0)) > 0;
const current = () => clipWindowOf(info(), {
start: get("start_seconds", 0),
end: get("end_seconds", 0),
cap: get("max_frames", 0),
rate: rate(),
}, limits());
const rangeWords = () => {
const { min, max } = limits();
if (min > 0 && max > 0) return min === max ? `${secondsText(min)} s` : `${secondsText(min)} to ${secondsText(max)} s`;
if (max > 0) return `up to ${secondsText(max)} s`;
if (min > 0) return `at least ${secondsText(min)} s`;
return "";
};
let stopText = "";
let thumbsKey = "";
const drawThumbs = () => {
const clip = info();
const board = storyboard?.();
const width = Math.round(strip.clientWidth);
const height = Math.round(strip.clientHeight);
const key = `${width}x${height}:${board?.image?.src?.length ?? 0}:${board?.times?.length ?? 0}:${clip.duration}`;
if (key === thumbsKey) return;
thumbsKey = key;
const scale = Math.min(2, window.devicePixelRatio || 1);
thumbs.width = Math.max(1, Math.round(width * scale));
thumbs.height = Math.max(1, Math.round(height * scale));
const context = thumbs.getContext("2d");
if (!context) return;
context.clearRect(0, 0, thumbs.width, thumbs.height);
if (!board?.image || !board.times?.length || !(clip.duration > 0) || !width) return;
// Cells as wide as a tile drawn at the strip's height, each showing the
// tile nearest its middle.
const cellWidth = Math.max(24, (board.tileWidth / board.tileHeight) * height);
const cells = Math.max(1, Math.ceil(width / cellWidth));
const cell = thumbs.width / cells;
for (let index = 0; index < cells; index++) {
const moment = ((index + 0.5) / cells) * clip.duration;
let tile = 0;
for (let other = 1; other < board.times.length; other++) {
if (Math.abs(board.times[other] - moment) < Math.abs(board.times[tile] - moment)) tile = other;
}
// Cover the cell: crop the tile's sides to the cell's shape.
const sourceWidth = Math.min(board.tileWidth, (cell / thumbs.height) * board.tileHeight);
const sourceX = tile * board.tileWidth + (board.tileWidth - sourceWidth) / 2;
context.drawImage(board.image, sourceX, 0, sourceWidth, board.tileHeight, Math.floor(index * cell), 0, Math.ceil(cell), thumbs.height);
}
};
const sync = () => {
const clip = info();
const window = clip.count ? current() : null;
const off = !window || setOnGraph();
strip.classList.toggle("is-off", off);
empty.hidden = Boolean(window);
box.hidden = !window;
shadeLeft.hidden = shadeRight.hidden = !window;
const range = rangeWords();
if (!clip.count) {
head.textContent = "";
readout.textContent = "";
hint.textContent = range ? `The clip will be ${range} long.` : "";
hint.classList.remove("is-stop");
thumbsKey = "";
drawThumbs();
syncPlayer();
return;
}
head.replaceChildren(el("b", "", `Your video: ${secondsText(clip.duration)} s long`));
if (range) head.append(document.createTextNode(`· the clip is ${range} long`));
if (!window) {
readout.textContent = "";
hint.textContent = "The clip length is known once the graph runs.";
syncPlayer();
return;
}
const duration = clip.duration || clip.count / clip.fps;
const left = Math.max(0, Math.min(1, window.start / duration));
const right = Math.max(left, Math.min(1, (window.start + window.seconds) / duration));
box.style.left = `${(left * 100).toFixed(3)}%`;
box.style.width = `${((right - left) * 100).toFixed(3)}%`;
shadeLeft.style.left = "0";
shadeLeft.style.width = `${(left * 100).toFixed(3)}%`;
shadeRight.style.left = `${(right * 100).toFixed(3)}%`;
shadeRight.style.right = "0";
box.classList.toggle("is-whole", window.whole || off);
box.setAttribute("aria-valuemin", "0");
box.setAttribute("aria-valuemax", String(Number(duration.toFixed(2))));
box.setAttribute("aria-valuenow", String(Number(window.start.toFixed(2))));
box.setAttribute("aria-valuetext", `${secondsText(window.seconds)} seconds from ${formatTimecode(window.start)}`);
readout.textContent = window.whole
? `The whole video is used: ${lengthText(window.seconds)} s`
: `${lengthText(window.seconds)} s used, starting at ${formatTimecode(Math.round(window.start * 10) / 10)}`;
hint.classList.toggle("is-stop", Boolean(stopText));
if (off) hint.textContent = "This clip is set on the graph, so it cannot be moved here.";
else if (window.whole) hint.textContent = `The video is shorter than ${secondsText(limits().min)} s, so all of it is used.`;
else if (stopText) hint.textContent = stopText;
else hint.textContent = range
? `Drag the box to pick where it starts. Drag an edge to shorten it, never under ${secondsText(limits().min || 0)} s or over ${secondsText(limits().max || duration)} s.`
: "Drag the box to pick where it starts. Drag an edge to change its length.";
drawThumbs();
syncPlayer();
};
// --- player ---------------------------------------------------------------
let playerUrl = "";
let wantPlay = true; // the person's play/pause choice; a drag only pauses for its length
let onScreen = false;
let frameRequest = 0;
const playable = () => Boolean(playerUrl) && !player.hidden;
const showPlayhead = () => {
const clip = info();
const duration = clip.duration || (clip.fps ? clip.count / clip.fps : 0);
playhead.hidden = !playable() || !(duration > 0) || !(video.readyState >= 1);
if (!playhead.hidden) playhead.style.left = `${(Math.max(0, Math.min(1, video.currentTime / duration)) * 100).toFixed(3)}%`;
};
const seek = (seconds) => {
if (!(video.readyState >= 1) || !Number.isFinite(seconds)) return;
if (Math.abs(video.currentTime - seconds) > 0.01) video.currentTime = Math.max(0, seconds);
showPlayhead();
};
// Keeps the playhead inside the picked part while it plays.
const tick = () => {
frameRequest = 0;
if (video.paused || !onScreen) return;
const window = info().count ? current() : null;
if (window && !drag) {
const next = loopPlayhead(video.currentTime, window.start, window.seconds);
if (next !== video.currentTime) video.currentTime = next;
}
showPlayhead();
frameRequest = requestAnimationFrame(tick);
};
const play = () => {
if (!playable() || !onScreen || drag || !wantPlay) return;
const window = info().count ? current() : null;
if (window) seek(loopPlayhead(video.currentTime, window.start, window.seconds));
video.play().catch(() => { /* not ready or not allowed: stays paused */ });
};
const pause = () => { if (!video.paused) video.pause(); };
video.addEventListener("play", () => { player.classList.remove("is-paused"); if (!frameRequest) frameRequest = requestAnimationFrame(tick); });
video.addEventListener("pause", () => player.classList.add("is-paused"));
video.addEventListener("loadedmetadata", () => {
if (video.videoWidth > 0 && video.videoHeight > 0) player.style.aspectRatio = `${video.videoWidth} / ${video.videoHeight}`;
const window = info().count ? current() : null;
if (window) seek(window.start);
play();
});
// A file the browser cannot play: no player, the strip still works.
video.addEventListener("error", () => { player.hidden = true; playhead.hidden = true; });
player.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
event.preventDefault();
event.stopPropagation();
wantPlay = video.paused;
if (wantPlay) play(); else pause();
});
// Plays only while it can be seen: hidden on the graph, it stays still.
new IntersectionObserver((entries) => {
onScreen = entries.some((entry) => entry.isIntersecting);
if (onScreen) play(); else pause();
}).observe(player);
const syncPlayer = () => {
const url = info().count ? String(videoUrl?.() || "") : "";
if (url !== playerUrl) {
playerUrl = url;
player.hidden = !url;
playhead.hidden = true;
if (url) { video.src = url; video.load(); } else { video.removeAttribute("src"); video.load(); }
}
if (!playable()) return;
const window = info().count ? current() : null;
if (window && !drag && !video.paused) {
const next = loopPlayhead(video.currentTime, window.start, window.seconds);
if (next !== video.currentTime) seek(next);
}
showPlayhead();
};
const store = (window) => {
const values = clipWindowValues(window, info());
if (!driven("fixed_frames") && Number(get("fixed_frames", 0)) !== 0) set("fixed_frames", 0);
set("start_seconds", values.start_seconds);
set("end_seconds", values.end_seconds);
set("max_frames", values.max_frames);
};
// Why a drag stopped short of the pointer, in words.
const stopWords = (zone, wanted, got) => {
if (zone === "move" || Math.abs(wanted - got) < 0.5 / Math.max(1, rate())) return "";
const range = limitFrameRange(limits(), rate());
const frames = Math.round(got * rate());
if (frames >= range.max) return `${secondsText(got)} s is the longest it can be.`;
if (frames <= range.min) return `${secondsText(got)} s is the shortest it can be.`;
return "The video ends there.";
};
// --- gestures ---------------------------------------------------------------
let drag = null;
const secondsAt = (event) => {
const rect = strip.getBoundingClientRect();
const clip = info();
const duration = clip.duration || (clip.fps ? clip.count / clip.fps : 0);
const x = Math.max(0, Math.min(rect.width, event.clientX - rect.left));
return { seconds: rect.width > 0 ? (x / rect.width) * duration : 0, x, width: rect.width, duration };
};
const apply = (event, settled) => {
if (!drag) return;
const { seconds } = secondsAt(event);
const target = drag.zone === "move" ? seconds - drag.grab : seconds;
const next = dragClipWindow(drag.base, drag.zone, target, info(), limits());
if (!next) return;
const wantedLength = drag.zone === "end" ? seconds - drag.base.start
: drag.zone === "start" ? drag.base.start + drag.base.seconds - seconds : next.seconds;
stopText = stopWords(drag.zone, wantedLength, next.seconds);
store(next);
sync();
if (playable()) seek(settled || drag.zone !== "end" ? next.start : Math.max(next.start, next.start + next.seconds - 1 / Math.max(1, rate())));
if (settled) {
onCommit?.();
stopText = "";
setTimeout(sync, 1600);
}
};
strip.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
const window = info().count && !setOnGraph() ? current() : null;
if (!window || window.whole) return;
event.preventDefault();
event.stopPropagation();
const { seconds, width, duration } = secondsAt(event);
const pxPerSecond = duration > 0 ? width / duration : 0;
const startX = window.start * pxPerSecond;
const endX = (window.start + window.seconds) * pxPerSecond;
const x = seconds * pxPerSecond;
const nearStart = Math.abs(x - startX) <= EDGE_HIT_PX;
const nearEnd = Math.abs(x - endX) <= EDGE_HIT_PX;
let zone;
if (nearStart || nearEnd) zone = nearStart && nearEnd ? (x < (startX + endX) / 2 ? "start" : "end") : nearStart ? "start" : "end";
else zone = "move";
// A press outside the box brings the box there, centred on the press.
const inside = x > startX && x < endX;
const grab = zone !== "move" ? 0 : inside ? seconds - window.start : window.seconds / 2;
drag = { zone, grab, base: window, pointerId: event.pointerId };
pause();
strip.classList.toggle("is-moving", zone === "move");
box.focus({ preventScroll: true });
try { strip.setPointerCapture(event.pointerId); } catch { /* mouse fallback */ }
apply(event, false);
});
strip.addEventListener("pointermove", (event) => {
if (!drag) {
const window = info().count && !setOnGraph() ? current() : null;
if (!window || window.whole) { strip.style.cursor = ""; return; }
const { seconds, width, duration } = secondsAt(event);
const px = duration > 0 ? width / duration : 0;
const near = Math.min(Math.abs(seconds - window.start), Math.abs(seconds - window.start - window.seconds)) * px <= EDGE_HIT_PX;
strip.style.cursor = near ? "ew-resize" : "grab";
return;
}
event.preventDefault();
event.stopPropagation();
apply(event, false);
});
const finish = (event) => {
if (!drag) return;
if (event) apply(event, true);
else onCommit?.();
try { if (strip.hasPointerCapture(drag.pointerId)) strip.releasePointerCapture(drag.pointerId); } catch { /* released already */ }
drag = null;
strip.classList.remove("is-moving");
play();
};
strip.addEventListener("pointerup", (event) => { event.stopPropagation(); finish(event); });
strip.addEventListener("pointercancel", () => finish(null));
strip.addEventListener("lostpointercapture", () => finish(null));
// Arrow keys slide the box a second at a time; Shift moves one frame.
box.addEventListener("keydown", (event) => {
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
const window = info().count && !setOnGraph() ? current() : null;
if (!window || window.whole) return;
event.preventDefault();
event.stopPropagation();
const clip = info();
const step = event.shiftKey && clip.fps > 0 ? 1 / clip.fps : 1;
const target = event.key === "Home" ? 0 : event.key === "End" ? Infinity
: window.start + (event.key === "ArrowLeft" ? -step : step);
const moved = dragClipWindow(window, "move", Number.isFinite(target) ? target : clip.duration, clip, limits());
store(moved);
sync();
if (moved && playable()) seek(moved.start);
onCommit?.();
});
new ResizeObserver(() => drawThumbs()).observe(strip);
sync();
return { root, sync };
}
+156
View File
@@ -0,0 +1,156 @@
// H3 Prompt Writer's two tabs. Simple is the card as it always was: your
// lines, the chips and the menus. Full prompt shows the prompt the node wrote
// on its last run, in a box you can change; whatever you type there is what
// H3 gets, until Reset to written. The `full_prompt` widget underneath holds
// the edit (empty when there is none), so it saves and loads like any value.
import { app } from "../../../scripts/app.js";
import { chainCallback, notifyAusbossChange } from "./index.mjs";
import { keepKeyInField } from "./canvas_passthrough.mjs";
import { compactAction } from "./panel_controls.mjs";
import { THEME as T } from "./theme.mjs";
import { commitWidgetValue } from "./widget_card_math.mjs";
import { FULL, SIMPLE, TAB_PROPERTY, WRITTEN_PROPERTY, boxText, editValue, isEdited, promptTab, writtenFromOutput } from "./h3_full_prompt_math.mjs";
export { FULL, SIMPLE, isEdited, promptTab };
const CSS_ID = "ausboss-h3-full-prompt-css";
const EDITED_NOTE = "Edited by you. This text is sent as it is; the Simple tab is not used until you reset.";
function ensureCss() {
if (document.getElementById(CSS_ID)) return;
const style = document.createElement("style");
style.id = CSS_ID;
style.textContent = `
.ausboss-prompt-tabs .dot{display:inline-block;width:6px;height:6px;margin-left:6px;border-radius:3px;background:${T.warn};vertical-align:1px}
.ausboss-prompt-tabs .dot[hidden]{display:none}
.ausboss-full-prompt{display:flex;flex-direction:column;gap:6px;height:100%;min-height:0}
.ausboss-full-prompt-area{display:block;flex:1 1 auto;width:100%;min-width:0;min-height:0;padding:5px 8px;box-sizing:border-box;border:1px solid transparent;border-radius:6px;background:${T.fill};color:${T.ink};font:11.5px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;resize:none;overflow:auto}
.ausboss-full-prompt-area:focus{outline:none;border-color:${T.brand}}
.ausboss-full-prompt-area::placeholder{color:${T.faint}}
.ausboss-full-prompt-note{flex:none;padding:5px 8px;border-radius:5px;background:${T.warnSoft};color:${T.warnInk};font-size:11px;line-height:1.35}
.ausboss-full-prompt-note[hidden]{display:none}
.ausboss-full-prompt-foot{flex:none;display:flex;align-items:center;gap:8px;min-height:24px}
.ausboss-full-prompt-foot span{flex:1 1 auto;min-width:0;color:${T.faint};font-size:11px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}
.ausboss-simple-edited{display:flex;align-items:center;height:100%;padding:0 8px;box-sizing:border-box;border-radius:5px;background:${T.warnSoft};color:${T.warnInk};font-size:11px;line-height:1.3}
`;
document.head.append(style);
}
const widgetOf = (node, name) => node.widgets?.find((widget) => widget.name === name) ?? null;
const redraw = (node) => (node.__ausbossCard?.refreshByHand ?? node.__ausbossCard?.refresh)?.();
const writtenOf = (node) => String(node.properties?.[WRITTEN_PROPERTY] ?? "");
function setEdit(node, value) {
const widget = widgetOf(node, "full_prompt");
if (!widget || widget.value === value) return;
commitWidgetValue(node, widget, value, app?.canvas);
node.graph?.setDirtyCanvas?.(true, true);
}
// The tab switch at the top of the card. The open tab is a display choice
// kept on the node, not a value: it changes nothing that is sent.
export function promptTabs(node) {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-card-seg ausboss-prompt-tabs";
const make = (tab, label, title) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.title = title;
button.addEventListener("click", () => {
if (promptTab(node) === tab) return;
node.properties ??= {};
node.properties[TAB_PROPERTY] = tab;
redraw(node);
});
element.append(button);
return button;
};
const simple = make(SIMPLE, "Simple", "Your lines, the pictures and the menus. The node writes the full prompt from them.");
const full = make(FULL, "Full prompt", "The prompt the node wrote on its last run. Change it here to send your own.");
const dot = document.createElement("span");
dot.className = "dot";
dot.title = "Edited: this text is sent instead of the Simple tab.";
full.append(dot);
return {
element,
sync(values) {
const tab = promptTab(node);
simple.classList.toggle("on", tab === SIMPLE);
full.classList.toggle("on", tab === FULL);
dot.hidden = !isEdited(values);
},
};
}
// One line on the Simple tab while an edit is being sent instead.
export function simpleEditedNote() {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-simple-edited";
element.textContent = "Full prompt is edited, so these lines are not used until you reset it there.";
return { element };
}
// The Full prompt tab: the box, a note while it holds an edit, and Reset.
export function fullPromptBox(node) {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-full-prompt";
const area = document.createElement("textarea");
// Not the card's own textarea class: the script's colouring takes the
// first box with that class, and it belongs to the script.
area.className = "ausboss-full-prompt-area";
area.spellcheck = false;
area.placeholder = "Run the workflow once and the prompt the node writes shows here. Change it to send your own.";
area.title = "What H3 gets. Type here to send your own text instead of the node's.";
const note = document.createElement("div");
note.className = "ausboss-full-prompt-note";
note.textContent = EDITED_NOTE;
const foot = document.createElement("div");
foot.className = "ausboss-full-prompt-foot";
const hint = document.createElement("span");
hint.textContent = "Filled in after each run.";
const reset = compactAction("Reset to written", "Throw your edit away and send what the Simple tab writes again.");
foot.append(hint, reset);
element.append(area, note, foot);
area.addEventListener("input", () => {
setEdit(node, editValue(area.value, writtenOf(node)));
redraw(node);
});
area.addEventListener("change", () => notifyAusbossChange());
area.addEventListener("keydown", (event) => {
keepKeyInField(event, { weights: true });
if (event.key === "Escape") area.blur();
});
// Leaving the box shows what is sent: emptied, it is the written prompt again.
area.addEventListener("blur", () => redraw(node));
reset.addEventListener("click", () => {
setEdit(node, "");
area.value = writtenOf(node);
notifyAusbossChange();
redraw(node);
});
// Each run hands back the prompt the node wrote. It is kept on the node, so
// a saved workflow opens with it.
chainCallback(node, "onExecuted", (output) => {
const written = writtenFromOutput(output);
if (written === null) return;
node.properties ??= {};
node.properties[WRITTEN_PROPERTY] = written;
redraw(node);
});
return {
element,
sync(values) {
const edited = isEdited(values);
if (document.activeElement !== area) area.value = boxText(values, writtenOf(node));
note.hidden = !edited;
reset.disabled = !edited;
},
};
}
+39
View File
@@ -0,0 +1,39 @@
// What H3 Prompt Writer's Full prompt tab decides, kept apart from the DOM so
// it can be tested. The node writes the prompt; the tab shows what it wrote
// after a run, and text typed there is sent in its place until Reset.
export const SIMPLE = "simple";
export const FULL = "full";
// Display choices kept on the node: the open tab, and the last prompt the
// node wrote (so a saved workflow opens the tab with it).
export const TAB_PROPERTY = "ausboss_prompt_tab";
export const WRITTEN_PROPERTY = "ausboss_written_prompt";
export function promptTab(node) {
return node?.properties?.[TAB_PROPERTY] === FULL ? FULL : SIMPLE;
}
// The widget holds an edit only when there is one: empty text, or the
// written prompt typed back unchanged, means "send what the node writes".
export function editValue(text, written = "") {
const typed = String(text ?? "");
if (!typed.trim()) return "";
if (written && typed.trim() === String(written).trim()) return "";
return typed;
}
export function isEdited(values) {
return String(values?.full_prompt ?? "").trim() !== "";
}
// What the box shows: the edit, else the last prompt the node wrote.
export function boxText(values, written = "") {
return isEdited(values) ? String(values.full_prompt) : String(written ?? "");
}
// The prompt the node wrote on its last run, from the run's ui output.
export function writtenFromOutput(output) {
const text = output?.written_prompt;
if (Array.isArray(text)) return typeof text[0] === "string" ? text[0] : null;
return typeof text === "string" ? text : null;
}
+117
View File
@@ -0,0 +1,117 @@
// Language for the pack's own node faces. ComfyUI translates node names and
// socket names from locales/<language>/nodeDefs.json; the controls the pack
// draws itself (widget cards, panels, bars, menus) are translated here.
//
// t("Preview") the Chinese text on a Chinese ComfyUI, else the same text
// translateText(text) the lookup alone, no locale check
//
// The Chinese table is js/shared/i18n_zh.mjs, keyed by the English text, so a
// string with no entry stays English. Only what is displayed changes; widget
// names, widget values and saved workflows never go through this.
import { PATTERNS, SCRUB_HINT_EN, SCRUB_HINT_ZH, ZH } from "./i18n_zh.mjs";
// "zh", "zh-CN", "zh-TW" ... all take the Chinese table.
export function isChineseLocale(code) {
return typeof code === "string" && /^zh(?:[-_]|$)/i.test(code.trim());
}
// ComfyUI's language setting, read each time so a changed setting is seen on
// the next call.
let localeSource = null;
// js/i18n/index.js hands over ComfyUI's own `app`, which is there before
// `window.app` is.
export function useLocaleSource(read) { localeSource = typeof read === "function" ? read : null; }
export function currentLocale() {
try {
const value = localeSource ? localeSource() : globalThis.app?.ui?.settings?.getSettingValue?.("Comfy.Locale");
return typeof value === "string" ? value : "";
} catch {
return "";
}
}
export const chineseActive = () => isChineseLocale(currentLocale());
// Look `text` up in the Chinese table, keeping any spaces around it. Returns
// the text itself when there is no entry.
export function translateText(text, table = ZH, patterns = PATTERNS) {
if (typeof text !== "string" || text === "") return text;
const trimmed = text.trim();
if (trimmed === "") return text;
// A number box's tooltip is "<its own tooltip> <the scrub hint>".
if (table === ZH && trimmed.endsWith(` ${SCRUB_HINT_EN}`)) {
const own = trimmed.slice(0, -SCRUB_HINT_EN.length - 1);
return text.replace(trimmed, () => `${translateText(own, table, patterns)} ${SCRUB_HINT_ZH}`);
}
const hit = Object.hasOwn(table, trimmed) ? table[trimmed] : undefined;
let result = typeof hit === "string" && hit !== "" ? hit : null;
if (result === null) {
for (const [pattern, build] of patterns) {
const match = pattern.exec(trimmed);
if (match) { result = build(...match); break; }
}
}
if (result === null) return text;
return text.replace(trimmed, () => result);
}
export function t(text) {
return chineseActive() ? translateText(text) : text;
}
// ---------- translating a face that is already built ----------
const ATTRIBUTES = ["title", "placeholder", "aria-label"];
// Text that belongs to the user or the graph, or that code reads back.
const SKIP = "[data-no-i18n],[class*='ausboss-callout'],[class*='ausboss-note'],.ausboss-show-text-body,.ausboss-lora-label";
// Text inside these is a value (what is typed, or the page's own scripts), not a label.
const VALUE_HOLDERS = "textarea,input,script,style,[contenteditable]";
const SCOPE = "[class*='ausboss']";
function inScope(element, text = false) {
if (!element?.closest?.(SCOPE) || element.closest(SKIP)) return false;
return !(text && element.closest(VALUE_HOLDERS));
}
function translateNode(node) {
if (node.nodeType === 3) {
const parent = node.parentElement;
// An <option>'s text is what the list shows; its value is its own attribute.
if (!parent || !inScope(parent, true)) return;
const next = translateText(node.nodeValue);
if (next !== node.nodeValue) node.nodeValue = next;
return;
}
if (node.nodeType !== 1 || !(node.matches?.(SCOPE) || node.querySelector?.(SCOPE) || node.closest?.(SCOPE))) return;
const walker = node.ownerDocument.createTreeWalker(node, 1 | 4);
const visit = (current) => {
if (current.nodeType === 3) translateNode(current);
else if (current.nodeType === 1 && inScope(current)) {
for (const name of ATTRIBUTES) {
const value = current.getAttribute(name);
if (!value) continue;
const next = translateText(value);
if (next !== value) current.setAttribute(name, next);
}
}
};
visit(node);
for (let current = walker.nextNode(); current; current = walker.nextNode()) visit(current);
}
// Keep every pack face in `root` translated, including text a face writes
// later. Returns a function that stops it.
export function followFaces(root = document.body) {
translateNode(root);
const observer = new MutationObserver((records) => {
for (const record of records) {
if (record.type === "characterData") translateNode(record.target);
else if (record.type === "attributes") translateNode(record.target);
else for (const added of record.addedNodes) translateNode(added);
}
});
observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ATTRIBUTES });
return () => observer.disconnect();
}
+340
View File
@@ -0,0 +1,340 @@
// Simplified Chinese for the text the pack draws on its own node faces
// (widget cards, panels, bars and menus). The key is the English text as the
// code writes it; a string with no entry here simply stays English.
// Only what is DISPLAYED changes: widget names, values, saved workflows and
// the API prompt never see these strings.
//
// Product and model names (H3, Pika, Qwen, FlashVSR, LoRA, VRAM, SAM 3) and
// file names, codec names and algorithm names stay as they are.
export const ZH = {
// ---- card rows and group headers
"Target": "目标", "Size": "尺寸", "Edge": "边缘", "Budget": "像素预算", "Scale": "缩放", "Fit": "适应",
"Fill": "填充", "Multiple": "倍数", "Filter": "滤镜", "Job": "任务", "Pieces": "分块数",
"Lock": "锁定", "Tolerance": "容差", "Feather": "羽化", "Remove tint": "去除偏色", "Strength": "强度",
"Method": "方法", "Reference": "参考", "Invert mask": "反转遮罩", "Megapixels": "百万像素",
"More": "更多", "MORE": "更多", "Tile size": "分块大小", "Overlap": "重叠", "Redraw limit": "重绘上限",
"Keep colors": "保持颜色", "Tone match": "色调匹配", "Fix edge halo": "修复边缘光晕", "Follow changes": "跟随变化",
"Context": "上下文", "Stay in picture": "不出画面", "Blend": "混合", "Grow": "扩大", "Blur": "模糊",
"Target size, extend": "目标尺寸与外扩", "Extra context": "额外上下文", "Target width": "目标宽度", "Target height": "目标高度",
"Rescale": "重新缩放", "Extend left": "向左外扩", "Extend right": "向右外扩", "Extend up": "向上外扩", "Extend down": "向下外扩",
"Expand": "扩张", "Fill holes": "填补孔洞", "Max hole size": "最大孔洞", "Smooth": "平滑", "Black point": "黑场", "White point": "白场",
"From": "来源", "Folder": "文件夹", "Subfolders": "子文件夹", "Order": "排序", "Run": "运行", "Picture": "图片",
"After a run": "运行之后", "At the end": "到末尾时", "Soften": "柔化", "Fine edges": "精细边缘", "Fill small holes": "填补小孔",
"Invert": "反转", "If nothing": "没选中时", "New picture": "换新图时", "Free VRAM": "释放显存", "Canvas": "画布",
"Find": "查找", "If several": "有多个时", "Sureness": "把握度", "FPS": "帧率", "Scene cut": "场景切换", "Batch": "批量",
"Model": "模型", "Mode": "模式", "Anchor": "对齐位置", "Pad fill": "扩边填充", "Pad color": "扩边颜色", "Color": "颜色",
"Empty fill": "空白填充", "Max zoom": "最大缩放", "Every nth": "每隔几帧", "Offset": "偏移", "Split after": "在此之后拆分",
"Mismatch": "尺寸不一致", "Value": "数值", "Split at": "拆分方式", "Numbering": "编号", "Limit": "数量上限",
"Length": "长度", "Camera": "镜头", "Look": "风格", "Song starts at": "歌曲起点", "Moments on the beat": "时刻对齐节拍",
"Language": "语言", "Clip's own sound": "素材自带声音", "Sound": "声音", "Music": "音乐", "Frame": "帧",
"KV cache": "KV 缓存", "VLM reference": "VLM 参考", "Source": "素材", "Width": "宽度", "Height": "高度",
"Longest side": "最长边", "Ratio": "比例", "Keep": "保留", "Round to": "取整到", "Enlarge": "放大小图",
"Backdrop": "背景虚化", "Exact padding": "精确扩边", "Left": "左", "Top": "上", "Right": "右", "Bottom": "下",
"Prefix": "文件名前缀", "Format": "格式", "FPS · CRF": "帧率 · CRF", "Ping-pong": "往返播放", "Embed workflow": "嵌入工作流",
"Pictures and settings": "图片与设置", "What H3 gets": "H3 收到的内容", "What happens": "发生了什么",
"Align": "对齐", "Aspect ratio": "画面比例", "Crop, pad & resize": "裁剪、扩边与缩放", "Duration": "时长", "Ends at": "结束于",
"Frames for": "帧数用于", "Start": "起点", "Whole video": "整段视频", "Clip IN": "片段入点", "Clip OUT": "片段出点",
"Colors": "颜色", "Preview steps": "预览步骤", "Show picture": "显示图片", "Preview": "预览",
"Settings": "设置", "Show as": "显示为", "When off": "关闭时", "Group order": "分组顺序", "Groups": "分组", "Inputs": "输入", "Outputs": "输出",
"Fit to ratio": "适应比例", "Hold the shape": "保持形状", "Box 1 is": "框 1 是",
// ---- on / off pills and short states
"on": "开", "off": "关", "On": "开", "Off": "关", "keep": "保留", "remove": "移除", "once per run": "每次运行一次", "every step": "每一步",
"Pause": "暂停", "wait for me": "等我取景", "run through": "直接运行",
"forward, back": "正放、倒放", "not used": "未使用", "by blend in": "(融合模式下)", "blend in": "融合", "blend": "混合",
// ---- choice labels
"Width × height": "宽 × 高", "Longest edge": "最长边", "Shortest edge": "最短边", "Scale factor": "缩放倍数",
"cover": "填满", "fit": "适应", "fit inside": "放入框内", "crop to fill": "裁剪填满", "crop to ratio": "按比例裁剪", "crop": "裁剪",
"pad": "扩边", "resize": "缩放", "stretch": "拉伸", "megapixels": "百万像素", "longest side": "最长边", "scale": "缩放",
"hist": "直方图", "histogram": "直方图", "first frame": "首帧", "reference": "参考图", "guided": "引导", "matting": "抠图",
"optical flow (RAFT)": "光流 (RAFT)", "match a": "匹配 a", "match b": "匹配 b", "error": "报错", "source rect": "源矩形",
"whole canvas": "整个画布", "all in one run": "一次全部", "one per run": "每次一张", "all of them": "全部", "none": "无", "None": "无",
"any": "任意", "always": "始终", "auto": "自动", "stay": "保持", "start over": "重新开始", "keep picks": "保留选择",
"stop the run": "停止运行", "empty mask": "空遮罩", "newest first": "最新在前", "oldest first": "最旧在前", "random": "随机", "Random": "随机",
"next": "下一张", "name": "名称", "title": "标题", "canvas": "画布", "each line": "每行一次", "blank line": "空行分隔",
"rows": "逐行", "one pill": "单选", "bypass": "绕过", "mute": "静音", "mirror": "镜像", "follow": "跟随", "linked": "已连接",
"gray": "灰色", "edge": "边缘", "edge pixel": "边缘像素", "color": "纯色", "pillarbox blur": "两侧虚化", "replicate": "复制边缘",
"source": "原图", "as typed": "照输入", "from the picture": "取自图片", "text": "文字", "object": "物体", "still": "静止", "handheld": "手持",
"shaky": "抖动", "push in": "推近", "pull back": "拉远", "orbit": "环绕", "walking pov": "步行视角", "anime": "动漫", "comic book": "漫画",
"pencil sketch": "铅笔素描", "watercolor": "水彩", "split sheet at gaps": "按空隙拆分拼图", "Pad": "扩边", "Crop": "裁剪",
"Resize": "缩放", "Center": "居中", "Soft": "柔和", "Simple": "简易", "Full prompt": "完整提示词", "Text": "文字", "Fixed": "固定",
"LTX (8n+1)": "LTX (8n+1)", "Wan (4n+1)": "Wan (4n+1)", "Every group": "每个分组", "Numbered groups": "编号分组",
"Titles matching…": "按标题匹配…", "No groups": "没有分组", "All": "全部", "Background": "背景", "Subject": "主体",
// ---- buttons, bars, captions
"Add": "添加", "Browse": "浏览", "Clear": "清除", "Done": "完成", "Erase": "擦除", "Paint": "绘制", "Pick": "选取", "Load": "加载",
"Open editor": "打开编辑器", "Reset": "重置", "Reset crop": "重置裁剪", "Reset padding": "重置扩边", "Reset to written": "恢复为所写内容",
"Undo": "撤销", "Use as start": "设为起点", "Use last run": "用上次的", "New seed": "新种子", "Step +1": "步进 +1", "STOP": "停止",
"FIND": "查找", "FRAME": "帧", "LOOP": "循环", "AUTO": "自动", "Turn": "旋转", "Step": "步进", "Match": "匹配",
"+ Choice": "+ 选项", "+ LoRA": "+ LoRA", "+ new": "+ 新建", "+ video": "+ 视频", "Layouts ▾": "布局 ▾",
"Select nodes, then add a switch": "先选中节点,再添加开关", "Description": "说明",
"Choose a file…": "选择文件…", "Choose a sound file": "选择声音文件", "Choose an input video…": "选择输入视频…",
"Choose an uploaded image…": "选择已上传的图片…", "Choose an uploaded video…": "选择已上传的视频…",
"Choose or upload a video": "选择或上传视频", "Choose an input image": "选择输入图片", "Choose an input video": "选择输入视频",
"Copy a folder from your computer": "从电脑复制一个文件夹", "Load image": "加载图片", "Load video": "加载视频",
"Connect a mask to see it here": "连接遮罩即可在此查看", "Connect an image to see it here": "连接图像即可在此查看",
"Connect frames to see it here": "连接帧即可在此查看",
"Connect a picture or a video. H3 needs one to start from.": "请连接一张图片或一段视频,H3 需要一个起点。",
"Drag on the canvas to draw a box": "在画布上拖动来画一个框",
"Each box you draw gets its words here: a thing to show, or text to write in the picture.": "你画的每个框都在这里写描述:要显示的东西,或要写在图里的文字。",
"Edited by you. This text is sent as it is; the Simple tab is not used until you reset.": "已由你修改。这段文字将原样发送,重置之前不会使用“简易”标签页。",
"Edited: this text is sent instead of the Simple tab.": "已修改:发送的是这段文字,而不是“简易”标签页。",
"Full prompt is edited, so these lines are not used until you reset it there.": "完整提示词已被修改,所以这些行在那边重置之前不会使用。",
"Filled in after each run.": "每次运行后自动填入。",
"No LoRAs yet": "还没有 LoRA", "no LoRAs": "没有 LoRA", "No pictures here yet. Drop a folder or pictures on the node, or bring a folder in:": "这里还没有图片。把文件夹或图片拖到节点上,或导入一个文件夹:",
"no pictures": "没有图片", "Working on the fine details…": "正在处理细节…", "Run to preview the saved video": "运行后预览保存的视频",
"run the graph to see the text that arrives here": "运行工作流即可在此看到传入的文字",
"rolls a new seed each queue": "每次排队都会换新种子", "Source · feather 24 px": "素材 · 羽化 24 px",
"Select the nodes of one part, such as a box and its Save, then press + Switch.": "选中某个部分的节点(例如一个框和它的保存节点),然后点“+ 开关”。",
"Choose an uploaded image or drop one onto this node.": "选择已上传的图片,或把图片拖到此节点上。",
"Choose an uploaded video or add one to ComfyUI's input folder.": "选择已上传的视频,或把视频放进 ComfyUI 的 input 文件夹。",
"Choose a file from ComfyUI's input folder or load a new image.": "从 ComfyUI 的 input 文件夹选择文件,或加载新图片。",
"Choose a file from ComfyUI's input folder or load a new video.": "从 ComfyUI 的 input 文件夹选择文件,或加载新视频。",
"Choose a rendered image from ComfyUI's output folder.": "从 ComfyUI 的 output 文件夹选择已生成的图片。",
"Choose a rendered video from ComfyUI's output folder.": "从 ComfyUI 的 output 文件夹选择已生成的视频。",
"Choose a picture or video to center.": "选择要居中的图片或视频。",
"Upload a picture into ComfyUI's input folder": "把图片上传到 ComfyUI 的 input 文件夹",
"Upload an image into ComfyUI's input folder": "把图片上传到 ComfyUI 的 input 文件夹",
"Upload a video into ComfyUI's input folder": "把视频上传到 ComfyUI 的 input 文件夹",
"Upload a sound file into ComfyUI's input folder": "把声音文件上传到 ComfyUI 的 input 文件夹",
// ---- tooltips written in the pack's own code
"Add a LoRA": "添加 LoRA", "Pick one LoRA, or click a folder name to add all its LoRAs.": "选一个 LoRA,或点文件夹名把里面的 LoRA 全部加入。",
"Re-check LoRA files: refresh the list and reconnect rows whose files moved or came back": "重新检查 LoRA 文件:刷新列表,并重新连接文件被移动或重新出现的行",
"LoRA templates: save this stack, or apply a saved one": "LoRA 模板:保存当前这组,或套用已保存的",
"Toggle every LoRA: mixed saves your setup and turns all on; on turns all off; off brings your saved setup back": "切换所有 LoRA:混合时保存当前设置并全部开启;全开时全部关闭;全关时恢复你保存的设置",
"Serialized LoRA stack managed by the node's row editor; edit the rows, not this value.": "由节点的行编辑器管理的 LoRA 列表;请编辑各行,不要改这个值。",
"LoRA Loader settings": "LoRA 加载器设置",
"Click to type a seed": "点击输入种子", "Copy the seed": "复制种子", "Copy the text": "复制文字", "Earlier seeds this node ran with": "此节点用过的历史种子",
"Increment the seed after each queue (click again for decrement)": "每次排队后种子加 1(再点一次改为减 1)",
"Keep this seed for every queue": "每次排队都用这个种子",
"Put the last run's seed back and pin it (Fixed)": "恢复上次运行的种子并固定",
"Roll a fresh seed and pin it (Fixed)": "随机一个新种子并固定",
"Roll a new seed after every queue": "每次排队后随机新种子",
"Rolls a new seed after each run. Tap for Fixed.": "每次运行后随机新种子。点一下切换为固定。",
"Seed settings: full or compact look": "种子设置:完整或紧凑外观", "Number settings": "数字设置", "Text settings": "文字设置",
"Image Crop + Rotate + Pad settings": "图像裁剪 + 旋转 + 扩边设置", "Stitch Inpaint settings": "拼回重绘设置",
"Step down; Shift = fine.": "减小;按住 Shift 精细调节。", "Step up; Shift = fine.": "增大;按住 Shift 精细调节。",
"Arithmetic over a, b and c: numbers, + - * / // % **, parentheses, and min/max/abs/round/floor/ceil/sqrt.": "对 a、b、c 做运算:数字、+ - * / // % **、括号,以及 min/max/abs/round/floor/ceil/sqrt。",
"Center side to side": "左右居中", "Center top to bottom": "上下居中",
"Choose how to reach the next ratio. Crop trims the picture and Pad adds fill.": "选择如何达到下一个比例:裁剪会切掉画面,扩边会补上填充。",
"Comma-separated text; a group is listed when its title contains any of it": "用逗号分隔的文字;分组标题包含其中任意一项就会列出",
"Drag a handle to set where the sound starts or stops. Drag the middle to slide it.": "拖动手柄设置声音的起点或终点,拖动中间可整体滑动。",
"Drag to change the Duration; the start stays.": "拖动来改变时长,起点不变。",
"Drag to move the clip; its Duration stays. Shift + arrow moves one frame.": "拖动来移动片段,时长不变。Shift + 方向键每次移动一帧。",
"Drag to slide the clip; its Duration stays.": "拖动来滑动片段,时长不变。",
"Fill #000000": "填充 #000000", "Fill #808080": "填充 #808080",
"Fill colour of the padding and rotation corners. Now #808080.": "扩边和旋转后空角的填充颜色。当前为 #808080。",
"Keep the canvas size.": "保持画布尺寸。", "Keep the whole picture and add fill to reach the selected ratio.": "保留整张图片,并补上填充以达到所选比例。",
"Trim the picture to the selected ratio.": "把图片裁剪到所选比例。",
"Pad to 16:9: keep every pixel and add fill around it.": "扩边到 16:9:保留每个像素,四周补上填充。",
"Pad to 1:1: keep every pixel and add fill around it.": "扩边到 1:1:保留每个像素,四周补上填充。",
"Pad to 21:9: keep every pixel and add fill around it.": "扩边到 21:9:保留每个像素,四周补上填充。",
"Pad to 3:2: keep every pixel and add fill around it.": "扩边到 3:2:保留每个像素,四周补上填充。",
"Pad to 4:3: keep every pixel and add fill around it.": "扩边到 4:3:保留每个像素,四周补上填充。",
"Tap a ratio to pad the picture to it (or crop it, with Fit on crop). Tap the lit one to go back to the whole picture.": "点一个比例,把图片扩边到该比例(“适应”选裁剪时则是裁剪)。再点亮着的那个可回到完整图片。",
"Show the portrait ratios": "显示竖版比例", "Show ratio, fit, align, fill, feather, center and resize settings": "显示比例、适应、对齐、填充、羽化、居中和缩放设置",
"Reset rotation, crop and padding, and turn the padlock off. Fill, feather, Align and the timeline stay.": "重置旋转、裁剪和扩边,并解除锁定。填充、羽化、对齐和时间线保持不变。",
"Show the whole picture again; rotation, padding and the timeline stay. With the padlock on, the bands it added to keep the shape go too.": "重新显示整张图片;旋转、扩边和时间线保持不变。锁定时,为保持形状而补的边也会去掉。",
"The diamonds and crop squares drag freely; the orange corners always keep the shape. Tap to hold this shape whatever you drag.": "菱形和裁剪方块可自由拖动;橙色角点始终保持形状。点一下,无论怎么拖都保持当前形状。",
"Make the canvas width and height multiples of this number before resizing. Padding grows or unpadded edges are trimmed. Use 1 to turn alignment off.": "缩放前先让画布宽高成为此数的倍数。扩边会加大,没扩边的边缘会被裁掉。填 1 表示不对齐。",
"Rounds each resized side to a multiple of this (32 for LTX and Wan, 8 or 64 for image models). Each side rounds on its own, so a large step can stretch the picture slightly; the readout warns above 1%.": "把缩放后的每条边取整为此数的倍数(LTX 和 Wan 用 32,图像模型用 8 或 64)。每条边各自取整,步长大时画面可能略有拉伸;超过 1% 时读数会提醒。",
"Output budget in megapixels (x 1024x1024). The size readout under the picture shows where it lands.": "输出像素预算,单位百万像素(x 1024x1024)。图片下方的尺寸读数会显示最终大小。",
"Resize the output to a megapixel budget, each side rounded to the step (32 for LTX and Wan).": "把输出缩放到像素预算,每条边取整到步长(LTX 和 Wan 用 32)。",
"Resize to the megapixel budget and round each side to the step.": "缩放到像素预算,每条边取整到步长。",
"Feather of the mask into the kept pixels; the image keeps a hard edge against the fill.": "遮罩向保留像素内的羽化;图片与填充之间保持硬边。",
"Feather of the mask into the kept frames, in pixels. The frames keep a hard edge against the fill whatever the feather, so a black-band outpaint still sees its bars.": "遮罩向保留画面内的羽化,单位像素。无论羽化多少,画面与填充之间都保持硬边,所以黑边外扩仍能看到黑条。",
"Where the clip starts in the source video.": "片段在源视频中的起点。", "Where the clip ends in the source video. Typing it changes the Duration.": "片段在源视频中的终点。输入它会改变时长。",
"Start the clip at the frame on the stage. The Duration stays.": "让片段从舞台上当前这一帧开始,时长不变。",
"How long the clip is. Counted in clip frames at the output rate.": "片段有多长,按输出帧率的片段帧数计算。",
"How long the sound is. Clear it, or type 0, to run to the end of the file.": "声音有多长。清空或输入 0 表示播到文件末尾。",
"Where the sound starts in the file, of 0:00.": "声音在文件中的起点,从 0:00 起算。", "Where the sound stops in the file. Typing it changes the Duration.": "声音在文件中的终点。输入它会改变时长。",
"Keep a frame count the video model takes: LTX wants 8n+1 (49, 97, 121), Wan 4n+1. The Duration steps to those counts. Any keeps every frame.": "保留视频模型能接受的帧数:LTX 需要 8n+1(49、97、121),Wan 需要 4n+1。时长会按这些帧数步进。选“任意”则保留每一帧。",
"Keep one frame in this many. Output fps is adjusted to keep real-time playback; the Duration counts the frames kept.": "每隔这么多帧保留一帧。输出帧率会随之调整以保持实时播放;时长按保留的帧数计算。",
"Use the whole video: start at 0 with no Duration limit. Keeps Every nth and Frames for.": "使用整段视频:从 0 开始,不限制时长。“每隔几帧”和“帧数用于”仍然有效。",
"Play it again and again": "循环播放", "Play the clip from its start": "从头播放片段", "Play the part that comes out": "播放最终输出的部分",
"Show times in frames: source frames for Start and Ends at, clip frames for Duration.": "以帧显示时间:起点和终点用源视频帧,时长用片段帧。", "Show times in seconds.": "以秒显示时间。",
"Playback frame rate; wire Load Video's fps output to match the source. A connected video input brings its own rate and overrides this widget. Fractional rates like 23.976 and 29.97 can be typed in.": "播放帧率;把加载视频的 fps 输出连过来可与源视频一致。连接了视频输入时会使用它自带的帧率,并覆盖这个控件。可以输入 23.976、29.97 这类小数帧率。",
"Play the clip forward then backward so it loops seamlessly. Roughly doubles the frame count and the encode time; the first and last frames are not repeated at the turnaround.": "先正放再倒放,让片段无缝循环。帧数和编码时间大约翻倍;转折处首尾帧不会重复。",
"On embeds the workflow in the video file, so dropping the file back on the canvas restores the graph that made it.": "开启后会把工作流嵌入视频文件,把文件拖回画布即可还原生成它的工作流。",
"Container and codec. mp4 h264 plays everywhere; mp4 h265 halves the size at the same quality where supported; the nvenc pair encodes on an NVIDIA GPU instead of the CPU (much faster, slightly larger); webm vp9 and webm av1 suit the web and mux Opus; mov prores": "封装格式和编码。mp4 h264 到处都能播放;mp4 h265 在支持的设备上同画质体积减半;两个 nvenc 选项用 NVIDIA 显卡而不是 CPU 编码(快得多,体积略大);webm vp9 和 webm av1 适合网页并封装 Opus;mov prores",
"Encode quality: lower is better and larger. 19 is visually lossless for h264; h265 and vp9 read the same scale (vp9 tolerates a few points higher).": "编码质量:数值越小画质越好、文件越大。h264 用 19 在视觉上无损;h265 和 vp9 用同样的刻度(vp9 可以高几个点)。",
"Show the clip here while it is being made: after each step, a few of its frames play in a loop, with a Stop button. Off by default.": "生成过程中在这里显示片段:每一步之后循环播放其中几帧,并带一个停止按钮。默认关闭。",
"Stop this run now. The next run in the queue still starts.": "立即停止这次运行。队列里的下一次运行仍会开始。",
"Moves each moment onto the nearest beat of the song. Pick off to keep your own seconds.": "把每个时刻移到歌曲最近的节拍上。选“关”则保留你自己写的秒数。",
"The second of the song to start from, so the clip gets the good part.": "从歌曲的第几秒开始,让片段用上最精彩的部分。",
"This video job uses the incoming clip, so Length is not used.": "这个视频任务使用传入的片段,所以不使用“长度”。", "From the clip": "取自片段",
"Plug a picture into picture_1 to name it @1 in your lines.": "把图片接到 picture_1,就能在文字里用 @1 称呼它。",
"Plug a picture into picture_2 to name it @2 in your lines.": "把图片接到 picture_2,就能在文字里用 @2 称呼它。",
"Plug a picture into picture_3 to name it @3 in your lines.": "把图片接到 picture_3,就能在文字里用 @3 称呼它。",
"Plug a picture into picture_4 to name it @4 in your lines.": "把图片接到 picture_4,就能在文字里用 @4 称呼它。",
"Plug a video into video to copy its moves, swap the person, keep it going or give it a new voice.": "把视频接到 video,可以复制它的动作、换人、接着往下拍,或换一个新声音。",
"Turn on when a swap keeps the video's own sound. Each line is timed from that sound, and words from anyone else are left out so only the new person's mouth moves.": "换人并保留视频原声时开启。每一行按原声计时,其他人的台词会被去掉,只有新人物的嘴在动。",
"Run the workflow once and the prompt the node writes shows here. Change it to send your own.": "运行一次工作流后,节点写出的提示词会显示在这里。修改它就会发送你自己的版本。",
"The prompt the node wrote on its last run. Change it here to send your own.": "节点上次运行写出的提示词。在这里修改即可发送你自己的版本。",
"Throw your edit away and send what the Simple tab writes again.": "放弃你的修改,重新发送“简易”标签页写出的内容。",
"What H3 gets. Type here to send your own text instead of the node's.": "H3 收到的内容。在这里输入即可用你自己的文字代替节点写的。",
"What happens, one line for each moment. A blank line cuts to a new place. @1 is Picture 1. Start a line with 3s: to put it on that second.": "发生了什么,每个时刻写一行。空行表示切到新的地点。@1 是图片 1。行首写 3s: 可把它放在第 3 秒。",
"Type what happens, one line for each thing. Picture 1 is @1. A blank line cuts to a new place.\n\nSwap: leave empty, or name who goes. Optional new look on its own line: @1 looks like a woman with blonde hair and a black hoodie.": "输入发生了什么,每件事一行。图片 1 是 @1。空行表示切到新的地点。\n\n换人:留空,或写明换掉谁。新造型可单独写一行:@1 是一位金发、穿黑色连帽衫的女士。",
"Your lines, the pictures and the menus. The node writes the full prompt from them.": "你写的文字、图片和各个菜单。节点会据此写出完整提示词。",
"What you can type in the words": "文字里可以怎么写", "rain on a window": "窗上的雨声", "slow piano: music makes it louder": "舒缓钢琴:加了音乐会更响",
"upscale, face": "放大, 人脸",
"Switching a row on switches the other rows off - for alternatives such as two upscalers.": "打开一行会关掉其他行,适合在两个放大器这类互斥方案之间切换。",
"Rows gives each switch a row with its own off | on. One pill makes the switches choices in a single pill, where one is always picked.": "“逐行”让每个开关各占一行,各自有关 | 开。“单选”把这些开关合成一个选项条,始终选中其中一个。",
"Show only the labels and their switches. Double-click a label, or right-click the node, to edit again.": "只显示名称和开关。双击名称或右键节点可重新编辑。",
"Select the nodes of one part on the canvas, then press this: they get one switch": "在画布上选中某一部分的节点再按这里,它们会得到一个开关",
"Set the nodes the way this choice should be, then press this and give it a name. Do it again for each choice: the card becomes one pill, and picking one sets the nodes that way.": "先把节点调成这个选项该有的样子,再按这里并起个名字。每个选项都这样做一遍:卡片会变成一个选项条,选中某项就会把节点设成对应状态。",
"What a switched-off part does. Bypass: its nodes hand their inputs straight through, so the rest of the workflow still runs. Mute: its nodes do not run, and nor does anything that needs their output.": "关闭的部分怎么处理。绕过:节点把输入直接传出去,工作流其余部分照常运行。静音:节点不运行,依赖它们输出的节点也不运行。",
"What off means, which groups get a switch of their own, and their order": "“关”是什么意思、哪些分组有各自的开关,以及它们的顺序",
"Which groups get a switch of their own, listed under the switches you made: none, every group, the numbered ones (titles starting with a digit, like 1 · Load), or titles matching text.": "哪些分组有各自的开关,列在你创建的开关下面:无、每个分组、编号分组(标题以数字开头,如 1 · Load),或标题匹配某段文字。",
"The order of the group rows. Canvas: the way the workflow reads, column by column from the left and top to bottom within a column. Title: by title, with numbers in numeric order.": "分组行的顺序。画布:按工作流的阅读顺序,从左到右逐列,每列从上到下。标题:按标题排序,数字按数值大小排。",
"Toggle looping for this saved preview": "切换此预览的循环播放",
// ---- tooltips of the nodes the Person Swap and Pika Remix workflows use
"A sound file in ComfyUI's input folder. Use Upload to add one.": "ComfyUI input 文件夹里的声音文件。用“上传”添加新的。",
"Fill colour of the padding and rotation corners. Video outpaint models key on it: the LTX IC-LoRA paints pure black (#000000) and leaves other colours alone. Now #000000.": "扩边和旋转后空角的填充颜色。视频外扩模型会以它为依据:LTX IC-LoRA 画纯黑(#000000),其他颜色保持不动。当前为 #000000。",
"Container and codec.": "封装格式和编码。mp4 h264 到处都能播放;mp4 h265 在支持的设备上同画质体积减半;两个 nvenc 选项用 NVIDIA 显卡而不是 CPU 编码(快得多,体积略大);webm vp9 和 webm av1 适合网页并封装 Opus;mov prores 是 ProRes HQ 剪辑母版;mkv ffv1 是逐位无损,文件非常大;gif 和 webp 没有声音、无限循环,并把每一帧都放进内存,只适合短片段。",
"Feather of the mask into the kept frames, in pixels. The frames keep a hard edge against the fill whatever the feather, so a black-band outpaint still sees its bars.": "遮罩向保留画面内的羽化,单位像素。无论羽化多少,画面与填充之间都保持硬边,所以黑边外扩仍能看到黑条。",
"From the picture keeps your photo's look. The others redraw it in that style.": "“取自图片”保留你照片原本的样子,其他选项会把它重绘成对应风格。",
"How long the clip is. Plan on about one moment a second at most.": "片段有多长。大约每秒最多安排一个时刻。",
"How many times larger each side gets. 1 keeps the size and only sharpens.": "每条边放大多少倍。1 表示尺寸不变,只做锐化。",
"How the camera moves the whole way through. As typed leaves it to your words; with a video wired it shows as from the video and keeps the video's own camera.": "镜头从头到尾怎么运动。“照输入”交给你写的文字;连了视频时显示为“取自视频”,沿用视频自带的镜头。",
"Keeps each frame's colours the same as your video. Leave it on.": "让每一帧的颜色与你的视频保持一致。建议保持开启。",
"Saved under the output folder; subfolders are created automatically.": "保存在 output 文件夹下;子文件夹会自动创建。",
"The FlashVSR model file, from ComfyUI/models/diffusion_models.": "FlashVSR 模型文件,位于 ComfyUI/models/diffusion_models。",
"The integer to output.": "要输出的整数。",
"The language of the words in quotes.": "引号里台词所用的语言。",
"The music, like a slow lo-fi beat. A clip with music comes out louder. Empty means no music.": "音乐,比如舒缓的 lo-fi 节奏。带音乐的片段声音会更响。留空表示没有音乐。",
"What you hear the whole way through, like rain on a window. Leave it empty for none.": "从头到尾都能听到的声音,比如窗上的雨声。留空表示没有。",
"Play": "播放",
"Load image": "加载图片",
"Load video": "加载视频",
"One at a time": "一次一个",
"applies to the next ratio": "应用于下一个比例",
"rain on a window": "窗上的雨声",
// ---- card tooltips and placeholders
"Size of the finished picture. 0 keeps the picture's own size.": "成品图片的大小。0 表示保持图片原有大小。",
"Used only while Fill holes is on.": "仅在“填补孔洞”开启时使用。",
"the folder itself": "文件夹本身",
"Choose a folder inside ComfyUI's input or output folder.": "选择 ComfyUI 的 input 或 output 文件夹里的一个文件夹。",
"Prompt, caption, or shared text": "提示词、字幕或共用文字",
"type here": "在此输入",
"One line for each run": "每次运行写一行",
"A woman in a {red|blue|green} {sweater|jacket}. One choice is picked from each set.": "一位穿着{红色|蓝色|绿色}{毛衣|夹克}的女士。每组花括号里会随机选一项。",
"Prompt - describe the whole finished canvas": "提示词:描述整个成品画面",
"Negative prompt (ignored at CFG 1)": "负面提示词(CFG 为 1 时忽略)",
"On, the vision tower also sees the reference images. Use on for AnyPaint with a whole-canvas reference; use off for Registered Outpaint with a source-rectangle reference. Match the adapter's conditioning contract.": "开启时,视觉模块也会看到参考图。AnyPaint 配整张画布的参考图时开启;Registered Outpaint 配源矩形参考图时关闭。要与适配器的条件约定保持一致。",
"0 keeps the source width; set one side only to keep the aspect.": "0 表示保持源宽度;只设一边即可保持宽高比。",
"0 keeps the source height; set one side only to keep the aspect.": "0 表示保持源高度;只设一边即可保持宽高比。",
"Lock the untouched parts; step aside when the whole picture changes": "锁住没改动的部分;整张图都变了就不介入",
"Lock even when the whole picture changes": "即使整张图都变了也锁定",
"Do nothing": "什么都不做",
"A separate horizontal and vertical zoom plus a shift: how Qwen edits drift": "水平和垂直方向各自缩放,再加平移:Qwen 编辑后画面通常就是这样偏移的",
"Also a slight rotation or shear": "另外还修正轻微的旋转或倾斜",
"Stretch the nearest edge pixels": "拉伸最近的边缘像素",
"The original's pixels": "使用原图的像素",
"Flat #808080, for an inpaint pass": "纯 #808080,用于重绘",
"resize b to a's size": "把 b 缩放到 a 的尺寸",
"resize a to b's size": "把 a 缩放到 b 的尺寸",
// ---- panels, menus and lists of the same nodes
"Absorb chain LoRAs": "并入串联的 LoRA",
"Add your own trigger word...": "添加自己的触发词…",
"Adds 1 after each run. Tap for -1.": "每次运行后加 1。点一下改为减 1。",
"Advisory range for this LoRA; out-of-range strengths tint orange on the row.": "这个 LoRA 的建议范围;超出范围的强度会让该行显示为橙色。",
"Asks civitai.com about this one file, from this browser.": "由此浏览器向 civitai.com 查询这一个文件。",
"Audio preview unavailable ⓘ": "无法预览音频 ⓘ",
"Audio preview unavailable. Show details.": "无法预览音频。查看详情。",
"Back to defaults for this node type": "恢复此节点类型的默认值",
"Changed from the suggested value": "与建议值不同",
"Choice": "选项",
"Choose a source to set the clip": "先选择素材,再设置片段",
"Choose a source to begin": "选择素材后开始",
"Civitai lookup button": "Civitai 查询按钮",
"Civitai lookup failed": "Civitai 查询失败",
"Civitai picture": "Civitai 图片",
"Close without saving: puts back everything as it was when the editor opened (Esc)": "不保存关闭:恢复为打开编辑器时的样子(Esc)",
"Crop image — right-click to copy": "裁剪后的图片,右键可复制",
"Default strength": "默认强度",
"Drag to move the whole group": "拖动可移动整个分组",
"Drag to reorder": "拖动可调整顺序",
"Each line becomes a moment. A blank line between lines is a cut.": "每一行是一个时刻,两行之间的空行表示切换场景。",
"Enable or disable this LoRA": "启用或停用这个 LoRA",
"Fetching...": "获取中…",
"Group name": "分组名称",
"Held": "已锁定",
"Hide file extension": "隐藏文件扩展名",
"Hide folder names": "隐藏文件夹名",
"Keeps this seed for every run. Tap for +1.": "每次运行都用这个种子。点一下改为加 1。",
"Loading…": "加载中…",
"Long names": "长名称",
"Mask feather in pixels.": "遮罩羽化,单位像素。",
"More ratios": "更多比例",
"Name this stack; saving over an existing name replaces it": "给这组 LoRA 起个名字;用已有名字保存会覆盖它",
"Not found on Civitai": "Civitai 上没有找到",
"Output budget in megapixels (x 1024x1024).": "输出像素预算,单位百万像素(x 1024x1024)。",
"Playhead frame / last frame": "当前帧 / 最后一帧",
"Preview thumbnails": "预览缩略图",
"Preview, base model, and trigger words": "预览图、基础模型和触发词",
"Put this seed back and pin it": "恢复这个种子并固定",
"Remove all padding.": "清除所有扩边。",
"Rotation in degrees: 1° per step, Shift for 0.1°. The crop stays over the same part of the picture.": "旋转角度:每步 1°,按住 Shift 为 0.1°。裁剪框保持在画面的同一部分上。",
"Rounds each resized side to a multiple of this (32 for LTX and Wan).": "把缩放后的每条边取整为此数的倍数(LTX 和 Wan 用 32)。",
"Rows on the box": "框上的行",
"Save current as...": "另存当前为…",
"Scrub strength on the name": "在名称上拖动调节强度",
"Search LoRAs": "搜索 LoRA",
"Search LoRAs...": "搜索 LoRA…",
"Seed settings": "种子设置",
"Select every node this switch turns off and on": "选中此开关控制的所有节点",
"Select nodes or groups on the canvas first, then add them to this switch": "先在画布上选中节点或分组,再把它们加入这个开关",
"Select nodes that run only while this is off, then take them off that side. They stay as they are.": "选中只在此项关闭时才运行的节点,再把它们放到“关”的一侧。节点本身保持原样。",
"Select nodes this switch holds first, then take them out of it": "先选中此开关管理的节点,再把它们移出",
"Select the nodes only this choice needs. They are switched off while another choice is picked.": "选中只有这个选项才需要的节点。选了其他选项时,它们会被关闭。",
"Separate model / CLIP strength": "分开设置模型 / CLIP 强度",
"Set the nodes the way this choice should be, then pick this": "先把节点调成这个选项该有的样子,再选中它",
"Show the mask on the picture": "在图片上显示遮罩",
"Stop on missing LoRA": "缺少 LoRA 时停止",
"Strength bars": "强度条",
"Strength step": "强度步长",
"Linked strength wires": "强度连线显示", "shown": "显示", "on hover": "悬停时显示", "hidden": "隐藏",
"Unlink strength": "断开强度连线", "link": "连线",
"Takes 1 off after each run. Tap for Random.": "每次运行后减 1。点一下改为随机。",
"The words come from the wire.": "文字来自连线。",
"Tick to add with others": "勾选后与其他一起添加",
"Toggle this trigger word into the row's output": "把这个触发词加入或移出该行的输出",
"Trigger word separator": "触发词分隔符",
"Turn this group on or off. Each LoRA in it keeps its own switch.": "开启或关闭这个分组。组里的每个 LoRA 仍有各自的开关。",
"Untick every file": "取消勾选所有文件",
"seeds this node ran with": "此节点用过的历史种子",
"the last run delivered an empty string": "上次运行传来的是空字符串",
"Start and Ends at are places in the source video. Duration counts the frames the clip sends on, at the output rate.": "起点和终点是源视频里的位置。时长是片段送出的帧数,按输出帧率计算。",
"The frame this node outputs (frame_index).": "此节点输出的帧(frame_index)。",
"Pick a color": "选择颜色",
"Show the advanced mask controls": "显示高级遮罩控制",
"Reset rotation, crop, padding, fill, feather and Align. Keep the source, current frame, trim window, fixed length and picture.": "重置旋转、裁剪、扩边、填充、羽化和对齐。素材、当前帧、截取范围、固定长度和图片保持不变。",
"Up/Down chooses a row, Space toggles it, and Left/Right changes strength.": "上下键选择一行,空格切换开关,左右键调整强度。",
"Tint the paste mask the stitcher will use - the same mask math as the backend, at preview resolution.": "给拼回时使用的贴回遮罩上色,计算方式与后端一致,只是分辨率为预览分辨率。",
"Ramp where generated pixels fade over the source, in pixels of the output. Separate from the padding feather.": "生成的像素渐隐到原图上的过渡宽度,单位为输出像素。与扩边羽化相互独立。",
"Your own ratios from ausboss_presets.json. Picking one works like a ratio button.": "来自 ausboss_presets.json 的自定义比例。选中它的效果和点比例按钮一样。",
"Choose or upload an image": "选择或上传图片",
"Preview could not load this image": "预览无法加载这张图片",
};
// Strings that deliberately stay English on a Chinese face: names, symbols
// and technical terms with no everyday Chinese form.
export const STAYS_ENGLISH = new Set([
"W", "H", "FPS", "CFG", "LoRA", "VRAM", "Seed", "H3",
"lab", "rgb", "mkl", "bicubic", "bilinear", "lanczos", "nearest", "area",
"gif", "webp", "mp4 h264", "mp4 h265", "mp4 h264 nvenc", "mp4 h265 nvenc", "mov prores", "mkv ffv1", "webm vp9", "webm av1",
"big-lama.pt", "loras", "script", "video", "flashvsr_v1.1_fp16.safetensors", "f(a, b, c)", "a + b",
]);
// The hint js/shared/scrub_input.mjs adds to every number box's tooltip.
export const SCRUB_HINT_EN = "Drag to scrub, click to type a number or a sum (1024*1.5), arrows to step; Shift = fine.";
export const SCRUB_HINT_ZH = "拖动调节,点击输入数字或算式(如 1024*1.5),方向键步进;按住 Shift 精细调节。";
// A few strings carry a number or a name; the number stays and the words around it change.
export const PATTERNS = [
[/^The limits of what this is wired to: (.*)\.$/, (m, names) => `它所连接对象的取值范围:${names}。`],
[/^Set by "(.*)"\. Click to show it\. Right-click the row to unlink\.$/, (m, name) => `由“${name}”设置。点击可定位到它。右键该行可断开连线。`],
[/^Source · feather (\d+) px · Fill (#[0-9a-fA-F]{6})$/, (m, f, c) => `素材 · 羽化 ${f} px · 填充 ${c}`],
[/^Source · Fill (#[0-9a-fA-F]{6})$/, (m, c) => `素材 · 填充 ${c}`],
[/^(\d+):(\d+): reshape to this ratio\. The flip button on the left sets the orientation\.$/, (m, a, b) => `${a}:${b}:重塑为此比例。左侧的翻转按钮用来切换横竖方向。`],
];
+1 -1
View File
@@ -9,7 +9,7 @@ import { app } from "../../../scripts/app.js";
// Must match `version` in pyproject.toml — scripts/release_preflight.py
// enforces it. The backend serves its copy at /ausboss/pack_version; a
// mismatch means the browser cached JavaScript from an older install.
export const AUSBOSS_JS_VERSION = "2.26.6";
export const AUSBOSS_JS_VERSION = "2.27.0";
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
export const BRAND_DARK = "#007f78";
+42
View File
@@ -48,3 +48,45 @@ export function moveHighlight(index, delta, length) {
if (index < 0 || index >= length) return delta > 0 ? 0 : length - 1;
return Math.max(0, Math.min(length - 1, index + delta));
}
// Keep every file in memory but only present one folder at a time; searching
// is global, like ComfyUI's default file selector. Values remain unchanged so
// ComfyUI's image widget still receives the full original filename.
export function browseMediaRows(options, query, directory = [], bare = (value) => value) {
if (String(query ?? "").trim()) {
return filterMedia(options, query).map((value) => ({ kind: "file", value }));
}
const folders = new Map();
const files = [];
for (const value of options) {
const parts = bare(value).replace(/\\/g, "/").split("/").filter(Boolean);
if (!directory.every((part, i) => parts[i] === part)) continue;
const name = parts[directory.length];
if (!name) continue;
if (parts.length > directory.length + 1) {
if (!folders.has(name)) folders.set(name, { kind: "folder", label: name, directory: [...directory, name] });
} else {
files.push({ kind: "file", value });
}
}
return [
...(directory.length ? [{ kind: "back", label: "..", directory: directory.slice(0, -1) }] : []),
...folders.values(),
...files,
];
}
// The folder a picked file sits in, as the parts browseMediaRows takes, so
// the picker opens where the current pick is. A top-level file gives [].
export function mediaFolderOf(value, bare = (v) => v) {
const parts = bare(String(value ?? "")).replace(/\\/g, "/").split("/").filter(Boolean);
return parts.slice(0, -1);
}
// Virtual scrolling uses a fixed row height. The DOM only contains this range
// while the scroll container's spacer retains the height of the entire list.
export function visibleMediaRange(total, scrollTop, height, rowHeight, overscan) {
const first = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
const last = Math.min(total, Math.ceil((scrollTop + height) / rowHeight) + overscan);
return { first, last };
}
+129 -40
View File
@@ -11,11 +11,13 @@
// Pure decisions live in media_list.mjs for node:test; this file is the DOM.
import { BRAND } from "./index.mjs";
import { THEME } from "./theme.mjs";
import { isAppShortcut, keepKeyInField } from "./canvas_passthrough.mjs";
import { filterMedia, mediaLabel, moveHighlight } from "./media_list.mjs";
import { browseMediaRows, mediaFolderOf, mediaLabel, moveHighlight, visibleMediaRange } from "./media_list.mjs";
const CSS_ID = "ausboss-media-picker-css";
const LIST_CAP = 400; // a crowded input folder shows this many; typing narrows it
const ROW_HEIGHT = 26; // fixed-height rows for virtual scrolling
const OVERSCAN = 8; // rows above and below the scroll window
const PREVIEW_DELAY_MS = 70; // skimming down the list does not start a load per row
const MONO = 'ui-monospace,"SF Mono",Menlo,Consolas,monospace';
@@ -35,6 +37,12 @@ function ensureCss() {
.ausboss-media-filter{box-sizing:border-box;width:100%;height:28px;padding:0 8px;border:1px solid #2a3437;border-radius:6px;outline:0;background:#0b0f10;color:#eef7f6;font:12px ${MONO}}
.ausboss-media-filter:focus{border-color:${BRAND}}
.ausboss-media-list{max-height:min(320px,50vh);overflow:auto;overscroll-behavior:contain}
.ausboss-media-space{position:relative;width:100%}
.ausboss-media-space .ausboss-media-item{position:absolute;left:0;right:0;box-sizing:border-box;height:26px;align-items:center}
.ausboss-media-path{padding:0 5px 2px;min-height:14px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#6f8886;font:10px ui-monospace,monospace}
.ausboss-media-navigation{font-weight:600}
.ausboss-media-folder-icon{flex:none;display:flex;align-items:center;width:20px;color:${THEME.faint}}
.ausboss-media-folder-icon svg{width:12px;height:12px}
.ausboss-media-item{display:flex;min-width:0;padding:5px 8px;border-radius:5px;cursor:pointer;white-space:nowrap;font:12px ${MONO}}
.ausboss-media-item.hot{background:#2c3238;color:#fff}
.ausboss-media-item.current .ausboss-media-name{color:${BRAND}}
@@ -50,6 +58,12 @@ function ensureCss() {
document.head.appendChild(style);
}
// Folder and "up one folder" marks for the list, drawn in the text colour.
const ICONS = {
folder: '<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1 3a1 1 0 0 1 1-1h2.6l1.2 1.2H10a1 1 0 0 1 1 1V9a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1z" fill="none" stroke="currentColor" stroke-width="1.2"/></svg>',
back: '<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M6 10V2.5M2.5 6 6 2.5 9.5 6" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>',
};
function el(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
@@ -114,7 +128,8 @@ export function createMediaPicker({ kind = "image", className = "", placeholder,
filter.setAttribute("aria-label", `Filter ${noun}s`);
const list = el("div", "ausboss-media-list");
list.setAttribute("role", "listbox");
column.append(filter, list);
const pathBar = el("div", "ausboss-media-path");
column.append(filter, pathBar, list);
const pane = el("div", "ausboss-media-pane");
const stage = el("div", "ausboss-media-stage");
const caption = el("div", "ausboss-media-caption");
@@ -122,7 +137,10 @@ export function createMediaPicker({ kind = "image", className = "", placeholder,
menu.append(column, pane);
let shown = [];
const items = [];
// The folder on show, only UI state; the widget keeps the full file name.
// It opens where the current pick sits.
let directory = all.includes(current) ? mediaFolderOf(current, bare) : [];
const items = new Map();
let highlight = -1;
let timer = null;
let serial = 0;
@@ -164,51 +182,122 @@ export function createMediaPicker({ kind = "image", className = "", placeholder,
}
};
const setHighlight = (index, scroll) => {
if (index === highlight) return;
items[highlight]?.classList.remove("hot");
highlight = index;
clearTimeout(timer);
const item = items[index];
if (!item) {
showPreview(null);
return;
}
item.classList.add("hot");
if (scroll) item.scrollIntoView({ block: "nearest" });
const value = shown[index];
timer = setTimeout(() => showPreview(value), PREVIEW_DELAY_MS);
// ComfyUI's own select widgets use a virtualizer for long lists. Do the
// same here with a fixed row height, retaining AusBoss's own preview and
// widget-commit logic. All filenames stay in `shown`; only visible DOM
// rows (plus a small buffer) are created.
let viewport = null;
let visibleRange = "";
const navigate = (entry) => {
directory = entry.directory;
filter.value = "";
render(true);
filter.focus();
};
const activate = (entry) => {
if (!entry) return;
if (entry.kind === "file") choose(entry.value);
else navigate(entry);
};
const render = () => {
shown = filterMedia(all, filter.value);
list.replaceChildren();
items.length = 0;
highlight = -1;
for (const value of shown.slice(0, LIST_CAP)) {
const { folder: under, name } = mediaLabel(bare(value));
const renderViewport = () => {
if (!viewport) return;
const visibleHeight = list.clientHeight || 320;
const { first, last } = visibleMediaRange(shown.length, list.scrollTop, visibleHeight, ROW_HEIGHT, OVERSCAN);
const range = `${first}:${last}`;
if (range === visibleRange) return;
visibleRange = range;
const fragment = document.createDocumentFragment();
const searching = Boolean(filter.value.trim());
items.clear();
for (let index = first; index < last; index++) {
const entry = shown[index];
const value = entry.value;
const { folder: under, name } = entry.kind === "file"
? mediaLabel(bare(value)) : { folder: "", name: entry.label };
const item = el("div", "ausboss-media-item");
item.setAttribute("role", "option");
item.title = bare(value);
if (value === current) {
item.setAttribute("aria-posinset", String(index + 1));
item.setAttribute("aria-setsize", String(shown.length));
item.title = entry.kind === "file" ? bare(value) :
entry.kind === "back" ? "Go to parent folder" : `Open folder: ${entry.label}`;
item.style.top = `${index * ROW_HEIGHT}px`;
if (index === highlight) item.classList.add("hot");
if (entry.kind === "file" && value === current) {
item.classList.add("current");
item.setAttribute("aria-selected", "true");
}
if (under) item.append(el("span", "ausboss-media-folder", under));
item.append(el("span", "ausboss-media-name", name));
const index = items.length;
if (entry.kind !== "file") {
item.classList.add("ausboss-media-navigation");
const icon = el("span", "ausboss-media-folder-icon");
icon.innerHTML = ICONS[entry.kind === "back" ? "back" : "folder"];
item.append(icon);
}
// Inside a folder the path bar already names it; a search shows it.
if (under && searching) item.append(el("span", "ausboss-media-folder", under));
item.append(el("span", "ausboss-media-name", entry.kind === "folder" ? `${name}/` : name));
item.addEventListener("mousemove", () => setHighlight(index, false));
item.addEventListener("click", () => choose(value));
list.append(item);
items.push(item);
item.addEventListener("click", () => activate(entry));
fragment.append(item);
items.set(index, item);
}
if (shown.length > LIST_CAP) list.append(el("div", "ausboss-media-more", `${shown.length - LIST_CAP} more · type to narrow`));
if (!shown.length) list.append(el("div", "ausboss-media-more", all.length ? "No matches" : emptyNote || `Upload ${noun === "video" ? "a video" : "an image"} and it shows up here`));
const start = shown.indexOf(current);
setHighlight(start >= 0 && start < items.length ? start : items.length ? 0 : -1, true);
if (!items.length) showPreview(null);
viewport.replaceChildren(fragment);
};
const setHighlight = (index, scroll) => {
if (scroll && index >= 0 && index < shown.length) {
const top = index * ROW_HEIGHT;
const height = list.clientHeight || 320;
if (top < list.scrollTop) list.scrollTop = top;
else if (top + ROW_HEIGHT > list.scrollTop + height) {
list.scrollTop = Math.max(0, top + ROW_HEIGHT - height);
}
renderViewport();
}
if (index === highlight) return;
items.get(highlight)?.classList.remove("hot");
highlight = index;
clearTimeout(timer);
const item = items.get(index);
if (!item) {
const entry = index >= 0 ? shown[index] : null;
showPreview(entry?.kind === "file" ? entry.value : null);
return;
}
item.classList.add("hot");
const entry = shown[index];
timer = setTimeout(() => showPreview(entry?.kind === "file" ? entry.value : null), PREVIEW_DELAY_MS);
};
const render = (startAtTop = false) => {
shown = browseMediaRows(all, filter.value, directory, bare);
pathBar.textContent = filter.value.trim() ? "Search all folders" :
[folder.charAt(0).toUpperCase() + folder.slice(1), ...directory].join(" / ");
list.replaceChildren();
list.scrollTop = 0;
items.clear();
highlight = -1;
clearTimeout(timer);
viewport = null;
visibleRange = "";
if (!shown.length) {
list.append(el("div", "ausboss-media-more", all.length ? "No matches" : emptyNote || `Upload ${noun === "video" ? "a video" : "an image"} and it shows up here`));
showPreview(null);
return;
}
viewport = el("div", "ausboss-media-space");
viewport.style.height = `${shown.length * ROW_HEIGHT}px`;
list.append(viewport);
// Preserve AusBoss's original behaviour: bring the selected file into
// view when opening or filtering, otherwise start at the first match.
const selected = shown.findIndex((entry) => entry.kind === "file" && entry.value === current);
const start = startAtTop === true ? 0 : selected >= 0 ? selected : 0;
renderViewport();
setHighlight(start, true);
};
list.addEventListener("scroll", renderViewport, { passive: true });
const abort = new AbortController();
const close = () => {
clearTimeout(timer);
@@ -232,10 +321,10 @@ export function createMediaPicker({ kind = "image", className = "", placeholder,
const step = { ArrowDown: 1, ArrowUp: -1, PageDown: 8, PageUp: -8 }[event.key];
if (step) {
event.preventDefault();
setHighlight(moveHighlight(highlight, step, items.length), true);
setHighlight(moveHighlight(highlight, step, shown.length), true);
} else if (event.key === "Enter") {
event.preventDefault();
if (highlight >= 0) choose(shown[highlight]);
if (highlight >= 0) activate(shown[highlight]);
} else if (event.key === "Escape") {
event.preventDefault();
close();
+4 -3
View File
@@ -10,6 +10,7 @@
// writePad(side, value) write one raw pad widget (with callbacks)
// onGestureEnd() called once per completed drag
import { t } from "./i18n.mjs";
import { canvasLocalPoint } from "./transform_geometry.mjs";
import {
edgeCursor,
@@ -86,7 +87,7 @@ function drawPill(ctx, text, cx, cy, accent = false) {
ctx.fillStyle = accent ? "#8de0da" : "#e7f4f2";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, cx, cy + 0.5);
ctx.fillText(t(text), cx, cy + 0.5);
ctx.restore();
return width;
}
@@ -99,7 +100,7 @@ function drawBandText(ctx, text, cx, cy) {
ctx.shadowColor = "rgba(0,0,0,0.9)";
ctx.shadowBlur = 3;
ctx.fillStyle = "#ffe2c2";
ctx.fillText(text, cx, cy);
ctx.fillText(t(text), cx, cy);
ctx.restore();
}
@@ -247,7 +248,7 @@ export function createPadStage(canvas, options) {
ctx.shadowColor = "rgba(0,0,0,0.85)";
ctx.shadowBlur = 4;
ctx.fillStyle = "#78908e";
ctx.fillText(source.emptyText, w / 2, h / 2);
ctx.fillText(t(source.emptyText), w / 2, h / 2);
ctx.restore();
}
+136
View File
@@ -0,0 +1,136 @@
// A card row of shape chips for a width and height pair, borrowed from Latent
// Size: a button that turns the shape on its side, then one chip per ratio.
// A chip gives a size of about one megapixel in that shape (Latent Size's
// default), divisible by the snap step, so clicking around never drifts. The width and height widgets stay the source of
// truth: a chip only writes their values, and the card's W x H row shows them.
import { app } from "../../../scripts/app.js";
import { BRAND, notifyAusbossChange } from "./index.mjs";
import { applyRatioAtBudget, chipMatch, fitRectInBox, orientRatio, parseRail } from "./resolution_math.mjs";
// The rail as typed ("21:9", not the reduced "7:3"), for the chip labels.
const typedRail = (rail) => String(rail).split(",").map((token) => token.trim().match(/^(\d{1,3})\s*[:x]\s*(\d{1,3})$/i)).filter(Boolean).map((m) => [Number(m[1]), Number(m[2])]);
import { commitWidgetValue } from "./widget_card_math.mjs";
export const VIEWER_RAIL = "1:1, 4:3, 3:2, 16:9, 21:9";
const CSS_ID = "ausboss-ratio-chips-css";
// Which way a square size turns when a chip is clicked; kept on the node.
const PORTRAIT_PROPERTY = "ausboss_ratio_portrait";
function ensureCss() {
if (document.getElementById(CSS_ID)) return;
const style = document.createElement("style");
style.id = CSS_ID;
style.textContent = `
.ausboss-ratio-row{display:flex;gap:5px;height:100%;min-width:0;align-items:stretch}
.ausboss-ratio-row button{display:flex;align-items:center;justify-content:center;gap:5px;min-width:0;padding:0 3px;box-sizing:border-box;border-radius:5px;cursor:pointer;font:500 10.5px ui-monospace,SFMono-Regular,Menlo,monospace;background:#1e2020;border:1px solid #313434;color:#9aa0a0;white-space:nowrap;overflow:hidden;transition:border-color .12s,color .12s}
.ausboss-ratio-row button:hover:not(:disabled){border-color:${BRAND};color:${BRAND}}
.ausboss-ratio-row button:disabled{opacity:.4;cursor:default}
.ausboss-ratio-row .flip{flex:none;width:32px;color:#c8cccc}
.ausboss-ratio-row .chip{flex:1 1 0}
.ausboss-ratio-row .chip.near{border:1px dashed #3c6663;color:#9fc4c1}
.ausboss-ratio-row .chip.exact{background:rgba(0,180,170,.16);border:1px solid ${BRAND};color:#7fe9e2}
.ausboss-ratio-row .glyph{display:inline-block;flex:none;border:1.4px solid currentColor;border-radius:1.5px;opacity:.75}
.ausboss-ratio-row .flip .glyph{border-width:1.5px;border-radius:2px;opacity:1}
`;
document.head.append(style);
}
const widgetOf = (node, name) => node.widgets?.find((widget) => widget.name === name) ?? null;
const linked = (node, name) => {
const slot = node.inputs?.find((input) => input?.widget?.name === name || input?.name === name);
return slot?.link !== null && slot?.link !== undefined;
};
const clampTo = (widget, value) => {
const min = Number(widget?.options?.min ?? 1), max = Number(widget?.options?.max ?? 8192);
return Math.min(max, Math.max(min, Math.round(value)));
};
// A card row: { panel: ratioChips(), height: 28 }.
export function ratioChips({ rail = VIEWER_RAIL, snap = 16, width = "width", height = "height" } = {}) {
const ratios = parseRail(rail);
const typed = typedRail(rail);
return (node) => {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-ratio-row";
const flip = document.createElement("button");
flip.type = "button";
flip.className = "flip";
const flipGlyph = document.createElement("span");
flipGlyph.className = "glyph";
flip.append(flipGlyph);
element.append(flip);
const chips = ratios.map((ratio, index) => {
const button = document.createElement("button");
button.type = "button";
button.className = "chip";
const glyph = document.createElement("span");
glyph.className = "glyph";
const label = document.createElement("span");
button.append(glyph, label);
element.append(button);
const [a, b] = typed[index] ?? [ratio.x, ratio.y];
return { ratio, button, glyph, label, long: Math.max(a, b), short: Math.min(a, b) };
});
const size = () => ({ w: Number(widgetOf(node, width)?.value) || 1, h: Number(widgetOf(node, height)?.value) || 1 });
const portrait = () => {
const { w, h } = size();
return w === h ? Boolean(node.properties?.[PORTRAIT_PROPERTY]) : h > w;
};
const commit = (w, h) => {
const wWidget = widgetOf(node, width), hWidget = widgetOf(node, height);
if (!wWidget || !hWidget) return;
// Height first, so the width's callback sees the new height: the 3D
// viewer redraws its frame from each callback with the other value.
commitWidgetValue(node, hWidget, clampTo(hWidget, h), app.canvas);
commitWidgetValue(node, wWidget, clampTo(wWidget, w), app.canvas);
node.setDirtyCanvas?.(true, true);
notifyAusbossChange();
// The card's W x H row shows the new numbers; its refresh syncs this row too.
if (node.__ausbossCard?.refresh) node.__ausbossCard.refresh();
else sync();
};
flip.addEventListener("click", () => {
const { w, h } = size();
if (w === h) {
node.properties ??= {};
node.properties[PORTRAIT_PROPERTY] = !portrait();
sync();
} else commit(h, w);
});
for (const { ratio, button } of chips) {
button.addEventListener("click", () => {
const next = applyRatioAtBudget(1024, 1024, ratio, snap, portrait());
commit(next.width, next.height);
});
}
const sync = () => {
const { w, h } = size();
const tall = portrait();
const locked = linked(node, width) || linked(node, height);
const turned = fitRectInBox(tall ? 3 : 4, tall ? 4 : 3, 14, 14);
flipGlyph.style.width = `${turned.w.toFixed(1)}px`;
flipGlyph.style.height = `${turned.h.toFixed(1)}px`;
flip.disabled = locked;
flip.title = locked ? "The size comes from a link." : `Turn the shape to ${tall ? "landscape" : "portrait"}.`;
for (const { ratio, button, glyph, label, long, short } of chips) {
const oriented = orientRatio(ratio, tall);
const fitted = fitRectInBox(oriented.x, oriented.y, 14, 14);
glyph.style.width = `${fitted.w.toFixed(1)}px`;
glyph.style.height = `${fitted.h.toFixed(1)}px`;
label.textContent = tall ? `${short}:${long}` : `${long}:${short}`;
const match = chipMatch(w, h, oriented);
const state = match && !match.flipped ? match.state : null;
button.classList.toggle("exact", state === "exact");
button.classList.toggle("near", state === "near");
button.setAttribute("aria-pressed", String(state === "exact"));
button.disabled = locked;
button.title = locked ? "The size comes from a link." : `${label.textContent}: about one megapixel in this shape.`;
}
};
return { element, sync };
};
}
+56 -1
View File
@@ -7,6 +7,10 @@
// mountStepOverlay lays the picture, a progress line and a short caption
// over a node's own picture box, and stopStepRun is the Stop button.
//
// For a clip, the server also sends about one frame per second of it after
// each step (FRAMES_EVENT), and the overlay plays them in a loop at the
// clip's own pace instead of the first frame alone.
//
// Runs queued from another workflow tab are left to that tab.
import { api } from "../../../scripts/api.js";
@@ -22,6 +26,7 @@ import {
consumersOf,
drawsTiles,
feedsInto,
frameMs,
nextRunState,
resultRank,
stepFraction,
@@ -30,6 +35,8 @@ import {
} from "./step_preview_math.mjs";
const CSS_ID = "ausboss-step-preview-css";
// The server's message with a clip's frames (nodes/_step_preview_helpers.py).
const FRAMES_EVENT = "ausboss.step_frames";
// How long a replaced picture's object URL lives on, so a face that is
// still swapping to the new one never shows a broken picture.
const URL_GRACE_MS = 2000;
@@ -105,10 +112,22 @@ function wire() {
type: "picture",
promptId: detail.jobId ?? null,
maker,
real: detail.nodeId ?? null,
url: URL.createObjectURL(detail.blob),
tile: drawsTiles(nodeType(nodeByExecutionId(rootGraph(), maker))),
});
});
// A clip's frames for the step picture that follows them.
on(FRAMES_EVENT, (detail) => {
if (isForeignRun(detail?.prompt_id)) return;
apply({
type: "frames",
promptId: detail?.prompt_id ?? null,
maker: detail?.node === undefined || detail?.node === null ? null : String(detail.node),
list: detail?.frames,
seconds: detail?.seconds,
});
});
// The tiles of a tiled upscale run between its split and its stitch.
on("executing", (detail) => {
const promptId = typeof detail === "object" ? detail?.prompt_id : undefined;
@@ -245,6 +264,35 @@ export function mountStepOverlay(stage) {
root.append(img, line, chip);
stage.append(root);
let shown = false;
// The moving picture: the frames playing, which one is up, and the timer.
let playing = null;
let frame = 0;
let timer = null;
const stopPlaying = () => {
if (timer) clearInterval(timer);
timer = null;
playing = null;
};
const tick = () => {
// A face taken off the page takes its timer with it.
if (!root.isConnected || !playing) return stopPlaying();
frame = (frame + 1) % playing.list.length;
img.src = playing.list[frame];
};
const play = (frames) => {
const ms = frameMs(frames);
const restart = !timer || frameMs(playing) !== ms;
// The frames of the next step pick up where the loop is.
if (playing !== frames) {
frame %= frames.list.length;
playing = frames;
img.src = frames.list[frame];
}
if (restart) {
if (timer) clearInterval(timer);
timer = setInterval(tick, ms);
}
};
return {
root,
get shown() {
@@ -255,7 +303,12 @@ export function mountStepOverlay(stage) {
show(current, { saves = false, result = false } = {}) {
const url = (result && current?.result) || current?.url;
if (!url) return this.hide();
if (img.getAttribute("src") !== url) img.src = url;
const frames = !(result && current?.result) && current?.frames?.list?.length > 1 ? current.frames : null;
if (frames) play(frames);
else {
stopPlaying();
if (img.getAttribute("src") !== url) img.src = url;
}
const stopped = current.status === "stopped";
root.classList.toggle("stopped", stopped);
line.style.width = `${Math.round(stepFraction(current) * 100)}%`;
@@ -266,6 +319,8 @@ export function mountStepOverlay(stage) {
return true;
},
hide() {
stopPlaying();
frame = 0;
root.classList.remove("on", "stopped");
stage.classList.remove("ausboss-steps-showing");
img.removeAttribute("src");
+28 -1
View File
@@ -27,6 +27,9 @@ export const IDLE = Object.freeze({
tiling: false,
tilePass: false,
whole: false,
// A clip's frames at this step, about one per second of the clip, so the
// picture can move: { maker, list: [url, ...], seconds } or null.
frames: null,
});
const sameId = (a, b) => a !== null && a !== undefined && b !== null && b !== undefined && String(a) === String(b);
@@ -39,12 +42,16 @@ const sameId = (a, b) => a !== null && a !== undefined && b !== null && b !== un
// { type: "tiles", promptId, on } a tiled upscale split (on) or
// stitched (off) the picture
// { type: "progress", promptId, node, value, max }
// { type: "frames", promptId, maker, list, seconds } a clip's frames for the
// step picture that follows
// { type: "result", promptId, url, rank } a node of the run showed a picture
// { type: "end", promptId, kind } "success" | "interrupted" | "error"
// A step's picture arrives just before its progress report, so a picture
// from a new node starts that node's count at nothing until the report.
// A tile's picture is counted but never replaces a whole one: a tile alone
// looks like a zoomed-in crop of the picture.
// looks like a zoomed-in crop of the picture. A clip's frames arrive just
// before its step picture, and stay with the pictures of the node that
// made them.
export function nextRunState(state, event) {
const run = state ?? IDLE;
switch (event?.type) {
@@ -59,6 +66,7 @@ export function nextRunState(state, event) {
const sameMaker = !otherRun && sameId(base.maker, event.maker);
const tile = Boolean(base.tiling || event.tile);
const keep = tile && Boolean(base.url) && base.whole;
const frames = base.frames && sameId(base.frames.maker, event.real ?? event.maker) ? base.frames : null;
return {
...base,
maker: event.maker ?? null,
@@ -67,11 +75,20 @@ export function nextRunState(state, event) {
tilePass: tile,
value: sameMaker ? base.value : 0,
max: sameMaker ? base.max : 0,
frames: keep ? base.frames : frames,
// A new step means the picture is being made again (an upscale pass).
result: null,
resultRank: -1,
};
}
case "frames": {
if (run.status !== "running") return run;
if (event.promptId && run.promptId && !sameId(event.promptId, run.promptId)) return run;
const list = Array.isArray(event.list) ? event.list.filter((url) => typeof url === "string" && url) : [];
const seconds = Number(event.seconds);
if (list.length < 2) return run.frames ? { ...run, frames: null } : run;
return { ...run, frames: { maker: event.maker ?? null, list, seconds: Number.isFinite(seconds) && seconds > 0 ? seconds : 1 } };
}
case "result": {
if (run.status !== "running" || !event.url) return run;
if (event.promptId && run.promptId && !sameId(event.promptId, run.promptId)) return run;
@@ -106,6 +123,16 @@ export function nextRunState(state, event) {
}
}
// How long each frame of a moving step picture stays up, in ms: the clip's
// own pace, held between a quick flicker and a slide show.
export const FRAME_MS_MIN = 250;
export const FRAME_MS_MAX = 2000;
export function frameMs(frames) {
const ms = Math.round(Number(frames?.seconds) * 1000);
if (!Number.isFinite(ms) || ms <= 0) return 1000;
return Math.min(FRAME_MS_MAX, Math.max(FRAME_MS_MIN, ms));
}
// "step 3 of 8", or "starting" before the first report; a tiled upscale
// says so ahead of its tile's count.
const TILES_TEXT = "upscaling in tiles";
+192
View File
@@ -367,3 +367,195 @@ export function lengthFillsClip(info, plan, everyNth = 1) {
if (!info?.count || !plan || (plan.mode !== "length" && plan.mode !== "fixed")) return false;
return plan.first === 0 && slideRange(info, plan, everyNth).max === 0;
}
// --- Length limits ------------------------------------------------------------
// min_seconds / max_seconds keep the clip's length inside a range (0 = no
// limit). The backend applies them after the window is resolved
// (nodes/_video_load_helpers.limit_clip_length); limitClipSeconds mirrors
// that rule, so the rail and the App-mode clip window show what a run uses.
// The two limits, cleaned: negative or broken values are 0, and a max below
// the min counts as the min.
export function lengthLimits(minSeconds = 0, maxSeconds = 0) {
const min = Math.max(0, finite(minSeconds));
let max = Math.max(0, finite(maxSeconds));
if (max > 0 && max < min) max = min;
return { min, max, active: min > 0 || max > 0 };
}
// The window a run uses under the limits, in seconds. `end` 0 is the
// video's end; `cap` output frames of `frameSeconds` each can cut it short.
// Returns the stored-value shape { start, end, cap } plus `whole` (a video
// shorter than the min, used whole) and `changed`.
export function limitClipSeconds({ start = 0, end = 0, cap = 0, duration = 0, frameSeconds = 0 } = {}, limits = {}) {
const { min, max, active } = lengthLimits(limits.min, limits.max);
let first = finite(start);
const stored = { start: first, end: finite(end), cap: Math.max(0, Math.trunc(finite(cap))) };
const same = { ...stored, whole: false, changed: false };
if (!active) return same;
const length0 = finite(duration);
const known = length0 > 0;
if (known && min > 0 && length0 <= min + TRIM_EPSILON) return { start: 0, end: 0, cap: 0, whole: true, changed: true };
let stop = stored.end > 0 ? stored.end : known ? length0 : Infinity;
if (known) stop = Math.min(stop, length0);
let length = stop - first;
if (!(length > 0)) return same;
const step = finite(frameSeconds);
const capped = stored.cap > 0 && step > 0;
if (capped) length = Math.min(length, stored.cap * step);
let target = length;
if (max > 0) target = Math.min(target, max);
if (min > 0) target = Math.max(target, min);
if (Math.abs(target - length) <= TRIM_EPSILON) return same;
let last = first + target;
if (known && last > length0) {
last = length0;
first = Math.max(0, length0 - target);
}
const keepCap = capped && !(stored.cap * step < target - TRIM_EPSILON);
return { start: first, end: last, cap: keepCap ? stored.cap : 0, whole: false, changed: true };
}
// The output-frame counts a Duration may take at `rate` frames a second:
// at least one frame, and inside the limits when they are set.
export function limitFrameRange(limits = {}, rate = 0) {
const { min, max } = lengthLimits(limits.min, limits.max);
const fps = finite(rate);
if (!(fps > 0)) return { min: 1, max: Infinity };
const low = min > 0 ? Math.max(1, Math.ceil(min * fps - 1e-6)) : 1;
const high = max > 0 ? Math.max(low, Math.floor(max * fps + 1e-6)) : Infinity;
return { min: low, max: high };
}
// A Duration in output frames held inside the limits; under a snap rule it
// steps inward to a count the rule keeps.
export function limitFrames(frames, limits = {}, rate = 0, rule = "free") {
const range = limitFrameRange(limits, rate);
const count = Math.max(1, Math.round(finite(frames, 1)));
const held = clamp(count, range.min, range.max);
if (snapStep(rule) <= 1) return held;
const snapped = snapToValid(held, rule);
if (snapped > range.max) return snapToValid(held, rule, -1);
if (snapped < range.min) return snapToValid(held, rule, 1);
return snapped;
}
// --- The App-mode clip window ---------------------------------------------------
// One box on the video: drag it to pick where the clip starts, drag an edge
// to change its length. The window is { start, frames }: start in seconds on
// the source's frame grid, length in output frames at `rate` (what the node
// stores as start_seconds and max_frames).
function sourceGrid(seconds, info) {
return info?.fps > 0 ? Math.round(finite(seconds) * info.fps) / info.fps : finite(seconds);
}
function videoLength(info) {
return info?.duration > 0 ? info.duration : info?.fps > 0 ? info.count / info.fps : 0;
}
// Output frames that fit between `start` and the video's end.
function roomAt(start, info, rate) {
return Math.max(1, Math.floor((videoLength(info) - finite(start)) * rate + 1e-6));
}
// The latest start that still fits `frames`.
function latestStart(frames, info, rate) {
if (!(info?.fps > 0)) return 0;
const latest = Math.floor((videoLength(info) - frames / rate) * info.fps + 1e-6) / info.fps;
return Math.max(0, latest);
}
// The window a run uses, from the stored values: the limits applied
// (limitClipSeconds) and the length counted in output frames.
// `whole` - the video is shorter than the min and is used whole;
// `fills` - the window already covers the whole video, so only an edge moves.
export function clipWindowOf(info, { start = 0, end = 0, cap = 0, rate = 0 } = {}, limits = {}) {
const fps = finite(rate);
const duration = videoLength(info);
if (!(fps > 0) || !(duration > 0)) return null;
const limited = limitClipSeconds({ start, end, cap, duration, frameSeconds: 1 / fps }, limits);
const first = clamp(sourceGrid(limited.start, info), 0, duration);
let stop = limited.end > 0 ? Math.min(limited.end, duration) : duration;
let frames = Math.max(1, Math.round((stop - first) * fps));
if (limited.cap > 0) frames = Math.min(frames, limited.cap);
frames = Math.min(frames, roomAt(first, info, fps));
const window = { start: first, frames, rate: fps, whole: limited.whole };
window.seconds = frames / fps;
window.fills = first <= 0 && frames >= roomAt(0, info, fps);
return window;
}
// Move the window by one gesture. zone "start" or "end" drags that edge to
// `seconds` (the other edge stays); "move" slides the whole box so its start
// lands at `seconds`. The length stays inside the limits and the video.
export function dragClipWindow(window, zone, seconds, info, limits = {}) {
if (!window || window.whole) return window;
const rate = window.rate;
const range = limitFrameRange(limits, rate);
const at = finite(seconds);
if (zone === "move") {
const start = clamp(sourceGrid(at, info), 0, latestStart(window.frames, info, rate));
return { ...window, start, seconds: window.frames / rate };
}
if (zone === "end") {
const most = Math.min(range.max, roomAt(window.start, info, rate));
const frames = clamp(Math.round((at - window.start) * rate), Math.min(range.min, most), most);
return { ...window, frames, seconds: frames / rate };
}
const end = window.start + window.frames / rate;
const most = Math.min(range.max, Math.max(1, Math.floor(end * rate + 1e-6)));
const frames = clamp(Math.round((end - at) * rate), Math.min(range.min, most), most);
const start = clamp(sourceGrid(end - frames / rate, info), 0, latestStart(frames, info, rate));
return { ...window, start, frames, seconds: frames / rate };
}
// What the node stores for a window: the start on the hundredths grid that
// keeps its first frame (windowSeconds), the length as max_frames, and an
// open end.
export function clipWindowValues(window, info) {
const first = info?.fps > 0 ? clampFrame(Math.round(window.start * info.fps), info) : 0;
return {
start_seconds: windowSeconds(info, first, first).start_seconds,
end_seconds: 0,
max_frames: Math.max(1, Math.round(window.frames)),
};
}
// --- The "Clip length limits" fold on the node face -------------------------
const limitText = (value) => String(Number(Math.max(0, finite(value)).toFixed(2)));
// The closed header's words: "5 – 8 s", "from 5 s", "up to 8 s", or "off".
export function limitsSummary(minSeconds = 0, maxSeconds = 0) {
const { min, max } = lengthLimits(minSeconds, maxSeconds);
if (min > 0 && max > 0) return min === max ? `${limitText(min)} s` : `${limitText(min)} – ${limitText(max)} s`;
if (min > 0) return `from ${limitText(min)} s`;
if (max > 0) return `up to ${limitText(max)} s`;
return "off";
}
// Type one limit; the other one moves with it so the shortest never ends up
// above the longest. 0 is off and never pushes the other.
export function setLengthLimit(edge, value, { min = 0, max = 0 } = {}) {
const next = Math.max(0, finite(value));
let low = Math.max(0, finite(min));
let high = Math.max(0, finite(max));
if (edge === "min") {
low = next;
if (high > 0 && low > high) high = low;
} else {
high = next;
if (high > 0 && low > high) low = high;
}
return { min: low, max: high };
}
// Where the clip window's player belongs: inside the picked part, going
// back to its start once it reaches the end (or when it sits before it).
export function loopPlayhead(time, start, seconds, slack = 0.04) {
const from = Math.max(0, Number(start) || 0);
const length = Math.max(0, Number(seconds) || 0);
const now = Number(time);
if (!Number.isFinite(now) || now < from - slack || now >= from + length) return from;
return now;
}
+150 -6
View File
@@ -4,6 +4,7 @@ import { linkedNodeInfo, timingUnits as clipUnits } from "./timing_links.mjs";
import { PANEL_LABELS } from "./panel_controls.mjs";
import { hideInputsInDef, hideWidget } from "./widget_visibility.mjs";
import { mountTransformTrim } from "./transform_trim.mjs";
import { mountClipWindow } from "./clip_window.mjs";
import { clipOutputRate, inputNumber } from "./clip_rate.mjs";
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "./index.mjs";
import { WIDGET_FRAME, fillNodeHeight, holdVueNodeMinWidth, holdVuePanelMinHeight } from "./panel_layout.mjs";
@@ -11,6 +12,7 @@ import { mediaViewQuery, unlistedMedia } from "./media_list.mjs";
import { createMediaPicker } from "./media_picker.mjs";
import { normalizeFillColor } from "./fill_color.mjs";
import { makeSlideSwitch } from "./slide_switch.mjs";
import { t } from "./i18n.mjs";
import { makeScrubInput } from "./scrub_input.mjs";
import { confirmDiscard } from "./discard_prompt.mjs";
import { PIXEL_PROBE, featherGeneratedMask, generatedAreaMask, overlayPlan, pixelReadTrusted, seeThroughMap, stitchBlendFromMask } from "./stitch_preview.mjs";
@@ -80,7 +82,7 @@ import {
wrapDegrees,
zoomAround,
} from "./transform_geometry.mjs";
import { clampFrame, clipInfo, frameTime } from "./timeline_math.mjs";
import { clampFrame, clipInfo, frameTime, lengthLimits, limitsSummary, setLengthLimit } from "./timeline_math.mjs";
import { liftSocket } from "./widget_card.mjs";
import { COPY_EDITS_SETTING, copyPicture, transformPicture } from "./transform_picture.mjs";
@@ -91,6 +93,9 @@ const HIDDEN_WIDGETS = [
"pad_left", "pad_top", "pad_right", "pad_bottom", "feather", "canvas_multiple", "fill_color",
"seek_mode", "frame_index", "frame_time",
"start_seconds", "end_seconds", "every_nth", "max_frames", "frame_snap", "fixed_frames",
// Clip node: the length limits, and the App-mode clip window (a DOM
// widget shown only in a form that lists it, js/app_mode/).
"min_seconds", "max_seconds", "clip_window",
// Stitch settings (clip and image nodes), driven by the editor's Inpaint & Stitch section.
"stitch_blend", "stitch_grow",
// Image node: what a painted part is handed on as, set in the same section.
@@ -602,6 +607,15 @@ export function transformGroupOpen(node) {
return node?.properties?.[TRANSFORM_GROUP_OPEN_PROPERTY] === true;
}
// The clip node's "Clip length limits" fold, under Crop, pad & resize: the
// min_seconds / max_seconds pair, closed by default. Its own node property,
// so it opens and shuts on its own.
export const LIMITS_GROUP_OPEN_PROPERTY = "ausboss_clip_limits_open";
function limitsGroupOpen(node) {
return node?.properties?.[LIMITS_GROUP_OPEN_PROPERTY] === true;
}
export function transformGroupSummary(state) {
const node = state.node;
const parts = [];
@@ -705,6 +719,94 @@ function buildTransformGroup(state, rows) {
return group;
}
// Clip length limits: Shortest and Longest, in seconds (min_seconds,
// max_seconds; 0 is off). Built like the Crop, pad & resize fold and opens
// the same way: the picture keeps its size and the node grows by the body.
function buildLimitsGroup(state) {
const node = state.node;
const group = createElement("div", "ausboss-transform-group ausboss-transform-limits");
const head = createElement("button", "ausboss-transform-group-head");
head.type = "button";
const left = createElement("span", "ausboss-transform-group-title");
const caret = createElement("span", "ausboss-transform-group-caret", "▸");
caret.setAttribute("aria-hidden", "true");
left.append(caret, createElement("span", "", "Clip length limits"));
const right = createElement("span", "ausboss-transform-group-summary");
head.append(left, right);
const body = createElement("div", "ausboss-transform-group-body");
const row = createElement("div", "ausboss-transform-row ausboss-transform-canvas-row");
const current = () => ({ min: Number(value(node, "min_seconds", 0)) || 0, max: Number(value(node, "max_seconds", 0)) || 0 });
const fields = {};
const write = (edge, amount) => {
const next = setLengthLimit(edge, amount, current());
setValue(node, "min_seconds", next.min);
setValue(node, "max_seconds", next.max);
sync();
for (const trim of state.trimViews) trim.sync();
};
for (const [edge, caption, tip] of [
["min", "Shortest", "The shortest the clip may be, in seconds. 0 is off. A shorter clip grows to this; a video shorter than this is used whole."],
["max", "Longest", "The longest the clip may be, in seconds. 0 is off. A longer clip, or the whole video, is cut to this."],
]) {
const label = createElement("label");
const control = makeScrubInput({
value: current()[edge], min: 0, max: 86400, step: 0.5, fineStep: 0.1, decimals: 2, minDecimals: 0, width: 72, unit: "s",
title: tip,
onChange: (amount) => write(edge, amount),
onSettle: notifyAusbossChange,
});
label.title = tip;
label.append(createElement("span", "", caption), control.root);
row.append(label);
fields[edge] = control;
}
body.append(row);
group.append(head, body);
const apply = () => {
const open = limitsGroupOpen(node);
group.classList.toggle("open", open);
body.hidden = !open;
head.setAttribute("aria-expanded", String(open));
head.title = open ? "Hide the clip length limits" : "Show the clip length limits: the shortest and longest the clip may be";
};
const sync = () => {
const limits = current();
const text = limitsSummary(limits.min, limits.max);
if (right.textContent !== text) right.textContent = text;
const clean = lengthLimits(limits.min, limits.max);
right.title = clean.active ? `The clip stays ${text} long` : "No limits: the clip is as long as you set it";
fields.min.set(limits.min);
fields.max.set(limits.max);
};
head.addEventListener("click", () => {
const stageHeight = state.previewCanvas?.clientHeight ?? 0;
const before = measureChrome(state) ?? 0;
node.properties ??= {};
node.properties[LIMITS_GROUP_OPEN_PROPERTY] = !limitsGroupOpen(node);
notifyAusbossChange();
apply();
const after = measureChrome(state) ?? before;
holdVuePanelMinHeight(state.previewCanvas?.parentElement, transformPanelFloor(node) - WIDGET_FRAME);
if (node.size && after !== before) {
const nextHeight = Math.max(transformPanelFloor(node), node.size[1] + after - before);
node.setSize?.([node.size[0], nextHeight]);
state.stageGrowth = { height: stageHeight, target: nextHeight };
}
node.setDirtyCanvas?.(true, true);
draw(state);
});
head.addEventListener("pointerdown", (event) => event.stopPropagation());
// The limits also change from the saved workflow and from undo.
state.trimViews.add({ sync });
chainCallback(node, "onConfigure", () => queueMicrotask(() => {
if (!state.disposed) { apply(); sync(); measureChrome(state); }
}));
apply();
sync();
return group;
}
export function installTransformNode(node, kind, mountPanel = null) {
installStyles();
const state = {
@@ -775,6 +877,7 @@ export function installTransformNode(node, kind, mountPanel = null) {
// center and resize controls into one collapsible group, with a live
// summary on the header so active settings stay visible when closed.
panel.append(buildTransformGroup(state, [modeRow.row, chipRow.row, ...canvasRows]));
if (state.isClip && widget(node, "min_seconds") && widget(node, "max_seconds")) panel.append(buildLimitsGroup(state));
panel.append(row);
state.previewCanvas = preview;
open.addEventListener("click", () => openEditor(state));
@@ -796,6 +899,7 @@ export function installTransformNode(node, kind, mountPanel = null) {
} else {
node.addWidget?.("button", "Open editor", null, () => openEditor(state), { serialize: false });
}
if (state.isClip && typeof node.addDOMWidget === "function") installClipWindow(state);
// A fresh node opens at its floor: the stage as tall as its width asks.
node.setSize?.([
Math.max(TRANSFORM_MIN_WIDTH, Math.min(520, node.size?.[0] || TRANSFORM_MIN_WIDTH)),
@@ -1051,7 +1155,7 @@ function buildAspectChipRow(state) {
caption.textContent = untouched ? "Source" : "Custom";
caption.title = `${untouched ? "The picture's own shape" : "No ratio button has this shape"}: ${canvas.width}×${canvas.height} (${ratioLabel(canvas.width, canvas.height)}). Tap a ratio to use one.`;
}
caption.classList.toggle("generic", caption.textContent === "Ratio");
caption.classList.toggle("generic", !held && Boolean(request || !picture));
caption.classList.toggle("custom", Boolean(picture && !request && !untouched && !held));
caption.classList.toggle("held", held);
for (const { chip, aspect } of chips) {
@@ -1763,6 +1867,8 @@ async function requestStoryboard(state, key, attempt = 0) {
image, times: payload.times, count: payload.count,
tileWidth: payload.tile_width, tileHeight: payload.tile_height,
};
// The App-mode clip window draws its strip from the same tiles.
for (const trim of state.trimViews) trim.sync();
} catch { /* storyboard is an enhancement, never an error */ }
}
@@ -1931,7 +2037,7 @@ function editorSnapshot(node) {
}
const properties = {};
for (const [key, current] of Object.entries(node.properties ?? {})) {
if (key.startsWith("ausboss_") && key !== TRANSFORM_GROUP_OPEN_PROPERTY) properties[key] = JSON.stringify(current);
if (key.startsWith("ausboss_") && key !== TRANSFORM_GROUP_OPEN_PROPERTY && key !== LIMITS_GROUP_OPEN_PROPERTY) properties[key] = JSON.stringify(current);
}
return { widgets, properties };
}
@@ -2333,6 +2439,43 @@ function buildTrim(state) {
return control.root;
}
// The clip window an App-mode form can list (js/shared/clip_window.mjs):
// only the part of the video the run uses, as one box to drag. Hidden on
// the graph, so the node's face is unchanged; js/app_mode/ shows it while a
// form that lists it is open.
function installClipWindow(state) {
const node = state.node;
const view = mountClipWindow({
get: (name, fallback) => value(node, name, fallback),
set: (name, next) => {
setValue(node, name, next);
for (const other of state.trimViews) if (other !== view) other.sync();
},
driven: (name) => trimInputDriven(node, name),
number: (name, fallback) => inputNumber(node, name, value(node, name, fallback)),
outputRate: () => clipOutputRate(node, state.metadata?.fps, value(node, "every_nth", 1)),
metadata: () => state.metadata,
storyboard: () => state.storyboard,
// Both source modes hold a name the way ComfyUI writes one
// ("clip.mp4", "clip.mp4 [output]"), so /view serves either.
videoUrl: () => {
const query = mediaViewQuery(sourceKey(node, "video") ? videoSourceState(
value(node, "source_mode", INPUT_FOLDER_MODE), value(node, "video", ""), value(node, "local_path", ""),
).selection : "");
return query ? api.apiURL(`/view?${query}`) : "";
},
onCommit: notifyAusbossChange,
});
state.trimViews.add(view);
const clipWidget = node.addDOMWidget("clip_window", "ausboss_clip_window", view.root, {
serialize: false,
hideOnZoom: false,
});
clipWidget.serialize = false;
clipWidget.label = "Clip window";
hideWidget(clipWidget);
}
function setPlayhead(state, index) {
const info = clipInfo(state.metadata);
const frame = clampFrame(index, info);
@@ -2633,8 +2776,9 @@ function draw(state) {
// measured on every draw; before the panel is on screen, these stand in:
// the rows of a node with no file picked yet, as the examples open (the
// canvas row's Resize adds the budget row under it).
const PANEL_CHROME_CLOSED_ESTIMATE = { image: 188, video: 291, clip: 377 };
const PANEL_CHROME_OPEN_ESTIMATE = { image: 347, video: 450, clip: 536 };
// The clip node's rows include the closed Clip length limits fold.
const PANEL_CHROME_CLOSED_ESTIMATE = { image: 188, video: 291, clip: 417 };
const PANEL_CHROME_OPEN_ESTIMATE = { image: 347, video: 450, clip: 576 };
// Node width minus stage width: the DOM widget frame, panel padding, borders.
const PANEL_SIDE_INSET = 38;
// The narrowest face the chip row and the button rows fit on.
@@ -3426,7 +3570,7 @@ function sizeLines(state) {
return lines;
}
function drawEmpty(state, text) { state.render = null; state.panelRender = null; syncReadout(state); for (const canvas of [state.canvas, state.previewCanvas]) { if (!canvas) continue; const prepared = prepareCanvas(canvas); drawEmptyCanvas(prepared.context, prepared.width, prepared.height, text); } }
function drawEmptyCanvas(context, width, height, text) { context.fillStyle = "#111"; context.fillRect(0, 0, width, height); context.fillStyle = "#9ba2aa"; context.font = "13px system-ui"; context.textAlign = "center"; context.fillText(text, width / 2, height / 2); context.textAlign = "left"; }
function drawEmptyCanvas(context, width, height, text) { context.fillStyle = "#111"; context.fillRect(0, 0, width, height); context.fillStyle = "#9ba2aa"; context.font = "13px system-ui"; context.textAlign = "center"; context.fillText(t(text), width / 2, height / 2); context.textAlign = "left"; }
// True when the node is an AusBoss transform node whose editor can open
// (installed by installTransformNode). Used by the pack-wide command.
+35 -4
View File
@@ -33,6 +33,9 @@ import {
keyboardStep,
lastFrameFor,
latestInFor,
lengthLimits,
limitClipSeconds,
limitFrames,
railZone,
setTrimFrame,
slideRange,
@@ -189,9 +192,22 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
};
const countAtRunTime = () => COUNT_INPUTS.some((name) => driven(name) && number(name, null) == null);
const outFps = () => (outputRate ? outputRate() : info().fps / everyNth());
// min_seconds / max_seconds: the clip's length stays inside them. A
// connected limit only the run knows counts as none here.
const limits = () => lengthLimits(
number("min_seconds", get("min_seconds", 0)) ?? 0,
number("max_seconds", get("max_seconds", 0)) ?? 0,
);
const limitWords = () => {
const { min, max } = limits();
if (min > 0 && max > 0) return min === max ? `${secondsText(min)} s long` : `between ${secondsText(min)} and ${secondsText(max)} s`;
return max > 0 ? `at most ${secondsText(max)} s` : `at least ${secondsText(min)} s`;
};
// A Duration in output frames, held inside the limits.
const holdFrames = (frames) => (limits().active && outFps() > 0 ? limitFrames(frames, limits(), outFps(), snapRule()) : frames);
const planValues = () => {
const wired = wiredBy();
return {
const values = {
start: boundSeconds("start"),
end: boundSeconds("end"),
everyNth: everyNth(),
@@ -203,6 +219,17 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
outputFps: outputRate ? outputRate() : info().fps,
resampled: driven("force_rate"),
};
// The window the run uses under the limits (the backend's
// limit_clip_length), so the rail shows what will come out. An exact
// Fixed frames count and a connected length are left as they are.
const clip = info();
const duration = clip.duration || (clip.fps > 0 ? clip.count / clip.fps : 0);
const rate = outFps();
if (limits().active && !wired && !(Math.trunc(Number(values.fixedFrames) || 0) > 0) && duration > 0) {
const limited = limitClipSeconds({ start: values.start, end: values.end, cap: values.maxFrames, duration, frameSeconds: rate > 0 ? 1 / rate : 0 }, limits());
if (limited.changed) Object.assign(values, { start: limited.start, end: limited.end, maxFrames: limited.cap });
}
return values;
};
const plan = () => (trim ? clipLengthPlan(info(), planValues()) : null);
// Output frames that fit between IN and the end of the video: the most a
@@ -332,10 +359,14 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
let frames = framesThrough(current.first, target, nth, snapRule());
if (driven("force_rate") && outFps() > 0) {
// Output frames at the linked rate from IN to the handle's boundary.
frames = snapToValid(Math.max(1, Math.round(((target + 1) / clip.fps - boundSeconds("start")) * outFps())), snapRule());
frames = snapToValid(Math.max(1, Math.round(((target + 1) / clip.fps - planValues().start) * outFps())), snapRule());
const room = roomFrames();
if (room != null) frames = Math.min(frames, Math.max(1, room));
}
// The limits stop OUT where the clip would get too short or too long.
const held = holdFrames(frames);
if (held !== frames) stopNote = `The clip stays ${limitWords()}.`;
frames = held;
if (current.mode === "length") {
set("max_frames", frames);
set("end_seconds", 0);
@@ -652,7 +683,7 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
const current = adoptLength(plan());
if (current.mode !== "length") return;
const was = current.requested ?? get("max_frames", 1);
set("max_frames", snapToValid(Math.max(1, frames), snapRule(), Math.sign(frames - was)));
set("max_frames", holdFrames(snapToValid(Math.max(1, frames), snapRule(), Math.sign(frames - was))));
set("end_seconds", 0);
stopNote = "";
};
@@ -851,7 +882,7 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
select.addEventListener("change", () => {
set("frame_snap", select.value);
// A Length moves to the nearest count the new rule keeps.
if (plan()?.mode === "length") set("max_frames", snapToValid(get("max_frames", 1), select.value));
if (plan()?.mode === "length") set("max_frames", holdFrames(snapToValid(get("max_frames", 1), select.value)));
sync(); onCommit?.();
});
controls.frame_snap = select;
+69
View File
@@ -0,0 +1,69 @@
// Where things sit in ComfyUI's 3D viewers, measured from what is on
// screen. The viewer's menu bar (Scene, Show grid, Panorama ...) lies over
// the top of the view; the pack's 360 strip opens right under it, and the
// axis gizmo and the tools sit under that, in the top-right corner.
//
// Every number is in the viewer's own pixels, before the graph's zoom:
// the graph scales the viewer as a whole, so a screen distance is divided
// by that scale.
/** The graph's zoom on this element: screen pixels per own pixel. */
export function viewerScale(host) {
const rect = host?.getBoundingClientRect?.();
const own = host?.offsetHeight;
return rect && own ? rect.height / own : 1;
}
function viewerRootOf(host) {
let el = host;
for (let i = 0; el && i < 12; i += 1, el = el.parentElement) {
if (el.querySelector?.('[data-testid="load3d-category-menu"]')) return el;
}
return null;
}
/**
* The bottom of the menu bar as it is drawn, measured from the top of
* `host` (the element that holds the view). The bar's wrapper can be taller
* than the bar itself, so this ends under the lowest button on the bar's
* first line. null while the viewer is not on screen.
*/
export function menuBarBottom(host) {
const root = viewerRootOf(host);
const menu = root?.querySelector('[data-testid="load3d-category-menu"]');
if (!menu) return 0;
const hostRect = host.getBoundingClientRect();
if (!hostRect.height) return null;
const scale = viewerScale(host) || 1;
// The bar: the smallest element holding both the Scene menu and Show grid.
const grid = root.querySelector('i[class*="lucide--grid-3x3"]')?.closest("button");
let row = menu;
if (grid) while (row && !row.contains(grid)) row = row.parentElement;
row ??= menu.parentElement ?? menu;
const rowRect = row.getBoundingClientRect();
let low = -Infinity;
for (const button of row.querySelectorAll("button")) {
const rect = button.getBoundingClientRect();
// Only the bar's first line: an open dropdown hangs further down.
if (rect.height && rect.top < rowRect.top + 48 * scale) low = Math.max(low, rect.bottom);
}
const bottom = Number.isFinite(low) ? Math.min(rowRect.bottom, low + 6 * scale) : rowRect.bottom;
return Math.max(0, Math.round((bottom - hostRect.top) / scale));
}
/**
* The viewer's own bottom buttons (fit, fullscreen, download): their
* distance from the bottom of `host` and their height, so a bar can sit on
* the same line. null when they are not found.
*/
export function bottomButtons(host) {
const root = viewerRootOf(host);
const icon = root?.querySelector('i[class*="lucide--download"]') ?? root?.querySelector('i[class*="lucide--scan"]');
const group = icon?.closest("button")?.parentElement;
if (!group) return null;
const hostRect = host.getBoundingClientRect();
const rect = group.getBoundingClientRect();
if (!hostRect.height || !rect.height) return null;
const scale = viewerScale(host) || 1;
return { bottom: Math.max(0, Math.round((hostRect.bottom - rect.bottom) / scale)), height: Math.round(rect.height / scale) };
}
+10 -5
View File
@@ -81,7 +81,7 @@ export function ensureCardCss() {
style.textContent = `
.ausboss-card{position:relative;box-sizing:border-box;width:100%;height:100%;display:flex;flex-direction:column;gap:${ROW_GAP}px;padding:${CARD_PADDING}px 8px;overflow:hidden;border:1px solid transparent;border-radius:${RADIUS_CARD}px;background:${T.card};font:12px/1.3 ${FONT};color:${T.inkSoft};pointer-events:none}
.ausboss-card-row{display:grid;grid-template-columns:minmax(56px,30%) 1fr;align-items:center;gap:8px;height:${ROW_HEIGHT}px;flex:none;pointer-events:auto}
.ausboss-card-row.hidden{display:none}
.ausboss-card .ausboss-card-row.hidden{display:none}
.ausboss-card-row.linked{opacity:.5}
.ausboss-card-row.linked .ausboss-card-control{pointer-events:none}
.ausboss-card-row.muted .ausboss-card-control{opacity:.35;pointer-events:none}
@@ -97,6 +97,7 @@ export function ensureCardCss() {
.ausboss-card-row.area{display:block}
.ausboss-card-row.panel{display:block}
.ausboss-card-row.area.grow{flex:1 1 auto;height:auto}
.ausboss-card-row.panel.grow{flex:1 1 auto;height:auto}
.ausboss-card-label{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:${T.label};font-size:11px;user-select:none}
.ausboss-card-control{display:flex;align-items:center;gap:6px;min-width:0;height:100%}
.ausboss-card-field{display:flex;align-items:center;gap:6px;flex:1 1 0;min-width:0;height:100%}
@@ -215,9 +216,10 @@ function isFloatWidget(widget) {
// - `top` lifts the widgets' sockets
// into the node's slot column
// { section: "Caption" }
// { panel: (node) => ({ element, sync(values) }), height }
// { panel: (node) => ({ element, sync(values) }), height, grow?, when? }
// - the node's own display, on a row
// of the card
// of the card; `grow` takes the
// node's spare height
// { group: "advanced", label: "More" } - a disclosure; later rows with
// group: "advanced" sit under it
// A numeric row may have readOnlyText(node, values): nonempty text replaces
@@ -538,7 +540,8 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
}
if (row.panel) {
const line = el("div", "ausboss-card-row panel");
line.style.height = `${rowHeight(row)}px`;
if (row.grow) { line.classList.add("grow"); line.style.minHeight = `${rowHeight(row)}px`; }
else line.style.height = `${rowHeight(row)}px`;
const panel = row.panel(node);
line.append(panel.element);
state.rows.push({ row, element: line, syncs: panel.sync ? [panel.sync] : [] });
@@ -762,7 +765,7 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
}
const groups = {};
for (const entry of state.rows) if (entry.header) groups[entry.row.group] = groupOpen(entry.row.group);
const visible = visibleRows(state.rows.map((entry) => entry.row), vals, groups);
const visible = visibleRows(state.rows.map((entry) => entry.row), vals, groups, node);
const visibleSet = new Set(visible);
const tops = rowTops(visible, look);
state.rowTop = new Map();
@@ -863,5 +866,7 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
refresh();
state.refresh = refresh; state.setGroupOpen = setGroupOpen; state.groupOpen = groupOpen;
// A panel that changes the card's rows itself (a tab) redraws it as a change by hand.
state.refreshByHand = () => byHand(refresh);
return state;
}
+4 -2
View File
@@ -18,12 +18,14 @@ const SEGMENT_MAX_CHARS = 26;
// Which rows the current values leave visible. `groups` maps a group name to
// its open state; a row inside a closed group is out, a row whose `when`
// says no is out, a group header stays as long as any row under it exists.
export function visibleRows(rows, values, groups = {}) {
// `when(values, node)` gets the node too, for a row that follows a display
// choice kept on the node rather than a widget value (a tab).
export function visibleRows(rows, values, groups = {}, node = null) {
return rows.filter((row) => {
if (row.group !== undefined && row.widget === undefined && row.pair === undefined && row.section === undefined) {
return true; // the disclosure header itself
}
if (row.when && row.when(values) === false) return false;
if (row.when && row.when(values, node) === false) return false;
if (row.inGroup && !groups[row.inGroup]) return false;
return true;
});
+62
View File
@@ -181,6 +181,43 @@ export function folderPath(dir) {
return `ComfyUI/models/${dir}`;
}
// ComfyUI still accepts two old folder names everywhere except in its
// /models/<folder> list, which answers 404 for them. Stability Matrix and
// older notes use them, so a row naming one is checked under the new name.
const LEGACY_FOLDERS = { clip: "text_encoders", unet: "diffusion_models" };
export function modelFolderKey(dir) {
const key = str(dir, 200).trim();
return Object.hasOwn(LEGACY_FOLDERS, key) ? LEGACY_FOLDERS[key] : key;
}
// Every folder this install reads for `dir`, from ComfyUI's
// /experiment/models list ([{ name, folders: [path, ...] }]). Launchers
// such as Stability Matrix add their own shared folders through
// extra_model_paths.yaml, so a file may live outside ComfyUI/models.
export function installFolders(dir, folderList) {
if (!dir || dir === INPUT_FOLDER || !Array.isArray(folderList)) return [];
const key = modelFolderKey(dir);
const entry = folderList.find((item) => item && item.name === key);
if (!entry || !Array.isArray(entry.folders)) return [];
return [...new Set(entry.folders.map((folder) => str(folder, 1000)).filter(Boolean))];
}
// The folders from `installFolders` with a name of their own, such as
// Stability Matrix's Data/Models/Lora: the ones worth showing, since a
// person would not guess them. A folder named like the kind itself
// (models/loras, output/loras, a shared .../loras) reads the way the card
// already says, so it is left out.
export function sharedFolders(dir, folderList) {
const key = modelFolderKey(dir);
const usual = new Set([key, ...Object.keys(LEGACY_FOLDERS).filter((name) => LEGACY_FOLDERS[name] === key)]
.map((name) => name.toLowerCase()));
return installFolders(dir, folderList).filter((folder) => {
const last = folder.replace(/\\/g, "/").replace(/\/+$/, "").split("/").pop().toLowerCase();
return !usual.has(last);
});
}
// Rows grouped by folder in first-seen order, so the card reads like the
// install tree: one heading per folder, its files beneath.
export function groupModels(models) {
@@ -245,6 +282,31 @@ export function packsFromGraph(nodeTypes, moduleOf) {
return packs;
}
// This pack, as a Workflow Note lists it. Its folder is ausboss-nodes from
// the Manager and ComfyUI-AusBoss from a git clone, so a row is named and
// linked by the Registry id: a GitHub link sent people to clone a second copy.
export const OWN_PACK = Object.freeze({
name: "AusBoss nodes",
url: "https://registry.comfy.org/nodes/ausboss-nodes",
});
const OWN_PACK_NAMES = new Set(["ausboss nodes", "ausboss-nodes", "comfyui-ausboss"]);
const OWN_PACK_URL = /^https?:\/\/(?:www\.)?(?:github\.com\/ausboss\/comfyui-ausboss(?:\.git)?|registry\.comfy\.org\/nodes\/ausboss-nodes)\/?$/i;
// Whether a saved pack row is this pack, by its name or link. The probe node
// does not decide it: other AusBoss packs use AUSBOSS_NODES_ class names too.
export function isOwnPackRow(row) {
const name = str(row?.name, 200).trim().toLowerCase();
const url = str(row?.url, 500).trim();
return OWN_PACK_NAMES.has(name) || OWN_PACK_URL.test(url);
}
// Detect names a pack by its folder. The folder this pack runs from becomes
// OWN_PACK, so a workflow saved on a git clone does not send people to GitHub.
export function nameOwnPack(packs, ownFolder) {
return packs.map((pack) => (ownFolder && pack.name === ownFolder ? { ...OWN_PACK, node: pack.node } : pack));
}
// How tall the node must be for the card to show all of its content, from
// three numbers the page measures: the card's natural height at its current
// width, the node's height, and the part of the node height the card never
+906
View File
@@ -0,0 +1,906 @@
// Blender's keys in ComfyUI's 3D viewers. With the mouse over a viewer:
// G move, R rotate, S scale: the model follows the mouse from where it is,
// no click needed. X / Y / Z lock to an axis (press again for the
// model's own axis, a third time to unlock); Shift+X / Y / Z lock to the
// plane without that axis. Middle mouse picks the lock from the mouse:
// hold it and slide along an axis, or click it and move (Shift: the
// plane); click again to unlock; C unlocks. Shift held: ten times slower. Ctrl held: snap
// (0.1, 5 degrees; with Shift 0.01, 1 degree). Type a number for an exact
// amount (minus flips it). Click, Enter or Space keeps it; Esc or a
// right-click puts it back. R twice: trackball.
// Alt+G / Alt+R / Alt+S put the place, the turn or the size back.
// Ctrl+Z / Ctrl+Shift+Z undo and redo these, while the viewer has some.
// Numpad (or the top-row digits): 1 front, 3 right, 7 top (Ctrl: the
// other side), 2 4 6 8 orbit by 15 degrees, 9 the other side; Home or
// numpad . frames the model. N opens and closes the 360 strip.
// Middle mouse orbits, Shift+middle pans, as in Blender.
// The model is the one the viewer saves as model_3d_info, so the run gets
// what the viewer shows. The maths is in js/shared/blender_transform.mjs.
import { app } from "../../../scripts/app.js";
import {
AXES, AXIS_NAMES, PICK_PX, add, along, autoConstraint, closestOnAxis, constraintLabel, dot, nearestLocalAxis,
nearestScreenAxis, nextConstraint, parseTyped, pickVector, rayPlane, readout, scaleFactors, screenTurn,
snapStep, snapTo, sub, times, typeKey, unit,
} from "../shared/blender_transform.mjs";
import { FONT_UI, RADIUS_CONTROL, RADIUS_XS, THEME as T } from "../shared/theme.mjs";
import { bottomButtons } from "../shared/viewer3d_layout.mjs";
const CSS_ID = "ausboss-viewer-keys-css";
const DEG = Math.PI / 180;
// Blender's axis colours, so a lock reads the same as there.
const AXIS_COLOR = { x: "#ff3352", y: "#8bdc00", z: "#2890ff" };
const ORBIT_STEP = 15 * DEG;
const TRACKBALL = 0.01; // radians per pixel
function ensureCss() {
if (document.getElementById(CSS_ID)) return;
const style = document.createElement("style");
style.id = CSS_ID;
style.textContent = `
.ausboss-vkeys-head{position:absolute;left:6px;z-index:7;max-width:calc(100% - 120px);box-sizing:border-box;height:20px;padding:0 8px;border-radius:${RADIUS_XS}px;background:rgba(30,32,34,.9);font:400 11px/20px ${FONT_UI};color:${T.ink};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums;pointer-events:none}
.ausboss-vkeys-head .lock{color:${T.inkSoft}}
.ausboss-vkeys-head .lock.x{color:#ff6b80}.ausboss-vkeys-head .lock.y{color:#a6e22e}.ausboss-vkeys-head .lock.z{color:#5aa9ff}
.ausboss-vkeys-head .pick{color:${T.brandInk}}
.ausboss-vkeys-head .typed{color:${T.onBrand};background:${T.brand};border-radius:${RADIUS_XS}px;padding:0 4px}
.ausboss-vkeys-bar{position:absolute;left:6px;z-index:7;max-width:calc(100% - 132px);box-sizing:border-box;height:20px;display:flex;align-items:center;gap:9px;padding:0 7px;border-radius:${RADIUS_XS}px;background:rgba(30,32,34,.88);font:400 10px/1 ${FONT_UI};color:${T.inkSoft};white-space:nowrap;overflow:hidden;pointer-events:none}
.ausboss-vkeys-bar span{display:inline-flex;align-items:center;gap:3px}
.ausboss-vkeys-bar kbd{font:600 9px/1 ${FONT_UI};color:${T.ink};background:rgba(255,255,255,.12);border-radius:3px;padding:2px 4px}
.ausboss-vkeys-lines{position:absolute;left:0;top:0;width:100%;height:100%;z-index:5;pointer-events:none}
.ausboss-vkeys-sheet{position:absolute;z-index:7;box-sizing:border-box;width:236px;padding:8px 10px;border-radius:${RADIUS_CONTROL}px;background:rgba(16,18,20,.94);box-shadow:0 2px 10px rgba(0,0,0,.5);font:400 11px/1.3 ${FONT_UI};color:${T.inkSoft};display:grid;grid-template-columns:auto 1fr;gap:3px 10px}
.ausboss-vkeys-sheet kbd{font:600 10px/1 ${FONT_UI};color:${T.ink};background:${T.fill};border-radius:${RADIUS_XS}px;padding:3px 5px;white-space:nowrap;justify-self:start;align-self:start}
.ausboss-vkeys-sheet .h{grid-column:1/-1;color:${T.faint};font-size:10px;margin-top:4px}
.ausboss-vkeys-sheet .h:first-child{margin-top:0}
`;
document.head.append(style);
}
// ------------------------------------------------------------ the viewer
// Each viewer the pack has taken over has a gizmo box (js/viewer_tools)
// that knows its camera, and a 360 strip (js/viewer_pano) that knows its
// scene. The core's gizmo manager knows the model; it registers itself on
// its scene here as soon as it is used.
function patchGizmoManager() {
const Gizmo = window.comfyAPI?.GizmoManager?.GizmoManager;
if (!Gizmo || Gizmo.prototype.__ausbossKeys) return;
for (const name of ["setupForModel", "setEnabled", "updateCamera", "getModelInfo", "getTransform", "applyModelTransform"]) {
const original = Gizmo.prototype[name];
if (typeof original !== "function") continue;
Gizmo.prototype[name] = function (...args) {
if (this.scene) this.scene.__ausbossGizmo = this;
return original.apply(this, args);
};
}
Gizmo.prototype.__ausbossKeys = true;
}
function modelIn(sceneManager) {
const scene = sceneManager?.scene;
const gizmo = scene?.__ausbossGizmo;
if (gizmo?.targetObject?.parent) return gizmo.targetObject;
return scene?.children?.find((child) => {
if (child.isLight || child === sceneManager.gridHelper || !child.visible || child.name === "GizmoTransformControls") return false;
let found = false;
child.traverse?.((part) => { if (!found && part.isMesh && part.material?.isMeshStandardMaterial) found = true; });
return found;
}) ?? null;
}
function contextOf(box) {
const helper = box?.__ausbossManager;
const sceneManager = box?.__ausbossScene;
const camera = helper?.getActiveCamera?.();
const host = box?.parentElement;
const canvas = host?.querySelector("canvas");
if (!camera || !sceneManager || !canvas) return null;
return { box, host, helper, sceneManager, camera, controls: helper.getControls?.() ?? null, canvas, model: modelIn(sceneManager) };
}
function viewerAt(x, y) {
const under = document.elementFromPoint(x, y);
if (!under) return null;
for (const box of document.querySelectorAll("div[data-ausboss-gizmo]")) {
const host = box.parentElement;
if (!host || !box.__ausbossScene) continue;
// The view and everything on it: the menu bar, the strip, the tools.
if (host.parentElement?.parentElement?.contains(under) || host.contains(under)) {
const rect = host.getBoundingClientRect();
if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) return box;
}
}
return null;
}
function redraw(ctx) {
try { ctx.sceneManager.__ausbossViewport?.forceRender?.(); } catch { /* the next frame shows it */ }
}
// The part of the canvas the camera's picture fills: the shot's frame when
// the viewer keeps the shot's shape (bars at the sides or top), else all of it.
function frameOf(ctx) {
const rect = ctx.canvas.getBoundingClientRect();
const width = ctx.canvas.clientWidth || rect.width;
const height = ctx.canvas.clientHeight || rect.height;
const k = width ? rect.width / width : 1;
let x = 0, y = 0, w = width, h = height;
const viewport = ctx.sceneManager.__ausbossViewport;
const letterbox = window.comfyAPI?.load3dViewport?.computeLetterboxedViewport;
try {
if (viewport && letterbox && viewport.shouldMaintainAspectRatio?.() && viewport.targetAspectRatio > 0) {
const box = letterbox({ width, height }, viewport.targetAspectRatio);
if (box?.width > 0 && box?.height > 0) { x = box.offsetX; w = box.width; h = box.height; y = height - box.offsetY - box.height; }
}
} catch { /* the whole canvas */ }
return { left: rect.left + x * k, top: rect.top + y * k, width: w * k, height: h * k };
}
const toNdc = (frame, p) => [((p[0] - frame.left) / frame.width) * 2 - 1, 1 - ((p[1] - frame.top) / frame.height) * 2];
const toScreen = (frame, n) => [frame.left + ((n[0] + 1) / 2) * frame.width, frame.top + ((1 - n[1]) / 2) * frame.height];
function V(ctx, x = 0, y = 0, z = 0) { return new ctx.camera.position.constructor(x, y, z); }
function rayAt(ctx, frame, point) {
const camera = ctx.camera;
camera.updateMatrixWorld();
const [nx, ny] = toNdc(frame, point);
if (camera.isOrthographicCamera) {
const origin = V(ctx, nx, ny, -1).unproject(camera);
return { o: origin.toArray(), d: V(ctx, 0, 0, -1).applyQuaternion(camera.quaternion).toArray() };
}
const far = V(ctx, nx, ny, 0.5).unproject(camera);
return { o: camera.position.toArray(), d: unit(sub(far.toArray(), camera.position.toArray())) };
}
function screenOf(ctx, frame, world) {
const p = V(ctx, ...world).project(ctx.camera);
return { at: toScreen(frame, [p.x, p.y]), front: p.z < 1 };
}
const viewDir = (ctx) => V(ctx, 0, 0, -1).applyQuaternion(ctx.camera.quaternion).toArray();
// The middle of the model's box, in the world.
function centreOf(model) {
model.updateMatrixWorld(true);
const lo = [Infinity, Infinity, Infinity];
const hi = [-Infinity, -Infinity, -Infinity];
const v = new model.position.constructor();
model.traverse((part) => {
if (!part.isMesh || !part.visible || !part.geometry) return;
if (!part.geometry.boundingBox) part.geometry.computeBoundingBox?.();
const b = part.geometry.boundingBox;
if (!b) return;
for (const x of [b.min.x, b.max.x]) for (const y of [b.min.y, b.max.y]) for (const z of [b.min.z, b.max.z]) {
v.set(x, y, z).applyMatrix4(part.matrixWorld);
lo[0] = Math.min(lo[0], v.x); lo[1] = Math.min(lo[1], v.y); lo[2] = Math.min(lo[2], v.z);
hi[0] = Math.max(hi[0], v.x); hi[1] = Math.max(hi[1], v.y); hi[2] = Math.max(hi[2], v.z);
}
});
if (!Number.isFinite(lo[0])) return { centre: model.position.toArray(), radius: 1 };
return { centre: times(add(lo, hi), 0.5), radius: Math.max(1e-3, Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) / 2) };
}
// The model's own axes, in the world.
const localAxes = (ctx, quaternion) => AXIS_NAMES.map((name) => V(ctx, ...AXES[name]).applyQuaternion(quaternion).toArray());
// ---------------------------------------------------------------- history
const snapshot = (model) => ({ p: model.position.toArray(), q: model.quaternion.toArray(), s: model.scale.toArray() });
function restore(model, shot) {
model.position.fromArray(shot.p);
model.quaternion.fromArray(shot.q);
model.scale.fromArray(shot.s);
model.updateMatrixWorld(true);
}
const histories = new WeakMap();
const historyOf = (model) => {
if (!histories.has(model)) histories.set(model, { undo: [], redo: [], first: snapshot(model) });
return histories.get(model);
};
function remember(model, before) {
const history = historyOf(model);
history.undo.push(before);
if (history.undo.length > 64) history.undo.shift();
history.redo.length = 0;
}
// The core saves the model's place through its gizmo; tell it, and let the
// Model tab show the new turn.
function settled(ctx) {
try { ctx.sceneManager.scene?.__ausbossGizmo?.onTransformChange?.(); } catch { /* saved with the shot anyway */ }
ctx.box.__ausbossPano?.refresh?.();
redraw(ctx);
}
// ------------------------------------------------------------ G / R / S
let pointer = null;
let session = null;
let swallowUntil = 0;
function begin(mode, box, at) {
const ctx = contextOf(box);
if (!ctx?.model) return false;
const model = ctx.model;
historyOf(model);
const frame = frameOf(ctx);
const { centre } = centreOf(model);
const start = snapshot(model);
// From the model's origin to its middle, in the model's own turned frame
// (before any new size), so rotating or scaling keeps the middle in place.
const q0 = new model.quaternion.constructor().fromArray(start.q);
const fromPivot = V(ctx, ...sub(centre, start.p)).applyQuaternion(q0.clone().invert()).toArray();
session = {
mode, ctx, frame, start, centre, fromPivot, origin: [...at], mouse: [...at], real: [...at],
constraint: null, typed: "", trackball: false, turn: 0, precise: false, snap: false,
centreScreen: screenOf(ctx, frame, centre).at,
};
session.controlsWere = ctx.controls?.enabled;
if (ctx.controls) ctx.controls.enabled = false;
ctx.host.style.cursor = mode === "grab" ? "move" : "crosshair";
session.head = document.createElement("div");
session.head.className = "ausboss-vkeys-head";
session.lines = document.createElement("canvas");
session.lines.className = "ausboss-vkeys-lines";
session.bar = document.createElement("div");
session.bar.className = "ausboss-vkeys-bar";
ctx.host.append(session.lines, session.head, session.bar);
update();
return true;
}
function switchMode(mode) {
const s = session;
if (mode === s.mode) {
if (mode === "rotate") { s.trackball = !s.trackball; s.typed = ""; update(); }
return;
}
// Blender starts the new tool from where the model began.
restore(s.ctx.model, s.start);
s.mode = mode;
s.trackball = false;
s.typed = "";
s.turn = 0;
s.origin = [...s.mouse];
s.ctx.host.style.cursor = mode === "grab" ? "move" : "crosshair";
update();
}
function finish(keep) {
const s = session;
if (!s) return;
session = null;
// A kept move can be undone from here.
holdGraphUndo = keep || hasHistory(s.ctx.box);
const { ctx } = s;
if (keep) remember(ctx.model, s.start);
else restore(ctx.model, s.start);
if (ctx.controls) ctx.controls.enabled = s.controlsWere ?? true;
ctx.host.style.cursor = "";
s.head.remove();
s.lines.remove();
s.bar.remove();
if (keep) settled(ctx); else { ctx.box.__ausbossPano?.refresh?.(); redraw(ctx); }
}
function axisOf(s, constraint) {
if (!constraint) return null;
const base = AXES[constraint.axis];
if (constraint.space !== "local") return [...base];
const q = new s.ctx.model.quaternion.constructor().fromArray(s.start.q);
return unit(V(s.ctx, ...base).applyQuaternion(q).toArray());
}
// ------------------------------------------------------------ middle-mouse lock
// Blender's automatic lock: during G, R or S the middle button locks to the
// world axis the mouse moves along. Held, all three axes show and the lock
// follows the mouse until the button comes up; clicked after a move, it
// locks to that move's axis; clicked before any move, the next move picks.
// Pressed while locked, a click unlocks and a held slide picks again.
// The three world axes as drawn on screen from the model's middle.
function screenAxes(s) {
const { ctx, frame, centre } = s;
const from = screenOf(ctx, frame, centre);
const reach = Math.max(1e-3, Math.hypot(...sub(ctx.camera.position.toArray(), centre))) * 0.1;
const dirs = AXIS_NAMES.map((name) => {
const to = screenOf(ctx, frame, add(centre, times(AXES[name], reach)));
return from.front && to.front ? [to.at[0] - from.at[0], to.at[1] - from.at[1]] : [0, 0];
});
const longest = Math.max(...dirs.map((d) => Math.hypot(d[0], d[1])));
return { dirs, minLength: Math.max(1e-3, longest * 0.12) };
}
function pickAxis(s, move, plane) {
if (!move) return false;
const { dirs, minLength } = screenAxes(s);
const index = nearestScreenAxis(move, dirs, minLength);
if (index < 0) return false;
s.constraint = autoConstraint(AXIS_NAMES[index], plane);
s.trackball = false; // a locked turn goes around the axis
return true;
}
function middleDown(plane) {
const s = session;
s.waiting = null;
// Picking follows the hand (s.real), not the slowed Shift move.
s.auto = { plane, press: [...s.real], moved: false, unlock: !!s.constraint };
// Not locked yet: a move made before the click picks at once.
if (!s.constraint) pickAxis(s, pickVector(s.origin, null, s.mouse), plane);
update();
}
function middleUp() {
const s = session;
const a = s?.auto;
if (!a) return;
s.auto = null;
if (a.unlock && !a.moved) s.constraint = null;
else if (!s.constraint) s.waiting = { plane: a.plane, press: [...s.real] };
update();
}
// Each mouse move while the middle button is down, or after a click that
// came before any move.
function middleMove(s) {
if (s.auto) {
const held = pickVector(s.auto.press, s.auto.press, s.real);
if (held) { s.auto.moved = true; pickAxis(s, held, s.auto.plane); }
} else if (s.waiting) {
const move = pickVector(s.waiting.press, null, s.real, PICK_PX);
if (move && pickAxis(s, move, s.waiting.plane)) s.waiting = null;
}
}
// G: where the mouse is now against where it started, on the plane through
// the model's middle facing the camera, along a locked axis, or on a
// locked plane.
function moveFromMouse(s) {
const { ctx, frame, centre } = s;
const r0 = rayAt(ctx, frame, s.origin);
const r1 = rayAt(ctx, frame, s.mouse);
const facing = viewDir(ctx);
const onPlane = (normal) => {
const t0 = rayPlane(r0.o, r0.d, centre, normal);
const t1 = rayPlane(r1.o, r1.d, centre, normal);
return t0 == null || t1 == null || t0 < 0 || t1 < 0 ? null : sub(along(r1.o, r1.d, t1), along(r0.o, r0.d, t0));
};
const free = () => onPlane(facing) ?? [0, 0, 0];
const c = s.constraint;
if (c?.kind === "axis") {
const axis = axisOf(s, c);
const t0 = closestOnAxis(r0.o, r0.d, centre, axis);
const t1 = closestOnAxis(r1.o, r1.d, centre, axis);
// Looking straight down the axis: follow the free move along it.
let distance = t0 == null || t1 == null ? dot(free(), axis) : t1 - t0;
if (s.snap) distance = snapTo(distance, snapStep("grab", s.precise));
return times(axis, distance);
}
let move;
if (c?.kind === "plane") {
const normal = axisOf(s, c);
move = Math.abs(dot(normal, facing)) > 0.08 ? onPlane(normal) : null;
if (!move) { const f = free(); move = sub(f, times(normal, dot(f, normal))); }
} else move = free();
if (s.snap) {
const step = snapStep("grab", s.precise);
if (c?.space === "local") {
// Snap along the model's own axes.
const axes = localAxes(ctx, new ctx.model.quaternion.constructor().fromArray(s.start.q));
move = axes.reduce((sum, axis) => add(sum, times(axis, snapTo(dot(move, axis), step))), [0, 0, 0]);
} else move = move.map((v) => snapTo(v, step));
}
return move;
}
function typedMove(s, value) {
const c = s.constraint;
if (c?.kind === "axis") return times(axisOf(s, c), value);
// Unlocked, a typed number moves along X (along Y when the lock leaves X out).
const name = c?.kind === "plane" && c.axis === "x" ? "y" : "x";
return times(c ? axisOf(s, { ...c, kind: "axis", axis: name }) : AXES[name], value);
}
function update() {
const s = session;
if (!s) return;
const { ctx } = s;
const model = ctx.model;
restore(model, s.start);
const typed = parseTyped(s.typed);
const Q = model.quaternion.constructor;
const q0 = new Q().fromArray(s.start.q);
let value;
if (s.mode === "grab") {
const move = typed != null ? typedMove(s, typed) : moveFromMouse(s);
model.position.fromArray(add(s.start.p, move));
value = move;
s.along = s.constraint?.kind === "axis" ? dot(move, axisOf(s, s.constraint)) : null;
} else if (s.mode === "rotate") {
let turn;
if (s.trackball && typed == null) {
const camera = ctx.camera;
const up = V(ctx, 0, 1, 0).applyQuaternion(camera.quaternion);
const right = V(ctx, 1, 0, 0).applyQuaternion(camera.quaternion);
const dx = s.mouse[0] - s.origin[0];
const dy = s.mouse[1] - s.origin[1];
turn = new Q().setFromAxisAngle(up, dx * TRACKBALL).multiply(new Q().setFromAxisAngle(right, dy * TRACKBALL));
value = [dx * TRACKBALL / DEG, dy * TRACKBALL / DEG];
} else {
const toCamera = times(viewDir(ctx), -1);
let axis = axisOf(s, s.constraint?.kind === "axis" ? s.constraint : null) ?? toCamera;
if (s.constraint?.kind === "plane") axis = axisOf(s, s.constraint);
// Follow the mouse round on screen: flip when the axis points away.
const sign = dot(axis, toCamera) < 0 ? -1 : 1;
let degrees = typed != null ? typed : (s.turn / DEG) * sign;
if (typed == null && s.snap) degrees = snapTo(degrees, snapStep("rotate", s.precise));
turn = new Q().setFromAxisAngle(V(ctx, ...axis), degrees * DEG);
value = degrees;
}
model.quaternion.copy(turn.clone().multiply(q0));
// Keep the model's middle where it was.
const offset = V(ctx, ...s.fromPivot).applyQuaternion(model.quaternion);
model.position.fromArray(sub(s.centre, offset.toArray()));
} else {
const d0 = Math.hypot(s.origin[0] - s.centreScreen[0], s.origin[1] - s.centreScreen[1]);
const d1 = Math.hypot(s.mouse[0] - s.centreScreen[0], s.mouse[1] - s.centreScreen[1]);
let factor = typed != null ? typed : d0 > 2 ? d1 / d0 : 1;
if (typed == null && s.snap) factor = snapTo(factor, snapStep("scale", s.precise));
if (Math.abs(factor) < 1e-4) factor = 1e-4;
let index = 0;
if (s.constraint) {
index = s.constraint.space === "local"
? AXIS_NAMES.indexOf(s.constraint.axis)
: nearestLocalAxis(localAxes(ctx, q0), AXES[s.constraint.axis]);
}
const factors = scaleFactors(factor, s.constraint, index);
model.scale.fromArray(s.start.s.map((v, i) => v * factors[i]));
// fromPivot is in the model's turned frame, before its size: scale it
// by the change and turn it back to keep the middle in place.
const offset = V(ctx, ...s.fromPivot).multiply(V(ctx, ...factors)).applyQuaternion(q0);
model.position.fromArray(sub(s.centre, offset.toArray()));
value = factor;
}
model.updateMatrixWorld(true);
s.value = value;
drawHead(s);
drawLines(s);
redraw(ctx);
}
const esc = (text) => String(text).replace(/[<>&]/g, "");
// The keys Blender's status bar lists while a move runs.
const BAR_KEYS = {
grab: [["LMB", "Confirm"], ["RMB", "Cancel"], ["X Y Z", "Axis"], ["⇧ X Y Z", "Plane"], ["MMB", "Auto lock"], ["C", "Clear"], ["Ctrl", "Snap"], ["⇧", "Precise"]],
rotate: [["LMB", "Confirm"], ["RMB", "Cancel"], ["X Y Z", "Axis"], ["MMB", "Auto lock"], ["C", "Clear"], ["R", "Trackball"], ["Ctrl", "Snap"], ["⇧", "Precise"]],
scale: [["LMB", "Confirm"], ["RMB", "Cancel"], ["X Y Z", "Axis"], ["⇧ X Y Z", "Plane"], ["MMB", "Auto lock"], ["C", "Clear"], ["Ctrl", "Snap"], ["⇧", "Precise"]],
};
// Blender's header line: one tight line at the top-left of the view, under
// the viewer's menu bar; the keys sit in a status strip at the bottom-left.
function drawHead(s) {
const mode = s.mode === "rotate" && s.trackball && !s.typed ? "trackball" : s.mode;
let amount;
if (s.typed) {
const label = { grab: "D:", rotate: "Rot:", scale: "Scale:" }[s.mode];
amount = `${label} <span class="typed">${esc(s.typed)}|</span>`;
} else amount = esc(readout(mode, s.value, s.constraint, s.along));
let lock = "";
if ((s.auto || s.waiting) && !s.constraint) lock = `<span class="pick">pick an axis: slide the mouse along it</span>`;
else if (s.constraint) lock = `<span class="lock ${s.constraint.kind === "axis" ? s.constraint.axis : ""}">${esc(constraintLabel(s.constraint))}</span>`;
else if (s.mode === "rotate" && mode !== "trackball") lock = `<span class="lock">around the view</span>`;
s.head.innerHTML = `${amount}${lock ? ` &nbsp;${lock}` : ""}${s.snap ? " &nbsp;· snap" : ""}`;
const layout = s.ctx.box.__ausbossLayout;
s.head.style.top = `${(layout?.base ?? 40) + 6}px`;
if (s.bar.dataset.mode !== s.mode) {
s.bar.dataset.mode = s.mode;
s.bar.innerHTML = BAR_KEYS[s.mode].map(([key, what]) => `<span><kbd>${key}</kbd>${what}</span>`).join("");
}
const line = bottomButtons(s.ctx.host);
s.bar.style.bottom = `${line ? line.bottom + Math.max(0, (line.height - 20) / 2) : 8}px`;
}
// Blender's guides: the locked axis as a line through the model's middle,
// and for R and S a dashed line from the middle to the mouse. While the
// middle button picks, all three axes show and the picked one is bright.
function drawLines(s) {
const { ctx, lines } = s;
const host = ctx.host;
const width = host.offsetWidth;
const height = host.offsetHeight;
const ratio = window.devicePixelRatio || 1;
if (lines.width !== Math.round(width * ratio) || lines.height !== Math.round(height * ratio)) {
lines.width = Math.round(width * ratio);
lines.height = Math.round(height * ratio);
}
const g = lines.getContext("2d");
if (!g) return;
g.setTransform(1, 0, 0, 1, 0, 0);
g.clearRect(0, 0, lines.width, lines.height);
const rect = host.getBoundingClientRect();
const k = width ? rect.width / width : 1;
g.setTransform(ratio / k, 0, 0, ratio / k, -rect.left * ratio / k, -rect.top * ratio / k);
const frame = frameOf(ctx);
const centre = s.mode === "grab" ? add(s.centre, s.value) : s.centre;
const middle = screenOf(ctx, frame, centre);
const reach = Math.max(1, Math.hypot(...sub(ctx.camera.position.toArray(), centre))) * 4;
const axisLine = (name, space, strong = true) => {
const axis = axisOf(s, { axis: name, space });
let a = null, b = null;
for (let r = reach; r > 1e-3 && !(a?.front && b?.front); r /= 2) {
a = screenOf(ctx, frame, add(centre, times(axis, r)));
b = screenOf(ctx, frame, add(centre, times(axis, -r)));
}
if (!a?.front || !b?.front) return;
g.strokeStyle = AXIS_COLOR[name];
g.lineWidth = (strong ? 1.5 : 1) * k;
g.globalAlpha = strong ? 0.9 : 0.45;
g.beginPath();
g.moveTo(...a.at);
g.lineTo(...b.at);
g.stroke();
};
const c = s.constraint;
const picking = !!(s.auto || s.waiting);
const on = (name) => !!c && (c.kind === "axis" ? name === c.axis : name !== c.axis);
if (picking) for (const name of AXIS_NAMES) axisLine(name, c?.space ?? "global", on(name));
else if (c) for (const name of AXIS_NAMES) if (on(name)) axisLine(name, c.space);
if (middle.front) {
g.globalAlpha = 1;
if (s.mode !== "grab" || s.auto) {
g.setLineDash([4 * k, 4 * k]);
g.strokeStyle = "rgba(255,255,255,.75)";
g.lineWidth = 1 * k;
g.beginPath();
g.moveTo(...middle.at);
g.lineTo(...s.real);
g.stroke();
g.setLineDash([]);
}
g.fillStyle = T.brand;
g.beginPath();
g.arc(middle.at[0], middle.at[1], 3 * k, 0, Math.PI * 2);
g.fill();
}
}
// ------------------------------------------------------------ one-shot keys
// Back to how the model was loaded: the core's gizmo keeps that, else the
// first sight of it here.
function clear(ctx, what) {
const model = ctx.model;
const before = snapshot(model);
const gizmo = ctx.sceneManager.scene?.__ausbossGizmo;
const loaded = gizmo?.targetObject === model && gizmo.initialPosition && gizmo.initialScale
? { p: gizmo.initialPosition.toArray(), s: gizmo.initialScale.toArray() }
: historyOf(model).first;
if (what === "place") model.position.fromArray(loaded.p);
if (what === "turn") model.quaternion.set(0, 0, 0, 1);
if (what === "size") model.scale.fromArray(loaded.s);
model.updateMatrixWorld(true);
remember(model, before);
settled(ctx);
}
function undo(ctx, redo) {
const model = ctx.model;
const history = histories.get(model);
const from = redo ? history?.redo : history?.undo;
if (!from?.length) return false;
const now = snapshot(model);
restore(model, from.pop());
(redo ? history.undo : history.redo).push(now);
settled(ctx);
return true;
}
function orbitTarget(ctx) {
return ctx.controls?.target ?? V(ctx, ...(ctx.model ? centreOf(ctx.model).centre : [0, 0, 0]));
}
function lookFrom(ctx, direction) {
const camera = ctx.camera;
const target = orbitTarget(ctx);
const distance = camera.position.distanceTo(target) || 5;
let d = V(ctx, ...direction).normalize();
// Orbit controls cannot look straight along their up axis.
if (Math.abs(d.y) > 0.999) d = V(ctx, 0, Math.sign(d.y), 1e-4).normalize();
camera.position.copy(target).addScaledVector(d, distance);
camera.lookAt(target);
ctx.controls?.update?.();
redraw(ctx);
}
function orbit(ctx, left, up) {
const controls = ctx.controls;
if (!controls?._rotateLeft) return;
if (left) controls._rotateLeft(left);
if (up) controls._rotateUp(up);
controls.update();
redraw(ctx);
}
function frameModel(ctx) {
if (!ctx.model) return;
const { centre, radius } = centreOf(ctx.model);
const camera = ctx.camera;
const target = V(ctx, ...centre);
const direction = camera.position.clone().sub(orbitTarget(ctx)).normalize();
if (camera.isPerspectiveCamera) {
const fov = Math.min(camera.fov, camera.fov * (camera.aspect || 1)) * DEG;
const distance = (radius / Math.sin(fov / 2)) * 1.05;
camera.position.copy(target).addScaledVector(direction.lengthSq() ? direction : V(ctx, 0, 0, 1), distance);
} else {
camera.position.copy(target).addScaledVector(direction.lengthSq() ? direction : V(ctx, 0, 0, 1), radius * 4);
const span = Math.min(camera.right - camera.left, camera.top - camera.bottom) || 2;
camera.zoom = span / (radius * 2.1);
camera.updateProjectionMatrix();
}
ctx.controls?.target?.copy?.(target);
camera.lookAt(target);
ctx.controls?.update?.();
redraw(ctx);
}
// Blender's numpad, also on the top-row digits for keyboards without one.
const NUMPAD = {
1: (ctx, other) => lookFrom(ctx, other ? [0, 0, -1] : [0, 0, 1]),
3: (ctx, other) => lookFrom(ctx, other ? [-1, 0, 0] : [1, 0, 0]),
7: (ctx, other) => lookFrom(ctx, other ? [0, -1, 0] : [0, 1, 0]),
9: (ctx) => { const target = orbitTarget(ctx); lookFrom(ctx, ctx.camera.position.clone().sub(target).multiplyScalar(-1).toArray()); },
4: (ctx) => orbit(ctx, ORBIT_STEP, 0),
6: (ctx) => orbit(ctx, -ORBIT_STEP, 0),
8: (ctx) => orbit(ctx, 0, ORBIT_STEP),
2: (ctx) => orbit(ctx, 0, -ORBIT_STEP),
};
const digitOf = (code) => /^(?:Numpad|Digit)(\d)$/.exec(code)?.[1] ?? null;
// ------------------------------------------------------------ the keys sheet
const SHEET = [
["Mouse over the view"],
["G", "move the model"], ["R", "rotate it (R again: trackball)"], ["S", "scale it"],
["X Y Z", "lock to an axis; again: its own axis"], ["Shift X Y Z", "lock to a plane"],
["Middle click", "lock to the axis you move along"], ["Middle hold", "slide along an axis to lock it (Shift: plane)"],
["C", "unlock"],
["Shift", "slower"], ["Ctrl", "snap"], ["0-9 . -", "type an exact amount"],
["Click / Enter", "keep"], ["Esc / right-click", "cancel"],
["Any time"],
["Alt G / R / S", "put back place, turn, size"], ["Ctrl Z", "undo (Shift: redo)"],
["1 3 7", "front, right, top (Ctrl: other side)"], ["2 4 6 8", "orbit 15°"], ["9", "other side"],
["Home", "frame the model"], ["Middle drag", "orbit (Shift: pan)"], ["N", "the 360 strip"],
];
const KEY_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><rect x="2.5" y="6" width="19" height="12" rx="2"/><path d="M6 10h.01M9.5 10h.01M13 10h.01M16.5 10h.01M7.5 14h9"/></svg>';
function addSheetButton(box) {
const tools = box.__ausbossTools?.tools;
if (!tools || tools.__ausbossKeys) return;
tools.__ausbossKeys = true;
const button = document.createElement("button");
button.type = "button";
button.title = "Blender keys: G move, R rotate, S scale. Click for the list.";
button.innerHTML = KEY_ICON;
let sheet = null;
const close = () => { sheet?.remove(); sheet = null; button.classList.remove("on"); };
button.addEventListener("pointerdown", (event) => event.stopPropagation());
button.addEventListener("click", (event) => {
event.stopPropagation();
if (sheet) { close(); return; }
sheet = document.createElement("div");
sheet.className = "ausboss-vkeys-sheet";
for (const [key, what] of SHEET) {
if (what == null) { const h = document.createElement("div"); h.className = "h"; h.textContent = key; sheet.append(h); continue; }
const kbd = document.createElement("kbd");
kbd.textContent = key;
const span = document.createElement("span");
span.textContent = what;
sheet.append(kbd, span);
}
for (const type of ["pointerdown", "mousedown"]) sheet.addEventListener(type, (e) => e.stopPropagation());
sheet.style.top = tools.style.top || "120px";
sheet.style.right = `${parseFloat(getComputedStyle(tools).right) + tools.offsetWidth + 8}px`;
box.parentElement.append(sheet);
button.classList.add("on");
});
document.addEventListener("pointerdown", (event) => { if (sheet && !sheet.contains(event.target) && event.target !== button) close(); }, true);
tools.append(button);
}
// Middle mouse orbits, Shift+middle pans: three's orbit controls pan when a
// rotate drag starts with Shift held.
function blenderMouse(box) {
const controls = box.__ausbossManager?.getControls?.();
if (!controls?.mouseButtons || controls.__ausbossMiddle) return;
controls.__ausbossMiddle = true;
controls.mouseButtons.MIDDLE = 0; // THREE.MOUSE.ROTATE
}
// ------------------------------------------------------------ events
// ComfyUI's own undo listens to every key before any extension can, and
// Ctrl+Z there reloads the whole graph. It stays quiet while the mask
// editor is open; the same check keeps it quiet while the mouse is over a
// viewer whose model has moves to undo, or while a move runs, so Ctrl+Z
// undoes the move and nothing else. Anywhere else it is ComfyUI's.
let holdGraphUndo = false;
function quietGraphUndo() {
const App = app?.constructor;
if (!App || App.__ausbossKeysQuiet) return;
const original = App.maskeditor_is_opended;
try {
App.maskeditor_is_opended = function (...args) {
return holdGraphUndo || (typeof original === "function" ? original.apply(this, args) : false);
};
App.__ausbossKeysQuiet = true;
} catch { /* then Ctrl+Z over a viewer also undoes the graph */ }
}
function hasHistory(box) {
const model = box?.__ausbossScene ? modelIn(box.__ausbossScene) : null;
const history = model ? histories.get(model) : null;
return !!(history && (history.undo.length || history.redo.length));
}
const typing = () => {
const el = document.activeElement;
return !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
};
const stop = (event) => { event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); };
function onKeyDown(event) {
if (session) {
const s = session;
const code = event.code;
if (code === "Escape") { stop(event); finish(false); return; }
if (code === "Enter" || code === "NumpadEnter" || code === "Space") { stop(event); finish(true); return; }
if (event.key === "Shift" || event.key === "Control") {
s.precise = event.shiftKey; s.snap = event.ctrlKey;
update();
return;
}
const letter = /^Key([A-Z])$/.exec(code)?.[1]?.toLowerCase();
if (letter && "xyz".includes(letter)) {
stop(event);
s.waiting = null;
if (s.auto) s.auto.moved = true; // the key's lock stays when the middle button comes up
s.constraint = nextConstraint(s.constraint, letter, event.shiftKey);
update();
return;
}
if (letter === "c" && !event.ctrlKey) { stop(event); s.constraint = null; s.waiting = null; s.auto = null; update(); return; }
if (letter === "g") { stop(event); switchMode("grab"); return; }
if (letter === "r") { stop(event); switchMode("rotate"); return; }
if (letter === "s") { stop(event); switchMode("scale"); return; }
const typedKey = code === "Backspace" ? "Backspace"
: code === "Minus" || code === "NumpadSubtract" ? "-"
: code === "Period" || code === "NumpadDecimal" ? "."
: digitOf(code);
if (typedKey) {
stop(event);
s.typed = event.ctrlKey && code === "Backspace" ? "" : typeKey(s.typed, typedKey);
update();
return;
}
// Everything else waits until the move is done.
if (!/^F\d+$/.test(event.key)) stop(event);
return;
}
if (event.repeat && !/^(?:Numpad|Digit)/.test(event.code)) return;
if (typing() || !pointer || event.metaKey) return;
const box = viewerAt(pointer[0], pointer[1]);
if (!box) return;
const code = event.code;
const letter = /^Key([A-Z])$/.exec(code)?.[1]?.toLowerCase();
const plain = !event.ctrlKey && !event.altKey && !event.shiftKey;
if (plain && (letter === "g" || letter === "r" || letter === "s")) {
const mode = { g: "grab", r: "rotate", s: "scale" }[letter];
if (begin(mode, box, pointer)) { holdGraphUndo = true; stop(event); }
return;
}
if (plain && letter === "n" && box.__ausbossPano?.toggle) { stop(event); box.__ausbossPano.toggle(); return; }
const ctx = contextOf(box);
if (!ctx) return;
if (event.altKey && !event.ctrlKey && ctx.model && (letter === "g" || letter === "r" || letter === "s")) {
stop(event);
clear(ctx, { g: "place", r: "turn", s: "size" }[letter]);
return;
}
if (event.ctrlKey && !event.altKey && ctx.model && (letter === "z" || letter === "y")) {
if (undo(ctx, letter === "y" || event.shiftKey)) stop(event);
return;
}
if (!event.altKey && !event.shiftKey && (code === "Home" || code === "NumpadDecimal")) { stop(event); frameModel(ctx); return; }
const digit = digitOf(code);
if (digit && NUMPAD[digit] && !event.altKey && !event.shiftKey && (!event.ctrlKey || "137".includes(digit))) {
stop(event);
NUMPAD[digit](ctx, event.ctrlKey);
}
}
function onKeyUp(event) {
if (!session) return;
if (event.key === "Shift" || event.key === "Control") {
session.precise = event.shiftKey;
session.snap = event.ctrlKey;
update();
}
}
function onPointerMove(event) {
pointer = [event.clientX, event.clientY];
const s = session;
if (!s) {
holdGraphUndo = hasHistory(viewerAt(pointer[0], pointer[1]));
return;
}
holdGraphUndo = true;
const scale = event.shiftKey ? 0.1 : 1;
s.mouse[0] += (event.clientX - s.real[0]) * scale;
s.mouse[1] += (event.clientY - s.real[1]) * scale;
if (s.mode === "rotate") {
// Count whole turns: the angle grows past 180 degrees as the mouse circles.
s.turn += screenTurn(s.centreScreen, s.lastMouse ?? s.origin, s.mouse);
s.lastMouse = [...s.mouse];
}
s.real = [event.clientX, event.clientY];
s.precise = event.shiftKey;
s.snap = event.ctrlKey;
if (s.auto) {
// A left click while the middle button is held keeps the move (the
// browser sends no pointerdown for a second button); a middle release
// missed outside the window ends the pick.
if (event.buttons & 1) { stop(event); swallowUntil = performance.now() + 600; finish(true); return; }
if (!(event.buttons & 4)) middleUp();
}
const lockWas = s.constraint;
middleMove(s);
if (!s.typed || s.constraint !== lockWas) update(); else drawLines(s);
}
function onPointerDown(event) {
if (!session) return;
stop(event);
// The middle button picks a lock from the mouse, as in Blender.
if (event.button === 1) { middleDown(event.shiftKey); return; }
swallowUntil = performance.now() + 600;
finish(event.button === 0);
}
function onPointerUp(event) {
if (!session || event.button !== 1) return;
stop(event);
// The auxclick and mouseup that follow are swallowed while the move runs.
middleUp();
}
function swallow(event) {
if (session || performance.now() < swallowUntil) {
stop(event);
if (event.type === "click" || event.type === "contextmenu") swallowUntil = 0;
}
}
function scan() {
patchGizmoManager();
quietGraphUndo();
for (const box of document.querySelectorAll("div[data-ausboss-gizmo]")) {
if (!box.__ausbossManager) continue;
addSheetButton(box);
blenderMouse(box);
const model = box.__ausbossScene ? modelIn(box.__ausbossScene) : null;
if (model) historyOf(model);
}
}
app.registerExtension({
name: "ausboss.viewer_keys",
setup() {
ensureCss();
window.addEventListener("keydown", onKeyDown, true);
window.addEventListener("keyup", onKeyUp, true);
window.addEventListener("pointermove", onPointerMove, true);
window.addEventListener("pointerdown", onPointerDown, true);
window.addEventListener("pointerup", onPointerUp, true);
for (const type of ["pointerup", "mouseup", "click", "auxclick", "contextmenu", "mousedown"]) window.addEventListener(type, swallow, true);
window.addEventListener("blur", () => finish(false));
setInterval(scan, 800);
},
});
+915
View File
@@ -0,0 +1,915 @@
// A strip for ComfyUI's 3D viewers that drops down under the viewer's menu
// bar, Blender-style, from a small "360" tab hanging under the bar's left
// end (the bar itself is full at a normal node width), so it never covers
// the frame. Its tabs:
// - Model: spin, tip and lean the model itself (saved with the shot, so
// the run's 3D shot follows).
// - Angle: turn, tilt and roll the 360 background, and its own field of
// view, and whether the 360 moves as the camera orbits (as the viewer
// draws it) or stays fixed in the frame like a photo backdrop.
// - Backdrop: the 360's brightness and blur.
// - Light: the studio lights, no light (the model's colours exactly as in
// the photo), or the 360 itself.
// - Colour: the model's brightness, contrast, saturation and warmth.
// The settings ride in the node's properties ("AusBoss View"), so they come
// back with the workflow. Nothing here touches a widget or the prompt.
// The floor grid sits at the model's feet (its lowest point, the shadow's
// floor), so the model stands on it instead of being cut through the middle.
//
// How: SceneManager.renderBackground runs once per frame before the scene.
// While a 360 setting is off its default, this file draws the panorama
// itself (three's own background drawing, in a scene of its own seen
// through a copy of the camera, which faces one fixed way when the 360 is
// fixed) and clears scene.background so the core's sky is not drawn twice.
// At its defaults the core's own sky is left alone. The look settings patch
// the model's standard materials with a colour grade, once one is used.
import { app } from "../../../scripts/app.js";
import { BRAND } from "../shared/index.mjs";
import { makeScrubInput, scrubbedValue } from "../shared/scrub_input.mjs";
import { menuBarBottom } from "../shared/viewer3d_layout.mjs";
import { FONT_UI, RADIUS_CONTROL, RADIUS_XS, THEME as T } from "../shared/theme.mjs";
const PROP = "AusBoss View";
const CSS_ID = "ausboss-viewer-pano-css";
const SCAN_MS = 800;
export const SKY_DEFAULTS = Object.freeze({ turn: 0, tilt: 0, roll: 0, fov: null, bright: 100, blur: 0, orbit: "moves", shadow: 0 });
export const ORBITS = Object.freeze(["moves", "fixed"]);
export const LIGHTS = Object.freeze(["studio", "photo", "360"]);
export const LOOK_DEFAULTS = Object.freeze({ light: "studio", strength: 100, bright: 100, contrast: 100, saturation: 100, warmth: 0 });
const ICONS = {
sky: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><circle cx="12" cy="12" r="8.5"/><ellipse cx="12" cy="12" rx="3.6" ry="8.5"/><path d="M3.5 12h17"/></svg>',
};
const isDefault = (values, defaults) => Object.keys(defaults).every((key) => values[key] === defaults[key]);
const DEG = Math.PI / 180;
// ---------------------------------------------------------------- the sky
// The 360 is drawn by three itself, the same way the viewer draws it, in a
// scene of its own and through a copy of the camera. The copy can have its
// own field of view, so the 360 can be wider or narrower than the shot.
function makeSky(manager) {
const scene = new manager.scene.constructor();
return { scene, camera: null };
}
function skyActive(manager, sky) {
return manager.backgroundRenderMode === "panorama"
&& manager.currentBackgroundType === "image"
&& !!manager.backgroundTexture
&& !isDefault(sky, SKY_DEFAULTS);
}
// The way the camera faced when the 360 was fixed, as a quaternion.
function fixedView(sky) {
const view = sky.view;
return Array.isArray(view) && view.length === 4 && view.every(Number.isFinite) ? view : [0, 0, 0, 1];
}
function drawSky(manager, state) {
const camera = manager.getActiveCamera?.();
const texture = manager.backgroundTexture;
if (!camera?.isPerspectiveCamera || !texture?.image) return false;
state.sky ??= makeSky(manager);
const sky = state.sky;
const values = state.values.sky;
camera.updateMatrixWorld();
sky.camera = sky.camera ? sky.camera.copy(camera) : camera.clone();
// The viewer draws the background into the letterboxed frame, so the
// copy covers exactly that frame.
sky.camera.clearViewOffset();
// Fixed: the copy always faces the same way, so orbiting the model leaves
// the 360 where it is in the frame.
// It holds the way the camera faced when the 360 was fixed.
if (values.orbit === "fixed") {
sky.camera.quaternion.fromArray(fixedView(values));
sky.camera.updateMatrixWorld();
}
sky.camera.fov = values.fov ?? camera.fov;
sky.camera.updateProjectionMatrix();
sky.scene.background = texture;
sky.scene.backgroundRotation?.set?.(values.tilt * DEG, values.turn * DEG, values.roll * DEG, "ZXY");
sky.scene.backgroundIntensity = values.bright / 100;
sky.scene.backgroundBlurriness = Math.min(1, values.blur / 100);
manager.scene.background = null;
manager.renderer.render(sky.scene, sky.camera);
return true;
}
// ------------------------------------------------------------- the shadow
// A soft shadow on the floor under the model, so it stands on the 360
// instead of floating in front of it. The floor is the model's lowest point;
// the shadow covers what touches it (the lowest tenth of the model). It is
// drawn with the backdrop, before the model, so the model covers it. Pause
// for Shot draws the same shadow into the run's backdrop
// (nodes/_backdrop_helpers.py, shadow_alpha), from the patch measured here.
const SHADOW_RINGS = 16;
const SHADOW_SIDES = 48;
const GROUND_SAMPLES = 60000;
// The same curve as shadow_falloff in nodes/_backdrop_helpers.py.
export const shadowFalloff = (distance) => {
const inside = Math.min(1, Math.max(0, 1 - distance * distance));
return inside * inside;
};
// The floor patch under the model, in the viewer's world: the floor height
// `y`, the middle `cx`, `cz` and the half sizes `rx`, `rz`.
export function groundPatch(points) {
let low = Infinity;
let high = -Infinity;
for (let i = 1; i < points.length; i += 3) { low = Math.min(low, points[i]); high = Math.max(high, points[i]); }
if (!Number.isFinite(low)) return null;
const tall = Math.max(high - low, 1e-6);
const band = low + tall * 0.1;
let x0 = Infinity; let x1 = -Infinity; let z0 = Infinity; let z1 = -Infinity;
for (let i = 0; i < points.length; i += 3) {
if (points[i + 1] > band) continue;
x0 = Math.min(x0, points[i]); x1 = Math.max(x1, points[i]);
z0 = Math.min(z0, points[i + 2]); z1 = Math.max(z1, points[i + 2]);
}
const margin = tall * 0.08;
return { y: low, cx: (x0 + x1) / 2, cz: (z0 + z1) / 2, rx: (x1 - x0) / 2 * 1.2 + margin, rz: (z1 - z0) / 2 * 1.2 + margin };
}
// Measured again only when the model or its turn changes.
function measureGround(model, state) {
model.updateMatrixWorld(true);
const key = `${model.uuid}:${model.matrixWorld.elements.map((v) => v.toFixed(5)).join(",")}`;
if (state.groundKey === key) return state.ground;
const meshes = [];
let count = 0;
model.traverse((part) => {
const position = part.isMesh && part.visible ? part.geometry?.attributes?.position : null;
if (position?.count) { meshes.push([part, position]); count += position.count; }
});
const stride = Math.max(1, Math.ceil(count / GROUND_SAMPLES));
const points = [];
for (const [part, position] of meshes) {
const e = part.matrixWorld.elements;
for (let i = 0; i < position.count; i += stride) {
const x = position.getX(i); const y = position.getY(i); const z = position.getZ(i);
points.push(e[0] * x + e[4] * y + e[8] * z + e[12], e[1] * x + e[5] * y + e[9] * z + e[13], e[2] * x + e[6] * y + e[10] * z + e[14]);
}
}
state.groundKey = key;
state.ground = groundPatch(points);
return state.ground;
}
// A disc of radius 1, black, its alpha falling off by shadowFalloff. Built
// from the classes of the viewer's own background plane.
function makeShadow(manager) {
const plane = manager.backgroundMesh;
const Material = manager.backgroundColorMaterial?.constructor;
const Attribute = plane?.geometry?.attributes?.position?.constructor;
if (!plane || !Material || !Attribute) return null;
const geometry = new plane.geometry.constructor();
const positions = [0, 0, 0];
const colors = [0, 0, 0, 1];
const index = [];
for (let ring = 1; ring <= SHADOW_RINGS; ring += 1) {
const r = ring / SHADOW_RINGS;
for (let side = 0; side < SHADOW_SIDES; side += 1) {
const a = (side / SHADOW_SIDES) * Math.PI * 2;
positions.push(Math.cos(a) * r, 0, Math.sin(a) * r);
colors.push(0, 0, 0, shadowFalloff(r));
const here = 1 + (ring - 1) * SHADOW_SIDES + side;
const next = 1 + (ring - 1) * SHADOW_SIDES + ((side + 1) % SHADOW_SIDES);
if (ring === 1) index.push(0, next, here);
else index.push(here - SHADOW_SIDES, next - SHADOW_SIDES, here, next - SHADOW_SIDES, next, here);
}
}
for (const name of Object.keys(geometry.attributes)) geometry.deleteAttribute(name);
geometry.setAttribute("position", new Attribute(positions, 3));
geometry.setAttribute("color", new Attribute(colors, 4));
geometry.setIndex(index);
const material = new Material({ color: 0xffffff, vertexColors: true, transparent: true, depthWrite: false, depthTest: false, side: 2 });
const mesh = new plane.constructor(geometry, material);
const scene = new manager.scene.constructor();
scene.add(mesh);
return { scene, mesh, camera: null };
}
function drawShadow(manager, state) {
const strength = state.values.sky.shadow;
if (!(strength > 0)) return;
const camera = manager.getActiveCamera?.();
const model = modelOf(manager);
if (!camera || !model) return;
const ground = measureGround(model, state);
if (!ground) return;
state.shadow ??= makeShadow(manager);
const shadow = state.shadow;
if (!shadow) return;
camera.updateMatrixWorld();
if (camera.position.y <= ground.y) return;
shadow.mesh.position.set(ground.cx, ground.y, ground.cz);
shadow.mesh.scale.set(ground.rx, 1, ground.rz);
shadow.mesh.material.opacity = Math.min(1, strength / 100);
shadow.mesh.updateMatrixWorld();
shadow.camera = shadow.camera ? shadow.camera.copy(camera) : camera.clone();
// With a picture behind, the viewer draws the backdrop into the
// letterboxed frame (see drawSky); otherwise into the whole view through
// the camera's own offset.
if (manager.currentBackgroundType === "image") shadow.camera.clearViewOffset?.();
manager.renderer.render(shadow.scene, shadow.camera);
}
// The viewer's grid lies at height 0, and many models (TRELLIS among them)
// are centred there, so the grid ran through the middle of the person. It
// goes to the floor the shadow uses instead, and back to 0 with no model.
// Only the grid moves: the model, the camera and the run stay as they were.
// While the viewer captures a run's pictures, the grid goes back to 0:
// Load3D's image is captured with the grid in it when the grid is shown,
// and that picture stays exactly what ComfyUI alone would make.
export function gridHeight(ground) {
return Number.isFinite(ground?.y) ? ground.y : 0;
}
function seatGrid(manager, state) {
const grid = manager.gridHelper;
if (!grid?.position || manager.__ausbossCapturing > 0) return;
const model = modelOf(manager);
const y = gridHeight(model ? measureGround(model, state) : null);
if (grid.position.y === y) return;
grid.position.y = y;
grid.updateMatrixWorld?.(true);
}
// ---------------------------------------------------------------- the look
const LOOK_FN = `
uniform vec4 abLook; // brightness, contrast, saturation, warmth
uniform float abUnlit; // 1: the model's own colours, no added light
vec3 abGradeLook(vec3 c) {
c *= abLook.x;
vec3 g = pow(max(c, 0.0), vec3(1.0 / 2.2));
g = (g - 0.5) * abLook.y + 0.5;
c = pow(max(g, 0.0), vec3(2.2));
float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
c = mix(vec3(l), c, abLook.z);
c *= vec3(1.0 + abLook.w * 0.12, 1.0 + abLook.w * 0.02, 1.0 - abLook.w * 0.12);
return c;
}
`;
// Shared by every viewer; each viewer sets the values just before it draws.
const lookUniform = { value: { x: 1, y: 1, z: 1, w: 0 } };
const unlitUniform = { value: 0 };
function patchMaterial(material) {
if (!material?.isMeshStandardMaterial || material.__ausbossLook) return;
material.__ausbossLook = true;
const before = material.onBeforeCompile;
material.onBeforeCompile = function (shader, renderer) {
before?.call(this, shader, renderer);
shader.uniforms.abLook = lookUniform;
shader.uniforms.abUnlit = unlitUniform;
if (!shader.fragmentShader.includes("abGradeLook")) {
shader.fragmentShader = LOOK_FN + shader.fragmentShader.replace(
"#include <opaque_fragment>",
"outgoingLight = abGradeLook(mix(outgoingLight, diffuseColor.rgb, abUnlit));\n#include <opaque_fragment>",
);
}
};
const key = material.customProgramCacheKey;
material.customProgramCacheKey = function () { return `${key.call(this)}|ausboss-look-v2`; };
material.needsUpdate = true;
}
// How bright a 360 is on average, so lighting the model with it gives the
// model about its own brightness: a night street lights it as much as a
// sunny one, only from other directions and in other colours.
const brightness = new WeakMap();
function meanLight(texture) {
if (brightness.has(texture)) return brightness.get(texture);
let mean = 0.18;
try {
const canvas = document.createElement("canvas");
canvas.width = 64;
canvas.height = 32;
const context = canvas.getContext("2d", { willReadFrequently: true });
context.drawImage(texture.image, 0, 0, 64, 32);
const { data } = context.getImageData(0, 0, 64, 32);
const linear = (v) => { const c = v / 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; };
let sum = 0, weights = 0;
for (let y = 0; y < 32; y += 1) {
const weight = Math.cos(((y + 0.5) / 32 - 0.5) * Math.PI);
for (let x = 0; x < 64; x += 1) {
const i = (y * 64 + x) * 4;
sum += weight * (0.2126 * linear(data[i]) + 0.7152 * linear(data[i + 1]) + 0.0722 * linear(data[i + 2]));
weights += weight;
}
}
mean = Math.max(0.005, sum / weights);
} catch { /* keep the middle value */ }
brightness.set(texture, mean);
return mean;
}
// When the 360 is fixed in the frame, its light turns with the camera: what
// lights the model from behind the camera is what the backdrop shows there.
// three turns a lookup direction by the inverse of the angles' rotation, the
// same for the backdrop and the light, so the light's rotation is the
// backdrop's lookup undone by the camera's, inverted back into angles.
function setLightTurn(manager, scene, sky) {
const rotation = scene.environmentRotation;
const camera = manager.getActiveCamera?.();
if (!rotation?.set) return;
if (!camera || sky.orbit !== "fixed") { rotation.set(sky.tilt * DEG, sky.turn * DEG, sky.roll * DEG, "ZXY"); return; }
const Euler = rotation.constructor;
const Matrix = camera.matrixWorld.constructor;
camera.updateMatrixWorld();
const backdrop = new Matrix().makeRotationFromEuler(new Euler(sky.tilt * DEG, sky.turn * DEG, sky.roll * DEG, "ZXY")).transpose()
.multiply(new Matrix().makeRotationFromQuaternion(new camera.quaternion.constructor().fromArray(fixedView(sky))));
const view = new Matrix().extractRotation(camera.matrixWorld).invert();
const angles = new Euler().setFromRotationMatrix(backdrop.multiply(view).transpose(), "ZXY");
rotation.set(angles.x, angles.y, angles.z, "ZXY");
}
function applyLook(manager, state) {
const look = state.values.look;
if (!isDefault(look, LOOK_DEFAULTS)) state.lookUsed = true;
if (!state.lookUsed) return;
if ((state.frame++ % 20) === 0 || state.dirty) {
manager.scene.traverse((child) => {
if (!child.isMesh) return;
(Array.isArray(child.material) ? child.material : [child.material]).forEach(patchMaterial);
});
}
lookUniform.value = { x: look.bright / 100, y: look.contrast / 100, z: look.saturation / 100, w: look.warmth / 100 };
unlitUniform.value = look.light === "photo" ? 1 : 0;
// Light from the 360: the panorama lights the model the way an HDRI does,
// and the studio lights are off while it is on.
const scene = manager.scene;
const sky = state.values.sky;
const from360 = look.light === "360" && manager.currentBackgroundType === "image" && manager.backgroundTexture
&& manager.backgroundRenderMode === "panorama";
const hdriOwns = scene.environment && scene.environment !== state.envTexture;
if (from360 && !hdriOwns) {
const texture = manager.backgroundTexture;
if (texture.mapping !== 303) { texture.mapping = 303; texture.needsUpdate = true; } // EquirectangularReflectionMapping
scene.environment = texture;
state.envTexture = texture;
scene.environmentIntensity = Math.min(40, (look.strength / 100) / meanLight(texture));
setLightTurn(manager, scene, sky);
scene.traverse((child) => { if (child.isLight && child.visible) { child.visible = false; child.__ausbossHidden = true; } });
} else if (state.envTexture) {
if (scene.environment === state.envTexture) scene.environment = null;
state.envTexture = null;
scene.environmentIntensity = 1;
scene.environmentRotation?.set?.(0, 0, 0, "XYZ");
scene.traverse((child) => { if (child.__ausbossHidden) { child.visible = true; child.__ausbossHidden = false; } });
}
state.dirty = false;
}
// ------------------------------------------------------- viewer registry
const managers = new Set();
function stateOf(manager) {
return (manager.__ausbossViewState ??= {
values: { sky: { ...SKY_DEFAULTS }, look: { ...LOOK_DEFAULTS } },
sky: null, skyWasOn: false, envTexture: null, lookUsed: false, frame: 0, dirty: true,
node: null, panorama: false, restored: false, lastMode: null,
});
}
// The core viewer drops a saved panorama while a workflow loads (it sets the
// background colour after the picture, which flips the mode back to flat),
// so the panel keeps its own note of it and puts it back once the picture
// is in. After that it follows the viewer's own Panorama button.
function keepPanorama(manager, state) {
if (!state.node) return;
const imageIn = manager.currentBackgroundType === "image" && !!manager.backgroundTexture;
const mode = manager.backgroundRenderMode;
if (!state.restored) {
if (!imageIn) return;
state.restored = true;
if (state.panorama && mode !== "panorama") {
manager.setBackgroundRenderMode("panorama");
state.lastMode = "panorama";
return;
}
}
if (!imageIn || mode === state.lastMode) return;
state.lastMode = mode;
const panorama = mode === "panorama";
if (panorama !== state.panorama) { state.panorama = panorama; writeSaved(state.node, state); }
}
function patchSceneManager() {
const Manager = window.comfyAPI?.SceneManager?.SceneManager;
if (!Manager) return false;
if (Manager.prototype.__ausbossView) return true;
const render = Manager.prototype.renderBackground;
Manager.prototype.renderBackground = function (...args) {
try {
seatGrid(this, stateOf(this));
} catch (error) {
console.warn("[AusBoss] 3D viewer floor grid:", error);
}
try {
managers.add(this);
const state = stateOf(this);
keepPanorama(this, state);
applyLook(this, state);
if (skyActive(this, state.values.sky)) {
if (drawSky(this, state)) { state.skyWasOn = true; drawShadow(this, state); return undefined; }
} else if (state.skyWasOn) {
// Back to the core's own sky.
state.skyWasOn = false;
if (this.backgroundRenderMode === "panorama" && this.currentBackgroundType === "image" && this.backgroundTexture) {
this.scene.background = this.backgroundTexture;
}
}
} catch (error) {
console.warn("[AusBoss] 3D viewer 360 panel:", error);
}
const out = render.apply(this, args);
try {
drawShadow(this, stateOf(this));
} catch (error) {
console.warn("[AusBoss] 3D viewer shadow:", error);
}
return out;
};
const capture = Manager.prototype.captureScene;
if (capture) {
Manager.prototype.captureScene = function (...args) {
const grid = this.gridHelper;
this.__ausbossCapturing = (this.__ausbossCapturing ?? 0) + 1;
if (grid?.position) { grid.position.y = 0; grid.updateMatrixWorld?.(true); }
// The next frame seats the grid again.
const done = () => { this.__ausbossCapturing -= 1; };
let out;
try {
out = capture.apply(this, args);
} catch (error) {
done();
throw error;
}
if (typeof out?.finally === "function") return out.finally(done);
done();
return out;
};
}
Manager.prototype.__ausbossView = true;
return true;
}
// The viewer only draws while the mouse is over it. The panel asks for a
// frame after a change, through the viewer that last drew this scene.
function patchViewport() {
const Viewport = window.comfyAPI?.Viewport3d?.Viewport3d;
if (!Viewport || Viewport.prototype.__ausbossView) return;
const main = Viewport.prototype.renderMainScene;
if (typeof main !== "function") return;
Viewport.prototype.renderMainScene = function (...args) {
if (this.sceneManager) this.sceneManager.__ausbossViewport = this;
return main.apply(this, args);
};
Viewport.prototype.__ausbossView = true;
}
function redraw(manager) {
try { manager.__ausbossViewport?.forceRender?.(); } catch { /* the next frame shows it */ }
}
function managerFor(root) {
for (const manager of managers) {
const canvas = manager.view?.canvas;
if (!canvas?.isConnected) { managers.delete(manager); continue; }
if (root.contains(canvas)) return manager;
}
return null;
}
// The graph node that owns a viewer's DOM. Nodes 2.0 marks its node
// elements with the id. The classic renderer floats the viewer over the
// canvas with nothing to name its node, so the node is the 3D node whose
// body sits under the viewer on screen.
const VIEWER_TYPES = new Set(["Preview3DAdvanced", "Preview3D", "Load3D", "Load3DAdvanced", "SaveGLB", "Preview3DAnimation"]);
function nodeFor(root) {
const nodes = app.graph?._nodes ?? [];
const id = root.closest?.("[data-node-id]")?.dataset?.nodeId;
if (id != null) {
const node = nodes.find((n) => String(n.id) === String(id));
if (node) return node;
}
const holder = root.closest?.(".dom-widget") ?? root;
const rect = holder.getBoundingClientRect();
const canvas = app.canvas?.canvas?.getBoundingClientRect?.();
const ds = app.canvas?.ds;
if (!canvas || !ds) return null;
let best = null;
for (const node of nodes) {
if (!node.widgets?.some((w) => w.type === "load3D") && !VIEWER_TYPES.has(node.type)) continue;
const left = canvas.left + (node.pos[0] + ds.offset[0]) * ds.scale;
const top = canvas.top + (node.pos[1] + ds.offset[1]) * ds.scale;
const width = node.size[0] * ds.scale;
const height = node.size[1] * ds.scale;
const inside = rect.left >= left - 4 && rect.right <= left + width + 4 && rect.top >= top - 4 && rect.top <= top + height;
const score = Math.abs(rect.left - left) + Math.abs(rect.right - (left + width)) + (inside ? 0 : 1e6);
if (!best || score < best.score) best = { node, score };
}
return best && best.score < 1e6 ? best.node : null;
}
// ---------------------------------------------------------------- strip
function ensureCss() {
if (document.getElementById(CSS_ID)) return;
const style = document.createElement("style");
style.id = CSS_ID;
style.textContent = `
.ausboss-vstrip-btn{position:absolute;left:6px;z-index:6;display:inline-flex;align-items:center;gap:5px;height:22px;padding:0 8px;border:0;border-radius:0 0 ${RADIUS_XS}px ${RADIUS_XS}px;background:rgba(16,18,20,.85);color:${T.inkSoft};font:600 11px/1 ${FONT_UI};cursor:pointer;white-space:nowrap}
.ausboss-vstrip-btn:hover{color:${BRAND}}
.ausboss-vstrip-btn.open{display:none}
.ausboss-vstrip-btn svg{width:13px;height:13px}
.ausboss-vstrip{position:absolute;left:0;right:0;z-index:6;display:none;box-sizing:border-box;padding:4px 8px 6px;background:rgba(16,18,20,.92);border-bottom:1px solid rgba(255,255,255,.07);font:400 11px/1.2 ${FONT_UI};color:${T.inkSoft};touch-action:none}
.ausboss-vstrip.open{display:block}
.ausboss-vstrip-head{display:flex;align-items:center;gap:2px;margin-bottom:4px}
.ausboss-vstrip-tab{height:20px;padding:0 9px;border:0;border-radius:${RADIUS_XS}px;background:transparent;color:${T.label};font:600 11px/1 ${FONT_UI};cursor:pointer;white-space:nowrap}
.ausboss-vstrip-tab.on{background:${T.brandSoft};color:${T.brandInk}}
.ausboss-vstrip-tab:hover{color:${T.ink}}
.ausboss-vstrip-sp{flex:1}
.ausboss-vstrip-act{height:20px;padding:0 7px;border:0;border-radius:${RADIUS_XS}px;background:${T.fill};color:${T.inkSoft};font:600 11px/1 ${FONT_UI};cursor:pointer}
.ausboss-vstrip-act:hover{background:${T.fillHover};color:${T.ink}}
.ausboss-vstrip-fields{display:flex;flex-wrap:wrap;align-items:center;gap:4px 10px;min-height:24px}
.ausboss-vstrip-field{display:flex;align-items:center;gap:5px;flex:1 1 0;min-width:112px}
.ausboss-vstrip-field>span{flex:none;color:${T.label};font-weight:600;cursor:ew-resize;user-select:none;white-space:nowrap}
.ausboss-vstrip-field>span:hover{color:${T.ink}}
.ausboss-vstrip-field>.ausboss-scrub{flex:1 1 auto;width:auto;min-width:64px}
.ausboss-vstrip-field.wide{flex:2 1 0;min-width:190px}
.ausboss-vstrip-pill{display:grid;flex:1 1 auto;height:24px;border-radius:${RADIUS_CONTROL}px;background:${T.fill};overflow:hidden}
.ausboss-vstrip-pill button{border:0;background:transparent;color:${T.label};font:600 11px/1 ${FONT_UI};cursor:pointer}
.ausboss-vstrip-pill button.on{background:${BRAND};color:${T.onBrand}}
.ausboss-vstrip-hint{color:${T.faint};font-size:11px}
.ausboss-vstrip-keys{flex:1 0 100%;font-size:10px}
`;
document.head.append(style);
}
const ANGLE = { title: "Angle", group: "sky", hint: "sky", fields: [
{ key: "turn", label: "Turn", min: -180, max: 180, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Spin the 360 around her. The camera does not move." },
{ key: "tilt", label: "Tilt", min: -180, max: 180, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Tip the 360 up or down, to level the horizon." },
{ key: "roll", label: "Roll", min: -180, max: 180, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Lean the 360 left or right, to straighten it." },
{ key: "fov", label: "FOV", min: 10, max: 150, step: 1, fineStep: 0.1, decimals: 1, unit: "°", allowEmpty: true, placeholder: "cam",
title: "How wide the 360 looks, apart from the camera. Empty follows the camera." },
{ key: "orbit", label: "Orbit", pill: ORBITS, wide: true,
title: "moves: the 360 turns as you orbit, like a real place. fixed: it stays put in the frame like a photo backdrop; only Turn, Tilt and Roll move it." },
] };
const BACKDROP = { title: "Backdrop", group: "sky", hint: "sky", fields: [
{ key: "bright", label: "Brightness", min: 0, max: 300, step: 5, fineStep: 1, decimals: 0, unit: "%", title: "Make the 360 darker or brighter." },
{ key: "blur", label: "Blur", min: 0, max: 100, step: 5, fineStep: 1, decimals: 0, unit: "%", title: "Soften the 360, like a shallow depth of field." },
{ key: "shadow", label: "Shadow", min: 0, max: 100, step: 5, fineStep: 1, decimals: 0, unit: "%",
title: "A soft shadow on the floor under her, so she stands on the 360 instead of floating. Pause for Shot puts it in the run's shot too." },
] };
const LIGHT = { title: "Light", group: "look", fields: [
{ key: "light", label: "Light", pill: LIGHTS, wide: true,
title: "studio: the viewer's own lights. photo: her colours exactly as in your picture, no added light. 360: lit by the 360 around her." },
{ key: "strength", label: "360 light", min: 0, max: 400, step: 5, fineStep: 1, decimals: 0, unit: "%", when: (look) => look.light === "360", title: "How strongly the 360 lights her." },
] };
const COLOUR = { title: "Colour", group: "look", fields: [
{ key: "bright", label: "Bright", min: 0, max: 300, step: 5, fineStep: 1, decimals: 0, unit: "%", title: "Make the model darker or brighter." },
{ key: "contrast", label: "Contrast", min: 0, max: 200, step: 5, fineStep: 1, decimals: 0, unit: "%", title: "Flatten or deepen the model's light and dark." },
{ key: "saturation", label: "Sat", min: 0, max: 200, step: 5, fineStep: 1, decimals: 0, unit: "%", title: "Saturation: less or more colour on the model." },
{ key: "warmth", label: "Warm", min: -100, max: 100, step: 5, fineStep: 1, decimals: 0, unit: "", title: "Cooler (blue) or warmer (orange) model." },
] };
// The model's own turn. These read and write the loaded model's rotation
// directly, which the viewer saves with the shot and hands to the run (its
// model_3d_info), so the 3D shot follows. Nothing extra is saved here.
const MODEL = { title: "Model", group: "model", fields: [
{ key: "spin", label: "Spin", min: -180, max: 180, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Turn the model around, left or right." },
{ key: "tip", label: "Tip", min: -90, max: 90, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Tip the model forward or back." },
{ key: "lean", label: "Lean", min: -90, max: 90, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Lean the model left or right." },
] };
const TABS = [MODEL, ANGLE, BACKDROP, LIGHT, COLOUR];
// The loaded model: the scene child with the model's standard materials.
function modelOf(manager) {
return manager.scene.children.find((child) => {
if (child.isLight || child === manager.gridHelper || !child.visible) return false;
let found = false;
child.traverse?.((part) => { if (!found && part.isMesh && part.material?.isMeshStandardMaterial) found = true; });
return found;
}) ?? null;
}
// Spin, tip and lean as one turn order (spin last), in degrees.
function readModelTurn(model) {
const euler = new model.rotation.constructor().setFromQuaternion(model.quaternion, "YXZ");
return { spin: euler.y / DEG, tip: euler.x / DEG, lean: euler.z / DEG };
}
function writeModelTurn(model, turn) {
const euler = new model.rotation.constructor(turn.tip * DEG, turn.spin * DEG, turn.lean * DEG, "YXZ");
model.quaternion.setFromEuler(euler);
model.updateMatrixWorld(true);
}
function readSaved(node, state) {
const saved = node?.properties?.[PROP];
if (node?.properties?.["Scene Config"]?.backgroundRenderMode === "panorama") state.panorama = true;
if (!saved || typeof saved !== "object") return;
if (saved.panorama === true) state.panorama = true;
for (const [group, defaults] of [["sky", SKY_DEFAULTS], ["look", LOOK_DEFAULTS]]) {
const from = saved[group] ?? {};
for (const key of Object.keys(defaults)) {
const value = from[key];
if (key === "light") { if (LIGHTS.includes(value)) state.values.look.light = value; }
else if (key === "orbit") {
if (ORBITS.includes(value)) state.values.sky.orbit = value;
if (Array.isArray(from.view)) state.values.sky.view = fixedView(from);
}
else if (key === "fov") state.values.sky.fov = Number.isFinite(value) ? value : null;
else if (Number.isFinite(value)) state.values[group][key] = value;
}
}
state.dirty = true;
}
function writeSaved(node, state) {
if (!node) return;
node.properties ??= {};
const skyDefault = isDefault(state.values.sky, SKY_DEFAULTS);
const lookDefault = isDefault(state.values.look, LOOK_DEFAULTS);
if (skyDefault && lookDefault && !state.panorama) delete node.properties[PROP];
else node.properties[PROP] = { panorama: state.panorama, sky: { ...state.values.sky }, look: { ...state.values.look } };
app.graph?.setDirtyCanvas?.(true, false);
}
function buildStrip(box, root, manager) {
const state = stateOf(manager);
const node = nodeFor(root);
readSaved(node, state);
state.node = node;
// Other panels find this viewer's box by its node (js/pause_shot).
box.__ausbossNode = node;
box.__ausbossScene = manager;
// Pause for Shot sends the floor patch with the shot, for its shadow.
manager.__ausbossGround = () => {
const model = modelOf(manager);
return model ? measureGround(model, state) : null;
};
const strip = document.createElement("div");
strip.className = "ausboss-vstrip";
for (const type of ["pointerdown", "mousedown", "dblclick", "contextmenu"]) strip.addEventListener(type, (event) => event.stopPropagation());
const head = document.createElement("div");
head.className = "ausboss-vstrip-head";
const fields = document.createElement("div");
fields.className = "ausboss-vstrip-fields";
strip.append(head, fields);
const tabButtons = TABS.map((spec) => {
const button = document.createElement("button");
button.type = "button";
button.className = "ausboss-vstrip-tab";
button.textContent = spec.title;
button.addEventListener("click", () => show(spec));
return button;
});
const spacer = document.createElement("span");
spacer.className = "ausboss-vstrip-sp";
const reset = document.createElement("button");
reset.type = "button";
reset.className = "ausboss-vstrip-act";
reset.textContent = "Reset";
reset.title = "Put this tab back to how the viewer draws it.";
const close = document.createElement("button");
close.type = "button";
close.className = "ausboss-vstrip-act";
close.textContent = "✕";
close.title = "Close";
head.append(...tabButtons, spacer, reset, close);
let tab = MODEL;
const camera = () => manager.getActiveCamera?.();
// Fixing the 360 holds what the frame shows right now.
const orbitField = ANGLE.fields.find((field) => field.key === "orbit");
orbitField.picked = (values, option) => {
const view = camera()?.quaternion;
if (option === "fixed" && view) values.view = view.toArray();
};
const has360 = () => manager.backgroundRenderMode === "panorama" && manager.currentBackgroundType === "image";
const changed = () => { state.dirty = true; writeSaved(node, state); redraw(manager); refreshWhen(); };
const rows = [];
const refreshWhen = () => rows.forEach(({ row, spec }) => { if (spec.when) row.style.display = spec.when(state.values.look) ? "" : "none"; });
function scrubField(spec, values) {
const row = document.createElement("label");
row.className = "ausboss-vstrip-field";
row.title = spec.title;
const name = document.createElement("span");
name.textContent = spec.label;
const scrub = makeScrubInput({
value: values[spec.key], min: spec.min, max: spec.max, step: spec.step, fineStep: spec.fineStep,
decimals: spec.decimals, unit: spec.unit, unitWidth: 12, title: spec.title,
allowEmpty: !!spec.allowEmpty, placeholder: spec.placeholder ?? "",
emptyStart: spec.key === "fov" ? Math.round(camera()?.fov ?? 35) : 0,
onChange: (value) => { values[spec.key] = value; changed(); },
});
// Drag the name to scrub as well, the way a 3D app's number fields work.
let drag = null;
name.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
event.preventDefault();
name.setPointerCapture(event.pointerId);
const start = values[spec.key] ?? (spec.key === "fov" ? Math.round(camera()?.fov ?? 35) : 0);
drag = { x: event.clientX, start };
});
name.addEventListener("pointermove", (event) => {
if (!drag) return;
const next = scrubbedValue(drag.start, event.clientX - drag.x, event.shiftKey, spec);
if (next === values[spec.key]) return;
values[spec.key] = next;
scrub.set(next);
changed();
});
const end = (event) => { drag = null; try { name.releasePointerCapture(event.pointerId); } catch { /* released */ } };
name.addEventListener("pointerup", end);
name.addEventListener("pointercancel", end);
name.addEventListener("click", (event) => event.preventDefault());
row.append(name, scrub.root);
return row;
}
function pillField(spec, values) {
const row = document.createElement("div");
row.className = "ausboss-vstrip-field wide";
row.title = spec.title;
const name = document.createElement("span");
name.textContent = spec.label;
name.style.cursor = "default";
const pill = document.createElement("div");
pill.className = "ausboss-vstrip-pill";
pill.style.gridTemplateColumns = `repeat(${spec.pill.length},1fr)`;
const options = spec.pill.map((option) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = option;
button.addEventListener("click", () => { values[spec.key] = option; spec.picked?.(values, option); paint(); changed(); });
pill.append(button);
return button;
});
const paint = () => options.forEach((button, i) => button.classList.toggle("on", spec.pill[i] === values[spec.key]));
paint();
row.append(name, pill);
return row;
}
function show(spec) {
tab = spec;
tabButtons.forEach((button, i) => button.classList.toggle("on", TABS[i] === spec));
fields.replaceChildren();
rows.length = 0;
const model = spec.group === "model" ? modelOf(manager) : null;
if (spec.group === "model" && !model) {
const hint = document.createElement("span");
hint.className = "ausboss-vstrip-hint";
hint.textContent = "Run the workflow to load the model first.";
fields.append(hint);
} else if (spec.hint === "sky" && !has360()) {
const hint = document.createElement("span");
hint.className = "ausboss-vstrip-hint";
hint.textContent = "Load a 360 picture with BG Image, then press Panorama.";
fields.append(hint);
} else {
let values = state.values[spec.group];
if (model) {
const turn = readModelTurn(model);
const round = (v) => Math.round(v * 10) / 10;
values = new Proxy({ spin: round(turn.spin), tip: round(turn.tip), lean: round(turn.lean) }, {
set(target, key, value) {
target[key] = value;
writeModelTurn(model, target);
return true;
},
});
}
for (const field of spec.fields) {
const row = field.pill ? pillField(field, values) : scrubField(field, values);
rows.push({ row, spec: field });
fields.append(row);
}
if (model) {
// The Blender keys (js/viewer_keys) do the rest on the model.
const hint = document.createElement("span");
hint.className = "ausboss-vstrip-hint ausboss-vstrip-keys";
hint.textContent = "Mouse over the view: G move · R rotate · S scale · X Y Z lock · Esc cancel";
fields.append(hint);
}
refreshWhen();
}
place();
}
reset.addEventListener("click", () => {
if (tab.group === "model") {
const model = modelOf(manager);
if (model) { writeModelTurn(model, { spin: 0, tip: 0, lean: 0 }); redraw(manager); }
show(tab);
return;
}
for (const field of tab.fields) state.values[tab.group][field.key] = (tab.group === "sky" ? SKY_DEFAULTS : LOOK_DEFAULTS)[field.key];
changed();
show(tab);
});
// The button in the viewer's menu bar that opens and closes the strip.
const button = document.createElement("button");
button.type = "button";
button.className = "ausboss-vstrip-btn";
button.title = "360 and light: turn the 360, its field of view, brightness, blur; light and colour the model.";
button.innerHTML = `${ICONS.sky}<span>360</span><svg viewBox="0 0 10 6" style="width:9px;height:6px"><path d="M1 1l4 4 4-4" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>`;
button.addEventListener("pointerdown", (event) => event.stopPropagation());
const toggle = (open) => {
strip.classList.toggle("open", open);
button.classList.toggle("open", open);
if (open) show(tab);
place();
};
button.addEventListener("click", (event) => { event.stopPropagation(); toggle(!strip.classList.contains("open")); });
close.addEventListener("click", () => toggle(false));
// Right under the menu bar as it is drawn (js/shared/viewer3d_layout.mjs).
function place() {
const bottom = menuBarBottom(box.parentElement);
if (bottom != null) {
const top = `${bottom}px`;
if (strip.style.top !== top) strip.style.top = top;
if (button.style.top !== top) button.style.top = top;
}
box.__ausbossTools?.place?.();
}
box.__ausbossStripHeight = () => (strip.classList.contains("open") ? strip.offsetHeight : 0);
box.parentElement.append(strip, button);
// The Model tab's numbers follow a turn made with the keys (js/viewer_keys).
const refresh = () => { if (strip.classList.contains("open") && tab.group === "model") show(tab); };
// N opens and closes it, like Blender's sidebar (js/viewer_keys).
box.__ausbossPano = { strip, place, refresh, toggle: () => toggle(!strip.classList.contains("open")) };
place();
}
// A viewer that is loaded with a workflow draws once, before this file's
// patches are in, and then only while the mouse is over its node. Until it
// draws again the strip cannot find it, so each 3D node gets one short
// "mouse over" (what the core does on hover) to make it draw a frame.
const nudged = new WeakSet();
function nudgeViewers() {
for (const node of app.graph?._nodes ?? []) {
if (nudged.has(node) || !node.widgets?.some((widget) => widget.type === "load3D")) continue;
nudged.add(node);
try {
node.onMouseEnter?.();
requestAnimationFrame(() => requestAnimationFrame(() => node.onMouseLeave?.()));
} catch { /* hover is only a nudge */ }
}
}
// A viewer that came up before its node was laid out could not tell which
// node it belongs to. Keep asking, so its saved 360 and Pause for Shot's
// Continue bar find it.
function bindLate(box) {
const node = nodeFor(box.parentElement);
const manager = box.__ausbossScene;
if (!node || !manager) return;
const state = stateOf(manager);
box.__ausbossNode = node;
state.node = node;
readSaved(node, state);
box.__ausbossPano.refresh?.();
}
function scan() {
if (!patchSceneManager()) return;
patchViewport();
let waiting = false;
for (const manager of managers) {
const state = manager.__ausbossViewState;
if (state?.node && !state.restored) { keepPanorama(manager, state); if (state.restored) redraw(manager); }
}
for (const box of document.querySelectorAll("div[data-ausboss-gizmo]")) {
if (box.__ausbossPano) {
if (!box.__ausbossNode) bindLate(box);
box.__ausbossPano.place();
continue;
}
if (!box.__ausbossTools?.tools || !box.parentElement) continue;
const manager = managerFor(box.parentElement);
if (!manager) { waiting = true; continue; }
buildStrip(box, box.parentElement, manager);
}
if (waiting) nudgeViewers();
}
app.registerExtension({
name: "ausboss.viewer_pano",
setup() {
ensureCss();
setInterval(scan, SCAN_MS);
},
});
+38
View File
@@ -0,0 +1,38 @@
// ComfyUI's 3D viewers with a frame (Preview 3D Advanced, Save 3D Advanced)
// size that frame with two plain width and height rows. This puts the shape
// chips from Latent Size above a W x H row instead: pick a shape, keep the
// megapixels, and the viewer's frame follows at once.
//
// The node is ComfyUI's own: its width and height widgets stay the source of
// truth (saved workflows, API prompts and links are untouched), the card only
// writes their values, and the sockets for the pair sit among the node's
// inputs, as on Image Resize.
import { app } from "../../../scripts/app.js";
import { chainCallback } from "../shared/index.mjs";
import { ratioChips } from "../shared/ratio_chips.mjs";
import { mountWidgetCard } from "../shared/widget_card.mjs";
import { hideInputsInDef } from "../shared/widget_visibility.mjs";
const VIEWERS = new Set(["Preview3DAdvanced", "Save3DAdvanced"]);
const CARD = {
minWidth: 300,
rows: [
{ panel: ratioChips(), height: 28 },
{ pair: ["width", "height"], label: "Size", prefixes: ["W", "H"], sep: "×", top: true, pixels: true },
],
};
app.registerExtension({
name: "ausboss.viewer_ratio",
beforeRegisterNodeDef(nodeType, nodeData) {
if (!VIEWERS.has(nodeData?.name)) return;
hideInputsInDef(nodeData, ["width", "height"]);
chainCallback(nodeType.prototype, "onNodeCreated", function () {
if (this.__ausbossCard) return;
// The viewer keeps the node's height; the card only takes its own rows.
const size = [...(this.size ?? [0, 0])];
mountWidgetCard(this, CARD);
if (size[0] && size[1]) this.setSize?.([Math.max(size[0], CARD.minWidth), Math.max(size[1], this.computeSize?.()[1] ?? 0)]);
});
},
});
+258
View File
@@ -0,0 +1,258 @@
// ComfyUI's 3D viewers, laid out like a 3D app's viewport: the axis gizmo
// moves from the bottom-left to the top-right corner (click an axis to look
// along it, as before), and a small column of tools sits under it:
// - zoom: drag up or down on the magnifier to move the camera in or out,
// - pan: drag on the hand to slide the view,
// - drag on the gizmo to orbit; a click still picks an axis view,
// - grid: show or hide the floor grid (it presses the viewer's own
// "Show grid", so the menu bar and the saved setting follow).
// Nothing is saved by this file and no widget changes; it only moves the
// camera the viewer already owns.
import { app } from "../../../scripts/app.js";
import { BRAND } from "../shared/index.mjs";
import { menuBarBottom } from "../shared/viewer3d_layout.mjs";
const CSS_ID = "ausboss-viewer-tools-css";
const SCAN_MS = 800;
// The core viewer's gizmo box: a 128 px square pinned to the bottom-left.
// Moved, it is drawn at three quarters of that size and tucked into the
// top-right corner: the axes end EDGE px from the view's right edge and
// BELOW px under the menu bar (or the open 360 strip). The square has empty
// room around the axes (PAD px at the drawn size), so the box hangs a little
// past the edge. The click area is scaled with CSS the same way, which is
// what the core's axis click reads (the box's on-screen rectangle).
const GIZMO_SCALE = 0.75;
const GIZMO_SIZE = 128 * GIZMO_SCALE;
const GIZMO_PAD = 18;
const GIZMO_EDGE = 8;
const GIZMO_BELOW = 6;
// The tools column, centred under the axes.
const TOOL_SIZE = 28;
const TOOLS_RIGHT = GIZMO_EDGE + (GIZMO_SIZE / 2 - GIZMO_PAD) - TOOL_SIZE / 2;
const TOOLS_BELOW = GIZMO_BELOW + GIZMO_SIZE - 2 * GIZMO_PAD + 10;
const isGizmoBox = (el) => el.style.position === "absolute" && el.style.width === "128px" && el.style.height === "128px"
&& el.style.bottom === "0px" && el.style.left === "0px";
const ICONS = {
zoom: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="10.5" cy="10.5" r="6"/><path d="M15 15l5.5 5.5M10.5 8v5M8 10.5h5"/></svg>',
pan: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M8 12.5V6a1.4 1.4 0 0 1 2.8 0v5.5M10.8 11V4.6a1.4 1.4 0 0 1 2.8 0V11M13.6 11V5.6a1.4 1.4 0 0 1 2.8 0V12M16.4 11.5V8.4a1.4 1.4 0 0 1 2.8 0v5.8c0 3.6-2.6 6.3-6.2 6.3h-.8c-2 0-3.4-.8-4.6-2.3l-3-4a1.45 1.45 0 0 1 2.2-1.9L8 13.6"/></svg>',
grid: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M3 9.5L21 9.5M2 14.5h20M8.5 4L5.5 20M15.5 4l3 16M4.5 5h15l2.5 14H2z"/></svg>',
};
function ensureCss() {
if (document.getElementById(CSS_ID)) return;
const style = document.createElement("style");
style.id = CSS_ID;
style.textContent = `
.ausboss-vtools{position:absolute;top:124px;right:${TOOLS_RIGHT}px;display:flex;flex-direction:column;gap:6px;z-index:5}
.ausboss-vtools button{width:${TOOL_SIZE}px;height:${TOOL_SIZE}px;padding:6px;box-sizing:border-box;border-radius:50%;border:1px solid rgba(255,255,255,.08);background:rgba(20,22,22,.72);color:#c8cccc;cursor:pointer;display:grid;place-items:center;touch-action:none}
.ausboss-vtools button svg{width:100%;height:100%;display:block}
.ausboss-vtools button:hover{color:${BRAND};border-color:${BRAND}}
.ausboss-vtools button.drag{cursor:grab}
.ausboss-vtools button.drag:active{cursor:grabbing;color:${BRAND};border-color:${BRAND}}
.ausboss-vtools button.on{color:#7fe9e2;background:rgba(0,180,170,.22);border-color:${BRAND}}
`;
document.head.append(style);
}
// The axis gizmo draws itself into the view's bottom-left corner. For a box
// this file has moved, draw it in the top-right corner instead; everything
// else is the core's own render.
function patchGizmoRender() {
const Manager = window.comfyAPI?.ViewHelperManager?.ViewHelperManager;
if (!Manager) return false;
if (Manager.prototype.__ausbossTopRight) return true;
const render = Manager.prototype.render;
Manager.prototype.render = function (renderer, size) {
const box = this.viewHelperContainer;
if (box && typeof box === "object") box.__ausbossManager = this;
const helper = this.viewHelper;
if (!box?.dataset?.ausbossGizmo || !helper?.isViewHelper || !this.savedViewport || !this.helperCamera) {
return render.call(this, renderer, size);
}
// Older frontends hand over the three.js renderer itself; newer ones
// (1.58+) a view that holds it as `.renderer` and owns the viewport.
const gl = typeof renderer?.clearDepth === "function" ? renderer : renderer?.renderer;
if (typeof gl?.clearDepth !== "function" || typeof renderer.getViewport !== "function") {
return render.call(this, renderer, size);
}
helper.quaternion.copy(this.getActiveCamera().quaternion).invert();
helper.updateMatrixWorld();
gl.clearDepth();
const { x, y, z, w } = renderer.getViewport(this.savedViewport) ?? this.savedViewport;
// Where the box is drawn on screen, in the canvas's own pixels (the
// viewport counts up from the bottom).
const width = gl.domElement?.clientWidth || x + z;
const height = gl.domElement?.clientHeight || y + w;
const top = Number(box.dataset.ausbossTop) || 0;
const right = Number(box.dataset.ausbossRight) || 0;
renderer.setViewport(width - right - GIZMO_SIZE, height - top - GIZMO_SIZE, GIZMO_SIZE, GIZMO_SIZE);
gl.render(helper, this.helperCamera);
renderer.setViewport(x, y, z, w);
};
Manager.prototype.__ausbossTopRight = true;
return true;
}
function placeGizmo(box) {
// Under the menu bar as it is drawn; the 360 strip (js/viewer_pano/) opens
// under the bar, and the gizmo and the tools step down under it.
const bar = menuBarBottom(box.parentElement);
if (bar == null) return;
const base = bar + (box.__ausbossStripHeight?.() ?? 0);
const top = base + GIZMO_BELOW - GIZMO_PAD;
const right = GIZMO_EDGE - GIZMO_PAD;
if (String(top) === box.dataset.ausbossTop && String(right) === box.dataset.ausbossRight) return;
box.dataset.ausbossTop = String(top);
box.dataset.ausbossRight = String(right);
box.style.top = `${top}px`;
box.style.right = `${right}px`;
const tools = box.__ausbossTools?.tools;
if (tools) tools.style.top = `${base + TOOLS_BELOW}px`;
box.__ausbossLayout = { base };
}
// The viewer's own "Show grid" button, found by its icon (its text is translated).
const gridButton = (root) => root?.querySelector?.('i[class*="lucide--grid-3x3"]')?.closest("button") ?? null;
function viewerRoot(box) {
let el = box.parentElement;
for (let i = 0; el && i < 12; i += 1, el = el.parentElement) if (gridButton(el)) return el;
return null;
}
function dragButton(kind, title, onDrag) {
const button = document.createElement("button");
button.type = "button";
button.className = "drag";
button.title = title;
button.innerHTML = ICONS[kind];
let last = null;
button.addEventListener("pointerdown", (event) => {
event.stopPropagation();
event.preventDefault();
button.setPointerCapture(event.pointerId);
last = [event.clientX, event.clientY];
});
button.addEventListener("pointermove", (event) => {
if (!last) return;
const dx = event.clientX - last[0], dy = event.clientY - last[1];
last = [event.clientX, event.clientY];
if (dx || dy) onDrag(dx, dy);
});
const end = (event) => { last = null; try { button.releasePointerCapture(event.pointerId); } catch { /* already released */ } };
button.addEventListener("pointerup", end);
button.addEventListener("pointercancel", end);
return button;
}
function addTools(box) {
const controls = () => box.__ausbossManager?.getControls?.();
const tools = document.createElement("div");
tools.className = "ausboss-vtools";
// Keep the graph from starting a node drag or a box select under the tools.
for (const type of ["pointerdown", "mousedown"]) tools.addEventListener(type, (event) => event.stopPropagation());
const zoom = dragButton("zoom", "Zoom: drag up to move in, down to move out.", (_dx, dy) => {
const c = controls();
if (!c?._dollyIn) return;
const scale = Math.pow(0.985, Math.abs(dy));
if (dy < 0) c._dollyIn(scale); else c._dollyOut(scale);
c.update();
});
const pan = dragButton("pan", "Pan: drag to slide the view.", (dx, dy) => {
const c = controls();
if (!c?._pan) return;
c._pan(dx, dy);
c.update();
});
const grid = document.createElement("button");
grid.type = "button";
grid.title = "Show or hide the floor grid.";
grid.innerHTML = ICONS.grid;
grid.addEventListener("pointerdown", (event) => event.stopPropagation());
grid.addEventListener("click", (event) => {
event.stopPropagation();
gridButton(viewerRoot(box))?.click();
});
// Follow the core button's pressed state as soon as it changes.
let watched = null;
const watch = new MutationObserver(() => syncGrid());
const syncGrid = () => {
const core = gridButton(viewerRoot(box));
if (core !== watched) {
watch.disconnect();
watched = core;
if (core) watch.observe(core, { attributes: true, attributeFilter: ["aria-pressed"] });
}
grid.style.display = core ? "" : "none";
grid.classList.toggle("on", core?.getAttribute("aria-pressed") === "true");
};
tools.append(zoom, pan, grid);
box.parentElement.append(tools);
box.__ausbossTools = { tools, syncGrid, place: () => placeGizmo(box) };
syncGrid();
}
// Drag on the gizmo to orbit, as in a 3D app; a click without a drag still
// picks an axis view.
function addGizmoOrbit(box) {
let drag = null;
box.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
drag = { x: event.clientX, y: event.clientY, moved: false, id: event.pointerId };
});
box.addEventListener("pointermove", (event) => {
if (!drag) return;
const dx = event.clientX - drag.x, dy = event.clientY - drag.y;
if (!drag.moved && Math.hypot(dx, dy) < 4) return;
if (!drag.moved) { drag.moved = true; try { box.setPointerCapture(drag.id); } catch { /* not ours */ } }
drag.x = event.clientX;
drag.y = event.clientY;
const c = box.__ausbossManager?.getControls?.();
if (!c?._rotateLeft) return;
const size = c.domElement?.clientHeight || 400;
c._rotateLeft((2 * Math.PI * dx) / size);
c._rotateUp((2 * Math.PI * dy) / size);
c.update();
event.stopPropagation();
});
const end = (event) => {
if (drag?.moved) {
// Keep the core's click-to-axis from firing after a drag.
event.stopImmediatePropagation();
try { box.releasePointerCapture(drag.id); } catch { /* released */ }
}
drag = null;
};
box.addEventListener("pointerup", end, true);
box.addEventListener("pointercancel", end, true);
box.addEventListener("click", (event) => { if (box.__ausbossDragged) event.stopImmediatePropagation(); }, true);
}
function scan() {
if (!patchGizmoRender()) return;
for (const box of document.querySelectorAll("div[style*='128px']")) {
if (box.dataset.ausbossGizmo) { placeGizmo(box); box.__ausbossTools?.syncGrid(); continue; }
if (!isGizmoBox(box) || !box.parentElement) continue;
box.dataset.ausbossGizmo = "top-right";
box.style.bottom = "auto";
box.style.left = "auto";
box.style.top = "0px";
box.style.right = "0px";
box.style.transformOrigin = "top right";
box.style.transform = `scale(${GIZMO_SCALE})`;
// Under the 360 strip and the tools where the empty room overlaps them.
box.style.zIndex = "4";
addTools(box);
addGizmoOrbit(box);
placeGizmo(box);
}
}
app.registerExtension({
name: "ausboss.viewer_tools",
setup() {
ensureCss();
setInterval(scan, SCAN_MS);
},
});
+16 -7
View File
@@ -11,6 +11,7 @@ import { chainCallback, notifyAusbossChange } from "../shared/index.mjs";
import { formatWidgetVisibility } from "../shared/save_video_formats.mjs";
import { hideInputsInDef } from "../shared/widget_visibility.mjs";
import { castChips } from "../shared/h3_cast_chips.mjs";
import { FULL, fullPromptBox, isEdited, promptTab, promptTabs, simpleEditedNote } from "../shared/h3_full_prompt.mjs";
import { cameraChoiceLabel, clipSetsDuration } from "../shared/h3_duration.mjs";
import { loadImagePreview, loadImageStrip } from "../shared/load_image_strip.mjs";
import { momentStrip } from "../shared/moment_strip.mjs";
@@ -134,6 +135,7 @@ const CARDS = {
{ widget: "pieces", label: "Pieces", when: isMode("job", "split sheet at gaps") },
],
},
AUSBOSS_NODES_PauseShot: { minWidth: 260, first: true, rows: [{ widget: "pause", label: "Pause", onText: "wait for me", offText: "run through" }] },
AUSBOSS_NODES_EditLock: {
minWidth: 300,
rows: [
@@ -390,18 +392,25 @@ const CARDS = {
// sockets, and each picture's job sits under the words.
AUSBOSS_NODES_H3PromptWriter: {
minWidth: 420,
hide: ["job_1", "job_2", "job_3", "job_4", "video_job"],
socketless: ["job_1", "job_2", "job_3", "job_4", "video_job"],
resetUnknown: { sound: "", music: "", clip_sound: false },
hide: ["job_1", "job_2", "job_3", "job_4", "video_job", "full_prompt"],
socketless: ["job_1", "job_2", "job_3", "job_4", "video_job", "full_prompt"],
resetUnknown: { sound: "", music: "", clip_sound: false, full_prompt: "" },
rows: [
{ section: "What happens" },
// Simple is the card as it always was; Full prompt shows the prompt the
// node wrote and sends an edit made there instead (js/shared/h3_full_prompt.mjs).
{ panel: promptTabs, height: 30 },
{ panel: simpleEditedNote, height: 30, when: (values, node) => promptTab(node) !== FULL && isEdited(values) },
{ section: "What H3 gets", when: (values, node) => promptTab(node) === FULL },
{ panel: fullPromptBox, height: 210, grow: true, when: (values, node) => promptTab(node) === FULL },
{ section: "What happens", when: (values, node) => promptTab(node) !== FULL },
{
when: (values, node) => promptTab(node) !== FULL,
widget: "script", kind: "textarea", height: 118, grow: true,
placeholder: "Type what happens, one line for each thing. Picture 1 is @1. A blank line cuts to a new place.\n\nSwap: leave empty, or name who goes. Optional new look on its own line: @1 looks like a woman with blonde hair and a black hoodie.",
},
{ panel: momentStrip, height: 76 },
{ widget: "sound", label: "Sound", placeholder: "rain on a window" },
{ widget: "music", label: "Music", placeholder: "slow piano: music makes it louder" },
{ panel: momentStrip, height: 76, when: (values, node) => promptTab(node) !== FULL },
{ widget: "sound", label: "Sound", placeholder: "rain on a window", when: (values, node) => promptTab(node) !== FULL },
{ widget: "music", label: "Music", placeholder: "slow piano: music makes it louder", when: (values, node) => promptTab(node) !== FULL },
{ section: "Pictures and settings" },
{ panel: castChips, height: 30 },
{ widget: "seconds", label: "Length", suffix: "s", readOnlyText: (node, values) => clipSetsDuration(node, values) ? "From the clip" : "", readOnlyTitle: "This video job uses the incoming clip, so Length is not used." },
+99 -9
View File
@@ -30,19 +30,25 @@ import {
MODEL_COLUMNS,
groupModels,
hostLabel,
installFolders,
listedSpelling,
loadersNeeding,
loraRowsNeeding,
matchInstalled,
modelFolderKey,
noteFit,
noteIsEmpty,
noteShowsTileFace,
normalizeNote,
onlyCopy,
OWN_PACK,
isOwnPackRow,
nameOwnPack,
packsFromGraph,
parseMarkdown,
rowFromCells,
serializeNote,
sharedFolders,
subfolderOf,
} from "../shared/workflow_note.mjs";
import { comboValues, commitWidgetValue } from "../shared/widget_card_math.mjs";
@@ -94,12 +100,13 @@ const PANEL_TOP = 2;
const folderLists = new Map(); // dir -> { at, promise }
let modelFolders = null; // Promise<string[]> from GET /models
let folderInfo = null; // { at, promise } of GET /experiment/models
function listFolder(dir, fresh = false) {
const cached = folderLists.get(dir);
if (!fresh && cached && performance.now() - cached.at < FOLDER_CACHE_MS) return cached.promise;
const promise = api
.fetchApi(`/models/${encodeURIComponent(dir)}`)
.fetchApi(`/models/${encodeURIComponent(modelFolderKey(dir))}`)
.then((response) => (response.ok ? response.json() : null))
.then((files) => (Array.isArray(files) ? files : null))
.catch(() => null);
@@ -124,6 +131,22 @@ function knownFolders() {
return modelFolders;
}
// Where this install looks for each kind of model: [{ name, folders }].
// Launchers such as Stability Matrix add shared folders outside
// ComfyUI/models through extra_model_paths.yaml. [] when the endpoint is
// missing (an older or newer ComfyUI): the card then just names the usual
// folder, as before.
function installFolderList(fresh = false) {
if (!fresh && folderInfo && performance.now() - folderInfo.at < FOLDER_CACHE_MS) return folderInfo.promise;
const promise = api
.fetchApi("/experiment/models")
.then((response) => (response.ok ? response.json() : []))
.then((list) => (Array.isArray(list) ? list : []))
.catch(() => []);
folderInfo = { at: performance.now(), promise };
return promise;
}
function nodeTypeRegistered(type) {
return Boolean(type && globalThis.LiteGraph?.registered_node_types?.[type]);
}
@@ -132,6 +155,36 @@ function moduleOfType(type) {
return globalThis.LiteGraph?.registered_node_types?.[type]?.nodeData?.python_module;
}
// The custom_nodes folder this pack runs from, read off the Workflow Note's
// own registration.
function ownPackFolder() {
return /^custom_nodes\.([^.]+)/.exec(String(moduleOfType("AUSBOSS_NODES_WorkflowNote") ?? ""))?.[1] ?? "";
}
// Open ComfyUI-Manager on its updates list, or its node list. Without the
// Manager, say what to do and open the Registry page instead.
const MANAGER_COMMANDS = [
"Comfy.Manager.ShowUpdateAvailablePacks",
"Comfy.Manager.CustomNodesManager.ShowCustomNodesMenu",
"Comfy.Manager.Menu.ToggleVisibility",
];
async function openManagerForUpdate(tip) {
const command = app.extensionManager?.command;
const known = new Set((command?.commands ?? []).map((entry) => entry?.id));
for (const id of MANAGER_COMMANDS) {
if (!known.has(id)) continue;
try {
await command.execute(id);
showToast({ severity: "info", summary: "AusBoss nodes", detail: tip, life: 12000 });
return;
} catch (_error) {
// Try the next way into the Manager.
}
}
showToast({ severity: "info", summary: "AusBoss nodes", detail: tip, life: 12000 });
window.open(OWN_PACK.url, "_blank", "noopener,noreferrer");
}
// ---------------------------------------------------------------------------
// CSS
// ---------------------------------------------------------------------------
@@ -214,6 +267,8 @@ ${TILE_FACE_CSS}
.ausboss-note-body a:hover,.ausboss-note-link:hover{text-decoration:underline;}
.ausboss-note-folder{margin:8px 0 4px;color:#a9c4c2;font:11px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;}
.ausboss-note-folder:first-child{margin-top:0;}
.ausboss-note-folder-also{margin:-2px 0 4px 18px;color:#7f9896;font:10.5px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow-wrap:anywhere;}
.ausboss-note-folder-also[hidden]{display:none;}
.ausboss-note-row{display:flex;align-items:center;gap:8px;min-height:30px;padding:3px 0;}
.ausboss-note-dot{flex:none;width:8px;height:8px;border-radius:50%;background:#4b5a5a;}
.ausboss-note-dot.checking{background:#4b5a5a;animation:ausboss-note-pulse 1s ease-in-out infinite;}
@@ -475,6 +530,18 @@ function packRow(state, row) {
pill.append(link);
}
action.append(pill);
} else if (installed === false && isOwnPackRow(row)) {
// This note is running, so the pack is installed: the workflow needs a
// newer version. Cloning from GitHub would add a second copy.
const tip = `This workflow needs a newer version of AusBoss nodes (${row.node} is missing). `
+ "Update AusBoss nodes in ComfyUI-Manager, then restart ComfyUI.";
setDot(dot, "missing", tip);
const button = el("button", "ausboss-note-dl", "Update");
button.type = "button";
button.title = tip;
button.addEventListener("pointerdown", (event) => event.stopPropagation());
button.addEventListener("click", () => openManagerForUpdate(tip));
action.append(button);
} else {
setDot(dot, installed === false ? "missing" : "unknown",
installed === false ? `${row.node} is not registered here - install the pack` : "No probe node set, so this row is not checked");
@@ -525,6 +592,7 @@ function render(state) {
const scroll = state.scroll;
scroll.textContent = "";
state.rows = [];
state.folderHints = new Map();
const head = el("div", "ausboss-note-head");
head.append(el("h1", "ausboss-note-title", note.title || "Untitled workflow"));
@@ -612,6 +680,10 @@ function renderSections(state, scroll) {
section.append(heading);
for (const group of groupModels(note.models)) {
section.append(el("div", "ausboss-note-folder", `📂 ${group.path}`));
const also = el("div", "ausboss-note-folder-also");
also.hidden = true;
section.append(also);
(state.folderHints ??= new Map()).set(group.dir, also);
for (const row of group.rows) section.append(modelRow(state, row));
}
scroll.append(section);
@@ -639,11 +711,26 @@ function renderSections(state, scroll) {
checkModels(state, false);
}
// A launcher's shared model folder (Stability Matrix keeps LoRAs in
// Data/Models/Lora) under the usual ComfyUI/models/<dir> line, so the card
// says where this install also finds the files and where to put new ones.
function showSharedFolders(state, dir, list) {
const also = state.folderHints?.get(dir);
if (!also) return;
const shared = sharedFolders(dir, list);
also.hidden = !shared.length;
also.textContent = shared.length ? `also read from ${shared.join(", ")}` : "";
also.title = shared.length
? "This install also reads this kind of model from here (set in extra_model_paths.yaml, for example by Stability Matrix). A file in either place counts."
: "";
}
async function checkModels(state, fresh) {
const generation = (state.checkGeneration = (state.checkGeneration || 0) + 1);
const rows = state.rows;
const picked = [];
for (const entry of rows) setDot(entry.dot, "checking", "checking…");
const folderList = installFolderList(fresh);
const byDir = new Map();
for (const entry of rows) {
const dir = entry.row.dir;
@@ -669,8 +756,13 @@ async function checkModels(state, fresh) {
}));
return;
}
const files = await listFolder(dir, fresh);
const [files, list] = await Promise.all([listFolder(dir, fresh), folderList]);
if (generation !== state.checkGeneration) return;
showSharedFolders(state, dir, list);
const searched = installFolders(dir, list);
const notFound = searched.length
? `Not found in the ${searched.length === 1 ? "folder" : "folders"} this install reads for ${dir}: ${searched.join(", ")}`
: `Not found in ComfyUI/models/${dir}`;
for (const entry of entries) {
if (files === null) {
setDot(entry.dot, "unknown", `This install has no "${dir}" model folder, so the file is not checked`);
@@ -695,7 +787,7 @@ async function checkModels(state, fresh) {
setDot(entry.dot, "ok", `Found: ${match.path}`);
entry.showInstalled(match.path);
} else {
setDot(entry.dot, "missing", `Not found in ComfyUI/models/${dir}`);
setDot(entry.dot, "missing", notFound);
entry.showDownload();
}
}
@@ -1002,8 +1094,8 @@ async function openEditor(state) {
form.append(field("Models", models.box, "Each row shows a Download button until the file is found in its folder (subfolders count). The note shows in grey under the file name."), modelTools);
const packs = table("packs", ["Pack", "URL", "Probe node class"], draft.packs, (row) => [
input(row.name, "ComfyUI-AusBoss"),
input(row.url, "https://github.com/ausboss/ComfyUI-AusBoss"),
input(row.name, OWN_PACK.name),
input(row.url, OWN_PACK.url),
input(row.node, "AUSBOSS_NODES_LoraLoader"),
]);
const packTools = el("div");
@@ -1018,11 +1110,9 @@ async function openEditor(state) {
detect.addEventListener("click", () => {
const types = collectGraphNodes(app.rootGraph ?? app.graph).map((node) => node.type);
const have = new Set(packs.entries.map((entry) => entry.controls[0].value.trim()));
for (const pack of packsFromGraph(types, moduleOfType)) {
for (const pack of nameOwnPack(packsFromGraph(types, moduleOfType), ownPackFolder())) {
if (have.has(pack.name)) continue;
packs.add(pack.name === "ComfyUI-AusBoss"
? { ...pack, url: "https://github.com/ausboss/ComfyUI-AusBoss" }
: pack);
packs.add(pack);
}
});
packTools.append(addPack, detect);
+213 -3
View File
@@ -216,6 +216,9 @@
},
"feather": {
"name": "羽化"
},
"remove_tint": {
"name": "去除偏色"
}
},
"outputs": {
@@ -292,7 +295,128 @@
},
"AUSBOSS_NODES_H3PromptWriter": {
"display_name": "H3 提示词写手 🆎",
"description": "每发生一件事写一行,给每张图片和视频分配一个任务,它就会写出 MiniMax H3 需要的提示词,并给出匹配的宽度和高度。视频里有两个人时,写明要换谁,就只替换那个人。"
"description": "每发生一件事写一行,给每张图片和视频分配一个任务,它就会写出 MiniMax H3 需要的提示词,并给出匹配的宽度和高度。视频里有两个人时,写明要换谁,就只替换那个人。",
"inputs": {
"script": {
"name": "脚本"
},
"seconds": {
"name": "长度"
},
"clip": {
"name": "片段"
},
"picture_1": {
"name": "图片 1"
},
"picture_2": {
"name": "图片 2"
},
"picture_3": {
"name": "图片 3"
},
"picture_4": {
"name": "图片 4"
},
"video": {
"name": "视频"
},
"video_sound": {
"name": "视频声音"
},
"voice": {
"name": "人声"
},
"song": {
"name": "歌曲"
},
"camera": {
"name": "镜头"
},
"look": {
"name": "风格"
},
"song_start": {
"name": "歌曲起点"
},
"cut_on_beat": {
"name": "按节拍切换"
},
"language": {
"name": "语言"
},
"job_1": {
"name": "图片 1 任务"
},
"job_2": {
"name": "图片 2 任务"
},
"job_3": {
"name": "图片 3 任务"
},
"job_4": {
"name": "图片 4 任务"
},
"video_job": {
"name": "视频任务"
},
"sound": {
"name": "声音"
},
"music": {
"name": "音乐"
},
"clip_sound": {
"name": "片段自带声音"
},
"full_prompt": {
"name": "完整提示词"
}
},
"outputs": {
"0": {
"name": "提示词"
},
"1": {
"name": "图片 1"
},
"2": {
"name": "图片 2"
},
"3": {
"name": "图片 3"
},
"4": {
"name": "图片 4"
},
"5": {
"name": "视频"
},
"6": {
"name": "视频声音"
},
"7": {
"name": "人声"
},
"8": {
"name": "歌曲"
},
"9": {
"name": "垫底歌曲"
},
"10": {
"name": "帧数"
},
"11": {
"name": "宽度"
},
"12": {
"name": "高度"
},
"13": {
"name": "保留片段声音"
}
}
},
"AUSBOSS_NODES_ImageCropRotatePad": {
"display_name": "图像裁剪 + 旋转 + 扩边 🆎",
@@ -984,6 +1108,9 @@
},
"fine_edges": {
"name": "精细边缘"
},
"new_picture": {
"name": "换新图时"
}
},
"outputs": {
@@ -1004,6 +1131,15 @@
"inputs": {
"expression": {
"name": "表达式"
},
"a": {
"name": "a"
},
"b": {
"name": "b"
},
"c": {
"name": "c"
}
},
"outputs": {
@@ -1021,6 +1157,12 @@
"inputs": {
"on_mismatch": {
"name": "不匹配时"
},
"a": {
"name": "a"
},
"b": {
"name": "b"
}
},
"outputs": {
@@ -1126,6 +1268,9 @@
},
"batch_size": {
"name": "批次大小"
},
"workflow_sizes": {
"name": "工作流尺寸"
}
},
"outputs": {
@@ -1337,6 +1482,14 @@
"index": {
"name": "索引"
}
},
"outputs": {
"0": {
"name": "a"
},
"1": {
"name": "b"
}
}
},
"AUSBOSS_NODES_StepPreview": {
@@ -1364,6 +1517,9 @@
},
"paste_onto": {
"name": "贴到"
},
"follow_changes": {
"name": "跟随变化"
}
},
"outputs": {
@@ -1688,6 +1844,9 @@
},
"fixed_frames": {
"name": "固定帧数"
},
"last_seconds": {
"name": "最后几秒"
}
},
"outputs": {
@@ -1764,11 +1923,21 @@
},
"AUSBOSS_NODES_CalloutTile": {
"display_name": "标注卡片 🆎",
"description": "紧凑的标题或彩色链接按钮。双击编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。"
"description": "紧凑的标题或彩色链接按钮。双击编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。",
"inputs": {
"text": {
"name": "文字"
}
}
},
"AUSBOSS_NODES_WorkflowNoteTile": {
"display_name": "工作流说明卡片 🆎",
"description": "点击打开完整说明的小按钮。点击铅笔编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。"
"description": "点击打开完整说明的小按钮。点击铅笔编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。",
"inputs": {
"note": {
"name": "备注"
}
}
},
"AUSBOSS_NODES_FlashVSRUpscale": {
"display_name": "FlashVSR 视频放大 🆎",
@@ -1812,5 +1981,46 @@
"name": "提示词"
}
}
},
"AUSBOSS_NODES_PauseShot": {
"display_name": "暂停取景 🆎",
"description": "在 3D 查看器之后暂停运行,让你在刚生成的模型上取景。转动相机后点“继续”(在这个节点上或查看器上):运行会按你调好的画面继续,前面的步骤不会重跑。“停止”在这里结束运行。关掉暂停则直接运行,使用按下运行时的相机。接入一张 360 全景图,它会在你取景时显示在模型后面,backdrop 输出相机看到的那部分。",
"inputs": {
"model_3d_info": {
"name": "模型位置"
},
"camera_info": {
"name": "相机"
},
"width": {
"name": "宽度"
},
"height": {
"name": "高度"
},
"pause": {
"name": "暂停"
},
"panorama": {
"name": "360 全景"
}
},
"outputs": {
"0": {
"name": "模型位置"
},
"1": {
"name": "相机"
},
"2": {
"name": "宽度"
},
"3": {
"name": "高度"
},
"4": {
"name": "背景"
}
}
}
}
+155
View File
@@ -0,0 +1,155 @@
"""The 360 behind the model, as the 3D viewer's camera sees it.
Pause for Shot hands this on so the run gets the same backdrop the viewer
showed. The maths follows three.js, which draws the viewer: a camera looks
down its -Z axis with +Y up, turned by its quaternion; the 360's own Turn,
Tilt and Roll (js/viewer_pano) turn each view direction by the inverse
(transpose) of their ZXY rotation, as three's background shader does (the
negated angles only agree while one angle is set); and a direction finds its pixel in the
equirectangular picture by u = atan2(z, x) / 2pi + 0.5 and
v = asin(y) / pi + 0.5, with v = 1 at the picture's top row.
"""
from __future__ import annotations
import math
import numpy as np
DEG = math.pi / 180
def quaternion_matrix(q) -> np.ndarray:
x, y, z, w = (float(v) for v in q)
n = math.sqrt(x * x + y * y + z * z + w * w) or 1.0
x, y, z, w = x / n, y / n, z / n, w / n
return np.array([
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
])
def euler_zxy_matrix(x: float, y: float, z: float) -> np.ndarray:
"""three.js Matrix4.makeRotationFromEuler for order 'ZXY'."""
a, b = math.cos(x), math.sin(x)
c, d = math.cos(y), math.sin(y)
e, f = math.cos(z), math.sin(z)
ce, cf, de, df = c * e, c * f, d * e, d * f
return np.array([
[ce - df * b, -a * f, de + cf * b],
[cf + de * b, a * e, df - ce * b],
[-a * d, b, a * c],
])
def _number(value, default: float) -> float:
return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) else default
def view_backdrop(panorama: np.ndarray, camera: dict, sky: dict, width: int, height: int) -> np.ndarray:
"""panorama: H x W x 3 float equirectangular picture. Returns height x
width x 3: the 360 as the viewer's camera saw it."""
sky = sky if isinstance(sky, dict) else {}
camera = camera if isinstance(camera, dict) else {}
quaternion = camera.get("quaternion") or {}
turn = [quaternion.get(k, 0.0 if k != "w" else 1.0) for k in ("x", "y", "z", "w")]
view = sky.get("view")
if sky.get("orbit") == "fixed":
turn = view if isinstance(view, list) and len(view) == 4 else [0.0, 0.0, 0.0, 1.0]
fov = _number(sky.get("fov"), _number(camera.get("fov"), 35.0))
fov = min(170.0, max(1.0, fov))
aspect = width / max(1, height)
half = math.tan(fov * DEG / 2)
xs = ((np.arange(width) + 0.5) / width * 2 - 1) * half * aspect
ys = (1 - (np.arange(height) + 0.5) / height * 2) * half
gx, gy = np.meshgrid(xs, ys)
directions = np.stack([gx, gy, -np.ones_like(gx)], -1)
directions /= np.linalg.norm(directions, axis=-1, keepdims=True)
rotation = euler_zxy_matrix(_number(sky.get("tilt"), 0) * DEG, _number(sky.get("turn"), 0) * DEG, _number(sky.get("roll"), 0) * DEG).T
world = directions @ (rotation @ quaternion_matrix(turn)).T
ph, pw = panorama.shape[:2]
u = np.arctan2(world[..., 2], world[..., 0]) / (2 * math.pi) + 0.5
v = np.arcsin(np.clip(world[..., 1], -1, 1)) / math.pi + 0.5
px = u * pw - 0.5
py = (1 - v) * ph - 0.5
x0 = np.floor(px).astype(np.int64)
y0 = np.clip(np.floor(py).astype(np.int64), 0, ph - 1)
y1 = np.clip(y0 + 1, 0, ph - 1)
fx = (px - x0)[..., None]
fy = np.clip(py - y0, 0, 1)[..., None]
x1 = (x0 + 1) % pw
x0 %= pw
top = panorama[y0, x0] * (1 - fx) + panorama[y0, x1] * fx
bottom = panorama[y1, x0] * (1 - fx) + panorama[y1, x1] * fx
picture = top * (1 - fy) + bottom * fy
return np.clip(picture * (_number(sky.get("bright"), 100) / 100), 0, 1)
def shadow_falloff(distance: np.ndarray) -> np.ndarray:
"""How dark the shadow is at a distance from its middle, where 1 is its
edge. The viewer draws the same curve (js/viewer_pano, SHADOW_RINGS)."""
inside = np.clip(1.0 - distance * distance, 0.0, 1.0)
return inside * inside
def clean_ground(ground) -> dict | None:
"""The patch of floor under the model, as the viewer measured it: the
floor's height `y`, the middle `cx`, `cz` and the half sizes `rx`, `rz`."""
if not isinstance(ground, dict):
return None
values = {key: _number(ground.get(key), math.nan) for key in ("y", "cx", "cz", "rx", "rz")}
if not all(math.isfinite(v) for v in values.values()) or values["rx"] <= 0 or values["rz"] <= 0:
return None
return values
def shadow_alpha(camera: dict, ground, strength: float, width: int, height: int) -> np.ndarray:
"""height x width, 0 to 1: how much a soft shadow on the floor under the
model darkens each pixel of the shot. The rays are the ones Render Mesh
casts for the same camera: from its position towards its target, +Y up,
no roll, its field of view narrowed by its zoom."""
ground = clean_ground(ground)
strength = min(1.0, max(0.0, float(strength)))
alpha = np.zeros((height, width), dtype=np.float64)
if ground is None or strength <= 0 or not isinstance(camera, dict):
return alpha
def vector(data, default):
if not isinstance(data, dict):
return default
return np.array([_number(data.get(k), d) for k, d in zip("xyz", default)])
eye = vector(camera.get("position"), np.array([0.0, 0.0, 5.0]))
target = vector(camera.get("target"), np.array([0.0, 0.0, 0.0]))
if eye[1] <= ground["y"]:
# Under the floor: no shadow, as in the viewer.
return alpha
forward = target - eye
if np.linalg.norm(forward) < 1e-9:
return alpha
forward /= np.linalg.norm(forward)
up = np.array([0.0, 1.0, 0.0]) if abs(forward[1]) < 0.99 else np.array([0.0, 0.0, 1.0])
right = np.cross(forward, up)
right /= np.linalg.norm(right)
up = np.cross(right, forward)
fov = min(170.0, max(1.0, _number(camera.get("fov"), 40.0) or 40.0))
zoom = max(1e-3, _number(camera.get("zoom"), 1.0) or 1.0)
tn = math.tan(fov * DEG / 2) / zoom
xs = (np.arange(width) + 0.5) / width * 2 - 1
ys = 1 - (np.arange(height) + 0.5) / height * 2
gx, gy = np.meshgrid(xs, ys)
rays = right * (gx * tn * (width / max(1, height)))[..., None] + up * (gy * tn)[..., None] + forward
dy = rays[..., 1]
with np.errstate(divide="ignore", invalid="ignore"):
t = (ground["y"] - eye[1]) / dy
hit = np.isfinite(t) & (t > 0)
t = np.where(hit, t, 0.0)
px = eye[0] + rays[..., 0] * t
pz = eye[2] + rays[..., 2] * t
distance = np.sqrt(((px - ground["cx"]) / ground["rx"]) ** 2 + ((pz - ground["cz"]) / ground["rz"]) ** 2)
return np.where(hit, shadow_falloff(distance) * strength, 0.0)
+38
View File
@@ -9,6 +9,7 @@ from __future__ import annotations
import json
import os
import re
from collections import OrderedDict
from pathlib import Path
from typing import Any
@@ -64,6 +65,7 @@ def parse_lora_stack(raw: str | None) -> list[dict[str, Any]]:
enabled = bool(entry.get("enabled", True)) and entry.get("group_off") is not True
rows.append(
{
"id": str(entry.get("id") or ""),
"name": name,
"strength": strength,
"strength_clip": clamp_strength(entry.get("strength_clip", strength), strength),
@@ -74,6 +76,42 @@ def parse_lora_stack(raw: str | None) -> list[dict[str, Any]]:
return rows
# A row's strength can come in on a link: the node then has an input named
# strength_<row id>, made by the frontend when a value is dropped on the row.
ROW_STRENGTH_PREFIX = "strength_"
_ROW_INPUT = re.compile(r"^strength_[A-Za-z0-9_-]{1,64}$")
def is_row_strength_input(name: Any) -> bool:
return isinstance(name, str) and bool(_ROW_INPUT.match(name))
def apply_linked_strengths(rows: list[dict[str, Any]], linked: dict[str, Any]) -> list[dict[str, Any]]:
"""Rows with each linked value as the model strength.
The CLIP strength keeps the ratio the row had to its model strength, so
one slider moves the whole LoRA. A row at model strength 0 has no ratio
to keep; its CLIP strength then follows the slider one for one.
"""
values = {
name[len(ROW_STRENGTH_PREFIX):]: value
for name, value in linked.items()
if is_row_strength_input(name) and value is not None
}
if not values:
return rows
out = []
for row in rows:
row_id = row.get("id")
if not row_id or row_id not in values:
out.append(row)
continue
strength = clamp_strength(values[row_id], row["strength"])
ratio = row["strength_clip"] / row["strength"] if row["strength"] else 1.0
out.append({**row, "strength": strength, "strength_clip": clamp_strength(strength * ratio, strength)})
return out
def collect_trigger_words(rows: list[dict[str, Any]], separator: str = ", ") -> str:
"""Join enabled rows' trigger words, deduplicated, order preserved."""
seen: set[str] = set()
+62
View File
@@ -0,0 +1,62 @@
"""Read the [project] table of a pyproject.toml.
``tomllib`` is in the standard library only from Python 3.11. Some ComfyUI
installs still run 3.10 (Stability Matrix, older portable builds), and there
a bare ``import tomllib`` stopped the whole pack from loading. So this uses
``tomllib`` when it is there, the ``tomli`` backport when that is installed,
and otherwise a small reader that takes the plain ``key = "value"`` lines of
[project], which is all the pack reads (its name and version).
"""
from __future__ import annotations
import re
try:
import tomllib as _toml
except ModuleNotFoundError: # Python 3.10
try:
import tomli as _toml
except ModuleNotFoundError:
_toml = None
_SECTION = re.compile(r"^\s*\[([^\[\]]+)\]\s*(?:#.*)?$")
_STRING_KEY = re.compile(r"""^\s*([A-Za-z0-9_-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')\s*(?:#.*)?$""")
def _plain_project(text: str) -> dict:
"""The top-level string keys of [project], without a TOML library."""
project: dict = {}
inside = False
for line in text.splitlines():
section = _SECTION.match(line)
if section:
inside = section.group(1).strip() == "project"
continue
if not inside:
continue
match = _STRING_KEY.match(line)
if match and match.group(1) not in project:
value = match.group(2) if match.group(2) is not None else match.group(3)
project[match.group(1)] = value
return project
def project_from_text(text: str) -> dict:
"""The [project] table of pyproject text, or {} when it has none."""
if _toml is not None:
project = _toml.loads(text).get("project", {})
return project if isinstance(project, dict) else {}
return _plain_project(text)
def read_project(path: str) -> dict:
"""The [project] table of the pyproject.toml at ``path``.
Raises OSError or a parse error like ``tomllib.load`` does, so callers
keep their own fallbacks.
"""
with open(path, "rb") as f:
raw = f.read()
# utf-8-sig drops a BOM, which tomllib itself would reject.
return project_from_text(raw.decode("utf-8-sig"))
+69 -3
View File
@@ -14,7 +14,8 @@ loads.
from __future__ import annotations
import os
import tomllib
from ._pyproject import read_project
PACK_NAME = "ausboss-nodes"
# A copy that has this file knows how to step aside.
@@ -24,8 +25,7 @@ _GUARD_FILE = os.path.join("nodes", "_single_copy.py")
def _read_pack(folder: str) -> dict | None:
"""Name the pack copy in ``folder``, or None when it is another pack."""
try:
with open(os.path.join(folder, "pyproject.toml"), "rb") as f:
project = tomllib.load(f).get("project", {})
project = read_project(os.path.join(folder, "pyproject.toml"))
except Exception:
return None
if project.get("name") != PACK_NAME:
@@ -95,3 +95,69 @@ def other_copy_that_loads(own_folder: str, roots: list[str] | None = None) -> di
return None
chosen = pick_copy(copies)
return None if chosen["folder"] == os.path.realpath(own_folder) else chosen
def is_older(version: str, than: str) -> bool:
return _version_key(version) < _version_key(than)
def second_copy_notice(own_folder: str, own_version: str, other: dict) -> dict:
"""What the browser tells someone whose pack is installed twice.
The usual case is an old git clone beside a newer Manager install: the
old clone cannot step aside, so it loads, and every node added since
shows as missing however often the Manager updates the other folder.
"""
own = os.path.basename(os.path.realpath(own_folder))
used = os.path.basename(other["folder"])
if is_older(other["version"], own_version):
summary = "AusBoss: an old copy is loading"
detail = (
f"ComfyUI is loading the old AusBoss v{other['version']} in "
f"custom_nodes/{used}, not v{own_version} in custom_nodes/{own}. "
f"Nodes added after v{other['version']} show as missing, and "
f"updating does not fix it. Delete the custom_nodes/{used} "
"folder, then restart ComfyUI."
)
else:
summary = "AusBoss is installed twice"
detail = (
f"AusBoss is in custom_nodes/{used} (v{other['version']}) and "
f"custom_nodes/{own} (v{own_version}). Only custom_nodes/{used} "
f"loads. Delete custom_nodes/{own}, then restart ComfyUI."
)
return {"summary": summary, "detail": detail, "older": is_older(other["version"], own_version)}
NOTICE_ROUTE = "/ausboss/second_copy"
def register_second_copy_notice(notice: dict, prompt_server=None) -> bool:
"""Serve ``notice`` to the browser at NOTICE_ROUTE.
Only copies that step aside call this, and the copy that loads never
adds this route, so nothing is added twice. Two copies that both step
aside share one route: the first adds it, the rest add their notice to
its list.
"""
if prompt_server is None:
try:
from server import PromptServer
prompt_server = PromptServer.instance
except Exception:
return False
notices = getattr(prompt_server, "_ausboss_second_copy_notices", None)
if notices is not None:
notices.append(notice)
return True
notices = [notice]
prompt_server._ausboss_second_copy_notices = notices
from aiohttp import web
@prompt_server.routes.get(NOTICE_ROUTE)
async def _second_copy_notices(_request):
return web.json_response(notices)
return True
+172
View File
@@ -107,3 +107,175 @@ def register_step_preview_handler() -> None:
return json_data
instance.add_on_prompt_handler(handler)
register_moving_step_pictures()
# --- Moving step pictures for video models --------------------------------
#
# ComfyUI's step picture of a clip is its first frame only. For a run that
# shows its steps (the same runs as above), the pack also sends about one
# frame per second of the clip after each step, and the step overlay plays
# them in a loop (js/shared/step_preview.mjs).
#
# The frames come from the previewer ComfyUI picked for the run (the quick
# color estimate under `auto`, or a tiny video decoder from
# `models/vae_approx` when the user chose TAESD), one frame per call, which
# is exactly the call ComfyUI makes for the first frame. So the peak memory
# of a decode stays what it already was, and nothing is loaded that was not.
FRAMES_EVENT = "ausboss.step_frames"
# The frame rate the frame picks assume; H3, LTX and most video models make 24.
CLIP_FPS = 24
# About one picture per second of the clip, as many as this at most.
FRAMES_PER_SECOND = 1
MAX_FRAMES = 16
JPEG_QUALITY = 80
# The frames take at most this share of the run's time: a slow decoder
# (the tiny video decoder on a small card) skips steps, and the loop keeps
# playing the frames it has.
FRAME_BUDGET = 0.1
def frame_picks(latent_frames, temporal_ratio, *, clip_fps=CLIP_FPS, per_second=FRAMES_PER_SECOND, cap=MAX_FRAMES):
"""The latent frames to show, and the clip seconds between two of them.
A clip latent holds one frame for every `temporal_ratio` frames of the
clip. Returns ([], 0.0) when there is nothing to move.
"""
try:
count = int(latent_frames)
ratio = max(1, int(temporal_ratio or 1))
except (TypeError, ValueError):
return [], 0.0
if count < 2 or cap < 2:
return [], 0.0
stride = max(1, round(clip_fps / max(per_second, 1e-6) / ratio))
picks = list(range(0, count, stride))
if len(picks) < 2:
picks = [0, count - 1]
if len(picks) > cap:
picks = sorted({round(index * (count - 1) / (cap - 1)) for index in range(cap)})
gap = (picks[-1] - picks[0]) / (len(picks) - 1)
return picks, gap * ratio / clip_fps
def _jpeg_data_url(picture, max_side: int) -> str:
import base64
import io
from PIL import ImageOps
if max_side and max(picture.size) > max_side:
picture = ImageOps.contain(picture, (max_side, max_side))
buffer = io.BytesIO()
picture.convert("RGB").save(buffer, format="JPEG", quality=JPEG_QUALITY)
return "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode("ascii")
class MovingStepPictures:
"""ComfyUI's previewer for one sampler, plus the clip's frames each step.
Everything else is the previewer it wraps: ComfyUI's own step picture
and every attribute pass through unchanged.
"""
def __init__(self, inner, latent_format, send, where, max_side=512, clock=None):
import time
self.inner = inner
self.clock = clock or time.perf_counter
# How long the last frames took to make, and when they were sent.
self.cost = 0.0
self.sent_at = None
self.ratio = getattr(latent_format, "temporal_downscale_ratio", 1) or 1
self.send = send
self.where = where
self.max_side = max_side
self.failed = False
def __getattr__(self, name):
# Only reached for names this class does not have.
if name == "inner":
raise AttributeError(name)
return getattr(self.inner, name)
def frames(self, x0):
"""The clip's frames as JPEG data URLs, and the seconds between them."""
if getattr(x0, "ndim", 0) != 5:
return [], 0.0
picks, seconds = frame_picks(x0.shape[2], self.ratio)
if not picks:
return [], 0.0
return [_jpeg_data_url(self.inner.decode_latent_to_preview(x0[:1, :, index:index + 1]), self.max_side) for index in picks], seconds
def due(self, now) -> bool:
"""Whether making frames now keeps them within FRAME_BUDGET."""
return self.sent_at is None or self.cost <= FRAME_BUDGET * (now - self.sent_at)
def decode_latent_to_preview_image(self, preview_format, x0):
now = self.clock()
if not self.failed and self.due(now):
try:
frames, seconds = self.frames(x0)
self.cost = self.clock() - now
self.sent_at = now
if frames:
prompt_id, node_id = self.where()
self.send(FRAMES_EVENT, {"prompt_id": prompt_id, "node": node_id, "frames": frames, "seconds": seconds})
except Exception:
# A previewer that cannot do single frames: the still stays.
self.failed = True
return self.inner.decode_latent_to_preview_image(preview_format, x0)
def _running_prompt():
"""The API prompt of the run executing now, or None."""
from comfy_execution.utils import get_executing_context
from server import PromptServer
context = get_executing_context()
queue = getattr(PromptServer.instance, "prompt_queue", None)
running = getattr(queue, "currently_running", None)
if context is None or not isinstance(running, dict):
return None
for item in list(running.values()):
if isinstance(item, (list, tuple)) and len(item) > 2 and item[1] == context.prompt_id:
return item[2]
return None
def _where():
from comfy_execution.utils import get_executing_context
context = get_executing_context()
return (context.prompt_id, context.node_id) if context else (None, None)
def _send(event, data):
from server import PromptServer
instance = PromptServer.instance
instance.send_sync(event, data, getattr(instance, "client_id", None))
def register_moving_step_pictures() -> None:
"""Wrap ComfyUI's previewer choice once, so clips can move."""
try:
import latent_preview
except Exception:
return
original = getattr(latent_preview, "get_previewer", None)
if not callable(original) or getattr(original, "_ausboss_moving", False):
return
def get_previewer(device, latent_format):
previewer = original(device, latent_format)
try:
if previewer is not None and getattr(latent_format, "latent_dimensions", 2) == 3 and wants_step_pictures(_running_prompt()):
return MovingStepPictures(previewer, latent_format, _send, _where, getattr(latent_preview, "MAX_PREVIEW_RESOLUTION", 512))
except Exception:
pass
return previewer
get_previewer._ausboss_moving = True
latent_preview.get_previewer = get_previewer
+51
View File
@@ -147,6 +147,57 @@ def clip_load_window(path, start_seconds, end_seconds, max_frames=0,
return float(start_seconds), float(end_seconds), max(0, int(cap))
def limit_clip_length(start_seconds, end_seconds, cap, duration, frame_seconds,
min_seconds=0.0, max_seconds=0.0):
"""Keep a resolved window between min_seconds and max_seconds long.
The window is start_seconds to end_seconds (0 = the video's end), cut
short by a cap of `cap` output frames that last `frame_seconds` each.
A limit of 0 is no limit, and a max below the min counts as the min.
Too long: the end moves in. Too short: the end moves out, and where the
video ends first the start moves back instead. A video shorter than the
min is used whole. A backwards window is left alone so the decode can
say what is wrong with it. Returns (start, end, cap); the cap is cleared
when it would cut the window under its new length.
js/shared/timeline_math.mjs limitClipSeconds mirrors this.
"""
low = max(0.0, float(min_seconds or 0.0)) if math.isfinite(float(min_seconds or 0.0)) else 0.0
high = max(0.0, float(max_seconds or 0.0)) if math.isfinite(float(max_seconds or 0.0)) else 0.0
start, end, cap = float(start_seconds), float(end_seconds), max(0, int(cap))
if low <= 0 and high <= 0:
return start, end, cap
if 0 < high < low:
high = low
known = math.isfinite(float(duration or 0)) and float(duration or 0) > 0
duration = float(duration) if known else 0.0
if known and low > 0 and duration <= low + _TIME_EPSILON:
return 0.0, 0.0, 0
stop = end if end > 0 else (duration if known else math.inf)
if known:
stop = min(stop, duration)
length = stop - start
if length <= 0:
return start, end, cap
step = float(frame_seconds or 0.0)
capped = cap > 0 and math.isfinite(step) and step > 0
if capped:
length = min(length, cap * step)
target = length
if high > 0:
target = min(target, high)
if low > 0:
target = max(target, low)
if abs(target - length) <= _TIME_EPSILON:
return start, end, cap
new_end = start + target
if known and new_end > duration:
new_end = duration
start = max(0.0, duration - target)
if capped and cap * step < target - _TIME_EPSILON:
cap = 0
return start, new_end, cap
def fixed_clip_window(metadata, start_seconds, frames, force_rate=0, every_nth=1):
"""Place an exact output-frame window on the source grid, sliding at ends."""
fps = float(metadata.get("fps") or 0)
+25 -1
View File
@@ -285,6 +285,19 @@ class AusBossH3PromptWriter:
),
},
),
"full_prompt": (
"STRING",
{
"default": "",
"multiline": True,
"dynamicPrompts": False,
"tooltip": (
"Your own edit of the finished prompt, from the Full prompt tab. When it holds "
"text, H3 gets exactly this text instead of the prompt the node writes. Empty "
"means the node's own prompt."
),
},
),
},
}
@@ -321,7 +334,7 @@ class AusBossH3PromptWriter:
"The height of your video, or else of your first picture. Wire it into H3's height.",
"On when the finished clip should keep your video's own sound: with clip_sound on, or always for change something.",
)
FUNCTION = "write"
FUNCTION = "run"
def write(self, script, seconds, clip=None, picture_1=None, picture_2=None, picture_3=None, picture_4=None, video=None,
video_sound=None, voice=None, song=None, camera=AS_TYPED, look=FROM_PICTURE, song_start=0.0, cut_on_beat=True,
@@ -378,6 +391,17 @@ class AusBossH3PromptWriter:
ordered = [*given.values(), None, None, None, None][: len(PICTURES)]
return (text, *ordered, video, video_sound, voice, song, song_under, frames, *clip_shape(video, ordered[0]), keeps_clip_sound)
def run(self, script, seconds, full_prompt="", **inputs):
# The Full prompt tab shows what the node wrote; an edit typed there is sent in its place.
written, *rest = self.write(script, seconds, **inputs)
return {"ui": {"written_prompt": [written]}, "result": (sent_prompt(written, full_prompt), *rest)}
def sent_prompt(written, edited):
"""The prompt H3 gets: the edit from the Full prompt tab when it holds any text, else the written one."""
edited = str(edited or "")
return edited if edited.strip() else written
def _register_routes():
try:
+29 -4
View File
@@ -5,7 +5,9 @@ from __future__ import annotations
from ._execution_helpers import ignore_extra_inputs
from ._lora_helpers import (
MISSING_MODES,
apply_linked_strengths,
apply_lora_stack,
is_row_strength_input,
collect_trigger_words,
missing_lora_rows,
parse_lora_stack,
@@ -16,6 +18,29 @@ from ._lora_helpers import (
)
class _OptionalWithRowStrengths(dict):
"""The node's optional inputs, plus strength_<row id> for any row.
ComfyUI passes a node only the inputs it declares. A row's strength input
exists only while something is linked to that row, so its name is not
known ahead: this dict answers for any such name.
"""
def __contains__(self, key):
return super().__contains__(key) or is_row_strength_input(key)
def __getitem__(self, key):
if not super().__contains__(key) and is_row_strength_input(key):
return ("FLOAT", {
"forceInput": True,
"tooltip": "A linked strength for one row. The CLIP strength keeps its ratio.",
})
return super().__getitem__(key)
def get(self, key, default=None):
return self[key] if key in self else default
class AusBossLoraLoader:
CATEGORY = "🆎 AusBoss/Loaders"
DESCRIPTION = (
@@ -53,7 +78,7 @@ class AusBossLoraLoader:
},
),
},
"optional": {
"optional": _OptionalWithRowStrengths({
"clip": ("CLIP", {"tooltip": "Optional CLIP to patch; without it, CLIP strengths are ignored."}),
"trigger_separator": (
"STRING",
@@ -81,7 +106,7 @@ class AusBossLoraLoader:
),
},
),
},
}),
}
RETURN_TYPES = ("MODEL", "CLIP", "STRING")
@@ -98,8 +123,8 @@ class AusBossLoraLoader:
)
FUNCTION = "load_loras"
def load_loras(self, model, loras: str, clip=None, trigger_separator=", ", on_missing="error"):
rows = parse_lora_stack(loras)
def load_loras(self, model, loras: str, clip=None, trigger_separator=", ", on_missing="error", **linked):
rows = apply_linked_strengths(parse_lora_stack(loras), linked)
missing: list[dict] = []
model, clip = apply_lora_stack(model, clip, rows, on_missing=on_missing, missing=missing)
# A row skipped for a missing file loaded nothing, so its words stay
+349
View File
@@ -0,0 +1,349 @@
"""Pause for Shot 🆎: the run waits after the 3D viewer, so you can frame the
shot on the model it just built, then Continue takes the camera as it is now.
Given a 360 picture, it also puts that behind the model in the viewer while
it waits, and hands on the part of the 360 the camera sees (`backdrop`), so
the shot and its background can be treated apart (blur one, not the other).
A plain re-run would rebuild nothing that is still cached, but a camera moved
after Run never reaches the run: the prompt holds the camera from the moment
Run was pressed. This node sits between a Preview 3D (Advanced) viewer and
what renders the shot. While it waits, Continue (on this node, and on the
viewer itself, js/pause_shot/) sends the viewer's camera, model turn and
size through POST /ausboss/pause_shot/answer, and the node hands those on in
place of the ones it was given.
The route takes the id of a node that is waiting right now and the shot as
numbers; it reads and writes no file, and an answer for a node that is not
waiting is refused. GET /ausboss/pause_shot/waiting lists the pauses waiting
now, so a page opened or reloaded during a pause shows it again. Cancel in
ComfyUI's queue ends a pause as well.
"""
from __future__ import annotations
import math
import os
import random
import threading
from ._backdrop_helpers import clean_ground, shadow_alpha, view_backdrop
EVENT_WAIT = "ausboss-pause-shot"
EVENT_DONE = "ausboss-pause-shot-done"
MAX_SIDE = 4096
_waiting: dict[str, dict] = {}
_lock = threading.Lock()
# What each 3D viewer was last told to show. ComfyUI sends a node's result
# only to the page that pressed Run; a pause is seen by every open page, so
# it carries its viewer's result along and any page can show the model.
_viewer_results: dict[str, dict] = {}
MODEL_SUFFIXES = (".glb", ".gltf", ".obj", ".fbx", ".stl", ".usdz", ".ply", ".spz", ".splat", ".ksplat")
def model_name(output) -> str:
"""The 3D file a viewer result names, in either shape ComfyUI sends:
{"result": ["model.glb [temp]", ...]}, or since its standard 3d output
item {"3d": [{"filename": "model.glb", "subfolder": "", "type": "temp"}]}."""
if not isinstance(output, dict):
return ""
result = output.get("result")
if isinstance(result, (list, tuple)) and result and isinstance(result[0], str):
return result[0].rsplit(" [", 1)[0]
items = output.get("3d")
if isinstance(items, (list, tuple)) and items and isinstance(items[0], dict):
name = items[0].get("filename")
return name if isinstance(name, str) else ""
return ""
def model_result(output) -> bool:
"""True for a viewer result that names a 3D file."""
return model_name(output).lower().endswith(MODEL_SUFFIXES)
def remember_result(event, data) -> None:
if event != "executed" or not isinstance(data, dict):
return
output = data.get("output")
if not model_result(output):
return
with _lock:
for key in {str(data.get("node")), str(data.get("display_node"))} - {"None"}:
_viewer_results.pop(key, None)
_viewer_results[key] = output
while len(_viewer_results) > 64:
_viewer_results.pop(next(iter(_viewer_results)))
def viewer_of(prompt, node_id: str):
"""The id of the viewer wired into this pause's model_3d_info."""
try:
link = prompt[node_id]["inputs"]["model_3d_info"]
except (KeyError, TypeError):
return None
return str(link[0]) if isinstance(link, (list, tuple)) and link else None
def _watch_results(server) -> None:
send = server.send_sync
if getattr(send, "_ausboss_pause_shot", False):
return
def send_sync(event, data, sid=None):
try:
remember_result(event, data)
except Exception:
pass
return send(event, data, sid)
send_sync._ausboss_pause_shot = True
server.send_sync = send_sync
def _server():
try:
from server import PromptServer
except Exception:
return None
return getattr(PromptServer, "instance", None)
def _send(event: str, data: dict) -> None:
server = _server()
if server is not None:
server.send_sync(event, data, None)
def clean_value(value, depth: int = 0):
"""Keep only what a camera or a model turn is made of: numbers, short
names, and small lists and objects of those. Anything else is dropped."""
if depth > 4:
return None
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return value if math.isfinite(value) else None
if isinstance(value, str):
return value if len(value) <= 40 else None
if isinstance(value, list):
return [item for item in (clean_value(v, depth + 1) for v in value[:16]) if item is not None]
if isinstance(value, dict):
out = {}
for key, item in list(value.items())[:32]:
if isinstance(key, str) and len(key) <= 40:
cleaned = clean_value(item, depth + 1)
if cleaned is not None:
out[key] = cleaned
return out
return None
def clean_shot(shot) -> dict:
"""The parts of an answer the node uses, checked."""
if not isinstance(shot, dict):
return {}
out = {}
camera = clean_value(shot.get("camera_info"))
if isinstance(camera, dict) and isinstance(camera.get("position"), dict):
out["camera_info"] = camera
model = clean_value(shot.get("model_3d_info"))
if isinstance(model, list) and all(isinstance(item, dict) for item in model):
out["model_3d_info"] = model
sky = clean_value(shot.get("sky"))
if isinstance(sky, dict):
out["sky"] = sky
ground = clean_ground(shot.get("ground"))
if ground:
out["ground"] = ground
# False when the 360 was taken out of the viewer: the backdrop goes grey.
if shot.get("panorama") is False:
out["panorama"] = False
for key in ("width", "height"):
side = shot.get(key)
if isinstance(side, (int, float)) and not isinstance(side, bool) and math.isfinite(side):
out[key] = max(1, min(MAX_SIDE, int(round(side))))
return out
def _save_panorama(panorama) -> dict | None:
"""The 360 as a temp picture, for the viewer to show while the run waits."""
try:
import folder_paths
from PIL import Image
array = (panorama[0].clamp(0, 1).cpu().numpy() * 255).round().astype("uint8")
temp = folder_paths.get_temp_directory()
os.makedirs(temp, exist_ok=True)
name = "ausboss_360_" + "".join(random.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(8)) + ".png"
Image.fromarray(array).save(os.path.join(temp, name), compress_level=1)
return {"filename": name, "subfolder": "", "type": "temp"}
except Exception:
return None
def _wait_for_answer(node_id: str, extra: dict | None = None) -> dict:
import comfy.model_management as mm
slot = {"event": threading.Event(), "answer": None, "payload": {"node": node_id, **(extra or {})}}
with _lock:
_waiting[node_id] = slot
try:
_send(EVENT_WAIT, slot["payload"])
while not slot["event"].wait(0.25):
mm.throw_exception_if_processing_interrupted()
finally:
with _lock:
if _waiting.get(node_id) is slot:
del _waiting[node_id]
_send(EVENT_DONE, {"node": node_id})
answer = slot["answer"] or {}
if answer.get("action") == "stop":
mm.interrupt_current_processing()
raise mm.InterruptProcessingException()
return answer
def answer_pause(body) -> tuple[int, dict]:
"""Hand an answer from the node or the viewer to the waiting run."""
if not isinstance(body, dict):
return 400, {"error": "Pause for Shot: the answer could not be read."}
node_id = body.get("node")
action = body.get("action")
if not isinstance(node_id, str) or action not in ("continue", "stop"):
return 400, {"error": "Pause for Shot: the answer needs a node and continue or stop."}
with _lock:
slot = _waiting.get(node_id)
if slot is None:
return 409, {"error": "That node is not waiting any more."}
slot["answer"] = {"action": action, "shot": clean_shot(body.get("shot"))}
slot["event"].set()
return 200, {"ok": True}
def waiting_pauses() -> list[dict]:
with _lock:
return [dict(slot["payload"]) for slot in _waiting.values()]
def register_routes() -> None:
server = _server()
if server is None or getattr(server, "_ausboss_pause_shot", False):
return
try:
from aiohttp import web
except Exception:
return
server._ausboss_pause_shot = True
_watch_results(server)
@server.routes.post("/ausboss/pause_shot/answer")
async def pause_shot_answer(request):
try:
body = await request.json()
except Exception:
body = None
status, data = answer_pause(body)
return web.json_response(data, status=status)
@server.routes.get("/ausboss/pause_shot/waiting")
async def pause_shot_waiting(_request):
return web.json_response({"waiting": waiting_pauses()})
class AusBossPauseShot:
CATEGORY = "🆎 AusBoss/Utility"
DESCRIPTION = (
"Stops the run right after the 3D viewer, so you can frame your shot "
"on the model it just made. Turn the camera, then press Continue, here "
"or on the viewer: the run goes on with the shot as you left it, and "
"nothing before this node runs again. Stop ends the run here. Turn "
"Pause off to let runs go straight through with the camera as it was "
"when you pressed Run. Wire a 360 picture into panorama and it shows "
"behind the model while you frame, and backdrop gives the part of it "
"the camera sees, with the viewer's ground shadow under the model."
)
SEARCH_ALIASES = ["pause", "pause shot", "frame shot", "camera", "3d", "viewer", "continue", "wait", "ausboss"]
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model_3d_info": ("LOAD3D_MODEL_INFO", {"tooltip": "The model's placement, from the viewer."}),
"camera_info": ("LOAD3D_CAMERA", {"tooltip": "The camera, from the viewer."}),
"width": ("INT", {"forceInput": True, "tooltip": "The shot's width, from the viewer."}),
"height": ("INT", {"forceInput": True, "tooltip": "The shot's height, from the viewer."}),
"pause": ("BOOLEAN", {"default": True, "tooltip": "On: the run waits here while you frame the shot. Off: it goes straight through."}),
},
"optional": {
"panorama": ("IMAGE", {"tooltip": "A 360 picture (twice as wide as tall) to show behind the model and hand on as backdrop."}),
},
"hidden": {"unique_id": "UNIQUE_ID", "prompt": "PROMPT"},
}
RETURN_TYPES = ("LOAD3D_MODEL_INFO", "LOAD3D_CAMERA", "INT", "INT", "IMAGE")
RETURN_NAMES = ("model_3d_info", "camera_info", "width", "height", "backdrop")
OUTPUT_TOOLTIPS = (
"The model's placement as the viewer shows it when you press Continue.",
"The camera as the viewer shows it when you press Continue.",
"The shot's width.",
"The shot's height.",
"The part of the 360 the camera sees, at the shot's size, with the viewer's ground shadow. Grey when no 360 is wired in.",
)
FUNCTION = "wait"
@classmethod
def IS_CHANGED(cls, pause=True, **_kwargs):
# A pause asks on every run, even when nothing above it changed.
return float("nan") if pause else 0
def wait(self, model_3d_info, camera_info, width, height, pause, panorama=None, unique_id=None, prompt=None):
shot = {}
if pause and unique_id is not None:
extra = {}
viewer = viewer_of(prompt, str(unique_id))
with _lock:
shown = _viewer_results.get(viewer) if viewer else None
if shown:
extra["viewer"] = {"node": viewer, "output": shown}
if panorama is not None:
saved = _save_panorama(panorama)
if saved:
extra["panorama"] = saved
shot = _wait_for_answer(str(unique_id), extra).get("shot") or {}
model_3d_info = shot.get("model_3d_info", model_3d_info)
camera_info = shot.get("camera_info", camera_info)
width = shot.get("width", width)
height = shot.get("height", height)
if shot.get("panorama") is False:
panorama = None
backdrop = _backdrop(panorama, camera_info, shot.get("sky"), shot.get("ground"), width, height)
return (model_3d_info, camera_info, width, height, backdrop)
def _backdrop(panorama, camera_info, sky, ground, width, height):
"""The 360 as the camera sees it (grey without one), with the viewer's
shadow under the model when its Shadow setting is above 0."""
import numpy as np
import torch
width, height = max(1, int(width)), max(1, int(height))
camera = camera_info if isinstance(camera_info, dict) else {}
sky = sky if isinstance(sky, dict) else {}
if panorama is None:
view = np.full((height, width, 3), 0.5)
else:
view = view_backdrop(panorama[0, :, :, :3].float().cpu().numpy(), camera, sky, width, height)
shadow = sky.get("shadow")
if ground and isinstance(shadow, (int, float)) and not isinstance(shadow, bool) and shadow > 0:
view = view * (1 - shadow_alpha(camera, ground, shadow / 100, width, height))[..., None]
return torch.from_numpy(view.astype("float32")).unsqueeze(0)
register_routes()
NODE_CLASS_MAPPINGS = {"AUSBOSS_NODES_PauseShot": AusBossPauseShot}
NODE_DISPLAY_NAME_MAPPINGS = {"AUSBOSS_NODES_PauseShot": "Pause for Shot 🆎"}
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
+3 -3
View File
@@ -167,9 +167,9 @@ class AusBossSaveVideo:
{
"default": STEP_PREVIEW_DEFAULT,
"tooltip": (
"Show the clip's first frame here while it is "
"being made, one step at a time, with a Stop "
"button. Display only: what is saved does not "
"Show the clip here while it is being made: after "
"each step, a few of its frames play in a loop, "
"with a Stop button. Display only: what is saved does not "
"change. A run with this on asks ComfyUI for the "
"step pictures, unless you chose a preview method "
"in ComfyUI's settings."
+32 -3
View File
@@ -13,7 +13,13 @@ from ._transform_engine import (
transform_tensor_batch_chunked,
)
from ._transform_inputs import resize_inputs, spec_from_values, transform_inputs
from ._video_load_helpers import clip_load_window, decode_video_range, fixed_clip_window, lazy_audio_range
from ._video_load_helpers import (
clip_load_window,
decode_video_range,
fixed_clip_window,
lazy_audio_range,
limit_clip_length,
)
FRAME_SNAP_RULES = ("free", "8n+1", "4n+1")
@@ -50,7 +56,8 @@ class AusBossVideoCropRotatePadClip:
"for the same window, the frame count, fps, size, and duration, and a "
"stitcher so Stitch Inpaint can paste the source frames back over the "
"generated clip. Set the clip with Start, Duration and Ends at, or drag "
"its two handles on the timeline."
"its two handles on the timeline. Min and max seconds keep the clip's "
"length inside a range, for an App-mode form that shows only the clip window."
)
SEARCH_ALIASES = [
"video crop",
@@ -243,6 +250,18 @@ class AusBossVideoCropRotatePadClip:
"tooltip": "Load only this many seconds from the end of the clip; 0 loads all of it. "
"Use it to carry on from a clip: a long clip then costs no more memory than a short one.",
}),
# Appended after release: an App-mode form can show only the clip
# window, and these keep whatever is picked there inside a range.
"min_seconds": ("FLOAT", {
"default": 0.0, "min": 0.0, "max": 86400.0, "step": 0.1,
"tooltip": "The shortest the clip may be, in seconds; 0 = no limit. "
"A shorter pick grows to this. A video shorter than this is used whole.",
}),
"max_seconds": ("FLOAT", {
"default": 0.0, "min": 0.0, "max": 86400.0, "step": 0.1,
"tooltip": "The longest the clip may be, in seconds; 0 = no limit. "
"A longer pick, or the whole video, is cut to this.",
}),
})
return {"required": required, "optional": optional}
@@ -289,6 +308,8 @@ class AusBossVideoCropRotatePadClip:
frame_load_cap=None,
fixed_frames=0,
last_seconds=0.0,
min_seconds=0.0,
max_seconds=0.0,
**values,
):
path = resolve_video_path(source_mode, video, local_path)
@@ -303,6 +324,14 @@ class AusBossVideoCropRotatePadClip:
start_seconds, end_seconds, cap = fixed_clip_window(
video_metadata(path), start_seconds, fixed_frames, force_rate, nth
)
elif float(min_seconds or 0) > 0 or float(max_seconds or 0) > 0:
# An exact Fixed frames count wins over the limits.
metadata = video_metadata(path)
rate = float(force_rate or 0) or float(metadata.get("fps") or 0)
start_seconds, end_seconds, cap = limit_clip_length(
start_seconds, end_seconds, cap, metadata.get("duration") or 0,
nth / rate if rate > 0 else 0.0, min_seconds, max_seconds,
)
# The decode blocks for as long as the trim is; off the loop so the
# executor keeps answering, with the context ComfyUI's progress and
# interrupt hooks need carried along. Its errors name this node and
@@ -409,7 +438,7 @@ class AusBossVideoCropRotatePadClip:
"every_nth": max(1, int(every_nth)),
"max_frames": max(0, int(max_frames)),
"frame_snap": str(frame_snap),
**{name: values.get(name) for name in ("force_rate", "start_frame", "end_frame", "frame_load_cap", "fixed_frames", "last_seconds")},
**{name: values.get(name) for name in ("force_rate", "start_frame", "end_frame", "frame_load_cap", "fixed_frames", "last_seconds", "min_seconds", "max_seconds")},
"stitch_blend": int(stitch_blend),
"stitch_grow": int(stitch_grow),
**spec.__dict__,
+2 -2
View File
@@ -2,8 +2,8 @@
name = "ausboss-nodes"
# Manager/registry search matches against this text, so it names the actual
# nodes instead of describing the collection abstractly.
description = "ComfyUI-AusBoss (AusBoss nodes): image and video nodes with compact controls: Image and Video Crop + Rotate + Pad (frame or clip), Load Image, Load Image + Pad, Image Folder, Image Resize, Align Image, Image Size, Color Match, Image Compare A/B, Image Toolbox, Realign to Source (experimental), Save Image (PNG, WebP/JXL, captions), Load Video, Load Audio, Save Video, Select Frame, Frame Interpolate, Mask Refine, Mask by Name and Mask by Touch, LaMa Inpaint, Crop For Inpaint, Stitch Inpaint, Tiled Upscale and Tiled Upscale Stitch, FlashVSR Upscale, Edit Lock and Edit Lock Restore, LoRA Loader, Krea 2 Encode and Outpaint Model Patch, Latent Size, Layout Boxes, Seed, Select Every Nth, Split Batch, Merge Batches, Text, Text Lines, Prompt Variations, H3 Prompt Writer, Integer, Float, Math Expression, Show Text, Free Memory, Workflow Note, Workflow Note Tile, Callout, Callout Tile, Workflow Switches, Run Timer, and Step Preview. Examples for Qwen Image 2.1, Krea 2, Klein 9B and LTX 2.3."
version = "2.26.6"
description = "ComfyUI-AusBoss (AusBoss nodes): image and video nodes with compact controls: Image and Video Crop + Rotate + Pad, Load Image, Load Image + Pad, Image Folder, Image Resize, Align Image, Image Size, Color Match, Image Compare A/B, Image Toolbox, Realign to Source (experimental), Save Image (PNG, WebP/JXL, captions), Load Video, Load Audio, Save Video, Select Frame, Frame Interpolate, Mask Refine, Mask by Name and Mask by Touch, LaMa Inpaint, Crop For Inpaint, Stitch Inpaint, Tiled Upscale and Tiled Upscale Stitch, FlashVSR Upscale, Edit Lock and Edit Lock Restore, LoRA Loader, Krea 2 Encode and Outpaint Model Patch, Latent Size, Layout Boxes, Seed, Select Every Nth, Split Batch, Merge Batches, Text, Text Lines, Prompt Variations, H3 Prompt Writer, Integer, Float, Math Expression, Show Text, Free Memory, Workflow Note, Workflow Note Tile, Callout, Callout Tile, Workflow Switches, Run Timer, Step Preview, and Pause for Shot. Examples for Qwen Image 2.1, Krea 2, Klein 9B and LTX 2.3."
version = "2.27.0"
# comfy-cli serializes this to JSON verbatim, so `file` publishes the literal
# string {"file": "LICENSE"} to the registry listing. `text` puts a readable
# name there instead. Both forms are supported; the LICENSE file is unchanged.
+2
View File
@@ -130,6 +130,7 @@ import fnmatch
ARCHIVE_ALLOWLIST = (
"__init__.py", "nodes/", "js/", "example_workflows/", "README.md",
"LICENSE", "pyproject.toml", "ausboss_presets_example.json", "locales/",
"web_second_copy/",
)
# Besides every allowlist entry these must ship too: the node help pages and
# the sample media the example workflows load.
@@ -298,6 +299,7 @@ NETWORK_PATTERNS = {
NETWORK_IMPORTS = {"requests", "httpx", "socket", "urllib.request", "http.client", "aiohttp.ClientSession"}
shipped_source = [ROOT / "__init__.py", *sorted((ROOT / "nodes").rglob("*.py"))]
shipped_source += sorted(p for p in (ROOT / "js").rglob("*") if p.suffix in (".js", ".mjs"))
shipped_source += sorted(p for p in (ROOT / "web_second_copy").rglob("*") if p.suffix in (".js", ".mjs"))
for path in shipped_source:
if "__pycache__" in path.parts or not path.is_file():
continue
+1
View File
@@ -58,6 +58,7 @@ PUBLIC_NODE_IDS = {
"AUSBOSS_NODES_CropForInpaint",
"AUSBOSS_NODES_EditLock",
"AUSBOSS_NODES_EditLockRestore",
"AUSBOSS_NODES_PauseShot",
"AUSBOSS_NODES_FlashVSRUpscale",
"AUSBOSS_NODES_Float",
"AUSBOSS_NODES_FrameInterpolate",
+4
View File
@@ -76,6 +76,10 @@ def pack_widget_names() -> dict[str, list[str]]:
groups = {k.value: v for k, v in zip(returned[0].keys, returned[0].values) if isinstance(k, ast.Constant)}
for group in ("required", "optional"):
inputs = groups.get(group)
# A group wrapped in a call, such as LoRA Loader's open
# optional inputs, lists its fixed inputs in the one dict.
if isinstance(inputs, ast.Call) and len(inputs.args) == 1:
inputs = inputs.args[0]
if not isinstance(inputs, ast.Dict):
continue
for name, spec in zip(inputs.keys, inputs.values):
+1 -1
View File
@@ -172,7 +172,7 @@ comfy node install ausboss-nodes
```
```bash
git clone https://github.com/ausboss/ComfyUI-AusBoss.git
git clone https://github.com/ausboss/ComfyUI-AusBoss.git ausboss-nodes
```
The first needs comfy-cli. The second runs inside ComfyUI's `custom_nodes`
+9 -1
View File
@@ -1,7 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import { appFields, createAppModeSync, workflowMode } from "../js/shared/app_mode.mjs";
import { appFields, createAppModeSync, formHostSelector, workflowMode } from "../js/shared/app_mode.mjs";
import { hideWidget, isWidgetHidden } from "../js/shared/widget_visibility.mjs";
function graph() {
@@ -69,3 +69,11 @@ test("builder mode and the graph leave card widgets hidden", () => {
assert.equal(isWidgetHidden(g.find("256", "image").widget), true);
}
});
test("formHostSelector names the form row's host for one node's widget", () => {
const selector = formHostSelector(150, "clip_window");
assert.match(selector, /\[data-widget-key\$=":150:clip_window"\]/);
assert.match(selector, /\[data-widget-name="clip_window"\] div\[node-type\]$/);
// Quotes and backslashes cannot break out of the attribute value.
assert.doesNotMatch(formHostSelector('1"]x', 'a\\"b'), /"\]x|\\/);
});
+112
View File
@@ -0,0 +1,112 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
AXES, autoConstraint, closestOnAxis, constraintLabel, nearestLocalAxis, nearestScreenAxis, nextConstraint,
parseTyped, pickVector, rayPlane, readout, scaleFactors, screenTurn, snapStep, snapTo, typeKey,
} from "../js/shared/blender_transform.mjs";
const near = (a, b, eps = 1e-9) => assert.ok(Math.abs(a - b) < eps, `${a} != ${b}`);
test("an axis key locks global, then local, then lets go", () => {
let c = nextConstraint(null, "x");
assert.deepEqual(c, { kind: "axis", axis: "x", space: "global" });
c = nextConstraint(c, "x");
assert.equal(c.space, "local");
assert.equal(nextConstraint(c, "x"), null);
// Another axis starts over on that axis.
assert.deepEqual(nextConstraint({ kind: "axis", axis: "x", space: "local" }, "y"), { kind: "axis", axis: "y", space: "global" });
// Shift+axis is the plane that leaves the axis out.
assert.equal(nextConstraint(nextConstraint(null, "x"), "x", true).kind, "plane");
});
test("the lock reads in plain words", () => {
assert.equal(constraintLabel(null), "");
assert.equal(constraintLabel({ kind: "axis", axis: "x", space: "global" }), "along global X");
assert.equal(constraintLabel({ kind: "plane", axis: "y", space: "local" }), "on local XZ");
});
test("a ray meets the floor; a ray along it never does", () => {
near(rayPlane([0, 5, 0], [0, -1, 0], [0, 0, 0], [0, 1, 0]), 5);
assert.equal(rayPlane([0, 5, 0], [1, 0, 0], [0, 0, 0], [0, 1, 0]), null);
});
test("the spot on an axis nearest a ray", () => {
// A ray straight down at x = 2 meets the X axis at 2.
near(closestOnAxis([2, 5, 0], [0, -1, 0], [0, 0, 0], AXES.x), 2);
// Looking straight along the axis: no answer.
assert.equal(closestOnAxis([0, 0, 5], [0, 0, -1], [0, 0, 0], AXES.z), null);
});
test("a screen turn is counter-clockwise positive with y down", () => {
near(screenTurn([0, 0], [1, 0], [0, -1]), Math.PI / 2);
near(screenTurn([0, 0], [1, 0], [0, 1]), -Math.PI / 2);
assert.equal(screenTurn([0, 0], [0, 0], [1, 1]), 0);
});
test("typing a number the way Blender takes it", () => {
let text = "";
for (const key of ["1", ".", "5", ".", "-"]) text = typeKey(text, key);
assert.equal(text, "-1.5");
assert.equal(parseTyped(text), -1.5);
assert.equal(parseTyped(typeKey(text, "-")), 1.5);
assert.equal(typeKey("12", "Backspace"), "1");
assert.equal(parseTyped(""), null);
assert.equal(parseTyped("-"), null);
assert.equal(parseTyped("."), null);
assert.equal(typeKey("1", "a"), "1");
});
test("Ctrl snaps; Shift makes the step ten times finer", () => {
assert.equal(snapStep("rotate", false), 5);
assert.equal(snapStep("rotate", true), 1);
assert.equal(snapStep("move", false), 0.1);
assert.equal(snapStep("scale", true), 0.01);
near(snapTo(17.4, 5), 15);
near(snapTo(0.26, 0.1), 0.3);
assert.equal(snapTo(0.26, 0), 0.26);
});
test("scaling along a world axis picks the model's nearest own axis", () => {
// Turned 90 degrees about Y: its own X points along world -Z.
const local = [[0, 0, -1], [0, 1, 0], [1, 0, 0]];
assert.equal(nearestLocalAxis(local, AXES.z), 0);
assert.equal(nearestLocalAxis(local, AXES.x), 2);
assert.deepEqual(scaleFactors(2, null, 0), [2, 2, 2]);
assert.deepEqual(scaleFactors(2, { kind: "axis", axis: "x" }, 0), [2, 1, 1]);
assert.deepEqual(scaleFactors(2, { kind: "plane", axis: "y" }, 1), [2, 1, 2]);
});
test("the middle button picks the axis the mouse slides along", () => {
// A view from the front-right: X runs right and down, Y (up) runs up the
// screen, Z runs left and down (screen y points down).
const screen = [[40, 12], [0, -45], [-30, 18]];
assert.equal(nearestScreenAxis([0, -60], screen), 1); // up the screen: the vertical axis
assert.equal(nearestScreenAxis([0, 30], screen), 1); // down too
assert.equal(nearestScreenAxis([80, 20], screen), 0);
assert.equal(nearestScreenAxis([-50, 31], screen), 2);
// An axis pointing at the camera is left out.
assert.equal(nearestScreenAxis([0, -60], [[40, 12], [0, -0.5], [-30, 18]], 3), 2);
assert.equal(nearestScreenAxis([0, 0], screen), -1);
});
test("held, the move since the press picks; clicked, the move since G", () => {
// Held and slid: the move since the press.
assert.deepEqual(pickVector([0, 0], [100, 0], [100, -20]), [0, -20]);
// A click after moving: the whole move since G.
assert.deepEqual(pickVector([0, 0], [100, 0], [102, 1]), [102, 1]);
// A click before any move: nothing yet, so the next move picks.
assert.equal(pickVector([0, 0], [2, 1], [3, 1]), null);
assert.equal(pickVector([0, 0], null, [3, 1]), null);
assert.deepEqual(autoConstraint("y"), { kind: "axis", axis: "y", space: "global" });
assert.deepEqual(autoConstraint("y", true), { kind: "plane", axis: "y", space: "global" });
});
test("the header reads like Blender's", () => {
assert.equal(readout("grab", [0, -0.5, 0], { kind: "axis", axis: "y" }, -0.5), "D: -0.500 (0.500)");
assert.equal(readout("grab", [0.3, 0, 0.4]), "Dx: 0.300 Dy: 0.000 Dz: 0.400 (0.500)");
assert.equal(readout("rotate", 45), "Rot: 45.0°");
assert.equal(readout("trackball", [10, -5]), "Trackball: 10.0° -5.0°");
assert.equal(readout("scale", 1.2, { kind: "axis", axis: "x" }), "Scale: 1.200");
assert.equal(readout("scale", 2), "Scale X: 2.000 Y: 2.000 Z: 2.000");
});
+11
View File
@@ -410,3 +410,14 @@ test("an Info card saves as a plain Callout, so an older pack shows its text", (
assert.ok(!saved[1].includes("card"), "an Info card would save as a Callout Tile");
assert.match(source, /\["card","Info card"\]/, "the Info card is gone from the note's menu");
});
test("the Callout's styles leave the shared card classes alone", () => {
// Its stylesheet is global: a rule on a class widget_card.mjs owns
// restyles every node card on the page (a card row turned into a flex
// row squeezed Workflow Switches' names down to a letter or two).
const shared = new Set(readFileSync(join(ROOT, "js/shared/widget_card.mjs"), "utf8").match(/ausboss-card-[a-z-]+/g));
const callout = readFileSync(join(ROOT, "js/callout/index.js"), "utf8");
// `.name` is a rule in its CSS; using a shared class on an element is fine.
const clashes = [...new Set(callout.match(/\.ausboss-card-[a-z-]+/g) ?? [])].map((rule) => rule.slice(1)).filter((name) => shared.has(name));
assert.deepEqual(clashes, []);
});
+168
View File
@@ -0,0 +1,168 @@
// Length limits (min_seconds / max_seconds) and the App-mode clip window.
// limitClipSeconds mirrors nodes/_video_load_helpers.limit_clip_length; the
// rows below are the ones tests/test_clip_length_limits.py holds it to.
import assert from "node:assert/strict";
import test from "node:test";
import {
clipInfo,
clipWindowOf,
clipWindowValues,
dragClipWindow,
frameWindow,
lengthLimits,
limitClipSeconds,
limitFrameRange,
limitFrames,
loopPlayhead,
} from "../js/shared/timeline_math.mjs";
const DURATION = 15.4;
const FRAME = 1 / 24;
const LIMITS = { min: 5, max: 8 };
// The test video of the Person Swap App: 23.976 fps, 370 frames.
const VIDEO = clipInfo({ fps: 24000 / 1001, frame_count: 370, duration: 15.432083 });
const limit = ({ start = 0, end = 0, cap = 0, duration = DURATION, step = FRAME, min = 5, max = 8 } = {}) =>
limitClipSeconds({ start, end, cap, duration, frameSeconds: step }, { min, max });
function window(got, start, end, cap) {
assert.ok(Math.abs(got.start - start) < 1e-6, `start ${got.start} != ${start}`);
assert.ok(Math.abs(got.end - end) < 1e-6, `end ${got.end} != ${end}`);
assert.equal(got.cap, cap);
}
test("limits: 0 is no limit and a max below the min counts as the min", () => {
assert.deepEqual(lengthLimits(0, 0), { min: 0, max: 0, active: false });
assert.deepEqual(lengthLimits(6, 2), { min: 6, max: 6, active: true });
assert.deepEqual(lengthLimits(-1, Number.NaN), { min: 0, max: 0, active: false });
const same = limitClipSeconds({ start: 1, end: 0, cap: 30, duration: DURATION, frameSeconds: FRAME }, { min: 0, max: 0 });
assert.equal(same.changed, false);
window(same, 1, 0, 30);
});
test("limits: the same rows as the backend", () => {
window(limit(), 0, 8, 0);
window(limit({ start: 3, cap: 192 }), 3, 0, 192);
window(limit({ start: 2, end: 8.5 }), 2, 8.5, 0);
window(limit({ start: 2, end: 4 }), 2, 7, 0);
window(limit({ start: 2, cap: 48 }), 2, 7, 0);
window(limit({ start: 1, cap: 300 }), 1, 9, 300);
window(limit({ start: 13 }), DURATION - 5, DURATION, 0);
const whole = limit({ start: 1, end: 2, duration: 4.2 });
assert.equal(whole.whole, true);
window(whole, 0, 0, 0);
window(limit({ min: 6, max: 2 }), 0, 6, 0);
window(limit({ start: 1, min: 0 }), 1, 9, 0);
window(limit({ start: 1, end: 3, min: 0 }), 1, 3, 0);
window(limit({ start: 1, duration: 0, min: 0 }), 1, 9, 0);
window(limit({ start: 4, end: 2 }), 4, 2, 0);
});
test("a Duration stays inside the limits, and inward under a snap rule", () => {
assert.deepEqual(limitFrameRange(LIMITS, 24), { min: 120, max: 192 });
assert.deepEqual(limitFrameRange({}, 24), { min: 1, max: Infinity });
assert.equal(limitFrames(300, LIMITS, 24), 192);
assert.equal(limitFrames(10, LIMITS, 24), 120);
assert.equal(limitFrames(150, LIMITS, 24), 150);
assert.equal(limitFrames(300, {}, 24), 300);
// 8n+1 inside 120..192: 121 and 185.
assert.equal(limitFrames(10, LIMITS, 24, "8n+1"), 121);
assert.equal(limitFrames(300, LIMITS, 24, "8n+1"), 185);
});
test("the clip window shows what a run uses: the first 8 s of a 15.4 s video", () => {
const box = clipWindowOf(VIDEO, { rate: 24 }, LIMITS);
assert.equal(box.start, 0);
assert.equal(box.frames, 192);
assert.equal(box.seconds, 8);
assert.equal(box.fills, false);
// A saved Duration of 192 frames from 3 s is kept as it is.
const saved = clipWindowOf(VIDEO, { start: 3, cap: 192, rate: 24 }, LIMITS);
assert.equal(saved.frames, 192);
assert.ok(Math.abs(saved.start - 3.003) < 1e-3);
});
test("dragging an edge stops at 5 s and at 8 s", () => {
const box = clipWindowOf(VIDEO, { rate: 24 }, LIMITS);
assert.equal(dragClipWindow(box, "end", 20, VIDEO, LIMITS).seconds, 8);
assert.equal(dragClipWindow(box, "end", 1, VIDEO, LIMITS).seconds, 5);
assert.equal(dragClipWindow(box, "end", 6.5, VIDEO, LIMITS).seconds, 6.5);
const later = dragClipWindow(box, "start", 6, VIDEO, LIMITS);
assert.equal(later.seconds, 5);
assert.ok(Math.abs(later.start + later.seconds - 8) < 1 / 24);
const earlier = dragClipWindow(later, "start", -4, VIDEO, LIMITS);
assert.equal(earlier.seconds, 8);
assert.equal(earlier.start, 0);
});
test("dragging the box keeps its length and stops at the video's ends", () => {
const box = clipWindowOf(VIDEO, { rate: 24 }, LIMITS);
assert.equal(dragClipWindow(box, "move", -2, VIDEO, LIMITS).start, 0);
const end = dragClipWindow(box, "move", 12, VIDEO, LIMITS);
assert.equal(end.frames, 192);
assert.ok(end.start + end.seconds <= VIDEO.duration + 1e-9);
assert.ok(end.start + end.seconds > VIDEO.duration - 2 / 24);
// The edge at the video's end cannot grow past it.
assert.ok(dragClipWindow({ ...end, frames: 120, seconds: 5 }, "end", 99, VIDEO, LIMITS).seconds <= VIDEO.duration - end.start);
});
test("what the window stores runs the same frames", () => {
const box = dragClipWindow(clipWindowOf(VIDEO, { rate: 24 }, LIMITS), "move", 3, VIDEO, LIMITS);
const stored = clipWindowValues(box, VIDEO);
assert.deepEqual(stored, { start_seconds: 3, end_seconds: 0, max_frames: 192 });
assert.equal(frameWindow(VIDEO, stored.start_seconds, 0).first, Math.round(box.start * VIDEO.fps));
const again = clipWindowOf(VIDEO, { start: stored.start_seconds, cap: stored.max_frames, rate: 24 }, LIMITS);
assert.equal(again.frames, box.frames);
assert.ok(Math.abs(again.start - box.start) < 1e-9);
});
test("a video shorter than the min is used whole and cannot be dragged", () => {
const short = clipInfo({ fps: 24, frame_count: 100, duration: 100 / 24 });
const box = clipWindowOf(short, { start: 1, rate: 24 }, LIMITS);
assert.equal(box.whole, true);
assert.equal(box.start, 0);
assert.equal(box.frames, 100);
assert.equal(dragClipWindow(box, "move", 2, short, LIMITS), box);
});
test("without limits the box can be as short as a frame and as long as the video", () => {
const box = clipWindowOf(VIDEO, { rate: 24 }, {});
assert.equal(box.fills, true);
assert.equal(dragClipWindow(box, "end", 0, VIDEO, {}).frames, 1);
});
test("the limits fold's closed line says what is set", async () => {
const { limitsSummary } = await import("../js/shared/timeline_math.mjs");
assert.equal(limitsSummary(5, 8), "5 – 8 s");
assert.equal(limitsSummary(0, 0), "off");
assert.equal(limitsSummary(5, 0), "from 5 s");
assert.equal(limitsSummary(0, 8), "up to 8 s");
assert.equal(limitsSummary(6, 6), "6 s");
assert.equal(limitsSummary(2.5, 7.25), "2.5 – 7.25 s");
// A saved max under the min reads as the min, as the run treats it.
assert.equal(limitsSummary(6, 2), "6 s");
assert.equal(limitsSummary(-1, Number.NaN), "off");
});
test("typing one limit never leaves the shortest above the longest", async () => {
const { setLengthLimit } = await import("../js/shared/timeline_math.mjs");
assert.deepEqual(setLengthLimit("min", 9, { min: 5, max: 8 }), { min: 9, max: 9 });
assert.deepEqual(setLengthLimit("max", 3, { min: 5, max: 8 }), { min: 3, max: 3 });
assert.deepEqual(setLengthLimit("min", 6, { min: 5, max: 8 }), { min: 6, max: 8 });
// 0 is off: it never drags the other limit along.
assert.deepEqual(setLengthLimit("max", 0, { min: 5, max: 8 }), { min: 5, max: 0 });
assert.deepEqual(setLengthLimit("min", 9, { min: 0, max: 0 }), { min: 9, max: 0 });
assert.deepEqual(setLengthLimit("min", -2, { min: 5, max: 8 }), { min: 0, max: 8 });
});
test("the player stays inside the picked part and loops back to its start", () => {
assert.equal(loopPlayhead(4.5, 3, 5), 4.5);
assert.equal(loopPlayhead(8, 3, 5), 3);
assert.equal(loopPlayhead(9.2, 3, 5), 3);
assert.equal(loopPlayhead(1, 3, 5), 3);
// A hair before the start (a seek that landed a frame early) is kept.
assert.equal(loopPlayhead(2.98, 3, 5), 2.98);
assert.equal(loopPlayhead(Number.NaN, 3, 5), 3);
assert.equal(loopPlayhead(0.5, -1, 5), 0.5);
});
+39 -2
View File
@@ -251,7 +251,8 @@
"video_job",
"sound",
"music",
"clip_sound"
"clip_sound",
"full_prompt"
],
"outputs": [
[
@@ -867,6 +868,40 @@
]
]
},
"AUSBOSS_NODES_PauseShot": {
"required": [
"model_3d_info",
"camera_info",
"width",
"height",
"pause"
],
"optional": [
"panorama"
],
"outputs": [
[
"LOAD3D_MODEL_INFO",
"model_3d_info"
],
[
"LOAD3D_CAMERA",
"camera_info"
],
[
"INT",
"width"
],
[
"INT",
"height"
],
[
"IMAGE",
"backdrop"
]
]
},
"AUSBOSS_NODES_PromptVariations": {
"required": [
"text",
@@ -1306,7 +1341,9 @@
"end_frame",
"frame_load_cap",
"fixed_frames",
"last_seconds"
"last_seconds",
"min_seconds",
"max_seconds"
],
"outputs": [
[
+45
View File
@@ -0,0 +1,45 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { FULL, SIMPLE, TAB_PROPERTY, boxText, editValue, isEdited, promptTab, writtenFromOutput } from "../js/shared/h3_full_prompt_math.mjs";
import { visibleRows } from "../js/shared/widget_card_math.mjs";
const WRITTEN = "summary:\nA slow push in. One continuous shot with no cuts.";
test("an edit is kept only when it differs from what the node wrote", () => {
assert.equal(editValue("summary:\nOne continuous shot with no cuts.", WRITTEN), "summary:\nOne continuous shot with no cuts.");
assert.equal(editValue(WRITTEN, WRITTEN), "");
assert.equal(editValue(` ${WRITTEN}\n`, WRITTEN), "");
assert.equal(editValue(" \n", WRITTEN), "");
// Before any run there is nothing written: whatever is typed is the edit.
assert.equal(editValue("my own prompt", ""), "my own prompt");
});
test("the box shows the edit, else the last written prompt", () => {
assert.equal(boxText({ full_prompt: "" }, WRITTEN), WRITTEN);
assert.equal(boxText({ full_prompt: "mine" }, WRITTEN), "mine");
assert.equal(boxText({}, ""), "");
assert.equal(isEdited({ full_prompt: " \n" }), false);
assert.equal(isEdited({ full_prompt: "mine" }), true);
});
test("the tab is Simple unless the node says Full", () => {
assert.equal(promptTab({}), SIMPLE);
assert.equal(promptTab({ properties: { [TAB_PROPERTY]: "nonsense" } }), SIMPLE);
assert.equal(promptTab({ properties: { [TAB_PROPERTY]: FULL } }), FULL);
});
test("the written prompt is read from a run's ui output", () => {
assert.equal(writtenFromOutput({ written_prompt: [WRITTEN] }), WRITTEN);
assert.equal(writtenFromOutput({ written_prompt: WRITTEN }), WRITTEN);
assert.equal(writtenFromOutput({ text: ["other"] }), null);
assert.equal(writtenFromOutput(null), null);
});
test("a row's when can follow a choice kept on the node", () => {
const simple = { widget: "script", when: (values, node) => promptTab(node) !== FULL };
const full = { panel: () => ({}), when: (values, node) => promptTab(node) === FULL };
const node = { properties: {} };
assert.deepEqual(visibleRows([simple, full], {}, {}, node), [simple]);
node.properties[TAB_PROPERTY] = FULL;
assert.deepEqual(visibleRows([simple, full], {}, {}, node), [full]);
});
+72
View File
@@ -0,0 +1,72 @@
// The Chinese on the pack's own node faces (js/shared/i18n.mjs).
//
// - a string with no Chinese entry stays English,
// - every word a widget card shows has a Chinese entry, or is on the short
// list of things that deliberately stay English,
// - only displayed text is translated: nothing in a card config that names a
// widget or a value is a key of the table by accident of spelling.
import assert from "node:assert/strict";
import fs from "node:fs";
import test from "node:test";
import { PATTERNS, STAYS_ENGLISH, ZH } from "../js/shared/i18n_zh.mjs";
import { isChineseLocale, translateText } from "../js/shared/i18n.mjs";
import { PANEL_LABELS } from "../js/shared/panel_controls.mjs";
const cards = fs.readFileSync(new URL("../js/widget_cards/index.js", import.meta.url), "utf8");
// Every string a card shows: row labels, group headers, pill texts, the
// words of a choice (`labels`), tooltips (`title`, `titles`), placeholders,
// button captions.
function displayedStrings(source) {
const found = new Set();
const literal = (raw) => JSON.parse(`"${raw}"`);
for (const match of source.matchAll(/\b(?:label|onText|offText|placeholder|title|muteTitle|readOnlyTitle|section|text|readOnlyText)\s*:\s*"((?:[^"\\]|\\.)*)"/g)) found.add(literal(match[1]));
for (const block of source.matchAll(/\b(?:labels|titles)\s*:\s*\{([^}]*)\}/g)) {
for (const match of block[1].matchAll(/:\s*"((?:[^"\\]|\\.)*)"/g)) found.add(literal(match[1]));
}
return found;
}
test("an unknown string stays English", () => {
assert.equal(translateText("A sentence no table has ever heard of"), "A sentence no table has ever heard of");
assert.equal(translateText(""), "");
assert.equal(translateText(" "), " ");
assert.equal(translateText("constructor"), "constructor");
assert.equal(translateText("toString"), "toString");
assert.equal(translateText("Preview", {}, []), "Preview");
});
test("a known string is translated and keeps the spaces around it", () => {
assert.equal(translateText("Feather"), ZH.Feather);
assert.equal(translateText(" Feather\n"), ` ${ZH.Feather}\n`);
assert.notEqual(ZH.Feather, "Feather");
});
test("the scrub hint is translated around a tooltip", () => {
const out = translateText("Feather. Drag to scrub, click to type a number or a sum (1024*1.5), arrows to step; Shift = fine.");
assert.match(out, /拖动调节/);
assert.ok(out.startsWith("Feather."));
const known = translateText("Do nothing Drag to scrub, click to type a number or a sum (1024*1.5), arrows to step; Shift = fine.");
assert.ok(known.startsWith(ZH["Do nothing"]) && /拖动调节/.test(known));
});
test("every Chinese language code takes the Chinese table", () => {
for (const code of ["zh", "zh-CN", "zh-TW", "zh_CN", "ZH"]) assert.equal(isChineseLocale(code), true, code);
for (const code of ["en", "ja", "ko", "", undefined, null, "zhx"]) assert.equal(isChineseLocale(code), false, String(code));
});
test("no entry is empty or the same as its key without being listed as English", () => {
for (const [english, chinese] of Object.entries(ZH)) {
assert.ok(typeof chinese === "string" && chinese.length > 0, `empty entry for ${english}`);
}
for (const [pattern] of PATTERNS) assert.ok(pattern instanceof RegExp);
});
test("every word a widget card shows has a Chinese entry or stays English on purpose", () => {
const strings = new Set([...displayedStrings(cards), ...Object.values(PANEL_LABELS).flatMap((value) => (typeof value === "string" ? [value] : Object.values(value)))]);
assert.ok(strings.size > 150, `only ${strings.size} strings found: the extraction broke`);
const missing = [...strings].filter((text) => !(text in ZH) && !STAYS_ENGLISH.has(text) && !/^[^A-Za-z]*$/.test(text));
assert.deepEqual(missing, []);
});
+51
View File
@@ -0,0 +1,51 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { browseMediaRows, mediaFolderOf, visibleMediaRange } from "../js/shared/media_list.mjs";
test("folder browsing shows only direct children and preserves original filenames", () => {
const values = ["root.png", "photos/cover.png", "photos/archive/old.png", "other/test.png"];
assert.deepEqual(browseMediaRows(values, "", []).map(({ kind, value, label }) => [kind, value ?? label]), [
["folder", "photos"], ["folder", "other"], ["file", "root.png"],
]);
assert.deepEqual(browseMediaRows(values, "", ["photos"]).map(({ kind, value, label }) => [kind, value ?? label]), [
["back", ".."], ["folder", "archive"], ["file", "photos/cover.png"],
]);
assert.deepEqual(browseMediaRows(values, "", ["photos", "archive"]).map(({ kind, value }) => [kind, value]), [
["back", undefined], ["file", "photos/archive/old.png"],
]);
});
test("search finds files across all folders and returns full widget values", () => {
const values = ["photos/archive/old.png", "other/oldest.png", "root.png"];
assert.deepEqual(browseMediaRows(values, "old", ["other"]).map((item) => item.value), values.slice(0, 2));
assert.deepEqual(browseMediaRows(values, "missing", []), []);
});
test("folder paths handle Windows separators and Output suffixes", () => {
const values = ["renders\\set\\001.png [output]", "renders/set/002.png [output]"];
const bare = (value) => value.replace(/ \[output\]$/, "");
assert.deepEqual(browseMediaRows(values, "", [], bare).map((x) => x.label), ["renders"]);
assert.deepEqual(browseMediaRows(values, "", ["renders", "set"], bare).filter((x) => x.kind === "file").map((x) => x.value), values);
});
test("virtualized list renders a bounded number of rows even far past item 400", () => {
const total = 1200;
const first = visibleMediaRange(total, 0, 320, 26, 8);
const deep = visibleMediaRange(total, 900 * 26, 320, 26, 8);
assert.deepEqual(first, { first: 0, last: 21 });
assert.equal(deep.first, 892);
assert.ok(deep.last - deep.first < 40);
assert.equal(visibleMediaRange(0, 0, 320, 26, 8).last, 0);
assert.equal(visibleMediaRange(1200, 1195 * 26, 320, 26, 8).last, 1200);
});
test("the picker opens in the folder of the current pick", () => {
const bare = (value) => value.replace(/ \[output\]$/, "");
assert.deepEqual(mediaFolderOf("photos/2025/trip.png"), ["photos", "2025"]);
assert.deepEqual(mediaFolderOf("renders\\set\\001.png [output]", bare), ["renders", "set"]);
assert.deepEqual(mediaFolderOf("root.png"), []);
assert.deepEqual(mediaFolderOf(""), []);
const values = ["photos/2025/trip.png", "photos/cover.png", "root.png"];
const rows = browseMediaRows(values, "", mediaFolderOf("photos/2025/trip.png"));
assert.ok(rows.some((row) => row.value === "photos/2025/trip.png"));
});
+2 -1
View File
@@ -149,7 +149,7 @@ test("a panel that should follow the node's height never declares computeSize",
//
// workflow_switches is a list sized to its rows, like the widget cards: one
// row per switch, and extra height would only be dead space under the last.
const fixedByDesign = new Set(["run_timer", "save_image", "seed", "widget_cards", "workflow_switches"]);
const fixedByDesign = new Set(["pause_shot", "run_timer", "save_image", "seed", "viewer_ratio", "widget_cards", "workflow_switches"]);
const seen = new Set();
for (const { name, source } of domWidgetEntries()) {
seen.add(name);
@@ -391,6 +391,7 @@ test("every panel root class carries border-box and an overflow clip", () => {
load_image_pad: ".ausboss-loadpad-root{",
image_crop_rotate_pad: ".ausboss-transform-panel{",
image_folder: ".ausboss-if{",
pause_shot: ".ausboss-pshot{",
layout_boxes: ".ausboss-lb{",
mask_by_touch: ".ausboss-touch{",
save_image: ".ausboss-save{",
+38
View File
@@ -0,0 +1,38 @@
import assert from "node:assert/strict";
import test from "node:test";
import { showSecondCopyNotices } from "../web_second_copy/notice.mjs";
test("an old copy loading shows a toast that stays until closed", () => {
const added = [];
const shown = showSecondCopyNotices(
[{ summary: "AusBoss: an old copy is loading", detail: "Delete custom_nodes/ComfyUI-AusBoss", older: true }],
{ add: (message) => added.push(message) },
);
assert.equal(added.length, 1);
assert.equal(added[0].severity, "error");
assert.equal(added[0].life, undefined);
assert.match(added[0].detail, /ComfyUI-AusBoss/);
assert.deepEqual(shown, added);
});
test("a newer copy loading is a warning", () => {
const added = [];
showSecondCopyNotices([{ detail: "Delete one", older: false }], { add: (m) => added.push(m) });
assert.equal(added[0].severity, "warn");
assert.equal(added[0].summary, "AusBoss is installed twice");
});
test("no toast store falls back to the console, and junk is ignored", () => {
const warned = [];
const original = console.warn;
console.warn = (line) => warned.push(line);
try {
const shown = showSecondCopyNotices([null, {}, { detail: "Delete one" }], undefined);
assert.equal(shown.length, 1);
assert.equal(warned.length, 1);
assert.equal(showSecondCopyNotices({ not: "a list" }, undefined).length, 0);
} finally {
console.warn = original;
}
});
+38
View File
@@ -6,6 +6,7 @@ import {
consumersOf,
drawsTiles,
feedsInto,
frameMs,
nextRunState,
resultRank,
stepFraction,
@@ -326,3 +327,40 @@ test("tile events from another run or after the end change nothing", () => {
const tiling = nextRunState(started, { type: "tiles", promptId: "p1", on: true });
assert.equal(nextRunState(tiling, { type: "start", promptId: "p3" }).tiling, false);
});
test("a clip's frames ride with the step picture of the node that made them", () => {
const frames = { type: "frames", promptId: "p1", maker: "5:3", list: ["a", "b", "c"], seconds: 1 };
const run = play([
{ type: "start", promptId: "p1" },
frames,
{ type: "picture", promptId: "p1", maker: "5:3", real: "5:3", url: "blob:1" },
]);
assert.deepEqual(run.frames, { maker: "5:3", list: ["a", "b", "c"], seconds: 1 });
assert.equal(run.url, "blob:1");
// The next sampler's still drops them; its own frames would come first.
const next = nextRunState(run, { type: "picture", promptId: "p1", maker: "9", real: "9", url: "blob:2" });
assert.equal(next.frames, null);
// A stopped run keeps the frames it reached.
const stopped = nextRunState(run, { type: "end", promptId: "p1", kind: "interrupted" });
assert.equal(stopped.frames, run.frames);
// A new run starts without them.
assert.equal(nextRunState(stopped, { type: "start", promptId: "p2" }).frames, null);
});
test("frames from another run, a single frame or junk change nothing", () => {
const run = play([{ type: "start", promptId: "p1" }]);
assert.equal(nextRunState(run, { type: "frames", promptId: "p2", maker: "1", list: ["a", "b"] }), run);
assert.equal(nextRunState(run, { type: "frames", promptId: "p1", maker: "1", list: ["a"] }), run);
assert.equal(nextRunState(run, { type: "frames", promptId: "p1", maker: "1", list: "x" }), run);
assert.equal(nextRunState(IDLE, { type: "frames", promptId: "p1", maker: "1", list: ["a", "b"] }), IDLE);
const kept = nextRunState(run, { type: "frames", promptId: "p1", maker: "1", list: ["a", 3, "", "b"], seconds: "x" });
assert.deepEqual(kept.frames, { maker: "1", list: ["a", "b"], seconds: 1 });
});
test("each frame stays up for the clip's own pace, within bounds", () => {
assert.equal(frameMs({ seconds: 1 }), 1000);
assert.equal(frameMs({ seconds: 0.85 }), 850);
assert.equal(frameMs({ seconds: 0.01 }), 250);
assert.equal(frameMs({ seconds: 9 }), 2000);
assert.equal(frameMs(null), 1000);
});
+60
View File
@@ -0,0 +1,60 @@
"""The ground shadow Pause for Shot draws into its backdrop."""
from __future__ import annotations
from pathlib import Path
import sys
import unittest
import numpy as np
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes._backdrop_helpers import clean_ground, shadow_alpha, shadow_falloff
# A camera 3 up and 3 back, looking at the floor's middle.
CAMERA = {"position": {"x": 0, "y": 3, "z": 3}, "target": {"x": 0, "y": 0, "z": 0}, "fov": 50, "zoom": 1}
GROUND = {"y": 0, "cx": 0, "cz": 0, "rx": 1, "rz": 1}
class ShadowTests(unittest.TestCase):
def test_falloff_is_full_in_the_middle_and_gone_at_the_edge(self):
self.assertAlmostEqual(float(shadow_falloff(np.array(0.0))), 1.0)
self.assertAlmostEqual(float(shadow_falloff(np.array(1.0))), 0.0)
self.assertAlmostEqual(float(shadow_falloff(np.array(2.0))), 0.0)
self.assertTrue(0 < float(shadow_falloff(np.array(0.5))) < 1)
def test_shadow_is_darkest_where_the_camera_looks_at_the_patch(self):
alpha = shadow_alpha(CAMERA, GROUND, 0.8, 64, 48)
self.assertEqual(alpha.shape, (48, 64))
# The target is the patch's middle, so the picture's middle is darkest.
self.assertAlmostEqual(float(alpha[24, 32]), 0.8, delta=0.02)
self.assertAlmostEqual(float(alpha.max()), 0.8, delta=0.01)
# The corners look past the patch.
self.assertEqual(float(alpha[0, 0]), 0.0)
self.assertEqual(float(alpha[0, 63]), 0.0)
def test_moving_the_patch_moves_the_shadow(self):
right = shadow_alpha(CAMERA, {**GROUND, "cx": 0.6}, 1.0, 64, 48)
cols = right.sum(0)
self.assertGreater(int(np.argmax(cols)), 32)
def test_nothing_from_below_the_floor_or_at_zero_strength(self):
below = {**CAMERA, "position": {"x": 0, "y": -2, "z": 3}}
self.assertEqual(float(shadow_alpha(below, GROUND, 1.0, 32, 24).max()), 0.0)
self.assertEqual(float(shadow_alpha(CAMERA, GROUND, 0.0, 32, 24).max()), 0.0)
self.assertEqual(float(shadow_alpha(CAMERA, None, 1.0, 32, 24).max()), 0.0)
def test_ground_from_the_page_is_checked(self):
self.assertEqual(clean_ground(GROUND), {k: float(v) for k, v in GROUND.items()})
self.assertIsNone(clean_ground({**GROUND, "rx": 0}))
self.assertIsNone(clean_ground({**GROUND, "y": "low"}))
self.assertIsNone(clean_ground({**GROUND, "cz": float("nan")}))
self.assertIsNone(clean_ground([1, 2, 3]))
if __name__ == "__main__":
unittest.main()
+70
View File
@@ -0,0 +1,70 @@
"""Pause for Shot's backdrop looks the 360 up the way the viewer draws it."""
from __future__ import annotations
import math
from pathlib import Path
import sys
import unittest
import numpy as np
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes._backdrop_helpers import view_backdrop
DEG = math.pi / 180
def three_lookup(tilt: float, turn: float, roll: float) -> np.ndarray:
"""three r180 WebGLBackground: backgroundRotation is
makeRotationFromEuler(scene.backgroundRotation).transpose(), with 'ZXY'
meaning Rz(roll) @ Rx(tilt) @ Ry(turn)."""
a, b, c = tilt * DEG, turn * DEG, roll * DEG
rx = np.array([[1, 0, 0], [0, math.cos(a), -math.sin(a)], [0, math.sin(a), math.cos(a)]])
ry = np.array([[math.cos(b), 0, math.sin(b)], [0, 1, 0], [-math.sin(b), 0, math.cos(b)]])
rz = np.array([[math.cos(c), -math.sin(c), 0], [math.sin(c), math.cos(c), 0], [0, 0, 1]])
return (rz @ rx @ ry).T
def coded_panorama(h: int = 512) -> np.ndarray:
"""Each pixel holds its own (u, v) so a lookup tells where it read."""
w = h * 2
u = (np.arange(w) + 0.5) / w
v = 1 - (np.arange(h) + 0.5) / h
gu, gv = np.meshgrid(u, v)
return np.stack([gu, gv, np.zeros_like(gu)], -1)
class BackdropViewTests(unittest.TestCase):
def check(self, tilt, turn, roll):
pano = coded_panorama()
sky = {"tilt": tilt, "turn": turn, "roll": roll, "fov": 40}
camera = {"quaternion": {"x": 0, "y": 0, "z": 0, "w": 1}, "fov": 40}
out = view_backdrop(pano, camera, sky, 9, 9)
d = three_lookup(tilt, turn, roll) @ np.array([0.0, 0.0, -1.0])
u = math.atan2(d[2], d[0]) / (2 * math.pi) + 0.5
v = math.asin(max(-1, min(1, d[1]))) / math.pi + 0.5
got_u, got_v = out[4, 4, 0], out[4, 4, 1]
self.assertAlmostEqual(min(abs(got_u - u), 1 - abs(got_u - u)), 0, delta=0.01)
self.assertAlmostEqual(got_v, v, delta=0.01)
def test_one_angle(self):
self.check(0, 40, 0)
self.check(25, 0, 0)
def test_turn_and_tilt_together(self):
# The negated-angle rotation only matched three while one angle was
# set: Tilt 180 with Turn -87 showed another part of the room.
self.check(180, -87, 0)
self.check(30, 120, 0)
def test_all_three(self):
self.check(20, -60, 15)
if __name__ == "__main__":
unittest.main()
+11 -4
View File
@@ -2,6 +2,7 @@
import ast
import copy
import importlib.util
import json
import os
from pathlib import Path
@@ -229,11 +230,17 @@ class CommandTests(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
with patch.object(changelog_notes, "ROOT", self.root):
self.assertEqual(changelog_notes.pyproject_version(), version)
# The banner's _read_version and the single-copy guard both read
# through nodes/_pyproject.py: check it with a TOML library and with
# the plain reader that Python 3.10 without tomli falls back to.
spec = importlib.util.spec_from_file_location("ausboss_pyproject", ROOT / "nodes" / "_pyproject.py")
reader_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(reader_module)
self.assertEqual(reader_module.read_project(str(path)).get("version"), version)
self.assertEqual(reader_module._plain_project(path.read_text()).get("version"), version)
tree = ast.parse((ROOT / "__init__.py").read_text())
body = [n for n in tree.body if isinstance(n, (ast.Import, ast.ImportFrom)) or isinstance(n, ast.FunctionDef) and n.name == "_read_version"]
scope = {"__file__": str(self.root / "__init__.py")}
exec(compile(ast.Module(body=body, type_ignores=[]), "version_reader", "exec"), scope)
self.assertEqual(scope["_read_version"](), version)
reader = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "_read_version")
self.assertIn("read_project", ast.unparse(reader))
if __name__ == "__main__":
+75
View File
@@ -0,0 +1,75 @@
"""limit_clip_length: the min/max seconds rule of Video Crop + Rotate + Pad -> Clip.
Pure arithmetic, no video: runs on the CPU in a blink. The node test in
test_video_clip_transform.py runs the same rule on a real decode.
js/shared/timeline_math.mjs limitClipSeconds mirrors it; tests/timeline_math.test.mjs
holds the same rows.
"""
from __future__ import annotations
import sys
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes._video_load_helpers import limit_clip_length
DURATION = 15.4
FRAME = 1 / 24
def limit(start=0.0, end=0.0, cap=0, duration=DURATION, step=FRAME, low=5.0, high=8.0):
return limit_clip_length(start, end, cap, duration, step, low, high)
class LimitClipLengthTests(unittest.TestCase):
def assertWindow(self, got, start, end, cap):
self.assertAlmostEqual(got[0], start, places=6)
self.assertAlmostEqual(got[1], end, places=6)
self.assertEqual(got[2], cap)
def test_no_limits_change_nothing(self):
self.assertEqual(limit_clip_length(1.0, 0.0, 30, DURATION, FRAME, 0, 0), (1.0, 0.0, 30))
def test_the_whole_video_is_cut_to_the_max(self):
self.assertWindow(limit(), 0.0, 8.0, 0)
def test_a_window_inside_the_limits_is_kept(self):
self.assertEqual(limit(start=3.0, cap=192), (3.0, 0.0, 192))
self.assertEqual(limit(start=2.0, end=8.5), (2.0, 8.5, 0))
def test_a_short_window_grows_to_the_min(self):
self.assertWindow(limit(start=2.0, end=4.0), 2.0, 7.0, 0)
# A cap that would cut it under the min is dropped.
self.assertWindow(limit(start=2.0, cap=48), 2.0, 7.0, 0)
def test_a_cap_longer_than_the_max_stays(self):
self.assertWindow(limit(start=1.0, cap=300), 1.0, 9.0, 300)
def test_the_start_moves_back_where_the_video_ends_first(self):
self.assertWindow(limit(start=13.0), DURATION - 5.0, DURATION, 0)
def test_a_video_shorter_than_the_min_is_used_whole(self):
self.assertEqual(limit(start=1.0, end=2.0, duration=4.2), (0.0, 0.0, 0))
def test_a_max_below_the_min_counts_as_the_min(self):
self.assertWindow(limit(low=6.0, high=2.0), 0.0, 6.0, 0)
def test_only_a_max(self):
self.assertWindow(limit(start=1.0, low=0.0), 1.0, 9.0, 0)
self.assertEqual(limit(start=1.0, end=3.0, low=0.0), (1.0, 3.0, 0))
def test_unknown_duration_still_cuts_to_the_max(self):
self.assertWindow(limit(start=1.0, duration=0, low=0.0), 1.0, 9.0, 0)
def test_a_backwards_window_is_left_for_the_decode_to_refuse(self):
self.assertEqual(limit(start=4.0, end=2.0), (4.0, 2.0, 0))
if __name__ == "__main__":
unittest.main()
+15
View File
@@ -57,6 +57,9 @@ INTERNALS = [
("comfy.model_management", "current_loaded_models", "Mask by Touch asks SAM 3 the quick way"),
("comfy.model_management", "intermediate_dtype", "the pack's tensors take ComfyUI's working type"),
("folder_paths", "folder_names_and_paths", "the pack reads ComfyUI's model folders"),
("latent_preview", "get_previewer", "a clip's step picture moves (Step Preview, Save Video)"),
("latent_preview", "MAX_PREVIEW_RESOLUTION", "a clip's step picture moves (Step Preview, Save Video)"),
("server", "PromptServer", "Pause for Shot sends the viewer's mesh to every open page"),
]
# The progress list's own switches, by the names the pack calls.
PROGRESS_SWITCHES = ("enable_handler", "disable_handler")
@@ -244,6 +247,18 @@ class CoreContractTests(unittest.TestCase):
lists = [thing for thing in vars(progress).values() if inspect.isclass(thing) and all(callable(getattr(thing, name, None)) for name in PROGRESS_SWITCHES)]
self.assertTrue(lists, f"no class in comfy_execution.progress has {PROGRESS_SWITCHES}")
def test_the_running_prompt_can_still_be_found(self):
# A clip's moving step picture reads the running prompt off the queue.
execution = importlib.import_module("execution")
self.assertIsInstance(getattr(execution.PromptQueue(None), "currently_running", None), dict)
def test_the_server_still_sends_messages_the_way_pause_for_shot_wraps(self):
server = importlib.import_module("server")
send = getattr(getattr(server, "PromptServer", None), "send_sync", None)
self.assertTrue(callable(send), "server.PromptServer has no send_sync(): Pause for Shot's mesh reaches only the page that pressed Run")
self.assertEqual(list(inspect.signature(send).parameters)[:3], ["self", "event", "data"],
"PromptServer.send_sync() takes other arguments than the ones Pause for Shot passes on")
def test_the_model_folders_the_pack_reads_exist(self):
folder_paths = importlib.import_module("folder_paths")
known = set(folder_paths.folder_names_and_paths)
+14 -1
View File
@@ -1294,6 +1294,19 @@ class NodeTests(unittest.TestCase):
self.assertEqual(frames, 141)
self.assertIn("<Audio 1>", node.write(SAYS, 6, picture_1=PICTURE, voice=self.audio())[0])
def test_an_edited_full_prompt_is_sent_and_the_written_one_shown(self):
node = AusBossH3PromptWriter()
written = node.write(LINES, 6, picture_1=PICTURE)
plain = node.run(LINES, 6, picture_1=PICTURE)
self.assertEqual(plain["ui"]["written_prompt"], [written[0]])
self.assertEqual(plain["result"][0], written[0])
self.assertEqual(plain["result"][1:11], written[1:11])
edited = node.run(LINES, 6, picture_1=PICTURE, full_prompt="my own prompt\nno push in")
self.assertEqual(edited["result"][0], "my own prompt\nno push in")
self.assertEqual(edited["ui"]["written_prompt"], [written[0]])
self.assertEqual(edited["result"][11], written[11])
self.assertEqual(node.run(LINES, 6, picture_1=PICTURE, full_prompt=" \n")["result"][0], written[0])
def test_the_picks_that_change_nothing_add_nothing(self):
node = AusBossH3PromptWriter()
self.assertEqual(node.write(LINES, 6, picture_1=PICTURE)[0], node.write(LINES, 6, picture_1=PICTURE, camera="as typed", look="from the picture")[0])
@@ -1457,7 +1470,7 @@ class SoundAndMusicBoxTests(unittest.TestCase):
def test_the_boxes_are_appended_after_every_older_input(self):
names = list(AusBossH3PromptWriter.INPUT_TYPES()["optional"])
self.assertEqual(names[-3:], ["sound", "music", "clip_sound"])
self.assertEqual(names[-4:], ["sound", "music", "clip_sound", "full_prompt"])
def spoken(stretches, seconds, rate=16000, noise=0.002, seed=3):
+72
View File
@@ -625,5 +625,77 @@ class ResolveLoraPathTests(unittest.TestCase):
self.assertEqual(asked, [])
class LinkedRowStrengthTests(unittest.TestCase):
"""A number wire dropped on a row arrives as strength_<row id> (issue #388)."""
ROW = {"name": "a.safetensors", "strength": 0.8, "strength_clip": 0.4,
"enabled": True, "triggers": ""}
def rows(self):
return [{**self.ROW, "id": "ra1"}, {**self.ROW, "id": "rb2", "name": "b.safetensors"}]
def test_the_linked_value_sets_the_model_strength_and_clip_keeps_its_ratio(self):
out = _lora_helpers.apply_linked_strengths(self.rows(), {"strength_rb2": 0.3})
self.assertEqual((out[0]["strength"], out[0]["strength_clip"]), (0.8, 0.4))
self.assertAlmostEqual(out[1]["strength"], 0.3)
self.assertAlmostEqual(out[1]["strength_clip"], 0.15)
def test_a_row_at_zero_follows_the_link_one_for_one(self):
rows = [{**self.ROW, "id": "r0", "strength": 0.0, "strength_clip": 0.0}]
out = _lora_helpers.apply_linked_strengths(rows, {"strength_r0": 0.5})
self.assertEqual((out[0]["strength"], out[0]["strength_clip"]), (0.5, 0.5))
def test_unknown_rows_and_other_names_change_nothing(self):
rows = self.rows()
out = _lora_helpers.apply_linked_strengths(rows, {"strength_gone": 0.1, "trigger_separator": ", "})
self.assertEqual(out, rows)
def test_row_input_names(self):
self.assertTrue(_lora_helpers.is_row_strength_input("strength_rb2"))
for name in ("strength_", "strength_a b", "strength_" + "x" * 65, "loras", 3, None):
self.assertFalse(_lora_helpers.is_row_strength_input(name), name)
def test_the_node_declares_any_row_input_as_an_optional_float(self):
try:
from nodes.node_lora_loader import AusBossLoraLoader
except Exception as exc: # pragma: no cover - needs the package importable
self.skipTest(f"node module not importable offline: {exc}")
optional = AusBossLoraLoader.INPUT_TYPES()["optional"]
self.assertIn("strength_rb2", optional)
self.assertEqual(optional["strength_rb2"][0], "FLOAT")
self.assertNotIn("strength_", optional)
self.assertNotIn("bogus", optional)
# The listed inputs are unchanged: saved workflows keep their slots.
self.assertEqual(list(optional), ["clip", "trigger_separator", "on_missing"])
def test_comfyui_hands_a_row_input_to_the_node(self):
# ComfyUI passes a node only inputs it can look up; this is its own lookup.
try:
from comfy_execution.graph import get_input_info
from nodes.node_lora_loader import AusBossLoraLoader
except Exception as exc: # pragma: no cover - needs ComfyUI on the path
self.skipTest(f"ComfyUI not importable: {exc}")
kind, category, _info = get_input_info(AusBossLoraLoader, "strength_rb2")
self.assertEqual((kind, category), ("FLOAT", "optional"))
self.assertEqual(get_input_info(AusBossLoraLoader, "bogus"), (None, None, None))
def test_load_loras_applies_the_linked_strength(self):
try:
from nodes.node_lora_loader import AusBossLoraLoader
import nodes.node_lora_loader as node_module
except Exception as exc: # pragma: no cover - needs the package importable
self.skipTest(f"node module not importable offline: {exc}")
seen = []
def apply(model, clip, rows, **_kwargs):
seen.extend(rows)
return model, clip
with patch.object(node_module, "apply_lora_stack", side_effect=apply):
AusBossLoraLoader().load_loras("model", json.dumps(self.rows()), strength_rb2=1.2)
self.assertEqual([round(row["strength"], 3) for row in seen], [0.8, 1.2])
self.assertEqual([round(row["strength_clip"], 3) for row in seen], [0.4, 0.6])
if __name__ == "__main__":
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
"""Pause for Shot carries its viewer's model to every open page."""
from __future__ import annotations
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes import node_pause_shot as ps
MESH = {"result": ["preview3d_advanced_abc.glb [temp]", {"fov": 35}, []]}
# ComfyUI since its "standard 3d output item" change: Preview 3D (Advanced)
# names its model in a "3d" list instead of "result".
MESH_3D = {"3d": [{"filename": "preview3d_advanced_abc.glb", "subfolder": "", "type": "temp"}],
"camera_info": [{"fov": 35}], "model_3d_info": []}
class FakeServer:
def __init__(self):
self.sent = []
def send_sync(self, event, data, sid=None):
self.sent.append((event, data, sid))
class ViewerResultTests(unittest.TestCase):
def setUp(self):
ps._viewer_results.clear()
def test_only_3d_results_are_kept(self):
self.assertTrue(ps.model_result(MESH))
self.assertTrue(ps.model_result(MESH_3D))
self.assertFalse(ps.model_result({"3d": [{"filename": "a.png", "subfolder": "", "type": "temp"}]}))
self.assertFalse(ps.model_result({"3d": []}))
self.assertFalse(ps.model_result({"images": [{"filename": "a.png"}]}))
self.assertFalse(ps.model_result({"result": ["notes.txt"]}))
self.assertFalse(ps.model_result(None))
def test_watch_keeps_the_viewer_result_and_still_sends(self):
server = FakeServer()
ps._watch_results(server)
ps._watch_results(server) # once only
server.send_sync("executed", {"node": "30", "display_node": "30", "output": MESH, "prompt_id": "p"}, "client-a")
server.send_sync("executed", {"node": "32", "output": {"images": []}}, "client-a")
self.assertEqual(ps._viewer_results, {"30": MESH})
self.assertEqual([s[2] for s in server.sent], ["client-a", "client-a"])
def test_viewer_is_the_node_wired_into_model_3d_info(self):
prompt = {"50": {"inputs": {"model_3d_info": ["30", 1]}}}
self.assertEqual(ps.viewer_of(prompt, "50"), "30")
self.assertIsNone(ps.viewer_of(prompt, "51"))
self.assertIsNone(ps.viewer_of(None, "50"))
def test_the_newer_3d_output_is_kept_too(self):
server = FakeServer()
ps._watch_results(server)
server.send_sync("executed", {"node": "30", "display_node": "30", "output": MESH_3D, "prompt_id": "p"}, "client-a")
self.assertEqual(ps._viewer_results, {"30": MESH_3D})
class PanoramaOffTests(unittest.TestCase):
def test_taken_out_360_is_kept_in_the_answer(self):
self.assertIs(ps.clean_shot({"panorama": False}).get("panorama"), False)
self.assertNotIn("panorama", ps.clean_shot({"panorama": "yes"}))
self.assertNotIn("panorama", ps.clean_shot({}))
if __name__ == "__main__":
unittest.main()
+124
View File
@@ -0,0 +1,124 @@
"""The pack loads on Python 3.10, where tomllib does not exist (issue #387).
Each check runs in a child interpreter with tomllib (and tomli) hidden, the
way a Python 3.10 install without the backport sees the world.
"""
from __future__ import annotations
from pathlib import Path
import subprocess
import sys
import tempfile
import textwrap
import unittest
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes._pyproject import _plain_project, project_from_text
# Run in a child interpreter: make tomllib and tomli look absent.
HIDE_TOML = textwrap.dedent(
"""
import sys
class _NoToml:
def find_spec(self, name, path=None, target=None):
if name in ("tomllib", "tomli"):
raise ModuleNotFoundError(f"No module named {name!r}", name=name)
return None
sys.meta_path.insert(0, _NoToml())
sys.modules.pop("tomllib", None)
sys.modules.pop("tomli", None)
"""
)
def run_without_toml(body: str) -> subprocess.CompletedProcess:
code = HIDE_TOML + textwrap.dedent(body)
return subprocess.run(
[sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, timeout=60
)
class PlainReaderTests(unittest.TestCase):
def test_matches_tomllib_on_the_real_pyproject(self):
text = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
real = project_from_text(text)
plain = _plain_project(text)
self.assertEqual(plain["name"], real["name"])
self.assertEqual(plain["version"], real["version"])
def test_reads_only_the_project_table(self):
text = textwrap.dedent(
"""
[tool.other]
name = "not-this"
[project]
name = 'ausboss-nodes' # single quotes and a comment
version = "1.2.3"
license = { text = "MIT License" }
[project.urls]
name = "not-this-either"
"""
)
self.assertEqual(_plain_project(text), {"name": "ausboss-nodes", "version": "1.2.3"})
def test_no_project_table(self):
self.assertEqual(_plain_project('[tool.x]\nversion = "9"\n'), {})
class NoTomllibTests(unittest.TestCase):
def test_reader_works_without_tomllib(self):
result = run_without_toml(
"""
from nodes import _pyproject
assert _pyproject._toml is None, _pyproject._toml
project = _pyproject.read_project("pyproject.toml")
print(project["name"], project["version"])
"""
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertTrue(result.stdout.startswith("ausboss-nodes "), result.stdout)
def test_single_copy_guard_works_without_tomllib(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp).resolve()
for name, version in (("ComfyUI-AusBoss", "2.0.0"), ("ausboss-nodes", "3.0.0")):
folder = root / name
(folder / "nodes").mkdir(parents=True)
(folder / "__init__.py").write_text("")
(folder / "nodes" / "_single_copy.py").write_text("")
(folder / "pyproject.toml").write_text(
f'[project]\nname = "ausboss-nodes"\nversion = "{version}"\n'
)
result = run_without_toml(
f"""
from nodes._single_copy import other_copy_that_loads
older = {str(root / "ComfyUI-AusBoss")!r}
winner = other_copy_that_loads(older, [{str(root)!r}])
print(winner)
"""
)
self.assertEqual(result.returncode, 0, result.stderr)
# The newer copy is found, so its version was read without tomllib.
self.assertIn("ausboss-nodes", result.stdout)
def test_shipped_python_never_imports_tomllib_directly(self):
offenders = []
for path in [ROOT / "__init__.py", *sorted((ROOT / "nodes").rglob("*.py"))]:
if path.name == "_pyproject.py":
continue
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
stripped = line.strip()
if stripped.startswith(("import tomllib", "from tomllib")):
offenders.append(f"{path.relative_to(ROOT)}:{number}")
self.assertEqual(offenders, [], "use nodes/_pyproject.py so Python 3.10 still loads")
if __name__ == "__main__":
unittest.main()
+35 -3
View File
@@ -56,6 +56,24 @@ def input_default(cls, name):
return kind[0] if isinstance(kind, (list, tuple)) else None
def run_parameter(cls, name):
"""The parameter an API prompt without `name` runs with, or None.
A node function that takes **inputs and hands them on in one call,
such as H3 Prompt Writer's run() to write(), is followed that one step.
"""
function = getattr(cls, cls.FUNCTION)
parameters = inspect.signature(function).parameters
if name in parameters:
return parameters[name]
if any(p.kind is p.VAR_KEYWORD for p in parameters.values()):
for target in re.findall(r"self\.(\w+)\([^()]*\*\*\w+\)", inspect.getsource(function)):
handed_on = inspect.signature(getattr(cls, target)).parameters
if name in handed_on:
return handed_on[name]
return None
@unittest.skipUnless(COMFY_ROOT, "set AUSBOSS_COMFY_ROOT to a ComfyUI checkout")
class SavedFallbackTests(unittest.TestCase):
@classmethod
@@ -74,16 +92,30 @@ class SavedFallbackTests(unittest.TestCase):
def test_each_fallback_is_the_new_node_default_and_the_api_default(self):
for node_id, fallbacks in self.fallbacks.items():
cls = self.pack.NODE_CLASS_MAPPINGS[node_id]
parameters = inspect.signature(getattr(cls, cls.FUNCTION)).parameters
for name, fallback in fallbacks.items():
with self.subTest(node=node_id, input=name):
self.assertEqual(fallback, input_default(cls, name), "a new node's default")
self.assertIn(name, parameters, f"{cls.FUNCTION}() does not take {name}")
parameter = run_parameter(cls, name)
self.assertIsNotNone(parameter, f"{cls.FUNCTION}() does not take {name}")
self.assertEqual(
fallback, parameters[name].default,
fallback, parameter.default,
"what an API prompt without the input runs with",
)
def test_a_function_that_hands_on_its_inputs_is_followed(self):
class Wrapper:
FUNCTION = "run"
def run(self, script, **inputs):
return self.write(script, **inputs)
def write(self, script, sound=""):
return script, sound
self.assertEqual(run_parameter(Wrapper, "sound").default, "")
self.assertIsNone(run_parameter(Wrapper, "music"))
self.assertEqual(run_parameter(Wrapper, "script").name, "script")
if __name__ == "__main__":
unittest.main()
+76 -1
View File
@@ -10,7 +10,12 @@ sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes._single_copy import other_copy_that_loads
from nodes._single_copy import (
NOTICE_ROUTE,
other_copy_that_loads,
register_second_copy_notice,
second_copy_notice,
)
def make_copy(root: Path, name: str, version: str, guarded: bool = True, pack: str = "ausboss-nodes") -> str:
@@ -75,5 +80,75 @@ class SingleCopyTests(unittest.TestCase):
self.assertTrue(loads(b, self.root))
class SecondCopyNoticeTests(unittest.TestCase):
def setUp(self):
self._tmp = tempfile.TemporaryDirectory()
self.root = Path(self._tmp.name).resolve()
def tearDown(self):
self._tmp.cleanup()
def test_an_old_copy_that_cannot_step_aside_is_named_for_deleting(self):
new = make_copy(self.root, "ausboss-nodes", "2.26.6")
make_copy(self.root, "ComfyUI-AusBoss", "2.23.0", guarded=False)
other = other_copy_that_loads(new, [str(self.root)])
notice = second_copy_notice(new, "2.26.6", other)
self.assertTrue(notice["older"])
self.assertIn("old copy", notice["summary"])
self.assertIn("v2.23.0 in custom_nodes/ComfyUI-AusBoss", notice["detail"])
self.assertIn("Delete the custom_nodes/ComfyUI-AusBoss folder", notice["detail"])
def test_a_newer_copy_loading_asks_to_delete_this_one(self):
old = make_copy(self.root, "ComfyUI-AusBoss", "2.24.0")
make_copy(self.root, "ausboss-nodes", "2.25.0")
notice = second_copy_notice(old, "2.24.0", other_copy_that_loads(old, [str(self.root)]))
self.assertFalse(notice["older"])
self.assertIn("Delete custom_nodes/ComfyUI-AusBoss,", notice["detail"])
class FakeRoutes:
def __init__(self):
self.added = {}
def get(self, path):
def add(handler):
if path in self.added:
raise AssertionError(f"{path} added twice")
self.added[path] = handler
return handler
return add
class FakeServer:
def __init__(self):
self.routes = FakeRoutes()
class SecondCopyRouteTests(unittest.TestCase):
def test_two_copies_stepping_aside_share_one_route(self):
import asyncio
import json
server = FakeServer()
self.assertTrue(register_second_copy_notice({"detail": "one"}, server))
self.assertTrue(register_second_copy_notice({"detail": "two"}, server))
self.assertEqual(list(server.routes.added), [NOTICE_ROUTE])
response = asyncio.run(server.routes.added[NOTICE_ROUTE](None))
self.assertEqual(json.loads(response.body), [{"detail": "one"}, {"detail": "two"}])
class EntryPointTests(unittest.TestCase):
def test_a_copy_that_steps_aside_serves_only_the_warning(self):
text = (ROOT / "__init__.py").read_text(encoding="utf-8")
self.assertIn('WEB_DIRECTORY = "./web_second_copy" if _other_copy else "./js"', text)
web = ROOT / "web_second_copy"
self.assertEqual(sorted(p.name for p in web.glob("*.js")), ["index.js"])
# Served alone, so nothing may reach into the pack's js/ folder.
for path in web.iterdir():
self.assertNotIn("../js/", path.read_text(encoding="utf-8"))
self.assertNotIn("/shared/", path.read_text(encoding="utf-8"))
if __name__ == "__main__":
unittest.main()
+114
View File
@@ -83,5 +83,119 @@ class AskForStepPictures(unittest.TestCase):
self.assertEqual(helpers.ask_for_step_pictures({"prompt": self.PROMPT, "extra_data": "x"}, "none")["extra_data"], "x")
class FramePicks(unittest.TestCase):
def test_about_one_frame_per_second_of_an_h3_clip(self):
# 124 frames at 24 fps (about 5 s) is 37 latent frames for H3.
picks, seconds = helpers.frame_picks(37, 4)
self.assertEqual(picks, [0, 6, 12, 18, 24, 30, 36])
self.assertAlmostEqual(seconds, 1.0)
def test_a_short_clip_still_moves(self):
picks, seconds = helpers.frame_picks(3, 4)
self.assertEqual(picks, [0, 2])
self.assertAlmostEqual(seconds, 2 * 4 / 24)
def test_a_long_clip_is_capped(self):
picks, _ = helpers.frame_picks(400, 4)
self.assertEqual(len(picks), helpers.MAX_FRAMES)
self.assertEqual((picks[0], picks[-1]), (0, 399))
def test_one_frame_or_junk_does_not_move(self):
for frames in (0, 1, None, "x"):
self.assertEqual(helpers.frame_picks(frames, 4), ([], 0.0), frames)
class _Picture:
def __init__(self, size=(80, 45)):
self.size = size
def convert(self, _mode):
return self
def save(self, buffer, **_kwargs):
buffer.write(b"jpeg")
class _Latent:
"""Just enough of a 5-D tensor: its shape, and slicing by frame."""
ndim = 5
def __init__(self, frames):
self.shape = (1, 24, frames, 45, 80)
def __getitem__(self, key):
return ("frame", key[2].start)
class _Previewer:
def __init__(self):
self.frames = []
self.stills = 0
self.extra = "kept"
def decode_latent_to_preview(self, x0):
self.frames.append(x0[1])
return _Picture()
def decode_latent_to_preview_image(self, preview_format, x0):
self.stills += 1
return (preview_format, "still", 512)
class _Format:
temporal_downscale_ratio = 4
class MovingStepPicturesTest(unittest.TestCase):
def make(self):
sent = []
inner = _Previewer()
moving = helpers.MovingStepPictures(inner, _Format(), lambda event, data: sent.append((event, data)), lambda: ("run", "5:3"))
return moving, inner, sent
def test_each_step_sends_the_frames_and_keeps_the_still(self):
moving, inner, sent = self.make()
self.assertEqual(moving.decode_latent_to_preview_image("JPEG", _Latent(37)), ("JPEG", "still", 512))
self.assertEqual(inner.frames, [0, 6, 12, 18, 24, 30, 36])
self.assertEqual(inner.stills, 1)
event, data = sent[0]
self.assertEqual(event, helpers.FRAMES_EVENT)
self.assertEqual((data["prompt_id"], data["node"], len(data["frames"])), ("run", "5:3", 7))
self.assertTrue(data["frames"][0].startswith("data:image/jpeg;base64,"))
self.assertAlmostEqual(data["seconds"], 1.0)
def test_a_still_latent_sends_nothing(self):
moving, inner, sent = self.make()
still = _Latent(1)
moving.decode_latent_to_preview_image("JPEG", still)
self.assertEqual((sent, inner.frames, inner.stills), ([], [], 1))
def test_a_failing_previewer_falls_back_to_the_still_for_good(self):
moving, inner, sent = self.make()
inner.decode_latent_to_preview = None
for _ in range(2):
self.assertEqual(moving.decode_latent_to_preview_image("JPEG", _Latent(37))[1], "still")
self.assertTrue(moving.failed)
self.assertEqual(sent, [])
def test_slow_frames_skip_steps_to_stay_in_budget(self):
sent = []
inner = _Previewer()
times = iter([0.0, 2.0, 10.0, 20.0, 22.0, 30.0])
moving = helpers.MovingStepPictures(inner, _Format(), lambda e, d: sent.append(d), lambda: ("run", "1"), clock=lambda: next(times))
# Step 1 at 0 s takes 2 s for its frames: 20 % of a 10 s step.
# Step 2 at 10 s is skipped (2 s > 10 % of 10 s); step 3 at 20 s sends;
# step 4 at 30 s is skipped again.
for _ in range(4):
moving.decode_latent_to_preview_image("JPEG", _Latent(37))
self.assertEqual(len(sent), 2)
self.assertEqual(inner.stills, 4)
def test_other_attributes_pass_through(self):
moving, _, _ = self.make()
self.assertEqual(moving.extra, "kept")
if __name__ == "__main__":
unittest.main()
+47
View File
@@ -237,6 +237,53 @@ class VideoClipNodeTests(unittest.TestCase):
self.assertAlmostEqual(duration, 1.0)
self.assertEqual(float(mask.max()), 0.0)
def test_length_limits_change_nothing_while_both_are_zero(self):
plain = self.run_node(start_seconds=0.5, max_frames=6)
limited = self.run_node(start_seconds=0.5, max_frames=6, min_seconds=0.0, max_seconds=0.0)
self.assertEqual(limited[3], plain[3])
self.assertTrue(torch.equal(limited[0], plain[0]))
def test_max_seconds_cuts_a_longer_window(self):
# The whole two-second video, limited to one second.
out = self.run_node(max_seconds=1.0)
self.assertEqual(out[3], FPS)
self.assertAlmostEqual(out[7], 1.0)
# A frame cap longer than the limit is cut too.
self.assertEqual(self.run_node(start_seconds=0.5, max_frames=20, max_seconds=1.0)[3], FPS)
def test_min_seconds_grows_a_shorter_window(self):
self.assertEqual(self.run_node(end_seconds=0.5, min_seconds=1.5)[3], 18)
# A frame cap under the limit gives way as well.
self.assertEqual(self.run_node(max_frames=3, min_seconds=1.0)[3], FPS)
def test_min_seconds_moves_the_start_back_at_the_video_end(self):
out = self.run_node(start_seconds=1.5, min_seconds=1.0, max_seconds=1.0)
self.assertEqual(out[3], FPS)
reference = self.run_node(start_seconds=1.0)
self.assertTrue(torch.equal(out[0], reference[0]))
def test_a_video_shorter_than_min_seconds_is_used_whole(self):
out = self.run_node(start_seconds=1.0, end_seconds=1.5, min_seconds=5.0, max_seconds=8.0)
self.assertEqual(out[3], FRAMES)
self.assertAlmostEqual(out[7], FRAMES / FPS)
def test_length_limits_follow_a_forced_rate(self):
# 24 frames a second, cut to one second: 24 output frames.
out = self.run_node(force_rate=24, max_seconds=1.0)
self.assertEqual(out[3], 24)
self.assertAlmostEqual(out[7], 1.0)
def test_fixed_frames_wins_over_the_length_limits(self):
self.assertEqual(self.run_node(fixed_frames=6, min_seconds=1.0)[3], 6)
def test_length_limits_change_the_fingerprint(self):
common = dict(video="", source_mode="local path", local_path=self.server_file, start_seconds=0.0, end_seconds=0.0)
values = transform_defaults()
one = AusBossVideoCropRotatePadClip.IS_CHANGED(**common, **values)
for name in ("min_seconds", "max_seconds"):
other = AusBossVideoCropRotatePadClip.IS_CHANGED(**common, **{name: 5.0}, **values)
self.assertNotEqual(one, other, name)
def test_preview_position_never_changes_the_fingerprint(self):
common = dict(video="", source_mode="local path", local_path=self.server_file, start_seconds=0.0, end_seconds=0.0)
values = transform_defaults(pad_right=8)
+74
View File
@@ -0,0 +1,74 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import vm from "node:vm";
test("gridHeight uses the measured floor and returns zero without a usable height", () => {
const source = readFileSync(new URL("../js/viewer_pano/index.js", import.meta.url), "utf8")
.replace(/^import .*;$/gm, "")
.replace(/^export /gm, "");
const { gridHeight } = vm.runInNewContext(source + "\n({ gridHeight })", {
app: { registerExtension() {} },
});
for (const y of [-1.75, 0, 2.5]) assert.equal(gridHeight({ y }), y);
for (const ground of [null, undefined, {}, { y: NaN }, { y: Infinity }, { y: -Infinity }, { y: "3" }]) {
assert.equal(gridHeight(ground), 0);
}
});
// A stand-in for ComfyUI's SceneManager: a grid, one model standing from
// y = -0.5 to 0.5, and a capture that reads the grid partway through.
function loadPatched() {
const source = readFileSync(new URL("../js/viewer_pano/index.js", import.meta.url), "utf8")
.replace(/^import .*;$/gm, "")
.replace(/^export /gm, "");
class Manager {
constructor() {
const points = [0, -0.5, 0, 0, 0.5, 0, 0.2, -0.5, 0.1];
const part = {
isMesh: true, visible: true, material: { isMeshStandardMaterial: true },
matrixWorld: { elements: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] },
geometry: { attributes: { position: { count: 3, getX: (i) => points[i * 3], getY: (i) => points[i * 3 + 1], getZ: (i) => points[i * 3 + 2] } } },
};
const model = { uuid: "m", visible: true, matrixWorld: part.matrixWorld, updateMatrixWorld() {}, traverse(fn) { fn(model); fn(part); } };
this.gridHelper = { visible: true, position: { y: 0 }, updateMatrixWorld() {} };
this.scene = { children: [this.gridHelper, model] };
this.seen = [];
}
renderBackground() { this.seen.push(this.gridHelper.position.y); }
captureScene() {
if (this.fail) throw new Error("capture failed");
this.renderBackground();
return Promise.resolve().then(() => { this.renderBackground(); return { scene: "data" }; });
}
}
const context = { app: { registerExtension() {} }, window: { comfyAPI: { SceneManager: { SceneManager: Manager } } }, console };
vm.runInNewContext(source + "\n;this.patchSceneManager = patchSceneManager;", context);
assert.equal(context.patchSceneManager(), true);
return Manager;
}
test("the grid stands at the model's feet on screen and at 0 in a capture", async () => {
const Manager = loadPatched();
const manager = new Manager();
manager.renderBackground();
assert.equal(manager.gridHelper.position.y, -0.5);
manager.seen.length = 0;
const shot = await manager.captureScene(64, 64);
assert.deepEqual(shot, { scene: "data" });
assert.deepEqual(manager.seen, [0, 0]);
assert.equal(manager.__ausbossCapturing, 0);
manager.renderBackground();
assert.equal(manager.gridHelper.position.y, -0.5);
});
test("a capture that throws still lets the grid go back to the feet", () => {
const Manager = loadPatched();
const manager = new Manager();
manager.fail = true;
assert.throws(() => manager.captureScene(64, 64), /capture failed/);
assert.equal(manager.__ausbossCapturing, 0);
manager.renderBackground();
assert.equal(manager.gridHelper.position.y, -0.5);
});
+78
View File
@@ -12,7 +12,9 @@ import {
folderPath,
groupModels,
hostLabel,
installFolders,
matchInstalled,
modelFolderKey,
onlyCopy,
noteFit,
noteIsEmpty,
@@ -23,6 +25,7 @@ import {
parseMarkdown,
rowFromCells,
safeUrl,
sharedFolders,
serializeNote,
} from "../js/shared/workflow_note.mjs";
import { collectGraphNodes } from "../js/shared/appearance.mjs";
@@ -127,6 +130,51 @@ test("folderPath and groupModels read like the install tree", () => {
assert.deepEqual(groups.map((g) => [g.dir, g.rows.map((r) => r.name)]), [["vae", ["a", "c"]], ["loras", ["b"]]]);
});
// Stability Matrix's extra_model_paths.yaml, as ComfyUI's
// /experiment/models reports it on Windows (issue #386).
const STABILITY_MATRIX = [
{ name: "loras", folders: ["C:\\SM\\Packages\\ComfyUI\\models\\loras", "C:\\SM\\Data\\Models\\Lora", "C:\\SM\\Data\\Models\\LyCORIS"] },
{ name: "text_encoders", folders: ["C:\\SM\\Packages\\ComfyUI\\models\\text_encoders", "C:\\SM\\Packages\\ComfyUI\\models\\clip", "C:\\SM\\Data\\Models\\TextEncoders"] },
{ name: "diffusion_models", folders: ["/opt/ComfyUI/models/unet", "/opt/ComfyUI/models/diffusion_models/", "/mnt/shared/DiffusionModels"] },
{ name: "vae", folders: ["/opt/ComfyUI/models/vae"] },
];
test("old folder names are checked under the names ComfyUI lists them by", () => {
// GET /models/clip and /models/unet answer 404; ComfyUI files them as these.
assert.equal(modelFolderKey("clip"), "text_encoders");
assert.equal(modelFolderKey("unet"), "diffusion_models");
assert.equal(modelFolderKey("loras"), "loras");
assert.equal(modelFolderKey("clip_vision"), "clip_vision");
assert.equal(modelFolderKey("input"), "input");
});
test("installFolders lists every folder the install reads, shared ones included", () => {
assert.deepEqual(installFolders("loras", STABILITY_MATRIX), STABILITY_MATRIX[0].folders);
assert.deepEqual(installFolders("clip", STABILITY_MATRIX), STABILITY_MATRIX[1].folders);
assert.deepEqual(installFolders("input", STABILITY_MATRIX), []);
assert.deepEqual(installFolders("checkpoints", STABILITY_MATRIX), []);
assert.deepEqual(installFolders("loras", null), []);
assert.deepEqual(installFolders("loras", [null, { name: "loras" }]), []);
});
test("sharedFolders names only the folders outside ComfyUI/models", () => {
assert.deepEqual(sharedFolders("loras", STABILITY_MATRIX), ["C:\\SM\\Data\\Models\\Lora", "C:\\SM\\Data\\Models\\LyCORIS"]);
// models/clip is ComfyUI's own old text-encoder folder, not a shared one.
assert.deepEqual(sharedFolders("text_encoders", STABILITY_MATRIX), ["C:\\SM\\Data\\Models\\TextEncoders"]);
assert.deepEqual(sharedFolders("clip", STABILITY_MATRIX), ["C:\\SM\\Data\\Models\\TextEncoders"]);
assert.deepEqual(sharedFolders("unet", STABILITY_MATRIX), ["/mnt/shared/DiffusionModels"]);
// A plain install has nothing extra to show, and neither do folders
// named like the kind (ComfyUI's own output/loras, a shared .../loras).
assert.deepEqual(sharedFolders("vae", STABILITY_MATRIX), []);
assert.deepEqual(sharedFolders("loras", [{ name: "loras", folders: ["/c/ComfyUI/models/loras", "/c/ComfyUI/output/loras", "D:\\shared\\LoRAs\\"] }]), []);
assert.deepEqual(sharedFolders("loras", []), []);
});
test("the note asks ComfyUI for a folder by the name it lists it under", () => {
const source = readFileSync(new URL("../js/workflow_note/index.js", import.meta.url), "utf8");
assert.match(source, /fetchApi\(`\/models\/\$\{encodeURIComponent\(modelFolderKey\(dir\)\)\}`\)/);
});
test("matchInstalled finds exact paths first, then basenames in any subfolder", () => {
const files = ["Krea 2/krea2_turbo_fp8.safetensors", "other/thing.safetensors", "top.safetensors"];
assert.deepEqual(matchInstalled("krea2_turbo_fp8.safetensors", files), { found: true, path: "Krea 2/krea2_turbo_fp8.safetensors" });
@@ -345,3 +393,33 @@ test("onlyCopy picks a file without asking only when there is one copy", () => {
assert.equal(onlyCopy("missing.safetensors", files), null);
assert.equal(onlyCopy("model.safetensors", []), null);
});
test("this pack's rows are recognized by name or link, never by an AUSBOSS_NODES_ probe", async () => {
const { isOwnPackRow, OWN_PACK } = await import("../js/shared/workflow_note.mjs");
assert.equal(isOwnPackRow({ name: "ComfyUI-AusBoss", url: "https://github.com/ausboss/ComfyUI-AusBoss" }), true);
assert.equal(isOwnPackRow({ name: "anything", url: "https://github.com/ausboss/ComfyUI-AusBoss.git/" }), true);
assert.equal(isOwnPackRow({ name: "ausboss-nodes" }), true);
assert.equal(isOwnPackRow(OWN_PACK), true);
assert.equal(isOwnPackRow({ name: "ComfyUI-AusBoss-Model-Downloader", url: "https://github.com/ausboss/ComfyUI-AusBoss-Model-Downloader", node: "AUSBOSS_NODES_ModelDownloader" }), false);
assert.equal(isOwnPackRow({ name: "rgthree-comfy", url: "https://github.com/rgthree/rgthree-comfy" }), false);
assert.equal(isOwnPackRow(null), false);
});
test("Detect names this pack by its Registry id, from either folder", async () => {
const { nameOwnPack, OWN_PACK } = await import("../js/shared/workflow_note.mjs");
const detected = [
{ name: "ComfyUI-AusBoss", url: "", node: "AUSBOSS_NODES_Seed" },
{ name: "rgthree-comfy", url: "", node: "Power Lora Loader (rgthree)" },
];
assert.deepEqual(nameOwnPack(detected, "ComfyUI-AusBoss")[0], { ...OWN_PACK, node: "AUSBOSS_NODES_Seed" });
assert.equal(nameOwnPack(detected, "ComfyUI-AusBoss")[1].name, "rgthree-comfy");
assert.equal(nameOwnPack([{ name: "ausboss-nodes", url: "", node: "AUSBOSS_NODES_Seed" }], "ausboss-nodes")[0].url, OWN_PACK.url);
assert.deepEqual(nameOwnPack(detected, ""), detected);
});
test("a missing node of this pack offers an update in the Manager, not a GitHub link", () => {
const source = readFileSync(new URL("../js/workflow_note/index.js", import.meta.url), "utf8");
assert.match(source, /installed === false && isOwnPackRow\(row\)/);
assert.match(source, /Comfy\.Manager\.ShowUpdateAvailablePacks/);
assert.doesNotMatch(source, /github\.com\/ausboss\/ComfyUI-AusBoss/);
});
+26
View File
@@ -0,0 +1,26 @@
// AusBoss installed twice 🆎 — the browser half of nodes/_single_copy.py.
//
// Only a copy that steps aside serves this folder. Its nodes are not loaded,
// so this file must not import anything from the pack's js/ folder: it
// asks the server for the notice and shows it as a toast that stays until
// it is closed, because the console line alone is easy to miss and the
// nodes added since the old copy just show as missing.
import { api } from "../../scripts/api.js";
import { app } from "../../scripts/app.js";
import { showSecondCopyNotices } from "./notice.mjs";
app.registerExtension({
name: "AusBoss.SecondCopy",
async setup() {
// Two copies that both step aside each serve this file; show the list once.
if (globalThis.__ausbossSecondCopyShown) return;
globalThis.__ausbossSecondCopyShown = true;
try {
const response = await api.fetchApi("/ausboss/second_copy");
if (!response.ok) return;
showSecondCopyNotices(await response.json(), app.extensionManager?.toast);
} catch (_error) {
// A warning must never break the page.
}
},
});
+25
View File
@@ -0,0 +1,25 @@
// Turns the server's second-copy notices into toasts. Kept apart from
// index.js so the tests can load it without ComfyUI.
export function showSecondCopyNotices(notices, toast) {
const shown = [];
for (const notice of Array.isArray(notices) ? notices : []) {
if (!notice?.detail) continue;
const message = {
severity: notice.older ? "error" : "warn",
summary: notice.summary || "AusBoss is installed twice",
detail: notice.detail,
};
shown.push(message);
try {
if (typeof toast?.add === "function") {
toast.add(message);
continue;
}
} catch (_error) {
// Toast store missing or incompatible: fall through to the console.
}
console.warn(`[AusBoss] ${message.summary}: ${message.detail}`);
}
return shown;
}