Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
385617781e | ||
|
|
c069de3566 | ||
|
|
708b6bdb1b | ||
|
|
520c7c45fb | ||
|
|
b9f905e04c | ||
|
|
431fcf9c58 | ||
|
|
9fb4428a3b | ||
|
|
7d122ddd6c | ||
|
|
536b8620ea | ||
|
|
81ca17463e | ||
|
|
d198428dc4 | ||
|
|
a01ada5372 | ||
|
|
d0b5669f46 | ||
|
|
5292c101db | ||
|
|
134c575727 | ||
|
|
68a1e40d3f | ||
|
|
5a5cea69db | ||
|
|
1edf854cd1 | ||
|
|
4fd6ccc9b0 | ||
|
|
352a928149 | ||
|
|
ce3a422f6a |
@@ -5,3 +5,7 @@ compile_commands.json
|
||||
__pycache__/
|
||||
*.o
|
||||
*.a
|
||||
packaging/arch/effector/
|
||||
packaging/arch/src/
|
||||
packaging/arch/pkg/
|
||||
packaging/arch/*.pkg.tar*
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
# Changelog
|
||||
|
||||
Every release of Effector, newest first. The version lives in one place, the
|
||||
`project()` line of `CMakeLists.txt`, and each release is a `vX.Y.Z` tag on the
|
||||
commit that made it. The interface shows this file under Changelog in its menu.
|
||||
|
||||
## [0.6.0] - 2026-09-26
|
||||
|
||||
### Added
|
||||
- Video projects: switch Video on under Setup and give the clip a length and a
|
||||
frame rate, or pick a preset that sets the canvas too: Instagram story,
|
||||
Instagram reel, Instagram feed video, TikTok / YouTube Short, Square loop and
|
||||
Full HD clip. The preview renders the clip and loops it, with play/pause and
|
||||
a scale to look at any one frame.
|
||||
- Save As… writes a video project as `.mp4`, `.mov`, `.mkv`, `.webm` or `.gif`
|
||||
through `ffmpeg`, with a progress window that can cancel it.
|
||||
- Channel split moves in a video: its channels sway, shake from frame to frame
|
||||
and a tracking bar rolls down the picture, like an old tape on a tube. The
|
||||
new Wobble, Jitter and Tracking bar settings show only in a video, and a
|
||||
still renders exactly as before.
|
||||
- `--duration`, `--fps` and `--video-preset` render a video from the command
|
||||
line.
|
||||
- A Vertical Full HD canvas format, 1080 × 1920.
|
||||
|
||||
## [0.5.3] - 2026-09-26
|
||||
|
||||
### Added
|
||||
- Effector has its own icon, an E split into its colour channels, in the app
|
||||
menu, the dock and About Effector; a one-colour version goes with it for
|
||||
panels.
|
||||
|
||||
## [0.5.2] - 2026-09-26
|
||||
|
||||
### Changed
|
||||
- Effector is free software under the GNU General Public License, version 3
|
||||
or later; the `LICENSE` file holds the text, and About Effector says so.
|
||||
|
||||
## [0.5.1] - 2026-09-26
|
||||
|
||||
### Added
|
||||
- An Arch Linux `PKGBUILD` in `packaging/arch`: `makepkg -si` there builds and
|
||||
installs the tagged release with pacman.
|
||||
- A desktop entry, so an installed Effector shows up in the app menu.
|
||||
|
||||
## [0.5.0] - 2026-09-26
|
||||
|
||||
### Added
|
||||
- A version number: `effector --version` prints it, and About Effector in the
|
||||
menu shows it.
|
||||
- This changelog, readable from the interface under Changelog in the menu.
|
||||
- Open Recent in the project menu, listing the projects opened or saved here.
|
||||
- An optional shadow or glow under the image overlay, with an offset, size,
|
||||
spread, colour and opacity.
|
||||
- Reordering the chain by dragging a row.
|
||||
|
||||
### Fixed
|
||||
- The params' scrollbar no longer covers the spin buttons.
|
||||
|
||||
## [0.4.0] - 2026-09-23
|
||||
|
||||
### Added
|
||||
- Eight chaotic effects: slit shift, channel split, pixel sort, corruption,
|
||||
shatter, warp, bit crush and feedback. None needs sources, so any of them can
|
||||
lead a chain.
|
||||
- The sidebar split into Chain and Setup tabs.
|
||||
- A rotation for the text effect's placement.
|
||||
- Text stages labelled in the chain list with their words.
|
||||
|
||||
### Changed
|
||||
- The preview stays centred however long the status line gets.
|
||||
- The status line stays short, with the full chain and setup in its tooltip.
|
||||
- The chain/params split fits the chain's rows until it is dragged; a
|
||||
double-click on the handle fits it again.
|
||||
- The mouse wheel scrolls past spin buttons that do not have the focus.
|
||||
|
||||
## [0.3.0] - 2026-09-19
|
||||
|
||||
### Added
|
||||
- Named styles: several text stages can share one font and colour, and editing
|
||||
the style moves every stage that follows it.
|
||||
- Switching a chain stage off without taking it apart, in the interface and
|
||||
with `--disable NAME` on the command line.
|
||||
|
||||
### Changed
|
||||
- The interface opens on an empty chain, and shows the sources only when the
|
||||
chain uses them.
|
||||
|
||||
## [0.2.0] - 2026-09-18
|
||||
|
||||
### Added
|
||||
- Effect chains: stages cascade, each handed the previous one's output, built in
|
||||
the sidebar or with repeated `-e`.
|
||||
- Blur, film grain, black and white, image overlay, text and tiles effects.
|
||||
- Projects saved and opened as plain JSON.
|
||||
- Standard web and print canvas formats (`--format`, `--dpi`).
|
||||
- Effects declare whether they need source images, so a chain led by blur
|
||||
renders with none loaded.
|
||||
|
||||
### Changed
|
||||
- The chain comes first in the sidebar.
|
||||
|
||||
### Fixed
|
||||
- The canvas size is checked before it is narrowed to an int.
|
||||
- Projects are written and read in the C locale, and keep the seed whole.
|
||||
|
||||
## [0.1.0] - 2026-09-18
|
||||
|
||||
### Added
|
||||
- The C++20 port of the Python prototype: a GTK 4 interface and a headless
|
||||
command line over pluggable effects, starting with scanlines.
|
||||
- Source images load in the background, with a progress window and Cancel.
|
||||
@@ -12,20 +12,45 @@ ctest --test-dir build --output-on-failure
|
||||
|
||||
Everything is warning-clean under `-Wall -Wextra -Wpedantic`; keep it that way.
|
||||
|
||||
The test suite is a single hand-rolled binary (no framework), so there is no
|
||||
The core test suite is a single hand-rolled binary (no framework), so there is no
|
||||
per-test filter: run `./build/tests/effector_tests` directly to see the section
|
||||
headings (`rng`, `registry`, `scanlines`, `tiles`, `blur`, `chain`, `project`,
|
||||
`image io`, `batch loading`) and the `ok`/`FAIL` lines. To iterate on one area, comment
|
||||
`image io`, `batch loading`, `video`, `version`) and the `ok`/`FAIL` lines. The
|
||||
`video` section writes real files through `ffmpeg` when it is on the PATH and
|
||||
prints a `skip` line otherwise. To iterate on one area, comment
|
||||
out the other blocks in `tests/core_tests.cpp` or add a new
|
||||
`std::cout << "section\n"` block — checks are plain
|
||||
`check(condition, "description")` calls and `main()` returns the failure count.
|
||||
|
||||
The interface has its own binary, `./build/tests/effector_gui_tests`
|
||||
(`tests/gui_tests.cpp`, same `check()` style), which opens the real window and
|
||||
drives it by widget names and tooltips (`chain-list`, `add-effect`,
|
||||
`sources`, "Move up", ...). It needs a display: ctest runs it under `xvfb-run`
|
||||
when that is installed and otherwise reports it skipped (exit 77). To run it by
|
||||
hand, use the Xvfb invocation below.
|
||||
|
||||
Headless render (no display needed, the fastest end-to-end smoke test):
|
||||
|
||||
```bash
|
||||
build/effector -o /tmp/out.png -s 800x600 --strip-height 6 --seed 1 a.jpg b.png
|
||||
```
|
||||
|
||||
### Versions and the changelog
|
||||
|
||||
The version is the `project()` line of `CMakeLists.txt`, and nowhere else.
|
||||
CMake writes it, together with the text of `CHANGELOG.md`, into a generated
|
||||
`core/version.hpp` (`kVersion`, `kChangelog`, from `src/core/version.hpp.in`)
|
||||
in the build tree. `--version` prints it, and the header-bar menu shows it
|
||||
under About Effector and the changelog under Changelog. The `version` core test
|
||||
fails unless the newest `## [X.Y.Z]` entry in `CHANGELOG.md` is the current
|
||||
version, so a bump and its changelog entry go in together, and it also fails unless
|
||||
`pkgver` in `packaging/arch/PKGBUILD` matches (that PKGBUILD builds the
|
||||
`vX.Y.Z` tag, so reset `pkgrel=1` on a bump). Each release is an
|
||||
annotated `vX.Y.Z` tag on the commit that made it. When you add a user-visible
|
||||
change, add a line to the newest changelog entry, or start a new entry if that
|
||||
one is already tagged. The Changelog window reads only headings, `- ` bullets
|
||||
(wrapped onto indented lines) and `` `code` ``, so keep the file to those.
|
||||
|
||||
### Running the GUI from this shell
|
||||
|
||||
GTK picks Wayland from an inherited `WAYLAND_DISPLAY` and will not draw into an
|
||||
@@ -106,7 +131,7 @@ both the style and the stage for that reason. `renderChain` takes the pool as a
|
||||
trailing argument; the command line builds no styles and passes none.
|
||||
|
||||
The interface builds the chain in the sidebar ("Effect chain": add from the
|
||||
menu, reorder, remove, switch off with the check on the row, one stage selected
|
||||
menu, reorder by dragging a row or with its arrows, remove, switch off with the check on the row, one stage selected
|
||||
at a time with its params below), the CLI builds it from repeated `-e`:
|
||||
`-e scanlines --strip-height 6 -e blur --radius 5`, with `--disable NAME`
|
||||
leaving a stage in place but skipping it. Flags share one namespace across all effects, so `buildChain`
|
||||
@@ -141,15 +166,64 @@ can be moved or shared whole.
|
||||
|
||||
The interface opens and saves projects from the header-bar menu (New, Open,
|
||||
Save, Save As, with the usual Ctrl+N/O/S accelerators); the window title shows
|
||||
the project name. Opening one replaces the sources, so a decode still in flight
|
||||
the project name. Open Recent lists the projects opened or saved here, kept in
|
||||
GTK's shared `RecentManager` list and told apart from other programs' files by
|
||||
the `effector` application name on each entry; the GUI tests point
|
||||
`XDG_DATA_HOME` at a temporary folder so they never touch the user's list. Opening one replaces the sources, so a decode still in flight
|
||||
is discarded rather than mixed into the new project (`dropLoadedImages_`).
|
||||
|
||||
### Video projects
|
||||
|
||||
A project is a still or a clip: `VideoSettings` (`src/core/video.hpp`: enabled,
|
||||
duration, fps, preset) rides in `Project::video` and `Options::video`, and is
|
||||
written to the project file only when enabled. `videoPresets()` is one table
|
||||
like `canvasFormats()` — a preset names a canvas format plus a length and rate,
|
||||
and like a format it is the presentation, never the truth: the render goes by
|
||||
duration and fps. Adding a preset is a line there.
|
||||
|
||||
Time reaches an effect as a `FrameTime` (`src/core/effect.hpp`; the default,
|
||||
`fps == 0`, is a still) through `Effect::renderFrame`, which falls back to
|
||||
`render` — an effect that does not move overrides nothing. One that moves
|
||||
overrides `renderFrame` and `animated(values)`, and marks its motion params
|
||||
`.forVideo()`: the interface hides those in a still project (declaratively,
|
||||
like `.styled()`), the CLI still has their flags. A still must render byte for
|
||||
byte what it did before the effect learned to move.
|
||||
|
||||
`renderFrames` (`src/core/chain.cpp`) renders a clip. Every frame starts from
|
||||
`Rng(seed)`, so a stage that does not move draws the same values every frame
|
||||
and holds still. A moving effect must therefore leave the shared rng in the
|
||||
same state on every frame — the channel split draws its per-frame shake from a
|
||||
generator of its own, seeded by one draw — or everything after it would flicker.
|
||||
The stages before the first `animated()` one are rendered once and their image
|
||||
and rng state reused; the `video` tests assert that frame k is exactly
|
||||
`renderChain(..., FrameTime{k, ...})`, so that shortcut can never change output.
|
||||
The determinism contract covers the frames; the encoded file is whatever the
|
||||
machine's ffmpeg makes of them.
|
||||
|
||||
`VideoWriter` pipes raw `rgb24` frames into the `ffmpeg` program
|
||||
(`posix_spawnp` with an argv — no shell; `SIGPIPE` ignored; stderr captured for
|
||||
the error message; codec by extension). `cancel()` SIGKILLs it — SIGTERM makes
|
||||
ffmpeg flush its encoder first — and removes the file; a writer destroyed
|
||||
unfinished cancels itself.
|
||||
|
||||
In the interface, a video render (`startRender`) renders every frame at full
|
||||
size, shrinks each (`Image::scaledToFit`, sized by `clipSide` to a memory
|
||||
budget) and hands them over through `pendingFrames_`/`clipProgress_`; the
|
||||
clip on screen keeps looping until the new one is complete, and
|
||||
`renderCancel_` stops a clip whose settings went stale. Save As… renders again
|
||||
at full size on `exporter_` into a `VideoWriter`, with an `exportWindow_`
|
||||
progress window (its `exportBar_` nulled in `closeExportWindow()`). Under Xvfb
|
||||
the GTK file dialog goes through the desktop portal and may open on the real
|
||||
session instead; set `GDK_DEBUG=no-portals` to keep it in the Xvfb display.
|
||||
|
||||
### Two link targets, deliberately
|
||||
|
||||
`effector_core` (static) holds image IO, params, effects, rng and links only
|
||||
`gdk-pixbuf-2.0`, `pangocairo` (the text effect's glyphs; Pango and Cairo need
|
||||
no display) + Threads — **no gtkmm, no display**. The `effector` executable
|
||||
adds `src/main.cpp`, `src/cli/`, `src/gui/` and links gtkmm. Keep GTK out of
|
||||
`effector_core` (static) holds image IO, params, effects, rng, video writing
|
||||
and links only `gdk-pixbuf-2.0`, `pangocairo` (the text effect's glyphs; Pango
|
||||
and Cairo need no display) + Threads — **no gtkmm, no display**; `ffmpeg` is a
|
||||
program it runs, not a library it links. `effector_gui` (static) adds
|
||||
`src/cli/` and `src/gui/` and links gtkmm, and the `effector` executable is
|
||||
`src/main.cpp` on top of it; the GUI tests link `effector_gui` too. Keep GTK out of
|
||||
`src/core/` and `src/effects/`; the tests link the core alone and rely on this.
|
||||
|
||||
### Determinism is a contract
|
||||
|
||||
+34
-6
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(effector VERSION 0.1.0 LANGUAGES CXX)
|
||||
project(effector VERSION 0.6.0 LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -21,6 +21,14 @@ pkg_check_modules(PANGOCAIRO REQUIRED IMPORTED_TARGET pangocairo)
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
# --- version: the one number, and the changelog that goes with it ------------
|
||||
# The version is the project() line above; each release is a vX.Y.Z tag on the
|
||||
# commit that set it. CHANGELOG.md is baked in so the interface can show it,
|
||||
# and editing it re-runs the configure step.
|
||||
file(READ ${CMAKE_CURRENT_SOURCE_DIR}/CHANGELOG.md EFFECTOR_CHANGELOG)
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS CHANGELOG.md)
|
||||
configure_file(src/core/version.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/generated/core/version.hpp @ONLY)
|
||||
|
||||
# --- core: effects and image handling, no GUI ---------------------------------
|
||||
add_library(effector_core STATIC
|
||||
src/core/canvas.cpp
|
||||
@@ -32,31 +40,51 @@ add_library(effector_core STATIC
|
||||
src/core/registry.cpp
|
||||
src/core/rng.cpp
|
||||
src/core/style.cpp
|
||||
src/core/video.cpp
|
||||
src/effects/bitcrush.cpp
|
||||
src/effects/blur.cpp
|
||||
src/effects/channelsplit.cpp
|
||||
src/effects/corrupt.cpp
|
||||
src/effects/feedback.cpp
|
||||
src/effects/grain.cpp
|
||||
src/effects/monochrome.cpp
|
||||
src/effects/overlay.cpp
|
||||
src/effects/pixelsort.cpp
|
||||
src/effects/scanlines.cpp
|
||||
src/effects/shatter.cpp
|
||||
src/effects/slitshift.cpp
|
||||
src/effects/text.cpp
|
||||
src/effects/tiles.cpp
|
||||
src/effects/warp.cpp
|
||||
)
|
||||
target_include_directories(effector_core PUBLIC src)
|
||||
target_include_directories(effector_core PUBLIC src ${CMAKE_CURRENT_BINARY_DIR}/generated)
|
||||
# The core is GUI-free: it only needs gdk-pixbuf for decoding and encoding,
|
||||
# so headless rendering works without a display.
|
||||
target_link_libraries(effector_core PUBLIC PkgConfig::GDKPIXBUF PkgConfig::PANGOCAIRO Threads::Threads)
|
||||
target_compile_options(effector_core PRIVATE -Wall -Wextra -Wpedantic)
|
||||
|
||||
# --- application --------------------------------------------------------------
|
||||
add_executable(effector
|
||||
src/main.cpp
|
||||
# --- interface: the GTK window, split out so the GUI tests can link it --------
|
||||
add_library(effector_gui STATIC
|
||||
src/cli/options.cpp
|
||||
src/gui/app.cpp
|
||||
src/gui/window.cpp
|
||||
)
|
||||
target_link_libraries(effector PRIVATE effector_core PkgConfig::GTKMM)
|
||||
target_link_libraries(effector_gui PUBLIC effector_core PkgConfig::GTKMM)
|
||||
target_compile_options(effector_gui PRIVATE -Wall -Wextra -Wpedantic)
|
||||
# Where a build that was never installed finds its own icon (see app.cpp).
|
||||
target_compile_definitions(effector_gui PRIVATE
|
||||
EFFECTOR_SOURCE_ICON_DIR="${CMAKE_CURRENT_SOURCE_DIR}/data/icons")
|
||||
|
||||
# --- application --------------------------------------------------------------
|
||||
add_executable(effector src/main.cpp)
|
||||
target_link_libraries(effector PRIVATE effector_gui)
|
||||
target_compile_options(effector PRIVATE -Wall -Wextra -Wpedantic)
|
||||
|
||||
install(TARGETS effector RUNTIME DESTINATION bin)
|
||||
# The launcher entry, so the interface shows up in the desktop's app menu.
|
||||
install(FILES data/org.effector.Effector.desktop DESTINATION share/applications)
|
||||
# The icon it names, in full colour and as a one-colour symbolic for panels.
|
||||
install(DIRECTORY data/icons/hicolor DESTINATION share/icons)
|
||||
|
||||
# --- tests --------------------------------------------------------------------
|
||||
include(CTest)
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
“This License” refers to version 3 of the GNU General Public License.
|
||||
|
||||
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
||||
|
||||
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
||||
|
||||
A “covered work” means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
||||
|
||||
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
||||
|
||||
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -9,6 +9,8 @@ those declarations, so a new effect needs no UI or CLI code.
|
||||
|
||||
Requirements: a C++20 compiler (GCC 13+), CMake 3.20+, `gtkmm-4.0` and
|
||||
`gdk-pixbuf-2.0` development packages. On Arch: `gcc cmake ninja gtkmm-4.0`.
|
||||
Writing videos needs the `ffmpeg` program at run time (on Arch: `ffmpeg`);
|
||||
without it everything else works and the video tests are skipped.
|
||||
|
||||
```bash
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
@@ -19,12 +21,20 @@ ctest --test-dir build --output-on-failure
|
||||
The binary lands at `build/effector`; `cmake --install build --prefix ~/.local`
|
||||
installs it to `~/.local/bin`.
|
||||
|
||||
On Arch, `packaging/arch/PKGBUILD` builds the release tagged `v<version>` from
|
||||
this repository and installs it with pacman, desktop entry included:
|
||||
|
||||
```bash
|
||||
cd packaging/arch && makepkg -si
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
build/effector # GTK interface
|
||||
build/effector --list-effects
|
||||
build/effector --help
|
||||
build/effector --version
|
||||
```
|
||||
|
||||
Headless rendering, no display needed:
|
||||
@@ -50,6 +60,32 @@ Custom hands them back, keeping whatever the format last worked out to. A
|
||||
format is saved with the project, so an A4 project reopens as A4 rather than as
|
||||
the pixels it happened to be.
|
||||
|
||||
### Video
|
||||
|
||||
A project can be a video clip instead of a still: switch **Video** on under
|
||||
Setup and give it a length and a frame rate, or pick a preset that sets the
|
||||
canvas too — Instagram story (1080×1920, 15 s), Instagram reel (30 s),
|
||||
Instagram feed video, TikTok / YouTube Short, Square loop (6 s) and Full HD
|
||||
clip. The preview renders the whole clip first, shrunk to fit in memory, and
|
||||
then loops it, with play/pause and a scale to look at any one frame. **Save
|
||||
As…** then writes the video at full size through `ffmpeg`, which has to be
|
||||
installed: `.mp4`, `.mov` and `.mkv` as H.264, `.webm` as VP9, `.gif` as a
|
||||
palette GIF.
|
||||
|
||||
```bash
|
||||
build/effector -o story.mp4 --video-preset instagram-story -e channelsplit --seed 1 photo.jpg
|
||||
build/effector -o loop.gif -s 480x480 --duration 3 --fps 15 -e channelsplit photo.jpg
|
||||
```
|
||||
|
||||
`--duration SECONDS` and `--fps N` make any run a video; a preset fills in
|
||||
whatever was not given alongside it. Effects that move over time are video
|
||||
effects; for now that is **Channel split**, which in a video sways its
|
||||
channels, shakes them from frame to frame and rolls a tracking bar down the
|
||||
picture, like a worn tape on an old tube. Its motion params only show in a
|
||||
video project, and a still renders exactly as before. Every frame starts from
|
||||
the same seed, so stages that do not move hold still while one that does
|
||||
moves, and a clip renders frame for frame the same again.
|
||||
|
||||
Any option can also be passed when launching the interface; it becomes the
|
||||
starting state (images, canvas size, effect settings, seed).
|
||||
|
||||
@@ -60,6 +96,17 @@ batch. Small batches finish before the window would be drawn, so it only appears
|
||||
if the decode is still going after 250 ms. On a terminal the headless mode keeps
|
||||
a single `reading n/total` line updated on stderr; redirected output stays clean.
|
||||
|
||||
## Versions
|
||||
|
||||
Releases are listed in [CHANGELOG.md](CHANGELOG.md) and tagged `vX.Y.Z`
|
||||
(`git tag -l 'v*'`). `effector --version` prints the version, and the menu in
|
||||
the interface has Changelog and About Effector.
|
||||
|
||||
To cut a release: bump the `project()` version in `CMakeLists.txt`, move the
|
||||
changes into a new `## [X.Y.Z] - date` entry at the top of `CHANGELOG.md` (the
|
||||
core tests fail until the two agree), commit, and tag it:
|
||||
`git tag -a vX.Y.Z -m "Effector X.Y.Z"`.
|
||||
|
||||
## Effects
|
||||
|
||||
### scanlines
|
||||
@@ -140,3 +187,14 @@ render time of the current preview in its status line.
|
||||
Decoding threads take the next file from a shared cursor rather than a fixed
|
||||
slice of the list, so one very large file cannot stall the files queued behind
|
||||
it and progress advances at a steady rate.
|
||||
|
||||
## License
|
||||
|
||||
Copyright © 2026 Si.
|
||||
|
||||
Effector is free software: you can redistribute it and/or modify it under the
|
||||
terms of the GNU General Public License as published by the Free Software
|
||||
Foundation, either version 3 of the License, or (at your option) any later
|
||||
version. It is distributed in the hope that it will be useful, but WITHOUT ANY
|
||||
WARRANTY; see `LICENSE` for the full text. Images you render with it are yours
|
||||
and are not covered by the license.
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
|
||||
<!-- Effector: an E split into its colour channels, two slices slipped sideways -->
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#2b2837"/>
|
||||
<stop offset="1" stop-color="#15131c"/>
|
||||
</linearGradient>
|
||||
<clipPath id="face"><rect x="12" y="10" width="104" height="104" rx="24"/></clipPath>
|
||||
<clipPath id="band0"><rect x="0" y="20" width="128" height="30"/></clipPath>
|
||||
<clipPath id="band1"><rect x="0" y="50" width="128" height="9"/></clipPath>
|
||||
<clipPath id="band2"><rect x="0" y="59" width="128" height="15"/></clipPath>
|
||||
<clipPath id="band3"><rect x="0" y="74" width="128" height="6"/></clipPath>
|
||||
<clipPath id="band4"><rect x="0" y="80" width="128" height="20"/></clipPath>
|
||||
</defs>
|
||||
<rect x="12" y="16" width="104" height="104" rx="24" fill="#0b0a10"/>
|
||||
<g clip-path="url(#face)">
|
||||
<rect x="12" y="10" width="104" height="104" fill="url(#bg)"/>
|
||||
<g fill="#ffffff" opacity=".05">
|
||||
<rect x="12" y="12" width="104" height="1.4"/>
|
||||
<rect x="12" y="16" width="104" height="1.4"/>
|
||||
<rect x="12" y="20" width="104" height="1.4"/>
|
||||
<rect x="12" y="24" width="104" height="1.4"/>
|
||||
<rect x="12" y="28" width="104" height="1.4"/>
|
||||
<rect x="12" y="32" width="104" height="1.4"/>
|
||||
<rect x="12" y="36" width="104" height="1.4"/>
|
||||
<rect x="12" y="40" width="104" height="1.4"/>
|
||||
<rect x="12" y="44" width="104" height="1.4"/>
|
||||
<rect x="12" y="48" width="104" height="1.4"/>
|
||||
<rect x="12" y="52" width="104" height="1.4"/>
|
||||
<rect x="12" y="56" width="104" height="1.4"/>
|
||||
<rect x="12" y="60" width="104" height="1.4"/>
|
||||
<rect x="12" y="64" width="104" height="1.4"/>
|
||||
<rect x="12" y="68" width="104" height="1.4"/>
|
||||
<rect x="12" y="72" width="104" height="1.4"/>
|
||||
<rect x="12" y="76" width="104" height="1.4"/>
|
||||
<rect x="12" y="80" width="104" height="1.4"/>
|
||||
<rect x="12" y="84" width="104" height="1.4"/>
|
||||
<rect x="12" y="88" width="104" height="1.4"/>
|
||||
<rect x="12" y="92" width="104" height="1.4"/>
|
||||
<rect x="12" y="96" width="104" height="1.4"/>
|
||||
<rect x="12" y="100" width="104" height="1.4"/>
|
||||
<rect x="12" y="104" width="104" height="1.4"/>
|
||||
<rect x="12" y="108" width="104" height="1.4"/>
|
||||
<rect x="12" y="112" width="104" height="1.4"/>
|
||||
</g>
|
||||
<g clip-path="url(#band0)"><g transform="translate(0 0)"><g transform="translate(-5 0)"><rect x="40" y="30" width="16" height="62" fill="#00e5ff"/><rect x="40" y="30" width="48" height="14" fill="#00e5ff"/><rect x="40" y="54" width="40" height="13" fill="#00e5ff"/><rect x="40" y="78" width="48" height="14" fill="#00e5ff"/></g><g transform="translate(5 0)"><rect x="40" y="30" width="16" height="62" fill="#ff2e88"/><rect x="40" y="30" width="48" height="14" fill="#ff2e88"/><rect x="40" y="54" width="40" height="13" fill="#ff2e88"/><rect x="40" y="78" width="48" height="14" fill="#ff2e88"/></g><rect x="40" y="30" width="16" height="62" fill="#ffffff"/><rect x="40" y="30" width="48" height="14" fill="#ffffff"/><rect x="40" y="54" width="40" height="13" fill="#ffffff"/><rect x="40" y="78" width="48" height="14" fill="#ffffff"/></g></g>
|
||||
<g clip-path="url(#band1)"><g transform="translate(9 0)"><g transform="translate(-5 0)"><rect x="40" y="30" width="16" height="62" fill="#00e5ff"/><rect x="40" y="30" width="48" height="14" fill="#00e5ff"/><rect x="40" y="54" width="40" height="13" fill="#00e5ff"/><rect x="40" y="78" width="48" height="14" fill="#00e5ff"/></g><g transform="translate(5 0)"><rect x="40" y="30" width="16" height="62" fill="#ff2e88"/><rect x="40" y="30" width="48" height="14" fill="#ff2e88"/><rect x="40" y="54" width="40" height="13" fill="#ff2e88"/><rect x="40" y="78" width="48" height="14" fill="#ff2e88"/></g><rect x="40" y="30" width="16" height="62" fill="#ffffff"/><rect x="40" y="30" width="48" height="14" fill="#ffffff"/><rect x="40" y="54" width="40" height="13" fill="#ffffff"/><rect x="40" y="78" width="48" height="14" fill="#ffffff"/></g></g>
|
||||
<g clip-path="url(#band2)"><g transform="translate(0 0)"><g transform="translate(-5 0)"><rect x="40" y="30" width="16" height="62" fill="#00e5ff"/><rect x="40" y="30" width="48" height="14" fill="#00e5ff"/><rect x="40" y="54" width="40" height="13" fill="#00e5ff"/><rect x="40" y="78" width="48" height="14" fill="#00e5ff"/></g><g transform="translate(5 0)"><rect x="40" y="30" width="16" height="62" fill="#ff2e88"/><rect x="40" y="30" width="48" height="14" fill="#ff2e88"/><rect x="40" y="54" width="40" height="13" fill="#ff2e88"/><rect x="40" y="78" width="48" height="14" fill="#ff2e88"/></g><rect x="40" y="30" width="16" height="62" fill="#ffffff"/><rect x="40" y="30" width="48" height="14" fill="#ffffff"/><rect x="40" y="54" width="40" height="13" fill="#ffffff"/><rect x="40" y="78" width="48" height="14" fill="#ffffff"/></g></g>
|
||||
<g clip-path="url(#band3)"><g transform="translate(-7 0)"><g transform="translate(-5 0)"><rect x="40" y="30" width="16" height="62" fill="#00e5ff"/><rect x="40" y="30" width="48" height="14" fill="#00e5ff"/><rect x="40" y="54" width="40" height="13" fill="#00e5ff"/><rect x="40" y="78" width="48" height="14" fill="#00e5ff"/></g><g transform="translate(5 0)"><rect x="40" y="30" width="16" height="62" fill="#ff2e88"/><rect x="40" y="30" width="48" height="14" fill="#ff2e88"/><rect x="40" y="54" width="40" height="13" fill="#ff2e88"/><rect x="40" y="78" width="48" height="14" fill="#ff2e88"/></g><rect x="40" y="30" width="16" height="62" fill="#ffffff"/><rect x="40" y="30" width="48" height="14" fill="#ffffff"/><rect x="40" y="54" width="40" height="13" fill="#ffffff"/><rect x="40" y="78" width="48" height="14" fill="#ffffff"/></g></g>
|
||||
<g clip-path="url(#band4)"><g transform="translate(0 0)"><g transform="translate(-5 0)"><rect x="40" y="30" width="16" height="62" fill="#00e5ff"/><rect x="40" y="30" width="48" height="14" fill="#00e5ff"/><rect x="40" y="54" width="40" height="13" fill="#00e5ff"/><rect x="40" y="78" width="48" height="14" fill="#00e5ff"/></g><g transform="translate(5 0)"><rect x="40" y="30" width="16" height="62" fill="#ff2e88"/><rect x="40" y="30" width="48" height="14" fill="#ff2e88"/><rect x="40" y="54" width="40" height="13" fill="#ff2e88"/><rect x="40" y="78" width="48" height="14" fill="#ff2e88"/></g><rect x="40" y="30" width="16" height="62" fill="#ffffff"/><rect x="40" y="30" width="48" height="14" fill="#ffffff"/><rect x="40" y="54" width="40" height="13" fill="#ffffff"/><rect x="40" y="78" width="48" height="14" fill="#ffffff"/></g></g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.5 KiB |
@@ -0,0 +1,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
|
||||
<!-- Effector, one colour: the E with its middle slice slipped sideways -->
|
||||
<g fill="#2e3436">
|
||||
<rect x="3" y="2" width="10" height="3"/>
|
||||
<rect x="3" y="5" width="3" height="1.5"/>
|
||||
<rect x="5" y="6.5" width="8" height="3"/>
|
||||
<rect x="3" y="9.5" width="3" height="1.5"/>
|
||||
<rect x="3" y="11" width="10" height="3"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 433 B |
@@ -0,0 +1,12 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Effector
|
||||
GenericName=Image Effects
|
||||
Comment=Cascade glitch and collage effects over your photographs
|
||||
Exec=effector %F
|
||||
Icon=org.effector.Effector
|
||||
Terminal=false
|
||||
Categories=Graphics;2DGraphics;RasterGraphics;GTK;
|
||||
MimeType=image/jpeg;image/png;image/webp;image/tiff;image/bmp;
|
||||
Keywords=glitch;collage;scanlines;photo;effect;
|
||||
StartupNotify=true
|
||||
@@ -0,0 +1,31 @@
|
||||
# Builds the release tagged v$pkgver from the repository this file sits in,
|
||||
# so pkgver must follow the project() line of CMakeLists.txt (the version core
|
||||
# test checks it). From this folder: makepkg -si
|
||||
pkgname=effector
|
||||
pkgver=0.6.0
|
||||
pkgrel=1
|
||||
pkgdesc='Image effects app: a GTK4 interface and a headless CLI over pluggable effects'
|
||||
arch=('x86_64' 'aarch64')
|
||||
url='https://git.plan9.uber.space/hans/effector'
|
||||
license=('GPL-3.0-or-later')
|
||||
depends=('gtkmm-4.0' 'gdk-pixbuf2' 'pango' 'cairo' 'glib2' 'glibc' 'gcc-libs')
|
||||
optdepends=('ffmpeg: write video projects')
|
||||
makedepends=('cmake' 'ninja' 'git')
|
||||
checkdepends=('xorg-server-xvfb')
|
||||
source=("$pkgname::git+file://${startdir%/packaging/arch}#tag=v$pkgver")
|
||||
sha256sums=('SKIP')
|
||||
|
||||
build() {
|
||||
cmake -S "$pkgname" -B build -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr
|
||||
cmake --build build
|
||||
}
|
||||
|
||||
check() {
|
||||
ctest --test-dir build --output-on-failure
|
||||
}
|
||||
|
||||
package() {
|
||||
DESTDIR="$pkgdir" cmake --install build
|
||||
}
|
||||
+72
-1
@@ -55,12 +55,19 @@ std::string requireValue(int argc, char** argv, int& i, const std::string& flag)
|
||||
|
||||
Options parseOptions(int argc, char** argv) {
|
||||
Options options;
|
||||
// What was given explicitly, so that a --video-preset fills in only the
|
||||
// rest, whichever order the flags come in.
|
||||
bool sizeGiven = false;
|
||||
bool durationGiven = false;
|
||||
bool fpsGiven = false;
|
||||
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string arg = argv[i];
|
||||
|
||||
if (arg == "-h" || arg == "--help") {
|
||||
options.showHelp = true;
|
||||
} else if (arg == "-V" || arg == "--version") {
|
||||
options.showVersion = true;
|
||||
} else if (arg == "--list-effects") {
|
||||
options.listEffects = true;
|
||||
} else if (arg == "-e" || arg == "--effect") {
|
||||
@@ -71,6 +78,7 @@ Options parseOptions(int argc, char** argv) {
|
||||
options.output = requireValue(argc, argv, i, arg);
|
||||
} else if (arg == "-s" || arg == "--size") {
|
||||
const std::string value = requireValue(argc, argv, i, arg);
|
||||
sizeGiven = true;
|
||||
if (!parseSize(value, options.width, options.height)) {
|
||||
throw EffectError("invalid size '" + value + "', expected e.g. 1920x1080 with "
|
||||
"each side between " + std::to_string(kMinCanvasSide) + " and " +
|
||||
@@ -90,6 +98,41 @@ Options parseOptions(int argc, char** argv) {
|
||||
std::to_string(kMinDpi) + "-" + std::to_string(kMaxDpi));
|
||||
}
|
||||
options.dpi = static_cast<int>(dpi);
|
||||
} else if (arg == "--duration") {
|
||||
const std::string value = requireValue(argc, argv, i, arg);
|
||||
double seconds = 0.0;
|
||||
try {
|
||||
std::size_t used = 0;
|
||||
seconds = std::stod(value, &used);
|
||||
if (used != value.size()) seconds = 0.0;
|
||||
} catch (const std::exception&) {
|
||||
seconds = 0.0;
|
||||
}
|
||||
if (!(seconds >= kMinDuration) || !(seconds <= kMaxDuration)) {
|
||||
throw EffectError("invalid duration '" + value + "', expected seconds between " +
|
||||
formatSeconds(kMinDuration) + " and " +
|
||||
formatSeconds(kMaxDuration));
|
||||
}
|
||||
options.video.enabled = true;
|
||||
options.video.duration = seconds;
|
||||
durationGiven = true;
|
||||
} else if (arg == "--fps") {
|
||||
const std::string value = requireValue(argc, argv, i, arg);
|
||||
long fps = 0;
|
||||
if (!parseLong(value, fps) || fps < kMinFps || fps > kMaxFps) {
|
||||
throw EffectError("invalid frame rate '" + value + "', expected " +
|
||||
std::to_string(kMinFps) + "-" + std::to_string(kMaxFps));
|
||||
}
|
||||
options.video.enabled = true;
|
||||
options.video.fps = static_cast<int>(fps);
|
||||
fpsGiven = true;
|
||||
} else if (arg == "--video-preset") {
|
||||
const std::string value = requireValue(argc, argv, i, arg);
|
||||
if (videoPresetByKey(value) == nullptr) {
|
||||
throw EffectError("unknown video preset '" + value + "', see --help");
|
||||
}
|
||||
options.video.enabled = true;
|
||||
options.video.preset = value;
|
||||
} else if (arg == "--disable") {
|
||||
const std::string name = requireValue(argc, argv, i, arg);
|
||||
effectByName(name); // validate now, exactly as -e does
|
||||
@@ -160,6 +203,18 @@ Options parseOptions(int argc, char** argv) {
|
||||
options.images.push_back(arg);
|
||||
}
|
||||
}
|
||||
// A preset fills in whatever was not given on its own: the length, the
|
||||
// rate and -- unless -s or --format named one -- the canvas. It keeps its
|
||||
// name only while the settings still are the preset's.
|
||||
if (const auto* preset = videoPresetByKey(options.video.preset)) {
|
||||
if (!durationGiven) options.video.duration = preset->seconds;
|
||||
if (!fpsGiven) options.video.fps = preset->fps;
|
||||
if (options.format.empty() && !sizeGiven) options.format = preset->canvasFormat;
|
||||
if (options.video.duration != preset->seconds || options.video.fps != preset->fps ||
|
||||
options.format != preset->canvasFormat) {
|
||||
options.video.preset.clear();
|
||||
}
|
||||
}
|
||||
// Applied once everything is parsed, so --dpi may come before --format and
|
||||
// so a format always wins over an -s given alongside it.
|
||||
if (const auto* format = canvasFormatByKey(options.format)) {
|
||||
@@ -181,9 +236,15 @@ std::string usage(const char* programName) {
|
||||
<< " --format NAME canvas format, overrides --size (see below)\n"
|
||||
<< " --dpi N resolution of a print format, " << kMinDpi << "-" << kMaxDpi
|
||||
<< " (default: " << kDefaultDpi << ")\n"
|
||||
<< " --duration SECS render a video this long, " << formatSeconds(kMinDuration)
|
||||
<< " to " << formatSeconds(kMaxDuration) << "\n"
|
||||
<< " --fps N frames per second of a video, " << kMinFps << "-" << kMaxFps
|
||||
<< " (default: " << kDefaultFps << ")\n"
|
||||
<< " --video-preset NAME a video's canvas and length in one (see below)\n"
|
||||
<< " --disable NAME keep this effect in the chain but skip it\n"
|
||||
<< " --seed N random seed (default: random)\n"
|
||||
<< " --list-effects list available effects and exit\n"
|
||||
<< " -V, --version show the version and exit\n"
|
||||
<< " -h, --help show this help and exit\n";
|
||||
|
||||
out << "\nCanvas formats (--format):\n";
|
||||
@@ -194,6 +255,15 @@ std::string usage(const char* programName) {
|
||||
<< (format.print ? " at --dpi" : "") << "\n";
|
||||
}
|
||||
|
||||
out << "\nA video is written through ffmpeg, as .mp4, .mov, .mkv, .webm or .gif by the "
|
||||
"name given to\n--output.\n";
|
||||
out << "\nVideo presets (--video-preset):\n";
|
||||
for (const auto& preset : videoPresets()) {
|
||||
out << " " << preset.key;
|
||||
if (preset.key.size() < 20) out << std::string(20 - preset.key.size(), ' ');
|
||||
out << " " << preset.label << ", " << videoPresetDetail(preset) << "\n";
|
||||
}
|
||||
|
||||
for (const auto& effect : effects()) {
|
||||
out << "\n" << effect->title() << " options:\n";
|
||||
for (const auto& spec : effect->params()) {
|
||||
@@ -201,7 +271,8 @@ std::string usage(const char* programName) {
|
||||
if (spec.type != ParamSpec::Type::Bool) flag += " VALUE";
|
||||
out << " " << flag;
|
||||
if (flag.size() < 20) out << std::string(20 - flag.size(), ' ');
|
||||
out << " " << (spec.help.empty() ? spec.label : spec.help) << "\n";
|
||||
out << " " << (spec.help.empty() ? spec.label : spec.help)
|
||||
<< (spec.videoOnly ? " (video only)" : "") << "\n";
|
||||
}
|
||||
}
|
||||
return out.str();
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "core/canvas.hpp"
|
||||
#include "core/chain.hpp"
|
||||
#include "core/params.hpp"
|
||||
#include "core/video.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
@@ -23,10 +24,14 @@ struct Options {
|
||||
int height = 1080;
|
||||
std::string format; // a named canvas format, empty for plain pixels
|
||||
int dpi = kDefaultDpi; // only a print format is rendered at a resolution
|
||||
// Enabled by --duration, --fps or --video-preset: the output is then a
|
||||
// video, and --output has to name one.
|
||||
VideoSettings video;
|
||||
std::optional<std::uint64_t> seed;
|
||||
ParamValues params; // only the keys the user actually passed
|
||||
bool listEffects = false;
|
||||
bool showHelp = false;
|
||||
bool showVersion = false;
|
||||
};
|
||||
|
||||
// Throws EffectError on bad input. Effect flags are generated from the
|
||||
|
||||
@@ -33,6 +33,7 @@ const std::vector<CanvasFormat>& canvasFormats() {
|
||||
{"instagram-post", "Instagram post", false, 1080, 1080, 0.0, 0.0},
|
||||
{"instagram-portrait", "Instagram portrait", false, 1080, 1350, 0.0, 0.0},
|
||||
{"instagram-story", "Instagram story", false, 1080, 1920, 0.0, 0.0},
|
||||
{"vertical-hd", "Vertical Full HD", false, 1080, 1920, 0.0, 0.0},
|
||||
{"hd", "Full HD", false, 1920, 1080, 0.0, 0.0},
|
||||
{"uhd", "4K UHD", false, 3840, 2160, 0.0, 0.0},
|
||||
{"a5", "A5", true, 0, 0, 148.0, 210.0},
|
||||
|
||||
+67
-7
@@ -1,5 +1,7 @@
|
||||
#include "core/chain.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace effector {
|
||||
|
||||
std::vector<const ChainStage*> enabledStages(const std::vector<ChainStage>& stages) {
|
||||
@@ -29,8 +31,10 @@ ParamValues stageValues(const ChainStage& stage, const StyleSet& styles) {
|
||||
return values;
|
||||
}
|
||||
|
||||
Image renderChain(const std::vector<ChainStage>& stages, const std::vector<Image>& sources,
|
||||
int width, int height, Rng& rng, const StyleSet& styles) {
|
||||
namespace {
|
||||
|
||||
// The stages that run, checked: throws for a chain with nothing to render.
|
||||
std::vector<const ChainStage*> runningStages(const std::vector<ChainStage>& stages) {
|
||||
if (stages.empty()) throw EffectError("The effect chain is empty.");
|
||||
for (const auto& stage : stages) {
|
||||
if (!stage.effect) throw EffectError("The effect chain has an empty stage.");
|
||||
@@ -39,27 +43,83 @@ Image renderChain(const std::vector<ChainStage>& stages, const std::vector<Image
|
||||
// A disabled stage never reaches the render at all: it is not handed an
|
||||
// image and draws nothing from the shared rng, so switching one off gives
|
||||
// back exactly the picture the chain made before it was added.
|
||||
const auto running = enabledStages(stages);
|
||||
auto running = enabledStages(stages);
|
||||
if (running.empty()) throw EffectError("Every effect in the chain is disabled.");
|
||||
return running;
|
||||
}
|
||||
|
||||
Image image;
|
||||
for (std::size_t i = 0; i < running.size(); ++i) {
|
||||
// Runs running[first, last) on `image`, which holds the sources' place for
|
||||
// the first stage of the chain and the previous stage's output after it.
|
||||
Image runStages(const std::vector<const ChainStage*>& running, std::size_t first,
|
||||
std::size_t last, const std::vector<Image>& sources, Image image, int width,
|
||||
int height, Rng& rng, const StyleSet& styles, const FrameTime& frame) {
|
||||
for (std::size_t i = first; i < last; ++i) {
|
||||
const auto& stage = *running[i];
|
||||
|
||||
const auto values = stageValues(stage, styles);
|
||||
|
||||
if (i == 0) {
|
||||
image = stage.effect->render(sources, width, height, rng, values);
|
||||
image = stage.effect->renderFrame(sources, width, height, rng, values, frame);
|
||||
} else {
|
||||
// Feeding the previous result back in as the only source is what
|
||||
// cascading means here; effects need to know nothing about it.
|
||||
const std::vector<Image> previous = {std::move(image)};
|
||||
image = stage.effect->render(previous, width, height, rng, values);
|
||||
image = stage.effect->renderFrame(previous, width, height, rng, values, frame);
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Image renderChain(const std::vector<ChainStage>& stages, const std::vector<Image>& sources,
|
||||
int width, int height, Rng& rng, const StyleSet& styles,
|
||||
const FrameTime& frame) {
|
||||
const auto running = runningStages(stages);
|
||||
return runStages(running, 0, running.size(), sources, Image(), width, height, rng, styles,
|
||||
frame);
|
||||
}
|
||||
|
||||
bool chainAnimated(const std::vector<ChainStage>& stages, const StyleSet& styles) {
|
||||
for (const auto* stage : enabledStages(stages)) {
|
||||
if (stage->effect->animated(stageValues(*stage, styles))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int renderFrames(const std::vector<ChainStage>& stages, const std::vector<Image>& sources,
|
||||
int width, int height, std::uint64_t seed, const StyleSet& styles,
|
||||
const VideoSettings& video,
|
||||
const std::function<bool(int index, Image&& frame)>& onFrame) {
|
||||
const auto running = runningStages(stages);
|
||||
const int count = video.frameCount();
|
||||
const int fps = std::clamp(video.fps, kMinFps, kMaxFps);
|
||||
|
||||
// Everything before the first stage that moves is the same on every
|
||||
// frame -- the same seed, the same values, no time -- so it is rendered
|
||||
// once, as frame 0, and picked up from there. The rng is copied along
|
||||
// with the picture, which is what makes the shortcut exact.
|
||||
std::size_t still = 0;
|
||||
while (still < running.size() &&
|
||||
!running[still]->effect->animated(stageValues(*running[still], styles))) {
|
||||
++still;
|
||||
}
|
||||
Rng prefixRng(seed);
|
||||
const Image prefix = runStages(running, 0, still, sources, Image(), width, height, prefixRng,
|
||||
styles, FrameTime{0, count, fps});
|
||||
|
||||
for (int index = 0; index < count; ++index) {
|
||||
const FrameTime frame{index, count, fps};
|
||||
Rng rng = prefixRng;
|
||||
Image image = still == running.size()
|
||||
? prefix
|
||||
: runStages(running, still, running.size(), sources, prefix, width,
|
||||
height, rng, styles, frame);
|
||||
if (!onFrame(index, std::move(image))) return index + 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
bool chainNeedsSources(const std::vector<ChainStage>& stages) {
|
||||
const auto running = enabledStages(stages);
|
||||
if (running.empty()) return false;
|
||||
|
||||
+23
-1
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -8,6 +9,7 @@
|
||||
#include "core/params.hpp"
|
||||
#include "core/rng.hpp"
|
||||
#include "core/style.hpp"
|
||||
#include "core/video.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
@@ -52,8 +54,28 @@ std::vector<const ChainStage*> enabledStages(const std::vector<ChainStage>& stag
|
||||
// reproduces the cascade byte for byte. Throws when no stage is left to run.
|
||||
// `styles` is the project's pool; a chain built without one -- the command
|
||||
// line's -- passes none and renders from the stages alone.
|
||||
//
|
||||
// `frame` says where in a video the render sits, a still by default; every
|
||||
// stage is handed it, and only one that moves makes anything of it.
|
||||
Image renderChain(const std::vector<ChainStage>& stages, const std::vector<Image>& sources,
|
||||
int width, int height, Rng& rng, const StyleSet& styles = {});
|
||||
int width, int height, Rng& rng, const StyleSet& styles = {},
|
||||
const FrameTime& frame = {});
|
||||
|
||||
// Whether any stage that runs moves over time with the values it runs with.
|
||||
bool chainAnimated(const std::vector<ChainStage>& stages, const StyleSet& styles = {});
|
||||
|
||||
// Renders every frame of a video, in order, handing each to `onFrame`; it
|
||||
// returning false stops the render there. Frame k is exactly what
|
||||
// renderChain gives with a fresh Rng(seed) and FrameTime{k, count, fps} --
|
||||
// every frame starts from the same seed, so a stage that does not move
|
||||
// renders the same picture throughout rather than reshuffling on every
|
||||
// frame. The stages before the first one that moves are rendered once, and
|
||||
// their picture and the rng state they leave are reused for every frame.
|
||||
// Returns the number of frames handed out.
|
||||
int renderFrames(const std::vector<ChainStage>& stages, const std::vector<Image>& sources,
|
||||
int width, int height, std::uint64_t seed, const StyleSet& styles,
|
||||
const VideoSettings& video,
|
||||
const std::function<bool(int index, Image&& frame)>& onFrame);
|
||||
|
||||
// Whether the chain has to be given source images. Only the first stage that
|
||||
// runs ever sees them — every later one works on the stage before it — so this
|
||||
|
||||
@@ -16,6 +16,19 @@ public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
// Where a render sits in time. The default -- no frame rate -- is a still
|
||||
// picture; a video hands every frame its index, the clip's length in frames
|
||||
// and its rate, so an effect that moves works out where it is from these
|
||||
// alone and a frame can be rendered on its own, in any order.
|
||||
struct FrameTime {
|
||||
int index = 0;
|
||||
int count = 1;
|
||||
int fps = 0;
|
||||
|
||||
bool video() const noexcept { return fps > 0; }
|
||||
double seconds() const noexcept { return video() ? static_cast<double>(index) / fps : 0.0; }
|
||||
};
|
||||
|
||||
// Base class for every effect. Canvas size and the random source are common to
|
||||
// all of them; params() covers only the effect-specific knobs.
|
||||
class Effect {
|
||||
@@ -38,9 +51,34 @@ public:
|
||||
// use. An effect with no kind must declare no styled params.
|
||||
virtual std::string styleKind() const { return {}; }
|
||||
|
||||
// How a stage of this effect is named in a list of stages, given its
|
||||
// values: the title unless the values say something more telling.
|
||||
virtual std::string label(const ParamValues& values) const {
|
||||
(void)values;
|
||||
return title();
|
||||
}
|
||||
|
||||
// Whether a stage with these values changes from one frame of a video to
|
||||
// the next. A stage that does not is rendered once for the whole clip.
|
||||
virtual bool animated(const ParamValues& values) const {
|
||||
(void)values;
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const = 0;
|
||||
|
||||
// One frame of a video, or a still when `frame` says so. An effect that
|
||||
// does not move needs only render(), which this falls back to. One that
|
||||
// does must leave `rng` in the same state on every frame -- a frame's own
|
||||
// randomness comes from a generator of its own -- so the stages after it
|
||||
// stay put while it moves.
|
||||
virtual Image renderFrame(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values, const FrameTime& frame) const {
|
||||
(void)frame;
|
||||
return render(sources, width, height, rng, values);
|
||||
}
|
||||
|
||||
ParamValues defaults() const;
|
||||
};
|
||||
|
||||
|
||||
@@ -91,6 +91,39 @@ Image Image::load(const std::string& path, std::vector<std::uint8_t>* alphaOut)
|
||||
return image;
|
||||
}
|
||||
|
||||
Image Image::scaledToFit(int maxSide) const {
|
||||
const int longest = std::max(width_, height_);
|
||||
if (empty() || maxSide < 1 || longest <= maxSide) return *this;
|
||||
|
||||
const double scale = static_cast<double>(maxSide) / longest;
|
||||
const int outWidth = std::max(1, static_cast<int>(width_ * scale));
|
||||
const int outHeight = std::max(1, static_cast<int>(height_ * scale));
|
||||
Image out(outWidth, outHeight);
|
||||
for (int y = 0; y < outHeight; ++y) {
|
||||
const int y0 = static_cast<int>(static_cast<long>(y) * height_ / outHeight);
|
||||
const int y1 = std::max(y0 + 1, static_cast<int>(static_cast<long>(y + 1) * height_ / outHeight));
|
||||
std::uint8_t* target = out.row(y);
|
||||
for (int x = 0; x < outWidth; ++x) {
|
||||
const int x0 = static_cast<int>(static_cast<long>(x) * width_ / outWidth);
|
||||
const int x1 = std::max(x0 + 1, static_cast<int>(static_cast<long>(x + 1) * width_ / outWidth));
|
||||
unsigned sum[3] = {0, 0, 0};
|
||||
for (int sy = y0; sy < y1; ++sy) {
|
||||
const std::uint8_t* in = row(sy) + static_cast<std::size_t>(x0) * 3;
|
||||
for (int sx = x0; sx < x1; ++sx, in += 3) {
|
||||
sum[0] += in[0];
|
||||
sum[1] += in[1];
|
||||
sum[2] += in[2];
|
||||
}
|
||||
}
|
||||
const unsigned area = static_cast<unsigned>((y1 - y0) * (x1 - x0));
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
target[static_cast<std::size_t>(x) * 3 + c] = static_cast<std::uint8_t>(sum[c] / area);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void Image::save(const std::string& path) const {
|
||||
if (empty()) throw std::runtime_error("nothing to save");
|
||||
|
||||
|
||||
@@ -40,6 +40,11 @@ public:
|
||||
// which is what an effect compositing the image needs.
|
||||
static Image load(const std::string& path, std::vector<std::uint8_t>* alphaOut = nullptr);
|
||||
|
||||
// A copy shrunk so that its longer side is at most `maxSide`, each pixel
|
||||
// the average of the ones it covers; an image already that small comes
|
||||
// back as it is. For previews: nothing rendered goes through it.
|
||||
Image scaledToFit(int maxSide) const;
|
||||
|
||||
// Encodes by file extension; png is used when the extension is unknown.
|
||||
void save(const std::string& path) const;
|
||||
|
||||
|
||||
@@ -16,6 +16,12 @@ ParamSpec ParamSpec::styled() const {
|
||||
return copy;
|
||||
}
|
||||
|
||||
ParamSpec ParamSpec::forVideo() const {
|
||||
ParamSpec copy = *this;
|
||||
copy.videoOnly = true;
|
||||
return copy;
|
||||
}
|
||||
|
||||
ParamSpec ParamSpec::makeInt(std::string key, std::string label, long defaultValue, long minimum,
|
||||
long maximum, std::string help, long step) {
|
||||
ParamSpec spec;
|
||||
|
||||
@@ -27,6 +27,10 @@ struct ParamSpec {
|
||||
// Whether a named style carries this param rather than the stage it sits
|
||||
// on: see core/style.hpp.
|
||||
bool inStyle = false;
|
||||
// Whether the param only means something in a video project -- how a
|
||||
// stage moves over time. The interface leaves it out of a still project,
|
||||
// where it would change nothing.
|
||||
bool videoOnly = false;
|
||||
|
||||
std::string flag() const; // "strip_height" -> "--strip-height"
|
||||
|
||||
@@ -34,6 +38,9 @@ struct ParamSpec {
|
||||
// reads makeDouble("font_size", ...).styled() and the factories keep the
|
||||
// signatures they have.
|
||||
ParamSpec styled() const;
|
||||
// A copy of this spec marked as mattering only in a video project, read
|
||||
// the same way: makeInt("split_jitter", ...).forVideo().
|
||||
ParamSpec forVideo() const;
|
||||
|
||||
static ParamSpec makeInt(std::string key, std::string label, long defaultValue, long minimum,
|
||||
long maximum, std::string help = {}, long step = 1);
|
||||
|
||||
@@ -319,6 +319,25 @@ int canvasDpi(const Json& value) {
|
||||
return static_cast<int>(value.number);
|
||||
}
|
||||
|
||||
// A clip's length in seconds and its frame rate, checked like the canvas.
|
||||
double videoDuration(const Json& value) {
|
||||
if (value.kind != Json::Kind::Number || !(value.number >= kMinDuration) ||
|
||||
!(value.number <= kMaxDuration)) {
|
||||
throw EffectError("the video duration must be between " + formatSeconds(kMinDuration) +
|
||||
" and " + formatSeconds(kMaxDuration));
|
||||
}
|
||||
return value.number;
|
||||
}
|
||||
|
||||
int videoFps(const Json& value) {
|
||||
if (value.kind != Json::Kind::Number || value.number != std::trunc(value.number) ||
|
||||
!(value.number >= kMinFps) || !(value.number <= kMaxFps)) {
|
||||
throw EffectError("the video frame rate must be a whole number between " +
|
||||
std::to_string(kMinFps) + " and " + std::to_string(kMaxFps));
|
||||
}
|
||||
return static_cast<int>(value.number);
|
||||
}
|
||||
|
||||
std::string resolve(const std::string& path, const std::string& directory) {
|
||||
std::filesystem::path file(path);
|
||||
if (file.is_absolute() || directory.empty()) return path;
|
||||
@@ -435,6 +454,16 @@ std::string projectToJson(const Project& project, const std::string& directory)
|
||||
if (format->print) out << ", \"dpi\": " << project.dpi;
|
||||
}
|
||||
out << "},\n";
|
||||
// Only a video says anything about time: a still project reads exactly as
|
||||
// it did before there were videos.
|
||||
if (project.video.enabled) {
|
||||
out << " \"video\": {\"duration\": " << number(project.video.duration, 3)
|
||||
<< ", \"fps\": " << project.video.fps;
|
||||
if (const auto* preset = videoPresetByKey(project.video.preset)) {
|
||||
out << ", \"preset\": " << quote(preset->key);
|
||||
}
|
||||
out << "},\n";
|
||||
}
|
||||
if (project.seed) out << " \"seed\": " << *project.seed << ",\n";
|
||||
|
||||
out << " \"sources\": [";
|
||||
@@ -506,6 +535,21 @@ Project projectFromJson(const std::string& text, const std::string& directory) {
|
||||
}
|
||||
}
|
||||
|
||||
if (const auto* video = root.member("video"); video != nullptr &&
|
||||
video->kind == Json::Kind::Object) {
|
||||
project.video.enabled = true;
|
||||
if (const auto* duration = video->member("duration")) {
|
||||
project.video.duration = videoDuration(*duration);
|
||||
}
|
||||
if (const auto* fps = video->member("fps")) project.video.fps = videoFps(*fps);
|
||||
// Like a canvas format, a preset this build does not know is just the
|
||||
// user's own settings: the numbers were written too.
|
||||
if (const auto* name = video->member("preset"); name != nullptr &&
|
||||
name->kind == Json::Kind::String) {
|
||||
if (const auto* preset = videoPresetByKey(name->text)) project.video.preset = preset->key;
|
||||
}
|
||||
}
|
||||
|
||||
if (const auto* seed = root.member("seed")) {
|
||||
// Taken from the digits rather than from the double: a 64-bit seed has
|
||||
// more bits than a double has mantissa, and a seed that comes back off
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "core/chain.hpp"
|
||||
#include "core/params.hpp"
|
||||
#include "core/style.hpp"
|
||||
#include "core/video.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
@@ -30,6 +31,8 @@ struct Project {
|
||||
// resolution for.
|
||||
std::string format;
|
||||
int dpi = kDefaultDpi;
|
||||
// Whether the project is a video, and how long and how fast.
|
||||
VideoSettings video;
|
||||
std::optional<std::uint64_t> seed;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
#include "core/registry.hpp"
|
||||
|
||||
#include "effects/bitcrush.hpp"
|
||||
#include "effects/blur.hpp"
|
||||
#include "effects/channelsplit.hpp"
|
||||
#include "effects/corrupt.hpp"
|
||||
#include "effects/feedback.hpp"
|
||||
#include "effects/grain.hpp"
|
||||
#include "effects/monochrome.hpp"
|
||||
#include "effects/overlay.hpp"
|
||||
#include "effects/pixelsort.hpp"
|
||||
#include "effects/scanlines.hpp"
|
||||
#include "effects/shatter.hpp"
|
||||
#include "effects/slitshift.hpp"
|
||||
#include "effects/text.hpp"
|
||||
#include "effects/tiles.hpp"
|
||||
#include "effects/warp.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
@@ -20,6 +28,14 @@ const std::vector<EffectPtr>& effects() {
|
||||
std::make_shared<OverlayEffect>(),
|
||||
std::make_shared<TextEffect>(),
|
||||
std::make_shared<TilesEffect>(),
|
||||
std::make_shared<SlitShiftEffect>(),
|
||||
std::make_shared<ChannelSplitEffect>(),
|
||||
std::make_shared<PixelSortEffect>(),
|
||||
std::make_shared<CorruptEffect>(),
|
||||
std::make_shared<ShatterEffect>(),
|
||||
std::make_shared<WarpEffect>(),
|
||||
std::make_shared<BitCrushEffect>(),
|
||||
std::make_shared<FeedbackEffect>(),
|
||||
};
|
||||
return registry;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
// Generated by CMake from src/core/version.hpp.in; edit that, not the copy in
|
||||
// the build tree. The version comes from the project() line of CMakeLists.txt
|
||||
// and the changelog from CHANGELOG.md, both read at configure time.
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace effector {
|
||||
|
||||
inline constexpr std::string_view kVersion = "@PROJECT_VERSION@";
|
||||
|
||||
// CHANGELOG.md as it stood when the build was configured, as Markdown.
|
||||
inline constexpr std::string_view kChangelog = R"changelog(@EFFECTOR_CHANGELOG@)changelog";
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,272 @@
|
||||
#include "core/video.hpp"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <spawn.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <locale>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
|
||||
#include "core/canvas.hpp"
|
||||
#include "core/effect.hpp"
|
||||
|
||||
extern char** environ;
|
||||
|
||||
namespace effector {
|
||||
|
||||
int VideoSettings::frameCount() const {
|
||||
const double seconds = std::clamp(duration, kMinDuration, kMaxDuration);
|
||||
const int rate = std::clamp(fps, kMinFps, kMaxFps);
|
||||
return std::max(1, static_cast<int>(std::lround(seconds * rate)));
|
||||
}
|
||||
|
||||
const std::vector<VideoPreset>& videoPresets() {
|
||||
// A story segment runs fifteen seconds, a reel is best kept to half a
|
||||
// minute, and a loop is short enough to watch go round a few times.
|
||||
static const std::vector<VideoPreset> presets = {
|
||||
{"instagram-story", "Instagram story", "instagram-story", 15.0, 30},
|
||||
{"instagram-reel", "Instagram reel", "instagram-story", 30.0, 30},
|
||||
{"instagram-feed", "Instagram feed video", "instagram-portrait", 10.0, 30},
|
||||
{"vertical-short", "TikTok / YouTube Short", "vertical-hd", 30.0, 30},
|
||||
{"square-loop", "Square loop", "instagram-post", 6.0, 30},
|
||||
{"hd-clip", "Full HD clip", "hd", 10.0, 30},
|
||||
};
|
||||
return presets;
|
||||
}
|
||||
|
||||
const VideoPreset* videoPresetByKey(const std::string& key) {
|
||||
if (key.empty()) return nullptr;
|
||||
for (const auto& preset : videoPresets()) {
|
||||
if (preset.key == key) return &preset;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// In the C locale whatever the user's is, for the same reason as the
|
||||
// millimetres of a paper size: "7.5 s", never "7,5 s".
|
||||
std::string formatSeconds(double seconds) {
|
||||
std::ostringstream out;
|
||||
out.imbue(std::locale::classic());
|
||||
out.setf(std::ios::fixed);
|
||||
out.precision(1);
|
||||
out << seconds;
|
||||
std::string text = out.str();
|
||||
if (text.size() > 2 && text.compare(text.size() - 2, 2, ".0") == 0) text.resize(text.size() - 2);
|
||||
return text + " s";
|
||||
}
|
||||
|
||||
std::string videoPresetDetail(const VideoPreset& preset) {
|
||||
const auto* format = canvasFormatByKey(preset.canvasFormat);
|
||||
std::string text = format != nullptr ? canvasFormatDetail(*format) + " · " : std::string();
|
||||
return text + formatSeconds(preset.seconds);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::string lowerExtension(const std::string& path) {
|
||||
std::string extension = std::filesystem::path(path).extension().string();
|
||||
std::transform(extension.begin(), extension.end(), extension.begin(),
|
||||
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
||||
return extension;
|
||||
}
|
||||
|
||||
// The container ffmpeg is told to write, by extension; empty for one that
|
||||
// is not a video.
|
||||
std::string muxerFor(const std::string& extension) {
|
||||
if (extension == ".mp4") return "mp4";
|
||||
if (extension == ".mov") return "mov";
|
||||
if (extension == ".mkv") return "matroska";
|
||||
if (extension == ".webm") return "webm";
|
||||
if (extension == ".gif") return "gif";
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool isVideoPath(const std::string& path) { return !muxerFor(lowerExtension(path)).empty(); }
|
||||
|
||||
bool ffmpegAvailable() {
|
||||
const char* path = std::getenv("PATH");
|
||||
if (path == nullptr) return false;
|
||||
std::stringstream dirs(path);
|
||||
std::string dir;
|
||||
while (std::getline(dirs, dir, ':')) {
|
||||
if (dir.empty()) dir = ".";
|
||||
if (::access((dir + "/ffmpeg").c_str(), X_OK) == 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
VideoWriter::VideoWriter(const std::string& path, int width, int height, int fps)
|
||||
: path_(path), width_(width), height_(height) {
|
||||
const std::string muxer = muxerFor(lowerExtension(path));
|
||||
if (muxer.empty()) {
|
||||
throw EffectError("A video is written as .mp4, .mov, .mkv, .webm or .gif, not '" +
|
||||
std::filesystem::path(path).filename().string() + "'.");
|
||||
}
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
|
||||
// A write to an ffmpeg that has already died must come back as an error
|
||||
// to report, not as a signal that takes the whole program down with it.
|
||||
static std::once_flag ignorePipe;
|
||||
std::call_once(ignorePipe, [] { ::signal(SIGPIPE, SIG_IGN); });
|
||||
|
||||
std::vector<std::string> args = {
|
||||
"ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
|
||||
"-f", "rawvideo", "-pix_fmt", "rgb24",
|
||||
"-s", std::to_string(width) + "x" + std::to_string(height),
|
||||
"-r", std::to_string(std::clamp(fps, kMinFps, kMaxFps)),
|
||||
"-i", "pipe:0", "-an",
|
||||
};
|
||||
if (muxer == "gif") {
|
||||
// One palette made for the whole clip, rather than the fixed web one.
|
||||
args.insert(args.end(), {"-vf", "split[a][b];[b]palettegen[p];[a][p]paletteuse",
|
||||
"-loop", "0"});
|
||||
} else {
|
||||
// 4:2:0 wants even sides; a pixel of padding beats refusing the canvas.
|
||||
args.insert(args.end(), {"-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2"});
|
||||
if (muxer == "webm") {
|
||||
args.insert(args.end(), {"-c:v", "libvpx-vp9", "-crf", "32", "-b:v", "0",
|
||||
"-row-mt", "1"});
|
||||
} else {
|
||||
args.insert(args.end(), {"-c:v", "libx264", "-preset", "medium", "-crf", "18"});
|
||||
}
|
||||
args.insert(args.end(), {"-pix_fmt", "yuv420p"});
|
||||
if (muxer == "mp4" || muxer == "mov") args.insert(args.end(), {"-movflags", "+faststart"});
|
||||
}
|
||||
// "file:" keeps a name that starts with a dash, or holds a colon, a file.
|
||||
args.insert(args.end(), {"-f", muxer, "file:" + path});
|
||||
|
||||
int pipeEnds[2] = {-1, -1};
|
||||
if (::pipe2(pipeEnds, O_CLOEXEC) != 0) {
|
||||
throw EffectError(std::string("Could not start ffmpeg: ") + std::strerror(errno));
|
||||
}
|
||||
errors_ = std::tmpfile();
|
||||
if (errors_ != nullptr) ::fcntl(fileno(errors_), F_SETFD, FD_CLOEXEC);
|
||||
|
||||
posix_spawn_file_actions_t actions;
|
||||
posix_spawn_file_actions_init(&actions);
|
||||
posix_spawn_file_actions_adddup2(&actions, pipeEnds[0], STDIN_FILENO);
|
||||
if (errors_ != nullptr) posix_spawn_file_actions_adddup2(&actions, fileno(errors_), STDERR_FILENO);
|
||||
|
||||
std::vector<char*> argv;
|
||||
for (auto& arg : args) argv.push_back(arg.data());
|
||||
argv.push_back(nullptr);
|
||||
|
||||
pid_t child = -1;
|
||||
const int spawned = ::posix_spawnp(&child, "ffmpeg", &actions, nullptr, argv.data(), environ);
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
::close(pipeEnds[0]);
|
||||
if (spawned != 0) {
|
||||
::close(pipeEnds[1]);
|
||||
if (errors_ != nullptr) std::fclose(errors_);
|
||||
errors_ = nullptr;
|
||||
if (spawned == ENOENT) {
|
||||
throw EffectError("Writing a video needs ffmpeg, which is not installed or not on "
|
||||
"the PATH.");
|
||||
}
|
||||
throw EffectError(std::string("Could not start ffmpeg: ") + std::strerror(spawned));
|
||||
}
|
||||
child_ = child;
|
||||
input_ = pipeEnds[1];
|
||||
}
|
||||
|
||||
VideoWriter::~VideoWriter() {
|
||||
if (child_ > 0) cancel();
|
||||
if (errors_ != nullptr) std::fclose(errors_);
|
||||
}
|
||||
|
||||
void VideoWriter::write(const Image& frame) {
|
||||
if (input_ < 0) throw EffectError("The video has already been closed.");
|
||||
if (frame.width() != width_ || frame.height() != height_) {
|
||||
throw EffectError("Every frame of a video must be the same size.");
|
||||
}
|
||||
const std::uint8_t* data = frame.data();
|
||||
std::size_t left = frame.byteSize();
|
||||
while (left > 0) {
|
||||
const ssize_t written = ::write(input_, data, left);
|
||||
if (written < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
failed("ffmpeg stopped taking frames");
|
||||
}
|
||||
data += written;
|
||||
left -= static_cast<std::size_t>(written);
|
||||
}
|
||||
}
|
||||
|
||||
int VideoWriter::wait() {
|
||||
int status = 0;
|
||||
while (::waitpid(child_, &status, 0) < 0) {
|
||||
if (errno != EINTR) {
|
||||
status = -1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
child_ = -1;
|
||||
return status;
|
||||
}
|
||||
|
||||
void VideoWriter::finish() {
|
||||
if (child_ <= 0) return;
|
||||
::close(input_);
|
||||
input_ = -1;
|
||||
const int status = wait();
|
||||
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
|
||||
std::error_code ignored;
|
||||
std::filesystem::remove(path_, ignored);
|
||||
std::string message = "ffmpeg could not write the video";
|
||||
const std::string said = errorOutput();
|
||||
if (!said.empty()) message += ": " + said;
|
||||
throw EffectError(message);
|
||||
}
|
||||
}
|
||||
|
||||
void VideoWriter::cancel() {
|
||||
if (input_ >= 0) {
|
||||
::close(input_);
|
||||
input_ = -1;
|
||||
}
|
||||
if (child_ > 0) {
|
||||
// Not SIGTERM: ffmpeg takes that as "finish up", and flushing a slow
|
||||
// encoder can take many seconds for a file that is thrown away.
|
||||
::kill(child_, SIGKILL);
|
||||
wait();
|
||||
}
|
||||
std::error_code ignored;
|
||||
std::filesystem::remove(path_, ignored);
|
||||
}
|
||||
|
||||
void VideoWriter::failed(const std::string& what) {
|
||||
cancel();
|
||||
std::string message = what;
|
||||
const std::string said = errorOutput();
|
||||
if (!said.empty()) message += ": " + said;
|
||||
throw EffectError(message);
|
||||
}
|
||||
|
||||
// The last thing ffmpeg said, which is where it names the problem.
|
||||
std::string VideoWriter::errorOutput() const {
|
||||
if (errors_ == nullptr) return {};
|
||||
std::string text;
|
||||
std::rewind(errors_);
|
||||
char buffer[4096];
|
||||
std::size_t read = 0;
|
||||
while ((read = std::fread(buffer, 1, sizeof buffer, errors_)) > 0) text.append(buffer, read);
|
||||
while (!text.empty() && (text.back() == '\n' || text.back() == '\r' || text.back() == ' ')) {
|
||||
text.pop_back();
|
||||
}
|
||||
const auto lastLine = text.rfind('\n');
|
||||
if (lastLine != std::string::npos) text.erase(0, lastLine + 1);
|
||||
return text;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "core/image.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// The frame rates and lengths both front-ends accept. Five minutes at sixty
|
||||
// frames is 18000 frames -- already a long wait -- and a tenth of a second is
|
||||
// the shortest clip that still has a few frames in it.
|
||||
inline constexpr int kMinFps = 1;
|
||||
inline constexpr int kMaxFps = 60;
|
||||
inline constexpr int kDefaultFps = 30;
|
||||
inline constexpr double kMinDuration = 0.1;
|
||||
inline constexpr double kMaxDuration = 300.0;
|
||||
inline constexpr double kDefaultDuration = 10.0;
|
||||
|
||||
// Whether a project is a video, and how long and how fast. A still project
|
||||
// carries the other fields too, so switching video off and on again gives
|
||||
// the same clip back.
|
||||
struct VideoSettings {
|
||||
bool enabled = false;
|
||||
double duration = kDefaultDuration; // seconds
|
||||
int fps = kDefaultFps;
|
||||
// The preset the settings came from, empty for the user's own. Like a
|
||||
// canvas format it is the presentation of the numbers, never the truth:
|
||||
// the render goes by duration and fps.
|
||||
std::string preset;
|
||||
|
||||
// The frames the clip has: the length at the rate, never fewer than one.
|
||||
int frameCount() const;
|
||||
};
|
||||
|
||||
// A named kind of clip both front-ends offer: a canvas and a length that go
|
||||
// together, so "Instagram story" is one choice rather than three.
|
||||
struct VideoPreset {
|
||||
std::string key; // written in a project and given to --video-preset
|
||||
std::string label; // shown in the interface
|
||||
std::string canvasFormat; // a key of canvasFormats()
|
||||
double seconds = 0.0;
|
||||
int fps = kDefaultFps;
|
||||
};
|
||||
|
||||
// In the order they are offered.
|
||||
const std::vector<VideoPreset>& videoPresets();
|
||||
|
||||
// Null when the key names no preset -- an empty or unknown key is "custom".
|
||||
const VideoPreset* videoPresetByKey(const std::string& key);
|
||||
|
||||
// "1080 × 1920 px · 15 s", for the dropdown and for --help.
|
||||
std::string videoPresetDetail(const VideoPreset& preset);
|
||||
|
||||
// "15 s", "7.5 s": a length as the interface and --help show it.
|
||||
std::string formatSeconds(double seconds);
|
||||
|
||||
// Whether a file name asks for a video: .mp4, .mov, .mkv, .webm or .gif.
|
||||
bool isVideoPath(const std::string& path);
|
||||
|
||||
// Whether an `ffmpeg` the writer below can run is on the PATH.
|
||||
bool ffmpegAvailable();
|
||||
|
||||
// Encodes frames into a video file by piping them, raw, into the `ffmpeg`
|
||||
// program. Run as a plain argv rather than through a shell, so a file name is
|
||||
// never read as anything but a file name. The container and codec follow the
|
||||
// extension: H.264 for .mp4, .mov and .mkv, VP9 for .webm, a palette GIF for
|
||||
// .gif. The encoded bytes are ffmpeg's business; the frames going in are the
|
||||
// ones the seed decides.
|
||||
//
|
||||
// Throws EffectError when ffmpeg is missing, fails, or quits early, with what
|
||||
// it had to say. A writer that is neither finished nor cancelled cancels
|
||||
// itself on destruction, so a half-written file is never left behind.
|
||||
class VideoWriter {
|
||||
public:
|
||||
VideoWriter(const std::string& path, int width, int height, int fps);
|
||||
~VideoWriter();
|
||||
VideoWriter(const VideoWriter&) = delete;
|
||||
VideoWriter& operator=(const VideoWriter&) = delete;
|
||||
|
||||
// Every frame must be the size the writer was opened with.
|
||||
void write(const Image& frame);
|
||||
// Closes the stream, waits for ffmpeg and throws if it failed.
|
||||
void finish();
|
||||
// Stops ffmpeg and removes the unfinished file.
|
||||
void cancel();
|
||||
|
||||
private:
|
||||
void failed(const std::string& what); // cancels, then throws with ffmpeg's words
|
||||
std::string errorOutput() const;
|
||||
int wait();
|
||||
|
||||
std::string path_;
|
||||
int width_ = 0;
|
||||
int height_ = 0;
|
||||
pid_t child_ = -1;
|
||||
int input_ = -1; // the write end of ffmpeg's stdin
|
||||
std::FILE* errors_ = nullptr; // ffmpeg's stderr, read back on failure
|
||||
};
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,129 @@
|
||||
#include "effects/bitcrush.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <vector>
|
||||
|
||||
#include "core/parallel.hpp"
|
||||
#include "effects/sampling.hpp"
|
||||
#include "effects/source_fill.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
const std::vector<ParamSpec>& BitCrushEffect::params() const {
|
||||
static const std::vector<ParamSpec> specs = {
|
||||
ParamSpec::makeChoice("crush_op", "Operation", "mixed",
|
||||
{"mixed", "posterize", "xor", "bitrotate", "channel_swap"},
|
||||
"posterize drops the low bits, xor flips random low bits, "
|
||||
"bitrotate turns each byte's bits round, channel_swap shuffles "
|
||||
"red, green and blue; mixed picks one for every band."),
|
||||
ParamSpec::makeInt("crush_bits", "Bits", 3, 1, 7,
|
||||
"How many bits the operation reaches: dropped by posterize, flipped "
|
||||
"at most by xor, turned at most by bitrotate."),
|
||||
ParamSpec::makeDouble("crush_coverage", "Coverage", 0.5, 0.0, 1.0,
|
||||
"Chance of each band being crushed."),
|
||||
ParamSpec::makeInt("crush_band_height", "Band height", 32, 1, 4096,
|
||||
"Thickness in pixels of each band."),
|
||||
};
|
||||
return specs;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
enum class Op : std::uint8_t { None, Posterize, Xor, Rotate, Swap };
|
||||
|
||||
struct Band {
|
||||
Op op = Op::None;
|
||||
int rotate = 0;
|
||||
std::array<std::uint8_t, 3> mask{};
|
||||
std::array<int, 3> order{0, 1, 2};
|
||||
};
|
||||
|
||||
Op opNamed(const std::string& name) {
|
||||
if (name == "posterize") return Op::Posterize;
|
||||
if (name == "xor") return Op::Xor;
|
||||
if (name == "bitrotate") return Op::Rotate;
|
||||
if (name == "channel_swap") return Op::Swap;
|
||||
return Op::None; // mixed: drawn per band
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Image BitCrushEffect::render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const {
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
|
||||
const Op fixed = opNamed(paramChoice(values, "crush_op", "mixed"));
|
||||
const int bits = static_cast<int>(std::clamp(paramInt(values, "crush_bits", 3), 1L, 7L));
|
||||
const double coverage = std::clamp(paramDouble(values, "crush_coverage", 0.5), 0.0, 1.0);
|
||||
const int bandHeight = static_cast<int>(std::max(1L, paramInt(values, "crush_band_height", 32)));
|
||||
|
||||
Image canvas = canvasFromSources(sources, width, height, rng);
|
||||
|
||||
const int bandCount = (height + bandHeight - 1) / bandHeight;
|
||||
std::vector<Band> plan(static_cast<std::size_t>(bandCount));
|
||||
for (auto& band : plan) {
|
||||
if (!chance(rng.next(), coverage)) continue;
|
||||
band.op = fixed != Op::None ? fixed : static_cast<Op>(1 + rng.below(3));
|
||||
switch (band.op) {
|
||||
case Op::Xor:
|
||||
for (auto& mask : band.mask) {
|
||||
mask = static_cast<std::uint8_t>(rng.inRange(1, (1L << bits) - 1));
|
||||
}
|
||||
break;
|
||||
case Op::Rotate:
|
||||
band.rotate = static_cast<int>(rng.inRange(1, bits));
|
||||
break;
|
||||
case Op::Swap:
|
||||
// Fisher-Yates, never leaving the order as it was.
|
||||
do {
|
||||
band.order = {0, 1, 2};
|
||||
for (int i = 2; i > 0; --i) {
|
||||
std::swap(band.order[static_cast<std::size_t>(i)],
|
||||
band.order[rng.below(static_cast<std::uint64_t>(i))]);
|
||||
}
|
||||
} while (band.order[0] == 0 && band.order[1] == 1);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const std::uint8_t keep = static_cast<std::uint8_t>(0xFF << bits);
|
||||
|
||||
parallelFor(static_cast<std::size_t>(height), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t y = begin; y < end; ++y) {
|
||||
const Band& band = plan[y / static_cast<std::size_t>(bandHeight)];
|
||||
if (band.op == Op::None) continue;
|
||||
std::uint8_t* row = canvas.row(static_cast<int>(y));
|
||||
for (int x = 0; x < width; ++x) {
|
||||
std::uint8_t* px = row + static_cast<std::size_t>(x) * 3;
|
||||
switch (band.op) {
|
||||
case Op::Posterize:
|
||||
for (int c = 0; c < 3; ++c) px[c] &= keep;
|
||||
break;
|
||||
case Op::Xor:
|
||||
for (int c = 0; c < 3; ++c) px[c] ^= band.mask[static_cast<std::size_t>(c)];
|
||||
break;
|
||||
case Op::Rotate:
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
px[c] = static_cast<std::uint8_t>((px[c] << band.rotate) |
|
||||
(px[c] >> (8 - band.rotate)));
|
||||
}
|
||||
break;
|
||||
case Op::Swap: {
|
||||
const std::uint8_t in[3] = {px[0], px[1], px[2]};
|
||||
for (int c = 0; c < 3; ++c) px[c] = in[band.order[static_cast<std::size_t>(c)]];
|
||||
break;
|
||||
}
|
||||
case Op::None:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/effect.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// Mangles the bytes of its input band by band: posterising, xoring with a
|
||||
// random mask, rotating the bits or shuffling the channels.
|
||||
// A pure transform: it needs no source images, and leading a chain with
|
||||
// sources loaded it starts from a crop of a randomly chosen one.
|
||||
class BitCrushEffect : public Effect {
|
||||
public:
|
||||
std::string name() const override { return "bitcrush"; }
|
||||
std::string title() const override { return "Bit crush"; }
|
||||
std::string description() const override {
|
||||
return "Mangles the bytes of random bands: posterises them, xors them with a random "
|
||||
"mask, rotates their bits or shuffles their channels.";
|
||||
}
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
bool needsSources() const override { return false; }
|
||||
|
||||
Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const override;
|
||||
};
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,261 @@
|
||||
#include "effects/channelsplit.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
#include <vector>
|
||||
|
||||
#include "core/parallel.hpp"
|
||||
#include "effects/source_fill.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
const std::vector<ParamSpec>& ChannelSplitEffect::params() const {
|
||||
static const std::vector<ParamSpec> specs = {
|
||||
ParamSpec::makeInt("split_amount", "Amount", 12, 0, 1024,
|
||||
"Furthest in pixels a channel may be moved, along either axis."),
|
||||
ParamSpec::makeChoice("split_mode", "Mode", "global", {"global", "per_band"},
|
||||
"global moves each channel once over the whole image; per_band "
|
||||
"draws new offsets for every band."),
|
||||
ParamSpec::makeInt("split_band_height", "Band height", 24, 1, 2048,
|
||||
"Thickness in pixels of each band; per_band mode only."),
|
||||
ParamSpec::makeChoice("split_channels", "Channels", "rgb", {"rgb", "red_cyan", "random"},
|
||||
"rgb moves all three channels apart; red_cyan moves red one way and "
|
||||
"green and blue the other, as 3D glasses would; random moves one "
|
||||
"channel picked at random."),
|
||||
ParamSpec::makeInt("split_wobble", "Wobble", 4, 0, 256,
|
||||
"How far in pixels the channels sway back and forth over time.")
|
||||
.forVideo(),
|
||||
ParamSpec::makeDouble("split_wobble_speed", "Wobble speed", 0.5, 0.0, 10.0,
|
||||
"Sways per second, rounded so that the clip loops without a jump.",
|
||||
0.1, 1)
|
||||
.forVideo(),
|
||||
ParamSpec::makeInt("split_jitter", "Jitter", 2, 0, 256,
|
||||
"Furthest in pixels the channels shake, anew on every frame and, in "
|
||||
"per_band mode, for every band.")
|
||||
.forVideo(),
|
||||
ParamSpec::makeInt("split_roll", "Tracking bar", 16, 0, 512,
|
||||
"How far in pixels a bar rolling down the picture tears the rows "
|
||||
"sideways and the channels apart; 0 for none.")
|
||||
.forVideo(),
|
||||
ParamSpec::makeDouble("split_roll_time", "Bar pass", 4.0, 0.5, 60.0,
|
||||
"Seconds the tracking bar takes from top to bottom, rounded so "
|
||||
"that the clip loops without a jump.",
|
||||
0.5, 1)
|
||||
.forVideo(),
|
||||
};
|
||||
return specs;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct Offset {
|
||||
int dx = 0;
|
||||
int dy = 0;
|
||||
};
|
||||
|
||||
using ChannelOffsets = std::array<Offset, 3>;
|
||||
|
||||
ChannelOffsets drawOffsets(Rng& rng, int amount, const std::string& channels, int& moved) {
|
||||
ChannelOffsets offsets{};
|
||||
auto draw = [&] {
|
||||
return Offset{static_cast<int>(rng.inRange(-amount, amount)),
|
||||
static_cast<int>(rng.inRange(-amount, amount))};
|
||||
};
|
||||
moved = -1;
|
||||
if (channels == "red_cyan") {
|
||||
const Offset red = draw();
|
||||
offsets[0] = red;
|
||||
offsets[1] = offsets[2] = Offset{-red.dx, -red.dy};
|
||||
} else if (channels == "random") {
|
||||
moved = static_cast<int>(rng.below(2));
|
||||
offsets[static_cast<std::size_t>(moved)] = draw();
|
||||
} else {
|
||||
for (auto& offset : offsets) offset = draw();
|
||||
}
|
||||
return offsets;
|
||||
}
|
||||
|
||||
// A motion of each channel, handed out the way the mode moves channels: all
|
||||
// three on their own, green and blue opposite red, or only the one channel
|
||||
// that was picked -- so the motion never moves a channel the still left alone.
|
||||
using Motion = std::array<double, 3>;
|
||||
|
||||
Motion spread(const Motion& motion, const std::string& channels, int moved) {
|
||||
if (channels == "red_cyan") return {motion[0], -motion[0], -motion[0]};
|
||||
if (moved >= 0) {
|
||||
Motion only{};
|
||||
only[static_cast<std::size_t>(moved)] = motion[0];
|
||||
return only;
|
||||
}
|
||||
return motion;
|
||||
}
|
||||
|
||||
double unit(Rng& rng) { return static_cast<double>(rng.next() >> 11) * 0x1.0p-53; }
|
||||
|
||||
struct MotionSettings {
|
||||
int wobble = 0;
|
||||
double wobbleSpeed = 0.0;
|
||||
int jitter = 0;
|
||||
int roll = 0;
|
||||
double rollTime = 1.0;
|
||||
|
||||
explicit MotionSettings(const ParamValues& values)
|
||||
: wobble(static_cast<int>(std::max(0L, paramInt(values, "split_wobble", 4)))),
|
||||
wobbleSpeed(std::max(0.0, paramDouble(values, "split_wobble_speed", 0.5))),
|
||||
jitter(static_cast<int>(std::max(0L, paramInt(values, "split_jitter", 2)))),
|
||||
roll(static_cast<int>(std::max(0L, paramInt(values, "split_roll", 16)))),
|
||||
rollTime(std::max(0.5, paramDouble(values, "split_roll_time", 4.0))) {}
|
||||
|
||||
bool moves() const { return (wobble > 0 && wobbleSpeed > 0.0) || jitter > 0 || roll > 0; }
|
||||
};
|
||||
|
||||
// Rounds a rate so a whole number of cycles fits the clip, never fewer than
|
||||
// one: the last frame then leads straight back into the first.
|
||||
double loopRate(double perSecond, double clipSeconds) {
|
||||
return std::max(1.0, std::round(perSecond * clipSeconds)) / clipSeconds;
|
||||
}
|
||||
|
||||
Image renderSplit(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values, const FrameTime& frame) {
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
|
||||
const int amount = static_cast<int>(std::max(0L, paramInt(values, "split_amount", 12)));
|
||||
const bool perBand = paramChoice(values, "split_mode", "global") == "per_band";
|
||||
const int bandHeight = static_cast<int>(std::max(1L, paramInt(values, "split_band_height", 24)));
|
||||
const std::string channels = paramChoice(values, "split_channels", "rgb");
|
||||
|
||||
const Image input = canvasFromSources(sources, width, height, rng);
|
||||
|
||||
// One set of offsets per band, a single band covering everything in global
|
||||
// mode; all of them drawn before the pixels are touched.
|
||||
const int band = perBand ? bandHeight : height;
|
||||
const int bandCount = (height + band - 1) / band;
|
||||
std::vector<ChannelOffsets> plan;
|
||||
std::vector<int> moved;
|
||||
plan.reserve(static_cast<std::size_t>(bandCount));
|
||||
moved.reserve(static_cast<std::size_t>(bandCount));
|
||||
for (int i = 0; i < bandCount; ++i) {
|
||||
int only = -1;
|
||||
plan.push_back(drawOffsets(rng, amount, channels, only));
|
||||
moved.push_back(only);
|
||||
}
|
||||
|
||||
// Every row's offsets, and a sideways shift of the whole row. A still is
|
||||
// just the band plan; a frame of a video adds the motion to it.
|
||||
std::vector<ChannelOffsets> rows(static_cast<std::size_t>(height));
|
||||
std::vector<int> shift(static_cast<std::size_t>(height), 0);
|
||||
for (int y = 0; y < height; ++y) rows[static_cast<std::size_t>(y)] = plan[static_cast<std::size_t>(y / band)];
|
||||
|
||||
const MotionSettings motion(values);
|
||||
if (frame.video() && motion.moves()) {
|
||||
// The same draws on every frame, after the still's: where each
|
||||
// channel starts its sway and which way it sways. The shake is the
|
||||
// one thing that differs between frames, so it comes from a generator
|
||||
// of the frame's own, seeded by one more draw -- the shared rng leaves
|
||||
// every frame in the same state, and the stages after this one hold
|
||||
// still while it moves.
|
||||
std::array<double, 3> phase{};
|
||||
std::array<double, 3> angle{};
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
phase[static_cast<std::size_t>(c)] = unit(rng) * 2.0 * std::numbers::pi;
|
||||
angle[static_cast<std::size_t>(c)] = unit(rng) * 2.0 * std::numbers::pi;
|
||||
}
|
||||
Rng shake(rng.next() ^ (0x9e3779b97f4a7c15ULL * static_cast<std::uint64_t>(frame.index + 1)));
|
||||
|
||||
const double clip = static_cast<double>(std::max(1, frame.count)) / frame.fps;
|
||||
const double t = frame.seconds();
|
||||
|
||||
Motion swayX{};
|
||||
Motion swayY{};
|
||||
if (motion.wobble > 0 && motion.wobbleSpeed > 0.0) {
|
||||
const double rate = loopRate(motion.wobbleSpeed, clip);
|
||||
for (std::size_t c = 0; c < 3; ++c) {
|
||||
const double sway = motion.wobble * std::sin(2.0 * std::numbers::pi * rate * t + phase[c]);
|
||||
swayX[c] = sway * std::cos(angle[c]);
|
||||
swayY[c] = sway * std::sin(angle[c]);
|
||||
}
|
||||
}
|
||||
|
||||
// The tracking bar: an eighth of the picture, soft at both edges,
|
||||
// entering above the top and leaving below the bottom.
|
||||
const double barHeight = std::max(8.0, height / 8.0);
|
||||
const double passes = loopRate(1.0 / motion.rollTime, clip);
|
||||
const double along = std::fmod(t * passes, 1.0);
|
||||
const double barTop = -barHeight + along * (height + barHeight);
|
||||
|
||||
for (int b = 0; b < bandCount; ++b) {
|
||||
Motion jitterX{};
|
||||
Motion jitterY{};
|
||||
if (motion.jitter > 0) {
|
||||
for (std::size_t c = 0; c < 3; ++c) {
|
||||
jitterX[c] = static_cast<double>(shake.inRange(-motion.jitter, motion.jitter));
|
||||
// Mostly sideways, as a picture losing its horizontal hold.
|
||||
jitterY[c] = static_cast<double>(shake.inRange(-motion.jitter, motion.jitter)) / 3.0;
|
||||
}
|
||||
}
|
||||
const int only = moved[static_cast<std::size_t>(b)];
|
||||
const Motion dx = spread({swayX[0] + jitterX[0], swayX[1] + jitterX[1], swayX[2] + jitterX[2]},
|
||||
channels, only);
|
||||
const Motion dy = spread({swayY[0] + jitterY[0], swayY[1] + jitterY[1], swayY[2] + jitterY[2]},
|
||||
channels, only);
|
||||
// The bar pulls red one way and blue the other (or the moved
|
||||
// channel alone), whatever the sway is doing.
|
||||
const Motion apart = spread({1.0, 0.0, -1.0}, channels, only);
|
||||
|
||||
const int end = std::min(height, (b + 1) * band);
|
||||
for (int y = b * band; y < end; ++y) {
|
||||
double bar = 0.0;
|
||||
if (motion.roll > 0 && y >= barTop && y < barTop + barHeight) {
|
||||
bar = motion.roll * std::sin(std::numbers::pi * (y - barTop) / barHeight);
|
||||
}
|
||||
auto& offsets = rows[static_cast<std::size_t>(y)];
|
||||
for (std::size_t c = 0; c < 3; ++c) {
|
||||
offsets[c].dx += static_cast<int>(std::lround(dx[c] + bar * apart[c]));
|
||||
offsets[c].dy += static_cast<int>(std::lround(dy[c]));
|
||||
}
|
||||
shift[static_cast<std::size_t>(y)] = static_cast<int>(std::lround(bar / 2.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Image canvas(width, height);
|
||||
parallelFor(static_cast<std::size_t>(height), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t y = begin; y < end; ++y) {
|
||||
const ChannelOffsets& offsets = rows[y];
|
||||
std::uint8_t* out = canvas.row(static_cast<int>(y));
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const Offset& offset = offsets[static_cast<std::size_t>(c)];
|
||||
const int dx = offset.dx + shift[y];
|
||||
const int sy = std::clamp(static_cast<int>(y) - offset.dy, 0, height - 1);
|
||||
const std::uint8_t* in = input.row(sy);
|
||||
for (int x = 0; x < width; ++x) {
|
||||
const int sx = std::clamp(x - dx, 0, width - 1);
|
||||
out[static_cast<std::size_t>(x) * 3 + c] = in[static_cast<std::size_t>(sx) * 3 + c];
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ChannelSplitEffect::animated(const ParamValues& values) const {
|
||||
return MotionSettings(values).moves();
|
||||
}
|
||||
|
||||
Image ChannelSplitEffect::render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const {
|
||||
return renderSplit(sources, width, height, rng, values, FrameTime{});
|
||||
}
|
||||
|
||||
Image ChannelSplitEffect::renderFrame(const std::vector<Image>& sources, int width, int height,
|
||||
Rng& rng, const ParamValues& values,
|
||||
const FrameTime& frame) const {
|
||||
return renderSplit(sources, width, height, rng, values, frame);
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/effect.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// Knocks the red, green and blue planes out of register, either the whole image
|
||||
// at once or band by band, each band with offsets of its own.
|
||||
// In a video the channels do not sit still: they sway, shake from frame to
|
||||
// frame, and a tracking bar rolls down the picture as on a worn tape or an old
|
||||
// tube. A still picture is rendered exactly as it always was.
|
||||
// A pure transform: it needs no source images, and leading a chain with
|
||||
// sources loaded it starts from a crop of a randomly chosen one.
|
||||
class ChannelSplitEffect : public Effect {
|
||||
public:
|
||||
std::string name() const override { return "channelsplit"; }
|
||||
std::string title() const override { return "Channel split"; }
|
||||
std::string description() const override {
|
||||
return "Knocks the red, green and blue planes out of register, over the whole image or "
|
||||
"band by band.";
|
||||
}
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
bool needsSources() const override { return false; }
|
||||
bool animated(const ParamValues& values) const override;
|
||||
|
||||
Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const override;
|
||||
Image renderFrame(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values, const FrameTime& frame) const override;
|
||||
};
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,143 @@
|
||||
#include "effects/corrupt.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "core/parallel.hpp"
|
||||
#include "effects/sampling.hpp"
|
||||
#include "effects/source_fill.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
const std::vector<ParamSpec>& CorruptEffect::params() const {
|
||||
static const std::vector<ParamSpec> specs = {
|
||||
ParamSpec::makeInt("corrupt_block", "Block size", 16, 2, 256,
|
||||
"Width and height in pixels of one block, as a codec would cut them."),
|
||||
ParamSpec::makeDouble("corrupt_rate", "Rate", 0.08, 0.0, 1.0,
|
||||
"Chance of each block being damaged."),
|
||||
ParamSpec::makeChoice("corrupt_kinds", "Damage", "mixed",
|
||||
{"mixed", "repeat", "displace", "colour"},
|
||||
"repeat freezes a block into a copy of the one to its left, "
|
||||
"displace pulls one in from elsewhere in the image, colour knocks "
|
||||
"it off colour; mixed picks one of them for every block."),
|
||||
ParamSpec::makeBool("corrupt_bleed", "Bleed", false,
|
||||
"Carry each damaged block's fault on to the end of its row, the way "
|
||||
"one broken bit spoils the rest of a stream."),
|
||||
};
|
||||
return specs;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
enum class Damage : std::uint8_t { None, Repeat, Displace, Colour };
|
||||
|
||||
struct Block {
|
||||
Damage damage = Damage::None;
|
||||
int sx = 0; // displace: where the block is read from
|
||||
int sy = 0;
|
||||
int shift[3] = {0, 0, 0}; // colour: added to each channel
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
Image CorruptEffect::render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const {
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
|
||||
const int size = static_cast<int>(std::max(2L, paramInt(values, "corrupt_block", 16)));
|
||||
const double rate = std::clamp(paramDouble(values, "corrupt_rate", 0.08), 0.0, 1.0);
|
||||
const std::string kinds = paramChoice(values, "corrupt_kinds", "mixed");
|
||||
const bool bleed = paramBool(values, "corrupt_bleed", false);
|
||||
|
||||
const Image input = canvasFromSources(sources, width, height, rng);
|
||||
|
||||
const int cols = (width + size - 1) / size;
|
||||
const int rows = (height + size - 1) / size;
|
||||
|
||||
auto drawBlock = [&](int bx) {
|
||||
Block block;
|
||||
if (kinds == "repeat") block.damage = Damage::Repeat;
|
||||
else if (kinds == "displace") block.damage = Damage::Displace;
|
||||
else if (kinds == "colour") block.damage = Damage::Colour;
|
||||
else block.damage = static_cast<Damage>(1 + rng.below(2));
|
||||
// The first block of a row has nothing to its left to repeat.
|
||||
if (block.damage == Damage::Repeat && bx == 0) block.damage = Damage::Displace;
|
||||
if (block.damage == Damage::Displace) {
|
||||
block.sx = static_cast<int>(rng.inRange(0, std::max(0, width - size)));
|
||||
block.sy = static_cast<int>(rng.inRange(0, std::max(0, height - size)));
|
||||
} else if (block.damage == Damage::Colour) {
|
||||
for (int& shift : block.shift) shift = static_cast<int>(rng.inRange(-128, 128));
|
||||
}
|
||||
return block;
|
||||
};
|
||||
|
||||
// The whole damage map is drawn up front, block by block in reading order.
|
||||
std::vector<Block> plan(static_cast<std::size_t>(cols) * rows);
|
||||
for (int by = 0; by < rows; ++by) {
|
||||
const Block* carried = nullptr;
|
||||
for (int bx = 0; bx < cols; ++bx) {
|
||||
Block& block = plan[static_cast<std::size_t>(by) * cols + bx];
|
||||
if (carried != nullptr) {
|
||||
block = *carried;
|
||||
// A displaced run keeps moving along with the row, so the
|
||||
// stretch reads as one shifted strip rather than one block
|
||||
// over and over.
|
||||
if (block.damage == Damage::Displace) block.sx += size;
|
||||
carried = █
|
||||
continue;
|
||||
}
|
||||
if (!chance(rng.next(), rate)) continue;
|
||||
block = drawBlock(bx);
|
||||
if (bleed) carried = █
|
||||
}
|
||||
}
|
||||
|
||||
Image canvas = input;
|
||||
// Block rows are independent (a repeat only ever reads to its left), so
|
||||
// they run in parallel and each walks its row in order.
|
||||
parallelFor(static_cast<std::size_t>(rows), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t by = begin; by < end; ++by) {
|
||||
const int y0 = static_cast<int>(by) * size;
|
||||
const int h = std::min(size, height - y0);
|
||||
for (int bx = 0; bx < cols; ++bx) {
|
||||
const Block& block = plan[by * static_cast<std::size_t>(cols) + bx];
|
||||
if (block.damage == Damage::None) continue;
|
||||
const int x0 = bx * size;
|
||||
const int w = std::min(size, width - x0);
|
||||
const std::size_t bytes = static_cast<std::size_t>(w) * 3;
|
||||
|
||||
for (int line = 0; line < h; ++line) {
|
||||
std::uint8_t* out = canvas.row(y0 + line) + static_cast<std::size_t>(x0) * 3;
|
||||
switch (block.damage) {
|
||||
case Damage::Repeat:
|
||||
std::memmove(out, out - static_cast<std::size_t>(size) * 3, bytes);
|
||||
break;
|
||||
case Damage::Displace: {
|
||||
const int sy = std::min(block.sy + line, height - 1);
|
||||
const std::uint8_t* in = input.row(sy);
|
||||
for (int x = 0; x < w; ++x) {
|
||||
const int sx = (block.sx + x) % width;
|
||||
std::memcpy(out + static_cast<std::size_t>(x) * 3,
|
||||
in + static_cast<std::size_t>(sx) * 3, 3);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Damage::Colour:
|
||||
for (std::size_t i = 0; i < bytes; ++i) {
|
||||
out[i] = static_cast<std::uint8_t>(
|
||||
std::clamp(out[i] + block.shift[i % 3], 0, 255));
|
||||
}
|
||||
break;
|
||||
case Damage::None:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/effect.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// Imitates a damaged video stream: blocks of the image are frozen into a copy of
|
||||
// their neighbour, pulled in from elsewhere or knocked off colour, and with
|
||||
// bleeding switched on the damage runs on to the end of the row.
|
||||
// A pure transform: it needs no source images, and leading a chain with
|
||||
// sources loaded it starts from a crop of a randomly chosen one.
|
||||
class CorruptEffect : public Effect {
|
||||
public:
|
||||
std::string name() const override { return "corrupt"; }
|
||||
std::string title() const override { return "Corruption"; }
|
||||
std::string description() const override {
|
||||
return "Imitates a damaged video stream: random blocks are smeared, displaced or knocked "
|
||||
"off colour, optionally bleeding on to the end of their row.";
|
||||
}
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
bool needsSources() const override { return false; }
|
||||
|
||||
Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const override;
|
||||
};
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,103 @@
|
||||
#include "effects/feedback.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#include "core/parallel.hpp"
|
||||
#include "effects/sampling.hpp"
|
||||
#include "effects/source_fill.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
const std::vector<ParamSpec>& FeedbackEffect::params() const {
|
||||
static const std::vector<ParamSpec> specs = {
|
||||
ParamSpec::makeInt("echo_count", "Echoes", 6, 1, 64,
|
||||
"How many times the image is laid back over itself."),
|
||||
ParamSpec::makeDouble("echo_scale", "Scale", 0.85, 0.1, 2.0,
|
||||
"Size of each echo against the one before; below 1 the echoes "
|
||||
"tunnel inwards, above 1 they burst outwards.",
|
||||
0.01),
|
||||
ParamSpec::makeDouble("echo_rotate", "Rotation", 4.0, -180.0, 180.0,
|
||||
"Turn in degrees of each echo against the one before.", 0.5, 1),
|
||||
ParamSpec::makeInt("echo_drift", "Drift", 20, 0, 4096,
|
||||
"Furthest in pixels each echo may wander off centre, either way."),
|
||||
ParamSpec::makeDouble("echo_fade", "Opacity", 0.8, 0.0, 1.0,
|
||||
"How strongly each echo covers what lies beneath it."),
|
||||
};
|
||||
return specs;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct Echo {
|
||||
double dx = 0.0;
|
||||
double dy = 0.0;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
Image FeedbackEffect::render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const {
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
|
||||
const long count = std::clamp(paramInt(values, "echo_count", 6), 1L, 64L);
|
||||
const double scale = std::clamp(paramDouble(values, "echo_scale", 0.85), 0.1, 2.0);
|
||||
const double rotate = std::clamp(paramDouble(values, "echo_rotate", 4.0), -180.0, 180.0);
|
||||
const int drift = static_cast<int>(std::max(0L, paramInt(values, "echo_drift", 20)));
|
||||
const double fade = std::clamp(paramDouble(values, "echo_fade", 0.8), 0.0, 1.0);
|
||||
|
||||
const Image input = canvasFromSources(sources, width, height, rng);
|
||||
|
||||
std::vector<Echo> echoes(static_cast<std::size_t>(count));
|
||||
for (auto& echo : echoes) {
|
||||
echo.dx = static_cast<double>(rng.inRange(-drift, drift));
|
||||
echo.dy = static_cast<double>(rng.inRange(-drift, drift));
|
||||
}
|
||||
|
||||
double sine = 0.0;
|
||||
double cosine = 1.0;
|
||||
sinCosDegrees(rotate, sine, cosine);
|
||||
const double cx = (width - 1) * 0.5;
|
||||
const double cy = (height - 1) * 0.5;
|
||||
const int mix = static_cast<int>(fade * 256.0 + 0.5);
|
||||
|
||||
// A camera filming its own monitor: every pass lays the whole picture so
|
||||
// far, shrunk (or grown), turned and drifted, over the untouched input, so
|
||||
// the older echoes nest inside the newer ones and fade as they go.
|
||||
Image frame = input;
|
||||
Image next(width, height);
|
||||
for (const Echo& echo : echoes) {
|
||||
parallelFor(static_cast<std::size_t>(height), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t row = begin; row < end; ++row) {
|
||||
const std::uint8_t* base = input.row(static_cast<int>(row));
|
||||
std::uint8_t* out = next.row(static_cast<int>(row));
|
||||
const double ry = static_cast<double>(row) - cy - echo.dy;
|
||||
for (int col = 0; col < width; ++col) {
|
||||
const std::size_t at = static_cast<std::size_t>(col) * 3;
|
||||
const double rx = col - cx - echo.dx;
|
||||
const double sx = cx + (rx * cosine + ry * sine) / scale;
|
||||
const double sy = cy + (-rx * sine + ry * cosine) / scale;
|
||||
if (sx < 0.0 || sy < 0.0 || sx > width - 1 || sy > height - 1) {
|
||||
out[at] = base[at];
|
||||
out[at + 1] = base[at + 1];
|
||||
out[at + 2] = base[at + 2];
|
||||
continue;
|
||||
}
|
||||
std::uint8_t echoed[3];
|
||||
sampleBilinear(frame, sx, sy, echoed);
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const int under = base[at + static_cast<std::size_t>(c)];
|
||||
out[at + static_cast<std::size_t>(c)] =
|
||||
static_cast<std::uint8_t>(under + (echoed[c] - under) * mix / 256);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
std::swap(frame, next);
|
||||
}
|
||||
|
||||
return frame;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/effect.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// Lays the image over itself again and again, each copy zoomed, turned and
|
||||
// drifted a little further and fading as it goes, like a camera filming its
|
||||
// own monitor.
|
||||
// A pure transform: it needs no source images, and leading a chain with
|
||||
// sources loaded it starts from a crop of a randomly chosen one.
|
||||
class FeedbackEffect : public Effect {
|
||||
public:
|
||||
std::string name() const override { return "feedback"; }
|
||||
std::string title() const override { return "Feedback"; }
|
||||
std::string description() const override {
|
||||
return "Lays the image over itself again and again, each copy zoomed, turned and drifted "
|
||||
"further and fading, like a camera filming its own monitor.";
|
||||
}
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
bool needsSources() const override { return false; }
|
||||
|
||||
Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const override;
|
||||
};
|
||||
|
||||
} // namespace effector
|
||||
+151
-2
@@ -32,6 +32,28 @@ const std::vector<ParamSpec>& OverlayEffect::params() const {
|
||||
ParamSpec::makeDouble("overlay_opacity", "Opacity", 1.0, 0.0, 1.0,
|
||||
"How strongly the image is mixed over the input; its own "
|
||||
"transparency is taken into account as well."),
|
||||
ParamSpec::makeChoice("overlay_halo", "Halo", "none", {"none", "shadow", "glow"},
|
||||
"Draws a soft copy of the image's outline beneath it: a shadow, "
|
||||
"moved by the shadow offset, or a glow all around it."),
|
||||
ParamSpec::makeColor("overlay_shadow_color", "Shadow colour", "#000000",
|
||||
"The colour of the shadow."),
|
||||
ParamSpec::makeColor("overlay_glow_color", "Glow colour", "#ffffff",
|
||||
"The colour of the glow."),
|
||||
ParamSpec::makeInt("overlay_halo_size", "Halo size", 12, 0, 500,
|
||||
"How far the shadow or glow fades out, in pixels; 0 gives a hard "
|
||||
"edge."),
|
||||
ParamSpec::makeDouble("overlay_halo_spread", "Halo spread", 0.0, 0.0, 0.9,
|
||||
"Pushes the full strength of the shadow or glow out from the "
|
||||
"image's edge before it starts to fade; a glow usually wants some."),
|
||||
ParamSpec::makeDouble("overlay_halo_opacity", "Halo opacity", 0.75, 0.0, 1.0,
|
||||
"How strongly the shadow or glow is drawn, on top of the image's "
|
||||
"own opacity."),
|
||||
ParamSpec::makeInt("overlay_shadow_x", "Shadow X", 8, -2000, 2000,
|
||||
"Moves the shadow right by this many pixels (left when negative); "
|
||||
"a glow stays centred."),
|
||||
ParamSpec::makeInt("overlay_shadow_y", "Shadow Y", 8, -2000, 2000,
|
||||
"Moves the shadow down by this many pixels (up when negative); a "
|
||||
"glow stays centred."),
|
||||
};
|
||||
return specs;
|
||||
}
|
||||
@@ -123,6 +145,44 @@ void sampleOverlay(const Image& src, const std::uint8_t* alpha, double u, double
|
||||
}
|
||||
}
|
||||
|
||||
// One box blur pass over a line of the halo mask. Unlike the blur effect's the
|
||||
// window counts zero beyond both ends, so the halo fades out at the edge of
|
||||
// the mask instead of smearing its last value outwards. Integers throughout,
|
||||
// so a seed reproduces the halo byte for byte on any machine.
|
||||
void maskPass(const std::int32_t* in, std::int32_t* out, int count, std::size_t stride,
|
||||
int radius) {
|
||||
const int window = 2 * radius + 1;
|
||||
std::int32_t sum = 0;
|
||||
for (int i = 0; i <= radius && i < count; ++i) sum += in[static_cast<std::size_t>(i) * stride];
|
||||
for (int i = 0; i < count; ++i) {
|
||||
out[static_cast<std::size_t>(i) * stride] = (sum + window / 2) / window;
|
||||
if (i + radius + 1 < count) sum += in[static_cast<std::size_t>(i + radius + 1) * stride];
|
||||
if (i - radius >= 0) sum -= in[static_cast<std::size_t>(i - radius) * stride];
|
||||
}
|
||||
}
|
||||
|
||||
// Three box passes each way, which is close enough to a gaussian: `size` is
|
||||
// roughly how far the result reaches past the edge of what was covered.
|
||||
void blurMask(std::vector<std::int32_t>& mask, int width, int height, int size) {
|
||||
if (size <= 0) return;
|
||||
const int radius = std::max(1, (size + 2) / 3);
|
||||
std::vector<std::int32_t> scratch(mask.size());
|
||||
for (int pass = 0; pass < 3; ++pass) {
|
||||
parallelFor(static_cast<std::size_t>(height), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t y = begin; y < end; ++y) {
|
||||
const std::size_t offset = y * static_cast<std::size_t>(width);
|
||||
maskPass(mask.data() + offset, scratch.data() + offset, width, 1, radius);
|
||||
}
|
||||
});
|
||||
parallelFor(static_cast<std::size_t>(width), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t x = begin; x < end; ++x) {
|
||||
maskPass(scratch.data() + x, mask.data() + x, height,
|
||||
static_cast<std::size_t>(width), radius);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void OverlayEffect::loadOverlay(const std::string& path, Image& image,
|
||||
@@ -187,11 +247,100 @@ Image OverlayEffect::render(const std::vector<Image>& sources, int width, int he
|
||||
const int lastRow = tiling ? height : std::min(height, place.y + place.height);
|
||||
const int firstCol = tiling ? 0 : std::max(0, place.x);
|
||||
const int lastCol = tiling ? width : std::min(width, place.x + place.width);
|
||||
if (firstRow >= lastRow || firstCol >= lastCol) return canvas; // entirely off the canvas
|
||||
|
||||
const int mix = static_cast<int>(opacity * 255.0 + 0.5);
|
||||
const std::uint8_t* alphaData = alpha.data();
|
||||
|
||||
// The halo goes down first, so that the image covers it wherever it is
|
||||
// opaque and shows it through wherever it is not.
|
||||
const std::string halo = paramChoice(values, "overlay_halo", "none");
|
||||
const double haloOpacity =
|
||||
std::clamp(paramDouble(values, "overlay_halo_opacity", 0.75), 0.0, 1.0);
|
||||
if ((halo == "shadow" || halo == "glow") && haloOpacity > 0.0) {
|
||||
const bool shadow = halo == "shadow";
|
||||
const int size =
|
||||
static_cast<int>(std::clamp<long>(paramInt(values, "overlay_halo_size", 12), 0, 500));
|
||||
const int reach = 3 * std::max(1, (size + 2) / 3);
|
||||
const int shiftX = shadow ? static_cast<int>(paramInt(values, "overlay_shadow_x", 8)) : 0;
|
||||
const int shiftY = shadow ? static_cast<int>(paramInt(values, "overlay_shadow_y", 8)) : 0;
|
||||
std::uint8_t colour[3];
|
||||
paramColor(values, shadow ? "overlay_shadow_color" : "overlay_glow_color",
|
||||
shadow ? "#000000" : "#ffffff", colour);
|
||||
|
||||
// The mask covers the canvas as the shadow sees it (moved back by the
|
||||
// offset) plus the blur's reach, so that parts of the image lying off
|
||||
// the canvas still cast onto it. Outside the image nothing is covered,
|
||||
// so the mask is cut down to the image plus that reach as well.
|
||||
int left = -shiftX - reach;
|
||||
int top = -shiftY - reach;
|
||||
int right = width - shiftX + reach;
|
||||
int bottom = height - shiftY + reach;
|
||||
if (!tiling) {
|
||||
left = std::max(left, place.x - reach);
|
||||
top = std::max(top, place.y - reach);
|
||||
right = std::min(right, place.x + place.width + reach);
|
||||
bottom = std::min(bottom, place.y + place.height + reach);
|
||||
}
|
||||
if (left < right && top < bottom) {
|
||||
const int maskWidth = right - left;
|
||||
const int maskHeight = bottom - top;
|
||||
std::vector<std::int32_t> mask(static_cast<std::size_t>(maskWidth) * maskHeight, 0);
|
||||
parallelFor(static_cast<std::size_t>(maskHeight), [&](std::size_t begin,
|
||||
std::size_t end) {
|
||||
int rgb[3];
|
||||
int pixelAlpha = 255;
|
||||
for (std::size_t i = begin; i < end; ++i) {
|
||||
const int y = top + static_cast<int>(i);
|
||||
if (!tiling && (y < place.y || y >= place.y + place.height)) continue;
|
||||
const double v = (y - place.y + 0.5) * stepY - 0.5;
|
||||
std::int32_t* out = mask.data() + i * static_cast<std::size_t>(maskWidth);
|
||||
for (int x = left; x < right; ++x) {
|
||||
if (!tiling && (x < place.x || x >= place.x + place.width)) continue;
|
||||
const double u = (x - place.x + 0.5) * stepX - 0.5;
|
||||
sampleOverlay(overlay, alphaData, u, v, tiling, rgb, pixelAlpha);
|
||||
out[x - left] = pixelAlpha;
|
||||
}
|
||||
}
|
||||
});
|
||||
blurMask(mask, maskWidth, maskHeight, size);
|
||||
|
||||
const int haloMix = static_cast<int>(haloOpacity * mix + 0.5);
|
||||
// Spread amplifies the blurred mask, so the part near the edge
|
||||
// saturates and only the outer rim still fades.
|
||||
const double spread =
|
||||
std::clamp(paramDouble(values, "overlay_halo_spread", 0.0), 0.0, 0.9);
|
||||
const std::int32_t gain = static_cast<std::int32_t>(256.0 / (1.0 - spread) + 0.5);
|
||||
const int fromRow = std::max(0, top + shiftY);
|
||||
const int toRow = std::min(height, bottom + shiftY);
|
||||
const int fromCol = std::max(0, left + shiftX);
|
||||
const int toCol = std::min(width, right + shiftX);
|
||||
if (fromRow < toRow && fromCol < toCol) {
|
||||
parallelFor(static_cast<std::size_t>(toRow - fromRow), [&](std::size_t begin,
|
||||
std::size_t end) {
|
||||
for (std::size_t i = begin; i < end; ++i) {
|
||||
const int y = fromRow + static_cast<int>(i);
|
||||
const std::int32_t* in =
|
||||
mask.data() + static_cast<std::size_t>(y - shiftY - top) * maskWidth;
|
||||
std::uint8_t* out = canvas.row(y);
|
||||
for (int x = fromCol; x < toCol; ++x) {
|
||||
const int weight =
|
||||
std::clamp<int>(in[x - shiftX - left] * gain / 256, 0, 255) *
|
||||
haloMix / 255;
|
||||
if (weight == 0) continue;
|
||||
std::uint8_t* px = out + static_cast<std::size_t>(x) * 3;
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
px[c] = static_cast<std::uint8_t>(
|
||||
px[c] + (colour[c] - px[c]) * weight / 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A shadow can reach the canvas from an image lying wholly beside it.
|
||||
if (firstRow >= lastRow || firstCol >= lastCol) return canvas;
|
||||
|
||||
parallelFor(static_cast<std::size_t>(lastRow - firstRow), [&](std::size_t begin,
|
||||
std::size_t end) {
|
||||
int rgb[3];
|
||||
|
||||
@@ -11,7 +11,8 @@ namespace effector {
|
||||
|
||||
// Lays one picture from disk over its input: a logo, a texture, a frame. The
|
||||
// overlay is fitted to the canvas in the chosen way, placed from the top left
|
||||
// or from the centre, nudged by an offset and mixed in by its opacity. Like the
|
||||
// or from the centre, nudged by an offset and mixed in by its opacity, with a
|
||||
// soft shadow or glow cut from its own outline beneath it if asked. Like the
|
||||
// blur it needs no source images of its own, so it can lead a chain; given
|
||||
// sources it fills the canvas from a randomly chosen one first.
|
||||
class OverlayEffect : public Effect {
|
||||
@@ -20,7 +21,8 @@ public:
|
||||
std::string title() const override { return "Image overlay"; }
|
||||
std::string description() const override {
|
||||
return "Lays a single image from disk over its input, fitted to the canvas, centred or "
|
||||
"not, nudged by an offset and mixed in by its opacity.";
|
||||
"not, nudged by an offset and mixed in by its opacity, optionally with a shadow or "
|
||||
"a glow around it.";
|
||||
}
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
bool needsSources() const override { return false; }
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
#include "effects/pixelsort.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "core/parallel.hpp"
|
||||
#include "effects/sampling.hpp"
|
||||
#include "effects/source_fill.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
const std::vector<ParamSpec>& PixelSortEffect::params() const {
|
||||
static const std::vector<ParamSpec> specs = {
|
||||
ParamSpec::makeDouble("sort_low", "Lower threshold", 0.25, 0.0, 1.0,
|
||||
"Pixels darker than this break a run and stay where they are."),
|
||||
ParamSpec::makeDouble("sort_high", "Upper threshold", 0.8, 0.0, 1.0,
|
||||
"Pixels brighter than this break a run and stay where they are."),
|
||||
ParamSpec::makeChoice("sort_key", "Sort by", "luma", {"luma", "hue", "saturation"},
|
||||
"What orders the pixels inside a run."),
|
||||
ParamSpec::makeChoice("sort_direction", "Direction", "horizontal",
|
||||
{"horizontal", "vertical"}, "Whether rows or columns are sorted."),
|
||||
ParamSpec::makeBool("sort_reverse", "Reverse", false,
|
||||
"Sort from high to low instead of from low to high."),
|
||||
ParamSpec::makeDouble("sort_line_chance", "Line chance", 1.0, 0.0, 1.0,
|
||||
"Chance of each row (or column) being sorted at all."),
|
||||
ParamSpec::makeInt("sort_max_run", "Longest run", 0, 0, 8192,
|
||||
"Each run is cut after a random length up to this many pixels, which "
|
||||
"frays the edges of the sorted streaks (0 = no limit)."),
|
||||
};
|
||||
return specs;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
int luma(const std::uint8_t* px) { return (px[0] * 54 + px[1] * 183 + px[2] * 19) >> 8; }
|
||||
|
||||
// Hue on a 0..1535 scale (six sectors of 256), in integers.
|
||||
int hue(const std::uint8_t* px) {
|
||||
const int r = px[0], g = px[1], b = px[2];
|
||||
const int hi = std::max({r, g, b});
|
||||
const int lo = std::min({r, g, b});
|
||||
const int range = hi - lo;
|
||||
if (range == 0) return 0;
|
||||
if (hi == r) return g >= b ? (g - b) * 255 / range : 1535 - (b - g) * 255 / range;
|
||||
if (hi == g) return 512 + (b - r) * 255 / range;
|
||||
return 1024 + (r - g) * 255 / range;
|
||||
}
|
||||
|
||||
int saturation(const std::uint8_t* px) {
|
||||
return std::max({px[0], px[1], px[2]}) - std::min({px[0], px[1], px[2]});
|
||||
}
|
||||
|
||||
// The image with rows and columns swapped, so vertical sorting is horizontal
|
||||
// sorting of the transpose.
|
||||
Image transposed(const Image& src) {
|
||||
Image out(src.height(), src.width());
|
||||
parallelFor(static_cast<std::size_t>(src.width()), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t x = begin; x < end; ++x) {
|
||||
std::uint8_t* row = out.row(static_cast<int>(x));
|
||||
for (int y = 0; y < src.height(); ++y) {
|
||||
std::memcpy(row + static_cast<std::size_t>(y) * 3, src.row(y) + x * 3, 3);
|
||||
}
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
struct LinePlan {
|
||||
bool sorted = false;
|
||||
std::uint64_t seed = 0; // for the run lengths, when they are limited
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
Image PixelSortEffect::render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const {
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
|
||||
const int low = static_cast<int>(std::clamp(paramDouble(values, "sort_low", 0.25), 0.0, 1.0) * 255.0 + 0.5);
|
||||
const int high = static_cast<int>(std::clamp(paramDouble(values, "sort_high", 0.8), 0.0, 1.0) * 255.0 + 0.5);
|
||||
const std::string keyName = paramChoice(values, "sort_key", "luma");
|
||||
const bool vertical = paramChoice(values, "sort_direction", "horizontal") == "vertical";
|
||||
const bool reverse = paramBool(values, "sort_reverse", false);
|
||||
const double lineChance = std::clamp(paramDouble(values, "sort_line_chance", 1.0), 0.0, 1.0);
|
||||
const int maxRun = static_cast<int>(std::max(0L, paramInt(values, "sort_max_run", 0)));
|
||||
|
||||
Image canvas = canvasFromSources(sources, width, height, rng);
|
||||
if (vertical) canvas = transposed(canvas);
|
||||
const int lines = canvas.height();
|
||||
const int span = canvas.width();
|
||||
|
||||
// Which lines are sorted, and a seed for each line's run lengths, are drawn
|
||||
// serially; the lines then sort in parallel, each from its own generator.
|
||||
std::vector<LinePlan> plan(static_cast<std::size_t>(lines));
|
||||
for (auto& line : plan) {
|
||||
line.sorted = chance(rng.next(), lineChance);
|
||||
if (maxRun > 0) line.seed = rng.next();
|
||||
}
|
||||
|
||||
auto keyOf = [&](const std::uint8_t* px) {
|
||||
if (keyName == "hue") return hue(px);
|
||||
if (keyName == "saturation") return saturation(px);
|
||||
return luma(px);
|
||||
};
|
||||
|
||||
parallelFor(static_cast<std::size_t>(lines), [&](std::size_t begin, std::size_t end) {
|
||||
std::vector<std::pair<int, std::array<std::uint8_t, 3>>> run;
|
||||
for (std::size_t line = begin; line < end; ++line) {
|
||||
if (!plan[line].sorted) continue;
|
||||
Rng runRng(plan[line].seed);
|
||||
std::uint8_t* row = canvas.row(static_cast<int>(line));
|
||||
|
||||
auto flush = [&](int start) {
|
||||
// A stable sort, so equal keys keep their order on every
|
||||
// standard library.
|
||||
std::stable_sort(run.begin(), run.end(), [&](const auto& a, const auto& b) {
|
||||
return reverse ? a.first > b.first : a.first < b.first;
|
||||
});
|
||||
for (std::size_t i = 0; i < run.size(); ++i) {
|
||||
std::memcpy(row + (static_cast<std::size_t>(start) + i) * 3, run[i].second.data(), 3);
|
||||
}
|
||||
run.clear();
|
||||
};
|
||||
|
||||
int start = 0;
|
||||
int limit = maxRun > 0 ? static_cast<int>(runRng.inRange(1, maxRun)) : span;
|
||||
for (int x = 0; x < span; ++x) {
|
||||
const std::uint8_t* px = row + static_cast<std::size_t>(x) * 3;
|
||||
const int brightness = luma(px);
|
||||
if (brightness < low || brightness > high) {
|
||||
flush(start);
|
||||
start = x + 1;
|
||||
continue;
|
||||
}
|
||||
if (static_cast<int>(run.size()) >= limit) {
|
||||
flush(start);
|
||||
start = x;
|
||||
if (maxRun > 0) limit = static_cast<int>(runRng.inRange(1, maxRun));
|
||||
}
|
||||
run.push_back({keyOf(px), {px[0], px[1], px[2]}});
|
||||
}
|
||||
flush(start);
|
||||
}
|
||||
});
|
||||
|
||||
return vertical ? transposed(canvas) : canvas;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/effect.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// Finds runs of pixels whose brightness lies between two thresholds and sorts
|
||||
// each run by brightness, hue or saturation, which makes the image drip.
|
||||
// A pure transform: it needs no source images, and leading a chain with
|
||||
// sources loaded it starts from a crop of a randomly chosen one.
|
||||
class PixelSortEffect : public Effect {
|
||||
public:
|
||||
std::string name() const override { return "pixelsort"; }
|
||||
std::string title() const override { return "Pixel sort"; }
|
||||
std::string description() const override {
|
||||
return "Sorts the runs of pixels whose brightness lies between two thresholds, along "
|
||||
"rows or columns, so the image melts and drips.";
|
||||
}
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
bool needsSources() const override { return false; }
|
||||
|
||||
Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const override;
|
||||
};
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
#include "core/image.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// Reads the colour at a fractional position, mixing the four neighbouring
|
||||
// pixels; positions off the image take the nearest edge pixel. The weights are
|
||||
// cut to 1/256 steps so the mix itself is integer arithmetic.
|
||||
inline void sampleBilinear(const Image& image, double x, double y, std::uint8_t out[3]) {
|
||||
const int maxX = image.width() - 1;
|
||||
const int maxY = image.height() - 1;
|
||||
x = std::clamp(x, 0.0, static_cast<double>(maxX));
|
||||
y = std::clamp(y, 0.0, static_cast<double>(maxY));
|
||||
|
||||
const int x0 = static_cast<int>(x);
|
||||
const int y0 = static_cast<int>(y);
|
||||
const int x1 = std::min(x0 + 1, maxX);
|
||||
const int y1 = std::min(y0 + 1, maxY);
|
||||
const int fx = static_cast<int>((x - x0) * 256.0);
|
||||
const int fy = static_cast<int>((y - y0) * 256.0);
|
||||
|
||||
const std::uint8_t* a = image.row(y0) + static_cast<std::size_t>(x0) * 3;
|
||||
const std::uint8_t* b = image.row(y0) + static_cast<std::size_t>(x1) * 3;
|
||||
const std::uint8_t* c = image.row(y1) + static_cast<std::size_t>(x0) * 3;
|
||||
const std::uint8_t* d = image.row(y1) + static_cast<std::size_t>(x1) * 3;
|
||||
for (int ch = 0; ch < 3; ++ch) {
|
||||
const int top = a[ch] * (256 - fx) + b[ch] * fx;
|
||||
const int bottom = c[ch] * (256 - fx) + d[ch] * fx;
|
||||
out[ch] = static_cast<std::uint8_t>((top * (256 - fy) + bottom * fy + 32768) >> 16);
|
||||
}
|
||||
}
|
||||
|
||||
// Sine and cosine of an angle in degrees from nothing but additions and
|
||||
// multiplications, so a rotation lands on the same pixels whatever the
|
||||
// machine's libm makes of std::sin. The angle is folded into one octant and a
|
||||
// short Taylor series does the rest, far below a pixel's worth of error.
|
||||
inline void sinCosDegrees(double degrees, double& sine, double& cosine) {
|
||||
const double turns = degrees / 90.0;
|
||||
const double quadrant = std::floor(turns + 0.5);
|
||||
const double x = (turns - quadrant) * 1.5707963267948966; // [-pi/4, pi/4]
|
||||
const double x2 = x * x;
|
||||
const double s =
|
||||
x * (1.0 - x2 / 6.0 * (1.0 - x2 / 20.0 * (1.0 - x2 / 42.0 * (1.0 - x2 / 72.0))));
|
||||
const double c =
|
||||
1.0 - x2 / 2.0 * (1.0 - x2 / 12.0 * (1.0 - x2 / 30.0 * (1.0 - x2 / 56.0 * (1.0 - x2 / 90.0))));
|
||||
switch (static_cast<int>(quadrant - 4.0 * std::floor(quadrant / 4.0))) {
|
||||
case 0: sine = s; cosine = c; break;
|
||||
case 1: sine = c; cosine = -s; break;
|
||||
case 2: sine = -s; cosine = -c; break;
|
||||
default: sine = -c; cosine = s; break;
|
||||
}
|
||||
}
|
||||
|
||||
// A uniform double in [0, 1) from the top 53 bits of one rng draw.
|
||||
inline double unitDouble(std::uint64_t bits) {
|
||||
return static_cast<double>(bits >> 11) * (1.0 / 9007199254740992.0);
|
||||
}
|
||||
|
||||
// Whether an event with the given probability happens, from one rng draw.
|
||||
inline bool chance(std::uint64_t bits, double probability) {
|
||||
return unitDouble(bits) < probability;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,178 @@
|
||||
#include "effects/shatter.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
#include "core/parallel.hpp"
|
||||
#include "effects/sampling.hpp"
|
||||
#include "effects/source_fill.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
const std::vector<ParamSpec>& ShatterEffect::params() const {
|
||||
static const std::vector<ParamSpec> specs = {
|
||||
ParamSpec::makeInt("shatter_cells", "Shards", 40, 2, 5000,
|
||||
"How many shards the image breaks into."),
|
||||
ParamSpec::makeInt("shatter_displace", "Displacement", 40, 0, 4096,
|
||||
"Furthest in pixels a shard's picture may slide, along either axis."),
|
||||
ParamSpec::makeDouble("shatter_rotate", "Rotation", 8.0, 0.0, 180.0,
|
||||
"Largest turn in degrees of a shard's picture, either way.", 0.5, 1),
|
||||
ParamSpec::makeDouble("shatter_zoom", "Zoom", 0.05, 0.0, 0.9,
|
||||
"Largest zoom in or out of a shard's picture, as a fraction.", 0.01),
|
||||
ParamSpec::makeInt("shatter_crack_width", "Crack width", 2, 0, 64,
|
||||
"Width in pixels of the cracks between the shards (0 = none)."),
|
||||
ParamSpec::makeColor("shatter_crack_colour", "Crack colour", "#101010",
|
||||
"Colour the cracks are drawn in."),
|
||||
};
|
||||
return specs;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct Shard {
|
||||
double x = 0.0; // the point the shard grows around
|
||||
double y = 0.0;
|
||||
double dx = 0.0;
|
||||
double dy = 0.0;
|
||||
double sine = 0.0;
|
||||
double cosine = 1.0;
|
||||
double zoom = 1.0;
|
||||
};
|
||||
|
||||
// The shard points bucketed on a coarse grid, so finding the two nearest to a
|
||||
// pixel looks at a few buckets instead of every point.
|
||||
class ShardGrid {
|
||||
public:
|
||||
ShardGrid(const std::vector<Shard>& shards, int width, int height) : shards_(shards) {
|
||||
cell_ = std::max(1.0, std::sqrt(static_cast<double>(width) * height /
|
||||
static_cast<double>(shards.size())));
|
||||
cols_ = static_cast<int>(width / cell_) + 1;
|
||||
rows_ = static_cast<int>(height / cell_) + 1;
|
||||
buckets_.resize(static_cast<std::size_t>(cols_) * rows_);
|
||||
for (std::size_t i = 0; i < shards.size(); ++i) {
|
||||
buckets_[bucketOf(shards[i].x, shards[i].y)].push_back(static_cast<int>(i));
|
||||
}
|
||||
}
|
||||
|
||||
// The nearest and second nearest shard to (x, y).
|
||||
void nearest(double x, double y, int& first, int& second) const {
|
||||
const int bx = std::clamp(static_cast<int>(x / cell_), 0, cols_ - 1);
|
||||
const int by = std::clamp(static_cast<int>(y / cell_), 0, rows_ - 1);
|
||||
double best = std::numeric_limits<double>::max();
|
||||
double next = best;
|
||||
first = second = -1;
|
||||
const int maxRing = std::max(cols_, rows_);
|
||||
for (int ring = 0; ring <= maxRing; ++ring) {
|
||||
// Anything in this ring is at least (ring - 1) cells away, so once
|
||||
// both answers are closer than that the search is over.
|
||||
const double reach = std::max(0, ring - 1) * cell_;
|
||||
if (second >= 0 && next < reach * reach) break;
|
||||
for (int gy = by - ring; gy <= by + ring; ++gy) {
|
||||
if (gy < 0 || gy >= rows_) continue;
|
||||
const bool edgeRow = gy == by - ring || gy == by + ring;
|
||||
for (int gx = bx - ring; gx <= bx + ring; gx += edgeRow ? 1 : 2 * std::max(ring, 1)) {
|
||||
if (gx < 0 || gx >= cols_) continue;
|
||||
for (int index : buckets_[static_cast<std::size_t>(gy) * cols_ + gx]) {
|
||||
const Shard& shard = shards_[static_cast<std::size_t>(index)];
|
||||
const double d = (shard.x - x) * (shard.x - x) + (shard.y - y) * (shard.y - y);
|
||||
if (d < best || (d == best && index < first)) {
|
||||
next = best;
|
||||
second = first;
|
||||
best = d;
|
||||
first = index;
|
||||
} else if (d < next || (d == next && index < second)) {
|
||||
next = d;
|
||||
second = index;
|
||||
}
|
||||
}
|
||||
if (ring == 0) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::size_t bucketOf(double x, double y) const {
|
||||
const int bx = std::clamp(static_cast<int>(x / cell_), 0, cols_ - 1);
|
||||
const int by = std::clamp(static_cast<int>(y / cell_), 0, rows_ - 1);
|
||||
return static_cast<std::size_t>(by) * cols_ + bx;
|
||||
}
|
||||
|
||||
const std::vector<Shard>& shards_;
|
||||
double cell_ = 1.0;
|
||||
int cols_ = 1;
|
||||
int rows_ = 1;
|
||||
std::vector<std::vector<int>> buckets_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
Image ShatterEffect::render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const {
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
|
||||
const long count = std::max(2L, paramInt(values, "shatter_cells", 40));
|
||||
const int displace = static_cast<int>(std::max(0L, paramInt(values, "shatter_displace", 40)));
|
||||
const double rotate = std::clamp(paramDouble(values, "shatter_rotate", 8.0), 0.0, 180.0);
|
||||
const double zoom = std::clamp(paramDouble(values, "shatter_zoom", 0.05), 0.0, 0.9);
|
||||
const double crackWidth = static_cast<double>(std::max(0L, paramInt(values, "shatter_crack_width", 2)));
|
||||
std::uint8_t crack[3];
|
||||
paramColor(values, "shatter_crack_colour", "#101010", crack);
|
||||
|
||||
const Image input = canvasFromSources(sources, width, height, rng);
|
||||
|
||||
std::vector<Shard> shards(static_cast<std::size_t>(count));
|
||||
for (auto& shard : shards) {
|
||||
shard.x = unitDouble(rng.next()) * width;
|
||||
shard.y = unitDouble(rng.next()) * height;
|
||||
shard.dx = static_cast<double>(rng.inRange(-displace, displace));
|
||||
shard.dy = static_cast<double>(rng.inRange(-displace, displace));
|
||||
sinCosDegrees((unitDouble(rng.next()) * 2.0 - 1.0) * rotate, shard.sine, shard.cosine);
|
||||
shard.zoom = 1.0 + (unitDouble(rng.next()) * 2.0 - 1.0) * zoom;
|
||||
}
|
||||
const ShardGrid grid(shards, width, height);
|
||||
|
||||
Image canvas(width, height);
|
||||
parallelFor(static_cast<std::size_t>(height), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t row = begin; row < end; ++row) {
|
||||
std::uint8_t* out = canvas.row(static_cast<int>(row));
|
||||
const double y = static_cast<double>(row) + 0.5;
|
||||
for (int col = 0; col < width; ++col) {
|
||||
std::uint8_t* px = out + static_cast<std::size_t>(col) * 3;
|
||||
const double x = col + 0.5;
|
||||
int first = 0;
|
||||
int second = 0;
|
||||
grid.nearest(x, y, first, second);
|
||||
const Shard& a = shards[static_cast<std::size_t>(first)];
|
||||
|
||||
if (crackWidth > 0.0 && second >= 0) {
|
||||
// Distance to the edge between the two nearest shards,
|
||||
// which is the perpendicular bisector of their points.
|
||||
const Shard& b = shards[static_cast<std::size_t>(second)];
|
||||
const double da = (x - a.x) * (x - a.x) + (y - a.y) * (y - a.y);
|
||||
const double db = (x - b.x) * (x - b.x) + (y - b.y) * (y - b.y);
|
||||
const double gap = std::sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
|
||||
if (gap > 0.0 && (db - da) / (2.0 * gap) < crackWidth * 0.5) {
|
||||
px[0] = crack[0];
|
||||
px[1] = crack[1];
|
||||
px[2] = crack[2];
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Undo the shard's slide, then its turn and zoom about its point.
|
||||
const double rx = x - a.dx - a.x;
|
||||
const double ry = y - a.dy - a.y;
|
||||
const double sx = a.x + (rx * a.cosine + ry * a.sine) / a.zoom;
|
||||
const double sy = a.y + (-rx * a.sine + ry * a.cosine) / a.zoom;
|
||||
sampleBilinear(input, sx - 0.5, sy - 0.5, px);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/effect.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// Breaks its input into random glass shards (the cells around scattered points),
|
||||
// each showing the image shifted, turned and zoomed a little on its own, with
|
||||
// optional cracks drawn along the edges.
|
||||
// A pure transform: it needs no source images, and leading a chain with
|
||||
// sources loaded it starts from a crop of a randomly chosen one.
|
||||
class ShatterEffect : public Effect {
|
||||
public:
|
||||
std::string name() const override { return "shatter"; }
|
||||
std::string title() const override { return "Shatter"; }
|
||||
std::string description() const override {
|
||||
return "Breaks the image into random shards, each shifted, turned and zoomed on its own, "
|
||||
"with optional cracks between them.";
|
||||
}
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
bool needsSources() const override { return false; }
|
||||
|
||||
Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const override;
|
||||
};
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,99 @@
|
||||
#include "effects/slitshift.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "core/parallel.hpp"
|
||||
#include "effects/source_fill.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
const std::vector<ParamSpec>& SlitShiftEffect::params() const {
|
||||
static const std::vector<ParamSpec> specs = {
|
||||
ParamSpec::makeInt("shift_bands", "Bands", 24, 1, 4096,
|
||||
"How many bands are torn out of place."),
|
||||
ParamSpec::makeInt("shift_max", "Largest shift", 120, 0, 8192,
|
||||
"Furthest in pixels a band may be pushed, either way."),
|
||||
ParamSpec::makeInt("shift_band_height", "Band height", 16, 1, 2048,
|
||||
"Thickness in pixels of each band."),
|
||||
ParamSpec::makeInt("shift_height_jitter", "Height jitter", 12, 0, 2048,
|
||||
"Random +/- variation added to the band thickness (0 = uniform)."),
|
||||
ParamSpec::makeChoice("shift_edge", "Edges", "wrap", {"wrap", "smear", "black"},
|
||||
"What fills the gap a band leaves: wrap brings in what was pushed "
|
||||
"off the other side, smear stretches the last pixel, black leaves "
|
||||
"it empty."),
|
||||
ParamSpec::makeChoice("shift_axis", "Axis", "horizontal", {"horizontal", "vertical"},
|
||||
"horizontal tears bands of rows sideways, vertical tears bands of "
|
||||
"columns up and down."),
|
||||
};
|
||||
return specs;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// Where the pixel at `index` of a line of `count` is read from once the line is
|
||||
// pushed by `offset`, or -1 for an empty (black) pixel.
|
||||
int shiftedIndex(int index, int offset, int count, char edge) {
|
||||
const int from = index - offset;
|
||||
if (from >= 0 && from < count) return from;
|
||||
if (edge == 'w') return ((from % count) + count) % count;
|
||||
if (edge == 's') return std::clamp(from, 0, count - 1);
|
||||
return -1;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Image SlitShiftEffect::render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const {
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
|
||||
const long bands = std::max(1L, paramInt(values, "shift_bands", 24));
|
||||
const int maxShift = static_cast<int>(std::max(0L, paramInt(values, "shift_max", 120)));
|
||||
const int bandHeight = static_cast<int>(std::max(1L, paramInt(values, "shift_band_height", 16)));
|
||||
const int jitter = static_cast<int>(std::max(0L, paramInt(values, "shift_height_jitter", 12)));
|
||||
const char edge = paramChoice(values, "shift_edge", "wrap").front();
|
||||
const bool vertical = paramChoice(values, "shift_axis", "horizontal") == "vertical";
|
||||
|
||||
const Image input = canvasFromSources(sources, width, height, rng);
|
||||
|
||||
// Every band is drawn up front, and overlapping bands simply add their
|
||||
// pushes, so what the pixels need is one offset per line.
|
||||
const int lines = vertical ? width : height;
|
||||
const int span = vertical ? height : width;
|
||||
std::vector<int> offsets(static_cast<std::size_t>(lines), 0);
|
||||
for (long band = 0; band < bands; ++band) {
|
||||
int thickness = bandHeight;
|
||||
if (jitter > 0) thickness += static_cast<int>(rng.inRange(-jitter, jitter));
|
||||
thickness = std::clamp(thickness, 1, lines);
|
||||
const int start = static_cast<int>(rng.inRange(0, lines - thickness));
|
||||
const int offset = static_cast<int>(rng.inRange(-maxShift, maxShift));
|
||||
for (int line = start; line < start + thickness; ++line) {
|
||||
offsets[static_cast<std::size_t>(line)] += offset;
|
||||
}
|
||||
}
|
||||
|
||||
Image canvas(width, height);
|
||||
parallelFor(static_cast<std::size_t>(lines), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t line = begin; line < end; ++line) {
|
||||
const int offset = offsets[line];
|
||||
for (int i = 0; i < span; ++i) {
|
||||
const int from = shiftedIndex(i, offset, span, edge);
|
||||
const int x = vertical ? static_cast<int>(line) : i;
|
||||
const int y = vertical ? i : static_cast<int>(line);
|
||||
std::uint8_t* out = canvas.row(y) + static_cast<std::size_t>(x) * 3;
|
||||
if (from < 0) {
|
||||
out[0] = out[1] = out[2] = 0;
|
||||
continue;
|
||||
}
|
||||
const int fx = vertical ? x : from;
|
||||
const int fy = vertical ? from : y;
|
||||
std::memcpy(out, input.row(fy) + static_cast<std::size_t>(fx) * 3, 3);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/effect.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// Tears its input apart: random bands of rows (or columns) are pushed sideways by a
|
||||
// random distance each, the way a video signal loses its sync.
|
||||
// A pure transform: it needs no source images, and leading a chain with
|
||||
// sources loaded it starts from a crop of a randomly chosen one.
|
||||
class SlitShiftEffect : public Effect {
|
||||
public:
|
||||
std::string name() const override { return "slitshift"; }
|
||||
std::string title() const override { return "Slit shift"; }
|
||||
std::string description() const override {
|
||||
return "Tears random bands of its input sideways, like a video signal losing sync; "
|
||||
"overlapping bands add their shifts up.";
|
||||
}
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
bool needsSources() const override { return false; }
|
||||
|
||||
Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const override;
|
||||
};
|
||||
|
||||
} // namespace effector
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "core/image.hpp"
|
||||
#include "core/parallel.hpp"
|
||||
#include "core/rng.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
@@ -35,4 +37,20 @@ inline void fillFromSource(Image& canvas, const Image& src, int sx, int sy) {
|
||||
});
|
||||
}
|
||||
|
||||
// The canvas a pure transform starts from: a crop of a randomly chosen source,
|
||||
// or black when there is none. Inside a chain the only source is the stage
|
||||
// before, which has the canvas size, so no random value is drawn at all; only a
|
||||
// transform leading a chain with photographs loaded spends any of the rng here.
|
||||
inline Image canvasFromSources(const std::vector<Image>& sources, int width, int height, Rng& rng) {
|
||||
Image canvas(width, height);
|
||||
if (!sources.empty()) {
|
||||
const std::size_t index = rng.below(sources.size() - 1);
|
||||
const Image& src = sources[index];
|
||||
const int sx = static_cast<int>(rng.inRange(0, std::max(0, src.width() - width)));
|
||||
const int sy = static_cast<int>(rng.inRange(0, std::max(0, src.height() - height)));
|
||||
fillFromSource(canvas, src, sx, sy);
|
||||
}
|
||||
return canvas;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <numbers>
|
||||
|
||||
#include "core/parallel.hpp"
|
||||
#include "effects/source_fill.hpp"
|
||||
@@ -57,6 +58,10 @@ const std::vector<ParamSpec>& TextEffect::params() const {
|
||||
"Moves the text right by this many pixels (left when negative)."),
|
||||
ParamSpec::makeInt("text_offset_y", "Offset Y", 0, -20000, 20000,
|
||||
"Moves the text down by this many pixels (up when negative)."),
|
||||
ParamSpec::makeDouble("text_rotation", "Rotation", 0.0, -360.0, 360.0,
|
||||
"Turns the text and its box about their centre by this many "
|
||||
"degrees, clockwise (anticlockwise when negative).",
|
||||
1.0, 1),
|
||||
ParamSpec::makeDouble("text_opacity", "Text opacity", 1.0, 0.0, 1.0,
|
||||
"How strongly the glyphs are mixed over what is behind them.")
|
||||
.styled(),
|
||||
@@ -198,6 +203,22 @@ void TextEffect::loadBoxImage(const std::string& path, Image& image,
|
||||
alpha = cachedAlpha_;
|
||||
}
|
||||
|
||||
std::string TextEffect::label(const ParamValues& values) const {
|
||||
// Several lines read as one: each run of whitespace becomes a single space.
|
||||
std::string words;
|
||||
bool gap = false;
|
||||
for (const char c : paramText(values, "text", "")) {
|
||||
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
|
||||
gap = !words.empty();
|
||||
continue;
|
||||
}
|
||||
if (gap) words += ' ';
|
||||
gap = false;
|
||||
words += c;
|
||||
}
|
||||
return words.empty() ? title() : title() + " (" + words + ")";
|
||||
}
|
||||
|
||||
Image TextEffect::render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const {
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
@@ -264,6 +285,18 @@ Image TextEffect::render(const std::vector<Image>& sources, int width, int heigh
|
||||
const double boxY = (centre ? (height - boxHeight) / 2.0 : 0.0) +
|
||||
static_cast<double>(paramInt(values, "text_offset_y", 0));
|
||||
|
||||
// The turn is about the middle of the box, so it never moves the text away
|
||||
// from where the centring and the offset put it. Cairo's y points down,
|
||||
// which makes a positive angle clockwise on screen.
|
||||
const double rotation = paramDouble(values, "text_rotation", 0.0);
|
||||
if (rotation != 0.0) {
|
||||
const double cx = boxX + boxWidth / 2.0;
|
||||
const double cy = boxY + boxHeight / 2.0;
|
||||
cairo_translate(cr.get, cx, cy);
|
||||
cairo_rotate(cr.get, rotation * std::numbers::pi / 180.0);
|
||||
cairo_translate(cr.get, -cx, -cy);
|
||||
}
|
||||
|
||||
if (drawsBox) {
|
||||
cairo_save(cr.get);
|
||||
cairo_rectangle(cr.get, boxX, boxY, boxWidth, boxHeight);
|
||||
|
||||
@@ -30,6 +30,8 @@ public:
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
std::string styleKind() const override { return "text"; }
|
||||
bool needsSources() const override { return false; }
|
||||
// "Text (Hello world)", so stages writing different words tell apart.
|
||||
std::string label(const ParamValues& values) const override;
|
||||
|
||||
Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const override;
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
#include "effects/warp.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#include "core/parallel.hpp"
|
||||
#include "effects/sampling.hpp"
|
||||
#include "effects/source_fill.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
const std::vector<ParamSpec>& WarpEffect::params() const {
|
||||
static const std::vector<ParamSpec> specs = {
|
||||
ParamSpec::makeInt("warp_strength", "Strength", 40, 0, 4096,
|
||||
"How far in pixels the field pushes the image at its strongest."),
|
||||
ParamSpec::makeInt("warp_scale", "Scale", 160, 4, 8192,
|
||||
"Size in pixels of the largest features in the field."),
|
||||
ParamSpec::makeInt("warp_octaves", "Octaves", 3, 1, 6,
|
||||
"Finer layers of noise laid over the first; more give a turbulent "
|
||||
"edge to the flow."),
|
||||
ParamSpec::makeChoice("warp_mode", "Mode", "displace", {"displace", "swirl"},
|
||||
"displace pushes along the field; swirl flows along its contour "
|
||||
"lines, which curls the image into eddies."),
|
||||
};
|
||||
return specs;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// One layer of value noise: random heights on a lattice `spacing` pixels
|
||||
// apart, blended smoothly between the lattice points.
|
||||
class NoiseLayer {
|
||||
public:
|
||||
NoiseLayer(Rng& rng, int width, int height, double spacing)
|
||||
: spacing_(spacing),
|
||||
cols_(static_cast<int>(width / spacing) + 2),
|
||||
rows_(static_cast<int>(height / spacing) + 2),
|
||||
lattice_(static_cast<std::size_t>(cols_) * rows_) {
|
||||
for (auto& value : lattice_) value = unitDouble(rng.next()) * 2.0 - 1.0;
|
||||
}
|
||||
|
||||
// The height at (x, y) in [-1, 1], and its slope per pixel along x and y.
|
||||
void sample(double x, double y, double& value, double& slopeX, double& slopeY) const {
|
||||
const double gx = x / spacing_;
|
||||
const double gy = y / spacing_;
|
||||
const int ix = std::min(static_cast<int>(gx), cols_ - 2);
|
||||
const int iy = std::min(static_cast<int>(gy), rows_ - 2);
|
||||
const double fx = gx - ix;
|
||||
const double fy = gy - iy;
|
||||
const double sx = fx * fx * (3.0 - 2.0 * fx);
|
||||
const double sy = fy * fy * (3.0 - 2.0 * fy);
|
||||
|
||||
const double a = at(ix, iy);
|
||||
const double b = at(ix + 1, iy);
|
||||
const double c = at(ix, iy + 1);
|
||||
const double d = at(ix + 1, iy + 1);
|
||||
const double cross = a - b - c + d;
|
||||
value = a + (b - a) * sx + (c - a) * sy + cross * sx * sy;
|
||||
slopeX = 6.0 * fx * (1.0 - fx) * ((b - a) + cross * sy) / spacing_;
|
||||
slopeY = 6.0 * fy * (1.0 - fy) * ((c - a) + cross * sx) / spacing_;
|
||||
}
|
||||
|
||||
private:
|
||||
double at(int x, int y) const { return lattice_[static_cast<std::size_t>(y) * cols_ + x]; }
|
||||
|
||||
double spacing_;
|
||||
int cols_;
|
||||
int rows_;
|
||||
std::vector<double> lattice_;
|
||||
};
|
||||
|
||||
// Octaves of noise summed, each twice as fine and half as strong as the one
|
||||
// before, and scaled back so the total stays in [-1, 1].
|
||||
class NoiseField {
|
||||
public:
|
||||
NoiseField(Rng& rng, int width, int height, double scale, int octaves) {
|
||||
double spacing = scale;
|
||||
double weight = 1.0;
|
||||
for (int i = 0; i < octaves; ++i) {
|
||||
layers_.emplace_back(rng, width, height, std::max(1.0, spacing));
|
||||
weights_.push_back(weight);
|
||||
total_ += weight;
|
||||
spacing *= 0.5;
|
||||
weight *= 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
void sample(double x, double y, double& value, double& slopeX, double& slopeY) const {
|
||||
value = slopeX = slopeY = 0.0;
|
||||
for (std::size_t i = 0; i < layers_.size(); ++i) {
|
||||
double v = 0.0, sx = 0.0, sy = 0.0;
|
||||
layers_[i].sample(x, y, v, sx, sy);
|
||||
value += v * weights_[i];
|
||||
slopeX += sx * weights_[i];
|
||||
slopeY += sy * weights_[i];
|
||||
}
|
||||
value /= total_;
|
||||
slopeX /= total_;
|
||||
slopeY /= total_;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<NoiseLayer> layers_;
|
||||
std::vector<double> weights_;
|
||||
double total_ = 0.0;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
Image WarpEffect::render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const {
|
||||
if (width < 1 || height < 1) throw EffectError("Canvas size must be at least 1x1 pixels.");
|
||||
|
||||
const double strength = static_cast<double>(std::max(0L, paramInt(values, "warp_strength", 40)));
|
||||
const double scale = static_cast<double>(std::max(4L, paramInt(values, "warp_scale", 160)));
|
||||
const int octaves = static_cast<int>(std::clamp(paramInt(values, "warp_octaves", 3), 1L, 6L));
|
||||
const bool swirl = paramChoice(values, "warp_mode", "displace") == "swirl";
|
||||
|
||||
const Image input = canvasFromSources(sources, width, height, rng);
|
||||
|
||||
// Lattices are drawn in full before any pixel moves: one field for the
|
||||
// swirl, which flows along its contours, two for a push along x and y.
|
||||
const NoiseField first(rng, width, height, scale, octaves);
|
||||
std::vector<NoiseField> extra;
|
||||
if (!swirl) extra.emplace_back(rng, width, height, scale, octaves);
|
||||
|
||||
Image canvas(width, height);
|
||||
parallelFor(static_cast<std::size_t>(height), [&](std::size_t begin, std::size_t end) {
|
||||
for (std::size_t row = begin; row < end; ++row) {
|
||||
std::uint8_t* out = canvas.row(static_cast<int>(row));
|
||||
const double y = static_cast<double>(row);
|
||||
for (int col = 0; col < width; ++col) {
|
||||
const double x = col;
|
||||
double value = 0.0, slopeX = 0.0, slopeY = 0.0;
|
||||
first.sample(x, y, value, slopeX, slopeY);
|
||||
double dx = 0.0;
|
||||
double dy = 0.0;
|
||||
if (swirl) {
|
||||
// Along the contour: the slope turned a quarter, which
|
||||
// never piles pixels up or tears them apart. The slope of
|
||||
// a field `scale` wide is about 1/scale, hence the factor.
|
||||
dx = slopeY * scale * strength * 0.5;
|
||||
dy = -slopeX * scale * strength * 0.5;
|
||||
} else {
|
||||
double other = 0.0;
|
||||
extra.front().sample(x, y, other, slopeX, slopeY);
|
||||
dx = value * strength;
|
||||
dy = other * strength;
|
||||
}
|
||||
sampleBilinear(input, x + dx, y + dy, out + static_cast<std::size_t>(col) * 3);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
} // namespace effector
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/effect.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
// Pushes every pixel along a smooth random noise field: a haze at low strength,
|
||||
// melted paint at high. The swirl mode follows the field's contour lines,
|
||||
// which turns the image into eddies instead of ripples.
|
||||
// A pure transform: it needs no source images, and leading a chain with
|
||||
// sources loaded it starts from a crop of a randomly chosen one.
|
||||
class WarpEffect : public Effect {
|
||||
public:
|
||||
std::string name() const override { return "warp"; }
|
||||
std::string title() const override { return "Warp"; }
|
||||
std::string description() const override {
|
||||
return "Pushes every pixel along a smooth random noise field, from a gentle haze to "
|
||||
"molten eddies.";
|
||||
}
|
||||
const std::vector<ParamSpec>& params() const override;
|
||||
bool needsSources() const override { return false; }
|
||||
|
||||
Image render(const std::vector<Image>& sources, int width, int height, Rng& rng,
|
||||
const ParamValues& values) const override;
|
||||
};
|
||||
|
||||
} // namespace effector
|
||||
@@ -13,6 +13,14 @@ int runGui(const Options& initial, int argc, char** argv) {
|
||||
|
||||
auto app = Gtk::Application::create("org.effector.Effector",
|
||||
Gio::Application::Flags::NON_UNIQUE);
|
||||
app->signal_startup().connect([] {
|
||||
// An installed Effector finds its icon in the hicolor theme; one run
|
||||
// straight from the build tree falls back to the copy in the sources.
|
||||
const char* icon = "org.effector.Effector";
|
||||
auto theme = Gtk::IconTheme::get_for_display(Gdk::Display::get_default());
|
||||
if (!theme->has_icon(icon)) theme->add_search_path(EFFECTOR_SOURCE_ICON_DIR);
|
||||
Gtk::Window::set_default_icon_name(icon);
|
||||
});
|
||||
return app->make_window_and_run<EffectorWindow>(0, nullptr, initial);
|
||||
}
|
||||
|
||||
|
||||
+1134
-56
File diff suppressed because it is too large
Load Diff
+105
-3
@@ -18,6 +18,7 @@
|
||||
#include "core/image.hpp"
|
||||
#include "core/project.hpp"
|
||||
#include "core/style.hpp"
|
||||
#include "core/video.hpp"
|
||||
|
||||
namespace effector {
|
||||
|
||||
@@ -29,6 +30,8 @@ public:
|
||||
private:
|
||||
void buildUi();
|
||||
Gtk::Widget& buildSidebar();
|
||||
Gtk::Widget& buildChainTab();
|
||||
Gtk::Widget& buildSetupTab();
|
||||
Gtk::Widget& buildPreview();
|
||||
void buildParamWidgets();
|
||||
ParamValues paramValues() const;
|
||||
@@ -72,7 +75,7 @@ private:
|
||||
void closeLoadWindow();
|
||||
void cancelLoad();
|
||||
void appendSourceRow(const std::string& path);
|
||||
void updateSourcesLabel(); // the collapsed expander shows the count
|
||||
void updateSourcesLabel(); // the heading shows the count
|
||||
// The whole sources section only shows while the chain asks for sources.
|
||||
void updateSourcesVisible();
|
||||
|
||||
@@ -85,22 +88,67 @@ private:
|
||||
void syncCanvasWidgets();
|
||||
void removeSource(Gtk::ListBoxRow* row);
|
||||
|
||||
// Video: a switch that makes the project a clip, and its length, rate and
|
||||
// preset. A preset owns the canvas format as well as the timing; changing
|
||||
// any of them by hand drops it back to "Custom".
|
||||
Gtk::Widget& buildVideoSection();
|
||||
VideoSettings videoSettings() const;
|
||||
void setVideoSettings(const VideoSettings& video); // quietly, for a project
|
||||
void onVideoToggled();
|
||||
void onVideoPresetSelected();
|
||||
void onVideoTimingChanged();
|
||||
void matchVideoPreset(); // "Custom" once the settings are no longer the preset's
|
||||
bool isVideo() const { return videoSwitch_.get_active(); }
|
||||
|
||||
// The preview of a video is the whole clip, rendered first and then looped.
|
||||
void onClipProgress(); // dispatcher: frames arrived from the worker
|
||||
void showClipFrame(int index);
|
||||
void startPlayback();
|
||||
void stopPlayback();
|
||||
void setPlaying(bool playing);
|
||||
void clearClip();
|
||||
|
||||
// Writing a video file: rendered again at full size, on a thread of its
|
||||
// own, into ffmpeg, with a progress window that can cancel it.
|
||||
void startExport(const std::string& path);
|
||||
void onExportProgress();
|
||||
void onExportFinished();
|
||||
void cancelExport();
|
||||
void closeExportWindow();
|
||||
|
||||
Gtk::Widget& buildChainSection();
|
||||
Gtk::Widget& buildAddMenu(); // the menu of effects that can be appended
|
||||
void appendStage(const EffectPtr& effect);
|
||||
void removeStage(int index);
|
||||
void moveStage(int index, int delta);
|
||||
void moveStage(int from, int to); // `to` is the index it ends up at
|
||||
// Dragging a row: the slot between rows it would drop into, and the line
|
||||
// that shows it.
|
||||
int chainDropSlot(double y) const;
|
||||
void showChainDropSlot(int slot);
|
||||
// The check on a chain row: the stage stays where it is, and is skipped.
|
||||
void setStageEnabled(int index, bool enabled);
|
||||
void rebuildChainRows();
|
||||
// Rests the split under the chain's rows, until the user drags it.
|
||||
void scheduleChainSplitFit();
|
||||
void fitChainSplit();
|
||||
void refitChainSplit(); // the double-click on the handle
|
||||
void onChainSplitMoved();
|
||||
std::string stageLabel(std::size_t index) const;
|
||||
void selectStage(int index);
|
||||
void onStageSelected();
|
||||
Gtk::Widget& buildMainMenu(); // the header menu: new, open, save project
|
||||
void showChangelog();
|
||||
void showAbout();
|
||||
Project currentProject() const;
|
||||
void applyProject(const Project& project, const std::string& path);
|
||||
void clearSources();
|
||||
void onNewProject();
|
||||
void onOpenProject();
|
||||
void openProject(const std::string& path);
|
||||
// Open Recent: the projects this program opened or saved, newest first,
|
||||
// kept in the desktop's shared list of recently used files.
|
||||
void rememberProject(const std::string& path);
|
||||
void rebuildRecentMenu();
|
||||
void onProjectChosen(const Glib::RefPtr<Gio::AsyncResult>& result,
|
||||
const Glib::RefPtr<Gtk::FileDialog>& dialog);
|
||||
void onSaveProject(); // falls back to Save As while the project is untitled
|
||||
@@ -143,9 +191,20 @@ private:
|
||||
StyleSet styles_;
|
||||
int selectedStage_ = 0;
|
||||
bool suspendStageSelect_ = false; // guards the rebuild of the chain rows
|
||||
// The split between the chain and the params, and where it was last put
|
||||
// to fit the rows: any other position the user reached by dragging.
|
||||
Gtk::Paned* chainSplit_ = nullptr;
|
||||
int fittedChainSplit_ = -1;
|
||||
bool chainSplitDragged_ = false;
|
||||
bool suspendSplitTrack_ = false;
|
||||
sigc::connection chainSplitFit_;
|
||||
// The name label of each chain row, renamed in place as params change.
|
||||
std::vector<Gtk::Label*> stageLabels_;
|
||||
Image result_;
|
||||
std::uint64_t seed_ = 0;
|
||||
std::string projectPath_; // empty until the project has been saved once
|
||||
Glib::RefPtr<Gio::Menu> recentMenu_;
|
||||
sigc::connection recentChanged_; // the recent list outlives the window
|
||||
bool suspendRender_ = true;
|
||||
|
||||
// Source loading. Decoding a batch of large photographs takes seconds, so
|
||||
@@ -175,21 +234,60 @@ private:
|
||||
Image pendingImage_;
|
||||
std::string pendingError_;
|
||||
double pendingMillis_ = 0.0;
|
||||
// Set to stop a clip render early once its settings are out of date.
|
||||
std::atomic<bool> renderCancel_{false};
|
||||
bool renderingVideo_ = false; // what the render in flight is making
|
||||
|
||||
// The clip being previewed: small frames, ready to show, and the frames
|
||||
// of the clip being rendered, which take its place once it is complete.
|
||||
Glib::Dispatcher clipProgress_;
|
||||
std::vector<Image> pendingFrames_; // handed over under resultMutex_
|
||||
std::vector<Glib::RefPtr<Gdk::Texture>> clip_;
|
||||
std::vector<Glib::RefPtr<Gdk::Texture>> incomingClip_;
|
||||
int incomingTotal_ = 0;
|
||||
int clipFps_ = kDefaultFps;
|
||||
int playFrame_ = 0;
|
||||
bool playing_ = true;
|
||||
sigc::connection playTimer_;
|
||||
bool suspendScrub_ = false; // set while playback moves the scale itself
|
||||
|
||||
// Video export
|
||||
std::thread exporter_;
|
||||
Glib::Dispatcher exportProgress_;
|
||||
Glib::Dispatcher exportDone_;
|
||||
std::atomic<bool> exportCancel_{false};
|
||||
std::atomic<int> exportFrames_{0};
|
||||
int exportTotal_ = 0;
|
||||
bool exporting_ = false;
|
||||
std::string exportPath_;
|
||||
std::string exportError_; // written by the exporter before exportDone_
|
||||
std::unique_ptr<Gtk::Window> exportWindow_;
|
||||
Gtk::ProgressBar* exportBar_ = nullptr; // nulled with the window
|
||||
|
||||
// Widgets
|
||||
Gtk::Label banner_;
|
||||
Gtk::Button* addButton_ = nullptr;
|
||||
// Built fresh with the progress window, and null whenever it is closed.
|
||||
std::unique_ptr<Gtk::Window> loadWindow_;
|
||||
// Opened from the menu on first use, then shown again rather than rebuilt.
|
||||
std::unique_ptr<Gtk::Window> changelogWindow_;
|
||||
std::unique_ptr<Gtk::AboutDialog> aboutDialog_;
|
||||
Gtk::ProgressBar* loadBar_ = nullptr;
|
||||
Gtk::Label* loadFileLabel_ = nullptr;
|
||||
Gtk::Expander sourcesExpander_;
|
||||
Gtk::Box sourcesSection_; // hidden while the chain needs no sources
|
||||
Gtk::Label sourcesHeading_;
|
||||
Gtk::ListBox sourceList_;
|
||||
Gtk::DropDown formatDrop_;
|
||||
Gtk::SpinButton widthSpin_;
|
||||
Gtk::SpinButton heightSpin_;
|
||||
Gtk::SpinButton dpiSpin_;
|
||||
Gtk::Label* dpiLabel_ = nullptr; // hidden along with the dpi spin
|
||||
Gtk::Switch videoSwitch_;
|
||||
Gtk::Box videoDetails_; // hidden while the project is a still
|
||||
Gtk::DropDown videoPresetDrop_;
|
||||
Gtk::SpinButton durationSpin_;
|
||||
Gtk::SpinButton fpsSpin_;
|
||||
bool suspendVideoSync_ = false; // set while code, not the user, fills them
|
||||
// Set while a format fills the spins, so their own handler does not queue
|
||||
// a second render on top of the one the format change asks for.
|
||||
bool suspendCanvasSync_ = false;
|
||||
@@ -211,6 +309,10 @@ private:
|
||||
Gtk::Label placeholder_;
|
||||
Gtk::Spinner spinner_;
|
||||
Gtk::Label status_;
|
||||
Gtk::Box playbackBar_; // under the preview of a video only
|
||||
Gtk::Button playButton_;
|
||||
Gtk::Scale playbackScale_;
|
||||
Gtk::Label playbackTime_;
|
||||
|
||||
struct ParamWidget {
|
||||
ParamSpec spec;
|
||||
|
||||
@@ -13,11 +13,55 @@
|
||||
#include "core/image.hpp"
|
||||
#include "core/registry.hpp"
|
||||
#include "core/rng.hpp"
|
||||
#include "core/video.hpp"
|
||||
#include "core/version.hpp"
|
||||
#include "gui/app.hpp"
|
||||
|
||||
namespace {
|
||||
|
||||
int renderVideo(const effector::Options& options, const std::vector<effector::ChainStage>& stages,
|
||||
const std::vector<effector::Image>& sources, std::uint64_t seed) {
|
||||
const int count = options.video.frameCount();
|
||||
const bool showProgress = isatty(fileno(stderr)) != 0;
|
||||
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
effector::VideoWriter writer(options.output, options.width, options.height, options.video.fps);
|
||||
effector::renderFrames(stages, sources, options.width, options.height, seed, {}, options.video,
|
||||
[&](int index, effector::Image&& frame) {
|
||||
writer.write(frame);
|
||||
if (showProgress) {
|
||||
std::cerr << "\r\033[Kframe " << index + 1 << "/" << count
|
||||
<< std::flush;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (showProgress) std::cerr << "\r\033[K" << std::flush;
|
||||
writer.finish();
|
||||
const auto seconds =
|
||||
std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
|
||||
|
||||
std::cout << options.output << " " << options.width << "x" << options.height << " "
|
||||
<< count << " frames at " << options.video.fps << " fps effect="
|
||||
<< effector::chainSlug(stages) << " seed=" << seed << " render=" << std::fixed
|
||||
<< std::setprecision(1) << seconds << " s\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
int renderHeadless(const effector::Options& options) {
|
||||
// Checked before anything is decoded: a mismatch between what was asked
|
||||
// for and the file named is a typo, not something to find out later.
|
||||
const bool videoFile = effector::isVideoPath(options.output);
|
||||
if (options.video.enabled && !videoFile) {
|
||||
std::cerr << "effector: a video is written as .mp4, .mov, .mkv, .webm or .gif, not "
|
||||
<< options.output << "\n";
|
||||
return 2;
|
||||
}
|
||||
if (!options.video.enabled && videoFile) {
|
||||
std::cerr << "effector: " << options.output
|
||||
<< " is a video; give its length with --duration or --video-preset\n";
|
||||
return 2;
|
||||
}
|
||||
|
||||
auto stages = effector::buildChain(options);
|
||||
// A headless run always renders something, so with no -e the default
|
||||
// effect stands in. The interface has no such need: it opens on an empty
|
||||
@@ -53,6 +97,7 @@ int renderHeadless(const effector::Options& options) {
|
||||
}
|
||||
|
||||
const std::uint64_t seed = options.seed.value_or(effector::Rng::randomSeed());
|
||||
if (options.video.enabled) return renderVideo(options, stages, sources, seed);
|
||||
effector::Rng rng(seed);
|
||||
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
@@ -78,6 +123,10 @@ int main(int argc, char** argv) {
|
||||
std::cout << effector::usage(argv[0]);
|
||||
return 0;
|
||||
}
|
||||
if (options.showVersion) {
|
||||
std::cout << "effector " << effector::kVersion << "\n";
|
||||
return 0;
|
||||
}
|
||||
if (options.listEffects) {
|
||||
for (const auto& effect : effector::effects()) {
|
||||
std::cout << effect->name() << "\t" << effect->title() << " - "
|
||||
|
||||
@@ -3,5 +3,23 @@
|
||||
add_executable(effector_tests core_tests.cpp ../src/cli/options.cpp)
|
||||
target_link_libraries(effector_tests PRIVATE effector_core)
|
||||
target_compile_options(effector_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
# The version test reads the Arch PKGBUILD to keep its pkgver in step.
|
||||
target_compile_definitions(effector_tests PRIVATE EFFECTOR_SOURCE_DIR="${PROJECT_SOURCE_DIR}")
|
||||
|
||||
add_test(NAME core COMMAND effector_tests)
|
||||
|
||||
# The interface drives the real window, so it needs a display. Under ctest it
|
||||
# gets a private Xvfb one when xvfb-run is installed; without it, or without a
|
||||
# display of its own, the test reports itself skipped rather than failed.
|
||||
add_executable(effector_gui_tests gui_tests.cpp)
|
||||
target_link_libraries(effector_gui_tests PRIVATE effector_gui)
|
||||
target_compile_options(effector_gui_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
|
||||
find_program(XVFB_RUN xvfb-run)
|
||||
if(XVFB_RUN)
|
||||
add_test(NAME gui COMMAND ${XVFB_RUN} -a -s "-screen 0 1400x900x24"
|
||||
env -u WAYLAND_DISPLAY GDK_BACKEND=x11 $<TARGET_FILE:effector_gui_tests>)
|
||||
else()
|
||||
add_test(NAME gui COMMAND effector_gui_tests)
|
||||
endif()
|
||||
set_tests_properties(gui PROPERTIES SKIP_RETURN_CODE 77)
|
||||
|
||||
+490
-1
@@ -12,6 +12,7 @@
|
||||
#include <locale>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -23,7 +24,10 @@
|
||||
#include "core/registry.hpp"
|
||||
#include "core/rng.hpp"
|
||||
#include "core/style.hpp"
|
||||
#include "core/version.hpp"
|
||||
#include "core/video.hpp"
|
||||
#include "effects/blur.hpp"
|
||||
#include "effects/channelsplit.hpp"
|
||||
#include "effects/grain.hpp"
|
||||
#include "effects/monochrome.hpp"
|
||||
#include "effects/overlay.hpp"
|
||||
@@ -201,6 +205,18 @@ effector::Image flat(int width, int height, std::uint8_t shade) {
|
||||
return image;
|
||||
}
|
||||
|
||||
// Renders any registered effect by name with its defaults, overridden by
|
||||
// `values`, from a generator seeded with `seed`.
|
||||
effector::Image renderNamed(const std::string& name, const std::vector<effector::Image>& sources,
|
||||
int width, int height, std::uint64_t seed,
|
||||
const effector::ParamValues& values) {
|
||||
const auto effect = effector::effectByName(name);
|
||||
effector::Rng rng(seed);
|
||||
auto merged = effect->defaults();
|
||||
for (const auto& [key, value] : values) merged[key] = value;
|
||||
return effect->render(sources, width, height, rng, merged);
|
||||
}
|
||||
|
||||
effector::Image render(const std::vector<effector::Image>& sources, int width, int height,
|
||||
std::uint64_t seed, const effector::ParamValues& values) {
|
||||
effector::ScanlinesEffect effect;
|
||||
@@ -243,6 +259,15 @@ int main() {
|
||||
threw = true;
|
||||
}
|
||||
check(threw, "unknown effect throws");
|
||||
|
||||
// Flags share one namespace, so a key two effects declared would be
|
||||
// handed to whichever came first.
|
||||
std::set<std::string> keys;
|
||||
bool unique = true;
|
||||
for (const auto& effect : effects()) {
|
||||
for (const auto& spec : effect->params()) unique = keys.insert(spec.key).second && unique;
|
||||
}
|
||||
check(unique, "no two effects declare the same param key");
|
||||
}
|
||||
|
||||
std::cout << "scanlines\n";
|
||||
@@ -616,6 +641,49 @@ int main() {
|
||||
solid(100, 100, 0, 0, 255)),
|
||||
"zero opacity leaves the input untouched");
|
||||
|
||||
// Halo: none by default, a shadow moved by its offset, a glow all round.
|
||||
check(sameBytes(renderOverlay(blue, 100, 100, at),
|
||||
renderOverlay(blue, 100, 100, [&] {
|
||||
ParamValues none = at;
|
||||
none["overlay_halo"] = std::string("none");
|
||||
return none;
|
||||
}())),
|
||||
"no halo is the default");
|
||||
ParamValues shadowed = at;
|
||||
shadowed["overlay_halo"] = std::string("shadow");
|
||||
shadowed["overlay_halo_size"] = 0L;
|
||||
shadowed["overlay_halo_opacity"] = 1.0;
|
||||
shadowed["overlay_shadow_x"] = 5L;
|
||||
shadowed["overlay_shadow_y"] = 5L;
|
||||
const auto shadow = renderOverlay(blue, 100, 100, shadowed);
|
||||
const auto dark = pixel(shadow, 72, 62); // past the logo's bottom right corner (70, 60)
|
||||
check(dark[0] == 0 && dark[1] == 0 && dark[2] == 0,
|
||||
"a hard shadow is cast down and right by its offset");
|
||||
check(isBlue(pixel(shadow, 28, 50)) && isRed(pixel(shadow, 50, 50)),
|
||||
"it leaves the other side alone and stays beneath the image");
|
||||
shadowed["overlay_halo_size"] = 12L;
|
||||
const auto soft = pixel(renderOverlay(blue, 100, 100, shadowed), 78, 50);
|
||||
check(soft[2] > 0 && soft[2] < 255, "a soft shadow fades out past the edge");
|
||||
|
||||
ParamValues glowing = at;
|
||||
glowing["overlay_halo"] = std::string("glow");
|
||||
const auto glow = renderOverlay(blue, 100, 100, glowing);
|
||||
const auto left = pixel(glow, 27, 50);
|
||||
const auto right = pixel(glow, 72, 50);
|
||||
check(left[0] > 0 && left[0] == right[0] && left[1] == right[1],
|
||||
"a glow lightens both sides alike");
|
||||
check(isBlue(pixel(glow, 2, 2)), "and fades out before the far corners");
|
||||
glowing["overlay_halo_spread"] = 0.5;
|
||||
check(pixel(renderOverlay(blue, 100, 100, glowing), 27, 50)[0] > left[0],
|
||||
"spread strengthens the halo near the edge");
|
||||
|
||||
ParamValues offCanvas = shadowed;
|
||||
offCanvas["overlay_halo_size"] = 0L;
|
||||
offCanvas["overlay_offset_x"] = -70L; // the logo ends just left of the canvas
|
||||
offCanvas["overlay_shadow_x"] = 20L;
|
||||
const auto cast = pixel(renderOverlay(blue, 100, 100, offCanvas), 5, 50);
|
||||
check(cast[2] == 0, "an image off the canvas still casts its shadow onto it");
|
||||
|
||||
// No image chosen is the state the interface starts in: a pass through.
|
||||
check(sameBytes(renderOverlay(blue, 100, 100, {}), solid(100, 100, 0, 0, 255)),
|
||||
"with no image chosen the stage passes its input through");
|
||||
@@ -737,6 +805,20 @@ int main() {
|
||||
check(countRed(moved, 100, 60, 200, 120) > 0 && countRed(moved, 0, 0, 100, 60) == 0,
|
||||
"the offset moves it down and to the right");
|
||||
|
||||
// A wide line turned a quarter stands upright: it reaches above and
|
||||
// below the band it filled unturned, and no longer out to the sides.
|
||||
ParamValues wide = plain;
|
||||
wide["text"] = std::string("HHHHHH");
|
||||
wide["font_size"] = 40.0;
|
||||
const auto flat = renderText(blue, 200, 120, wide);
|
||||
ParamValues turned = wide;
|
||||
turned["text_rotation"] = 90.0;
|
||||
const auto upright = renderText(blue, 200, 120, turned);
|
||||
check(countRed(flat, 0, 0, 200, 25) == 0 && countRed(upright, 0, 0, 200, 25) > 0,
|
||||
"rotation turns the text about its centre");
|
||||
check(countRed(flat, 0, 0, 50, 120) > 0 && countRed(upright, 0, 0, 50, 120) == 0,
|
||||
"and takes it in from the sides");
|
||||
|
||||
// Weight and size are the two knobs the glyphs themselves answer to: a
|
||||
// bolder or a larger setting covers strictly more of the canvas.
|
||||
ParamValues bold = plain;
|
||||
@@ -821,6 +903,13 @@ int main() {
|
||||
// Like blur and overlay it needs no sources of its own, and the same
|
||||
// settings render the same bytes twice over.
|
||||
check(!TextEffect().needsSources(), "text can lead a chain");
|
||||
|
||||
// A text stage is named after its words, on one line.
|
||||
check(TextEffect().label({{"text", std::string(" Two\nlines ")}}) == "Text (Two lines)",
|
||||
"a text stage is labelled with its words");
|
||||
check(TextEffect().label({{"text", std::string(" \n")}}) == "Text",
|
||||
"a text stage with no words is labelled with the title alone");
|
||||
check(effectByName("blur")->label({}) == "Blur", "other effects are labelled with their title");
|
||||
const auto alone = renderText({}, 200, 120, plain);
|
||||
check(alone.width() == 200 && countRed(alone, 0, 0, 200, 120) > 0,
|
||||
"without sources it draws on an empty canvas");
|
||||
@@ -855,7 +944,8 @@ int main() {
|
||||
carries("box_padding") && carries("box_opacity"),
|
||||
"the look is what it carries");
|
||||
check(!carries("text") && !carries("text_wrap") && !carries("box_image") &&
|
||||
!carries("text_center") && !carries("text_offset_x") && !carries("text_offset_y"),
|
||||
!carries("text_center") && !carries("text_offset_x") && !carries("text_offset_y") &&
|
||||
!carries("text_rotation"),
|
||||
"the words and the placement stay on the stage");
|
||||
check(styleSpecs("").empty() && styleSpecs("nosuchkind").empty(),
|
||||
"a kind no effect claims carries nothing");
|
||||
@@ -933,6 +1023,150 @@ int main() {
|
||||
"and so does a chain handed no styles at all");
|
||||
}
|
||||
|
||||
std::cout << "chaos transforms\n";
|
||||
{
|
||||
const std::vector<Image> sources = {gradient(1200, 800, 10), gradient(640, 480, 90)};
|
||||
const std::vector<Image> input = {gradient(400, 300, 40)};
|
||||
|
||||
// What every one of them must do, and what switches each one off.
|
||||
const std::vector<std::pair<std::string, ParamValues>> transforms = {
|
||||
{"slitshift", {{"shift_max", 0L}}},
|
||||
{"channelsplit", {{"split_amount", 0L}}},
|
||||
{"pixelsort", {{"sort_line_chance", 0.0}}},
|
||||
{"corrupt", {{"corrupt_rate", 0.0}}},
|
||||
{"shatter",
|
||||
{{"shatter_displace", 0L}, {"shatter_rotate", 0.0}, {"shatter_zoom", 0.0},
|
||||
{"shatter_crack_width", 0L}}},
|
||||
{"warp", {{"warp_strength", 0L}}},
|
||||
{"bitcrush", {{"crush_coverage", 0.0}}},
|
||||
{"feedback", {{"echo_fade", 0.0}}},
|
||||
};
|
||||
for (const auto& [name, off] : transforms) {
|
||||
check(!effectByName(name)->needsSources(), name + " needs no source images");
|
||||
|
||||
const auto first = renderNamed(name, sources, 400, 300, 4, {});
|
||||
const auto again = renderNamed(name, sources, 400, 300, 4, {});
|
||||
const auto other = renderNamed(name, sources, 400, 300, 11, {});
|
||||
check(first.width() == 400 && first.height() == 300,
|
||||
name + " renders the requested size");
|
||||
check(sameBytes(first, again), name + " reproduces itself from a seed");
|
||||
check(!sameBytes(first, other), name + " changes with the seed");
|
||||
check(!sameBytes(renderNamed(name, input, 400, 300, 4, {}), input[0]),
|
||||
name + " changes its input");
|
||||
check(sameBytes(renderNamed(name, input, 400, 300, 4, off), input[0]),
|
||||
name + " switched right down leaves its input alone");
|
||||
|
||||
const auto blank = renderNamed(name, {}, 120, 80, 1, {});
|
||||
check(blank.width() == 120 && blank.height() == 80,
|
||||
name + " renders without sources");
|
||||
|
||||
ChainStage scanlines{effectByName("scanlines"), {{"strip_height", 6L}}};
|
||||
ChainStage stage{effectByName(name), {}};
|
||||
Rng a(9);
|
||||
Rng b(9);
|
||||
check(sameBytes(renderChain({scanlines, stage}, sources, 300, 200, a),
|
||||
renderChain({scanlines, stage}, sources, 300, 200, b)),
|
||||
name + " cascades reproducibly");
|
||||
check(!chainNeedsSources({stage, scanlines}), "a chain led by " + name + " needs no sources");
|
||||
|
||||
// A canvas one pixel wide or high must not trip any of them up.
|
||||
check(renderNamed(name, {}, 1, 1, 2, {}).width() == 1 &&
|
||||
renderNamed(name, input, 1, 57, 2, {}).height() == 57 &&
|
||||
renderNamed(name, input, 57, 1, 2, {}).width() == 57,
|
||||
name + " copes with a sliver of a canvas");
|
||||
}
|
||||
|
||||
// Wrapped slit shifts only rotate each row, so every row keeps its
|
||||
// pixels, just not their places.
|
||||
const auto wrapped = renderNamed("slitshift", input, 400, 300, 5, {{"shift_bands", 200L}});
|
||||
bool rotated = true;
|
||||
for (int y = 0; y < 300; ++y) {
|
||||
std::vector<std::uint8_t> before(input[0].row(y), input[0].row(y) + 1200);
|
||||
std::vector<std::uint8_t> after(wrapped.row(y), wrapped.row(y) + 1200);
|
||||
std::sort(before.begin(), before.end());
|
||||
std::sort(after.begin(), after.end());
|
||||
rotated = rotated && before == after;
|
||||
}
|
||||
check(rotated, "a wrapped slit shift keeps every row's pixels");
|
||||
const auto upright = renderNamed("slitshift", input, 400, 300, 5,
|
||||
{{"shift_axis", std::string("vertical")}});
|
||||
check(!sameBytes(upright, wrapped), "the vertical axis tears columns instead");
|
||||
|
||||
// Moving a plane of one colour moves nothing that can be seen.
|
||||
const auto split = renderNamed("channelsplit", {solid(80, 60, 200, 90, 30)}, 80, 60, 3,
|
||||
{{"split_mode", std::string("per_band")},
|
||||
{"split_band_height", 7L}});
|
||||
check(sameBytes(split, solid(80, 60, 200, 90, 30)), "a channel split keeps a flat colour");
|
||||
const auto rc = renderNamed("channelsplit", input, 400, 300, 3,
|
||||
{{"split_channels", std::string("red_cyan")}});
|
||||
check(pixel(rc, 200, 150)[2] == pixel(input[0], 200, 150)[2],
|
||||
"red_cyan leaves blue where a flat plane has it");
|
||||
|
||||
// With the thresholds wide open every row comes out sorted.
|
||||
const auto sorted = renderNamed("pixelsort", {stripes(64, 16)}, 64, 16, 1,
|
||||
{{"sort_low", 0.0}, {"sort_high", 1.0}});
|
||||
bool ordered = true;
|
||||
for (int y = 0; y < 16; ++y) {
|
||||
for (int x = 1; x < 64; ++x) ordered = ordered && pixel(sorted, x - 1, y)[0] <= pixel(sorted, x, y)[0];
|
||||
}
|
||||
check(ordered, "an open pixel sort orders every row");
|
||||
const auto downward = renderNamed("pixelsort", {stripes(64, 16)}, 64, 16, 1,
|
||||
{{"sort_low", 0.0}, {"sort_high", 1.0},
|
||||
{"sort_direction", std::string("vertical")}});
|
||||
check(sameBytes(downward, stripes(64, 16)), "sorting uniform columns changes nothing");
|
||||
|
||||
// Every block repeated is the first block smeared across the row.
|
||||
const auto smeared = renderNamed("corrupt", input, 64, 32, 2,
|
||||
{{"corrupt_rate", 1.0},
|
||||
{"corrupt_block", 16L},
|
||||
{"corrupt_kinds", std::string("repeat")}});
|
||||
bool periodic = true;
|
||||
for (int y = 0; y < 32; ++y) {
|
||||
for (int x = 16; x < 64; ++x) periodic = periodic && pixel(smeared, x, y) == pixel(smeared, x - 16, y);
|
||||
}
|
||||
check(periodic, "repeated blocks copy the block to their left");
|
||||
const auto bled = renderNamed("corrupt", input, 400, 300, 2,
|
||||
{{"corrupt_rate", 0.02}, {"corrupt_bleed", true}});
|
||||
check(!sameBytes(bled, renderNamed("corrupt", input, 400, 300, 2, {{"corrupt_rate", 0.02}})),
|
||||
"bleeding carries the damage further");
|
||||
|
||||
const auto cracked = renderNamed("shatter", {flat(200, 150, 128)}, 200, 150, 6,
|
||||
{{"shatter_crack_colour", std::string("#ff0000")}});
|
||||
bool red = false;
|
||||
for (int y = 0; y < 150; ++y) {
|
||||
for (int x = 0; x < 200; ++x) red = red || isRed(pixel(cracked, x, y));
|
||||
}
|
||||
check(red, "shatter draws its cracks in the crack colour");
|
||||
|
||||
check(!sameBytes(renderNamed("warp", input, 400, 300, 4, {{"warp_mode", std::string("swirl")}}),
|
||||
renderNamed("warp", input, 400, 300, 4, {})),
|
||||
"swirl flows differently from a plain push");
|
||||
|
||||
const auto poster = renderNamed("bitcrush", input, 400, 300, 3,
|
||||
{{"crush_op", std::string("posterize")},
|
||||
{"crush_coverage", 1.0}});
|
||||
bool coarse = true;
|
||||
for (std::size_t i = 0; i < poster.byteSize(); ++i) coarse = coarse && poster.data()[i] % 8 == 0;
|
||||
check(coarse, "posterising three bits leaves multiples of eight");
|
||||
const auto swapped = renderNamed("bitcrush", {solid(40, 40, 250, 120, 5)}, 40, 40, 3,
|
||||
{{"crush_op", std::string("channel_swap")},
|
||||
{"crush_coverage", 1.0}});
|
||||
check(pixel(swapped, 20, 20) != std::array<int, 3>{250, 120, 5},
|
||||
"a channel swap never leaves the order as it was");
|
||||
|
||||
// A shrunk, fully opaque echo lands the image's corner inside the
|
||||
// canvas, while the border outside every echo stays the input's.
|
||||
const auto tunnel = renderNamed("feedback", input, 400, 300, 1,
|
||||
{{"echo_scale", 0.5}, {"echo_rotate", 0.0},
|
||||
{"echo_drift", 0L}, {"echo_fade", 1.0}});
|
||||
check(pixel(tunnel, 0, 0) == pixel(input[0], 0, 0), "the border outside the echoes is the input");
|
||||
// Halfway to the corner reads the corner of the image at half size.
|
||||
const auto near = pixel(tunnel, 100, 75);
|
||||
check(std::abs(near[0] - pixel(input[0], 0, 0)[0]) < 4 &&
|
||||
std::abs(near[1] - pixel(input[0], 0, 0)[1]) < 4,
|
||||
"the echoes nest inside it");
|
||||
}
|
||||
|
||||
std::cout << "chain\n";
|
||||
{
|
||||
std::vector<Image> sources = {gradient(1200, 800, 10), gradient(640, 480, 90)};
|
||||
@@ -1484,6 +1718,261 @@ int main() {
|
||||
std::filesystem::remove_all(dir);
|
||||
}
|
||||
|
||||
std::cout << "video\n";
|
||||
{
|
||||
using effector::ChainStage;
|
||||
using effector::FrameTime;
|
||||
using effector::VideoSettings;
|
||||
|
||||
// Every preset names a canvas format this build offers, and its
|
||||
// numbers are ones the project reader and the CLI accept.
|
||||
int sound = 0;
|
||||
for (const auto& preset : effector::videoPresets()) {
|
||||
if (effector::canvasFormatByKey(preset.canvasFormat) != nullptr &&
|
||||
preset.seconds >= effector::kMinDuration && preset.seconds <= effector::kMaxDuration &&
|
||||
preset.fps >= effector::kMinFps && preset.fps <= effector::kMaxFps &&
|
||||
effector::videoPresetByKey(preset.key) == &preset) {
|
||||
++sound;
|
||||
}
|
||||
}
|
||||
check(sound == static_cast<int>(effector::videoPresets().size()),
|
||||
"every video preset names a known canvas and a valid length and rate");
|
||||
const auto* story = effector::videoPresetByKey("instagram-story");
|
||||
check(story != nullptr && story->canvasFormat == "instagram-story" && story->seconds == 15.0,
|
||||
"the Instagram story preset is a 15 s vertical clip");
|
||||
VideoSettings clip;
|
||||
clip.duration = 15.0;
|
||||
clip.fps = 30;
|
||||
check(clip.frameCount() == 450, "15 s at 30 fps is 450 frames");
|
||||
clip.duration = 0.01;
|
||||
check(clip.frameCount() == 3, "a clip below the shortest length is clamped to it");
|
||||
check(effector::formatSeconds(7.5) == "7.5 s" && effector::formatSeconds(15) == "15 s",
|
||||
"lengths read as 7.5 s and 15 s");
|
||||
check(effector::isVideoPath("a/b.MP4") && effector::isVideoPath("x.webm") &&
|
||||
effector::isVideoPath("x.gif") && !effector::isVideoPath("x.png") &&
|
||||
!effector::isVideoPath("mp4"),
|
||||
"a video is recognised by its extension");
|
||||
|
||||
const auto split = effector::effectByName("channelsplit");
|
||||
const std::vector<effector::Image> sources = {gradient(96, 64, 40)};
|
||||
|
||||
// A still ignores every motion param: the picture is the one it
|
||||
// always was, whatever they are set to.
|
||||
auto calm = split->defaults();
|
||||
calm["split_mode"] = std::string("per_band");
|
||||
auto wild = calm;
|
||||
wild["split_wobble"] = 40L;
|
||||
wild["split_jitter"] = 30L;
|
||||
wild["split_roll"] = 60L;
|
||||
effector::Rng stillA(5);
|
||||
effector::Rng stillB(5);
|
||||
check(sameBytes(split->render(sources, 96, 64, stillA, calm),
|
||||
split->renderFrame(sources, 96, 64, stillB, wild, FrameTime{})),
|
||||
"motion params leave a still untouched");
|
||||
|
||||
check(split->animated(split->defaults()), "channel split moves by default in a video");
|
||||
auto frozen = split->defaults();
|
||||
frozen["split_wobble"] = 0L;
|
||||
frozen["split_jitter"] = 0L;
|
||||
frozen["split_roll"] = 0L;
|
||||
check(!split->animated(frozen), "and holds still with every motion at 0");
|
||||
|
||||
// A moving stage leaves the shared rng in the same state on every
|
||||
// frame, so what comes after it holds still.
|
||||
effector::Rng frameA(9);
|
||||
effector::Rng frameB(9);
|
||||
split->renderFrame(sources, 96, 64, frameA, wild, FrameTime{3, 30, 30});
|
||||
split->renderFrame(sources, 96, 64, frameB, wild, FrameTime{17, 30, 30});
|
||||
check(frameA.next() == frameB.next(), "every frame leaves the shared rng in one state");
|
||||
|
||||
auto stage = [](const std::string& name, effector::ParamValues values = {}) {
|
||||
ChainStage built;
|
||||
built.effect = effector::effectByName(name);
|
||||
built.values = values.empty() ? built.effect->defaults() : std::move(values);
|
||||
return built;
|
||||
};
|
||||
std::vector<ChainStage> chain = {stage("tiles"), stage("channelsplit", wild), stage("grain")};
|
||||
VideoSettings video;
|
||||
video.enabled = true;
|
||||
video.duration = 1.0;
|
||||
video.fps = 8;
|
||||
|
||||
std::vector<effector::Image> first;
|
||||
const int handed = effector::renderFrames(chain, sources, 80, 48, 21, {}, video,
|
||||
[&](int, effector::Image&& frame) {
|
||||
first.push_back(std::move(frame));
|
||||
return true;
|
||||
});
|
||||
check(handed == 8 && first.size() == 8, "a clip hands out every one of its frames");
|
||||
std::vector<effector::Image> second;
|
||||
effector::renderFrames(chain, sources, 80, 48, 21, {}, video,
|
||||
[&](int, effector::Image&& frame) {
|
||||
second.push_back(std::move(frame));
|
||||
return true;
|
||||
});
|
||||
bool repeatable = second.size() == first.size();
|
||||
for (std::size_t i = 0; repeatable && i < first.size(); ++i) {
|
||||
repeatable = sameBytes(first[i], second[i]);
|
||||
}
|
||||
check(repeatable, "a clip renders byte for byte again from its seed");
|
||||
|
||||
// The still stages before the moving one are rendered once and
|
||||
// reused; that shortcut must give exactly what a frame on its own is.
|
||||
bool exact = true;
|
||||
for (const int index : {0, 3, 7}) {
|
||||
effector::Rng rng(21);
|
||||
const auto alone = effector::renderChain(chain, sources, 80, 48, rng, {},
|
||||
FrameTime{index, 8, 8});
|
||||
exact = exact && sameBytes(alone, first[static_cast<std::size_t>(index)]);
|
||||
}
|
||||
check(exact, "a clip's frame is exactly that frame rendered on its own");
|
||||
check(!sameBytes(first[0], first[3]) && !sameBytes(first[3], first[7]),
|
||||
"frames of a moving chain differ");
|
||||
|
||||
std::vector<ChainStage> steady = {stage("tiles"), stage("channelsplit", frozen), stage("grain")};
|
||||
std::vector<effector::Image> held;
|
||||
effector::renderFrames(steady, sources, 80, 48, 21, {}, video,
|
||||
[&](int, effector::Image&& frame) {
|
||||
held.push_back(std::move(frame));
|
||||
return true;
|
||||
});
|
||||
bool same = held.size() == 8;
|
||||
for (const auto& frame : held) same = same && sameBytes(frame, held[0]);
|
||||
effector::Rng stillRng(21);
|
||||
check(same && sameBytes(held[0], effector::renderChain(steady, sources, 80, 48, stillRng)),
|
||||
"a chain that does not move renders its still on every frame");
|
||||
|
||||
int seen = 0;
|
||||
effector::renderFrames(chain, sources, 80, 48, 21, {}, video,
|
||||
[&](int, effector::Image&&) { return ++seen < 3; });
|
||||
check(seen == 3, "returning false stops a clip early");
|
||||
|
||||
chain[1].enabled = false;
|
||||
std::vector<effector::Image> skipped;
|
||||
effector::renderFrames(chain, sources, 80, 48, 21, {}, video,
|
||||
[&](int, effector::Image&& frame) {
|
||||
skipped.push_back(std::move(frame));
|
||||
return true;
|
||||
});
|
||||
check(skipped.size() == 8 && sameBytes(skipped[0], skipped[7]),
|
||||
"with the moving stage switched off the clip holds still");
|
||||
|
||||
const auto big = gradient(300, 120, 10);
|
||||
const auto small = big.scaledToFit(100);
|
||||
check(small.width() == 100 && small.height() == 40, "a preview frame keeps its shape");
|
||||
check(big.scaledToFit(400).width() == 300, "a frame already small enough is left alone");
|
||||
|
||||
// The project file: a video says so, a still says nothing about time.
|
||||
effector::Project project;
|
||||
project.stages = {stage("channelsplit", wild)};
|
||||
const auto stillJson = effector::projectToJson(project);
|
||||
check(stillJson.find("\"video\"") == std::string::npos, "a still project writes no video");
|
||||
check(!effector::projectFromJson(stillJson).video.enabled, "and reads back as a still");
|
||||
project.video.enabled = true;
|
||||
project.video.duration = 7.5;
|
||||
project.video.fps = 24;
|
||||
project.video.preset = "instagram-story";
|
||||
const auto back = effector::projectFromJson(effector::projectToJson(project));
|
||||
check(back.video.enabled && back.video.duration == 7.5 && back.video.fps == 24 &&
|
||||
back.video.preset == "instagram-story",
|
||||
"a video project keeps its length, rate and preset");
|
||||
const auto motion = back.stages.at(0).values;
|
||||
check(effector::paramInt(motion, "split_jitter", 0) == 30 &&
|
||||
effector::paramInt(motion, "split_roll", 0) == 60,
|
||||
"and its stages keep their motion");
|
||||
const std::string base = "{\"chain\": [{\"effect\": \"blur\"}], \"video\": {\"duration\": ";
|
||||
check(!effector::projectFromJson(base + "2, \"preset\": \"cinema\"}}").video.preset.size(),
|
||||
"an unknown preset reads as custom");
|
||||
bool rejected = false;
|
||||
try {
|
||||
effector::projectFromJson(base + "2, \"fps\": 500}}");
|
||||
} catch (const effector::EffectError&) {
|
||||
rejected = true;
|
||||
}
|
||||
check(rejected, "a frame rate out of range is refused");
|
||||
|
||||
// The command line.
|
||||
const auto preset = parsedOptions({"--video-preset", "instagram-story", "-o", "x.mp4"});
|
||||
check(preset && preset->video.enabled && preset->width == 1080 && preset->height == 1920 &&
|
||||
preset->video.duration == 15.0 && preset->video.fps == 30 &&
|
||||
preset->video.preset == "instagram-story",
|
||||
"--video-preset sets the canvas, length and rate");
|
||||
const auto shorter = parsedOptions({"--duration", "5", "--video-preset", "instagram-story"});
|
||||
check(shorter && shorter->video.duration == 5.0 && shorter->height == 1920 &&
|
||||
shorter->video.preset.empty(),
|
||||
"a length given alongside wins and leaves the preset custom");
|
||||
const auto sized = parsedOptions({"--video-preset", "hd-clip", "-s", "320x240"});
|
||||
check(sized && sized->width == 320 && sized->format.empty(),
|
||||
"a size given alongside wins over the preset's canvas");
|
||||
check(!parsedOptions({"--fps", "0"}) && !parsedOptions({"--duration", "abc"}) &&
|
||||
!parsedOptions({"--duration", "400"}) && !parsedOptions({"--video-preset", "vhs"}),
|
||||
"a bad rate, length or preset is refused");
|
||||
check(!parsedOptions({"-o", "x.png"})->video.enabled, "without them the output is a still");
|
||||
|
||||
bool wrongName = false;
|
||||
try {
|
||||
effector::VideoWriter writer("clip.png", 16, 16, 30);
|
||||
} catch (const effector::EffectError&) {
|
||||
wrongName = true;
|
||||
}
|
||||
check(wrongName, "a video is not written under an image's name");
|
||||
|
||||
if (effector::ffmpegAvailable()) {
|
||||
const auto dir = std::filesystem::temp_directory_path() / "effector-video-test";
|
||||
std::filesystem::create_directories(dir);
|
||||
const auto file = (dir / "clip.mp4").string();
|
||||
{
|
||||
// Odd sides: the writer pads them for the encoder.
|
||||
effector::VideoWriter writer(file, 17, 9, 12);
|
||||
for (int i = 0; i < 3; ++i) writer.write(gradient(17, 9, 40 * i));
|
||||
writer.finish();
|
||||
}
|
||||
check(std::filesystem::exists(file) && std::filesystem::file_size(file) > 0,
|
||||
"ffmpeg writes an .mp4 of odd size");
|
||||
const auto dropped = (dir / "dropped.webm").string();
|
||||
{
|
||||
effector::VideoWriter writer(dropped, 16, 16, 12);
|
||||
writer.write(gradient(16, 16, 10));
|
||||
writer.cancel();
|
||||
}
|
||||
check(!std::filesystem::exists(dropped), "a cancelled video leaves no file behind");
|
||||
bool wrongSize = false;
|
||||
try {
|
||||
effector::VideoWriter writer((dir / "sized.mp4").string(), 16, 16, 12);
|
||||
writer.write(gradient(8, 8, 10));
|
||||
} catch (const effector::EffectError&) {
|
||||
wrongSize = true;
|
||||
}
|
||||
check(wrongSize && !std::filesystem::exists(dir / "sized.mp4"),
|
||||
"a frame of the wrong size is refused and the file dropped");
|
||||
std::filesystem::remove_all(dir);
|
||||
} else {
|
||||
std::cout << " skip writing a video (ffmpeg is not installed)\n";
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << "version\n";
|
||||
{
|
||||
// A release is the version in CMakeLists.txt and its entry at the top
|
||||
// of CHANGELOG.md; bumping one without the other fails here.
|
||||
const std::string_view log = kChangelog;
|
||||
const auto newest = log.find("\n## [");
|
||||
check(newest != std::string_view::npos &&
|
||||
log.substr(newest + 5).starts_with(std::string(kVersion) + "]"),
|
||||
"the newest changelog entry is this version");
|
||||
std::ifstream pkgbuild(std::string(EFFECTOR_SOURCE_DIR) + "/packaging/arch/PKGBUILD");
|
||||
std::string line;
|
||||
std::string pkgver;
|
||||
while (std::getline(pkgbuild, line)) {
|
||||
if (line.starts_with("pkgver=")) pkgver = line.substr(7);
|
||||
}
|
||||
check(pkgver == kVersion, "the Arch PKGBUILD packages this version");
|
||||
const auto options = parsedOptions({"--version"});
|
||||
check(options && options->showVersion, "--version is understood");
|
||||
const auto shortOptions = parsedOptions({"-V"});
|
||||
check(shortOptions && shortOptions->showVersion, "and so is -V");
|
||||
}
|
||||
|
||||
std::cout << (failures == 0 ? "\nall checks passed\n" : "\n" + std::to_string(failures) + " failed\n");
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
// Checks for the interface, driven through the real window: the widgets are
|
||||
// found by what a user sees (a name, a tooltip, a label) and pressed the way a
|
||||
// click would press them. Needs a display; exits 77 (skipped) without one.
|
||||
|
||||
#include <gtkmm.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "cli/options.hpp"
|
||||
#include "core/project.hpp"
|
||||
#include "core/registry.hpp"
|
||||
#include "core/version.hpp"
|
||||
#include "gui/window.hpp"
|
||||
|
||||
namespace {
|
||||
|
||||
int failures = 0;
|
||||
|
||||
void check(bool condition, const std::string& what) {
|
||||
if (condition) {
|
||||
std::cout << " ok " << what << "\n";
|
||||
} else {
|
||||
std::cout << " FAIL " << what << "\n";
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
|
||||
// Lets the main loop run for a while: popovers map, renders come back, and
|
||||
// the rows rebuilt by a click are laid out.
|
||||
void pump(int milliseconds = 100) {
|
||||
auto context = Glib::MainContext::get_default();
|
||||
const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(milliseconds);
|
||||
while (std::chrono::steady_clock::now() < until) {
|
||||
while (context->pending()) context->iteration(false);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T, typename Pred>
|
||||
void collect(Gtk::Widget& root, Pred pred, std::vector<T*>& out) {
|
||||
for (auto* child = root.get_first_child(); child != nullptr; child = child->get_next_sibling()) {
|
||||
if (auto* match = dynamic_cast<T*>(child); match != nullptr && pred(*match)) out.push_back(match);
|
||||
collect<T>(*child, pred, out);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::vector<T*> all(Gtk::Widget& root) {
|
||||
std::vector<T*> out;
|
||||
collect<T>(root, [](T&) { return true; }, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T* named(Gtk::Widget& root, const std::string& name) {
|
||||
std::vector<T*> out;
|
||||
collect<T>(root, [&](T& w) { return w.get_name() == name; }, out);
|
||||
return out.empty() ? nullptr : out.front();
|
||||
}
|
||||
|
||||
Gtk::Button* withTooltip(Gtk::Widget& root, const std::string& tip) {
|
||||
std::vector<Gtk::Button*> out;
|
||||
collect<Gtk::Button>(root, [&](Gtk::Button& b) { return b.get_tooltip_text() == tip; }, out);
|
||||
return out.empty() ? nullptr : out.front();
|
||||
}
|
||||
|
||||
bool isAncestor(const Gtk::Widget& ancestor, const Gtk::Widget& widget) {
|
||||
for (auto* w = widget.get_parent(); w != nullptr; w = w->get_parent()) {
|
||||
if (w == &ancestor) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int rowCount(Gtk::ListBox& list) {
|
||||
int count = 0;
|
||||
while (list.get_row_at_index(count) != nullptr) ++count;
|
||||
return count;
|
||||
}
|
||||
|
||||
std::string rowTitle(Gtk::ListBox& list, int index) {
|
||||
auto* row = list.get_row_at_index(index);
|
||||
if (row == nullptr) return {};
|
||||
const auto labels = all<Gtk::Label>(*row);
|
||||
return labels.empty() ? std::string{} : std::string(labels.front()->get_text());
|
||||
}
|
||||
|
||||
// The top of `widget` in the window's coordinates.
|
||||
double topIn(Gtk::Widget& widget, Gtk::Widget& window) {
|
||||
graphene_rect_t bounds;
|
||||
if (!gtk_widget_compute_bounds(widget.gobj(), window.gobj(), &bounds)) return -1.0;
|
||||
return bounds.origin.y;
|
||||
}
|
||||
|
||||
// The menu of effects: the popover the "Add effect" button opens, and the
|
||||
// entry in it for one effect.
|
||||
Gtk::Button* menuEntry(Gtk::Popover& menu, const std::string& title) {
|
||||
for (auto* button : all<Gtk::Button>(menu)) {
|
||||
if (button->get_label() == title) return button;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Presses a button the way the keyboard does. GTK shows the press for a
|
||||
// quarter of a second before the button reports the click, so wait it out.
|
||||
void press(Gtk::Button& button) {
|
||||
button.activate();
|
||||
pump(400);
|
||||
}
|
||||
|
||||
bool addFromMenu(Gtk::MenuButton& add, const std::string& title) {
|
||||
auto* menu = add.get_popover();
|
||||
if (menu == nullptr) return false;
|
||||
add.popup();
|
||||
pump();
|
||||
auto* entry = menuEntry(*menu, title);
|
||||
if (entry == nullptr || !menu->get_mapped()) return false;
|
||||
press(*entry);
|
||||
return true;
|
||||
}
|
||||
|
||||
// The drop target the chain list reorders its rows with.
|
||||
GtkDropTarget* chainDropTarget(Gtk::Widget& list) {
|
||||
GListModel* controllers = gtk_widget_observe_controllers(list.gobj());
|
||||
GtkDropTarget* found = nullptr;
|
||||
for (guint i = 0; i < g_list_model_get_n_items(controllers) && found == nullptr; ++i) {
|
||||
auto* controller = g_list_model_get_item(controllers, i);
|
||||
if (GTK_IS_DROP_TARGET(controller)) found = GTK_DROP_TARGET(controller);
|
||||
g_object_unref(controller);
|
||||
}
|
||||
g_object_unref(controllers);
|
||||
return found;
|
||||
}
|
||||
|
||||
// What dropping the row of stage `index` at `y` does; a real drag needs a
|
||||
// pointer, which the tests do not have.
|
||||
void dropStage(GtkDropTarget* drop, int index, double y) {
|
||||
GValue value = G_VALUE_INIT;
|
||||
g_value_init(&value, G_TYPE_INT);
|
||||
g_value_set_int(&value, index);
|
||||
gboolean handled = FALSE;
|
||||
g_signal_emit_by_name(drop, "drop", &value, 1.0, y, &handled);
|
||||
g_value_unset(&value);
|
||||
}
|
||||
|
||||
void runTests(Gtk::Window& window) {
|
||||
const auto& effects = effector::effects();
|
||||
|
||||
std::cout << "sidebar\n";
|
||||
auto* stack = all<Gtk::Stack>(window).empty() ? nullptr : all<Gtk::Stack>(window).front();
|
||||
check(stack != nullptr && stack->get_child_by_name("chain") != nullptr &&
|
||||
stack->get_child_by_name("setup") != nullptr,
|
||||
"the sidebar has a Chain and a Setup tab");
|
||||
check(stack != nullptr && stack->get_visible_child_name() == "chain",
|
||||
"it opens on the Chain tab");
|
||||
|
||||
auto* chainList = named<Gtk::ListBox>(window, "chain-list");
|
||||
auto* add = named<Gtk::MenuButton>(window, "add-effect");
|
||||
auto* sources = named<Gtk::Box>(window, "sources");
|
||||
check(chainList != nullptr && add != nullptr && sources != nullptr,
|
||||
"the chain list, the Add effect button and the sources are there");
|
||||
if (chainList == nullptr || add == nullptr || sources == nullptr) return;
|
||||
|
||||
std::vector<Gtk::Paned*> panes;
|
||||
collect<Gtk::Paned>(window, [&](Gtk::Paned& p) { return isAncestor(p, *chainList); }, panes);
|
||||
auto* split = panes.empty() ? nullptr : panes.back();
|
||||
check(split != nullptr && split->get_orientation() == Gtk::Orientation::VERTICAL,
|
||||
"the Chain tab is a vertical split");
|
||||
check(split != nullptr && split->get_start_child() != nullptr &&
|
||||
isAncestor(*split->get_start_child(), *chainList),
|
||||
"the chain list is above the split");
|
||||
check(split != nullptr && split->get_end_child() != nullptr &&
|
||||
!isAncestor(*split->get_end_child(), *chainList),
|
||||
"the params are below it, apart from the list");
|
||||
check(split != nullptr && !split->get_shrink_start_child() && !split->get_shrink_end_child(),
|
||||
"neither side can be dragged below its minimum");
|
||||
check(topIn(*add, window) >= 0.0 && topIn(*add, window) < topIn(*chainList, window),
|
||||
"Add effect sits above the chain list, not under it");
|
||||
check(isAncestor(*stack->get_child_by_name("setup"), *sources),
|
||||
"the sources are on the Setup tab");
|
||||
|
||||
std::cout << "add effect\n";
|
||||
auto* menu = add->get_popover();
|
||||
check(menu != nullptr, "Add effect has a menu");
|
||||
if (menu == nullptr) return;
|
||||
bool listed = true;
|
||||
for (const auto& effect : effects) listed = listed && menuEntry(*menu, effect->title()) != nullptr;
|
||||
check(listed, "the menu has an entry for every registered effect");
|
||||
check(all<Gtk::Button>(*menu).size() == effects.size(), "and nothing else");
|
||||
|
||||
add->popup();
|
||||
pump();
|
||||
check(menu->get_mapped(), "the menu opens");
|
||||
// A popover taller than the room below its button is not shown at all --
|
||||
// though GTK still calls it mapped -- which is what broke the button once
|
||||
// there were enough effects: the entries have to scroll instead, in a
|
||||
// menu short enough to open below a button near the top of a 768-pixel
|
||||
// screen.
|
||||
const auto scrollers = all<Gtk::ScrolledWindow>(*menu);
|
||||
const int cap = scrollers.empty() ? -1 : scrollers.front()->get_max_content_height();
|
||||
check(!scrollers.empty() && isAncestor(*scrollers.front(), *menuEntry(*menu, effects.front()->title())),
|
||||
"the entries scroll");
|
||||
check(cap > 0 && cap <= 480, "past a height that fits a small screen");
|
||||
check(menu->get_height() > 0 && menu->get_height() <= cap + 40,
|
||||
"and the menu stays within it however many effects there are");
|
||||
add->popdown();
|
||||
pump();
|
||||
|
||||
|
||||
std::vector<Gtk::ScrolledWindow*> listScrollers;
|
||||
collect<Gtk::ScrolledWindow>(window, [&](Gtk::ScrolledWindow& s) {
|
||||
return s.get_child() != nullptr && isAncestor(*s.get_child(), *chainList);
|
||||
}, listScrollers);
|
||||
auto* listScroller = listScrollers.empty() ? nullptr : listScrollers.back();
|
||||
check(listScroller != nullptr && listScroller->get_propagate_natural_height() &&
|
||||
listScroller->get_max_content_height() > 0,
|
||||
"the chain list asks for the height of its rows, up to a cap");
|
||||
const int emptySplit = split != nullptr ? split->get_position() : -1;
|
||||
|
||||
check(rowCount(*chainList) == 0, "the chain starts empty");
|
||||
check(addFromMenu(*add, "Blur"), "picking Blur from the menu");
|
||||
check(!menu->get_mapped(), "closes the menu");
|
||||
check(rowCount(*chainList) == 1 && rowTitle(*chainList, 0) == "1. Blur",
|
||||
"and appends a Blur stage");
|
||||
check(chainList->get_selected_row() == chainList->get_row_at_index(0),
|
||||
"the new stage is selected");
|
||||
check(!sources->get_visible(), "a chain led by blur hides the sources");
|
||||
|
||||
check(addFromMenu(*add, "Scanlines"), "picking Scanlines");
|
||||
check(rowCount(*chainList) == 2 && rowTitle(*chainList, 1) == "2. Scanlines",
|
||||
"appends it after Blur");
|
||||
check(chainList->get_selected_row() == chainList->get_row_at_index(1),
|
||||
"and selects it");
|
||||
|
||||
std::cout << "stage rows\n";
|
||||
if (rowCount(*chainList) != 2) return;
|
||||
auto* second = chainList->get_row_at_index(1);
|
||||
check(second->has_css_class("stage-row"), "a row is a stage row");
|
||||
std::vector<Gtk::Button*> actions;
|
||||
collect<Gtk::Button>(*second, [](Gtk::Button& b) { return b.has_css_class("stage-action"); }, actions);
|
||||
check(actions.size() == 3, "with a move up, a move down and a remove action");
|
||||
auto* first = chainList->get_row_at_index(0);
|
||||
auto* firstUp = withTooltip(*first, "Move up");
|
||||
auto* lastDown = withTooltip(*second, "Move down");
|
||||
check(firstUp != nullptr && !firstUp->get_sensitive(), "the first stage cannot move up");
|
||||
check(lastDown != nullptr && !lastDown->get_sensitive(), "the last stage cannot move down");
|
||||
|
||||
auto* up = withTooltip(*second, "Move up");
|
||||
check(up != nullptr, "the second stage has Move up");
|
||||
if (up != nullptr) press(*up);
|
||||
check(rowTitle(*chainList, 0) == "1. Scanlines" && rowTitle(*chainList, 1) == "2. Blur",
|
||||
"Move up swaps the stages");
|
||||
check(chainList->get_selected_row() == chainList->get_row_at_index(0),
|
||||
"and the moved stage stays selected");
|
||||
check(sources->get_visible(), "a chain led by scanlines shows the sources");
|
||||
|
||||
auto* remove = withTooltip(*chainList->get_row_at_index(0), "Remove");
|
||||
if (remove != nullptr) press(*remove);
|
||||
check(rowCount(*chainList) == 1 && rowTitle(*chainList, 0) == "1. Blur",
|
||||
"Remove drops the stage and renumbers the rest");
|
||||
check(!sources->get_visible(), "and the sources hide again");
|
||||
|
||||
std::cout << "drag and drop\n";
|
||||
addFromMenu(*add, "Scanlines");
|
||||
for (const auto& effect : effects) {
|
||||
if (effect->title() != "Blur" && effect->title() != "Scanlines") {
|
||||
addFromMenu(*add, effect->title());
|
||||
break;
|
||||
}
|
||||
}
|
||||
GtkDropTarget* drop = chainDropTarget(*chainList);
|
||||
check(drop != nullptr, "the chain list takes drops");
|
||||
if (drop != nullptr && rowCount(*chainList) == 3) {
|
||||
const std::string first = rowTitle(*chainList, 0).substr(3);
|
||||
const std::string second = rowTitle(*chainList, 1).substr(3);
|
||||
const std::string third = rowTitle(*chainList, 2).substr(3);
|
||||
const double bottom = chainList->get_row_at_index(2)->get_height() * 3.0;
|
||||
GdkDragAction action = GDK_ACTION_NONE;
|
||||
g_signal_emit_by_name(drop, "motion", 1.0, bottom, &action);
|
||||
check(chainList->get_row_at_index(2)->has_css_class("drop-after"),
|
||||
"dragging past the last row marks its bottom edge");
|
||||
dropStage(drop, 0, bottom);
|
||||
pump();
|
||||
check(rowTitle(*chainList, 0) == "1. " + second && rowTitle(*chainList, 1) == "2. " + third &&
|
||||
rowTitle(*chainList, 2) == "3. " + first,
|
||||
"dropping the first stage past the last moves it to the end");
|
||||
check(chainList->get_selected_row() == chainList->get_row_at_index(2),
|
||||
"and selects it");
|
||||
check(!chainList->get_row_at_index(2)->has_css_class("drop-after"),
|
||||
"and clears the mark");
|
||||
dropStage(drop, 2, 1.0);
|
||||
pump();
|
||||
check(rowTitle(*chainList, 0) == "1. " + first && rowTitle(*chainList, 1) == "2. " + second,
|
||||
"dropping on the top edge of the first row moves it to the front");
|
||||
}
|
||||
for (int i = rowCount(*chainList) - 1; i > 0; --i) {
|
||||
if (auto* removeRow = withTooltip(*chainList->get_row_at_index(i), "Remove")) press(*removeRow);
|
||||
}
|
||||
|
||||
std::cout << "many stages\n";
|
||||
for (int i = 0; i < 4; ++i) addFromMenu(*add, effects[static_cast<std::size_t>(i) % effects.size()]->title());
|
||||
pump();
|
||||
const int fewSplit = split != nullptr ? split->get_position() : -1;
|
||||
check(split != nullptr && fewSplit > emptySplit,
|
||||
"the split moves down as the chain grows");
|
||||
for (int i = 4; i < 12; ++i) addFromMenu(*add, effects[static_cast<std::size_t>(i) % effects.size()]->title());
|
||||
check(rowCount(*chainList) == 13, "the menu still works with a long chain");
|
||||
check(addFromMenu(*add, effects.back()->title()) && rowCount(*chainList) == 14,
|
||||
"including for the last effect in the menu");
|
||||
pump();
|
||||
const int longSplit = split != nullptr ? split->get_position() : -1;
|
||||
check(longSplit > fewSplit && listScroller != nullptr &&
|
||||
listScroller->get_height() <= listScroller->get_max_content_height() + 2,
|
||||
"up to the cap, past which the list scrolls");
|
||||
if (split != nullptr) split->set_position(emptySplit + 20);
|
||||
pump();
|
||||
addFromMenu(*add, effects.front()->title());
|
||||
pump();
|
||||
check(split != nullptr && split->get_position() == emptySplit + 20,
|
||||
"once dragged, the split stays put as the chain grows");
|
||||
|
||||
// With the split dragged all the way down, the button must still work.
|
||||
if (split != nullptr) split->set_position(10000);
|
||||
pump();
|
||||
add->popup();
|
||||
pump();
|
||||
check(menu->get_mapped(), "the menu opens with the split dragged to the bottom");
|
||||
add->popdown();
|
||||
pump();
|
||||
}
|
||||
|
||||
// The labels of the entries under the "Open Recent" submenu of `model`, or
|
||||
// nothing when there is no such submenu.
|
||||
void recentLabels(GMenuModel* model, std::vector<std::string>& out, bool& found) {
|
||||
for (int i = 0; i < g_menu_model_get_n_items(model); ++i) {
|
||||
char* label = nullptr;
|
||||
g_menu_model_get_item_attribute(model, i, G_MENU_ATTRIBUTE_LABEL, "s", &label);
|
||||
const std::string text = label != nullptr ? label : "";
|
||||
g_free(label);
|
||||
if (GMenuModel* section = g_menu_model_get_item_link(model, i, G_MENU_LINK_SECTION)) {
|
||||
recentLabels(section, out, found);
|
||||
g_object_unref(section);
|
||||
}
|
||||
if (GMenuModel* submenu = g_menu_model_get_item_link(model, i, G_MENU_LINK_SUBMENU)) {
|
||||
if (text == "Open Recent") {
|
||||
found = true;
|
||||
for (int j = 0; j < g_menu_model_get_n_items(submenu); ++j) {
|
||||
char* entry = nullptr;
|
||||
g_menu_model_get_item_attribute(submenu, j, G_MENU_ATTRIBUTE_LABEL, "s", &entry);
|
||||
out.emplace_back(entry != nullptr ? entry : "");
|
||||
g_free(entry);
|
||||
}
|
||||
}
|
||||
g_object_unref(submenu);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> recentEntries(Gtk::Window& window) {
|
||||
std::vector<Gtk::MenuButton*> buttons;
|
||||
collect<Gtk::MenuButton>(window, [](Gtk::MenuButton& b) { return b.get_tooltip_text() == "Project menu"; },
|
||||
buttons);
|
||||
std::vector<std::string> labels;
|
||||
bool found = false;
|
||||
if (buttons.empty()) return labels;
|
||||
auto* popover = dynamic_cast<Gtk::PopoverMenu*>(buttons.front()->get_popover());
|
||||
if (popover == nullptr || !popover->get_menu_model()) return labels;
|
||||
recentLabels(popover->get_menu_model()->gobj(), labels, found);
|
||||
if (!found) labels.emplace_back("<no Open Recent submenu>");
|
||||
return labels;
|
||||
}
|
||||
|
||||
// The version and the changelog, each a menu entry away.
|
||||
void testHelpWindows(Gtk::Window& window) {
|
||||
std::cout << "changelog and about\n";
|
||||
auto toplevel = [](const std::string& title) -> Gtk::Window* {
|
||||
for (auto* w : Gtk::Window::list_toplevels()) {
|
||||
if (w->get_title() == title && w->get_visible()) return w;
|
||||
}
|
||||
return nullptr;
|
||||
};
|
||||
|
||||
window.activate_action("win.show-changelog");
|
||||
pump(200);
|
||||
auto* changelog = toplevel("Changelog");
|
||||
check(changelog != nullptr, "Changelog opens a window");
|
||||
auto* text = changelog != nullptr ? named<Gtk::TextView>(*changelog, "changelog") : nullptr;
|
||||
const std::string shown = text != nullptr ? std::string(text->get_buffer()->get_text()) : "";
|
||||
check(shown.find(std::string(effector::kVersion) + " — ") != std::string::npos,
|
||||
"listing this version as a release");
|
||||
check(shown.find("[") == std::string::npos && shown.find("`") == std::string::npos &&
|
||||
shown.find("### ") == std::string::npos,
|
||||
"with the Markdown laid out rather than shown");
|
||||
if (changelog != nullptr) changelog->close();
|
||||
pump(50);
|
||||
check(toplevel("Changelog") == nullptr, "and closes");
|
||||
|
||||
window.activate_action("win.about");
|
||||
pump(200);
|
||||
Gtk::AboutDialog* about = nullptr;
|
||||
for (auto* w : Gtk::Window::list_toplevels()) {
|
||||
if (auto* dialog = dynamic_cast<Gtk::AboutDialog*>(w); dialog != nullptr && dialog->get_visible()) {
|
||||
about = dialog;
|
||||
}
|
||||
}
|
||||
check(about != nullptr && about->get_version() == std::string(effector::kVersion),
|
||||
"About Effector shows the version");
|
||||
if (about != nullptr) about->close();
|
||||
pump(50);
|
||||
}
|
||||
|
||||
void testRecentProjects(Gtk::Window& window, const std::filesystem::path& dir) {
|
||||
std::cout << "recent projects\n";
|
||||
check(recentEntries(window) == std::vector<std::string>{"No Recent Projects"},
|
||||
"Open Recent starts out empty");
|
||||
|
||||
// Two projects of the same name in different folders, and a third.
|
||||
std::filesystem::create_directories(dir / "first");
|
||||
std::filesystem::create_directories(dir / "second");
|
||||
const std::filesystem::path paths[] = {dir / "first" / "my_look.json", dir / "second" / "my_look.json",
|
||||
dir / "other.json"};
|
||||
effector::Project project;
|
||||
project.stages.push_back({effector::effectByName("blur"), {}}); // renders with no sources
|
||||
for (const auto& path : paths) {
|
||||
effector::saveProject(path.string(), project);
|
||||
window.activate_action("win.open-recent",
|
||||
Glib::Variant<Glib::ustring>::create(Glib::filename_to_uri(path.string())));
|
||||
pump(50);
|
||||
}
|
||||
pump(500); // the recent list is written, and announced, from an idle
|
||||
check(window.get_title() == "other — Effector", "an entry opens its project");
|
||||
const auto labels = recentEntries(window);
|
||||
check(labels == std::vector<std::string>{"other", "my__look (second)", "my__look (first)"},
|
||||
"opened projects are listed newest first, a shared name with its folder");
|
||||
}
|
||||
|
||||
// Visible labels in the params grid saying `text`.
|
||||
bool showsLabel(Gtk::Widget& root, const std::string& text) {
|
||||
for (auto* label : all<Gtk::Label>(root)) {
|
||||
if (label->get_text() == text && label->is_drawable()) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void testVideo(Gtk::Window& window, const std::filesystem::path& dir) {
|
||||
std::cout << "video\n";
|
||||
std::filesystem::create_directories(dir);
|
||||
const auto path = dir / "moving.json";
|
||||
effector::Project project;
|
||||
project.stages.push_back({effector::effectByName("channelsplit"), {}}); // needs no sources
|
||||
effector::saveProject(path.string(), project);
|
||||
window.activate_action("win.open-recent",
|
||||
Glib::Variant<Glib::ustring>::create(Glib::filename_to_uri(path.string())));
|
||||
pump(300);
|
||||
|
||||
auto* stack = all<Gtk::Stack>(window).front();
|
||||
auto* toggle = named<Gtk::Switch>(window, "video");
|
||||
auto* preset = named<Gtk::DropDown>(window, "video-preset");
|
||||
auto* duration = named<Gtk::SpinButton>(window, "video-duration");
|
||||
auto* width = named<Gtk::SpinButton>(window, "canvas-width");
|
||||
auto* height = named<Gtk::SpinButton>(window, "canvas-height");
|
||||
auto* playback = named<Gtk::Box>(window, "playback");
|
||||
check(toggle != nullptr && preset != nullptr && duration != nullptr && width != nullptr &&
|
||||
height != nullptr && playback != nullptr,
|
||||
"the video switch, its settings and the playback bar are there");
|
||||
if (toggle == nullptr || preset == nullptr || duration == nullptr || width == nullptr ||
|
||||
height == nullptr || playback == nullptr) {
|
||||
return;
|
||||
}
|
||||
check(isAncestor(*stack->get_child_by_name("setup"), *toggle), "the video switch is on Setup");
|
||||
check(!toggle->get_active() && !preset->is_drawable() && !playback->get_visible(),
|
||||
"a still project shows no video settings and no playback");
|
||||
check(!showsLabel(window, "Wobble"), "and no motion params for the channel split");
|
||||
|
||||
toggle->set_active(true);
|
||||
pump(200);
|
||||
check(showsLabel(window, "Wobble") && showsLabel(window, "Tracking bar"),
|
||||
"a video shows the channel split's motion params");
|
||||
stack->set_visible_child("setup");
|
||||
pump(100);
|
||||
check(preset->is_drawable() && duration->is_drawable(), "and its preset and length");
|
||||
|
||||
preset->set_selected(1); // Instagram story, the first preset
|
||||
pump(200);
|
||||
check(width->get_value() == 1080 && height->get_value() == 1920 && duration->get_value() == 15,
|
||||
"Instagram story picks a 1080 × 1920 canvas and 15 s");
|
||||
duration->set_value(0.5);
|
||||
pump(100);
|
||||
check(preset->get_selected() == 0, "changing the length drops the preset to Custom");
|
||||
|
||||
for (int waited = 0; waited < 200 && !playback->get_visible(); ++waited) pump(50);
|
||||
check(playback->get_visible(), "the clip is rendered and plays in the preview");
|
||||
auto* scale = all<Gtk::Scale>(*playback).empty() ? nullptr : all<Gtk::Scale>(*playback).front();
|
||||
const double before = scale != nullptr ? scale->get_value() : -1.0;
|
||||
pump(250);
|
||||
check(scale != nullptr && scale->get_value() != before, "and it moves on by itself");
|
||||
|
||||
window.activate_action("win.save-project");
|
||||
pump(100);
|
||||
const auto saved = effector::loadProject(path.string());
|
||||
check(saved.video.enabled && saved.video.duration == 0.5 && saved.width == 1080,
|
||||
"the project is saved as a video");
|
||||
|
||||
toggle->set_active(false);
|
||||
pump(300);
|
||||
check(!playback->get_visible() && !showsLabel(window, "Wobble"),
|
||||
"switched back to a still, the playback and motion params go");
|
||||
stack->set_visible_child("chain");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
// A crash should still leave every check before it on the screen.
|
||||
std::cout << std::unitbuf;
|
||||
const char* x11 = std::getenv("DISPLAY");
|
||||
const char* wayland = std::getenv("WAYLAND_DISPLAY");
|
||||
if ((x11 == nullptr || *x11 == '\0') && (wayland == nullptr || *wayland == '\0')) {
|
||||
std::cout << "no display, skipped\n";
|
||||
return 77;
|
||||
}
|
||||
|
||||
// Keep the projects the tests open out of the user's own recent list.
|
||||
std::string dataTemplate = (std::filesystem::temp_directory_path() / "effector-gui-XXXXXX").string();
|
||||
const std::filesystem::path dataDir = g_mkdtemp(dataTemplate.data());
|
||||
g_setenv("XDG_DATA_HOME", dataDir.c_str(), TRUE);
|
||||
|
||||
auto app = Gtk::Application::create("org.effector.GuiTests",
|
||||
Gio::Application::Flags::NON_UNIQUE);
|
||||
app->signal_activate().connect([&app, &dataDir] {
|
||||
auto window = std::make_unique<effector::EffectorWindow>(effector::Options{});
|
||||
app->add_window(*window);
|
||||
window->present();
|
||||
pump(300);
|
||||
runTests(*window);
|
||||
testHelpWindows(*window);
|
||||
testRecentProjects(*window, dataDir / "projects");
|
||||
testVideo(*window, dataDir / "video");
|
||||
app->remove_window(*window);
|
||||
});
|
||||
const int status = app->run(argc > 0 ? 1 : 0, argv);
|
||||
std::filesystem::remove_all(dataDir);
|
||||
if (status != 0) return status;
|
||||
std::cout << (failures == 0 ? "all passed\n" : std::to_string(failures) + " failed\n");
|
||||
return failures;
|
||||
}
|
||||
Reference in New Issue
Block a user