Snapshot of the Umamo working tree as it is

Uploaded as-is from /home/litruv/dev/vtsmaker/umamo on 2026-11-03. 1347 files.
Includes the uncommitted work in progress in :edit, :runtime, and :ui, and the
untracked files under module/edit/src/jvmAndroidMain/.

History is not carried over. The source repo is https://github.com/umamoorg/umamo.
This commit is contained in:
litruv
2026-11-03 18:20:25 +11:00
commit 8bd8fa7a0b
1347 changed files with 246161 additions and 0 deletions
@@ -0,0 +1,124 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
/** The brush radius (viewport px) a freshly armed Circle-select tool starts at. */
const val DEFAULT_CIRCLE_RADIUS_PX: Float = 40f
/** The smallest Circle-select brush radius (viewport px); the wheel / numpad clamp to it. */
const val MIN_CIRCLE_RADIUS_PX: Float = 5f
/** The largest Circle-select brush radius (viewport px); the wheel / numpad clamp to it. */
const val MAX_CIRCLE_RADIUS_PX: Float = 500f
/** How much one wheel notch or numpad +/- press changes the Circle-select radius (viewport px). */
const val CIRCLE_RADIUS_STEP_PX: Float = 8f
/**
* One endpoint of a staged Add Vertex draft edge: either an existing mesh vertex or a draft vert index.
*/
sealed interface DraftEndpoint {
/** An existing mesh vertex that the draft chain touches. */
data class Existing(val vertexIndex: Int) : DraftEndpoint
/** A floating draft vertex (index into [ActiveSelectTool.AddVertex.verts]). */
data class Draft(val index: Int) : DraftEndpoint
}
/**
* An undirected draft edge between two [DraftEndpoint]s (canonicalized so [a] <= [b] by kind then index).
*
* @property DraftEndpoint a One endpoint.
* @property DraftEndpoint b The other endpoint.
*/
data class DraftEdge(val a: DraftEndpoint, val b: DraftEndpoint) {
companion object {
/**
* Builds a canonical undirected draft edge for two endpoints in either order.
*
* @return DraftEdge? The edge, or null when both ends are the same endpoint.
*/
fun of(endpointA: DraftEndpoint, endpointB: DraftEndpoint): DraftEdge? {
if (endpointA == endpointB) {
return null
}
return if (endpointRank(endpointA) <= endpointRank(endpointB)) {
DraftEdge(endpointA, endpointB)
} else {
DraftEdge(endpointB, endpointA)
}
}
private fun endpointRank(endpoint: DraftEndpoint): Long =
when (endpoint) {
is DraftEndpoint.Existing -> endpoint.vertexIndex.toLong()
is DraftEndpoint.Draft -> (1L shl 32) or endpoint.index.toLong()
}
}
}
/**
* One staged floating vertex in an Add Vertex draft: a free world point, or snapped to an existing edge.
*
* @property Float x World x.
* @property Float y World y.
* @property MeshElement.Edge? snapEdge The edge this vert snaps to, or null for a free float.
* @property Float snapT The parameter along [snapEdge] (ignored when free).
*/
data class DraftVert(
val x: Float,
val y: Float,
val snapEdge: MeshElement.Edge? = null,
val snapT: Float = 0.5f,
)
/**
* A latched Edit-mode selection / geometry tool the gizmo overlay drives - the selection-gesture analog of
* [MeshOperatorKind]. Null when no tool is armed (a plain click selects and an empty drag rubber-bands a
* box); a command latches one and the overlay reads it to reinterpret pointer input. Transient editor
* state, never snapshotted and never on the change bus, exactly like [EditorSession.activeMeshOperator].
*/
sealed interface ActiveSelectTool {
/**
* The viewport area that armed the tool (an opaque workspace-leaf id, the [ActiveOperator]
* currency): only the arming area's overlay drives the gesture, so an armed brush in one split
* viewport stays inert everywhere else.
*/
val areaId: String
/**
* Blender's B box select: the overlay shows full-viewport crosshair guides and the next drag rubber-bands
* a box (ignoring element hit-tests), then the tool disarms (one-shot).
*
* @property String areaId The arming viewport's area id.
*/
data class BoxArmed(override val areaId: String) : ActiveSelectTool
/**
* Blender's C circle select: a brush circle of [radiusPx] follows the cursor; a primary drag paints
* selection, a middle or Shift+primary drag erases, the wheel and numpad +/- resize it, and Esc / RMB /
* Enter leave the tool.
*
* @property Float radiusPx The brush radius in viewport pixels.
* @property String areaId The arming viewport's area id.
*/
data class Circle(val radiusPx: Float, override val areaId: String) : ActiveSelectTool
/**
* Cubism-style Add Vertex draft: clicks place floating verts (auto-edged from the tip) without touching
* the document; Enter accepts into the mesh; Esc / empty RMB discards; RMB on a draft vert deletes it.
*
* @property String areaId The arming viewport's area id.
* @property DrawableId drawableId The session mesh the draft targets.
* @property List<DraftVert> verts Staged floating verts (document-untouched).
* @property List<DraftEdge> edges Auto-chained draft edges between tips.
* @property DraftEndpoint? tip The chain tip for the next auto-edge, or null before the first click.
*/
data class AddVertex(
override val areaId: String,
val drawableId: DrawableId,
val verts: List<DraftVert> = emptyList(),
val edges: List<DraftEdge> = emptyList(),
val tip: DraftEndpoint? = null,
) : ActiveSelectTool
}
@@ -0,0 +1,193 @@
package org.umamo.edit
import org.umamo.runtime.model.AtlasPlacement
import org.umamo.runtime.model.AtlasTileId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.composeAffine
import org.umamo.runtime.model.placementAffine
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.hypot
import kotlin.math.sin
/*
* The placement gizmo's model math: how a gesture affine measured on the page rewrites one tile's
* translation / rotation / scale, the page-space affines the three operators build, and which tiles
* a selection moves. Pure over :runtime, so the overlay that drives the gesture, the commit, and the
* tests all read one algebra - a placement written by one rule and previewed by another is exactly the
* drift the gizmo must not have.
*
* Every affine here is the runtime's 2x3 row-major form (m00, m01, m02, m10, m11, m12) over PAGE
* pixels, y down, the frame AtlasPlacement is expressed in.
*/
/**
* How far from orthogonal a composed affine's axes may be (normalized) before it stops being a
* translation / rotation / scale and becomes a shear no placement can express.
*/
private const val PLACEMENT_SHEAR_TOLERANCE = 1e-4f
/**
* This placement with [pageAffine] applied on top - the placement whose forward transform is
* `pageAffine . placementAffine(this)` - or null when that product is not a placement.
*
* A placement is translation / rotation / scale and nothing else, so only a similarity (translate,
* rotate, uniform scale) or a scale along the tile's own axes composes onto one exactly; a non-uniform
* scale along the page's axes shears a rotated tile, which no placement can carry. Refusing beats
* writing the closest placement, which would visibly re-point every mesh bound to the tile.
*
* The scale signs follow the receiver's, so a mirrored import stays mirrored through a move rather
* than flipping into a half-turn with positive scales (both describe the same pixels, but the export
* should write the file's own convention back). The rotation comes back normalized to (-180, 180].
*
* @param FloatArray pageAffine The gesture's transform in page pixels, applied after the placement.
* @return AtlasPlacement? The composed placement, or null when the product is not TRS-expressible or
* degenerate.
*/
fun AtlasPlacement.composedWith(pageAffine: FloatArray): AtlasPlacement? {
val composed = composeAffine(pageAffine, placementAffine(this))
val columnX0 = composed[0]
val columnX1 = composed[3]
val columnY0 = composed[1]
val columnY1 = composed[4]
val lengthX = hypot(columnX0, columnX1)
val lengthY = hypot(columnY0, columnY1)
if (lengthX == 0f || lengthY == 0f) {
return null
}
// The two columns are the rotated, scaled unit axes; a placement keeps them perpendicular.
val shear = abs(columnX0 * columnY0 + columnX1 * columnY1) / (lengthX * lengthY)
if (shear > PLACEMENT_SHEAR_TOLERANCE) {
return null
}
// The rotation is read off the x axis, negated back when that axis carries a mirror so the
// receiver's sign convention survives; the y scale is then the y axis projected onto the rotated
// y direction, which carries its own sign.
val signX = if (scaleX < 0f) -1f else 1f
val radians = atan2(columnX1 * signX, columnX0 * signX)
val cosine = cos(radians)
val sine = sin(radians)
val scaleYSigned = columnY1 * cosine - columnY0 * sine
return AtlasPlacement(
pageIndex = pageIndex,
positionX = composed[2],
positionY = composed[5],
scaleX = lengthX * signX,
scaleY = scaleYSigned,
rotationDegrees = (radians * 180.0 / PI).toFloat(),
)
}
/**
* The page-space translation by ([deltaX], [deltaY]).
*
* @param Float deltaX The horizontal move in page pixels.
* @param Float deltaY The vertical move in page pixels (positive is down).
* @return FloatArray The affine.
*/
fun translationAffine(deltaX: Float, deltaY: Float): FloatArray = floatArrayOf(1f, 0f, deltaX, 0f, 1f, deltaY)
/**
* The page-space rotation by [radians] about ([pivotX], [pivotY]), in the same sense
* [AtlasPlacement.rotationDegrees] uses - composing this onto a placement adds the angle to it.
*
* @param Float pivotX The pivot's x in page pixels.
* @param Float pivotY The pivot's y in page pixels.
* @param Float radians The angle.
* @return FloatArray The affine.
*/
fun rotationAboutAffine(pivotX: Float, pivotY: Float, radians: Float): FloatArray {
val cosine = cos(radians)
val sine = sin(radians)
return floatArrayOf(
cosine,
-sine,
pivotX - cosine * pivotX + sine * pivotY,
sine,
cosine,
pivotY - sine * pivotX - cosine * pivotY,
)
}
/**
* The page-space scale by ([factorX], [factorY]) about ([pivotX], [pivotY]), along the PAGE axes.
* Only a uniform factor composes onto a rotated placement; the axis-locked form for a rotated tile is
* [localAxisScaleAboutAffine].
*
* @param Float pivotX The pivot's x in page pixels.
* @param Float pivotY The pivot's y in page pixels.
* @param Float factorX The horizontal factor.
* @param Float factorY The vertical factor.
* @return FloatArray The affine.
*/
fun scaleAboutAffine(pivotX: Float, pivotY: Float, factorX: Float, factorY: Float): FloatArray =
floatArrayOf(factorX, 0f, pivotX - factorX * pivotX, 0f, factorY, pivotY - factorY * pivotY)
/**
* The page-space scale by ([factorX], [factorY]) about ([pivotX], [pivotY]) along [placement]'s OWN
* axes: `T(P) . R(rotation) . diag(factorX, factorY) . R(-rotation) . T(-P)`. This is the one
* axis-locked scale a rotated placement can express - it multiplies the placement's own scale pair and
* leaves its rotation alone - and for an unrotated placement it is the page-axis scale exactly.
*
* @param AtlasPlacement placement The placement whose axes the factors follow.
* @param Float pivotX The pivot's x in page pixels.
* @param Float pivotY The pivot's y in page pixels.
* @param Float factorX The factor along the tile's x axis.
* @param Float factorY The factor along the tile's y axis.
* @return FloatArray The affine.
*/
fun localAxisScaleAboutAffine(
placement: AtlasPlacement,
pivotX: Float,
pivotY: Float,
factorX: Float,
factorY: Float,
): FloatArray {
val radians = (placement.rotationDegrees.toDouble() * PI / 180.0).toFloat()
val intoTileAxes = rotationAboutAffine(pivotX, pivotY, -radians)
val scaled = scaleAboutAffine(pivotX, pivotY, factorX, factorY)
val outOfTileAxes = rotationAboutAffine(pivotX, pivotY, radians)
return composeAffine(outOfTileAxes, composeAffine(scaled, intoTileAxes))
}
/**
* The placed tiles under [selection]: every selected drawable's tile that is packed onto a page,
* pinned or not, in document order. A drawable over unpacked art has nothing on a page, and a part
* or deformer in the selection contributes nothing. The pin commands' domain - Unpin must find the
* pinned tiles - where a gesture reads the narrower [placementDragTileIds].
*
* @param Selection selection The session's object selection.
* @return Set<AtlasTileId> The placed tiles the selection covers, empty when there are none.
*/
fun PuppetModel.placementSelectedTileIds(selection: Selection): Set<AtlasTileId> {
val selectedIds = selection.targets.mapNotNullTo(HashSet()) { target -> (target as? SelectionTarget.Drawable)?.id }
if (selectedIds.isEmpty()) {
return emptySet()
}
val tileIds = LinkedHashSet<AtlasTileId>()
for (drawable in drawables) {
if (drawable.id !in selectedIds) {
continue
}
val tileId = drawable.atlasTileId ?: continue
if (atlas.tileById[tileId]?.placement == null) {
continue
}
tileIds.add(tileId)
}
return tileIds
}
/**
* The tiles a placement gesture over [selection] moves: the placed tiles under it
* ([placementSelectedTileIds]) minus the pinned ones. A pin means "keep this where it is", and a
* hand move is no exception - a pinned tile stays put until it is unpinned, and a gesture over a
* mixed selection moves the rest around it.
*
* @param Selection selection The session's object selection.
* @return Set<AtlasTileId> The movable placed tiles the selection covers, empty when there are none.
*/
fun PuppetModel.placementDragTileIds(selection: Selection): Set<AtlasTileId> =
placementSelectedTileIds(selection).filterTo(LinkedHashSet()) { tileId -> atlas.tileById[tileId]?.pinned != true }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,361 @@
package org.umamo.edit
import org.umamo.runtime.eval.meshGridDefaultDeltas
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.WarpLatticeForm
import org.umamo.runtime.model.partByDrawable
import kotlin.math.max
/*
* Creating warp deformers for a selection: mint a lattice fitted to the selected meshes' parent-local
* bounds at the default pose, bind those drawables under it, and remap their rest positions (and keyed
* mesh deltas) into the lattice's normalized UV so the art does not jump. Cubism's Create Warp
* Deformer, reduced to the default size/parent choices (armature root, padded AABB, 2×2 conversion
* divisions).
*
* Parent-local (not raw rest mesh) matters for Cubism-imported art under an existing warp: rest
* positions stay in canvas units while keyform deltas place the drawable in the parent's UV, and the
* new lattice must be authored in that same parent-local space or the overlay / cascade maps it off
* into oblivion.
*
* 選択メッシュに合わせたワープデフォーマの作成。格子生成・親子付け・UV再マップを1操作で行う。
*/
/** Default conversion-division count Cubism-style create uses for a new warp (→ 3×3 control points). */
private const val DEFAULT_WARP_DIVISIONS = 2
/** Padding around the selection AABB, as a fraction of each axis extent (so the lattice is not skin-tight). */
private const val LATTICE_PADDING_FRACTION = 0.05f
/** Floor for a degenerate (zero-size) selection axis so division by width / height stays defined. */
private const val MIN_LATTICE_EXTENT = 1e-3f
/**
* Mints a unused deformer id with [prefix] (then [prefix]2, [prefix]3, …), matching the parameter /
* parameter-group id minting style.
*
* @param String prefix The base id stem (e.g. "Warp").
* @return DeformerId A free id.
*/
fun PuppetModel.freshDeformerId(prefix: String = "Warp"): DeformerId {
val existing = deformers.map { deformer -> deformer.id }.toSet()
if (DeformerId(prefix) !in existing) {
return DeformerId(prefix)
}
var suffix = 2
while (DeformerId("$prefix$suffix") in existing) {
suffix++
}
return DeformerId("$prefix$suffix")
}
/**
* Builds a rectangular identity lattice covering [minX]..[maxX] × [minY]..[maxY] with
* ([rows]+1)×([columns]+1) control points, row-major (Y ascending), column-major within each row
* (X ascending) - the order [org.umamo.render.eval.warpInGrid] expects.
*
* @param Float minX Left edge.
* @param Float minY Bottom edge.
* @param Float maxX Right edge.
* @param Float maxY Top edge.
* @param Int rows Conversion divisions vertically.
* @param Int columns Conversion divisions horizontally.
* @return FloatArray Interleaved (x, y) control points.
*/
fun rectLatticeControlPoints(minX: Float, minY: Float, maxX: Float, maxY: Float, rows: Int, columns: Int): FloatArray {
val pointsPerRow = columns + 1
val pointsPerCol = rows + 1
val points = FloatArray(pointsPerRow * pointsPerCol * 2)
for (row in 0 until pointsPerCol) {
val y = minY + (maxY - minY) * (row.toFloat() / rows.coerceAtLeast(1))
for (col in 0 until pointsPerRow) {
val x = minX + (maxX - minX) * (col.toFloat() / columns.coerceAtLeast(1))
val index = (row * pointsPerRow + col) * 2
points[index] = x
points[index + 1] = y
}
}
return points
}
/**
* The drawable ids a warp-create gesture should wrap: mesh-carrying drawables reached from [selection]
* (a part expands to its outliner subtree). Already-parented meshes are included — create inserts the
* new warp under their shared parent (Cubism-style). When the selection spans more than one parent
* deformer, only the preferred parent's group is kept (the active drawable's parent when that is one
* of the candidates, otherwise the most common parent among candidates). Empty when nothing qualifies.
*
* @param Selection selection The object selection.
* @return List The drawable ids to wrap, in stable encounter order.
*/
fun PuppetModel.drawablesForWarpCreate(selection: Selection): List<DrawableId> {
val ids = LinkedHashSet<DrawableId>()
for (target in selection.targets) {
when (target) {
is SelectionTarget.Drawable -> ids.add(target.id)
is SelectionTarget.Part -> {
for (sub in subtreeTargets(target)) {
val drawable = sub as? SelectionTarget.Drawable ?: continue
ids.add(drawable.id)
}
}
is SelectionTarget.Deformer -> Unit
}
}
val candidates =
ids.mapNotNull { id ->
val drawable = drawables.firstOrNull { it.id == id } ?: return@mapNotNull null
if (drawable.mesh == null) {
null
} else {
drawable
}
}
if (candidates.isEmpty()) {
return emptyList()
}
val parentCounts = candidates.groupingBy { drawable -> drawable.parentDeformerId }.eachCount()
val activeParent =
(selection.active as? SelectionTarget.Drawable)?.let { active ->
candidates.firstOrNull { drawable -> drawable.id == active.id }?.parentDeformerId
}
val preferredParent =
if (activeParent != null && parentCounts.containsKey(activeParent)) {
activeParent
} else {
parentCounts.maxBy { entry -> entry.value }.key
}
return candidates.mapNotNull { drawable ->
if (drawable.parentDeformerId == preferredParent) drawable.id else null
}
}
/**
* Returns a copy of [this] with a new warp deformer [newId] named [name] wrapping [drawableIds]: the
* lattice is fitted to their combined parent-local AABB at the default pose (padded), the warp is
* parented under that shared parent, each drawable is rebound to the warp, and its rest positions plus
* keyed mesh deltas are remapped into the lattice's normalized UV so the art stays put. Refuses
* (returns this) when [newId] collides, [drawableIds] is empty, any named drawable is missing /
* mesh-less, or the drawables do not share one parent deformer.
*
* @param DeformerId newId The minted deformer id.
* @param String name The initial display name.
* @param List drawableIds The mesh drawables to wrap (must share one parent deformer, which may be null).
* @param Int rows Conversion divisions vertically (default 2 → 3 control-point rows).
* @param Int columns Conversion divisions horizontally (default 2 → 3 control-point columns).
* @return PuppetModel The model with the warp and rebound drawables, or this if refused.
*/
fun PuppetModel.withWarpDeformerCreatedForDrawables(
newId: DeformerId,
name: String,
drawableIds: List<DrawableId>,
rows: Int = DEFAULT_WARP_DIVISIONS,
columns: Int = DEFAULT_WARP_DIVISIONS,
): PuppetModel {
if (drawableIds.isEmpty() || deformers.any { it.id == newId }) {
return this
}
val targets =
drawableIds.mapNotNull { id ->
val drawable = drawables.firstOrNull { it.id == id } ?: return@mapNotNull null
val mesh = drawable.mesh ?: return@mapNotNull null
drawable to mesh
}
if (targets.size != drawableIds.size) {
return this
}
val sharedParent = targets.first().first.parentDeformerId
if (targets.any { (drawable, _) -> drawable.parentDeformerId != sharedParent }) {
return this
}
if (sharedParent != null && deformers.none { deformer -> deformer.id == sharedParent }) {
return this
}
val defaultValue: (ParameterId) -> Float = { id -> parameters.firstOrNull { it.id == id }?.default ?: 0f }
var minX = Float.POSITIVE_INFINITY
var minY = Float.POSITIVE_INFINITY
var maxX = Float.NEGATIVE_INFINITY
var maxY = Float.NEGATIVE_INFINITY
for ((drawable, mesh) in targets) {
val positions = parentLocalPositions(drawable, mesh.positions, defaultValue)
var index = 0
while (index + 1 < positions.size) {
val x = positions[index]
val y = positions[index + 1]
if (x < minX) minX = x
if (y < minY) minY = y
if (x > maxX) maxX = x
if (y > maxY) maxY = y
index += 2
}
}
if (!minX.isFinite() || !minY.isFinite() || !maxX.isFinite() || !maxY.isFinite()) {
return this
}
var width = max(maxX - minX, MIN_LATTICE_EXTENT)
var height = max(maxY - minY, MIN_LATTICE_EXTENT)
// Re-center a collapsed axis so a zero-extent selection still gets a real lattice around it.
if (maxX - minX < MIN_LATTICE_EXTENT) {
val mid = (minX + maxX) * 0.5f
minX = mid - width * 0.5f
maxX = mid + width * 0.5f
}
if (maxY - minY < MIN_LATTICE_EXTENT) {
val mid = (minY + maxY) * 0.5f
minY = mid - height * 0.5f
maxY = mid + height * 0.5f
}
val padX = width * LATTICE_PADDING_FRACTION
val padY = height * LATTICE_PADDING_FRACTION
minX -= padX
maxX += padX
minY -= padY
maxY += padY
width = maxX - minX
height = maxY - minY
val controlPoints = rectLatticeControlPoints(minX, minY, maxX, maxY, rows, columns)
val restGrid =
KeyformGrid(
emptyList(),
listOf(KeyformCell(IntArray(0), WarpLatticeForm(controlPoints))),
)
val ownerByDrawable = partByDrawable()
val partId: PartId? = drawableIds.firstOrNull()?.let { id -> ownerByDrawable[id] }
val warp =
Deformer.Warp(
id = newId,
name = name,
parent = sharedParent,
partId = partId,
rows = rows,
columns = columns,
isQuadTransform = true,
geometryGrid = restGrid,
)
val targetIds = drawableIds.toSet()
val newDrawables =
drawables.map { drawable ->
if (drawable.id !in targetIds) {
return@map drawable
}
val mesh = drawable.mesh ?: return@map drawable
val remappedPositions = remapPositionsToLatticeUv(mesh.positions, minX, minY, width, height)
val remappedGrid = drawable.geometryGrid?.let { grid -> remapMeshDeltaGrid(grid, width, height) }
drawable.copy(
parentDeformerId = newId,
mesh = DrawableMesh(remappedPositions, mesh.uvs, mesh.indices),
geometryGrid = remappedGrid,
)
}
return copy(deformers = deformers + warp, drawables = newDrawables)
}
/**
* Parent-local positions at the default pose: rest mesh plus the grid's default-pose deltas. Cubism
* art parented under a warp often keeps canvas units in the rest mesh and lands in parent UV only
* after those deltas - fitting / remapping must use this space, not the raw rest buffer.
*
* @param Drawable drawable The drawable (for its geometry grid).
* @param FloatArray rest Interleaved rest positions.
* @param Function defaultValue Default value per parameter id.
* @return FloatArray Parent-local interleaved positions (a copy when deltas apply).
*/
private fun parentLocalPositions(
drawable: Drawable,
rest: FloatArray,
defaultValue: (ParameterId) -> Float,
): FloatArray {
val deltas = meshGridDefaultDeltas(drawable, defaultValue) ?: return rest
val out = rest.copyOf()
val count = minOf(out.size, deltas.size)
for (index in 0 until count) {
out[index] += deltas[index]
}
return out
}
/**
* Remaps interleaved model-space positions into the lattice's normalized UV ([0,1]² over the fitted rect).
*
* @param FloatArray positions Interleaved (x, y) rest positions.
* @param Float minX Lattice left.
* @param Float minY Lattice bottom.
* @param Float width Lattice width.
* @param Float height Lattice height.
* @return FloatArray Fresh remapped positions.
*/
private fun remapPositionsToLatticeUv(positions: FloatArray, minX: Float, minY: Float, width: Float, height: Float): FloatArray {
val out = FloatArray(positions.size)
var index = 0
while (index + 1 < positions.size) {
out[index] = (positions[index] - minX) / width
out[index + 1] = (positions[index + 1] - minY) / height
index += 2
}
return out
}
/**
* Scales every cell's position deltas by the inverse lattice extent so keyed morphs stay correct after
* the rest mesh is remapped into UV.
*
* @param KeyformGrid grid The drawable's geometry grid.
* @param Float width Lattice width.
* @param Float height Lattice height.
* @return KeyformGrid The remapped grid.
*/
private fun remapMeshDeltaGrid(grid: KeyformGrid<MeshDeltaForm>, width: Float, height: Float): KeyformGrid<MeshDeltaForm> =
KeyformGrid(
grid.axes,
grid.cells.map { cell ->
val deltas = cell.form.positionDeltas
val remapped = FloatArray(deltas.size)
var index = 0
while (index + 1 < deltas.size) {
remapped[index] = deltas[index] / width
remapped[index + 1] = deltas[index + 1] / height
index += 2
}
KeyformCell(cell.coordinate.copyOf(), MeshDeltaForm(remapped))
},
)
/**
* Creates a warp deformer wrapping the mesh drawables in the current selection (parts expand to their
* subtree meshes; already-parented meshes insert the warp under their shared parent). One undo step;
* selects the new deformer and switches to Object mode on success so the lattice overlay is visible
* (it is Object-mode only). Emits a near-cursor notice and returns null when nothing in the selection
* can be wrapped.
*
* @param String name The initial display name.
* @return DeformerId? The new deformer's id, or null when the create was refused.
*/
fun EditorSession.createWarpDeformerForSelection(name: String): DeformerId? {
val drawableIds = model.value.drawablesForWarpCreate(selection.value)
if (drawableIds.isEmpty()) {
emitNotice("notice.deformer.createWarp.none", NoticePlacement.NearCursor)
return null
}
val id = model.value.freshDeformerId()
mutate(DeformerChange.Create(id)) { model ->
model.withWarpDeformerCreatedForDrawables(id, name, drawableIds)
}
if (model.value.deformers.none { it.id == id }) {
return null
}
// Lattice editing / drawing lives on the Object-mode overlay; stay there after create so the new
// warp is immediately visible and grab-able rather than only appearing in the outliner.
setMode(EditorMode.Object)
setSelection(Selection(setOf(SelectionTarget.Deformer(id)), SelectionTarget.Deformer(id)))
return id
}
@@ -0,0 +1,224 @@
package org.umamo.edit
import org.umamo.runtime.eval.invertPointsThroughWarpLattice
import org.umamo.runtime.eval.mapPointsThroughWarpLattice
import org.umamo.runtime.eval.rotationFormAt
import org.umamo.runtime.eval.warpControlPointsAt
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.RotationPivotForm
import org.umamo.runtime.model.WarpLatticeForm
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.sin
/*
* Keeping a deformer's authored geometry put in world space when its parent nesting changes: control
* points (and rotation pivots) live in immediate-parent-local space, so a reparent without conversion
* sends lattices flying (canvas CPs under a UV parent, or UV CPs promoted to root).
*/
/** Degrees → radians factor matching the renderer's PI_F-based conversion. */
private const val DEG_TO_RAD = 3.1415927f / 180f
/**
* Ancestor chain from [startParentId] up to the armature root (immediate parent first).
*
* @param DeformerId? startParentId The first ancestor, or null for an empty chain.
* @return List Deformers from near to far.
*/
private fun PuppetModel.ancestorChain(startParentId: DeformerId?): List<Deformer> {
if (startParentId == null) {
return emptyList()
}
val byId = deformers.associateBy { deformer -> deformer.id }
val chain = ArrayList<Deformer>()
val visited = HashSet<DeformerId>()
var current: DeformerId? = startParentId
while (current != null && visited.add(current)) {
val deformer = byId[current] ?: break
chain.add(deformer)
current = deformer.parent
}
return chain
}
/**
* Maps interleaved points from [startParentId]'s local space up to armature-root / canvas space by
* applying each ancestor's rest (default-pose) transform.
*
* @param DeformerId? startParentId Immediate parent (null = already root-local).
* @param FloatArray points Interleaved positions.
* @param Function defaultValue Default parameter sampler.
* @return FloatArray Root-local interleaved positions.
*/
private fun PuppetModel.mapToRootLocal(
startParentId: DeformerId?,
points: FloatArray,
defaultValue: (ParameterId) -> Float,
): FloatArray {
var current = points
for (ancestor in ancestorChain(startParentId)) {
current =
when (ancestor) {
is Deformer.Warp -> {
val cp = warpControlPointsAt(ancestor.geometryGrid, defaultValue) ?: continue
mapPointsThroughWarpLattice(current, cp, ancestor.columns, ancestor.rows, ancestor.isQuadTransform)
}
is Deformer.Rotation -> {
val form = rotationFormAt(ancestor.geometryGrid, defaultValue) ?: continue
mapPointsThroughRotation(current, form.originX, form.originY, form.angle, form.scale, ancestor.flipX, ancestor.flipY)
}
}
}
return current
}
/**
* Inverse of [mapToRootLocal]: root-local points → [startParentId]'s local space.
*
* @param DeformerId? startParentId Immediate parent (null = already root-local).
* @param FloatArray points Root-local interleaved positions.
* @param Function defaultValue Default parameter sampler.
* @return FloatArray Parent-local interleaved positions.
*/
private fun PuppetModel.mapFromRootLocal(
startParentId: DeformerId?,
points: FloatArray,
defaultValue: (ParameterId) -> Float,
): FloatArray {
var current = points
for (ancestor in ancestorChain(startParentId).asReversed()) {
current =
when (ancestor) {
is Deformer.Warp -> {
val cp = warpControlPointsAt(ancestor.geometryGrid, defaultValue) ?: continue
invertPointsThroughWarpLattice(current, cp, ancestor.columns, ancestor.rows, ancestor.isQuadTransform)
}
is Deformer.Rotation -> {
val form = rotationFormAt(ancestor.geometryGrid, defaultValue) ?: continue
invertPointsThroughRotation(current, form.originX, form.originY, form.angle, form.scale, ancestor.flipX, ancestor.flipY)
}
}
}
return current
}
/**
* Applies a rotation deformer's rest affine to interleaved points (same coefficient grouping as the
* renderer).
*/
private fun mapPointsThroughRotation(
points: FloatArray,
originX: Float,
originY: Float,
angleDegrees: Float,
scale: Float,
flipX: Boolean,
flipY: Boolean,
): FloatArray {
val radians = angleDegrees * DEG_TO_RAD
val sn = sin(radians.toDouble()).toFloat()
val cs = cos(radians.toDouble()).toFloat()
val fx = if (flipX) -1f else 1f
val fy = if (flipY) -1f else 1f
val c12 = cs * scale * fx
val c13 = fy * cs * scale
val c14 = fx * scale * sn
val c15 = -sn * scale * fy
val out = FloatArray(points.size)
var index = 0
while (index + 1 < points.size) {
val x = points[index]
val y = points[index + 1]
out[index] = c15 * y + c12 * x + originX
out[index + 1] = y * c13 + x * c14 + originY
index += 2
}
return out
}
/** Closed-form inverse of [mapPointsThroughRotation]. Degenerate determinants leave points unchanged. */
private fun invertPointsThroughRotation(
points: FloatArray,
originX: Float,
originY: Float,
angleDegrees: Float,
scale: Float,
flipX: Boolean,
flipY: Boolean,
): FloatArray {
val radians = angleDegrees * DEG_TO_RAD
val sn = sin(radians.toDouble()).toFloat()
val cs = cos(radians.toDouble()).toFloat()
val fx = if (flipX) -1f else 1f
val fy = if (flipY) -1f else 1f
val c12 = cs * scale * fx
val c13 = fy * cs * scale
val c14 = fx * scale * sn
val c15 = -sn * scale * fy
val determinant = c12 * c13 - c15 * c14
if (abs(determinant) < 1e-12f) {
return points.copyOf()
}
val out = FloatArray(points.size)
var index = 0
while (index + 1 < points.size) {
val relativeX = points[index] - originX
val relativeY = points[index + 1] - originY
out[index] = (relativeX * c13 - c15 * relativeY) / determinant
out[index + 1] = (c12 * relativeY - c14 * relativeX) / determinant
index += 2
}
return out
}
/**
* Rewrites [deformer]'s keyed geometry from [oldParentId]-local into [newParentId]-local so its world
* pose is unchanged by the reparent. Same-parent (reorder-only) returns [deformer] unchanged.
*
* @param Deformer deformer The deformer being moved (still carrying [oldParentId]).
* @param DeformerId? oldParentId Prior parent.
* @param DeformerId? newParentId Destination parent.
* @return Deformer Geometry-converted copy (parent field still the old one - caller sets the new parent).
*/
fun PuppetModel.withDeformerGeometryConvertedForReparent(
deformer: Deformer,
oldParentId: DeformerId?,
newParentId: DeformerId?,
): Deformer {
if (oldParentId == newParentId) {
return deformer
}
val defaultValue: (ParameterId) -> Float = { id -> parameters.firstOrNull { it.id == id }?.default ?: 0f }
return when (deformer) {
is Deformer.Warp -> {
val grid = deformer.geometryGrid ?: return deformer
val newCells =
grid.cells.map { cell ->
val rootLocal = mapToRootLocal(oldParentId, cell.form.controlPoints, defaultValue)
val newLocal = mapFromRootLocal(newParentId, rootLocal, defaultValue)
KeyformCell(cell.coordinate.copyOf(), WarpLatticeForm(newLocal))
}
deformer.copy(geometryGrid = KeyformGrid(grid.axes, newCells))
}
is Deformer.Rotation -> {
val grid = deformer.geometryGrid ?: return deformer
val newCells =
grid.cells.map { cell ->
val origin = floatArrayOf(cell.form.originX, cell.form.originY)
val rootLocal = mapToRootLocal(oldParentId, origin, defaultValue)
val newLocal = mapFromRootLocal(newParentId, rootLocal, defaultValue)
KeyformCell(
cell.coordinate.copyOf(),
RotationPivotForm(newLocal[0], newLocal[1], cell.form.angle, cell.form.scale),
)
}
deformer.copy(geometryGrid = KeyformGrid(grid.axes, newCells))
}
}
}
@@ -0,0 +1,357 @@
package org.umamo.edit
import org.umamo.runtime.eval.mapPointsThroughWarpLattice
import org.umamo.runtime.eval.meshGridDefaultDeltas
import org.umamo.runtime.eval.warpControlPointsAt
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.WarpLatticeForm
import org.umamo.runtime.model.withDerivedRenderRoot
/*
* Entity deletion over the org tree. Removing a drawable, a deformer, or a part scrubs every dangling
* reference so no later code dereferences a deleted id. Deleting an art mesh is the only inherently
* destructive case; deleting a deformer "unwraps" it (its sub-deformers and bound meshes re-home to its
* parent, with child coordinates baked through the deleted deformer's rest lattice so art stays put);
* deleting a part is either a cascade (the part and its whole subtree) or an ungroup (the folder only,
* contents spliced up into its parent). Org-tree edits re-derive the render order.
*
* Deformer delete never touches the organizational part tree - Cubism's "Apply deformer to child
* elements", not "Delete Deformer and its Content".
*/
/** A copy of this deformer re-nested under [newParent] in the transform hierarchy (used to re-home orphans). */
private fun Deformer.reparentedTo(newParent: DeformerId?): Deformer =
when (this) {
is Deformer.Warp -> copy(parent = newParent)
is Deformer.Rotation -> copy(parent = newParent)
}
/** A copy of this deformer re-bound to the organizational part [newPart] (or null to clear a dangling ref). */
private fun Deformer.reboundToPart(newPart: PartId?): Deformer =
when (this) {
is Deformer.Warp -> copy(partId = newPart)
is Deformer.Rotation -> copy(partId = newPart)
}
/**
* Returns a copy of [this] with every drawable in [ids] removed and every reference to them scrubbed: the
* drawables list, the org tree (their [OrgChild.Drawable] entries), any other drawable's clip mask, and any
* glue whose either partner was deleted. The render order is NOT re-derived here - the caller does that once
* it has finished its structural changes. An empty set returns the same instance.
*
* @param Set<DrawableId> ids The drawables to delete.
* @return PuppetModel The model with those drawables and their references gone.
*/
internal fun PuppetModel.removingDrawables(ids: Set<DrawableId>): PuppetModel {
if (ids.isEmpty()) {
return this
}
val remaining =
drawables.filterNot { drawable -> drawable.id in ids }
.map { drawable ->
val cleanedMasks = drawable.maskedBy.filterNot { maskId -> maskId in ids }
if (cleanedMasks.size != drawable.maskedBy.size) drawable.copy(maskedBy = cleanedMasks) else drawable
}
val cleanedGlues = glues.filterNot { glue -> glue.meshA in ids || glue.meshB in ids }
val cleanedRoot = rootChildren.filterNot { child -> child is OrgChild.Drawable && child.id in ids }
val cleanedParts =
parts.map { part ->
val kids = part.children.filterNot { child -> child is OrgChild.Drawable && child.id in ids }
if (kids.size != part.children.size) part.copy(children = kids) else part
}
return copy(drawables = remaining, glues = cleanedGlues, rootChildren = cleanedRoot, parts = cleanedParts)
}
/**
* Returns a copy of [this] with the single drawable [id] deleted (mask / glue / tree references scrubbed,
* render order re-derived). A no-op (no such drawable) returns the same instance.
*
* @param DrawableId id The drawable to delete.
* @return PuppetModel The model without that drawable, or [this] if it was absent.
*/
fun PuppetModel.withDrawableDeleted(id: DrawableId): PuppetModel {
if (drawables.none { it.id == id }) {
return this
}
return removingDrawables(setOf(id)).withDerivedRenderRoot()
}
/**
* Bakes a drawable that lived under a deleted warp into the warp's parent space: rest + every keyform
* absolute is mapped through the warp's rest lattice, then re-expressed as rest + deltas so default-pose
* art stays put. Does not change [Drawable.parentDeformerId] - the caller rebinds.
*
* @param Drawable drawable The child drawable.
* @param FloatArray cp Deleted warp's rest control points.
* @param Int columns Warp columns.
* @param Int rows Warp rows.
* @param Boolean bilinear Warp blend mode.
* @param Function defaultValue Default parameter values (for choosing the new rest).
* @return Drawable The baked drawable (same instance when mesh-less).
*/
private fun bakeDrawableThroughWarp(
drawable: Drawable,
cp: FloatArray,
columns: Int,
rows: Int,
bilinear: Boolean,
defaultValue: (ParameterId) -> Float,
): Drawable {
val mesh = drawable.mesh ?: return drawable
val rest = mesh.positions
val grid = drawable.geometryGrid
if (grid == null) {
val bakedRest = mapPointsThroughWarpLattice(rest, cp, columns, rows, bilinear)
return drawable.copy(mesh = DrawableMesh(bakedRest, mesh.uvs, mesh.indices))
}
val defaultDeltas = meshGridDefaultDeltas(drawable, defaultValue)
val defaultAbs =
if (defaultDeltas == null) {
rest
} else {
FloatArray(rest.size) { index -> rest[index] + (defaultDeltas.getOrNull(index) ?: 0f) }
}
val newRest = mapPointsThroughWarpLattice(defaultAbs, cp, columns, rows, bilinear)
val newCells =
grid.cells.map { cell ->
val deltas = cell.form.positionDeltas
val absolute =
FloatArray(rest.size) { index ->
rest[index] + (deltas.getOrNull(index) ?: 0f)
}
val warpedAbs = mapPointsThroughWarpLattice(absolute, cp, columns, rows, bilinear)
val newDeltas =
FloatArray(warpedAbs.size) { index ->
warpedAbs[index] - newRest[index]
}
KeyformCell(cell.coordinate.copyOf(), MeshDeltaForm(newDeltas))
}
return drawable.copy(
mesh = DrawableMesh(newRest, mesh.uvs, mesh.indices),
geometryGrid = KeyformGrid(grid.axes, newCells),
)
}
/**
* Bakes a child warp's rest lattice control points through a deleted parent warp.
*
* @param Deformer.Warp child The child warp.
* @param FloatArray parentCp Deleted parent's rest control points.
* @param Int parentColumns Parent columns.
* @param Int parentRows Parent rows.
* @param Boolean parentBilinear Parent blend mode.
* @param Function defaultValue Default parameter values.
* @return Deformer.Warp The baked child (reparent not applied).
*/
private fun bakeChildWarpThroughWarp(
child: Deformer.Warp,
parentCp: FloatArray,
parentColumns: Int,
parentRows: Int,
parentBilinear: Boolean,
defaultValue: (ParameterId) -> Float,
): Deformer.Warp {
val grid = child.geometryGrid ?: return child
val newCells =
grid.cells.map { cell ->
val baked =
mapPointsThroughWarpLattice(cell.form.controlPoints, parentCp, parentColumns, parentRows, parentBilinear)
KeyformCell(cell.coordinate.copyOf(), WarpLatticeForm(baked))
}
// Also ensure a 0-axis / default sample stays coherent when the grid is empty-axes rest-only.
val defaultCps = warpControlPointsAt(KeyformGrid(grid.axes, newCells), defaultValue)
if (defaultCps == null && newCells.isEmpty()) {
return child
}
return child.copy(geometryGrid = KeyformGrid(grid.axes, newCells))
}
/**
* Returns a copy of [this] with the deformer [id] deleted by unwrapping it: its child deformers and the
* drawables it deformed are baked through its rest transform into its own parent space (null = an
* armature root), then rebound there, so removing a transform wrapper never deletes art and never
* touches the organizational part tree. A no-op (no such deformer) returns the same instance.
*
* @param DeformerId id The deformer to delete.
* @return PuppetModel The model without that deformer, or [this] if it was absent.
*/
fun PuppetModel.withDeformerDeleted(id: DeformerId): PuppetModel {
val deformer = deformers.firstOrNull { it.id == id } ?: return this
val grandParent = deformer.parent
val defaultValue: (ParameterId) -> Float = { paramId -> parameters.firstOrNull { it.id == paramId }?.default ?: 0f }
val bakeWarp =
(deformer as? Deformer.Warp)?.let { warp ->
val cp = warpControlPointsAt(warp.geometryGrid, defaultValue) ?: return@let null
BakeWarp(cp, warp.columns, warp.rows, warp.isQuadTransform)
}
val updatedDeformers =
deformers.filter { it.id != id }
.map { other ->
val reparented = if (other.parent == id) other.reparentedTo(grandParent) else other
if (bakeWarp != null && other.parent == id && reparented is Deformer.Warp) {
bakeChildWarpThroughWarp(
reparented,
bakeWarp.cp,
bakeWarp.columns,
bakeWarp.rows,
bakeWarp.bilinear,
defaultValue,
)
} else {
reparented
}
}
val updatedDrawables =
drawables.map { drawable ->
if (drawable.parentDeformerId != id) {
return@map drawable
}
val baked =
if (bakeWarp != null) {
bakeDrawableThroughWarp(
drawable,
bakeWarp.cp,
bakeWarp.columns,
bakeWarp.rows,
bakeWarp.bilinear,
defaultValue,
)
} else {
drawable
}
baked.copy(parentDeformerId = grandParent)
}
return copy(deformers = updatedDeformers, drawables = updatedDrawables)
}
/** Rest lattice used to bake children when unwrapping a deleted warp. */
private data class BakeWarp(
val cp: FloatArray,
val columns: Int,
val rows: Int,
val bilinear: Boolean,
)
/** The set of part ids in [id]'s org-tree subtree (the part itself plus every descendant part). */
private fun PuppetModel.partSubtreeIds(id: PartId): Set<PartId> {
val partById = parts.associateBy { it.id }
val subtree = LinkedHashSet<PartId>()
val stack = ArrayDeque<PartId>()
stack.add(id)
while (stack.isNotEmpty()) {
val next = stack.removeLast()
if (!subtree.add(next)) {
continue
}
partById[next]?.children?.forEach { child -> if (child is OrgChild.Part) stack.add(child.id) }
}
return subtree
}
/**
* Returns a copy of [this] with the part [id] deleted. A [cascade] removes the whole subtree - the part,
* every descendant part, and every drawable under any of them (references scrubbed); an ungroup (cascade
* false) dissolves only the folder - its children (sub-parts and drawables) splice into its parent in
* place, so nothing is destroyed. The render order is re-derived. A no-op (no such part) returns the same
* instance.
*
* @param PartId id The part to delete.
* @param Boolean cascade True to delete the subtree, false to ungroup (keep contents, splice them up).
* @return PuppetModel The model with the part deleted, or [this] if it was absent.
*/
fun PuppetModel.withPartDeleted(id: PartId, cascade: Boolean): PuppetModel {
val part = parts.firstOrNull { it.id == id } ?: return this
val partRef = OrgChild.Part(id)
// The deleted part's parent (where ungrouped contents land / dangling deformer bindings fall back to).
val grandParentId = parts.firstOrNull { partRef in it.children }?.id
return if (cascade) {
val subtree = partSubtreeIds(id)
val doomedDrawables =
parts.filter { it.id in subtree }
.flatMap { it.children }
.filterIsInstance<OrgChild.Drawable>()
.map { it.id }
.toSet()
// Drop the subtree parts; detach the part ref from wherever it sits (root or its parent).
val remainingParts =
parts.filterNot { it.id in subtree }
.map { candidate -> if (partRef in candidate.children) candidate.copy(children = candidate.children - partRef) else candidate }
val cleanedRoot = rootChildren.filter { it != partRef }
// A deformer's organizational partId may point into the deleted subtree; clear it so nothing dangles.
val cleanedDeformers =
deformers.map { deformer ->
if (deformer.partId != null && deformer.partId in subtree) deformer.reboundToPart(null) else deformer
}
copy(parts = remainingParts, rootChildren = cleanedRoot, deformers = cleanedDeformers)
.removingDrawables(doomedDrawables)
.copy(rootPartId = if (rootPartId != null && rootPartId in subtree) null else rootPartId)
.withDerivedRenderRoot()
} else {
// Ungroup: replace the part ref with the part's own children, in place, wherever it sits.
fun splice(children: List<OrgChild>): List<OrgChild> = children.flatMap { if (it == partRef) part.children else listOf(it) }
val cleanedRoot = splice(rootChildren)
val remainingParts = parts.filterNot { it.id == id }.map { it.copy(children = splice(it.children)) }
val cleanedDeformers = deformers.map { deformer -> if (deformer.partId == id) deformer.reboundToPart(grandParentId) else deformer }
copy(
parts = remainingParts,
rootChildren = cleanedRoot,
deformers = cleanedDeformers,
rootPartId = if (rootPartId == id) grandParentId else rootPartId,
).withDerivedRenderRoot()
}
}
/**
* Deletes the drawable [id] as one undo step. A no-op records nothing.
*
* @param DrawableId id The drawable to delete.
*/
fun EditorSession.deleteDrawable(id: DrawableId) {
mutate(DrawableChange.Delete(id)) { model -> model.withDrawableDeleted(id) }
}
/**
* Deletes the deformer [id] (unwrapping it - children re-home to its parent with coordinates baked
* through) as one undo step. Never removes parts or art meshes.
*
* @param DeformerId id The deformer to delete.
*/
fun EditorSession.deleteDeformer(id: DeformerId) {
mutate(DeformerChange.Delete(id)) { model -> model.withDeformerDeleted(id) }
}
/**
* Deletes the part [id] as one undo step: a cascade (subtree) when [cascade], else an ungroup (contents spliced up).
*
* @param PartId id The part to delete.
* @param Boolean cascade True to delete the subtree, false to ungroup.
*/
fun EditorSession.deletePart(id: PartId, cascade: Boolean) {
mutate(PartChange.Delete(id, cascade)) { model -> model.withPartDeleted(id, cascade) }
}
/**
* Deletes the entity named by [target] as one undo step. [cascade] applies only to a part (a drawable or a
* deformer ignores it - a deformer always unwraps without destroying children).
*
* @param SelectionTarget target The entity to delete.
* @param Boolean cascade For a part, true to delete the subtree, false to ungroup; ignored otherwise.
*/
fun EditorSession.deleteTarget(target: SelectionTarget, cascade: Boolean) {
when (target) {
is SelectionTarget.Part -> deletePart(target.id, cascade)
is SelectionTarget.Drawable -> deleteDrawable(target.id)
is SelectionTarget.Deformer -> deleteDeformer(target.id)
}
}
@@ -0,0 +1,104 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.withDerivedRenderRoot
/**
* Duplicates one whole drawable (Object-mode Shift+D): the copy takes a Blender-style ".001"-suffixed
* unique id and name, a fresh mesh instance (positions copied so the copy edits independently;
* uvs / indices shared - the copy-on-write discipline), a re-wrapped keyform grid sharing the form
* payloads by reference (immutable in practice; a later edit copy-on-writes them), and its source's
* mask references. It sits immediately after its source in the org tree (or appends at the root when
* the source was never placed - the import safety net's rule), and carries NO glue membership: glues
* reference meshes by id, so a fresh id naturally welds nothing.
*
* 描画オブジェクトの複製。".001" 形式の一意な id と名前を付け、元の直後にツリー挿入する。
* グルーには参加しない。
*
* @param DrawableId id The drawable to duplicate.
* @return Pair<PuppetModel, DrawableId>? The edited model and the copy's id, or null when the source
* is missing or carries no mesh.
*/
fun PuppetModel.withDrawableDuplicated(id: DrawableId): Pair<PuppetModel, DrawableId>? {
val source = drawables.firstOrNull { candidate -> candidate.id == id } ?: return null
val mesh = source.mesh ?: return null
val copyId = uniqueDuplicateId(id)
val copy =
source.copy(
id = copyId,
name = uniqueDuplicateName(source.name),
mesh = DrawableMesh(mesh.positions.copyOf(), mesh.uvs, mesh.indices),
geometryGrid =
source.geometryGrid?.let { grid ->
KeyformGrid(grid.axes, grid.cells.map { cell -> KeyformCell(cell.coordinate, cell.form) })
},
// The atlas mapping is keyed by the source format's ids, so the copy resolves its texture
// through its source (or the original, when duplicating a duplicate).
textureSourceId = source.textureSourceId ?: source.id,
)
// Insert the copy immediately after its source, in whichever child list holds it.
var placed = false
fun insertAfterSource(children: List<OrgChild>): List<OrgChild> {
if (placed) {
return children
}
val sourceIndex = children.indexOfFirst { child -> child is OrgChild.Drawable && child.id == id }
if (sourceIndex < 0) {
return children
}
placed = true
return children.toMutableList().apply { add(sourceIndex + 1, OrgChild.Drawable(copyId)) }
}
val newRootChildren = insertAfterSource(rootChildren)
val newParts = parts.map { part -> if (placed) part else part.copy(children = insertAfterSource(part.children)) }
val finalRootChildren = if (placed) newRootChildren else newRootChildren + OrgChild.Drawable(copyId)
val edited =
copy(
drawables = drawables + copy,
parts = newParts,
rootChildren = finalRootChildren,
)
return edited.withDerivedRenderRoot().let { derived -> derived to copyId }
}
/**
* The first free ".NNN"-suffixed id derived from [id] (d -> d.001, d.002, ...), so repeated duplicates
* never collide.
*
* @param DrawableId id The source id.
* @return DrawableId The unique copy id.
*/
private fun PuppetModel.uniqueDuplicateId(id: DrawableId): DrawableId {
var counter = 1
while (true) {
val candidate = DrawableId("${id.raw}.${counter.toString().padStart(3, '0')}")
if (drawables.none { drawable -> drawable.id == candidate }) {
return candidate
}
counter++
}
}
/**
* The first free ".NNN"-suffixed display name derived from [name], mirroring [uniqueDuplicateId].
*
* @param String name The source display name.
* @return String The unique copy name.
*/
private fun PuppetModel.uniqueDuplicateName(name: String): String {
var counter = 1
while (true) {
val candidate = "$name.${counter.toString().padStart(3, '0')}"
if (drawables.none { drawable -> drawable.name == candidate }) {
return candidate
}
counter++
}
}
@@ -0,0 +1,17 @@
package org.umamo.edit
/**
* The editor's interaction mode, Blender-style. Object mode selects whole entities (parts, drawables,
* deformers) and shows the rendered puppet; Edit mode dives into the active entity's interior (mesh,
* warp lattice, or rotation pivot). The mode scopes hit-testing and tool behaviour. v1 implements
* Object fully and leaves Edit as a routed stub.
*
* エディタの操作モード(Blender 流)。オブジェクトモードは要素全体を選択し、編集モードは内部を編集する。
*/
enum class EditorMode {
/** Whole-entity selection and posing — the default. */
Object,
/** Interior editing of the active entity (stubbed in v1). */
Edit,
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,300 @@
package org.umamo.edit
import kotlin.math.abs
/**
* One of the eight Photoshop-style scale handles on an axis-aligned bounds box: four corners and four
* edge midpoints. Corner handles resize both axes; edge handles resize only the axis they sit on.
*
* World y is up (the viewport's displayed Z). Screen drawing maps through the camera; hit-testing is
* done in screen pixels by the overlay.
*/
enum class BoundsHandle {
MinXMinY,
MidXMinY,
MaxXMinY,
MinXMidY,
MaxXMidY,
MinXMaxY,
MidXMaxY,
MaxXMaxY,
;
/** True when dragging this handle changes the x extent. */
val affectsX: Boolean
get() = this != MidXMinY && this != MidXMaxY
/** True when dragging this handle changes the y extent. */
val affectsY: Boolean
get() = this != MinXMidY && this != MaxXMidY
}
/**
* Axis-aligned bounds of a selection, with explicit min/max corners. Prefer this over [MeshBounds]
* when a free-transform handle needs the fixed opposite edge as a pivot - center+extent alone forces
* every caller to re-derive the corners and risk off-by-half errors.
*
* @property Float minX The left edge (smallest x).
* @property Float minY The bottom edge in world space (smallest y; world y is up).
* @property Float maxX The right edge (largest x).
* @property Float maxY The top edge in world space (largest y).
*/
data class AxisAlignedBounds(
val minX: Float,
val minY: Float,
val maxX: Float,
val maxY: Float,
) {
val width: Float get() = maxX - minX
val height: Float get() = maxY - minY
val centerX: Float get() = (minX + maxX) * 0.5f
val centerY: Float get() = (minY + maxY) * 0.5f
val isEmpty: Boolean get() = width <= 0f && height <= 0f
/**
* The world-space position of [handle] on this box (corners and edge midpoints).
*
* @param BoundsHandle handle The handle.
* @return Pair The (x, y) world position.
*/
fun handleWorld(handle: BoundsHandle): Pair<Float, Float> =
when (handle) {
BoundsHandle.MinXMinY -> minX to minY
BoundsHandle.MidXMinY -> centerX to minY
BoundsHandle.MaxXMinY -> maxX to minY
BoundsHandle.MinXMidY -> minX to centerY
BoundsHandle.MaxXMidY -> maxX to centerY
BoundsHandle.MinXMaxY -> minX to maxY
BoundsHandle.MidXMaxY -> centerX to maxY
BoundsHandle.MaxXMaxY -> maxX to maxY
}
}
/**
* Axis-aligned bounds of the vertices in [indices] (or every vertex when [indices] is null / empty and
* [positions] is non-empty). Returns a zero box when there is nothing to measure.
*
* @param FloatArray positions Interleaved (x, y) positions.
* @param Set<Int>? indices Vertex indices to include, or null / empty for the whole array.
* @return AxisAlignedBounds The selection's AABB.
*/
fun selectionBounds(positions: FloatArray, indices: Set<Int>? = null): AxisAlignedBounds {
val pointCount = positions.size / 2
if (pointCount == 0) {
return AxisAlignedBounds(0f, 0f, 0f, 0f)
}
val cover =
if (indices.isNullOrEmpty()) {
null
} else {
indices
}
var minX = Float.POSITIVE_INFINITY
var minY = Float.POSITIVE_INFINITY
var maxX = Float.NEGATIVE_INFINITY
var maxY = Float.NEGATIVE_INFINITY
var found = false
if (cover == null) {
var slot = 0
while (slot + 1 < positions.size) {
val x = positions[slot]
val y = positions[slot + 1]
if (x < minX) minX = x
if (x > maxX) maxX = x
if (y < minY) minY = y
if (y > maxY) maxY = y
found = true
slot += 2
}
} else {
for (index in cover) {
if (index < 0 || index >= pointCount) {
continue
}
val x = positions[index * 2]
val y = positions[index * 2 + 1]
if (x < minX) minX = x
if (x > maxX) maxX = x
if (y < minY) minY = y
if (y > maxY) maxY = y
found = true
}
}
if (!found) {
return AxisAlignedBounds(0f, 0f, 0f, 0f)
}
return AxisAlignedBounds(minX, minY, maxX, maxY)
}
/**
* Combined axis-aligned bounds of several interleaved position arrays (optionally restricted per array).
* Used when Object-mode Scale wraps multiple drawables in one marquee.
*
* @param List<Pair<FloatArray, Set<Int>?>> sources Each (positions, indices-or-null-for-all) pair.
* @return AxisAlignedBounds The union AABB, or a zero box when every source is empty.
*/
fun unionSelectionBounds(sources: List<Pair<FloatArray, Set<Int>?>>): AxisAlignedBounds {
var minX = Float.POSITIVE_INFINITY
var minY = Float.POSITIVE_INFINITY
var maxX = Float.NEGATIVE_INFINITY
var maxY = Float.NEGATIVE_INFINITY
var found = false
for ((positions, indices) in sources) {
if (positions.size < 2) {
continue
}
val box = selectionBounds(positions, indices)
if (box.minX < minX) minX = box.minX
if (box.minY < minY) minY = box.minY
if (box.maxX > maxX) maxX = box.maxX
if (box.maxY > maxY) maxY = box.maxY
found = true
}
if (!found) {
return AxisAlignedBounds(0f, 0f, 0f, 0f)
}
return AxisAlignedBounds(minX, minY, maxX, maxY)
}
/**
* Per-axis scale factors and pivot for a Photoshop-style handle drag: the opposite edge/corner stays
* fixed (or the bounds center when [fromCenter] is set), and the dragged handle follows [targetX] /
* [targetY]. Degenerate axes (zero extent) yield factor 1 so a flat selection cannot explode.
*
* [uniform] (Shift) forces both factors to the dominant axis's factor on corner handles; edge handles
* stay single-axis.
*
* @param AxisAlignedBounds startBounds The selection AABB at gesture start.
* @param BoundsHandle handle The handle being dragged.
* @param Float targetX The pointer's world x (where the handle should land).
* @param Float targetY The pointer's world y.
* @param Boolean uniform Keep aspect ratio (corner drags).
* @param Boolean fromCenter Scale about the bounds center instead of the opposite side.
* @return Triple factorX, factorY, pivot (x, y).
*/
fun handleScaleFactors(
startBounds: AxisAlignedBounds,
handle: BoundsHandle,
targetX: Float,
targetY: Float,
uniform: Boolean,
fromCenter: Boolean,
): Triple<Float, Float, Pair<Float, Float>> {
val width = startBounds.width
val height = startBounds.height
val pivotX: Float
val pivotY: Float
var factorX = 1f
var factorY = 1f
if (fromCenter) {
pivotX = startBounds.centerX
pivotY = startBounds.centerY
if (handle.affectsX && width > 1e-6f) {
val startOffset =
when (handle) {
BoundsHandle.MinXMinY, BoundsHandle.MinXMidY, BoundsHandle.MinXMaxY -> -width * 0.5f
BoundsHandle.MaxXMinY, BoundsHandle.MaxXMidY, BoundsHandle.MaxXMaxY -> width * 0.5f
else -> width * 0.5f
}
factorX = (targetX - pivotX) / startOffset
}
if (handle.affectsY && height > 1e-6f) {
val startOffset =
when (handle) {
BoundsHandle.MinXMinY, BoundsHandle.MidXMinY, BoundsHandle.MaxXMinY -> -height * 0.5f
BoundsHandle.MinXMaxY, BoundsHandle.MidXMaxY, BoundsHandle.MaxXMaxY -> height * 0.5f
else -> height * 0.5f
}
factorY = (targetY - pivotY) / startOffset
}
} else {
pivotX =
when {
!handle.affectsX -> startBounds.centerX
handle == BoundsHandle.MinXMinY || handle == BoundsHandle.MinXMidY || handle == BoundsHandle.MinXMaxY ->
startBounds.maxX
else -> startBounds.minX
}
pivotY =
when {
!handle.affectsY -> startBounds.centerY
handle == BoundsHandle.MinXMinY || handle == BoundsHandle.MidXMinY || handle == BoundsHandle.MaxXMinY ->
startBounds.maxY
else -> startBounds.minY
}
if (handle.affectsX && width > 1e-6f) {
val startHandleX =
when (handle) {
BoundsHandle.MinXMinY, BoundsHandle.MinXMidY, BoundsHandle.MinXMaxY -> startBounds.minX
else -> startBounds.maxX
}
val startSpan = startHandleX - pivotX
if (abs(startSpan) > 1e-6f) {
factorX = (targetX - pivotX) / startSpan
}
}
if (handle.affectsY && height > 1e-6f) {
val startHandleY =
when (handle) {
BoundsHandle.MinXMinY, BoundsHandle.MidXMinY, BoundsHandle.MaxXMinY -> startBounds.minY
else -> startBounds.maxY
}
val startSpan = startHandleY - pivotY
if (abs(startSpan) > 1e-6f) {
factorY = (targetY - pivotY) / startSpan
}
}
}
if (uniform && handle.affectsX && handle.affectsY) {
// Dominant axis by how far the pointer pulled that side, measured in world units of the start box.
val pullX = abs(factorX - 1f) * width
val pullY = abs(factorY - 1f) * height
val shared = if (pullX >= pullY) factorX else factorY
factorX = shared
factorY = shared
}
return Triple(factorX, factorY, pivotX to pivotY)
}
/**
* Scales [indices] in [positions] so the dragged [handle] of [startBounds] follows ([targetX],
* [targetY]) - Photoshop free-transform scale. Pure: returns a new array (or the same instance when
* nothing moves).
*
* @param FloatArray positions Interleaved (x, y) positions.
* @param Set<Int> indices Vertices to scale.
* @param AxisAlignedBounds startBounds The selection AABB frozen at gesture start.
* @param BoundsHandle handle The handle under the pointer.
* @param Float targetX Pointer world x.
* @param Float targetY Pointer world y.
* @param Boolean uniform Shift: keep aspect ratio on corner drags.
* @param Boolean fromCenter Alt: scale about the bounds center.
* @return FloatArray The scaled positions.
*/
fun scaledByHandleDrag(
positions: FloatArray,
indices: Set<Int>,
startBounds: AxisAlignedBounds,
handle: BoundsHandle,
targetX: Float,
targetY: Float,
uniform: Boolean = false,
fromCenter: Boolean = false,
): FloatArray {
if (indices.isEmpty() || positions.size < 2) {
return positions
}
val (factorX, factorY, pivot) =
handleScaleFactors(startBounds, handle, targetX, targetY, uniform, fromCenter)
if (factorX == 1f && factorY == 1f) {
return positions
}
return MeshTransforms.scaleVerticesAxis(positions, indices, factorX, factorY, pivot.first, pivot.second)
}
@@ -0,0 +1,258 @@
package org.umamo.edit
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.KeyableTarget
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
/** The default cap on retained undo steps; the oldest is dropped past this (a memory backstop). */
const val DEFAULT_HISTORY_LIMIT: Int = 200
/**
* A pose: the live value of every parameter (the current scrub position the renderer deforms to). Held
* as ephemeral editor state outside [PuppetModel] - it is not document content (keyforms are), but it is
* snapshotted so a scrub is undoable. A small immutable map, so capturing one in a snapshot is cheap.
*
* ポーズ:各パラメータの現在値。ドキュメント内容ではない一時的な編集状態だが、スクラブを取り消せるよう保持。
*/
typealias Pose = Map<ParameterId, Float>
/**
* One undoable state: the document model plus the ephemeral editor state that rides with it. The
* interaction mode, the object-mode selection, the live pose, and the Edit-mode vertex selection are
* snapshotted here (not inside [PuppetModel]) so undo restores the mode (entering / leaving Edit is a
* real history step, not a guess), the prior selection after a misclick, the prior pose after a scrub,
* and the vertex selection after a mesh edit; a document edit also restores all of these as they were at
* that edit. Every field is an immutable value, so a snapshot is just a few references — cheap to keep
* and to restore.
*
* 取り消し可能な1状態:ドキュメントモデルと、それに付随するモード・選択・ポーズ・頂点選択。PuppetModel の外に持つ。
*
* @property PuppetModel model The document model at this step.
* @property Selection selection The object-mode selection at this step.
* @property Pose pose The live parameter values (scrub position) at this step.
* @property MeshSelection meshSelection The Edit-mode vertex selection at this step.
* @property EditorMode mode The interaction mode (Object / Edit) at this step.
*/
data class EditorSnapshot(
val model: PuppetModel,
val selection: Selection,
val pose: Pose,
val meshSelection: MeshSelection = MeshSelection(),
val mode: EditorMode = EditorMode.Object,
/**
* The parameters targeted for keyform authoring. Restored like the other selections, so undoing back
* across a parameter click returns the target the edit was made against.
*/
val parameterSelection: ParameterSelection = ParameterSelection(),
/**
* The channel values edited but not yet keyed at this step.
*
* Snapshotted even though a pending edit never reaches the document: it is a deliberate user action
* that shows in the viewport, so Blender records one and so do we. The pose rides in the same
* snapshot, which is what makes restoring these coherent - a pending value was chosen FOR a pose, and
* undo returns to both together.
*/
val pendingChannelEdits: Map<KeyableTarget, ChannelValue> = emptyMap(),
/**
* The keyform-sheet keys selected at this step.
*
* The fourth selection to be snapshotted, and for the same reason as the other three: a misclick that
* loses a carefully built selection is otherwise unrecoverable, and the sheet's selection takes the most
* work to build of any of them. Ordinals renumber when keys cross, so a restored ref can name a key
* that no longer exists there - the sheet prunes at use, which is what makes that harmless.
*/
val keySelection: Set<TrackKeyRef> = emptySet(),
)
/**
* One history entry: a [snapshot] and the [change] that produced it (null for the initial state). The
* change is metadata — the snapshot does the undoing — used for the history-panel label and coalescing.
*
* 履歴の1項目:スナップショットと、それを生んだ変更(初期状態は null)。
*
* @property EditorSnapshot snapshot The state after [change] was applied.
* @property Change change The change that produced [snapshot], or null for the seed entry.
*/
data class HistoryEntry(
val snapshot: EditorSnapshot,
val change: Change?,
)
/**
* A flattened, immutable projection of the undo stack for the history panel: each step's display
* [labelKey] and the [cursor] index of the live step. Rebuilt on every history change so a Compose
* panel renders it as plain state (clicking a row jumps the session there). Compose-free, so the label
* stays a key the UI resolves to a localized string.
*
* 履歴パネル用の取り消しスタックの平坦化ビュー。各段のラベルキーと現在位置を持つ。
*
* @property List<HistoryStep> steps The stack oldest-first.
* @property Int cursor The index of the live step within [steps].
*/
data class HistoryView(
val steps: List<HistoryStep>,
val cursor: Int,
)
/**
* One row of a [HistoryView].
*
* @property String? labelKey The label key of the change that produced this step, or null for the seed
* (the initial open) entry; the UI maps it to a localized label.
* @property Boolean saved Whether this exact step is the last-saved baseline (the panel marks it).
*/
data class HistoryStep(
val labelKey: String?,
val saved: Boolean,
)
/**
* A linear undo/redo stack of immutable snapshots. The entry at [cursor] is the live state; [push]
* records a new step (discarding any redo branch, the chosen v1 behaviour), and [undo] / [redo] move the
* cursor and return the state to restore. Snapshots structurally share their unchanged sub-trees, so the
* stack's cost is bounded by what each step actually changed plus the [limit] cap on retained steps.
*
* Undo is a cursor move, never an inverse op — correctness is structural, since each entry holds the
* whole prior value. A future branching "undo tree" can replace the linear backing without touching the
* session API; v1 is deliberately linear.
*
* 不変スナップショットの線形な取り消し/やり直しスタック。やり直し枝は新規記録で破棄する(v1 の方針)。
*
* @param EditorSnapshot initial The seed entry — the state the document opened on.
* @param Int initialLimit The starting cap; [limit] carries it and may be reassigned later.
* @property Int limit The maximum retained entries; the oldest is dropped past this. Settable at
* runtime, since the cap is a user preference.
*/
class History(
initial: EditorSnapshot,
initialLimit: Int = DEFAULT_HISTORY_LIMIT,
) {
private val entries: MutableList<HistoryEntry> = mutableListOf(HistoryEntry(initial, null))
private var cursor: Int = 0
/**
* The maximum retained entries, settable at runtime because the cap is a user preference. Assigning a
* lower value trims the stack at once (see [trimToLimit]), so lowering it frees memory without waiting
* for the next edit. Clamped to at least 1 so a degenerate cap never empties the stack.
*/
var limit: Int = initialLimit.coerceAtLeast(1)
set(value) {
field = value.coerceAtLeast(1)
trimToLimit()
}
/** The live state — the snapshot at the current cursor. */
val current: EditorSnapshot get() = entries[cursor].snapshot
/** The change that produced the live state, or null at the seed entry (the label for "Undo X"). */
val currentChange: Change? get() = entries[cursor].change
/** The cursor's index into the stack — the position of the live step (the history panel highlights it). */
val cursorIndex: Int get() = cursor
/** A read-only copy of the stack, oldest-first — the source the history panel renders. */
val steps: List<HistoryEntry> get() = entries.toList()
/** True when there is a prior step to undo to. */
val canUndo: Boolean get() = cursor > 0
/** True when a redo step is available (an undo with no intervening [push]). */
val canRedo: Boolean get() = cursor < entries.lastIndex
/**
* Records [snapshot] as a new step produced by [change]. Any redo branch ahead of the cursor is
* discarded (linear history); once the stack exceeds [limit] the oldest entry is dropped so the
* cursor stays valid. The seed entry is never dropped below a single retained step.
*
* @param EditorSnapshot snapshot The new live state.
* @param Change change The change that produced it.
*/
fun push(snapshot: EditorSnapshot, change: Change) {
// Drop the redo branch: everything after the cursor is now an abandoned future.
while (entries.lastIndex > cursor) {
entries.removeAt(entries.lastIndex)
}
entries.add(HistoryEntry(snapshot, change))
cursor = entries.lastIndex
trimToLimit()
}
/**
* Replaces the live entry with [snapshot] and [change], keeping the cursor where it is - the
* mechanism behind adjusting the last operation: its result is recomputed from the state before
* it and lands over its own step, so the stack never grows and the base is never replayed.
*
* Refuses when a redo branch exists: an adjustment applies only to the newest step, and the caller
* clears its record on any undo anyway. Works at cursor 0 too, since a cap of one drops the base
* entry on push and the adjusting record holds that base itself.
*
* @param EditorSnapshot snapshot The recomputed live state.
* @param Change change The change that produced it (normally the entry's own).
* @return Boolean True when the entry was replaced, false when a redo branch made it refuse.
*/
fun amendTop(snapshot: EditorSnapshot, change: Change): Boolean {
if (canRedo) {
return false
}
entries[cursor] = HistoryEntry(snapshot, change)
return true
}
/**
* Drops the oldest entries until the stack fits [limit], stopping at the live step so the current state
* and its redo branch are never discarded. That stop is what makes a lowered cap safe to apply to a
* stack whose cursor sits mid-history: it frees what it can at once and sheds the rest on subsequent
* pushes, and the cursor stays valid throughout. On the push path the cursor is the last entry, so the
* stop never engages and the stack lands exactly at the cap.
*/
private fun trimToLimit() {
while (entries.size > limit && cursor > 0) {
entries.removeAt(0)
cursor--
}
}
/**
* Moves back one step and returns the state to restore, or null when already at the oldest entry.
*
* @return EditorSnapshot? The prior state, or null if nothing to undo.
*/
fun undo(): EditorSnapshot? {
if (!canUndo) {
return null
}
cursor--
return current
}
/**
* Moves forward one step and returns the state to restore, or null when already at the newest entry.
*
* @return EditorSnapshot? The next state, or null if nothing to redo.
*/
fun redo(): EditorSnapshot? {
if (!canRedo) {
return null
}
cursor++
return current
}
/**
* Moves the cursor directly to [index] (clamped to the valid range) and returns the state to restore,
* or null when [index] is already the cursor (a no-op jump). This lets the history panel jump across
* several steps at once — multi-undo or multi-redo — rather than walking one level at a time.
*
* @param Int index The target step index within the stack.
* @return EditorSnapshot? The state at [index], or null when it is already the live step.
*/
fun jumpTo(index: Int): EditorSnapshot? {
val target = index.coerceIn(0, entries.lastIndex)
if (target == cursor) {
return null
}
cursor = target
return current
}
}
@@ -0,0 +1,154 @@
package org.umamo.edit
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import org.umamo.runtime.model.PuppetModel
/**
* The session's undo machinery: the snapshot [History] stack, the saved baseline (both the exact
* snapshot for the history panel's marker and the model instance for the reference-equality dirty
* flag), and the flags/view derived from them. [EditorSession] pushes snapshots and republishes
* flows from the ones this hands back; the derived flows here are exposed on the session unchanged.
* Dirty is measured against the model only, so pose-only and selection-only steps never trip it.
*/
internal class HistoryCore(initialSnapshot: EditorSnapshot, initialHistoryLimit: Int) {
private val history = History(initialSnapshot, initialHistoryLimit)
/**
* The retained-undo-step cap. Assigning trims the stack immediately, never past the live step; the
* session republishes the derived flags afterwards so the panel and the undo/redo enabled states
* follow the trim.
*/
var limit: Int
get() = history.limit
set(value) {
history.limit = value
}
/**
* The live step's snapshot - what the last push (or the last undo) recorded.
*
* Distinct from the session's live flows, which run ahead of it whenever an edit is being previewed
* without being recorded. A caller that must decide whether an edit would record anything new has to
* compare against THIS, not against the flows.
*/
val current: EditorSnapshot get() = history.current
// The exact stack entry last persisted to disk, tracked by snapshot reference so the panel marks one
// row precisely (the dirty flag below tracks the model instead - see EditorSession's class doc).
private var savedSnapshot: EditorSnapshot = history.current
// The model instance last persisted to disk; dirty is measured against it by reference.
private var savedModel: PuppetModel = initialSnapshot.model
private val mutableDirty = MutableStateFlow(false)
/** True when the document model differs from the last-saved state. */
val dirty: StateFlow<Boolean> = mutableDirty.asStateFlow()
private val mutableCanUndo = MutableStateFlow(false)
/** True when there is a step to undo. */
val canUndo: StateFlow<Boolean> = mutableCanUndo.asStateFlow()
private val mutableCanRedo = MutableStateFlow(false)
/** True when there is a step to redo. */
val canRedo: StateFlow<Boolean> = mutableCanRedo.asStateFlow()
private val mutableHistoryView = MutableStateFlow(buildHistoryView())
/** The undo stack projected for the history panel. */
val historyView: StateFlow<HistoryView> = mutableHistoryView.asStateFlow()
/**
* Records one undo step.
*
* @param EditorSnapshot snapshot The complete post-edit state.
* @param Change change The descriptor for the bus and the history-panel label.
*/
fun push(snapshot: EditorSnapshot, change: Change) {
history.push(snapshot, change)
}
/** The change that produced the live step, or null at the seed entry. */
val currentChange: Change? get() = history.currentChange
/**
* Replaces the live step in place (see [History.amendTop]).
*
* @param EditorSnapshot snapshot The recomputed live state.
* @param Change change The change that produced it.
* @return Boolean True when replaced, false when a redo branch made the stack refuse.
*/
fun amendTop(snapshot: EditorSnapshot, change: Change): Boolean = history.amendTop(snapshot, change)
/**
* Steps the cursor back one level.
*
* @return EditorSnapshot? The snapshot to restore, or null with nothing to undo.
*/
fun undo(): EditorSnapshot? = history.undo()
/**
* Steps the cursor forward one level.
*
* @return EditorSnapshot? The snapshot to restore, or null with nothing to redo.
*/
fun redo(): EditorSnapshot? = history.redo()
/**
* Jumps the cursor directly to [index].
*
* @param Int index The target step index.
* @return EditorSnapshot? The snapshot to restore, or null when [index] is already live.
*/
fun jumpTo(index: Int): EditorSnapshot? = history.jumpTo(index)
/**
* Moves the saved baseline to [model]: it becomes the dirty reference, and the stack entry holding that
* instance becomes the panel's saved marker.
*
* The entry is found by the model's identity rather than taken to be the live one, because a save
* snapshots the model and writes off-thread: an edit landed while the file was being written makes a
* newer entry live, and that entry was never persisted. Dirty then stays true (the live model is not
* the saved instance) and the marker sits on the row that was. A model no entry holds any more (the
* step was trimmed) falls back to the live entry.
*
* @param PuppetModel model The model instance just persisted.
*/
fun markSaved(model: PuppetModel) {
savedModel = model
savedSnapshot = history.steps.lastOrNull { entry -> entry.snapshot.model === model }?.snapshot ?: history.current
}
/**
* Republishes the derived flags - dirty, canUndo, canRedo, and the projected history view. The
* session calls this after every mutation, restore, and saved-baseline move.
*
* @param PuppetModel currentModel The live document model dirty is measured against.
*/
fun refreshFlags(currentModel: PuppetModel) {
mutableDirty.value = currentModel !== savedModel
mutableCanUndo.value = history.canUndo
mutableCanRedo.value = history.canRedo
mutableHistoryView.value = buildHistoryView()
}
/**
* Builds the current [HistoryView] from the stack: one [HistoryStep] per entry (its label key and
* whether it is the saved baseline) plus the live cursor. The saved flag is by snapshot reference, so
* exactly one row is marked even when adjacent selection-only steps share a model instance.
*
* @return HistoryView The projected stack for the panel.
*/
private fun buildHistoryView(): HistoryView =
HistoryView(
steps =
history.steps.map { entry ->
HistoryStep(labelKey = entry.change?.labelKey, saved = entry.snapshot === savedSnapshot)
},
cursor = history.cursorIndex,
)
}
@@ -0,0 +1,360 @@
package org.umamo.edit
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.KeyableTarget
import org.umamo.runtime.model.KeyformTrackRef
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.channelGridsOf
/*
* What "key this" and "unkey this" MEAN when the user asks for them - the intent layer over the concrete
* ops in KeyformTrackEdits / KeyformChannelEdits / KeyformGeometryEdits.
*
* Three questions live here: which parameter an edit writes on, whether it acts where the user pointed or
* where the pose stands, and whether a typed value becomes a pending edit or a static write. All three are
* editing SEMANTICS, so they belong in this module - a panel row, a keypress, and a lane context menu must
* answer them identically, and none of them is the right place to decide.
*
* This is also why these are not in :ui, where they started out: taking a Compose-side hover type put
* authoring rules in the UI module and made them untestable without a composition. A :ui caller now passes
* plain data - a track, an optional parameter id, and a KeyformAim - and keeps only the pointer bookkeeping
* that produced them.
*/
/**
* Where a keyform edit is aimed: at a place the user named, or at the pose the rig is standing in.
*
* The distinction is not cosmetic. Pointing at a spot on a track is a statement about WHICH spot, so a key
* lands there rather than at the playhead; and pointing at a track but not at a key means "that key, of
* which there is none", which must remove nothing rather than falling back to the pose and destroying a key
* the user never pointed at.
*/
sealed interface KeyformAim {
/** No place was named, so the edit acts at the current pose - a property row, or a bare keypress. */
data object Pose : KeyformAim
/**
* A named place on the track's axis.
*
* @property Float position The parameter value pointed at.
* @property Int? keyIndex The ordinal of the key sitting there, or null when the pointer is between keys.
*/
data class Position(val position: Float, val keyIndex: Int?) : KeyformAim
}
/**
* What a deferred keyform edit will do once the user picks the axis it writes on.
*/
enum class KeyformAction {
/** Insert a key ([captureKeyOnTrack]). */
Capture,
/** Remove a key ([removeKeyOnTrack]). */
Remove,
}
/**
* A keyform edit held back because more than one parameter is targeted and the user never named one.
*
* The linked-pad case: a 2D pad targets both its axes but reports only the HORIZONTAL one as active, so an
* unaimed edit would silently always write there and the vertical section would keep reading as unkeyed.
* Guessing is the one thing that must not happen - the wrong axis is authored work in the wrong place - so
* the edit parks here and the shell asks.
*
* Carries the whole edit rather than just the question, so answering it is a plain replay through the same
* entry point with the axis filled in; the UI decides nothing but which name was clicked.
*
* @property KeyformTrackRef track The track the edit was aimed at.
* @property KeyformAim aim Where on that track it lands.
* @property KeyformAction action Which edit is waiting.
* @property List candidates The targeted parameters to choose between, in model order.
* @property String? rowKey The keyform-sheet row the aim came from, carried so the replay can reconcile the
* key selection exactly as an unparked edit does; null when the aim came from somewhere with no sheet row.
*/
data class ParameterChoiceRequest(
val track: KeyformTrackRef,
val aim: KeyformAim,
val action: KeyformAction,
val candidates: List<ParameterId>,
val rowKey: String? = null,
)
/**
* The targeted parameters an unaimed edit would have to choose between, or null when there is no choice.
*
* Null - meaning "just proceed" - whenever the caller named a parameter (a sheet lane always does, and its
* lane is the answer), or fewer than two of the targeted ids still resolve in the model.
*
* @param ParameterId? parameterId The axis the caller named, or null.
* @return List? The candidates to ask about, or null to proceed without asking.
*/
private fun EditorSession.parameterChoiceFor(parameterId: ParameterId?): List<ParameterId>? {
if (parameterId != null) {
return null
}
val targeted = parameterSelection.value.ids
if (targeted.size < 2) {
return null
}
// Model order, not set order: the prompt has to list the axes the way the panel does, and a Set's
// iteration order is an implementation detail the user would experience as the menu reshuffling.
val candidates = model.value.parameters.map { parameter -> parameter.id }.filter { id -> id in targeted }
return if (candidates.size < 2) null else candidates
}
/**
* Answers the pending [ParameterChoiceRequest] by writing on [parameterId], replaying the parked edit.
*
* Replayed through the ordinary entry point with the axis now named, so the answered edit takes exactly the
* path an aimed one takes - there is no second implementation of what an insert or a removal means.
*
* @param ParameterId parameterId The axis the user picked.
*/
fun EditorSession.resolveParameterChoice(parameterId: ParameterId) {
val request = pendingParameterChoice.value ?: return
cancelParameterChoice()
when (request.action) {
KeyformAction.Capture -> captureKeyOnTrack(request.track, parameterId, request.aim, request.rowKey)
KeyformAction.Remove -> removeKeyOnTrack(request.track, parameterId, request.aim, request.rowKey)
}
}
/**
* Captures a key on [track] at [aim], keyed on the parameter the edit writes on.
*
* An aimed capture inserts a shape-preserving key at that position, so it holds whatever the track already
* evaluates to there. A capture at the pose stores the PENDING unkeyed edit when there is one, else the
* channel's current evaluated value - so an insert after typing stores what was typed, and an insert with
* nothing edited pins what is already on screen (Blender's behaviour, and how a rigger anchors a pose before
* moving on).
*
* Refuses with a notice rather than silently doing nothing when no parameter resolves, since that is a thing
* the user can fix.
*
* When no parameter is named and more than one is targeted (a linked pad), the edit parks as a
* [ParameterChoiceRequest] instead of writing on whichever axis happens to be active.
*
* Reconciles the keyform sheet's key selection when [rowKey] names the row the aim came from, exactly as
* [removeKeyOnTrack] does: the new key renumbers every key at or above where it lands, so a selection on
* one of those keys must shift up by one to keep naming the same key.
*
* @param KeyformTrackRef track The track to key.
* @param ParameterId? parameterId The axis to key on, or null to use the session's targeted parameter.
* @param KeyformAim aim Where the key lands.
* @param String? rowKey The sheet row the aim came from, or null when it came from somewhere without one.
*/
fun EditorSession.captureKeyOnTrack(
track: KeyformTrackRef,
parameterId: ParameterId?,
aim: KeyformAim,
rowKey: String? = null,
) {
parameterChoiceFor(parameterId)?.let { candidates ->
requestParameterChoice(ParameterChoiceRequest(track, aim, KeyformAction.Capture, candidates, rowKey))
return
}
val parameter = keyformParameterFor(parameterId) ?: return
// An aimed capture keys where it was pointed; every other kind keys at the pose. Resolved once, because
// it is both where the key goes and what the ordinal query has to be asked about.
val keyPosition =
when (aim) {
is KeyformAim.Position -> aim.position
is KeyformAim.Pose -> pose.value[parameter.id] ?: parameter.default
}
val inserted = insertedKeyRef(track, parameter, keyPosition, rowKey)
if (aim is KeyformAim.Position) {
insertingKey(inserted) { insertTrackKeyAt(track, parameter, aim.position) }
return
}
when (track) {
is KeyformTrackRef.Channel -> {
val target = track.target
// Resolved before the wrap, because a channel with no value to capture must leave the selection
// alone rather than reconcile it around an edit that never happens.
val value = pendingChannelEdits.value[target] ?: model.value.channelValueAt(target, pose.value) ?: return
insertingKey(inserted) {
// Retired BEFORE the capture records its step, exactly as the unkeyed branch of editKeyedChannel
// does below and for the same reason: a snapshot defaults every field to live state, so clearing
// afterwards leaves the consumed value inside the step that consumed it - and redo then re-shows
// the uncommitted-edit warning over the very key that now stores the value.
//
// Only THIS target's pending edit is consumed; the pose did not move, so any other target's typed
// value is still the value its user chose and must survive for its own capture.
clearPendingChannelEdit(target)
captureChannelKey(target, parameter, value)
}
}
// Geometry: bind the targeted parameter when needed, then capture the form already on screen -
// the same loop channels use, so a warp / drawable / rotation can be keyed on ANY parameter.
is KeyformTrackRef.Geometry ->
insertingKey(inserted) {
captureGeometryKey(track.owner, parameter)
}
}
}
/**
* The [TrackKeyRef] a key inserted at [position] would take, or null when nothing new is added.
*
* Null whenever the selection cannot be affected: the caller named no sheet row, or a key already sits at
* [position] so the capture overwrites a cell rather than renumbering the axis.
*
* @param KeyformTrackRef track The track the key goes on.
* @param Parameter parameter The parameter whose axis it goes on.
* @param Float position The new key's parameter value.
* @param String? rowKey The sheet row the aim came from, or null when it came from somewhere without one.
* @return TrackKeyRef? The new key's ref, or null when no ordinal renumbers.
*/
private fun EditorSession.insertedKeyRef(
track: KeyformTrackRef,
parameter: Parameter,
position: Float,
rowKey: String?,
): TrackKeyRef? {
if (rowKey == null) {
return null
}
val keyIndex = model.value.trackKeyIndexAfterInsert(track, parameter, position)
return if (keyIndex < 0) null else TrackKeyRef(parameter.id, rowKey, keyIndex)
}
/**
* Removes the key [aim] names from [track], on the parameter the edit writes on.
*
* Either way the key is an ORDINAL, and either way aiming at nothing removes nothing: picking "the nearest
* key" would be a guess at which one the user meant, and a wrong guess silently destroys authored work.
*
* Parks as a [ParameterChoiceRequest] on an ambiguous target, exactly as [captureKeyOnTrack] does - a
* removal aimed at the wrong axis destroys authored work, so it is the LAST thing to guess at.
*
* Reconciles the keyform sheet's key selection when [rowKey] names the row the aim came from - the removal
* renumbers the keys above it, so a selection left alone would end up naming the neighbour. Done HERE
* rather than at each caller because this is where the ordinal is finally resolved, and the aim may not
* carry one at all (a pose aim resolves it against the track).
*
* @param KeyformTrackRef track The track to unkey.
* @param ParameterId? parameterId The axis to remove from, or null to use the session's targeted parameter.
* @param KeyformAim aim The key pointed at, or [KeyformAim.Pose] to take the key the pose stands on.
* @param String? rowKey The sheet row the aim came from, or null when it came from somewhere without one.
*/
fun EditorSession.removeKeyOnTrack(
track: KeyformTrackRef,
parameterId: ParameterId?,
aim: KeyformAim,
rowKey: String? = null,
) {
parameterChoiceFor(parameterId)?.let { candidates ->
requestParameterChoice(ParameterChoiceRequest(track, aim, KeyformAction.Remove, candidates, rowKey))
return
}
val parameter = keyformParameterFor(parameterId) ?: return
val keyIndex =
when (aim) {
is KeyformAim.Position -> aim.keyIndex ?: -1
is KeyformAim.Pose -> model.value.trackKeyIndexAtPose(track, parameter, pose.value)
}
if (keyIndex < 0) {
return
}
// An empty set when the caller has no row to name, which leaves the selection untouched.
val removed = rowKey?.let { row -> setOf(TrackKeyRef(parameter.id, row, keyIndex)) }.orEmpty()
removingKeys(removed) {
removeTrackKeys(listOf(Triple(track, parameter, keyIndex)))
}
}
/**
* Routes a keyable property's typed or picked [value]: a KEYED channel records it as a pending unkeyed
* edit, an unkeyed channel writes the static through [writeStatic].
*
* The one place the rule lives. Writing the static of a keyed channel is shadowed by the track, so the
* edit appears to be silently rejected (the field snaps back and a following `I` captures the old track
* value); a pending edit previews in the viewport and waits for `I`. An unkeyed channel has no track to
* shadow it, so the static is the real store. Reimplementing this branch at each property row instead of
* calling here would let the two halves drift: some rows would apply the guard and others would silently
* skip it.
*
* Both branches record exactly one undo step, and both record it under [change] - which of the two a given
* channel takes depends on whether it happens to carry a track, which is not a distinction the rigger made.
*
* @param KeyableTarget target The entity and channel being edited.
* @param ChannelValue value The value the user chose.
* @param Change change The descriptor of this edit, used by whichever branch runs.
* @param Function writeStatic Writes the owner's static (the unkeyed path); the caller supplies it because
* which setter that is depends on the owner and channel.
*/
fun EditorSession.editKeyedChannel(
target: KeyableTarget,
value: ChannelValue,
change: Change,
writeStatic: () -> Unit,
) {
val keyed = model.value.channelGridsOf(target.owner)?.get(target.channel) != null
if (keyed) {
commitPendingChannelEdit(target, value, change)
} else {
// A scrub previews through the pending buffer even on an unkeyed channel (see previewChannelEdit),
// so the static write has to retire that preview - otherwise the stale pending value keeps
// shadowing the very static just committed, and the field stays tinted as an uncommitted edit.
clearPendingChannelEdit(target)
writeStatic()
}
}
/**
* Previews [value] on [target] without committing anything - what a field reports while being scrubbed.
*
* Always the pending buffer, whether or not the channel is keyed. For a keyed channel that is already
* where a committed edit lands, so preview and commit coincide; for an unkeyed one it is the difference
* between a live viewport and a history entry per pointer frame. [editKeyedChannel] retires the preview
* when the gesture ends.
*
* @param KeyableTarget target The entity and channel being scrubbed.
* @param ChannelValue value The in-flight value.
*/
fun EditorSession.previewChannelEdit(target: KeyableTarget, value: ChannelValue) {
setPendingChannelEdit(target, value)
}
/**
* The parameter a keyform edit writes on: [parameterId] when the caller named one (a sheet lane belongs to
* one section's axis, which need not be the selection's active member), else the targeted parameter.
*
* Emits the no-parameter notice and returns null when the named parameter no longer resolves.
*
* @param ParameterId? parameterId The axis the caller named, or null to fall back to the target.
* @return Parameter? The parameter to write on, or null.
*/
private fun EditorSession.keyformParameterFor(parameterId: ParameterId?): Parameter? {
val namedId = parameterId ?: return targetedParameter()
val parameter = model.value.parameters.firstOrNull { candidate -> candidate.id == namedId }
if (parameter == null) {
emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor)
}
return parameter
}
/**
* The parameter a keyform edit falls back to - the active member of the session's parameter selection.
*
* Emits a notice and returns null when nothing is targeted, since an edit with no axis to write on has no
* sensible default: guessing a parameter would key the rig somewhere the user never looked.
*
* @return Parameter? The targeted parameter, or null.
*/
private fun EditorSession.targetedParameter(): Parameter? {
val activeId = parameterSelection.value.active
if (activeId == null) {
emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor)
return null
}
val parameter = model.value.parameters.firstOrNull { candidate -> candidate.id == activeId }
if (parameter == null) {
// A dangling id (a stale snapshot's target for a parameter since deleted) is as unfixable-by-waiting
// as no target at all, so it gets the same notice rather than a silent no-op.
emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor)
}
return parameter
}
@@ -0,0 +1,401 @@
package org.umamo.edit
import org.umamo.runtime.eval.cellsByLinearIndex
import org.umamo.runtime.eval.colorAt
import org.umamo.runtime.eval.flagAt
import org.umamo.runtime.eval.gridCornersHolding
import org.umamo.runtime.eval.scalarAt
import org.umamo.runtime.keyform.ChannelValueInterpolator
import org.umamo.runtime.keyform.axisIndexOf
import org.umamo.runtime.keyform.keyIndexAt
import org.umamo.runtime.keyform.withAxisSeeded
import org.umamo.runtime.keyform.withFormCaptured
import org.umamo.runtime.keyform.withKeyMoved
import org.umamo.runtime.keyform.withKeyRemoved
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.ChannelValueKind
import org.umamo.runtime.model.ColorRgb
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.Glue
import org.umamo.runtime.model.KeyableTarget
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.KeyformOwner
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.channelGridsOf
import org.umamo.runtime.model.withDerivedRenderRoot
/*
* Keyform authoring for the SCALAR and COLOR channels - opacity, the multiply / screen tints, draw order,
* glue intensity. Geometry keyframing is deliberately not here: it needs the deformer-chain inverse under
* a pose, which is a separate problem, while these channels need no inverse at all. That is exactly why
* they come first - the whole authoring loop (bind, capture, remove, undo, and the sheet reflecting it)
* gets proven on the easy case before the hard one raises its own questions.
*
* Two rules from the grid algebra shape everything below, both forced by how the evaluator brackets a pose:
* a newly bound axis SPANS the parameter's range (an axis that does not reach the ends leaves the channel
* falling back to its static there), and removal COLLAPSES below two keys (a one-key axis resolves only
* within EPS_KEY of that key).
*/
/**
* This owner's STATIC value for [channel] - what the channel reads when it has no track.
*
* The seed value for a first bind: binding replicates the entity's present look across the new axis, so
* that binding alone never changes the render, only the capture that follows does.
*/
private fun PuppetModel.staticValueOf(owner: KeyformOwner, channel: FormChannel): ChannelValue? =
when (owner) {
is KeyformOwner.Drawable ->
drawables.firstOrNull { it.id == owner.id }?.let { drawable ->
when (channel) {
FormChannel.DRAW_ORDER -> ChannelValue.Scalar(drawable.drawOrder)
FormChannel.OPACITY -> ChannelValue.Scalar(drawable.opacity)
FormChannel.MULTIPLY_COLOR -> ChannelValue.Color(drawable.multiplyColor)
FormChannel.SCREEN_COLOR -> ChannelValue.Color(drawable.screenColor)
else -> null
}
}
is KeyformOwner.Part ->
parts.firstOrNull { it.id == owner.id }?.let { part ->
when (channel) {
FormChannel.DRAW_ORDER -> ChannelValue.Scalar(part.drawOrder.toFloat())
FormChannel.OPACITY -> ChannelValue.Scalar(part.composite.opacity)
FormChannel.MULTIPLY_COLOR -> ChannelValue.Color(part.composite.multiplyColor)
FormChannel.SCREEN_COLOR -> ChannelValue.Color(part.composite.screenColor)
else -> null
}
}
is KeyformOwner.Deformer ->
deformers.firstOrNull { it.id == owner.id }?.let { deformer ->
when (deformer) {
is Deformer.Warp ->
when (channel) {
FormChannel.OPACITY -> ChannelValue.Scalar(deformer.opacity)
FormChannel.MULTIPLY_COLOR -> ChannelValue.Color(deformer.multiplyColor)
FormChannel.SCREEN_COLOR -> ChannelValue.Color(deformer.screenColor)
else -> null
}
is Deformer.Rotation ->
when (channel) {
FormChannel.OPACITY -> ChannelValue.Scalar(deformer.opacity)
FormChannel.MULTIPLY_COLOR -> ChannelValue.Color(deformer.multiplyColor)
FormChannel.SCREEN_COLOR -> ChannelValue.Color(deformer.screenColor)
FormChannel.FLIP_X -> ChannelValue.Flag(deformer.flipX)
FormChannel.FLIP_Y -> ChannelValue.Flag(deformer.flipY)
else -> null
}
}
}
is KeyformOwner.Glue ->
glues.firstOrNull { it.meshA == owner.meshA && it.meshB == owner.meshB }?.let { glue ->
if (channel == FormChannel.GLUE_INTENSITY) ChannelValue.Scalar(glue.intensity) else null
}
}
/**
* This model with [owner]'s channel tracks replaced.
*
* A part edit re-derives the render root, because the render tree carries its own copy of each part's
* tracks and would otherwise keep evaluating the pre-edit ones.
*/
private fun PuppetModel.withChannelGrids(owner: KeyformOwner, channelGrids: ChannelGrids): PuppetModel =
when (owner) {
is KeyformOwner.Drawable ->
copy(drawables = drawables.map { if (it.id == owner.id) it.copy(channelGrids = channelGrids) else it })
is KeyformOwner.Part ->
copy(parts = parts.map { if (it.id == owner.id) it.copy(channelGrids = channelGrids) else it })
.withDerivedRenderRoot()
is KeyformOwner.Deformer ->
copy(
deformers =
deformers.map { deformer ->
if (deformer.id != owner.id) {
deformer
} else {
when (deformer) {
is Deformer.Warp -> deformer.copy(channelGrids = channelGrids)
is Deformer.Rotation -> deformer.copy(channelGrids = channelGrids)
}
}
},
)
is KeyformOwner.Glue ->
copy(
glues =
glues.map { glue ->
if (glue.meshA == owner.meshA && glue.meshB == owner.meshB) {
glue.copy(channelGrids = channelGrids)
} else {
glue
}
},
)
}
/** Whether [value] is the kind [channel] stores - a guard against writing a color into a scalar track. */
private fun FormChannel.accepts(value: ChannelValue): Boolean = valueKind == value.valueKind
/**
* This model with [value] captured on [target]'s channel at [pose], keyed on [parameter].
*
* The whole authoring gesture in one op:
*
* - An UNBOUND channel is bound first - a new axis spanning the parameter's min / default / max holding
* the entity's current static value, so binding alone changes nothing on screen.
* - A channel already keyed on OTHER parameters gains this one as an additional axis, its existing cells
* replicated across it, so the motion it already had is preserved.
* - The capture then inserts a key at the pose if one is not already there (filling the new slice by
* interpolation, so every other pose is unchanged) and writes [value] into the single cell the pose now
* sits exactly on.
*
* Because the capture always lands on a key, the write is a plain assignment - there is never a blend to
* invert, which is why these channels need no math the geometry path is still missing.
*
* Returns the same instance when the entity is missing, the channel does not belong to it, [value] is the
* wrong kind for the channel, or the grid algebra refused the reshape (a degenerate parameter range).
*
* @param KeyableTarget target The entity and channel to key.
* @param Parameter parameter The parameter to key on.
* @param Pose pose The current pose; the capture lands at its value on [parameter].
* @param ChannelValue value The value to store.
* @return PuppetModel The model with the key captured, or this on a refusal.
*/
fun PuppetModel.withChannelKeyCaptured(
target: KeyableTarget,
parameter: Parameter,
pose: Pose,
value: ChannelValue,
): PuppetModel {
if (!target.channel.accepts(value)) {
return this
}
val grids = channelGridsOf(target.owner) ?: return this
val staticValue = staticValueOf(target.owner, target.channel) ?: return this
val defaults = parameters.associate { it.id to it.default }
val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: defaults[id] ?: 0f }
val existing = grids[target.channel]
val bound: KeyformGrid<ChannelValue> =
if (existing == null || existing.axisIndexOf(parameter.id) < 0) {
existing.withAxisSeeded(parameter, staticValue) ?: return this
} else {
existing
}
// Compared against BOUND, not existing: a capture that refuses after a fresh seed must refuse the whole
// op - committing the bare axis bind would discard the user's value while the channel reads as keyed.
val captured = bound.withFormCaptured(poseValue, value, ChannelValueInterpolator)
if (captured === bound) {
return this
}
return withChannelGrids(target.owner, ChannelGrids(grids.gridsByChannel + (target.channel to captured)))
}
/**
* This model with the key at [pose] removed from [target]'s channel on [parameter]'s axis.
*
* Removing below two keys collapses the axis entirely - a one-key axis would resolve only within EPS_KEY of
* that key and leave the channel on its static everywhere else, which reads as the key having done
* something bizarre rather than having been removed. Collapsing the last axis drops the track, and the
* channel returns to its owner's static value.
*
* Returns the same instance when nothing is keyed there - in particular when the pose is not ON a key,
* since removing "the nearest key" to a pose between two of them is a guess, not an instruction.
*
* @param KeyableTarget target The entity and channel.
* @param Parameter parameter The parameter whose axis to remove from.
* @param Pose pose The current pose; the key at its value is the one removed.
* @return PuppetModel The model with the key removed, or this on a refusal.
*/
fun PuppetModel.withChannelKeyRemoved(target: KeyableTarget, parameter: Parameter, pose: Pose): PuppetModel {
val track = channelGridsOf(target.owner)?.get(target.channel) ?: return this
val scrubValue = pose[parameter.id] ?: parameters.firstOrNull { it.id == parameter.id }?.default ?: 0f
val keyIndex = track.keyIndexAt(parameter.id, scrubValue)
if (keyIndex < 0) {
return this
}
// One removal body: the pose-addressed remove is the ordinal-addressed one after resolving the key,
// so the collapse-below-two-keys rule cannot fork between the two paths.
return withChannelKeyRemovedAt(target, parameter, keyIndex)
}
/**
* The value [target]'s channel currently evaluates to at [pose], or null when the entity or channel does
* not exist.
*
* What an insert captures when nothing is being edited: pinning the value already on screen, which is what
* Blender's `I` does and how a rigger anchors a pose before moving on. Reads through the same channel
* sampling the renderer uses, so the key lands on exactly what was displayed rather than on a value
* recomputed by a second code path.
*
* @param KeyableTarget target The entity and channel.
* @param Pose pose The pose to sample at.
* @return ChannelValue? The current value, or null when the target does not resolve.
*/
fun PuppetModel.channelValueAt(target: KeyableTarget, pose: Pose): ChannelValue? {
val grids = channelGridsOf(target.owner) ?: return null
val staticValue = staticValueOf(target.owner, target.channel) ?: return null
// No defaults map: this runs per keyable row per recomposition, a track has at most a few axes, and
// the pose usually answers - the per-miss linear scan beats an every-call full-map build.
val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: parameters.firstOrNull { it.id == id }?.default ?: 0f }
return when (staticValue) {
is ChannelValue.Scalar -> ChannelValue.Scalar(grids.scalarAt(target.channel, staticValue.value, poseValue))
is ChannelValue.Color -> ChannelValue.Color(grids.colorAt(target.channel, staticValue.color, poseValue))
is ChannelValue.Flag -> ChannelValue.Flag(grids.flagAt(target.channel, staticValue.flag, poseValue))
}
}
/**
* [channelValueAt] with out-of-span hold: past the track's first/last key the nearest end value is used
* instead of the owner's static. Insert uses this so a key after the last copies that last authored
* value; the property-panel read stays on [channelValueAt] so it still matches the renderer.
*
* @param KeyableTarget target The entity and channel.
* @param Pose pose The pose to sample at.
* @return ChannelValue? The held value, or null when the target does not resolve.
*/
fun PuppetModel.channelValueAtHolding(target: KeyableTarget, pose: Pose): ChannelValue? {
val grids = channelGridsOf(target.owner) ?: return null
val staticValue = staticValueOf(target.owner, target.channel) ?: return null
val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: parameters.firstOrNull { it.id == id }?.default ?: 0f }
val grid = grids[target.channel] ?: return staticValue
val corners = gridCornersHolding(grid, poseValue) ?: return staticValue
val cells = cellsByLinearIndex(grid)
return when (staticValue) {
is ChannelValue.Scalar -> {
var total = 0f
for (corner in corners) {
val value = (cells[corner.linearIndex]?.form as? ChannelValue.Scalar)?.value ?: continue
total += corner.weight * value
}
ChannelValue.Scalar(total)
}
is ChannelValue.Color -> {
var red = 0f
var green = 0f
var blue = 0f
for (corner in corners) {
val color = (cells[corner.linearIndex]?.form as? ChannelValue.Color)?.color ?: continue
red += corner.weight * color.red
green += corner.weight * color.green
blue += corner.weight * color.blue
}
ChannelValue.Color(ColorRgb(red, green, blue))
}
is ChannelValue.Flag -> {
val floorCorner = corners.firstOrNull() ?: return staticValue
ChannelValue.Flag((cells[floorCorner.linearIndex]?.form as? ChannelValue.Flag)?.flag ?: staticValue.flag)
}
}
}
/**
* This model with the key at [fromValue] on [target]'s channel moved to [toValue].
*
* The sheet's drag gesture: the key keeps whatever it holds and only changes where on the parameter it
* applies. Identified by ORDINAL, not by its current value - keys a hair apart are legal, and resolving a
* value back to a key picks whichever is nearer, which silently moves the wrong one.
*
* @param KeyableTarget target The entity and channel.
* @param Parameter parameter The parameter whose axis the key sits on.
* @param Int keyIndex The key's ordinal on that axis.
* @param Float toValue The requested new position.
* @return PuppetModel The model with the key moved, or this on a refusal.
*/
fun PuppetModel.withChannelKeyMoved(
target: KeyableTarget,
parameter: Parameter,
keyIndex: Int,
toValue: Float,
): PuppetModel {
val grids = channelGridsOf(target.owner) ?: return this
val track = grids[target.channel] ?: return this
val moved = track.withKeyMoved(parameter.id, keyIndex, toValue)
if (moved === track) {
return this
}
return withChannelGrids(target.owner, ChannelGrids(grids.gridsByChannel + (target.channel to moved)))
}
/**
* This model with key [keyIndex] removed from [target]'s channel on [parameter]'s axis.
*
* By ordinal, for the same reason [withChannelKeyMoved] is: the sheet knows exactly which mark was
* clicked and must not re-derive it from a value two keys could answer to.
*
* @param KeyableTarget target The entity and channel.
* @param Parameter parameter The parameter whose axis to remove from.
* @param Int keyIndex The key's ordinal on that axis.
* @return PuppetModel The model with the key removed, or this on a refusal.
*/
fun PuppetModel.withChannelKeyRemovedAt(target: KeyableTarget, parameter: Parameter, keyIndex: Int): PuppetModel {
val grids = channelGridsOf(target.owner) ?: return this
val track = grids[target.channel] ?: return this
val reduced = track.withKeyRemoved(parameter.id, keyIndex)
if (reduced === track) {
return this
}
val remaining =
if (reduced == null) {
grids.gridsByChannel - target.channel
} else {
grids.gridsByChannel + (target.channel to reduced)
}
return withChannelGrids(target.owner, ChannelGrids(remaining))
}
/**
* Whether [target]'s channel is keyed on [parameter] at all - what the properties panel's keyed indicator
* and the `I` / `Alt+I` availability read.
*
* @param KeyableTarget target The entity and channel.
* @param ParameterId parameterId The parameter to look for.
* @return Boolean True when a track exists and keys on that parameter.
*/
fun PuppetModel.isChannelKeyedOn(target: KeyableTarget, parameterId: ParameterId): Boolean {
val track = channelGridsOf(target.owner)?.get(target.channel) ?: return false
return track.axisIndexOf(parameterId) >= 0
}
/**
* Captures [value] on [target] at the current pose, keyed on [parameter], as one undo step.
*
* @param KeyableTarget target The entity and channel to key.
* @param Parameter parameter The parameter to key on.
* @param ChannelValue value The value to store.
*/
fun EditorSession.captureChannelKey(target: KeyableTarget, parameter: Parameter, value: ChannelValue) {
mutate(KeyformChange.InsertKey(target.channel)) { model ->
model.withChannelKeyCaptured(target, parameter, pose.value, value)
}
}
/**
* Removes the key at the current pose from [target]'s channel on [parameter], as one undo step.
*
* @param KeyableTarget target The entity and channel.
* @param Parameter parameter The parameter whose axis to remove from.
*/
fun EditorSession.removeChannelKey(target: KeyableTarget, parameter: Parameter) {
mutate(KeyformChange.DeleteKey(target.channel)) { model ->
model.withChannelKeyRemoved(target, parameter, pose.value)
}
}
/** The kind guard's counterpart for callers building a value: the neutral value of [channel]'s kind. */
internal fun FormChannel.neutralValue(): ChannelValue =
when (valueKind) {
ChannelValueKind.SCALAR -> ChannelValue.Scalar(0f)
ChannelValueKind.COLOR -> ChannelValue.Color(org.umamo.runtime.model.ColorRgb(0f, 0f, 0f))
ChannelValueKind.FLAG -> ChannelValue.Flag(false)
}
@@ -0,0 +1,627 @@
package org.umamo.edit
import org.umamo.runtime.eval.cellsByLinearIndex
import org.umamo.runtime.eval.gridCornersHolding
import org.umamo.runtime.keyform.FormInterpolator
import org.umamo.runtime.keyform.MeshDeltaInterpolator
import org.umamo.runtime.keyform.RotationPivotInterpolator
import org.umamo.runtime.keyform.WarpLatticeInterpolator
import org.umamo.runtime.keyform.axisIndexOf
import org.umamo.runtime.keyform.withAxisSeeded
import org.umamo.runtime.keyform.withFormCaptured
import org.umamo.runtime.keyform.withKeyInserted
import org.umamo.runtime.keyform.withKeyMoved
import org.umamo.runtime.keyform.withKeyRemoved
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.KeyformOwner
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.RotationPivotForm
import org.umamo.runtime.model.WarpLatticeForm
/*
* Geometry-track keyform authoring: bind an owner to a parameter, capture a form at a pose, and move /
* insert / remove key POSITIONS.
*
* Deliberately separate from KeyformChannelEdits: a channel is addressed by (owner, channel) and its cells
* hold a ChannelValue, while geometry is a privileged per-owner field whose cell type differs by owner
* (MeshDeltaForm / WarpLatticeForm / RotationPivotForm). One generic op cannot span both without erasing
* that distinction, and erasing it is exactly what would let a scalar track reach buildDeltaTexels.
*
* Binding and capturing a form mirror the channel path (seed the axis, then withFormCaptured). Interactive
* lattice / mesh sculpting that PRODUCES a new form still lives with the viewport; this file stores whatever
* form the caller (or the pose sample) already holds.
*/
/**
* Whether [owner] has a geometry track keyed on [parameterId] at all.
*
* @param KeyformOwner owner The entity.
* @param ParameterId parameterId The parameter to look for.
* @return Boolean True when a geometry grid exists and keys on that parameter.
*/
fun PuppetModel.isGeometryKeyedOn(owner: KeyformOwner, parameterId: ParameterId): Boolean =
// Through geometryGridOf, the one owner dispatch - a second copy of the when let the keyed indicator
// and the actual edit ops disagree about a new owner kind.
(geometryGridOf(owner)?.axisIndexOf(parameterId) ?: -1) >= 0
/**
* [owner]'s geometry grid, or null when that kind of entity carries none.
*
* The grid rather than one axis, so callers can use the grid's own tolerance-aware lookups instead of
* re-deriving the evaluator's epsilon beside them.
*
* @param KeyformOwner owner The entity.
* @return KeyformGrid? Its geometry grid, or null.
*/
fun PuppetModel.geometryGridOf(owner: KeyformOwner): KeyformGrid<*>? =
when (owner) {
is KeyformOwner.Drawable -> drawableGeometry(owner)
is KeyformOwner.Deformer ->
when (val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id }) {
is Deformer.Warp -> deformer.geometryGrid
is Deformer.Rotation -> deformer.geometryGrid
null -> null
}
// A part is organizational and a glue welds two meshes; neither carries geometry of its own.
is KeyformOwner.Part, is KeyformOwner.Glue -> null
}
/**
* This model with [owner]'s geometry captured at [pose] on [parameter] - bind the axis if needed, then
* write the form the owner currently evaluates to (or a rest-zero mesh delta for an unkeyed drawable).
*
* The geometry twin of [withChannelKeyCaptured]: seeding alone never changes the render, and a capture at
* the pose pins whatever is already on screen so a later sculpt (or a sheet insert at another value) has a
* handle to edit from. Refused when the owner cannot supply a form to seed with - an unkeyed warp has no
* rest lattice, so there is nothing to bind.
*
* @param KeyformOwner owner The entity whose geometry track to key.
* @param Parameter parameter The parameter to key on.
* @param Pose pose The pose the capture lands at.
* @return PuppetModel The model with the capture written, or this on a refusal.
*/
fun PuppetModel.withGeometryKeyCaptured(owner: KeyformOwner, parameter: Parameter, pose: Pose): PuppetModel {
val defaults = parameters.associate { it.id to it.default }
val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: defaults[id] ?: 0f }
return when (owner) {
is KeyformOwner.Drawable -> {
val drawable = drawables.firstOrNull { candidate -> candidate.id == owner.id } ?: return this
val form =
meshDeltasAt(drawable.geometryGrid, poseValue)
?: drawable.mesh?.let { mesh -> MeshDeltaForm(FloatArray(mesh.positions.size)) }
?: return this
captureDrawableGeometry(owner, parameter, poseValue, form)
}
is KeyformOwner.Deformer ->
when (val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id }) {
is Deformer.Warp -> {
val points = warpControlPointsHolding(deformer.geometryGrid, poseValue) ?: return this
captureWarpGeometry(owner, parameter, poseValue, WarpLatticeForm(points.copyOf()))
}
is Deformer.Rotation -> {
val form = rotationFormHolding(deformer.geometryGrid, poseValue) ?: return this
captureRotationGeometry(owner, parameter, poseValue, form)
}
null -> this
}
is KeyformOwner.Part, is KeyformOwner.Glue -> this
}
}
/**
* Mesh-delta form sampled at [poseValue] with out-of-span hold (nearest end key), or null when the grid
* is absent. Authoring capture uses hold so a key past the last copies that last form, not rest-zero.
*
* @param KeyformGrid? grid The drawable's geometry grid.
* @param Function poseValue Value per parameter id.
* @return MeshDeltaForm? The blended deltas, or null.
*/
private fun meshDeltasAt(grid: KeyformGrid<MeshDeltaForm>?, poseValue: (ParameterId) -> Float): MeshDeltaForm? {
if (grid == null) {
return null
}
val corners = gridCornersHolding(grid, poseValue) ?: return null
val byLinearIndex = cellsByLinearIndex(grid)
var blended: FloatArray? = null
for (corner in corners) {
val form = byLinearIndex[corner.linearIndex]?.form ?: continue
val target = blended ?: FloatArray(form.positionDeltas.size).also { blended = it }
for (componentIndex in target.indices) {
target[componentIndex] += corner.weight * form.positionDeltas[componentIndex]
}
}
return blended?.let(::MeshDeltaForm)
}
/**
* Warp lattice sampled at [poseValue] with out-of-span hold, or null when the grid is absent.
* Authoring twin of [org.umamo.runtime.eval.warpControlPointsAt] - that one freezes out of range.
*/
private fun warpControlPointsHolding(
grid: KeyformGrid<WarpLatticeForm>?,
poseValue: (ParameterId) -> Float,
): FloatArray? {
if (grid == null) {
return null
}
val corners = gridCornersHolding(grid, poseValue) ?: return null
val byLinearIndex = cellsByLinearIndex(grid)
var blended: FloatArray? = null
for (corner in corners) {
val form = byLinearIndex[corner.linearIndex]?.form ?: continue
val target = blended ?: FloatArray(form.controlPoints.size).also { blended = it }
for (componentIndex in target.indices) {
target[componentIndex] += corner.weight * form.controlPoints[componentIndex]
}
}
return blended
}
/**
* Rotation form sampled at [poseValue] with out-of-span hold, or null when the grid is absent.
* Authoring twin of [org.umamo.runtime.eval.rotationFormAt] - that one freezes out of range.
*/
private fun rotationFormHolding(
grid: KeyformGrid<RotationPivotForm>?,
poseValue: (ParameterId) -> Float,
): RotationPivotForm? {
if (grid == null) {
return null
}
val corners = gridCornersHolding(grid, poseValue) ?: return null
val byLinearIndex = cellsByLinearIndex(grid)
var originX = 0f
var originY = 0f
var angle = 0f
var scale = 0f
var resolvedAnyCell = false
for (corner in corners) {
val form = byLinearIndex[corner.linearIndex]?.form ?: continue
resolvedAnyCell = true
originX += corner.weight * form.originX
originY += corner.weight * form.originY
angle += corner.weight * form.angle
scale += corner.weight * form.scale
}
if (!resolvedAnyCell) {
return null
}
return RotationPivotForm(originX, originY, angle, scale)
}
/**
* Seeds / captures a drawable mesh-delta grid on [parameter] at [poseValue].
*
* @param KeyformOwner.Drawable owner The drawable.
* @param Parameter parameter The parameter to key on.
* @param Function poseValue The pose sampler.
* @param MeshDeltaForm form The form to store at the pose.
* @return PuppetModel The rewritten model, or this.
*/
private fun PuppetModel.captureDrawableGeometry(
owner: KeyformOwner.Drawable,
parameter: Parameter,
poseValue: (ParameterId) -> Float,
form: MeshDeltaForm,
): PuppetModel {
val existing = drawableGeometry(owner)
val bound = existing.withAxisSeeded(parameter, form) ?: return this
val captured = bound.withFormCaptured(poseValue, form, MeshDeltaInterpolator)
if (captured === bound && existing != null && existing.axisIndexOf(parameter.id) >= 0) {
// Already keyed on this parameter and the cell already holds [form] - nothing to record.
return this
}
if (captured === existing) {
return this
}
return copy(
drawables =
drawables.map { candidate ->
if (candidate.id == owner.id) candidate.copy(geometryGrid = captured) else candidate
},
)
}
/**
* This model with [owner]'s warp lattice written as [form] at [pose] on [parameter] - binds the axis when
* needed, then overwrites the cell the pose lands in. The viewport lattice drag commits through here so a
* sculpted form becomes a key on whatever parameter the rigger targeted.
*
* @param KeyformOwner.Deformer owner The warp.
* @param Parameter parameter The parameter to key on.
* @param Pose pose The pose the form is authored at.
* @param WarpLatticeForm form The lattice control points to store (parent-local, interleaved x,y).
* @return PuppetModel The model with the form written, or this on a refusal.
*/
fun PuppetModel.withWarpLatticeCaptured(
owner: KeyformOwner.Deformer,
parameter: Parameter,
pose: Pose,
form: WarpLatticeForm,
): PuppetModel {
val defaults = parameters.associate { it.id to it.default }
val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: defaults[id] ?: 0f }
return captureWarpGeometry(owner, parameter, poseValue, form)
}
/**
* Seeds / captures a warp lattice grid on [parameter] at [poseValue].
*
* @param KeyformOwner.Deformer owner The deformer id wrapper.
* @param Parameter parameter The parameter to key on.
* @param Function poseValue The pose sampler.
* @param WarpLatticeForm form The lattice to store at the pose.
* @return PuppetModel The rewritten model, or this.
*/
private fun PuppetModel.captureWarpGeometry(
owner: KeyformOwner.Deformer,
parameter: Parameter,
poseValue: (ParameterId) -> Float,
form: WarpLatticeForm,
): PuppetModel {
val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id } as? Deformer.Warp ?: return this
val existing = deformer.geometryGrid
val bound = existing.withAxisSeeded(parameter, form) ?: return this
val captured = bound.withFormCaptured(poseValue, form, WarpLatticeInterpolator)
if (captured === bound && existing != null && existing.axisIndexOf(parameter.id) >= 0) {
return this
}
if (captured === existing) {
return this
}
return copy(
deformers =
deformers.map { candidate ->
if (candidate.id == owner.id && candidate is Deformer.Warp) {
candidate.copy(geometryGrid = captured)
} else {
candidate
}
},
)
}
/**
* Seeds / captures a rotation pivot grid on [parameter] at [poseValue].
*
* @param KeyformOwner.Deformer owner The deformer id wrapper.
* @param Parameter parameter The parameter to key on.
* @param Function poseValue The pose sampler.
* @param RotationPivotForm form The pivot to store at the pose.
* @return PuppetModel The rewritten model, or this.
*/
private fun PuppetModel.captureRotationGeometry(
owner: KeyformOwner.Deformer,
parameter: Parameter,
poseValue: (ParameterId) -> Float,
form: RotationPivotForm,
): PuppetModel {
val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id } as? Deformer.Rotation ?: return this
val existing = deformer.geometryGrid
val bound = existing.withAxisSeeded(parameter, form) ?: return this
val captured = bound.withFormCaptured(poseValue, form, RotationPivotInterpolator)
if (captured === bound && existing != null && existing.axisIndexOf(parameter.id) >= 0) {
return this
}
if (captured === existing) {
return this
}
return copy(
deformers =
deformers.map { candidate ->
if (candidate.id == owner.id && candidate is Deformer.Rotation) {
candidate.copy(geometryGrid = captured)
} else {
candidate
}
},
)
}
/**
* This model with [owner]'s geometry key at [fromValue] moved to [toValue] on [parameter]'s axis.
*
* Moving a key changes only WHERE on the parameter its form applies - the cells are untouched - so it is
* safe for every owner, including a deformer with no rest lattice. The grid clamps at the neighbouring
* keys, so the stored destination can differ from the requested one.
*
* @param KeyformOwner owner The entity whose geometry track to edit.
* @param Parameter parameter The parameter whose axis the key sits on.
* @param Int keyIndex The key's ordinal on that axis.
* @param Float toValue The requested new position.
* @return PuppetModel The model with the key moved, or this on a refusal.
*/
fun PuppetModel.withGeometryKeyMoved(
owner: KeyformOwner,
parameter: Parameter,
keyIndex: Int,
toValue: Float,
): PuppetModel = rewriteGeometry(owner) { grid -> grid.withKeyMoved(parameter.id, keyIndex, toValue) }
/**
* This model with a key inserted at [position] on [owner]'s geometry track, holding the interpolated form.
*
* Shape-preserving: the new slice is the blend of its neighbours, the same operation the export refinement
* performs, so the deformation through the new key is the deformation that was already there.
*
* @param KeyformOwner owner The entity whose geometry track to edit.
* @param Parameter parameter The parameter whose axis to insert on.
* @param Float position The new key's parameter value.
* @return PuppetModel The model with the key inserted, or this on a refusal.
*/
fun PuppetModel.withGeometryKeyInserted(owner: KeyformOwner, parameter: Parameter, position: Float): PuppetModel =
rewriteGeometry(owner) { grid, interpolator -> grid.withKeyInserted(parameter.id, position, interpolator) }
/**
* This model with [owner]'s geometry key at [position] removed from [parameter]'s axis.
*
* REFUSED for a deformer when the removal would collapse its last axis. A warp's control points live only
* in its keyform cells - there is no rest lattice - so an unkeyed deformer is hidden, and silently making a
* deformer and everything under it vanish is not an acceptable outcome of deleting one key. A drawable
* has a rest mesh, so the same removal there is safe and simply returns it to its rest shape.
*
* @param KeyformOwner owner The entity whose geometry track to edit.
* @param Parameter parameter The parameter whose axis to remove from.
* @param Int keyIndex The key's ordinal on that axis.
* @return PuppetModel The model with the key removed, or this on a refusal.
*/
fun PuppetModel.withGeometryKeyRemoved(owner: KeyformOwner, parameter: Parameter, keyIndex: Int): PuppetModel =
rewriteGeometryNullable(owner) { grid ->
val reduced = grid.withKeyRemoved(parameter.id, keyIndex)
if (reduced == null && owner is KeyformOwner.Deformer) grid else reduced
}
/**
* Applies a same-shaped rewrite to whichever geometry grid [owner] has, keeping the form type.
*
* The generic form, for ops whose expression does not depend on what a cell holds. Returning the receiver
* means "no change", matching the algebra's own refusal convention.
*
* @param KeyformOwner owner The entity.
* @param Function rewrite Produces the new grid from the current one.
* @return PuppetModel The rewritten model, or this.
*/
private fun PuppetModel.rewriteGeometry(
owner: KeyformOwner,
rewrite: (KeyformGrid<Nothing>) -> KeyformGrid<Nothing>,
): PuppetModel = rewriteGeometryNullable(owner) { grid -> rewrite(grid) }
/**
* Applies a rewrite that needs the grid's matching [FormInterpolator].
*
* A second overload rather than a parameter on the first, because the interpolator's type is tied to the
* grid's and only the per-owner dispatch below knows both at once.
*
* @param KeyformOwner owner The entity.
* @param Function rewrite Produces the new grid from the current one and its interpolator.
* @return PuppetModel The rewritten model, or this.
*/
private fun PuppetModel.rewriteGeometry(
owner: KeyformOwner,
rewrite: (KeyformGrid<Nothing>, FormInterpolator<Nothing>) -> KeyformGrid<Nothing>,
): PuppetModel =
when (owner) {
is KeyformOwner.Drawable ->
replaceDrawableGeometry(owner) { grid -> rewrite(grid.asNothing(), MeshDeltaInterpolator.asNothing()) }
is KeyformOwner.Deformer ->
replaceDeformerGeometry(
owner = owner,
onWarp = { grid -> rewrite(grid.asNothing(), WarpLatticeInterpolator.asNothing()) },
onRotation = { grid -> rewrite(grid.asNothing(), RotationPivotInterpolator.asNothing()) },
)
is KeyformOwner.Part, is KeyformOwner.Glue -> this
}
/**
* The shared owner dispatch: reads [owner]'s geometry grid, asks [rewrite] for the new one, writes it back.
*
* One place that knows which entity kinds carry geometry, so adding one is a compile error here rather
* than a silently-ignored owner at three call sites. A null result drops the grid entirely (the entity
* becomes unkeyed); returning the receiver leaves the model untouched.
*
* @param KeyformOwner owner The entity.
* @param Function rewrite Produces the new grid, the same grid to refuse, or null to drop it.
* @return PuppetModel The rewritten model, or this.
*/
private fun PuppetModel.rewriteGeometryNullable(
owner: KeyformOwner,
rewrite: (KeyformGrid<Nothing>) -> KeyformGrid<Nothing>?,
): PuppetModel =
when (owner) {
is KeyformOwner.Drawable -> replaceDrawableGeometry(owner) { grid -> rewrite(grid.asNothing()) }
is KeyformOwner.Deformer ->
replaceDeformerGeometry(
owner = owner,
onWarp = { grid -> rewrite(grid.asNothing()) },
onRotation = { grid -> rewrite(grid.asNothing()) },
)
is KeyformOwner.Part, is KeyformOwner.Glue -> this
}
/** This drawable's geometry grid, or null when the id is unknown or it has none. */
private fun PuppetModel.drawableGeometry(owner: KeyformOwner.Drawable) =
drawables.firstOrNull { candidate -> candidate.id == owner.id }?.geometryGrid
/**
* Runs [rewrite] over a drawable's mesh-delta grid and writes the result back.
*
* @param KeyformOwner.Drawable owner The drawable.
* @param Function rewrite Produces the new grid, the same one to refuse, or null to drop it.
* @return PuppetModel The rewritten model, or this.
*/
private fun <TForm> PuppetModel.replaceDrawableGeometry(
owner: KeyformOwner.Drawable,
rewrite: (KeyformGrid<TForm>) -> KeyformGrid<TForm>?,
): PuppetModel {
@Suppress("UNCHECKED_CAST")
val grid = (drawableGeometry(owner) as KeyformGrid<TForm>?) ?: return this
val rewritten = rewrite(grid)
if (rewritten === grid) {
return this
}
@Suppress("UNCHECKED_CAST")
return copy(
drawables =
drawables.map { candidate ->
if (candidate.id == owner.id) {
candidate.copy(geometryGrid = rewritten as KeyformGrid<org.umamo.runtime.model.MeshDeltaForm>?)
} else {
candidate
}
},
)
}
/**
* Runs the matching rewrite over a deformer's lattice or pivot grid and writes the result back.
*
* @param KeyformOwner.Deformer owner The deformer.
* @param Function onWarp The rewrite for a warp's lattice grid.
* @param Function onRotation The rewrite for a rotation's pivot grid.
* @return PuppetModel The rewritten model, or this.
*/
private fun <TForm> PuppetModel.replaceDeformerGeometry(
owner: KeyformOwner.Deformer,
onWarp: (KeyformGrid<TForm>) -> KeyformGrid<TForm>?,
onRotation: (KeyformGrid<TForm>) -> KeyformGrid<TForm>?,
): PuppetModel {
val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id } ?: return this
@Suppress("UNCHECKED_CAST")
val grid =
when (deformer) {
is Deformer.Warp -> deformer.geometryGrid as KeyformGrid<TForm>?
is Deformer.Rotation -> deformer.geometryGrid as KeyformGrid<TForm>?
} ?: return this
val rewritten =
when (deformer) {
is Deformer.Warp -> onWarp(grid)
is Deformer.Rotation -> onRotation(grid)
}
if (rewritten === grid) {
return this
}
@Suppress("UNCHECKED_CAST")
return copy(
deformers =
deformers.map { candidate ->
when {
candidate.id != owner.id -> candidate
candidate is Deformer.Warp ->
candidate.copy(
geometryGrid = rewritten as KeyformGrid<org.umamo.runtime.model.WarpLatticeForm>?,
)
candidate is Deformer.Rotation ->
candidate.copy(
geometryGrid = rewritten as KeyformGrid<org.umamo.runtime.model.RotationPivotForm>?,
)
else -> candidate
}
},
)
}
/**
* Views a grid as one over an unconstrained form type.
*
* The ops here move and remove KEYS and never touch a cell, so the form type is genuinely irrelevant to
* them - but Kotlin has no way to say "any grid" without a type argument. Confined to this file, and
* sound because [KeyformGrid] is immutable and no cell is ever read or written through the view.
*/
@Suppress("UNCHECKED_CAST")
private fun <TForm> KeyformGrid<TForm>.asNothing(): KeyformGrid<Nothing> = this as KeyformGrid<Nothing>
/** The [asNothing] counterpart for an interpolator, for the same reason and with the same confinement. */
@Suppress("UNCHECKED_CAST")
private fun <TForm> FormInterpolator<TForm>.asNothing(): FormInterpolator<Nothing> = this as FormInterpolator<Nothing>
/**
* Moves [owner]'s geometry key at [fromValue] to [toValue], as one undo step.
*
* @param KeyformOwner owner The entity.
* @param Parameter parameter The parameter whose axis the key sits on.
* @param Int keyIndex The key's ordinal on that axis.
* @param Float toValue The new position.
*/
fun EditorSession.moveGeometryKey(owner: KeyformOwner, parameter: Parameter, keyIndex: Int, toValue: Float) {
mutate(KeyformChange.MoveKey(null)) { model -> model.withGeometryKeyMoved(owner, parameter, keyIndex, toValue) }
}
/**
* Inserts a shape-preserving key at [position] on [owner]'s geometry track, as one undo step.
*
* @param KeyformOwner owner The entity.
* @param Parameter parameter The parameter whose axis to insert on.
* @param Float position The new key's parameter value.
*/
fun EditorSession.insertGeometryKeyAt(owner: KeyformOwner, parameter: Parameter, position: Float) {
mutate(KeyformChange.InsertKey(null)) { model -> model.withGeometryKeyInserted(owner, parameter, position) }
}
/**
* Captures [owner]'s current geometry at the live pose on [parameter], as one undo step - bind the axis
* when needed (any parameter, not a fixed set).
*
* @param KeyformOwner owner The entity.
* @param Parameter parameter The parameter to key on.
*/
fun EditorSession.captureGeometryKey(owner: KeyformOwner, parameter: Parameter) {
mutate(KeyformChange.InsertKey(null)) { model -> model.withGeometryKeyCaptured(owner, parameter, pose.value) }
}
/**
* Writes [form] onto [owner]'s geometry at [pose], on the session's targeted parameter, as one undo
* step. Seeds the axis when the warp is not yet keyed on that parameter.
*
* Pass the LIVE scrub pose from the viewport ([LiveParams]) when committing from the lattice overlay -
* [EditorSession.pose] only moves when a scrub ends, so capturing against it mid-drag would land the
* form on the wrong key.
*
* Refuses (near-cursor notice) when nothing is targeted: guessing an axis would author work on a
* parameter the rigger never looked at.
*
* @param KeyformOwner.Deformer owner The warp.
* @param WarpLatticeForm form The lattice to store.
* @param Pose pose The pose the form is authored at (defaults to the session's committed pose).
*/
fun EditorSession.commitWarpLattice(
owner: KeyformOwner.Deformer,
form: WarpLatticeForm,
pose: Pose = this.pose.value,
) {
val activeId = parameterSelection.value.active
if (activeId == null) {
emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor)
return
}
val parameter = model.value.parameters.firstOrNull { candidate -> candidate.id == activeId }
if (parameter == null) {
emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor)
return
}
mutate(KeyformChange.InsertKey(null)) { model -> model.withWarpLatticeCaptured(owner, parameter, pose, form) }
}
/**
* Removes [owner]'s geometry key at [position], as one undo step.
*
* @param KeyformOwner owner The entity.
* @param Parameter parameter The parameter whose axis to remove from.
* @param Int keyIndex The key's ordinal on that axis.
*/
fun EditorSession.removeGeometryKeyAt(owner: KeyformOwner, parameter: Parameter, keyIndex: Int) {
mutate(KeyformChange.DeleteKey(null)) { model -> model.withGeometryKeyRemoved(owner, parameter, keyIndex) }
}
@@ -0,0 +1,119 @@
package org.umamo.edit
/*
* What a key REMOVAL does to the keyform sheet's key selection.
*
* Removing keys renumbers the ones above them: a [TrackKeyRef] names a row and an ordinal on that row's
* track, so a selection left untouched across a removal stops naming the key the user selected and instead
* names whichever key slides down onto the freed ordinal.
*
* The rule lives in :edit rather than in the sheet because it is a statement about what an edit MEANS, and
* three call sites need to agree on it - the aimed removal behind Alt+I and the lane menu, the selected-keys
* removal behind Delete, and the summary-mark removal. A [TrackKeyRef]'s row key is opaque here, which is
* all this needs: the algebra compares row keys, it never resolves one.
*/
/**
* [current] with [removed] taken out and every ordinal that renumbers under them corrected.
*
* Only two kinds of ref are at risk from a removal: the removed keys themselves, and the LATER ordinals on
* the same row, which slide down one place per key removed below them. Everything else names exactly what
* it named before, so a mark the user had not selected must leave their selection untouched rather than
* clearing it wholesale.
*
* Matched on the parameter as well as the row because a linked pair renders one row under two sections, and
* a removal renumbers only the axis it happened on.
*
* @param Set<TrackKeyRef> current The selection before the removal.
* @param Set<TrackKeyRef> removed The keys the removal takes out.
* @return Set<TrackKeyRef> The selection that survives it.
*/
fun selectionAfterKeyRemoval(current: Set<TrackKeyRef>, removed: Set<TrackKeyRef>): Set<TrackKeyRef> {
if (removed.isEmpty()) {
return current
}
return current
.filterNot { key -> key in removed }
.map { key ->
val removedBelow =
removed.count { gone ->
gone.parameterId == key.parameterId && gone.rowKey == key.rowKey && gone.keyIndex < key.keyIndex
}
if (removedBelow == 0) key else key.copy(keyIndex = key.keyIndex - removedBelow)
}.toSet()
}
/**
* [current] with every ordinal at or above [inserted] shifted up to make room for it.
*
* The mirror of [selectionAfterKeyRemoval]: an insert renumbers every key at or above where it lands, so a
* selection on one of those keys must shift up by one to keep naming the same key. A key below the
* insertion point already names the right key and is left untouched.
*
* @param Set<TrackKeyRef> current The selection before the insert.
* @param TrackKeyRef inserted The new key, at the ordinal it takes.
* @return Set<TrackKeyRef> The selection as it reads afterwards.
*/
fun selectionAfterKeyInsertion(current: Set<TrackKeyRef>, inserted: TrackKeyRef): Set<TrackKeyRef> =
current
.map { key ->
val renumbers =
key.parameterId == inserted.parameterId &&
key.rowKey == inserted.rowKey &&
key.keyIndex >= inserted.keyIndex
if (renumbers) key.copy(keyIndex = key.keyIndex + 1) else key
}.toSet()
/**
* Runs [removeKeys] with the key selection re-pointed at what survives it, as ONE undo step.
*
* An empty [removed] is the caller saying it cannot name what it removed in sheet terms (a Properties row
* has no sheet row), and leaves the selection exactly as it was.
*
* @param Set<TrackKeyRef> removed The keys [removeKeys] takes out, in sheet-row terms.
* @param Function removeKeys The removal itself, which records its own step.
*/
fun EditorSession.removingKeys(removed: Set<TrackKeyRef>, removeKeys: () -> Unit) {
editingKeys({ current -> selectionAfterKeyRemoval(current, removed) }, removeKeys)
}
/**
* Runs [insertKey] with the key selection re-pointed past the key it adds, as ONE undo step.
*
* A null [inserted] is the caller saying no key is added, or that it cannot name the new one in sheet terms,
* and leaves the selection exactly as it was.
*
* @param TrackKeyRef? inserted The new key at the ordinal it takes, or null when none is added.
* @param Function insertKey The insert itself, which records its own step.
*/
fun EditorSession.insertingKey(inserted: TrackKeyRef?, insertKey: () -> Unit) {
editingKeys({ current -> if (inserted == null) current else selectionAfterKeyInsertion(current, inserted) }, insertKey)
}
/**
* Runs [edit] with the key selection put through [reconcile], as ONE undo step.
*
* STAGE, EDIT, CONFIRM (see [EditorSession.stageKeySelection]): the reconciled selection is staged first so
* the edit's own snapshot records it, and confirmed afterwards so it still reaches history when the edit
* declines to record anything. Staging it AFTER instead would leave every recorded step holding the
* pre-edit refs, so undoing back to one would point the selection at whichever keys had taken those ordinals.
*
* An edit that refuses is rolled back to the selection as it was, because nothing renumbered - the
* re-pointing would then be a shift with no edit under it. Measured by model identity, which the edit ops
* maintain: a refused edit hands back the instance it was given.
*
* @param Function reconcile The selection as it reads after [edit], given how it reads now.
* @param Function edit The edit itself, which records its own step.
*/
private fun EditorSession.editingKeys(reconcile: (Set<TrackKeyRef>) -> Set<TrackKeyRef>, edit: () -> Unit) {
val selectionBefore = keySelection.value
val reconciled = reconcile(selectionBefore)
val modelBeforeEdit = model.value
stageKeySelection(reconciled)
edit()
if (model.value === modelBeforeEdit) {
stageKeySelection(selectionBefore)
} else {
setKeySelection(reconciled)
}
}
@@ -0,0 +1,520 @@
package org.umamo.edit
import org.umamo.runtime.keyform.keyDestinationFor
import org.umamo.runtime.keyform.keyIndexAfterInsert
import org.umamo.runtime.keyform.keyIndexAfterMove
import org.umamo.runtime.keyform.keyIndexAt
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.KeyformTrackRef
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.channelGridsOf
/*
* The one dispatch from "a track the sheet is pointing at" to the channel or geometry implementation.
*
* The sheet applies the same three gestures - drag a key, insert one, remove one - to every row it draws,
* and which underlying op that becomes is not a decision the UI should be making twice per gesture. It is
* made once, here.
*/
/**
* This model with [track]'s key at [fromValue] moved to [toValue] on [parameter]'s axis.
*
* @param KeyformTrackRef track The track to edit.
* @param Parameter parameter The parameter whose axis the key sits on.
* @param Int keyIndex The key's ordinal on that axis.
* @param Float toValue The requested new position.
* @return PuppetModel The model with the key moved, or this on a refusal.
*/
fun PuppetModel.withTrackKeyMoved(
track: KeyformTrackRef,
parameter: Parameter,
keyIndex: Int,
toValue: Float,
): PuppetModel =
when (track) {
is KeyformTrackRef.Channel -> withChannelKeyMoved(track.target, parameter, keyIndex, toValue)
is KeyformTrackRef.Geometry -> withGeometryKeyMoved(track.owner, parameter, keyIndex, toValue)
}
/**
* This model with a shape-preserving key inserted at [position] on [track]'s axis for [parameter].
*
* @param KeyformTrackRef track The track to edit.
* @param Parameter parameter The parameter whose axis to insert on.
* @param Float position The new key's parameter value.
* @param Pose pose The current pose, which fixes the cell on every OTHER axis of a multi-keyed track.
* @return PuppetModel The model with the key inserted, or this on a refusal.
*/
fun PuppetModel.withTrackKeyInserted(
track: KeyformTrackRef,
parameter: Parameter,
position: Float,
pose: Pose,
): PuppetModel =
when (track) {
is KeyformTrackRef.Channel -> {
val posed = pose + (parameter.id to position)
// Hold-extrapolate past the track's key span so a key after the last copies that last value
// (render sampling falls back to the static out of range, which would author the wrong form).
val heldValue = channelValueAtHolding(track.target, posed)
if (heldValue == null) this else withChannelKeyCaptured(track.target, parameter, posed, heldValue)
}
is KeyformTrackRef.Geometry -> {
// Same capture path as channels: seed the axis when the owner is not yet keyed on this
// parameter (any parameter the rigger targeted), then pin the form already on screen -
// withGeometryKeyCaptured hold-samples past the span so the new key copies the end form.
val posed = pose + (parameter.id to position)
withGeometryKeyCaptured(track.owner, parameter, posed)
}
}
/**
* This model with [track]'s key at [position] removed from [parameter]'s axis.
*
* @param KeyformTrackRef track The track to edit.
* @param Parameter parameter The parameter whose axis to remove from.
* @param Int keyIndex The key's ordinal on that axis.
* @return PuppetModel The model with the key removed, or this on a refusal.
*/
fun PuppetModel.withTrackKeyRemoved(track: KeyformTrackRef, parameter: Parameter, keyIndex: Int): PuppetModel =
when (track) {
is KeyformTrackRef.Channel -> withChannelKeyRemovedAt(track.target, parameter, keyIndex)
is KeyformTrackRef.Geometry -> withGeometryKeyRemoved(track.owner, parameter, keyIndex)
}
/** The history-label channel for [track] - null for geometry, which has no channel to name. */
private fun channelOf(track: KeyformTrackRef) =
when (track) {
is KeyformTrackRef.Channel -> track.target.channel
is KeyformTrackRef.Geometry -> null
}
/**
* [value] clamped into [parameter]'s range, tolerating a reversed (min > max) range from a malformed
* import.
*
* Centralized HERE rather than at each call site, so a pointer drag, a keyboard nudge, and a lane-edge
* insert cannot disagree about where the ends are.
*
* @param Float value The requested parameter value.
* @param Parameter parameter The parameter whose range bounds it.
* @return Float The clamped value.
*/
private fun clampToParameterRange(value: Float, parameter: Parameter): Float =
value.coerceIn(minOf(parameter.min, parameter.max), maxOf(parameter.min, parameter.max))
/**
* Moves [track]'s key at [fromValue] to [toValue], as one undo step.
*
* @param KeyformTrackRef track The track to edit.
* @param Parameter parameter The parameter whose axis the key sits on.
* @param Int keyIndex The key's ordinal on that axis.
* @param Float toValue The new position.
* @return Int The ordinal the key holds AFTER the move, which a crossing changes.
*/
fun EditorSession.moveTrackKey(
track: KeyformTrackRef,
parameter: Parameter,
keyIndex: Int,
toValue: Float,
): Int {
// Within the parameter's range a key may cross its neighbours freely; the grid re-sorts and permutes
// its cells to match. Only the range itself is a wall - a key outside it can never be reached again.
val clamped = clampToParameterRange(toValue, parameter)
// Resolved BEFORE the mutate, against the grid this ordinal still refers to. A crossing renumbers the
// axis, so afterwards the ordinal names a different key - which is exactly why the caller has to be
// told the new one rather than left holding the old.
val landedIndex = model.value.trackKeyIndexAfterMove(track, parameter, keyIndex, toValue)
mutate(KeyformChange.MoveKey(channelOf(track))) { model ->
model.withTrackKeyMoved(track, parameter, keyIndex, clamped)
}
return landedIndex
}
/**
* The ordinal a key inserted at [position] on [track] would take, or -1 when the insert adds none.
*
* The insert counterpart of [trackKeyIndexAfterMove], and needed for the same reason: an insert renumbers
* every key at or above it, so the keyform sheet has to correct its key selection to the ordinal the
* selected key lands on - and it has to do so before the insert records its step, since the selection rides
* that snapshot.
*
* Clamps [position] exactly as [insertTrackKeyAt] does, so the query cannot answer for a destination the
* insert would never use.
*
* @param KeyformTrackRef track The track to insert into.
* @param Parameter parameter The parameter whose axis the key goes on.
* @param Float position The new key's requested parameter value.
* @return Int The new key's ordinal, or -1 when the track does not resolve or a key already sits there.
*/
fun PuppetModel.trackKeyIndexAfterInsert(track: KeyformTrackRef, parameter: Parameter, position: Float): Int =
trackGridOf(this, track)?.keyIndexAfterInsert(parameter.id, clampToParameterRange(position, parameter)) ?: -1
/**
* The ordinal [keyIndex] on [track] would hold after being moved to [toValue] - pure, nothing recorded.
*
* Public for the same reason [limitedDragFraction] is: the keyform sheet has to know where a key will land
* BEFORE the move records its step, because the sheet's key selection rides that step's snapshot and a
* selection staged afterwards reaches no history entry at all. Preview, stage, and commit must agree about
* the landing, so they call one function rather than reimplementing the crossing rule.
*
* Clamps [toValue] exactly as [moveTrackKey] does, which is why the clamp lives here and not at either
* call site - a query that answered for an unclamped destination would disagree with the move it describes.
*
* @param KeyformTrackRef track The track the key sits on.
* @param Parameter parameter The parameter whose axis the key sits on.
* @param Int keyIndex The key's current ordinal on that axis.
* @param Float toValue The requested destination.
* @return Int The ordinal after the move, or [keyIndex] when the track no longer resolves.
*/
fun PuppetModel.trackKeyIndexAfterMove(
track: KeyformTrackRef,
parameter: Parameter,
keyIndex: Int,
toValue: Float,
): Int =
trackGridOf(this, track)
?.keyIndexAfterMove(parameter.id, keyIndex, clampToParameterRange(toValue, parameter))
?: keyIndex
/**
* Inserts a shape-preserving key at [position] on [track], as one undo step.
*
* Shape-preserving means the new key holds whatever the track already evaluates to there, so the insert is
* a handle to edit from rather than an edit in itself.
*
* @param KeyformTrackRef track The track to edit.
* @param Parameter parameter The parameter whose axis to insert on.
* @param Float position The new key's parameter value.
*/
fun EditorSession.insertTrackKeyAt(track: KeyformTrackRef, parameter: Parameter, position: Float) {
// Clamped like a move: the lane's edge inset extrapolates a hit past the domain ends, and an unclamped
// insert would author a key outside the range that no scrub can ever reach.
val clamped = clampToParameterRange(position, parameter)
mutate(KeyformChange.InsertKey(channelOf(track))) { model ->
model.withTrackKeyInserted(track, parameter, clamped, pose.value)
}
}
/**
* Moves every key in [keys] to [toValue] as ONE undo step - the summary-row drag.
*
* They go to the same place rather than by the same delta because that is what dragging a summary mark
* means: the marks were stacked at one value and stay stacked. Each still lands through its own track's
* `withKeyMoved`, so a key that would collide with a neighbour on ITS track is nudged the sub-pixel
* distance that keeps the span resolvable - the group can drift apart by at most EPS_SPAN, which is far
* below anything the sheet can draw.
*
* @param List keys The (track, parameter, key ordinal) triples to move.
* @param Float toValue The destination, in the parameter's units.
*/
fun EditorSession.moveTrackKeys(keys: List<Triple<KeyformTrackRef, Parameter, Int>>, toValue: Float) {
if (keys.isEmpty()) {
return
}
mutate(KeyformChange.MoveKey(channelOf(keys.first().first))) { model ->
keys.fold(model) { current, (track, parameter, keyIndex) ->
current.withTrackKeyMoved(track, parameter, keyIndex, clampToParameterRange(toValue, parameter))
}
}
}
/**
* [fraction] reduced to what every key in [keys] can actually take without leaving its parameter's range.
*
* Public because the sheet PREVIEWS a group drag before committing it, and a preview drawn at the
* unclamped fraction would show the marks travelling past a wall they are about to stop at - which is the
* snap-back this exists to prevent. Preview and commit must be the same number, so they call the same
* function rather than reimplementing the bound.
*
* @param List keys The (track, parameter, key ordinal) triples being dragged.
* @param Float fraction The requested drag as a signed fraction of each parameter's range.
* @return Float The fraction the whole group can take - same sign, or zero when it cannot move.
*/
fun PuppetModel.limitedDragFraction(keys: List<Triple<KeyformTrackRef, Parameter, Int>>, fraction: Float): Float =
keyDragsOf(keys).filterNotNull().fold(fraction) { limited, move -> move.limitedTo(limited) }
/**
* One [KeyDrag] per entry of [keys], null where the ref no longer resolves.
*
* Aligned WITH keys rather than compacted: a caller gets one answer back per key it passed, so a stale ref
* must not shift every later answer by one.
*
* @param List keys The (track, parameter, key ordinal) triples.
* @return List The drags, position for position.
*/
private fun PuppetModel.keyDragsOf(keys: List<Triple<KeyformTrackRef, Parameter, Int>>): List<KeyDrag?> =
keys.map { (track, parameter, keyIndex) ->
trackKeyValue(track, parameter, keyIndex)?.let { fromValue -> KeyDrag(track, parameter, fromValue) }
}
/**
* Drags every key in [keys] by [fraction] of its parameter's range, as ONE undo step - the multi-select
* mark drag.
*
* By a fraction rather than an absolute delta because a selection can span two parameters (a linked pad
* shows both axes at once) whose ranges differ by orders of magnitude. Within ONE parameter a fraction of
* its range IS the absolute delta, so the common case is exactly what the hand did; across two it is the
* only reading that keeps the group together on screen.
*
* Clamped to the MOST CONSTRAINED member rather than per key: clamping individually would let the keys
* nearest an end pile up while the rest kept travelling, silently destroying the spacing the rigger
* authored. Reducing the whole drag instead just stops the group at the wall.
*
* Each key is re-found BY VALUE inside the fold rather than trusted to keep its ordinal: a key that crosses
* an unselected neighbour renumbers the axis under the keys still to be moved.
*
* @param List keys The (track, parameter, key ordinal) triples to drag.
* @param Float fraction The drag as a signed fraction of each parameter's range.
* @return List<Int> Each key's ordinal AFTER the drag, in the order given - crossings renumber the axis, so
* a caller holding the old ordinals would be pointing at whichever keys took their place.
*/
fun EditorSession.dragTrackKeys(keys: List<Triple<KeyformTrackRef, Parameter, Int>>, fraction: Float): List<Int> {
val plan = model.value.planTrackKeyDrag(keys, fraction) ?: return keys.map { (_, _, keyIndex) -> keyIndex }
// Computed before the mutate rather than inside it because the landing VALUES have to come back out, and
// mutate hands back only a model. It applies the transform exactly once against this same instance, so
// handing it the finished model is equivalent - including the reference-equality no-op check, which
// still fires when nothing moved.
mutate(KeyformChange.MoveKey(channelOf(keys.first().first))) { plan.model }
return plan.landedOrdinals
}
/**
* Where every key in [keys] would land if dragged by [fraction] - pure, nothing recorded.
*
* The query half of [dragTrackKeys], public for the reason [trackKeyIndexAfterMove] spells out: the sheet
* has to re-point its key selection at the landed ordinals BEFORE the drag records its step, because the
* selection rides that step's snapshot. Both call the same planner, so the answer cannot drift from the
* drag it describes.
*
* @param List keys The (track, parameter, key ordinal) triples being dragged.
* @param Float fraction The drag as a signed fraction of each parameter's range.
* @return List<Int> Each key's ordinal after the drag, in the order given - the starting ordinals when the
* drag would move nothing.
*/
fun PuppetModel.trackKeyDragLandings(keys: List<Triple<KeyformTrackRef, Parameter, Int>>, fraction: Float): List<Int> =
planTrackKeyDrag(keys, fraction)?.landedOrdinals ?: keys.map { (_, _, keyIndex) -> keyIndex }
/**
* A planned group drag: the model it would produce, and the ordinal each key would hold in it.
*
* @property PuppetModel model The model with every drag applied.
* @property List<Int> landedOrdinals Each key's post-drag ordinal, aligned with the keys as given.
*/
private class KeyDragPlan(val model: PuppetModel, val landedOrdinals: List<Int>)
/**
* Plans the group drag [dragTrackKeys] applies, or null when it would move nothing.
*
* Pure over this model, which is what lets the sheet ask for the landings and then commit the same drag.
* Null rather than a plan whose model is this one, so a caller cannot mistake "refused" for "applied".
*
* @param List keys The (track, parameter, key ordinal) triples to drag.
* @param Float fraction The drag as a signed fraction of each parameter's range.
* @return KeyDragPlan? The plan, or null when the drag is empty, unresolvable, or clamped to nothing.
*/
private fun PuppetModel.planTrackKeyDrag(
keys: List<Triple<KeyformTrackRef, Parameter, Int>>,
fraction: Float,
): KeyDragPlan? {
if (keys.isEmpty() || fraction == 0f) {
return null
}
val moves = keyDragsOf(keys)
val live = moves.filterNotNull()
if (live.isEmpty()) {
return null
}
val effectiveFraction = live.fold(fraction) { limited, move -> move.limitedTo(limited) }
if (effectiveFraction == 0f) {
return null
}
val destinations = live.associateWith { move -> move.destinationAt(effectiveFraction) }
// Nearest the destination first, so a run of keys shuffling the same way cannot have an earlier one
// clamp against a neighbour that is about to move out of the way.
val ordered = if (effectiveFraction > 0f) live.sortedByDescending { it.fromValue } else live.sortedBy { it.fromValue }
val outcome = withKeyDragsApplied(ordered, destinations)
val landedOrdinals =
keys.mapIndexed { position, (track, parameter, keyIndex) ->
// Resolved by where the key ACTUALLY landed, not by where it was sent. A key dropped onto a
// neighbour is nudged EPS_SPAN aside, which is wider than the EPS_KEY tolerance this lookup uses -
// so asking for the requested value would find the key already sitting there and hand the caller
// ITS ordinal, silently moving the selection onto the wrong mark (and merging two of them into one).
val landed = moves[position]?.let { move -> outcome.landedValueByMove[move] } ?: return@mapIndexed keyIndex
outcome.model.trackKeyIndexAt(track, parameter, landed).takeIf { index -> index >= 0 } ?: keyIndex
}
return KeyDragPlan(outcome.model, landedOrdinals)
}
/**
* The result of applying a batch of key drags: the new model, and where each key actually ended up.
*
* The landing values are not the requested destinations. A key dropped within EPS_SPAN of a neighbour is
* nudged aside, and one that cannot be nudged anywhere resolvable does not move at all - so the only
* description of a key that survives its own move is the value it truly holds afterwards.
*
* @property PuppetModel model The model with every drag applied.
* @property Map landedValueByMove Each drag's true landing value.
*/
private class KeyDragOutcome(val model: PuppetModel, val landedValueByMove: Map<KeyDrag, Float>)
/**
* This model with [ordered] applied in sequence, reporting where each key truly landed.
*
* Pure, and applied in the given order because each move reshapes the axis the next one is found on.
*
* @param List ordered The drags, already sorted into the direction of travel.
* @param Map destinations Each drag's requested destination.
* @return KeyDragOutcome The new model plus each drag's true landing value.
*/
private fun PuppetModel.withKeyDragsApplied(ordered: List<KeyDrag>, destinations: Map<KeyDrag, Float>): KeyDragOutcome {
val landed = HashMap<KeyDrag, Float>(ordered.size)
var working = this
for (move in ordered) {
// Re-found BY VALUE, not by the ordinal the caller passed: an earlier key crossing an unselected
// neighbour renumbers the axis under the keys still to be moved.
val liveIndex = working.trackKeyIndexAt(move.track, move.parameter, move.fromValue)
if (liveIndex < 0) {
continue
}
val requested = destinations.getValue(move)
// Asked BEFORE the move, off the same grid withTrackKeyMoved will consult, so the answer is the one
// that is about to be applied. Null is a refusal - the key stays exactly where it is.
landed[move] = working.trackKeyDestination(move.track, move.parameter, liveIndex, requested) ?: move.fromValue
working = working.withTrackKeyMoved(move.track, move.parameter, liveIndex, requested)
}
return KeyDragOutcome(working, landed)
}
/**
* Where [track]'s key at [keyIndex] would land if moved toward [requested] - the collision nudge applied.
*
* @param KeyformTrackRef track The track to read.
* @param Parameter parameter The parameter whose axis the key sits on.
* @param Int keyIndex The key's ordinal on that axis.
* @param Float requested The requested destination.
* @return Float? The value it would take, or null when the move cannot apply.
*/
private fun PuppetModel.trackKeyDestination(
track: KeyformTrackRef,
parameter: Parameter,
keyIndex: Int,
requested: Float,
): Float? = trackGridOf(this, track)?.keyDestinationFor(parameter.id, keyIndex, requested)
/**
* One key's in-flight drag: where it is now, and what bounds how far it may go.
*
* @property KeyformTrackRef track The track it sits on.
* @property Parameter parameter The parameter whose axis it sits on.
* @property Float fromValue Its position before the drag.
*/
private class KeyDrag(val track: KeyformTrackRef, val parameter: Parameter, val fromValue: Float) {
/** The parameter's span, floored so a degenerate (min == max) parameter cannot divide by zero. */
private val span: Float get() = (maxOf(parameter.min, parameter.max) - minOf(parameter.min, parameter.max)).takeIf { it > 0f } ?: 1f
/**
* [fraction] reduced, if needed, so this key stays inside its parameter's range.
*
* @param Float fraction The requested drag.
* @return Float The fraction this key can take, same sign or zero.
*/
fun limitedTo(fraction: Float): Float {
val low = minOf(parameter.min, parameter.max)
val high = maxOf(parameter.min, parameter.max)
return if (fraction > 0f) {
minOf(fraction, ((high - fromValue) / span).coerceAtLeast(0f))
} else {
maxOf(fraction, ((low - fromValue) / span).coerceAtMost(0f))
}
}
/**
* Where this key lands at [fraction] of its parameter's range.
*
* @param Float fraction The (already limited) drag.
* @return Float The destination, clamped defensively to the range.
*/
fun destinationAt(fraction: Float): Float =
(fromValue + span * fraction).coerceIn(minOf(parameter.min, parameter.max), maxOf(parameter.min, parameter.max))
}
/**
* The parameter value key [keyIndex] currently sits at on [track], or null when there is no such key.
*
* @param KeyformTrackRef track The track to read.
* @param Parameter parameter The parameter whose axis to read.
* @param Int keyIndex The key's ordinal on that axis.
* @return Float? Its current position, or null.
*/
fun PuppetModel.trackKeyValue(track: KeyformTrackRef, parameter: Parameter, keyIndex: Int): Float? {
val axis =
trackGridOf(this, track)?.axes?.firstOrNull { candidate -> candidate.parameterId == parameter.id }
?: return null
return axis.keys.getOrNull(keyIndex)
}
/**
* The ordinal of [track]'s key at the current [pose] on [parameter]'s axis, or -1 when the pose is not on
* one.
*
* Within EPS_KEY, the same tolerance `bindBracket` snaps with - so "on a key" here means exactly what it
* means to the evaluator, and the field tint, the shortcut, and the rendered result cannot disagree about
* whether the pose is sitting on a key.
*
* @param KeyformTrackRef track The track to read.
* @param Parameter parameter The parameter whose axis to read.
* @param Pose pose The pose to resolve against.
* @return Int The key's ordinal, or -1.
*/
fun PuppetModel.trackKeyIndexAtPose(track: KeyformTrackRef, parameter: Parameter, pose: Pose): Int {
val grid = trackGridOf(this, track) ?: return -1
return grid.keyIndexAt(parameter.id, pose[parameter.id] ?: parameter.default)
}
/**
* The ordinal of [track]'s key sitting at [value] on [parameter]'s axis, or -1 when none does.
*
* Within EPS_KEY, the same tolerance the evaluator snaps with - so "the key at this value" means what it
* means everywhere else. The value-addressed sibling of [trackKeyIndexAtPose], for the one case where an
* ordinal cannot be trusted: after a move that may have crossed a neighbour and renumbered the axis.
*
* @param KeyformTrackRef track The track to read.
* @param Parameter parameter The parameter whose axis to read.
* @param Float value The parameter value to look at.
* @return Int The key's ordinal, or -1.
*/
fun PuppetModel.trackKeyIndexAt(track: KeyformTrackRef, parameter: Parameter, value: Float): Int =
trackGridOf(this, track)?.keyIndexAt(parameter.id, value) ?: -1
/** The grid behind [track] - its owner's channel track or its geometry - or null when there is none. */
private fun trackGridOf(puppet: PuppetModel, track: KeyformTrackRef): KeyformGrid<*>? =
when (track) {
is KeyformTrackRef.Channel -> puppet.channelGridsOf(track.owner)?.get(track.target.channel)
is KeyformTrackRef.Geometry -> puppet.geometryGridOf(track.owner)
}
/**
* Removes every key in [keys] as ONE undo step - the sheet's Delete over a multi-key selection.
*
* One step rather than one per key because the user made one gesture; a per-key step would make undoing a
* five-key delete take five presses. Applied in DESCENDING index order so each removal cannot renumber
* the keys the later ones still have to find.
*
* @param List keys The (track, parameter, key ordinal) triples to remove.
*/
fun EditorSession.removeTrackKeys(keys: List<Triple<KeyformTrackRef, Parameter, Int>>) {
if (keys.isEmpty()) {
return
}
mutate(KeyformChange.DeleteKey(channelOf(keys.first().first))) { model ->
keys
.sortedByDescending { (_, _, keyIndex) -> keyIndex }
.fold(model) { current, (track, parameter, keyIndex) ->
current.withTrackKeyRemoved(track, parameter, keyIndex)
}
}
}
@@ -0,0 +1,53 @@
package org.umamo.edit
/*
* The merge's face on the operation settings strip: its one setting, where the survivor lands, as a
* choice row the rigger can switch after the fact. The keys are declared here, in the module that
* runs the merge, so the UI's label table names constants rather than repeating strings.
*/
/** The parameter key and the choice label-key prefix the merge's row carries. */
object MergeParameterKeys {
/** The Merge At row: which vertex the survivor lands on. */
const val TARGET = "merge.target"
/** The label-key prefix of the row's choices; a target's [MergeTarget.parameterKey] follows it. */
const val TARGET_CHOICE_PREFIX = "merge.target."
}
/** The stable choice key of this target, as the strip's row stores it. */
val MergeTarget.parameterKey: String
get() =
when (this) {
MergeTarget.AtCenter -> "center"
MergeTarget.AtFirst -> "first"
MergeTarget.AtLast -> "last"
}
/**
* The strip's rows for a merge that landed at [target]: the Merge At choice over every target.
*
* @param MergeTarget target Where the survivor landed.
* @return List The one row.
*/
fun mergeParameters(target: MergeTarget): List<OperatorParameter> =
listOf(
OperatorParameter.ChoiceParameter(
MergeParameterKeys.TARGET,
MergeParameterKeys.TARGET,
target.parameterKey,
MergeTarget.entries.map { candidate -> ParameterChoice(candidate.parameterKey, MergeParameterKeys.TARGET_CHOICE_PREFIX + candidate.parameterKey) },
),
)
/**
* The target the strip's rows name, or [fallback] when the row is absent or names no known target.
*
* @param List parameters The strip's rows.
* @param MergeTarget fallback The target the merge first ran with.
* @return MergeTarget The target to re-merge at.
*/
fun mergeTargetOf(parameters: List<OperatorParameter>, fallback: MergeTarget): MergeTarget {
val key = parameters.choiceValue(MergeParameterKeys.TARGET, fallback.parameterKey)
return MergeTarget.entries.firstOrNull { candidate -> candidate.parameterKey == key } ?: fallback
}
@@ -0,0 +1,83 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.PuppetModel
/**
* The session's remembered-selection memory: which drawable was last active (so entering Edit mode
* with an empty selection lands somewhere sensible - Blender's remembered selection), and each
* mesh's stashed element selection (stashed when Edit mode is left or the session switches meshes,
* restored per drawable on re-entry when the elements still fit - Blender remembers the mesh
* selection across mode switches per mesh). Transient UI convenience, deliberately NOT part of
* [EditorSnapshot]: undo restores whatever the snapshot holds, this only seeds fresh entries.
*
* セッションの選択記憶。最後にアクティブだった描画対象と、メッシュごとの要素選択スタッシュを保持
* する(Blender のモード切替をまたぐ選択記憶に相当)。スナップショットには含めない。
*/
internal class MeshElementMemory {
/** The last drawable that was active, or null before any; Edit-mode entry falls back to it. */
var lastActiveDrawableId: DrawableId? = null
// Per-mesh element-selection memory, keyed by drawable, plus the select mode remembered alongside.
private val rememberedElementsByDrawable = HashMap<DrawableId, Set<MeshElement>>()
private val rememberedActiveElementByDrawable = HashMap<DrawableId, MeshElement>()
private var rememberedSelectMode: MeshSelectMode? = null
/**
* Stashes each session drawable's element selection into the per-mesh memory, so re-entering Edit
* mode - or switching back to the mesh with Alt+Q - restores it. An emptied mesh clears its slot;
* the select mode is remembered alongside.
*
* @param MeshSelection current The element selection to stash.
*/
fun stash(current: MeshSelection) {
if (current.drawableIds.isEmpty()) {
return
}
rememberedSelectMode = current.selectMode
for (drawableId in current.drawableIds) {
val elements = current.elementsOf(drawableId)
if (elements.isEmpty()) {
rememberedElementsByDrawable.remove(drawableId)
rememberedActiveElementByDrawable.remove(drawableId)
} else {
rememberedElementsByDrawable[drawableId] = elements
}
}
current.activeElement?.let { active -> rememberedActiveElementByDrawable[active.drawableId] = active.element }
}
/**
* Restores the per-mesh remembered elements into [seeded]: each seeded drawable whose stored
* elements still fit its current mesh gets them back (validated per drawable, so one stale mesh
* never discards the others' memory); the remembered select mode returns when anything restored.
*
* @param MeshSelection seeded The freshly seeded session selection.
* @param PuppetModel model The current model (element fit is validated against its meshes).
* @return MeshSelection The seeded selection with the remembered elements folded in.
*/
fun restore(seeded: MeshSelection, model: PuppetModel): MeshSelection {
val restored =
seeded.drawableIds.mapNotNull { drawableId ->
val stored = rememberedElementsByDrawable[drawableId]?.takeIf { elements -> elements.isNotEmpty() } ?: return@mapNotNull null
val probe = seeded.copy(selectMode = rememberedSelectMode ?: seeded.selectMode, elementsByDrawable = mapOf(drawableId to stored))
val fits = MeshSelectionOps.fitsWithinMeshes(probe) { candidateId -> model.drawables.firstOrNull { drawable -> drawable.id == candidateId }?.mesh }
if (fits) drawableId to stored else null
}.toMap()
if (restored.isEmpty()) {
return seeded
}
// The active mesh's remembered active element returns with it (when it is still selected there).
val restoredActive =
seeded.activeDrawableId?.let { activeId ->
rememberedActiveElementByDrawable[activeId]
?.takeIf { element -> restored[activeId]?.contains(element) == true }
?.let { element -> ActiveMeshElement(activeId, element) }
}
return seeded.copy(
selectMode = rememberedSelectMode ?: seeded.selectMode,
elementsByDrawable = restored,
activeElement = restoredActive,
)
}
}
@@ -0,0 +1,520 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
/**
* The Edit-mode selection domain, mirroring Blender's vertex / edge / face select modes: which kind of
* mesh element the pointer picks and the selection stores. Only the current mode's domain is stored in
* [MeshSelection.elementsByDrawable]; highlights in the other domains are derived for display, and
* switching modes converts the stored sets (see [MeshSelectionOps.changeSelectMode]).
*
* 編集モードの選択対象の種類。Blender の頂点・辺・面選択モードに対応する。
*/
enum class MeshSelectMode {
Vertex,
Edge,
Face,
}
/**
* One selectable mesh element: a vertex, an undirected edge, or a face. Element identity is LOCAL to
* its drawable's mesh (a vertex index means nothing without knowing which mesh), which is why
* [MeshSelection] stores elements per drawable and the active element carries its drawable alongside.
* The mesh topology is immutable while editing (copy-on-write replaces only positions), so vertex
* indices, canonical (low, high) edge pairs, and triangle indices are stable identities across every
* gesture.
*
* メッシュの選択可能要素。頂点・無向辺・面(三角形)のいずれか。要素の同一性はメッシュ内ローカル。
*/
sealed interface MeshElement {
/**
* A single mesh vertex.
*
* @property Int index The vertex index (into the mesh's vertex list).
*/
data class Vertex(val index: Int) : MeshElement
/**
* An undirected mesh edge, canonicalized so (a, b) and (b, a) are one identity. Construct via [of].
*
* @property Int endpointLow The smaller endpoint vertex index.
* @property Int endpointHigh The larger endpoint vertex index.
*/
data class Edge(val endpointLow: Int, val endpointHigh: Int) : MeshElement {
companion object {
/**
* Builds the canonical undirected edge for two endpoint vertex indices, given in either order.
*
* @param Int vertexA One endpoint vertex index.
* @param Int vertexB The other endpoint vertex index.
* @return Edge The canonical (low, high) edge.
*/
fun of(vertexA: Int, vertexB: Int): Edge =
if (vertexA <= vertexB) {
Edge(vertexA, vertexB)
} else {
Edge(vertexB, vertexA)
}
}
}
/**
* A single mesh face. The mesh is triangles-only, so a face is one triangle of the index list.
*
* @property Int triangleIndex The triangle ordinal (three consecutive entries of the index list).
*/
data class Face(val triangleIndex: Int) : MeshElement
}
/**
* The active (primary) element of an Edit session: the last-touched element together with the drawable
* whose mesh it lives in - element indices are mesh-local, so the pair is the element's full identity.
*
* @property DrawableId drawableId The drawable whose mesh holds the element.
* @property MeshElement element The last-touched element.
*/
data class ActiveMeshElement(val drawableId: DrawableId, val element: MeshElement)
/**
* An immutable Edit-mode sub-object selection over one or more drawables' meshes: which meshes are in
* the edit session, the select mode (vertex / edge / face), and the selected elements per mesh with the
* active (primary) one. This is the sub-object analog of [Selection] - where object-mode selects whole
* entities, Edit mode selects elements inside the session meshes - and the multi-mesh shape is what lets
* a rigger edit several art meshes at once (entering Edit with a multi-selection, and later the glue
* workflows that need two meshes live together).
*
* Only the current [selectMode]'s domain is ever stored in [elementsByDrawable] (a vertex-mode selection
* holds only [MeshElement.Vertex] members, and so on). Cross-domain highlights - an edge lighting up
* because both endpoints are selected in vertex mode - are derived for display via [MeshTopology], never
* stored, which is exactly Blender's model.
*
* [drawableIds] is empty when Edit mode is inert (entered without an editable drawable); the overlay
* then draws nothing and the transform operators no-op. [activeDrawableId] is Blender's active object
* within the session - the mesh a click last landed on, which anchors per-mesh actions (select-mode
* conversion display, the status bar's denominators). [activeElement] is the element analog of
* [Selection.active]: the last-touched element with its drawable; it is always a member of its
* drawable's element set, or null when nothing is selected.
*
* @property List<DrawableId> drawableIds The meshes in the edit session, in selection order.
* @property DrawableId? activeDrawableId The session's active mesh, or null when the session is inert.
* @property MeshSelectMode selectMode The element domain clicks select (vertex / edge / face).
* @property Map<DrawableId, Set<MeshElement>> elementsByDrawable The selected elements per mesh, all of
* the current mode's domain; a drawable with no selection may be absent.
* @property ActiveMeshElement? activeElement The primary element (last touched), or null when none.
*/
data class MeshSelection(
val drawableIds: List<DrawableId> = emptyList(),
val activeDrawableId: DrawableId? = null,
val selectMode: MeshSelectMode = MeshSelectMode.Vertex,
val elementsByDrawable: Map<DrawableId, Set<MeshElement>> = emptyMap(),
val activeElement: ActiveMeshElement? = null,
) {
/** True when no elements are selected on any mesh (the session may still hold drawables). */
val isEmpty: Boolean get() = elementsByDrawable.values.all { elements -> elements.isEmpty() }
/** The number of selected elements across every session mesh. */
val size: Int get() = elementsByDrawable.values.sumOf { elements -> elements.size }
/**
* The selected elements of one mesh (empty when the drawable has no selection or is not in the
* session).
*
* @param DrawableId drawableId The mesh to read.
* @return Set<MeshElement> That mesh's selected elements.
*/
fun elementsOf(drawableId: DrawableId): Set<MeshElement> = elementsByDrawable[drawableId] ?: emptySet()
/**
* Reports whether the given element is selected on the given mesh.
*
* @param DrawableId drawableId The mesh the element lives in.
* @param MeshElement element The element to test.
* @return Boolean True when selected.
*/
fun contains(drawableId: DrawableId, element: MeshElement): Boolean = element in elementsOf(drawableId)
companion object {
/**
* An empty Edit session over the given meshes: nothing selected, the first (or given) mesh active.
*
* @param List<DrawableId> drawableIds The session meshes, in selection order.
* @param DrawableId? activeDrawableId The active mesh; defaults to the first.
* @return MeshSelection The seeded session selection.
*/
fun editing(drawableIds: List<DrawableId>, activeDrawableId: DrawableId? = drawableIds.firstOrNull()): MeshSelection =
MeshSelection(drawableIds = drawableIds, activeDrawableId = activeDrawableId)
}
}
/**
* Pure transformations over a [MeshSelection], one per selection gesture (mirroring [SelectionOps]).
* Element gestures name the drawable they land on (element identity is mesh-local); whole-session
* gestures (select all, invert, mode conversion) take a mesh provider so each session mesh converts
* against its own topology. Each function returns a new immutable [MeshSelection] over the same
* session and never mutates its input, so they are unit-testable without Compose. The active element
* is maintained per the [MeshSelection] invariant: always a member of its drawable's element set, or
* null when nothing remains.
*/
object MeshSelectionOps {
/**
* Rebuilds the per-drawable element map with one drawable's set replaced, dropping empty sets so the
* map never accumulates stale keys.
*
* @param MeshSelection selection The selection whose map to rebuild.
* @param DrawableId drawableId The drawable whose set changes.
* @param Set<MeshElement> elements That drawable's new element set.
* @return Map<DrawableId, Set<MeshElement>> The rebuilt map.
*/
private fun withElements(
selection: MeshSelection,
drawableId: DrawableId,
elements: Set<MeshElement>,
): Map<DrawableId, Set<MeshElement>> =
if (elements.isEmpty()) {
selection.elementsByDrawable - drawableId
} else {
selection.elementsByDrawable + (drawableId to elements)
}
/**
* Replaces the whole selection with a single element (a plain click): every session mesh clears and
* only [element] on [drawableId] remains, active, with its mesh becoming the session's active mesh.
*
* @param MeshSelection selection The selection to modify.
* @param DrawableId drawableId The mesh the click landed on.
* @param MeshElement element The sole element to select.
* @return MeshSelection A selection holding only [element], with it active.
*/
fun replace(selection: MeshSelection, drawableId: DrawableId, element: MeshElement): MeshSelection =
selection.copy(
activeDrawableId = drawableId,
elementsByDrawable = mapOf(drawableId to setOf(element)),
activeElement = ActiveMeshElement(drawableId, element),
)
/**
* Toggles an element's membership on its mesh (a Shift or Ctrl / Cmd click, Blender-style): removes
* it when present, adds it otherwise. When added it becomes active (and its mesh the active mesh);
* when removed the active element falls back to another member of the same mesh, or null.
*
* @param MeshSelection selection The selection to modify.
* @param DrawableId drawableId The mesh the click landed on.
* @param MeshElement element The element to toggle.
* @return MeshSelection The resulting selection.
*/
fun toggle(selection: MeshSelection, drawableId: DrawableId, element: MeshElement): MeshSelection {
val current = selection.elementsOf(drawableId)
return if (element in current) {
val remaining = current - element
val fallback = remaining.lastOrNull()?.let { survivor -> ActiveMeshElement(drawableId, survivor) }
selection.copy(
activeDrawableId = drawableId,
elementsByDrawable = withElements(selection, drawableId, remaining),
activeElement = if (selection.activeElement?.drawableId == drawableId && selection.activeElement.element == element) fallback else selection.activeElement,
)
} else {
selection.copy(
activeDrawableId = drawableId,
elementsByDrawable = withElements(selection, drawableId, current + element),
activeElement = ActiveMeshElement(drawableId, element),
)
}
}
/**
* Adds an element without removing anything (an additive gesture), making it active and its mesh the
* session's active mesh.
*
* @param MeshSelection selection The selection to extend.
* @param DrawableId drawableId The mesh the element lives in.
* @param MeshElement element The element to add.
* @return MeshSelection The extended selection.
*/
fun add(selection: MeshSelection, drawableId: DrawableId, element: MeshElement): MeshSelection =
selection.copy(
activeDrawableId = drawableId,
elementsByDrawable = withElements(selection, drawableId, selection.elementsOf(drawableId) + element),
activeElement = ActiveMeshElement(drawableId, element),
)
/**
* Applies a box (rubber-band) selection across the session meshes: replaces every mesh's element set
* with its entry in [elementsByDrawable], or unions them in when [additive]. The active element is
* kept when it remains selected, otherwise it drops to null (a box has no single "last touched"
* element).
*
* @param MeshSelection selection The selection to modify.
* @param Map<DrawableId, Set<MeshElement>> elementsByDrawable The enclosed elements per session mesh.
* @param Boolean additive True to union with the current sets (Shift box), false to replace them.
* @return MeshSelection The resulting selection.
*/
fun box(selection: MeshSelection, elementsByDrawable: Map<DrawableId, Set<MeshElement>>, additive: Boolean): MeshSelection {
val resulting = HashMap<DrawableId, Set<MeshElement>>()
if (additive) {
selection.elementsByDrawable.forEach { (drawableId, elements) -> resulting[drawableId] = elements }
elementsByDrawable.forEach { (drawableId, elements) ->
resulting[drawableId] = (resulting[drawableId] ?: emptySet()) + elements
}
} else {
elementsByDrawable.forEach { (drawableId, elements) ->
if (elements.isNotEmpty()) {
resulting[drawableId] = elements
}
}
}
resulting.values.removeAll { elements -> elements.isEmpty() }
val active = selection.activeElement?.takeIf { active -> active.element in (resulting[active.drawableId] ?: emptySet()) }
return selection.copy(elementsByDrawable = resulting, activeElement = active)
}
/**
* Removes elements per mesh (the erase half of a Circle-select stroke), keeping the active element
* only when it survives. The mirror of [box]'s additive union.
*
* @param MeshSelection selection The selection to shrink.
* @param Map<DrawableId, Set<MeshElement>> elementsByDrawable The elements to deselect per mesh.
* @return MeshSelection The selection with those elements removed.
*/
fun remove(selection: MeshSelection, elementsByDrawable: Map<DrawableId, Set<MeshElement>>): MeshSelection {
val resulting = HashMap<DrawableId, Set<MeshElement>>(selection.elementsByDrawable)
elementsByDrawable.forEach { (drawableId, elements) ->
val remaining = (resulting[drawableId] ?: emptySet()) - elements
if (remaining.isEmpty()) {
resulting.remove(drawableId)
} else {
resulting[drawableId] = remaining
}
}
val active = selection.activeElement?.takeIf { active -> active.element in (resulting[active.drawableId] ?: emptySet()) }
return selection.copy(elementsByDrawable = resulting, activeElement = active)
}
/**
* Clears the selection, keeping the session meshes and mode (the Edit session stays open, nothing
* selected).
*
* @param MeshSelection selection The selection to clear.
* @return MeshSelection The selection with empty element sets.
*/
fun clear(selection: MeshSelection): MeshSelection =
selection.copy(elementsByDrawable = emptyMap(), activeElement = null)
/**
* Switches the select mode, converting every session mesh's stored elements into the new domain with
* Blender's flush-down / derive-up rules. Flushing down (to vertex) expands every element to the
* vertices it covers, so selection is never lost. Deriving up is strict per Blender: an edge
* qualifies only when both endpoints were selected, and a face only when all of its own vertices
* (from vertex mode) or all three of its own edges (from edge mode) were selected. The active
* element drops to null on conversion (no single "last touched" element survives a domain change);
* a same-mode call returns the selection unchanged. A session mesh whose triangles the provider
* cannot resolve converts to empty.
*
* @param MeshSelection selection The selection to convert.
* @param MeshSelectMode newMode The target select mode.
* @param Function triangleIndicesOf Resolves a session mesh's triangle indices, or null when absent.
* @return MeshSelection The selection in [newMode] with the converted element sets.
*/
fun changeSelectMode(
selection: MeshSelection,
newMode: MeshSelectMode,
triangleIndicesOf: (DrawableId) -> IntArray?,
): MeshSelection {
if (newMode == selection.selectMode) {
return selection
}
val converted = HashMap<DrawableId, Set<MeshElement>>()
for ((drawableId, elements) in selection.elementsByDrawable) {
val triangleIndices = triangleIndicesOf(drawableId) ?: continue
val convertedElements = convertElements(elements, selection.selectMode, newMode, triangleIndices)
if (convertedElements.isNotEmpty()) {
converted[drawableId] = convertedElements
}
}
return selection.copy(selectMode = newMode, elementsByDrawable = converted, activeElement = null)
}
/**
* Converts one mesh's element set between select-mode domains (the single-mesh core of
* [changeSelectMode]; see its docblock for the flush / derive rules).
*
* @param Set<MeshElement> elements The stored elements, all of [fromMode]'s domain.
* @param MeshSelectMode fromMode The current domain.
* @param MeshSelectMode newMode The target domain.
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @return Set<MeshElement> The converted set in [newMode]'s domain.
*/
private fun convertElements(
elements: Set<MeshElement>,
fromMode: MeshSelectMode,
newMode: MeshSelectMode,
triangleIndices: IntArray,
): Set<MeshElement> =
when (newMode) {
MeshSelectMode.Vertex ->
MeshTopology.coveredVertexIndices(elements, triangleIndices)
.map { vertexIndex -> MeshElement.Vertex(vertexIndex) }
.toSet()
MeshSelectMode.Edge ->
when (fromMode) {
MeshSelectMode.Vertex ->
MeshTopology.edgesWithBothEndpointsSelected(
triangleIndices,
MeshTopology.coveredVertexIndices(elements, triangleIndices),
)
MeshSelectMode.Face ->
elements
.filterIsInstance<MeshElement.Face>()
.flatMap { face -> MeshTopology.edgesOfTriangle(triangleIndices, face.triangleIndex) }
.toSet()
// Unreachable: the same-mode case returned above; kept for exhaustiveness.
MeshSelectMode.Edge -> elements
}
MeshSelectMode.Face ->
when (fromMode) {
MeshSelectMode.Vertex ->
MeshTopology.facesWithAllVerticesSelected(
triangleIndices,
MeshTopology.coveredVertexIndices(elements, triangleIndices),
)
MeshSelectMode.Edge ->
MeshTopology.facesWithAllEdgesSelected(
triangleIndices,
elements.filterIsInstance<MeshElement.Edge>().toSet(),
)
// Unreachable: the same-mode case returned above; kept for exhaustiveness.
MeshSelectMode.Face -> elements
}
}
/**
* Every element of a select mode's domain over a mesh: all vertices, all unique edges, or all faces.
* The full set [selectAll] fills and [invert] complements against. The vertex count comes from the
* mesh because an isolated vertex (one in no triangle) is still a valid element that the triangle
* indices alone would miss.
*
* @param MeshSelectMode mode The domain to enumerate.
* @param DrawableMesh mesh The mesh whose domain to enumerate.
* @return Set<MeshElement> Every element of [mode]'s domain.
*/
private fun allElements(mode: MeshSelectMode, mesh: DrawableMesh): Set<MeshElement> =
when (mode) {
MeshSelectMode.Vertex -> (0 until mesh.vertexCount).map { vertexIndex -> MeshElement.Vertex(vertexIndex) }.toSet<MeshElement>()
MeshSelectMode.Edge -> MeshTopology.uniqueEdges(mesh.indices).toSet<MeshElement>()
MeshSelectMode.Face -> (0 until mesh.triangleCount).map { triangleIndex -> MeshElement.Face(triangleIndex) }.toSet<MeshElement>()
}
/**
* Selects every element of the current select mode's domain on every session mesh (Blender's Select
* All). The active element is kept (it is necessarily still selected); from an empty selection it
* stays null. A session mesh the provider cannot resolve contributes nothing.
*
* @param MeshSelection selection The selection to fill.
* @param Function meshOf Resolves a session drawable's mesh, or null when absent.
* @return MeshSelection The selection holding every element of its domain on every session mesh.
*/
fun selectAll(selection: MeshSelection, meshOf: (DrawableId) -> DrawableMesh?): MeshSelection {
val filled = HashMap<DrawableId, Set<MeshElement>>()
for (drawableId in selection.drawableIds) {
val mesh = meshOf(drawableId) ?: continue
val all = allElements(selection.selectMode, mesh)
if (all.isNotEmpty()) {
filled[drawableId] = all
}
}
val active = selection.activeElement?.takeIf { active -> active.element in (filled[active.drawableId] ?: emptySet()) }
return selection.copy(elementsByDrawable = filled, activeElement = active)
}
/**
* Inverts the selection within the current select mode's domain on every session mesh (Blender's
* Ctrl+I): every element not currently selected becomes selected and vice versa. The active element
* drops unless it happens to remain selected (in practice it drops - it was selected before).
*
* @param MeshSelection selection The selection to invert.
* @param Function meshOf Resolves a session drawable's mesh, or null when absent.
* @return MeshSelection The inverted selection.
*/
fun invert(selection: MeshSelection, meshOf: (DrawableId) -> DrawableMesh?): MeshSelection {
val inverted = HashMap<DrawableId, Set<MeshElement>>()
for (drawableId in selection.drawableIds) {
val mesh = meshOf(drawableId) ?: continue
val complement = allElements(selection.selectMode, mesh) - selection.elementsOf(drawableId)
if (complement.isNotEmpty()) {
inverted[drawableId] = complement
}
}
val active = selection.activeElement?.takeIf { active -> active.element in (inverted[active.drawableId] ?: emptySet()) }
return selection.copy(elementsByDrawable = inverted, activeElement = active)
}
/**
* Unions a connectivity island's elements into one mesh's selection, in the CURRENT select mode's
* domain - Blender's Select Linked (L): every vertex of the island in vertex mode, every edge with
* both endpoints in the island in edge mode, every face with all vertices in the island in face
* mode. Additive by design (repeated L grows the selection island by island); the active element
* is left untouched (still a member - the union only adds).
*
* @param MeshSelection selection The selection to extend.
* @param DrawableId drawableId The mesh the island lives in.
* @param Set<Int> islandVertices The island's vertex indices (a [MeshTopology.connectedVertices] result).
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @return MeshSelection The selection with the island's elements added.
*/
fun selectLinked(
selection: MeshSelection,
drawableId: DrawableId,
islandVertices: Set<Int>,
triangleIndices: IntArray,
): MeshSelection {
val islandElements: Set<MeshElement> =
when (selection.selectMode) {
MeshSelectMode.Vertex -> islandVertices.map { vertexIndex -> MeshElement.Vertex(vertexIndex) }.toSet()
MeshSelectMode.Edge -> MeshTopology.edgesWithBothEndpointsSelected(triangleIndices, islandVertices)
MeshSelectMode.Face -> MeshTopology.facesWithAllVerticesSelected(triangleIndices, islandVertices)
}
if (islandElements.isEmpty()) {
return selection
}
return selection.copy(
elementsByDrawable = withElements(selection, drawableId, selection.elementsOf(drawableId) + islandElements),
)
}
/**
* Reports whether every selected element still exists in its mesh: vertex indices within the vertex
* count, edges present in the mesh's edge set, and face ordinals within the triangle count - across
* every session mesh. Used to decide whether a stashed selection may be restored (re-entering Edit
* mode) after the meshes may have changed underneath it. A session mesh the provider cannot resolve
* fails the check.
*
* @param MeshSelection selection The selection to validate.
* @param Function meshOf Resolves a session drawable's mesh, or null when absent.
* @return Boolean True when every element still fits its mesh.
*/
fun fitsWithinMeshes(selection: MeshSelection, meshOf: (DrawableId) -> DrawableMesh?): Boolean {
for ((drawableId, elements) in selection.elementsByDrawable) {
val mesh = meshOf(drawableId) ?: return false
// Built lazily: vertex- and face-only selections never pay for the edge scan.
val meshEdges by lazy { MeshTopology.uniqueEdges(mesh.indices).toSet() }
for (element in elements) {
val fits =
when (element) {
is MeshElement.Vertex -> element.index in 0 until mesh.vertexCount
is MeshElement.Edge -> element in meshEdges
is MeshElement.Face -> element.triangleIndex in 0 until mesh.triangleCount
}
if (!fits) {
return false
}
}
}
return true
}
}
@@ -0,0 +1,231 @@
package org.umamo.edit
/**
* Pure topology queries over a triangle index list (three vertex indices per triangle). The single
* source of truth for Blender's select-mode rules: [MeshSelectionOps.changeSelectMode] uses these to
* convert a selection between domains, and the gizmo overlay uses the same derive-up functions for its
* cross-domain display highlights - so the flush / derive semantics live (and are tested) once.
*
* 三角形インデックス列に対する純粋なトポロジ照会。選択モード変換と表示ハイライトの共通基盤。
*/
object MeshTopology {
/**
* The deduplicated undirected edges of a triangle index list. Each interior edge is shared by two
* triangles but must appear once, so edges are canonicalized to (low, high) before deduplication.
*
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @return List<MeshElement.Edge> The unique edges, in first-encounter order.
*/
fun uniqueEdges(triangleIndices: IntArray): List<MeshElement.Edge> {
val edges = LinkedHashSet<MeshElement.Edge>()
val triangleCount = triangleIndices.size / 3
for (triangleIndex in 0 until triangleCount) {
edges.addAll(edgesOfTriangle(triangleIndices, triangleIndex))
}
return edges.toList()
}
/**
* The three canonical edges of one triangle.
*
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @param Int triangleIndex The triangle ordinal.
* @return List<MeshElement.Edge> The triangle's edges.
*/
fun edgesOfTriangle(triangleIndices: IntArray, triangleIndex: Int): List<MeshElement.Edge> {
val cornerA = triangleIndices[triangleIndex * 3]
val cornerB = triangleIndices[triangleIndex * 3 + 1]
val cornerC = triangleIndices[triangleIndex * 3 + 2]
return listOf(
MeshElement.Edge.of(cornerA, cornerB),
MeshElement.Edge.of(cornerB, cornerC),
MeshElement.Edge.of(cornerC, cornerA),
)
}
/**
* The three vertex indices of one triangle.
*
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @param Int triangleIndex The triangle ordinal.
* @return Set<Int> The triangle's vertex indices.
*/
fun verticesOfTriangle(triangleIndices: IntArray, triangleIndex: Int): Set<Int> =
setOf(
triangleIndices[triangleIndex * 3],
triangleIndices[triangleIndex * 3 + 1],
triangleIndices[triangleIndex * 3 + 2],
)
/**
* The union of vertices covered by a set of elements: a vertex covers itself, an edge its two
* endpoints, a face its three corners. This is the flush-down rule (any mode to vertex mode), and
* what the G / S / R operators transform for an edge or face selection.
*
* @param Set<MeshElement> elements The selected elements (any mix of domains).
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @return Set<Int> The covered vertex indices.
*/
fun coveredVertexIndices(elements: Set<MeshElement>, triangleIndices: IntArray): Set<Int> {
val covered = HashSet<Int>()
for (element in elements) {
when (element) {
is MeshElement.Vertex -> covered.add(element.index)
is MeshElement.Edge -> {
covered.add(element.endpointLow)
covered.add(element.endpointHigh)
}
is MeshElement.Face -> covered.addAll(verticesOfTriangle(triangleIndices, element.triangleIndex))
}
}
return covered
}
/**
* The edges whose both endpoints are in the selected vertex set - the vertex-to-edge derive-up rule,
* also used to highlight edges while selecting vertices.
*
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @param Set<Int> selectedVertexIndices The selected vertex indices.
* @return Set<MeshElement.Edge> The qualifying edges.
*/
fun edgesWithBothEndpointsSelected(triangleIndices: IntArray, selectedVertexIndices: Set<Int>): Set<MeshElement.Edge> =
uniqueEdges(triangleIndices)
.filter { edge -> edge.endpointLow in selectedVertexIndices && edge.endpointHigh in selectedVertexIndices }
.toSet()
/**
* The faces whose every vertex is in the selected vertex set - the vertex-to-face derive-up rule,
* also used to highlight faces while selecting vertices.
*
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @param Set<Int> selectedVertexIndices The selected vertex indices.
* @return Set<MeshElement.Face> The qualifying faces.
*/
fun facesWithAllVerticesSelected(triangleIndices: IntArray, selectedVertexIndices: Set<Int>): Set<MeshElement.Face> {
val faces = HashSet<MeshElement.Face>()
val triangleCount = triangleIndices.size / 3
for (triangleIndex in 0 until triangleCount) {
if (verticesOfTriangle(triangleIndices, triangleIndex).all { vertexIndex -> vertexIndex in selectedVertexIndices }) {
faces.add(MeshElement.Face(triangleIndex))
}
}
return faces
}
/**
* The faces whose all three own edges are in the selected edge set - the edge-to-face derive-up rule,
* also used to highlight faces while selecting edges. Strict per Blender: a face whose vertices are
* merely covered by neighboring faces' selected edges does not qualify.
*
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @param Set<MeshElement.Edge> selectedEdges The selected (canonical) edges.
* @return Set<MeshElement.Face> The qualifying faces.
*/
fun facesWithAllEdgesSelected(triangleIndices: IntArray, selectedEdges: Set<MeshElement.Edge>): Set<MeshElement.Face> {
val faces = HashSet<MeshElement.Face>()
val triangleCount = triangleIndices.size / 3
for (triangleIndex in 0 until triangleCount) {
if (edgesOfTriangle(triangleIndices, triangleIndex).all { edge -> edge in selectedEdges }) {
faces.add(MeshElement.Face(triangleIndex))
}
}
return faces
}
/**
* The per-vertex neighbor table of a triangle mesh: entry v lists the vertices sharing an edge with
* vertex v, deduplicated (an interior edge is shared by two triangles but yields one neighbor pair).
* Vertices outside every triangle (or an out-of-range index in a malformed list) get an empty entry.
* Build once per mesh and feed the connectivity walks below - Select Linked's flood fill and the
* Individual Origins island split.
*
* @param Int vertexCount The mesh's vertex count (the table's size).
* @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle).
* @return List<IntArray> The neighbor vertex indices per vertex.
*/
fun buildVertexAdjacency(vertexCount: Int, triangleIndices: IntArray): List<IntArray> {
val neighborSets = List(vertexCount) { HashSet<Int>() }
fun connect(vertexA: Int, vertexB: Int) {
if (vertexA in 0 until vertexCount && vertexB in 0 until vertexCount && vertexA != vertexB) {
neighborSets[vertexA].add(vertexB)
neighborSets[vertexB].add(vertexA)
}
}
val triangleCount = triangleIndices.size / 3
for (triangleIndex in 0 until triangleCount) {
val cornerA = triangleIndices[triangleIndex * 3]
val cornerB = triangleIndices[triangleIndex * 3 + 1]
val cornerC = triangleIndices[triangleIndex * 3 + 2]
connect(cornerA, cornerB)
connect(cornerB, cornerC)
connect(cornerC, cornerA)
}
return neighborSets.map { neighbors -> neighbors.toIntArray() }
}
/**
* Every vertex connected to [seedVertexIndex] through the mesh's edges, the seed included - the flood
* fill behind Select Linked (Blender's L). An out-of-range seed yields an empty set.
*
* @param List<IntArray> adjacency The neighbor table from [buildVertexAdjacency].
* @param Int seedVertexIndex The vertex to flood from.
* @return Set<Int> The seed's whole connected component.
*/
fun connectedVertices(adjacency: List<IntArray>, seedVertexIndex: Int): Set<Int> {
if (seedVertexIndex !in adjacency.indices) {
return emptySet()
}
val reached = HashSet<Int>()
val frontier = ArrayDeque<Int>()
reached.add(seedVertexIndex)
frontier.add(seedVertexIndex)
while (frontier.isNotEmpty()) {
val vertexIndex = frontier.removeFirst()
for (neighbor in adjacency[vertexIndex]) {
if (reached.add(neighbor)) {
frontier.add(neighbor)
}
}
}
return reached
}
/**
* Splits a vertex subset into its connected islands: the components of the sub-graph induced on
* [vertexIndices] (two selected vertices join an island only when a mesh edge connects them within
* the subset). This is Blender's Individual Origins grouping - each island transforms about its own
* pivot. Out-of-range indices are dropped; the island order follows the subset's iteration order.
*
* @param List<IntArray> adjacency The neighbor table from [buildVertexAdjacency].
* @param Set<Int> vertexIndices The vertex subset to split.
* @return List<Set<Int>> The islands, each a disjoint subset of [vertexIndices].
*/
fun selectionIslands(adjacency: List<IntArray>, vertexIndices: Set<Int>): List<Set<Int>> {
val unvisited = vertexIndices.filterTo(LinkedHashSet()) { vertexIndex -> vertexIndex in adjacency.indices }
val islands = ArrayList<Set<Int>>()
while (unvisited.isNotEmpty()) {
val seed = unvisited.first()
val island = HashSet<Int>()
val frontier = ArrayDeque<Int>()
island.add(seed)
unvisited.remove(seed)
frontier.add(seed)
while (frontier.isNotEmpty()) {
val vertexIndex = frontier.removeFirst()
for (neighbor in adjacency[vertexIndex]) {
if (neighbor in unvisited) {
unvisited.remove(neighbor)
island.add(neighbor)
frontier.add(neighbor)
}
}
}
islands.add(island)
}
return islands
}
}
@@ -0,0 +1,220 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.GluePair
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.MeshForm
import org.umamo.runtime.model.PuppetModel
/**
* How one vertex of a topology-edited mesh derives its keyform deltas (and its glue identity) from the
* old mesh's vertices. A topology operation changes the vertex count, and every keyform cell's
* positionDeltas array is parallel to the positions (stride 2 * vertexCount) - so each NEW vertex must
* say where its per-cell deltas come from:
*
* - [FromOld] copies one old vertex's deltas verbatim (a kept or duplicated vertex).
* - [AverageOf] averages several old vertices' deltas (a merge's surviving vertex).
* - [LerpOf] interpolates two old vertices' deltas by t (a split point on an old edge).
*
* トポロジ編集後の各頂点が、旧頂点からどのようにキーフォームのデルタを引き継ぐかの指定。
*/
sealed interface VertexSource {
/**
* The new vertex is old vertex [oldIndex], kept or duplicated: its deltas copy verbatim.
*
* @property Int oldIndex The old vertex the deltas copy from.
*/
data class FromOld(val oldIndex: Int) : VertexSource
/**
* The new vertex merges several old vertices: its deltas are their per-cell mean.
*
* @property List<Int> oldIndices The merged old vertices.
*/
data class AverageOf(val oldIndices: List<Int>) : VertexSource
/**
* The new vertex splits the old edge (oldA, oldB) at parameter [t]: its deltas lerp accordingly.
*
* @property Int oldA The edge's first old endpoint.
* @property Int oldB The edge's second old endpoint.
* @property Float t The split parameter (0 = at oldA, 1 = at oldB).
*/
data class LerpOf(val oldA: Int, val oldB: Int, val t: Float) : VertexSource
}
/**
* One topology edit of one drawable's mesh, ready to commit: the complete replacement mesh (positions,
* uvs, and indices all sized to the new vertex count) plus one [VertexSource] per NEW vertex, from
* which [withMeshTopologyEdit] rebuilds every keyform cell's deltas and remaps the glue pairs. The op
* builders in MeshTopologyOps produce these; they never touch the model themselves.
*
* 1つの描画メッシュのトポロジ編集。置き換えメッシュと、新頂点ごとのデルタ導出指定を持つ。
*
* @property DrawableMesh newMesh The replacement mesh (a freshly built instance).
* @property List<VertexSource> vertexSources One source per new vertex, in vertex order.
*/
class MeshTopologyEdit(
val newMesh: DrawableMesh,
val vertexSources: List<VertexSource>,
)
/**
* Applies a topology edit to one drawable: swaps in the full replacement mesh, rebuilds EVERY keyform
* cell's positionDeltas to the new vertex count per the edit's [VertexSource]s (copy / average / lerp -
* so a parameter scrub after the edit still deforms sanely), and remaps the model's glue pairs through
* the old-to-new vertex mapping (a pair whose vertex was removed is dropped rather than left dangling).
* Everything else structurally shares with the receiver (the copy-on-write discipline). Returns the
* same instance when the drawable is missing, carries no mesh, or the edit's source list does not match
* its new mesh (a malformed edit must not corrupt the model).
*
* トポロジ編集の適用。メッシュ全体を差し替え、全キーフォームセルのデルタを新頂点数に再構築し、
* グルー対も旧→新の対応で再マップする(消えた頂点の対は破棄)。
*
* @param DrawableId id The drawable whose mesh the edit replaces.
* @param MeshTopologyEdit edit The edit to apply.
* @return PuppetModel The edited model, or this instance on a no-op.
*/
fun PuppetModel.withMeshTopologyEdit(id: DrawableId, edit: MeshTopologyEdit): PuppetModel {
val drawable = drawables.firstOrNull { candidate -> candidate.id == id } ?: return this
val oldMesh = drawable.mesh ?: return this
val newVertexCount = edit.newMesh.vertexCount
if (edit.vertexSources.size != newVertexCount) {
return this
}
// Rebuild each geometry cell's deltas at the new stride, deriving per vertex from the old deltas.
// The channel tracks (multiply / screen tints, opacity, draw order, ...) carry no per-vertex data, so a
// topology edit leaves them untouched entirely - only the per-vertex geometry cells need this remap.
val newGeometry =
drawable.geometryGrid?.let { grid ->
KeyformGrid(
axes = grid.axes,
cells =
grid.cells.map { cell ->
KeyformCell(cell.coordinate, remapMeshDeltas(cell.form, edit.vertexSources, oldMesh.vertexCount))
},
)
}
// Blend-shape forms are per-vertex too, so they need the same remap to the new vertex count; leaving
// them at the old count would silently zero every blend contribution after a topology edit.
val newBlendShapes =
drawable.blendShapes.map { binding ->
binding.copy(
forms =
binding.forms.map { form ->
form?.let {
MeshForm(
remapMeshDeltas(MeshDeltaForm(it.positionDeltas), edit.vertexSources, oldMesh.vertexCount).positionDeltas,
it.drawOrder,
it.opacity,
it.multiplyColor,
it.screenColor,
)
}
},
)
}
// The old-to-new vertex mapping glue remapping resolves through: a kept / duplicated / merged old
// vertex maps to the FIRST new vertex that claims it; an unclaimed old vertex maps to -1 (removed).
// First-claim is deliberate for duplicates: the kept originals (enumerated before the copies) claim
// their old indices, so a glue weld stays on the original and the copy floats free.
val oldToNewIndex = IntArray(oldMesh.vertexCount) { -1 }
edit.vertexSources.forEachIndexed { newIndex, source ->
when (source) {
is VertexSource.FromOld ->
if (source.oldIndex in 0 until oldMesh.vertexCount && oldToNewIndex[source.oldIndex] == -1) {
oldToNewIndex[source.oldIndex] = newIndex
}
is VertexSource.AverageOf ->
for (oldIndex in source.oldIndices) {
if (oldIndex in 0 until oldMesh.vertexCount && oldToNewIndex[oldIndex] == -1) {
oldToNewIndex[oldIndex] = newIndex
}
}
// A split point is a brand-new vertex; it claims no old identity.
is VertexSource.LerpOf -> {}
}
}
val newDrawables =
drawables.map { candidate ->
if (candidate.id == id) {
candidate.copy(mesh = edit.newMesh, geometryGrid = newGeometry, blendShapes = newBlendShapes)
} else {
candidate
}
}
val newGlues =
glues.map { glue ->
if (glue.meshA != id && glue.meshB != id) {
glue
} else {
val remappedPairs =
glue.pairs.mapNotNull { pair ->
val newIndexA = if (glue.meshA == id) oldToNewIndex.getOrElse(pair.indexA) { -1 } else pair.indexA
val newIndexB = if (glue.meshB == id) oldToNewIndex.getOrElse(pair.indexB) { -1 } else pair.indexB
if (newIndexA < 0 || newIndexB < 0) {
// The welded vertex no longer exists: the pair is dropped, never left dangling.
null
} else {
GluePair(newIndexA, newIndexB, pair.weightA, pair.weightB)
}
}
glue.copy(pairs = remappedPairs)
}
}
return copy(drawables = newDrawables, glues = newGlues)
}
/**
* Rebuilds one keyform cell's [MeshForm] at the new vertex count: each new vertex's delta pair copies,
* averages, or lerps from the old form's deltas per its [VertexSource]. An old index beyond the old
* form's array (a malformed grid) contributes zero, keeping the rebuild total.
*
* @param MeshForm form The old cell form (deltas at the old stride).
* @param List<VertexSource> vertexSources One source per new vertex.
* @param Int oldVertexCount The old mesh's vertex count (bounds the old delta reads).
* @return MeshForm The rebuilt form (deltas at the new stride; drawOrder / opacity carried).
*/
private fun remapMeshDeltas(form: MeshDeltaForm, vertexSources: List<VertexSource>, oldVertexCount: Int): MeshDeltaForm {
val oldDeltas = form.positionDeltas
fun oldDeltaX(oldIndex: Int): Float = if (oldIndex in 0 until oldVertexCount && oldIndex * 2 < oldDeltas.size) oldDeltas[oldIndex * 2] else 0f
fun oldDeltaY(oldIndex: Int): Float = if (oldIndex in 0 until oldVertexCount && oldIndex * 2 + 1 < oldDeltas.size) oldDeltas[oldIndex * 2 + 1] else 0f
val newDeltas = FloatArray(vertexSources.size * 2)
vertexSources.forEachIndexed { newIndex, source ->
when (source) {
is VertexSource.FromOld -> {
newDeltas[newIndex * 2] = oldDeltaX(source.oldIndex)
newDeltas[newIndex * 2 + 1] = oldDeltaY(source.oldIndex)
}
is VertexSource.AverageOf -> {
if (source.oldIndices.isNotEmpty()) {
var sumX = 0f
var sumY = 0f
for (oldIndex in source.oldIndices) {
sumX += oldDeltaX(oldIndex)
sumY += oldDeltaY(oldIndex)
}
newDeltas[newIndex * 2] = sumX / source.oldIndices.size
newDeltas[newIndex * 2 + 1] = sumY / source.oldIndices.size
}
}
is VertexSource.LerpOf -> {
newDeltas[newIndex * 2] = oldDeltaX(source.oldA) + (oldDeltaX(source.oldB) - oldDeltaX(source.oldA)) * source.t
newDeltas[newIndex * 2 + 1] = oldDeltaY(source.oldA) + (oldDeltaY(source.oldB) - oldDeltaY(source.oldA)) * source.t
}
}
}
return MeshDeltaForm(newDeltas)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,302 @@
package org.umamo.edit
import kotlin.math.cos
import kotlin.math.sin
/**
* The active modal mesh operator: Blender-style Grab (translate), Scale, or Rotate. The session latches
* one of these while a gesture is in flight (the desktop overlay drives the pointer tracking and the
* corresponding [MeshTransforms] function); null means no operator is running.
*
* モーダルなメッシュ操作の種類(移動・拡縮・回転)。
*/
enum class MeshOperatorKind {
Grab,
Scale,
Rotate,
/**
* Slides the active vertex along one of its incident edges (Blender's Shift+V), clamped between the
* endpoints. Edit mode only, driven by the Edit overlay's own slide branch (the pointer projects
* onto the edge rather than through the shared operator math).
*/
VertexSlide,
}
/**
* Pure transforms over an interleaved mesh-position array for the modal G / S / R operators. Positions
* are interleaved (x0, y0, x1, y1, ...), so vertex [index] occupies slots `2*index` and `2*index+1`
* (matching [org.umamo.runtime.model.DrawableMesh]). Each operator returns a NEW array, mutating only the
* coordinates of the selected vertices and copying the rest verbatim - it never touches its input, which
* keeps them trivially testable and upholds the copy-on-write discipline (the caller commits the returned
* array into a fresh DrawableMesh).
*
* The functions are coordinate-space agnostic: they operate on whatever values the array holds. The
* caller (the gizmo overlay) maps the pointer gesture into the same space the positions live in (model
* space) before computing the delta / factor / angle and the pivot.
*
* モーダルな移動・拡縮・回転の純粋変換。選択頂点のみを変更した新しい配列を返し、入力は変更しない。
*/
object MeshTransforms {
/**
* The median pivot for scale / rotate: the mean (centroid) of the selected vertices' positions, in the
* array's coordinate space. Returns (0, 0) when nothing is selected (no operator runs in that case).
*
* @param FloatArray positions The interleaved mesh positions.
* @param Set<Int> indices The selected vertex indices.
* @return Pair<Float, Float> The (x, y) centroid of the selected vertices.
*/
fun medianPivot(positions: FloatArray, indices: Set<Int>): Pair<Float, Float> {
if (indices.isEmpty()) {
return 0f to 0f
}
var sumX = 0f
var sumY = 0f
for (vertexIndex in indices) {
sumX += positions[vertexIndex * 2]
sumY += positions[vertexIndex * 2 + 1]
}
val count = indices.size.toFloat()
return (sumX / count) to (sumY / count)
}
/**
* The combined median pivot across several interleaved position arrays: the mean (centroid) of every
* vertex of every array, weighted by vertex count (so a denser mesh pulls the pivot toward itself, the
* same way [medianPivot] weights a single mesh by its vertices). This is the shared anchor an object-mode
* Scale / Rotate turns all selected drawables about. Returns (0, 0) when the collection is empty or holds
* only empty arrays (no gesture runs in that case).
*
* @param Collection<FloatArray> positionsList The interleaved position arrays, one per selected drawable.
* @return Pair<Float, Float> The (x, y) centroid across all arrays' vertices.
*/
fun combinedCentroid(positionsList: Collection<FloatArray>): Pair<Float, Float> {
var sumX = 0f
var sumY = 0f
var vertexCount = 0
for (positions in positionsList) {
var slotIndex = 0
while (slotIndex + 1 < positions.size) {
sumX += positions[slotIndex]
sumY += positions[slotIndex + 1]
vertexCount++
slotIndex += 2
}
}
if (vertexCount == 0) {
return 0f to 0f
}
val count = vertexCount.toFloat()
return (sumX / count) to (sumY / count)
}
/**
* Translates the selected vertices by ([deltaX], [deltaY]).
*
* @param FloatArray positions The interleaved mesh positions.
* @param Set<Int> indices The selected vertex indices.
* @param Float deltaX The x offset.
* @param Float deltaY The y offset.
* @return FloatArray A new positions array with the selected vertices moved.
*/
fun translateVertices(positions: FloatArray, indices: Set<Int>, deltaX: Float, deltaY: Float): FloatArray {
val result = positions.copyOf()
for (vertexIndex in indices) {
result[vertexIndex * 2] += deltaX
result[vertexIndex * 2 + 1] += deltaY
}
return result
}
/**
* Collapses the selected vertices onto one point ([targetX], [targetY]) - Blender's pile-up snap
* semantics (Selection to Cursor / Selection to Active). Unlike [translateVertices], the vertices
* do not keep their offsets from each other; every one lands exactly on the target.
*
* @param FloatArray positions The interleaved mesh positions.
* @param Set<Int> indices The selected vertex indices.
* @param Float targetX The x every selected vertex lands on.
* @param Float targetY The y every selected vertex lands on.
* @return FloatArray A new positions array with the selected vertices piled onto the target.
*/
fun collapseVertices(positions: FloatArray, indices: Set<Int>, targetX: Float, targetY: Float): FloatArray {
val result = positions.copyOf()
for (vertexIndex in indices) {
result[vertexIndex * 2] = targetX
result[vertexIndex * 2 + 1] = targetY
}
return result
}
/**
* Scales the selected vertices about the pivot ([pivotX], [pivotY]) by [factor] (uniform on both axes).
*
* @param FloatArray positions The interleaved mesh positions.
* @param Set<Int> indices The selected vertex indices.
* @param Float factor The uniform scale factor (1 leaves them unchanged).
* @param Float pivotX The pivot x (the scale anchor).
* @param Float pivotY The pivot y.
* @return FloatArray A new positions array with the selected vertices scaled.
*/
fun scaleVertices(positions: FloatArray, indices: Set<Int>, factor: Float, pivotX: Float, pivotY: Float): FloatArray {
val result = positions.copyOf()
for (vertexIndex in indices) {
val x = result[vertexIndex * 2]
val y = result[vertexIndex * 2 + 1]
result[vertexIndex * 2] = pivotX + (x - pivotX) * factor
result[vertexIndex * 2 + 1] = pivotY + (y - pivotY) * factor
}
return result
}
/**
* Scales the selected vertices about the pivot ([pivotX], [pivotY]) with independent per-axis
* factors - the axis-locked variant of [scaleVertices] (an X-locked scale passes factorY = 1 and
* vice versa).
*
* @param FloatArray positions The interleaved mesh positions.
* @param Set<Int> indices The selected vertex indices.
* @param Float factorX The scale factor along x (1 leaves x unchanged).
* @param Float factorY The scale factor along y (1 leaves y unchanged).
* @param Float pivotX The pivot x (the scale anchor).
* @param Float pivotY The pivot y.
* @return FloatArray A new positions array with the selected vertices scaled.
*/
fun scaleVerticesAxis(positions: FloatArray, indices: Set<Int>, factorX: Float, factorY: Float, pivotX: Float, pivotY: Float): FloatArray {
val result = positions.copyOf()
for (vertexIndex in indices) {
val x = result[vertexIndex * 2]
val y = result[vertexIndex * 2 + 1]
result[vertexIndex * 2] = pivotX + (x - pivotX) * factorX
result[vertexIndex * 2 + 1] = pivotY + (y - pivotY) * factorY
}
return result
}
/**
* Pairwise swaps one axis among [orderedIndices]: index 0 with last, 1 with last-1, …. Odd count
* leaves the middle index alone. Horizontal swaps x (or u); vertical swaps y (or v); the other
* component stays on its vertex.
*
* @param FloatArray positions The interleaved positions (or UVs).
* @param List<Int> orderedIndices The selection in reverse-swap order (typically sorted indices).
* @param Boolean horizontal True to swap x/u only; false to swap y/v only.
* @return FloatArray A new array with pairs swapped; same instance when fewer than two indices.
*/
fun reverseSwapPositions(
positions: FloatArray,
orderedIndices: List<Int>,
horizontal: Boolean,
): FloatArray {
if (orderedIndices.size < 2) {
return positions
}
val result = positions.copyOf()
val component = if (horizontal) 0 else 1
var low = 0
var high = orderedIndices.lastIndex
while (low < high) {
val a = orderedIndices[low] * 2 + component
val b = orderedIndices[high] * 2 + component
val tmp = result[a]
result[a] = result[b]
result[b] = tmp
low++
high--
}
return result
}
/**
* Rotates the selected vertices about the pivot ([pivotX], [pivotY]) by [radians].
*
* @param FloatArray positions The interleaved mesh positions.
* @param Set<Int> indices The selected vertex indices.
* @param Float radians The rotation angle in radians.
* @param Float pivotX The pivot x (the rotation center).
* @param Float pivotY The pivot y.
* @return FloatArray A new positions array with the selected vertices rotated.
*/
fun rotateVertices(positions: FloatArray, indices: Set<Int>, radians: Float, pivotX: Float, pivotY: Float): FloatArray {
val result = positions.copyOf()
val cosAngle = cos(radians)
val sinAngle = sin(radians)
for (vertexIndex in indices) {
val offsetX = result[vertexIndex * 2] - pivotX
val offsetY = result[vertexIndex * 2 + 1] - pivotY
result[vertexIndex * 2] = pivotX + offsetX * cosAngle - offsetY * sinAngle
result[vertexIndex * 2 + 1] = pivotY + offsetX * sinAngle + offsetY * cosAngle
}
return result
}
/**
* Translates the weighted vertices by their share of ([deltaX], [deltaY]) - the proportional-editing
* companion of [translateVertices]: a weight of 1 moves fully, 0.5 half way.
*
* @param FloatArray positions The interleaved mesh positions.
* @param Map<Int, Float> weights Vertex index to influence weight in [0, 1].
* @param Float deltaX The full x offset (each vertex takes weight x this).
* @param Float deltaY The full y offset.
* @return FloatArray A new positions array with the weighted vertices moved.
*/
fun translateVerticesWeighted(positions: FloatArray, weights: Map<Int, Float>, deltaX: Float, deltaY: Float): FloatArray {
val result = positions.copyOf()
for ((vertexIndex, weight) in weights) {
result[vertexIndex * 2] += deltaX * weight
result[vertexIndex * 2 + 1] += deltaY * weight
}
return result
}
/**
* Scales the weighted vertices about the pivot by their share of the per-axis factors - the
* proportional-editing companion of [scaleVerticesAxis]: each vertex lerps from its current position
* toward its fully-scaled position by its weight (equivalently, its effective factor per axis is
* 1 + (factor - 1) x weight).
*
* @param FloatArray positions The interleaved mesh positions.
* @param Map<Int, Float> weights Vertex index to influence weight in [0, 1].
* @param Float factorX The full scale factor along x.
* @param Float factorY The full scale factor along y.
* @param Float pivotX The pivot x (the scale anchor).
* @param Float pivotY The pivot y.
* @return FloatArray A new positions array with the weighted vertices scaled.
*/
fun scaleVerticesWeighted(positions: FloatArray, weights: Map<Int, Float>, factorX: Float, factorY: Float, pivotX: Float, pivotY: Float): FloatArray {
val result = positions.copyOf()
for ((vertexIndex, weight) in weights) {
val x = result[vertexIndex * 2]
val y = result[vertexIndex * 2 + 1]
result[vertexIndex * 2] = pivotX + (x - pivotX) * (1f + (factorX - 1f) * weight)
result[vertexIndex * 2 + 1] = pivotY + (y - pivotY) * (1f + (factorY - 1f) * weight)
}
return result
}
/**
* Rotates the weighted vertices about the pivot by their share of [radians] - the
* proportional-editing companion of [rotateVertices]. The ANGLE is weighted (a half-weight vertex
* turns half the angle along the arc), not the endpoint position: lerping positions would cut the
* chord and collapse the falloff ring toward the pivot on large rotations.
*
* @param FloatArray positions The interleaved mesh positions.
* @param Map<Int, Float> weights Vertex index to influence weight in [0, 1].
* @param Float radians The full rotation angle in radians (each vertex turns weight x this).
* @param Float pivotX The pivot x (the rotation center).
* @param Float pivotY The pivot y.
* @return FloatArray A new positions array with the weighted vertices rotated.
*/
fun rotateVerticesWeighted(positions: FloatArray, weights: Map<Int, Float>, radians: Float, pivotX: Float, pivotY: Float): FloatArray {
val result = positions.copyOf()
for ((vertexIndex, weight) in weights) {
val cosAngle = cos(radians * weight)
val sinAngle = sin(radians * weight)
val offsetX = result[vertexIndex * 2] - pivotX
val offsetY = result[vertexIndex * 2 + 1] - pivotY
result[vertexIndex * 2] = pivotX + offsetX * cosAngle - offsetY * sinAngle
result[vertexIndex * 2 + 1] = pivotY + offsetX * sinAngle + offsetY * cosAngle
}
return result
}
}
@@ -0,0 +1,221 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableMesh
import kotlin.math.abs
/**
* Projects rest-space positions onto the stored UVs of an Edit-enter reference mesh.
*
* Wipe-and-rebuild must not invent a new UV layout: every new vert samples this field so the texture
* stays locked to the original mapping no matter how the rigger retriangulates.
*
* Inside a reference face: barycentric (exact piecewise-linear field). Outside: a least-squares
* affine fit over all reference verts (smooth; no nearest-vert UV plateaus that stretch the art).
*
* @property DrawableMesh seed The mesh at Edit enter (positions + uvs + indices).
*/
class MeshUvField(private val seed: DrawableMesh) {
private val affine: FloatArray? = fitAffine(seed)
/**
* Stored (u, v) at a rest-space point.
*
* @param Float x Rest x.
* @param Float y Rest y.
* @return Pair<Float, Float> Stored UVs.
*/
fun uvAt(x: Float, y: Float): Pair<Float, Float> {
if (seed.vertexCount == 0) {
return 0f to 0f
}
val face = containingFace(seed, x, y)
if (face != null) {
val a = seed.indices[face * 3]
val b = seed.indices[face * 3 + 1]
val c = seed.indices[face * 3 + 2]
val (wA, wB, wC) =
barycentric(
x,
y,
seed.positions[a * 2],
seed.positions[a * 2 + 1],
seed.positions[b * 2],
seed.positions[b * 2 + 1],
seed.positions[c * 2],
seed.positions[c * 2 + 1],
)
val u = uvComponent(a, 0) * wA + uvComponent(b, 0) * wB + uvComponent(c, 0) * wC
val v = uvComponent(a, 1) * wA + uvComponent(b, 1) * wB + uvComponent(c, 1) * wC
return u to v
}
val fit = affine
if (fit != null) {
return (fit[0] * x + fit[1] * y + fit[2]) to (fit[3] * x + fit[4] * y + fit[5])
}
val nearest = nearestVertex(seed, x, y)
return uvComponent(nearest, 0) to uvComponent(nearest, 1)
}
/**
* Rewrites every vertex UV on [mesh] by projecting its rest position through this field.
*
* @param DrawableMesh mesh The mesh to re-UV.
* @return DrawableMesh A copy with projected uvs (positions / indices shared when unchanged).
*/
fun projectAll(mesh: DrawableMesh): DrawableMesh {
if (mesh.vertexCount == 0) {
return mesh
}
val uvs = FloatArray(mesh.vertexCount * 2)
for (index in 0 until mesh.vertexCount) {
val (u, v) = uvAt(mesh.positions[index * 2], mesh.positions[index * 2 + 1])
uvs[index * 2] = u
uvs[index * 2 + 1] = v
}
return DrawableMesh(mesh.positions, uvs, mesh.indices)
}
private fun uvComponent(vertexIndex: Int, component: Int): Float {
val index = vertexIndex * 2 + component
return if (index < seed.uvs.size) seed.uvs[index] else 0f
}
companion object {
/**
* Least-squares affine [u,v] = M · [x, y, 1] over all seed verts with UVs. Null when fewer than
* three distinct positions or the system is degenerate.
*/
private fun fitAffine(seed: DrawableMesh): FloatArray? {
val count = seed.vertexCount
if (count < 3 || seed.uvs.size < count * 2) {
return null
}
// Normal equations for [x y 1; ...] → u and v separately (3x3 shared Gram matrix).
var sxx = 0.0
var sxy = 0.0
var sx = 0.0
var syy = 0.0
var sy = 0.0
var n = 0.0
var sxu = 0.0
var syu = 0.0
var su = 0.0
var sxv = 0.0
var syv = 0.0
var sv = 0.0
for (index in 0 until count) {
val x = seed.positions[index * 2].toDouble()
val y = seed.positions[index * 2 + 1].toDouble()
val u = seed.uvs[index * 2].toDouble()
val v = seed.uvs[index * 2 + 1].toDouble()
sxx += x * x
sxy += x * y
sx += x
syy += y * y
sy += y
n += 1.0
sxu += x * u
syu += y * u
su += u
sxv += x * v
syv += y * v
sv += v
}
val det =
sxx * (syy * n - sy * sy) - sxy * (sxy * n - sx * sy) + sx * (sxy * sy - syy * sx)
if (abs(det) < 1e-18) {
return null
}
fun solve(bx: Double, by: Double, b1: Double): Triple<Double, Double, Double> {
// Cramer's rule on the 3x3 Gram matrix.
val a0 =
(
bx * (syy * n - sy * sy) - sxy * (by * n - b1 * sy) + sx * (by * sy - syy * b1)
) / det
val a1 =
(
sxx * (by * n - b1 * sy) - bx * (sxy * n - sx * sy) + sx * (sxy * b1 - by * sx)
) / det
val a2 =
(
sxx * (syy * b1 - sy * by) - sxy * (sxy * b1 - sx * by) + bx * (sxy * sy - syy * sx)
) / det
return Triple(a0, a1, a2)
}
val (a, b, c) = solve(sxu, syu, su)
val (d, e, f) = solve(sxv, syv, sv)
return floatArrayOf(a.toFloat(), b.toFloat(), c.toFloat(), d.toFloat(), e.toFloat(), f.toFloat())
}
private fun containingFace(mesh: DrawableMesh, x: Float, y: Float): Int? {
val triangleCount = mesh.indices.size / 3
for (tri in 0 until triangleCount) {
val a = mesh.indices[tri * 3]
val b = mesh.indices[tri * 3 + 1]
val c = mesh.indices[tri * 3 + 2]
val (wA, wB, wC) =
barycentric(
x,
y,
mesh.positions[a * 2],
mesh.positions[a * 2 + 1],
mesh.positions[b * 2],
mesh.positions[b * 2 + 1],
mesh.positions[c * 2],
mesh.positions[c * 2 + 1],
)
if (wA >= -1e-4f && wB >= -1e-4f && wC >= -1e-4f) {
return tri
}
}
return null
}
private fun nearestVertex(mesh: DrawableMesh, x: Float, y: Float): Int {
var best = 0
var bestDist = Float.MAX_VALUE
for (index in 0 until mesh.vertexCount) {
val dx = mesh.positions[index * 2] - x
val dy = mesh.positions[index * 2 + 1] - y
val dist = dx * dx + dy * dy
if (dist < bestDist) {
bestDist = dist
best = index
}
}
return best
}
private fun barycentric(
px: Float,
py: Float,
ax: Float,
ay: Float,
bx: Float,
by: Float,
cx: Float,
cy: Float,
): Triple<Float, Float, Float> {
val v0x = bx - ax
val v0y = by - ay
val v1x = cx - ax
val v1y = cy - ay
val v2x = px - ax
val v2y = py - ay
val dot00 = v0x * v0x + v0y * v0y
val dot01 = v0x * v1x + v0y * v1y
val dot02 = v0x * v2x + v0y * v2y
val dot11 = v1x * v1x + v1y * v1y
val dot12 = v1x * v2x + v1y * v2y
val denom = dot00 * dot11 - dot01 * dot01
if (abs(denom) < 1e-12f) {
return Triple(1f, 0f, 0f)
}
val wB = (dot11 * dot02 - dot01 * dot12) / denom
val wC = (dot00 * dot12 - dot01 * dot02) / denom
val wA = 1f - wB - wC
return Triple(wA, wB, wC)
}
}
}
@@ -0,0 +1,206 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
/**
* How Individual Origins ([TransformPivotMode.IndividualOrigins]) partitions one mesh into pivot groups.
*
* The two editing contexts read the same pivot mode differently, which the mode's own docblock already
* describes: in Edit and the UV editor a mesh's covered vertices split into connectivity islands, each
* turning about its own centroid; in Object mode a whole drawable turns about its single centroid. Making
* that an explicit parameter of [buildModalTransformCapture] keeps the one difference visible instead of
* hiding it in two copies of the group-derivation code.
*/
enum class IndividualOriginScope {
/** Split the covered set into connectivity islands (Edit mode, the UV editor). */
ConnectivityIsland,
/** One group for the whole covered set, about its centroid (Object mode). */
WholeMesh,
}
/**
* One mesh offered to [buildModalTransformCapture], before its pivots are resolved.
*
* The positions are frozen in whatever space the gesture runs in - world-posed for the viewport overlays,
* texel display for the UV editor - and the covered indices are the union of vertices the mesh's selected
* elements span (every vertex, for an Object-mode whole-drawable transform). A source whose covered set is
* empty contributes nothing and is dropped by the builder.
*
* @property DrawableId drawableId The drawable this mesh belongs to (the capture's per-mesh key).
* @property FloatArray positions The frozen interleaved positions the operator transforms and the pivots
* are measured in. The builder does not copy it - the caller freezes (copies) before handing it over.
* @property IntArray triangleIndices The mesh's triangle vertex indices (connectivity for islands and the
* geodesic proportional falloff).
* @property Set<Int> coveredIndices The vertices the selection covers on this mesh.
*/
class ModalCaptureSource(
val drawableId: DrawableId,
val positions: FloatArray,
val triangleIndices: IntArray,
val coveredIndices: Set<Int>,
)
/**
* One mesh inside an in-flight modal transform: its frozen source geometry plus the pivot groups its
* covered vertices turn about, and the proportional-editing halo re-derived from the same frozen positions.
*
* [influence] and [movedIndices] are the only mutable state, because a mid-gesture radius or falloff change
* re-derives them - always from [positions], never from a live preview, so the influence ring can never
* feed back on its own output.
*
* @property DrawableId drawableId The drawable this entry belongs to.
* @property FloatArray positions The frozen positions the operator transforms (shared by reference from the
* source - never mutated).
* @property Set<Int> coveredIndices The vertices the selection covers on this mesh.
* @property IntArray triangleIndices The mesh's triangle vertex indices.
* @property List<TransformPivotGroup> groups The pivot groups the covered vertices turn about.
*/
class ModalCaptureEntry internal constructor(
val drawableId: DrawableId,
val positions: FloatArray,
val coveredIndices: Set<Int>,
val triangleIndices: IntArray,
val groups: List<TransformPivotGroup>,
) {
/** The proportional-editing halo: influenced unselected vertices to weight, empty when proportional is off. */
var influence: Map<Int, ProportionalInfluence> = emptyMap()
private set
/** Every vertex the gesture moves: the covered set, plus the influenced halo when proportional is on. */
var movedIndices: Set<Int> = coveredIndices
private set
/**
* Re-derives this mesh's influence halo and moved set from the FROZEN positions.
*
* @param ProportionalEditState? state The proportional configuration, or null to clear the halo.
* @param Float radius The influence radius in the positions' units (unused when [state] is null).
*/
internal fun deriveInfluence(state: ProportionalEditState?, radius: Float) {
influence =
when {
state == null -> emptyMap()
state.connectedOnly ->
proportionalInfluencesConnected(positions, coveredIndices, radius, state.falloff, triangleIndices)
else -> proportionalInfluences(positions, coveredIndices, radius, state.falloff)
}
movedIndices =
if (influence.isEmpty()) {
coveredIndices
} else {
coveredIndices + influence.keys
}
}
}
/**
* The captured state of an in-flight modal transform, frozen when the operator latches so the whole drag is
* atomic across the meshes it moves. Shared by the Edit, Object, and UV gizmo overlays: each freezes its
* own-space geometry into [ModalCaptureSource]s, resolves its own active-element and cursor anchors, and
* hands both to [buildModalTransformCapture]; what comes back is identical in shape across all three.
*
* Overlays that need extra per-mesh data the shared capture does not carry (the Edit and Object overlays'
* deformer-chain mapping, the UV editor's page dimensions) hold it in a map keyed on
* [ModalCaptureEntry.drawableId] rather than a second index-aligned list.
*
* @property List<ModalCaptureEntry> entries The moving meshes, one per source that had covered vertices.
* @property Pair<Float, Float> anchor The point in the gesture's space that factors and angles measure
* against (and the shared-pivot modes turn about); the HUD's pivot marker draws here.
* @property MeshOperatorKind operatorKind The operator that latched, frozen so the commit names the
* operation that actually ran rather than re-reading a latch that may already have cleared.
*/
class ModalTransformCapture internal constructor(
val entries: List<ModalCaptureEntry>,
val anchor: Pair<Float, Float>,
val operatorKind: MeshOperatorKind,
) {
/** The Rotate gesture's angle accumulator (unwrapped per-move increments; see RotationAngleTracker). */
val rotationTracker = RotationAngleTracker()
/** The captured drawables, in capture order. */
val drawableIds: List<DrawableId> get() = entries.map { entry -> entry.drawableId }
/**
* Re-derives every mesh's proportional halo from the frozen originals. Called on latch and again on a
* mid-gesture radius or falloff change; feeding the same inputs twice is idempotent.
*
* @param ProportionalEditState? state The proportional configuration, or null to clear the halos.
* @param Float radius The influence radius in the gesture space's units (unused when [state] is null).
*/
fun applyProportional(state: ProportionalEditState?, radius: Float) {
for (entry in entries) {
entry.deriveInfluence(state, radius)
}
}
}
/**
* Builds a [ModalTransformCapture] from the meshes a gesture will move, resolving the shared anchor and each
* mesh's pivot groups per the active [pivotMode].
*
* This owns exactly the part every overlay duplicated: the covered-vertex mean across the meshes, the
* fallback policy (Active Element and Cursor both fall back to the median when their anchor is absent), and
* the per-mesh group derivation. What differs between overlays stays with the caller and arrives
* pre-resolved: [activeAnchor] (each overlay finds its active element / drawable differently) and
* [cursorAnchor] (each reads a different cursor, in a different space).
*
* @param List<ModalCaptureSource> sources The meshes offered; those with no covered vertices are dropped.
* @param TransformPivotMode pivotMode The active pivot mode (which anchor, and single vs per-island groups).
* @param IndividualOriginScope individualOriginScope How Individual Origins partitions a mesh.
* @param MeshOperatorKind operatorKind The operator that latched (frozen onto the capture).
* @param Pair<Float, Float>? activeAnchor The Active-Element anchor the caller resolved, or null to fall
* back to the median.
* @param Pair<Float, Float>? cursorAnchor The Cursor anchor the caller resolved, or null to fall back to
* the median.
* @return ModalTransformCapture? The capture, or null when no source had covered vertices (no gesture runs).
*/
fun buildModalTransformCapture(
sources: List<ModalCaptureSource>,
pivotMode: TransformPivotMode,
individualOriginScope: IndividualOriginScope,
operatorKind: MeshOperatorKind,
activeAnchor: Pair<Float, Float>?,
cursorAnchor: Pair<Float, Float>?,
): ModalTransformCapture? {
val moving = sources.filter { source -> source.coveredIndices.isNotEmpty() }
if (moving.isEmpty()) {
return null
}
// The covered-vertex mean across every moving mesh - the shared median anchor, and the fallback for the
// Active-Element and Cursor modes. Object mode covers every vertex, so this equals its combined
// centroid (MeshTransforms.combinedCentroid) up to summation order.
var coveredSumX = 0f
var coveredSumY = 0f
var coveredCount = 0
for (source in moving) {
for (vertexIndex in source.coveredIndices) {
coveredSumX += source.positions[vertexIndex * 2]
coveredSumY += source.positions[vertexIndex * 2 + 1]
coveredCount++
}
}
val median = (coveredSumX / coveredCount) to (coveredSumY / coveredCount)
val anchor =
when (pivotMode) {
TransformPivotMode.MedianPoint, TransformPivotMode.IndividualOrigins -> median
TransformPivotMode.ActiveElement -> activeAnchor ?: median
TransformPivotMode.Cursor -> cursorAnchor ?: median
}
val entries =
moving.map { source ->
val groups =
when {
pivotMode == TransformPivotMode.IndividualOrigins && individualOriginScope == IndividualOriginScope.ConnectivityIsland ->
TransformPivots.islandGroups(source.positions, source.coveredIndices, source.triangleIndices)
pivotMode == TransformPivotMode.IndividualOrigins -> {
// WholeMesh: the drawable turns about its own centroid (the object-mode island).
val ownCentroid = MeshTransforms.medianPivot(source.positions, source.coveredIndices)
TransformPivots.sharedGroup(source.coveredIndices, ownCentroid.first, ownCentroid.second)
}
else -> TransformPivots.sharedGroup(source.coveredIndices, anchor.first, anchor.second)
}
ModalCaptureEntry(source.drawableId, source.positions, source.coveredIndices, source.triangleIndices, groups)
}
return ModalTransformCapture(entries, anchor, operatorKind)
}
@@ -0,0 +1,225 @@
package org.umamo.edit
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.PuppetModel
/**
* The drawables an object-mode Grab / Scale / Rotate may transform, or null when the gesture must be
* blocked. Object G / S / R writes only DrawableMesh.positions, so the transformable unit is always a
* mesh-carrying drawable:
* - a selected drawable contributes itself (when it has a mesh);
* - a selected part expands to every mesh-carrying drawable in its outliner subtree
* ([PuppetModel.subtreeTargets]), so Grab on a group moves the group's art together;
* - a deformer is still skipped (its shape lives in absolute per-keyform forms with no writer yet - the
* remaining Deformer → Part → Mesh cascade).
* Ineligible targets are silently ignored rather than blocking: a Select All that sweeps deformers in
* still lets G move the meshes. Only a selection with nothing transformable at all (empty, or holding
* only deformers / empty parts / mesh-less drawables) returns null, and the caller blocks with a note.
*
* オブジェクトモードの G / S / R が変形できる描画メッシュ。選択中のパーツはその配下のメッシュへ展開し、
* デフォーマ・メッシュ無しは黙って除外する。1つも無ければ null(ジェスチャをブロック)。
*
* @param Selection selection The object-mode selection to evaluate.
* @param PuppetModel model The rig the targets index into.
* @return List<DrawableId>? The transformable drawable ids, or null when nothing is transformable.
*/
fun eligibleTransformDrawables(selection: Selection, model: PuppetModel): List<DrawableId>? {
if (selection.isEmpty) {
return null
}
// LinkedHashSet: a part and one of its drawables in the same selection must not double-transform the mesh.
val drawableIds = LinkedHashSet<DrawableId>()
for (target in selection.targets) {
when (target) {
is SelectionTarget.Drawable -> addMeshDrawable(drawableIds, model, target.id)
is SelectionTarget.Part -> {
for (sub in model.subtreeTargets(target)) {
val drawableTarget = sub as? SelectionTarget.Drawable ?: continue
addMeshDrawable(drawableIds, model, drawableTarget.id)
}
}
// Deformers cannot be transformed yet (no lattice / cascade writer for Object G / S / R here).
is SelectionTarget.Deformer -> Unit
}
}
return drawableIds.toList().ifEmpty { null }
}
/**
* Adds [id] to [into] when the drawable exists and carries a mesh (positions to move).
*
* @param MutableSet into The accumulator.
* @param PuppetModel model The rig to look the drawable up in.
* @param DrawableId id The candidate drawable.
*/
private fun addMeshDrawable(into: MutableSet<DrawableId>, model: PuppetModel, id: DrawableId) {
val drawable = model.drawables.firstOrNull { it.id == id }
if (drawable?.mesh != null) {
into.add(id)
}
}
/**
* The active warp deformer when Object-mode G / S / R should edit its lattice, or null.
*
* Prefers the selection's active target when it is a keyed warp; otherwise the sole selected warp with a
* lattice. Drawables in the same selection do not block this - [eligibleTransformDrawables] already won
* if any mesh was transformable.
*
* @param Selection selection The object selection.
* @param PuppetModel model The rig.
* @return DeformerId? The warp to edit, or null.
*/
fun selectedWarpDeformerId(selection: Selection, model: PuppetModel): DeformerId? {
fun warpIdOf(target: SelectionTarget): DeformerId? {
val deformerTarget = target as? SelectionTarget.Deformer ?: return null
val warp = model.deformers.firstOrNull { candidate -> candidate.id == deformerTarget.id } as? Deformer.Warp
return if (warp?.geometryGrid != null) warp.id else null
}
selection.active?.let { active -> warpIdOf(active)?.let { return it } }
val warps = selection.targets.mapNotNull { target -> warpIdOf(target) }
return warps.singleOrNull()
}
/**
* Reports whether the live pose sits at every parameter's default value. Object-mode transforms capture
* the displayed (posed) geometry and write it back through the deformer-chain inverse, which is only
* exact at the neutral pose - so [EditorSession.beginObjectOperator] refuses to start while any
* parameter is scrubbed away from its default. A parameter missing from the pose map counts as neutral
* (the renderer substitutes the default for it).
*
* @param PuppetModel model The rig whose parameter defaults define neutral.
* @param Pose pose The live parameter values to test.
* @return Boolean True when every posed value equals its parameter's default.
*/
fun isPoseNeutral(model: PuppetModel, pose: Pose): Boolean {
for (parameter in model.parameters) {
val value = pose[parameter.id] ?: continue
if (value != parameter.default) {
return false
}
}
return true
}
/**
* The axis-aligned bounds of an interleaved position array: its center and its extents. A drawable has no
* scalar transform - its placement IS its geometry - so a "transform" for one is derived from these bounds,
* and an edit to the transform is an edit to the geometry that produced them.
*
* Space-agnostic: this measures whatever array it is handed. Which array that should be is the caller's
* decision and a consequential one - see the Properties panel's DrawableWorldTransform, which measures
* WORLD positions because a keyformed drawable's base array is nothing like its on-screen shape.
*
* @property Float centerX The bounds' center x.
* @property Float centerY The bounds' center y.
* @property Float width The x extent (0 for a degenerate or empty mesh).
* @property Float height The y extent (0 for a degenerate or empty mesh).
*/
class MeshBounds(val centerX: Float, val centerY: Float, val width: Float, val height: Float)
/**
* Computes the axis-aligned bounds of an interleaved (x, y) position array. Shared by the Properties
* readout and the transform edits below, so what is displayed and what is written are the same measurement
* - a second definition would let the two drift and make a typed value land somewhere else. Both must be
* handed positions in the SAME space for that to hold.
*
* @param FloatArray positions Interleaved x, y vertex positions.
* @return MeshBounds The center and extents; a zero box when there are no vertices.
*/
fun meshBounds(positions: FloatArray): MeshBounds {
if (positions.size < 2) {
return MeshBounds(0f, 0f, 0f, 0f)
}
var minX = Float.POSITIVE_INFINITY
var minY = Float.POSITIVE_INFINITY
var maxX = Float.NEGATIVE_INFINITY
var maxY = Float.NEGATIVE_INFINITY
var slotIndex = 0
while (slotIndex + 1 < positions.size) {
val x = positions[slotIndex]
val y = positions[slotIndex + 1]
if (x < minX) {
minX = x
}
if (x > maxX) {
maxX = x
}
if (y < minY) {
minY = y
}
if (y > maxY) {
maxY = y
}
slotIndex += 2
}
return MeshBounds((minX + maxX) / 2f, (minY + maxY) / 2f, maxX - minX, maxY - minY)
}
/** Every vertex index of an interleaved position array - the whole-mesh index set the object edits move. */
private fun allVertexIndices(positions: FloatArray): Set<Int> = (0 until positions.size / 2).toSet()
/**
* Translates a whole mesh so its bounds center lands on ([newCenterX], [newCenterY]). This is the write
* side of the Properties Position row: the row reads [meshBounds]'s center, and typing a value moves the
* mesh rigidly by the difference, so the displayed number becomes exactly the value entered.
*
* Pure and space-agnostic - it moves the array it is given. The Properties panel applies it to WORLD
* positions and inverts the result back onto the base mesh; see DrawableWorldTransform.
*
* @param FloatArray positions The interleaved positions.
* @param Float newCenterX The x the bounds center should land on.
* @param Float newCenterY The y the bounds center should land on.
* @return FloatArray A new positions array, or the same instance when nothing moves.
*/
fun movedToBoundsCenter(positions: FloatArray, newCenterX: Float, newCenterY: Float): FloatArray {
if (positions.size < 2) {
return positions
}
val bounds = meshBounds(positions)
val deltaX = newCenterX - bounds.centerX
val deltaY = newCenterY - bounds.centerY
if (deltaX == 0f && deltaY == 0f) {
return positions
}
return MeshTransforms.translateVertices(positions, allVertexIndices(positions), deltaX, deltaY)
}
/**
* Scales a whole mesh about its bounds center so its extents become ([newWidth], [newHeight]). The write
* side of the Properties Size row. Pure and space-agnostic like [movedToBoundsCenter].
*
* The bounds center is the pivot precisely because it is a fixed point of the scale: the Position row reads
* that same center, so resizing never makes the position readout jump. (The vertex centroid -
* MeshTransforms.combinedCentroid, which the viewport gizmo pivots on - sits off the bounds center on an
* asymmetric mesh and would move it.)
*
* An axis whose current extent is zero has no defined factor - a degenerate mesh with every vertex on one
* line cannot be given a width - so that axis is left alone rather than multiplied by infinity.
*
* @param FloatArray positions The interleaved positions.
* @param Float newWidth The target x extent (ignored when the current x extent is 0).
* @param Float newHeight The target y extent (ignored when the current y extent is 0).
* @return FloatArray A new positions array, or the same instance when nothing changes.
*/
fun resizedAboutBoundsCenter(positions: FloatArray, newWidth: Float, newHeight: Float): FloatArray {
if (positions.size < 2) {
return positions
}
val bounds = meshBounds(positions)
val factorX = if (bounds.width > 0f) newWidth / bounds.width else 1f
val factorY = if (bounds.height > 0f) newHeight / bounds.height else 1f
if (factorX == 1f && factorY == 1f) {
return positions
}
return MeshTransforms.scaleVerticesAxis(
positions,
allVertexIndices(positions),
factorX,
factorY,
bounds.centerX,
bounds.centerY,
)
}
@@ -0,0 +1,205 @@
package org.umamo.edit
/*
* The record behind "adjust the last operation".
*
* An operation that has settings runs at once with its defaults and registers one of these. Editing
* a parameter re-runs the operation from the base snapshot the record holds and lands the result over
* the operation's own history step (History.amendTop), so an adjustment costs one run of the operation
* and nothing is replayed. Everything here is plain data the UI renders and the session owns; nothing
* about Compose or any one operation may appear in this file.
*/
/** The unit a numeric parameter is shown in. */
enum class ParameterUnit {
None,
Pixels,
Degrees,
Percent,
}
/**
* One editable setting of an adjustable operation.
*
* Carries a stable [key] the operation reads its value back by and a [labelKey] the UI maps to a
* localized label (the [Change.labelKey] convention, so this module stays presentation-free). The
* value is typed per kind; the UI renders one row per kind and never needs to know the operation.
*/
sealed interface OperatorParameter {
/** The stable identity the operation reads the value back by. */
val key: String
/** The stable key the UI resolves to the row's localized label. */
val labelKey: String
/**
* A real-valued setting with a range, a scrub step, and a display unit.
*
* @property String key See [OperatorParameter.key].
* @property String labelKey See [OperatorParameter.labelKey].
* @property Float value The current value.
* @property Float min The smallest value the row accepts.
* @property Float max The largest value the row accepts.
* @property Float step The scrub / chevron increment.
* @property ParameterUnit unit The display unit.
*/
data class FloatParameter(
override val key: String,
override val labelKey: String,
val value: Float,
val min: Float,
val max: Float,
val step: Float = 1f,
val unit: ParameterUnit = ParameterUnit.None,
) : OperatorParameter
/**
* An integer setting with a range, a scrub step, and a display unit.
*
* @property String key See [OperatorParameter.key].
* @property String labelKey See [OperatorParameter.labelKey].
* @property Int value The current value.
* @property Int min The smallest value the row accepts.
* @property Int max The largest value the row accepts.
* @property Int step The scrub / chevron increment.
* @property ParameterUnit unit The display unit.
*/
data class IntParameter(
override val key: String,
override val labelKey: String,
val value: Int,
val min: Int,
val max: Int,
val step: Int = 1,
val unit: ParameterUnit = ParameterUnit.None,
) : OperatorParameter
/**
* An on / off setting.
*
* @property String key See [OperatorParameter.key].
* @property String labelKey See [OperatorParameter.labelKey].
* @property Boolean value The current value.
*/
data class BooleanParameter(
override val key: String,
override val labelKey: String,
val value: Boolean,
) : OperatorParameter
/**
* A pick from a closed list of choices.
*
* @property String key See [OperatorParameter.key].
* @property String labelKey See [OperatorParameter.labelKey].
* @property String value The key of the chosen entry of [choices].
* @property List choices The entries, in display order.
*/
data class ChoiceParameter(
override val key: String,
override val labelKey: String,
val value: String,
val choices: List<ParameterChoice>,
) : OperatorParameter
}
/**
* One entry of a [OperatorParameter.ChoiceParameter].
*
* @property String key The stable value the operation reads back.
* @property String? labelKey The key the UI resolves to the entry's label, or null to show [key] verbatim
* (a page size, a number the rigger recognises).
*/
data class ParameterChoice(
val key: String,
val labelKey: String? = null,
)
/**
* The parameter list with the entry at [key] replaced by [updated].
*
* @param String key The entry to replace.
* @param OperatorParameter updated Its replacement (normally a copy with a new value).
* @return List The list with that one entry swapped; unchanged when no entry has the key.
*/
fun List<OperatorParameter>.withParameter(key: String, updated: OperatorParameter): List<OperatorParameter> =
map { parameter -> if (parameter.key == key) updated else parameter }
/**
* The integer value of the parameter at [key], or [fallback] when absent or of another kind.
*
* @param String key The entry to read.
* @param Int fallback The value when the list carries no such integer.
* @return Int The value.
*/
fun List<OperatorParameter>.intValue(key: String, fallback: Int): Int =
(firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.IntParameter)?.value ?: fallback
/**
* The real value of the parameter at [key], or [fallback] when absent or of another kind.
*
* @param String key The entry to read.
* @param Float fallback The value when the list carries no such float.
* @return Float The value.
*/
fun List<OperatorParameter>.floatValue(key: String, fallback: Float): Float =
(firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.FloatParameter)?.value ?: fallback
/**
* The boolean value of the parameter at [key], or [fallback] when absent or of another kind.
*
* @param String key The entry to read.
* @param Boolean fallback The value when the list carries no such flag.
* @return Boolean The value.
*/
fun List<OperatorParameter>.booleanValue(key: String, fallback: Boolean): Boolean =
(firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.BooleanParameter)?.value ?: fallback
/**
* The chosen key of the choice parameter at [key], or [fallback] when absent or of another kind.
*
* @param String key The entry to read.
* @param String fallback The value when the list carries no such choice.
* @return String The chosen entry's key.
*/
fun List<OperatorParameter>.choiceValue(key: String, fallback: String): String =
(firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.ChoiceParameter)?.value ?: fallback
/**
* The one operation that may still be adjusted: what it committed, what it ran from, its current
* settings, and how to run it again.
*
* Immutable; an adjustment replaces the session's record with [withParameters], and the two share an
* [identity] so a rerun launched against the earlier value still lands (see
* [EditorSession.amendLastCommit]). The [baseSnapshot] is held here rather than looked up in the
* history because a cap of one drops it from the stack the moment the operation pushes.
*
* @property Change change The change the operation committed; its label titles the strip.
* @property String? areaId The area the operation ran in, or null for one that ran nowhere in
* particular (the strip then shows nowhere; the record stays adjustable through the F9 command).
* @property List parameters The current settings, in display order.
* @property EditorSnapshot baseSnapshot The state the operation ran from.
* @property Function rerun Runs the operation again from [baseSnapshot] under the record it is
* given (whose [parameters] are the new values) and lands through [EditorSession.amendLastCommit]. The
* client's closure, which owns whatever expensive inputs it retained and launches its own coroutine if
* it needs one.
* @property Any identity Shared by every value of one registration, so a stale value can be
* told from a cleared record.
*/
class AdjustableOperation internal constructor(
val change: Change,
val areaId: String?,
val parameters: List<OperatorParameter>,
val baseSnapshot: EditorSnapshot,
val rerun: (AdjustableOperation) -> Unit,
internal val identity: Any,
) {
/**
* This record with new settings, keeping everything else including the identity.
*
* @param List parameters The new settings.
* @return AdjustableOperation The updated record.
*/
fun withParameters(parameters: List<OperatorParameter>): AdjustableOperation =
AdjustableOperation(change, areaId, parameters, baseSnapshot, rerun, identity)
}
@@ -0,0 +1,295 @@
package org.umamo.edit
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.deformerSelfAndDescendants
import org.umamo.runtime.model.partSelfAndDescendants
/*
* Outliner drop resolution: the pure rules deciding what dropping one outliner row onto another does,
* over the organizational tree (parts / drawables) and the deformer armature. The UI reads the band
* for its indicator and resolves the drop for its dispatch through the SAME functions here, so the
* line / fill the user sees always matches the move that happens. The tree transforms themselves
* (withOrgChildMoved / withDeformerMoved) live in StructureEdits.kt; this file only routes a drop to
* them. Mirrors the parameter panel's split (ParametersDropRules in :ui feeds ParameterTreeEdits
* here) - except the outliner's rules mention no UI types, so the whole resolution lives in :edit.
*
* アウトライナーのドロップ解決。行ドロップの帯域判定と移動先の解決を一箇所で行い、指標と実際の
* 移動が常に一致する。ツリー変換自体は StructureEdits.kt にある。
*/
/**
* Where an outliner drop is aimed: a real entity row, the synthetic puppet root (org-tree top level),
* or the synthetic Armature row (deformer-hierarchy root). Synthetic rows carry no [SelectionTarget],
* so the UI names them explicitly rather than overloading a null target.
*/
sealed interface OutlinerDropTarget {
/** A selectable outliner row (part, drawable, or deformer). */
data class Entity(val target: SelectionTarget) : OutlinerDropTarget
/** The synthetic puppet-root row - org children drop here to sit at the top level. */
data object PuppetRoot : OutlinerDropTarget
/** The synthetic Armature row - deformers drop here to become armature roots. */
data object Armature : OutlinerDropTarget
}
/**
* A resolved outliner drop: the concrete move a drop dispatches, plus whether the UI should expand
* the target row afterwards (a nest-inside drop opens the destination so the user sees the moved
* item land, rather than fearing it vanished into a collapsed branch).
*/
sealed interface OutlinerDrop {
/** True when the UI should expand the drop-target row after applying the move. */
val expandTarget: Boolean
/** Re-home a deformer in the armature's nesting hierarchy. */
data class MoveDeformer(
val id: DeformerId,
val newParentId: DeformerId?,
val beforeId: DeformerId?,
override val expandTarget: Boolean,
) : OutlinerDrop
/** Re-home an org child (a part or drawable) in the organizational tree. */
data class MoveOrgChild(
val child: OrgChild,
val newParentId: PartId?,
val before: OrgChild?,
override val expandTarget: Boolean,
) : OutlinerDrop
}
/**
* The single source of truth for what a drag will do, given what is dragged, the row under the pointer,
* and the pointer's vertical band within that row - used by BOTH the drop dispatch and the row's indicator,
* so the line / fill the user sees always matches the move that happens.
*
* Rules of thumb:
* - org children (parts / drawables) only drop inside the org tree (including the puppet root); deformers
* only inside the armature (including the Armature row);
* - a part dropped on another part reorders beside it (before / after at the midline), matching the
* parameters panel's group-on-group behaviour - nesting a part into a part is done by dropping beside
* a child inside the destination (or via Properties);
* - a drawable dropped on a part nests in the middle band and reorders at the edges;
* - a drawable target is only before / after (no children to nest into);
* - a cycle (part into its own subtree, deformer into its own subtree) returns null so the indicator and
* the dispatch agree that nothing will happen.
*
* @param SelectionTarget dragged The entity being dragged.
* @param OutlinerDropTarget target The row under the pointer.
* @param Float fraction The pointer's 0..1 position down the target row.
* @return RowDropBand? The resolved band, or null when the drop is not allowed.
*/
fun PuppetModel.outlinerDropBandFor(dragged: SelectionTarget, target: OutlinerDropTarget, fraction: Float): RowDropBand? {
// Resolve first so cycles / illegal pairings yield null - the indicator must match the dispatch.
resolveOutlinerDrop(dragged, target, fraction) ?: return null
return when (target) {
OutlinerDropTarget.PuppetRoot -> beforeOrAfter(fraction)
OutlinerDropTarget.Armature -> RowDropBand.Into
is OutlinerDropTarget.Entity -> entityDropBand(dragged, target.target, fraction)
}
}
/**
* The band an entity-row drop shows once the pairing is known to be legal.
*
* @param SelectionTarget dragged The entity being dragged.
* @param SelectionTarget target The entity under the pointer.
* @param Float fraction The pointer's 0..1 position down the target row.
* @return RowDropBand The indicator band.
*/
private fun entityDropBand(dragged: SelectionTarget, target: SelectionTarget, fraction: Float): RowDropBand =
when (target) {
// A part dropped on a part only reorders / reparents as a sibling of the target (Parameters
// group-on-group parity): the whole row is before / after at the midline, so moving folders is
// not fighting a wide "into" band. Nesting a part into a part is dropping beside a child inside
// it (or via Properties). A drawable onto a part still gets Into.
is SelectionTarget.Part ->
if (dragged is SelectionTarget.Part) {
beforeOrAfter(fraction)
} else {
nestingContainerBand(fraction)
}
is SelectionTarget.Deformer -> nestingContainerBand(fraction)
is SelectionTarget.Drawable -> beforeOrAfter(fraction)
}
/** Before above the row's midline, After below it. */
private fun beforeOrAfter(fraction: Float): RowDropBand =
if (fraction >= 0.5f) RowDropBand.After else RowDropBand.Before
/** Wider middle "into" band with before / after reorder at the edges (container rows that nest). */
private fun nestingContainerBand(fraction: Float): RowDropBand =
when {
fraction < 0.33f -> RowDropBand.Before
fraction > 0.66f -> RowDropBand.After
else -> RowDropBand.Into
}
/**
* This selection target as an [OrgChild] (a part or drawable), or null for a deformer (not in the org tree).
*
* @return OrgChild? The org-tree child, or null.
*/
fun SelectionTarget.asOrgChild(): OrgChild? =
when (this) {
is SelectionTarget.Part -> OrgChild.Part(id)
is SelectionTarget.Drawable -> OrgChild.Drawable(id)
is SelectionTarget.Deformer -> null
}
/** The org child [child]'s sibling list - its owning part's children, or the root level when it is top-level. */
private fun PuppetModel.orgSiblingsOf(child: OrgChild): List<OrgChild> {
val parent = parts.firstOrNull { child in it.children }
return parent?.children ?: rootChildren
}
/** The id of the part owning [child], or null when it is at the top level. */
private fun PuppetModel.orgParentOf(child: OrgChild): PartId? =
parts.firstOrNull { child in it.children }?.id
/** The org child immediately after [child] among its siblings, or null when it is last (append). */
private fun PuppetModel.orgSiblingAfter(child: OrgChild): OrgChild? {
val siblings = orgSiblingsOf(child)
return siblings.getOrNull(siblings.indexOf(child) + 1)
}
/** The deformer [id]'s parent in the nesting hierarchy, or null when it is an armature root. */
private fun PuppetModel.deformerParentOf(id: DeformerId): DeformerId? =
deformers.firstOrNull { it.id == id }?.parent
/** The deformer immediately after [id] among its same-parent siblings (list order), or null when last. */
private fun PuppetModel.deformerSiblingAfter(id: DeformerId): DeformerId? {
val parent = deformerParentOf(id)
val siblings = deformers.filter { it.parent == parent }.map { it.id }
return siblings.getOrNull(siblings.indexOf(id) + 1)
}
/**
* True when applying [drop] would nest a part / deformer inside its own subtree (a cycle the structure
* edit would refuse). Used so the band indicator stays blank rather than promising a no-op.
*
* @param OutlinerDrop drop The candidate move.
* @return Boolean True when the move is a cycle.
*/
private fun PuppetModel.outlinerDropIsCycle(drop: OutlinerDrop): Boolean =
when (drop) {
is OutlinerDrop.MoveOrgChild ->
drop.child is OrgChild.Part &&
drop.newParentId != null &&
drop.newParentId in partSelfAndDescendants(drop.child.id)
is OutlinerDrop.MoveDeformer ->
drop.newParentId != null && drop.newParentId in deformerSelfAndDescendants(drop.id)
}
/**
* Resolves a drop of [dragged] onto [target] at [fraction] into the concrete move it performs, routed
* by the pointer's vertical band within the target row (the same [outlinerDropBandFor] the indicator
* drew):
* - before / after a sibling: re-home the dragged item next to the target in its parent (parts and
* drawables interleave, so a drawable can land between two parts) - which changes the panel order,
* hence the draw-order tiebreak, so the viewport follows when draw orders are equal;
* - into a part (or a deformer): nest the dragged item inside it, expanding the target;
* - onto the puppet root: move an org child to the top level (before = front, after = append);
* - onto the Armature row: make a deformer an armature root.
* Drops with no valid band or across the org / armature boundary resolve to null - no move. Cycles
* resolve to null here too (not only inside the move transforms), so a release on a descendant of the
* dragged folder does nothing visibly rather than looking like a failed drag.
*
* @param SelectionTarget dragged The entity being dragged.
* @param OutlinerDropTarget target The row under the pointer.
* @param Float fraction The pointer's 0..1 position down the target row.
* @return OutlinerDrop? The move to dispatch, or null when the drop does nothing.
*/
fun PuppetModel.resolveOutlinerDrop(dragged: SelectionTarget, target: OutlinerDropTarget, fraction: Float): OutlinerDrop? {
val drop =
when (target) {
OutlinerDropTarget.PuppetRoot -> resolvePuppetRootDrop(dragged, fraction)
OutlinerDropTarget.Armature -> resolveArmatureDrop(dragged)
is OutlinerDropTarget.Entity -> resolveEntityDrop(dragged, target.target, fraction)
} ?: return null
return if (outlinerDropIsCycle(drop)) null else drop
}
/**
* Moves an org child to the puppet-root level: before = insert at the front of [PuppetModel.rootChildren],
* after (or into) = append.
*
* @param SelectionTarget dragged The entity being dragged.
* @param Float fraction The pointer's 0..1 position down the root row.
* @return OutlinerDrop? The move, or null when [dragged] is not an org child.
*/
private fun PuppetModel.resolvePuppetRootDrop(dragged: SelectionTarget, fraction: Float): OutlinerDrop? {
val child = dragged.asOrgChild() ?: return null
return if (fraction < 0.5f) {
OutlinerDrop.MoveOrgChild(child, newParentId = null, before = rootChildren.firstOrNull(), expandTarget = false)
} else {
OutlinerDrop.MoveOrgChild(child, newParentId = null, before = null, expandTarget = false)
}
}
/**
* Makes a deformer an armature root (appended among the parentless deformers).
*
* @param SelectionTarget dragged The entity being dragged.
* @return OutlinerDrop? The move, or null when [dragged] is not a deformer.
*/
private fun resolveArmatureDrop(dragged: SelectionTarget): OutlinerDrop? {
val id = (dragged as? SelectionTarget.Deformer)?.id ?: return null
return OutlinerDrop.MoveDeformer(id, newParentId = null, beforeId = null, expandTarget = true)
}
/**
* Resolves a drop onto a real entity row from the pointer band (without going through
* [outlinerDropBandFor], which itself calls resolve - that would recurse).
*
* @param SelectionTarget dragged The entity being dragged.
* @param SelectionTarget target The entity under the pointer.
* @param Float fraction The pointer's 0..1 position down the target row.
* @return OutlinerDrop? The move, or null when the pairing is illegal.
*/
private fun PuppetModel.resolveEntityDrop(dragged: SelectionTarget, target: SelectionTarget, fraction: Float): OutlinerDrop? {
if ((dragged is SelectionTarget.Deformer) != (target is SelectionTarget.Deformer)) {
return null
}
val band = entityDropBand(dragged, target, fraction)
if (dragged is SelectionTarget.Deformer && target is SelectionTarget.Deformer) {
return when (band) {
RowDropBand.Before ->
OutlinerDrop.MoveDeformer(dragged.id, deformerParentOf(target.id), beforeId = target.id, expandTarget = false)
RowDropBand.After ->
OutlinerDrop.MoveDeformer(dragged.id, deformerParentOf(target.id), beforeId = deformerSiblingAfter(target.id), expandTarget = false)
RowDropBand.Into ->
OutlinerDrop.MoveDeformer(dragged.id, target.id, beforeId = null, expandTarget = true)
}
}
val draggedChild = dragged.asOrgChild() ?: return null
val targetChild = target.asOrgChild() ?: return null
return when (band) {
RowDropBand.Before ->
OutlinerDrop.MoveOrgChild(draggedChild, orgParentOf(targetChild), before = targetChild, expandTarget = false)
RowDropBand.After ->
OutlinerDrop.MoveOrgChild(draggedChild, orgParentOf(targetChild), before = orgSiblingAfter(targetChild), expandTarget = false)
RowDropBand.Into ->
if (target is SelectionTarget.Part) {
OutlinerDrop.MoveOrgChild(draggedChild, target.id, before = null, expandTarget = true)
} else {
null
}
}
}
/**
* Applies a resolved outliner drop as one undo step, dispatching to the matching structure edit.
*
* @param OutlinerDrop drop The resolved move.
*/
fun EditorSession.applyOutlinerDrop(drop: OutlinerDrop) {
when (drop) {
is OutlinerDrop.MoveDeformer -> moveDeformer(drop.id, drop.newParentId, drop.beforeId)
is OutlinerDrop.MoveOrgChild -> moveOrgChild(drop.child, drop.newParentId, drop.before)
}
}
@@ -0,0 +1,454 @@
package org.umamo.edit
import org.umamo.runtime.keyform.CollapsedChannels
import org.umamo.runtime.keyform.colorOr
import org.umamo.runtime.keyform.flagOr
import org.umamo.runtime.keyform.hasFractionalDrawOrder
import org.umamo.runtime.keyform.integralDrawOrderOrNull
import org.umamo.runtime.keyform.scalarOr
import org.umamo.runtime.keyform.withAxisCollapsed
import org.umamo.runtime.keyform.withAxisCollapsedLifting
import org.umamo.runtime.keyform.withAxisRetargeted
import org.umamo.runtime.model.BlendShapeBinding
import org.umamo.runtime.model.BlendWeightLimit
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.ParameterKind
import org.umamo.runtime.model.ParameterNode
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.withDerivedRenderRoot
/*
* Parameter document edits: create a new axis, rename one (its display name), and delete one everywhere.
* Create and rename mirror the group edits (ParameterGroupEdits.kt) - pure PuppetModel.withX plus thin
* EditorSession wrappers through mutate. Delete is the heavier one: besides the flat parameters list, the
* panel tree, and any link, it must scrub the parameter out of every object's keyform grid and blend-shape
* binding, since each grid axis / binding references a parameter by id. The default path collapses each
* axis to the deleted parameter's default slice (discarding off-axis motion). An optional moveKeysTo
* destination retargets those axes onto another parameter instead, keeping key values and forms.
* The live pose entry is dropped in the session wrapper (pose lives on EditorSession).
*
* パラメータの作成・改名・削除。削除は各オブジェクトのキーフォーム格子から該当軸を取り除き、既定値の
* スライスへ畳み込む。moveKeysTo 指定時は軸を別パラメータへ付け替える。
*/
/**
* A fresh CParameterSource-style idstr ("Param", then "Param2", "Param3", ...) that collides with no
* existing parameter id. Deterministic from the model alone so the same edit replays identically under
* undo / redo - no clock, no random.
*
* // CMO3: CParameterSource id idstr - editor-minted sequential parameter identifiers.
*
* @return ParameterId A parameter id not already present in this model.
*/
fun PuppetModel.freshParameterId(): ParameterId {
val existing = parameters.map { parameter -> parameter.id }.toSet()
if (ParameterId("Param") !in existing) {
return ParameterId("Param")
}
var suffix = 2
while (ParameterId("Param$suffix") in existing) {
suffix++
}
return ParameterId("Param$suffix")
}
/**
* A copy of this model with a new animatable parameter [newId] named [name] of [kind] appended to the axis
* list and its leaf prepended at the root top of the panel tree (so it lands on-screen for the immediate
* inline rename, like a new group). The default -1..1 / 0 range makes it animatable (min < max) so it
* renders as a slider; it is a neutral starting point the user retargets in the range editor. A
* BLEND_SHAPE kind renders with square knob / key marks (it carries no keys until authoring captures
* them). Materializes a flat tree first for a group-less model, so the existing rows keep their order
* beneath the new parameter. Refuses (returns this same instance) a colliding id.
*
* @param ParameterId newId The minted id of the new parameter.
* @param String name The initial display name.
* @param ParameterKind kind The parameter kind (NORMAL key-form or BLEND_SHAPE); defaults to NORMAL.
* @return PuppetModel The model with the parameter added, or this if the id already exists.
*/
fun PuppetModel.withParameterCreated(
newId: ParameterId,
name: String,
kind: ParameterKind = ParameterKind.NORMAL,
): PuppetModel {
if (parameters.any { parameter -> parameter.id == newId }) {
return this
}
val newParameter = Parameter(newId, name, min = -1f, max = 1f, default = 0f, kind = kind)
val newLeaf = ParameterNode.Param(newId)
return copy(
parameters = parameters + newParameter,
parameterTree = listOf(newLeaf) + materializedParameterTree(),
)
}
/**
* A copy of this model with parameter [id] renamed to [newName] (trimmed). The id is format-level and
* never changes - only the display name. A blank name is a no-op (returns this same instance), so an empty
* commit keeps the old label; an unchanged name likewise returns this.
*
* @param ParameterId id The parameter to rename.
* @param String newName The new display name (trimmed; blank is ignored).
* @return PuppetModel The model with the parameter renamed, or this if unchanged or blank.
*/
fun PuppetModel.withParameterRenamed(id: ParameterId, newName: String): PuppetModel {
val trimmed = newName.trim()
if (trimmed.isEmpty()) {
return this
}
var changed = false
val newParameters =
parameters.map { parameter ->
if (parameter.id == id && parameter.name != trimmed) {
changed = true
parameter.copy(name = trimmed)
} else {
parameter
}
}
return if (changed) {
copy(parameters = newParameters)
} else {
this
}
}
/**
* A copy of this model with parameter [id] removed everywhere: the axis list, every panel-tree leaf, any
* link it belongs to (its partner reverts to a plain slider), and every keyform grid / blend-shape binding
* in the rig - drawables, both deformer kinds, parts, and glue intensities.
*
* Without [moveKeysTo], dropping the deleted axis collapses each grid to the slice at the parameter's
* default value (the neutral look), discarding that axis's motion. A channel track left with no axes is
* dropped, and the value of its kept slice is lifted into the owner's static so the neutral look survives
* the drop; a fractional part draw order stays behind as a constant track because the Int static slot
* cannot hold it without rounding. A geometry grid left with no axes becomes null (the drawable returns
* to its rest mesh - the base mesh is authored, never baked from a slice). Blend-shape bindings driven by
* [id] are dropped, and weight-limit curves that constrain on [id] are scrubbed.
*
* With [moveKeysTo], each matching axis is retargeted onto that destination instead (key values and forms
* kept absolute). When a grid already keys the destination, the destination axis collapses to its default
* slice first so the source's keys take over. Blend-shape bindings and weight-limit curves retarget the
* same way; a destination binding on the same owner is dropped in favour of the moved source.
*
* The render root is re-derived at the end so its per-group copies of the part tracks lose the deleted
* axis too. The live pose entry is dropped by the session wrapper. A no-op (no such parameter, or a
* missing / self [moveKeysTo]) returns this same instance.
*
* @param ParameterId id The parameter to delete.
* @param ParameterId? moveKeysTo Destination to retarget keys onto, or null to discard them.
* @return PuppetModel The model with the parameter removed, or this if it was absent / the move is invalid.
*/
fun PuppetModel.withParameterDeleted(id: ParameterId, moveKeysTo: ParameterId? = null): PuppetModel {
val deleted = parameters.firstOrNull { parameter -> parameter.id == id } ?: return this
val destination =
if (moveKeysTo != null) {
if (moveKeysTo == id) {
return this
}
parameters.firstOrNull { parameter -> parameter.id == moveKeysTo } ?: return this
} else {
null
}
val keepValue = deleted.default
val destinationKeepValue = destination?.default ?: 0f
// Both halves of a drawable key on parameters: the geometry grid and every channel track.
val newDrawables =
drawables.map { drawable ->
val geometry =
if (destination != null) {
drawable.geometryGrid?.withAxisRetargeted(id, destination.id, destinationKeepValue)
} else {
drawable.geometryGrid?.withAxisCollapsed(id, keepValue)
}
val scrubbed =
if (destination != null) {
CollapsedChannels(
drawable.channelGrids.withAxisRetargeted(id, destination.id, destinationKeepValue),
emptyMap(),
)
} else {
drawable.channelGrids.withAxisCollapsedLifting(id, keepValue)
}
val blendShapes = drawable.blendShapes.withParameterScrubbed(id, destination?.id)
if (
geometry === drawable.geometryGrid &&
scrubbed.channelGrids === drawable.channelGrids &&
blendShapes === drawable.blendShapes
) {
drawable
} else {
drawable.copy(
geometryGrid = geometry,
channelGrids = scrubbed.channelGrids,
drawOrder = scrubbed.lifted.scalarOr(FormChannel.DRAW_ORDER, drawable.drawOrder),
opacity = scrubbed.lifted.scalarOr(FormChannel.OPACITY, drawable.opacity),
multiplyColor = scrubbed.lifted.colorOr(FormChannel.MULTIPLY_COLOR, drawable.multiplyColor),
screenColor = scrubbed.lifted.colorOr(FormChannel.SCREEN_COLOR, drawable.screenColor),
blendShapes = blendShapes,
)
}
}
// Both halves of a deformer key on parameters: the geometry grid and every channel track.
val newDeformers =
deformers.map { deformer ->
val scrubbed =
if (destination != null) {
CollapsedChannels(
deformer.channelGrids.withAxisRetargeted(id, destination.id, destinationKeepValue),
emptyMap(),
)
} else {
deformer.channelGrids.withAxisCollapsedLifting(id, keepValue)
}
when (deformer) {
is Deformer.Warp -> {
val geometry =
if (destination != null) {
deformer.geometryGrid?.withAxisRetargeted(id, destination.id, destinationKeepValue)
} else {
deformer.geometryGrid?.withAxisCollapsed(id, keepValue)
}
val blendShapes = deformer.blendShapes.withParameterScrubbed(id, destination?.id)
if (
geometry === deformer.geometryGrid &&
scrubbed.channelGrids === deformer.channelGrids &&
blendShapes === deformer.blendShapes
) {
deformer
} else {
deformer.copy(
geometryGrid = geometry,
channelGrids = scrubbed.channelGrids,
opacity = scrubbed.lifted.scalarOr(FormChannel.OPACITY, deformer.opacity),
multiplyColor = scrubbed.lifted.colorOr(FormChannel.MULTIPLY_COLOR, deformer.multiplyColor),
screenColor = scrubbed.lifted.colorOr(FormChannel.SCREEN_COLOR, deformer.screenColor),
blendShapes = blendShapes,
)
}
}
is Deformer.Rotation -> {
val geometry =
if (destination != null) {
deformer.geometryGrid?.withAxisRetargeted(id, destination.id, destinationKeepValue)
} else {
deformer.geometryGrid?.withAxisCollapsed(id, keepValue)
}
val blendShapes = deformer.blendShapes.withParameterScrubbed(id, destination?.id)
if (
geometry === deformer.geometryGrid &&
scrubbed.channelGrids === deformer.channelGrids &&
blendShapes === deformer.blendShapes
) {
deformer
} else {
deformer.copy(
geometryGrid = geometry,
channelGrids = scrubbed.channelGrids,
opacity = scrubbed.lifted.scalarOr(FormChannel.OPACITY, deformer.opacity),
multiplyColor = scrubbed.lifted.colorOr(FormChannel.MULTIPLY_COLOR, deformer.multiplyColor),
screenColor = scrubbed.lifted.colorOr(FormChannel.SCREEN_COLOR, deformer.screenColor),
flipX = scrubbed.lifted.flagOr(FormChannel.FLIP_X, deformer.flipX),
flipY = scrubbed.lifted.flagOr(FormChannel.FLIP_Y, deformer.flipY),
blendShapes = blendShapes,
)
}
}
}
}
val newParts =
parts.map { part ->
val scrubbed =
if (destination != null) {
CollapsedChannels(
part.channelGrids.withAxisRetargeted(id, destination.id, destinationKeepValue),
emptyMap(),
)
} else {
part.channelGrids.withAxisCollapsedLifting(id, keepValue)
}
val blendShapes = part.blendShapes.withParameterScrubbed(id, destination?.id)
if (scrubbed.channelGrids === part.channelGrids && blendShapes === part.blendShapes) {
part
} else {
val channels =
if (destination != null) {
scrubbed.channelGrids
} else {
scrubbed.withFractionalDrawOrderKept().channelGrids
}
part.copy(
channelGrids = channels,
drawOrder = scrubbed.lifted.integralDrawOrderOrNull() ?: part.drawOrder,
composite =
part.composite.copy(
opacity = scrubbed.lifted.scalarOr(FormChannel.OPACITY, part.composite.opacity),
multiplyColor = scrubbed.lifted.colorOr(FormChannel.MULTIPLY_COLOR, part.composite.multiplyColor),
screenColor = scrubbed.lifted.colorOr(FormChannel.SCREEN_COLOR, part.composite.screenColor),
),
blendShapes = blendShapes,
)
}
}
// Glue tracks key on parameters exactly like the rest, so they need the same scrub - without it a
// deleted parameter survives as a dangling KeyformAxis.parameterId that nothing can ever resolve.
val newGlues =
glues.map { glue ->
val scrubbed =
if (destination != null) {
CollapsedChannels(
glue.channelGrids.withAxisRetargeted(id, destination.id, destinationKeepValue),
emptyMap(),
)
} else {
glue.channelGrids.withAxisCollapsedLifting(id, keepValue)
}
if (scrubbed.channelGrids === glue.channelGrids) {
glue
} else {
glue.copy(
channelGrids = scrubbed.channelGrids,
intensity = scrubbed.lifted.scalarOr(FormChannel.GLUE_INTENSITY, glue.intensity),
)
}
}
return copy(
parameters = parameters.filterNot { parameter -> parameter.id == id },
parameterLinks = parameterLinks.filterNot { link -> link.horizontal == id || link.vertical == id },
parameterTree = removeParameterLeaf(parameterTree, id),
drawables = newDrawables,
deformers = newDeformers,
parts = newParts,
glues = newGlues,
).withDerivedRenderRoot()
}
/**
* These blend-shape bindings with [id] discarded or retargeted onto [moveKeysTo]. Destination bindings
* on the same owner yield to a moved source. Weight-limit curves that constrain on [id] follow the same
* rule. Returns this same list when nothing referenced [id].
*/
private fun <TForm : Any> List<BlendShapeBinding<TForm>>.withParameterScrubbed(
id: ParameterId,
moveKeysTo: ParameterId?,
): List<BlendShapeBinding<TForm>> {
val hasSource = any { binding -> binding.parameterId == id }
val touchesId =
hasSource || any { binding -> binding.limits.any { limit -> limit.parameterId == id } }
if (!touchesId) {
return this
}
var changed = false
val result = ArrayList<BlendShapeBinding<TForm>>(size)
for (binding in this) {
when {
binding.parameterId == id && moveKeysTo != null -> {
changed = true
result +=
binding.copy(
parameterId = moveKeysTo,
limits = binding.limits.withConstraintScrubbed(id, moveKeysTo),
)
}
binding.parameterId == id -> {
changed = true
}
binding.parameterId == moveKeysTo && hasSource -> {
changed = true
}
else -> {
val newLimits = binding.limits.withConstraintScrubbed(id, moveKeysTo)
if (newLimits !== binding.limits) {
changed = true
result += binding.copy(limits = newLimits)
} else {
result += binding
}
}
}
}
return if (changed) result else this
}
/** These weight-limit curves with [id] discarded or retargeted onto [moveKeysTo]. */
private fun List<BlendWeightLimit>.withConstraintScrubbed(
id: ParameterId,
moveKeysTo: ParameterId?,
): List<BlendWeightLimit> {
if (none { limit -> limit.parameterId == id }) {
return this
}
return if (moveKeysTo != null) {
mapNotNull { limit ->
when {
limit.parameterId == id -> limit.copy(parameterId = moveKeysTo)
limit.parameterId == moveKeysTo -> null
else -> limit
}
}
} else {
filterNot { limit -> limit.parameterId == id }
}
}
/**
* These collapsed channels with a fractional lifted DRAW_ORDER kept as a zero-axis constant track.
*
* A part's static draw-order slot is an Int, so a fractional slice value cannot lift without rounding,
* and rounding could reorder two parts the track kept distinct. The deleted axis cannot stay either, so
* the value is kept as a single-cell track with no axes - the same degenerate shape MOC3 import already
* produces - which the evaluator reads as a constant.
*
* @return CollapsedChannels The channels with the fractional draw order retained as a constant track.
*/
private fun CollapsedChannels.withFractionalDrawOrderKept(): CollapsedChannels {
if (!lifted.hasFractionalDrawOrder()) {
return this
}
val constantTrack = KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), lifted[FormChannel.DRAW_ORDER]!!)))
return CollapsedChannels(
ChannelGrids(channelGrids.gridsByChannel + (FormChannel.DRAW_ORDER to constantTrack)),
lifted,
)
}
/** This node list with every [ParameterNode.Param] leaf for [id] spliced out, recursing into groups. */
private fun removeParameterLeaf(nodes: List<ParameterNode>, id: ParameterId): List<ParameterNode> =
nodes.mapNotNull { node ->
when (node) {
is ParameterNode.Param -> if (node.id == id) null else node
is ParameterNode.Group -> node.copy(children = removeParameterLeaf(node.children, id))
}
}
/**
* Creates a new animatable parameter (a freshly minted id, default -1..1 range) named [name] of [kind]
* and returns its id, so the caller can immediately open inline rename on it. One undo step.
*
* @param String name The initial display name.
* @param ParameterKind kind The parameter kind (NORMAL key-form or BLEND_SHAPE); defaults to NORMAL.
* @return ParameterId The id of the created parameter.
*/
fun EditorSession.createParameter(name: String, kind: ParameterKind = ParameterKind.NORMAL): ParameterId {
val id = model.value.freshParameterId()
mutate(ParameterChange.Create(id)) { model -> model.withParameterCreated(id, name, kind) }
return id
}
/**
* Renames parameter [id]'s display name to [newName] (trimmed) as one undo step. A blank or unchanged
* name records nothing.
*
* @param ParameterId id The parameter to rename.
* @param String newName The new display name.
*/
fun EditorSession.renameParameter(id: ParameterId, newName: String) {
mutate(ParameterChange.Rename(id, newName.trim())) { model -> model.withParameterRenamed(id, newName) }
}
@@ -0,0 +1,87 @@
package org.umamo.edit
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.ParameterLink
import org.umamo.runtime.model.PuppetModel
/**
* A copy of this model with parameter [id]'s range set to [min]..[max] and its default clamped within
* it. The range is normalized so the stored minimum never exceeds the maximum regardless of entry order
* (typing a maximum below the current minimum still yields a valid range). The default is coerced into
* the resulting range. Returns this same instance unchanged when nothing actually differs (so the caller
* need not pre-check) or when [id] is not a parameter of this model.
*
* Pure over the model: it does not touch the live pose. Re-clamping the live value into a shrunk range
* is the session's concern, since the pose is editor state held outside the model.
*
* パラメータ [id] の範囲(最小・最大)と既定値を設定したモデルのコピー。範囲は最小≤最大に正規化し、
* 既定値は範囲内に丸める。変化が無ければ同一インスタンスを返す。ライブのポーズには触れない。
*
* @param ParameterId id The parameter to retarget.
* @param Float min The requested minimum.
* @param Float default The requested default (clamped into the resulting range).
* @param Float max The requested maximum.
* @return PuppetModel This model with the parameter's range and default updated, or this if unchanged.
*/
fun PuppetModel.withParameterRange(id: ParameterId, min: Float, default: Float, max: Float): PuppetModel {
val low = minOf(min, max)
val high = maxOf(min, max)
val clampedDefault = default.coerceIn(low, high)
val updated =
parameters.map { parameter ->
if (parameter.id == id) {
parameter.copy(min = low, max = high, default = clampedDefault)
} else {
parameter
}
}
if (updated == parameters) {
return this
}
return copy(parameters = updated)
}
/**
* A copy of this model with the parameter link [horizontal]->[vertical] added ([linked] = true) or
* removed ([linked] = false). The model edit is the invariant keeper - any UI-side validity check is
* advisory only - so an invalid request returns this same instance unchanged (and the session's
* same-instance short-circuit then records no undo step): a link is refused when either id already
* belongs to any existing link, when the ids are equal, or when either id is not a parameter of this
* model; an unlink of a pair that is not present is a no-op.
*
* Pure over the model: values, ranges, and the live pose are untouched - a link only changes how the
* pair presents (one 2D pad instead of two sliders).
*
* // CMO3: CParameterSource.combined - the first member flags the pair, the partner is the next
* // parameter in document order (see Cmo3Import's link derivation).
*
* パラメータリンクを追加または削除したモデルのコピー。無効な要求(既にリンク済み・同一 ID・未知の
* ID・存在しないペアの解除)は同一インスタンスを返し、取り消し段も記録されない。値やポーズには
* 触れない。
*
* @param ParameterId horizontal The X-axis (upper) parameter.
* @param ParameterId vertical The Y-axis parameter (the next parameter below in panel order).
* @param Boolean linked True to create the link, false to remove it.
* @return PuppetModel This model with the link added / removed, or this same instance when refused.
*/
fun PuppetModel.withParameterLink(horizontal: ParameterId, vertical: ParameterId, linked: Boolean): PuppetModel {
if (linked) {
if (horizontal == vertical) {
return this
}
val knownIds = parameters.map { parameter -> parameter.id }.toSet()
if (horizontal !in knownIds || vertical !in knownIds) {
return this
}
val linkedMembers = parameterLinks.flatMap { link -> listOf(link.horizontal, link.vertical) }.toSet()
if (horizontal in linkedMembers || vertical in linkedMembers) {
return this
}
return copy(parameterLinks = parameterLinks + ParameterLink(horizontal, vertical))
}
val remaining = parameterLinks.filterNot { link -> link.horizontal == horizontal && link.vertical == vertical }
if (remaining.size == parameterLinks.size) {
return this
}
return copy(parameterLinks = remaining)
}
@@ -0,0 +1,142 @@
package org.umamo.edit
import org.umamo.runtime.model.ParameterGroupId
import org.umamo.runtime.model.ParameterNode
import org.umamo.runtime.model.PuppetModel
/*
* Parameter-group document edits: create an empty group, delete (unwrap) a group keeping its parameters,
* and rename a group. All operate on PuppetModel.parameterTree (layout) and never touch the flat
* parameters list or the links; each undoes for free through EditorSession.mutate's whole-model snapshot.
* Reuses materializedParameterTree / collectParameterGroupIds from ParameterTreeEdits.
*
* パラメータグループの編集:空グループ作成・グループ解除(子は残す)・改名。parameterTree のみを変更。
*/
/**
* A fresh CParameterGroup-style idstr ("ParamGroup", then "ParamGroup2", "ParamGroup3", ...) that
* collides with no existing group id anywhere in the tree. Deterministic from the model alone so the
* same edit replays identically under undo / redo - no clock, no random.
*
* // CMO3: CParameterGroupId.idstr - editor-minted sequential group identifiers.
*
* @return ParameterGroupId A group id not already present in this model.
*/
fun PuppetModel.freshParameterGroupId(): ParameterGroupId {
val existing = collectParameterGroupIds(parameterTree)
if (ParameterGroupId("ParamGroup") !in existing) {
return ParameterGroupId("ParamGroup")
}
var suffix = 2
while (ParameterGroupId("ParamGroup$suffix") in existing) {
suffix++
}
return ParameterGroupId("ParamGroup$suffix")
}
/**
* A copy of this model with a new empty group [newGroupId] named [name] inserted at the top of the
* parameter root, expanded. Materializes a flat tree first for a group-less model, so the existing rows
* keep their order beneath the new group. An empty group has no visual anchor, so it lands at the top of
* the scroll region where the user is already looking and its immediate inline-rename is on screen -
* rather than below the fold. Refuses (returns this same instance) a colliding id.
*
* @param ParameterGroupId newGroupId The minted id of the new group.
* @param String name The initial display name.
* @return PuppetModel The model with the group added, or this if the id already exists.
*/
fun PuppetModel.withParameterGroupCreated(newGroupId: ParameterGroupId, name: String): PuppetModel {
if (newGroupId in collectParameterGroupIds(parameterTree)) {
return this
}
val newGroup = ParameterNode.Group(newGroupId, name, initiallyOpen = true, children = emptyList())
return copy(parameterTree = listOf(newGroup) + materializedParameterTree())
}
/**
* A copy of this model with group [groupId] dissolved: its child nodes splice into the tree at the
* group's own position and the group node is dropped, so no parameter is lost. Never touches the flat
* parameters list or the links. A no-op (no such group) returns this same instance.
*
* @param ParameterGroupId groupId The group to unwrap.
* @return PuppetModel The model with the group unwrapped, or this if it was absent.
*/
fun PuppetModel.withParameterGroupDeleted(groupId: ParameterGroupId): PuppetModel {
if (groupId !in collectParameterGroupIds(parameterTree)) {
return this
}
fun splice(nodes: List<ParameterNode>): List<ParameterNode> =
nodes.flatMap { node ->
when {
node is ParameterNode.Group && node.id == groupId -> node.children
node is ParameterNode.Group -> listOf(node.copy(children = splice(node.children)))
else -> listOf(node)
}
}
return copy(parameterTree = splice(parameterTree))
}
/**
* A copy of this model with group [groupId] renamed to [newName] (trimmed). A blank name is a no-op
* (returns this same instance), so an empty commit keeps the old label. Names are user data - never
* localized - and are not unique; identity is the group id, so only the matching node changes.
*
* @param ParameterGroupId groupId The group to rename.
* @param String newName The new display name (trimmed; blank is ignored).
* @return PuppetModel The model with the group renamed, or this if unchanged or blank.
*/
fun PuppetModel.withParameterGroupRenamed(groupId: ParameterGroupId, newName: String): PuppetModel {
val trimmed = newName.trim()
if (trimmed.isEmpty()) {
return this
}
fun rename(nodes: List<ParameterNode>): List<ParameterNode> =
nodes.map { node ->
when {
node is ParameterNode.Group && node.id == groupId -> node.copy(name = trimmed)
node is ParameterNode.Group -> node.copy(children = rename(node.children))
else -> node
}
}
val newTree = rename(parameterTree)
if (newTree == parameterTree) {
return this
}
return copy(parameterTree = newTree)
}
/**
* Creates a new empty parameter group (a freshly minted id, expanded) and returns its id, so the caller
* can immediately open inline rename on it. One undo step.
*
* @param String name The initial display name.
* @return ParameterGroupId The id of the created group.
*/
fun EditorSession.createParameterGroup(name: String): ParameterGroupId {
val id = model.value.freshParameterGroupId()
mutate(ParameterChange.CreateGroup(id)) { model -> model.withParameterGroupCreated(id, name) }
return id
}
/**
* Deletes (unwraps) parameter group [id], splicing its parameters into the parent, as one undo step. A
* no-op records nothing.
*
* @param ParameterGroupId id The group to unwrap.
*/
fun EditorSession.deleteParameterGroup(id: ParameterGroupId) {
mutate(ParameterChange.DeleteGroup(id)) { model -> model.withParameterGroupDeleted(id) }
}
/**
* Renames parameter group [id] to [newName] (trimmed) as one undo step. A blank or unchanged name
* records nothing.
*
* @param ParameterGroupId id The group to rename.
* @param String newName The new display name.
*/
fun EditorSession.renameParameterGroup(id: ParameterGroupId, newName: String) {
mutate(ParameterChange.RenameGroup(id, newName.trim())) { model -> model.withParameterGroupRenamed(id, newName) }
}
@@ -0,0 +1,257 @@
package org.umamo.edit
import org.umamo.runtime.model.ParameterGroupId
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.ParameterNode
import org.umamo.runtime.model.PuppetModel
/*
* Parameter-panel group-tree structure edits. PuppetModel.parameterTree is the canonical panel order
* (an ordered mix of parameter leaves and named groups); the flat parameters list stays the id-keyed
* authoritative axis list, whose ORDER nothing reads at runtime once a tree exists. So a reorder or a
* move into / out of a group rewrites ONLY parameterTree, leaving parameters and parameterLinks alone -
* the future CMO3 exporter flattens the tree for the _sources order. A model imported with no groups
* has an empty tree; the first real structure edit materializes a flat all-leaves-at-root tree so there
* is one code path afterward. Every edit snapshots the whole PuppetModel through EditorSession.mutate,
* so it undoes for free.
*
* パラメータパネルのグループツリー構造編集。parameterTree が表示順の正で、平坦な parameters は id 基準
* の軸リスト。並べ替え・グループ出入りは parameterTree だけを書き換える。
*/
/**
* What a parameter-tree move relocates: a run of one or two adjacent parameter leaves (a slider is one
* leaf, a linked 2D pad is two, moved contiguously so they stay adjacent for combined CMO3 export), or a
* whole group.
*/
sealed interface ParameterMoveSubject {
/** One or two adjacent parameter leaves, in order (a pad is horizontal then vertical). */
data class Leaves(val ids: List<ParameterId>) : ParameterMoveSubject
/** A whole group node, moved with its children intact. */
data class Group(val id: ParameterGroupId) : ParameterMoveSubject
}
/**
* A position anchor in the parameter tree - "insert before this node". Null anywhere a ref is expected
* means "append at the destination's end".
*/
sealed interface ParameterNodeRef {
/** Anchor on a parameter leaf. */
data class Leaf(val id: ParameterId) : ParameterNodeRef
/** Anchor on a group. */
data class Group(val id: ParameterGroupId) : ParameterNodeRef
}
/**
* This model's parameter tree, materializing a flat all-leaves-at-root tree when the model carries no
* groups. Gives structure edits one shape to operate on: a group-less model becomes a root list of
* [ParameterNode.Param] in the flat parameters order (which is what the panel already renders for an
* empty tree), so the first move / group edit has a tree to rewrite.
*
* @return List<ParameterNode> The existing tree, or a freshly materialized flat one.
*/
internal fun PuppetModel.materializedParameterTree(): List<ParameterNode> =
if (parameterTree.isEmpty()) {
parameters.map { parameter -> ParameterNode.Param(parameter.id) }
} else {
parameterTree
}
/**
* Every group id anywhere in [nodes], recursing into nested groups. Used to mint collision-free ids and
* to validate a move destination.
*
* @param List nodes The tree (or subtree) to scan.
* @return Set<ParameterGroupId> Every group id present.
*/
internal fun collectParameterGroupIds(nodes: List<ParameterNode>): Set<ParameterGroupId> {
val ids = HashSet<ParameterGroupId>()
fun walk(list: List<ParameterNode>) {
for (node in list) {
if (node is ParameterNode.Group) {
ids.add(node.id)
walk(node.children)
}
}
}
walk(nodes)
return ids
}
/** The node ids removed by a detach for [subject] (leaf ids, or the single group id). */
private fun ParameterMoveSubject.movedLeafIds(): Set<ParameterId> =
when (this) {
is ParameterMoveSubject.Leaves -> ids.toSet()
is ParameterMoveSubject.Group -> emptySet()
}
/** The group id removed by a detach for [subject], or null when it moves leaves. */
private fun ParameterMoveSubject.movedGroupId(): ParameterGroupId? =
when (this) {
is ParameterMoveSubject.Leaves -> null
is ParameterMoveSubject.Group -> id
}
/**
* Removes the moved node(s) from a node list (non-recursively at this level), returning the survivors and
* the detached group node when [subject] was a group found here.
*/
private fun List<ParameterNode>.detachSubject(subject: ParameterMoveSubject): List<ParameterNode> {
val movedLeaves = subject.movedLeafIds()
val movedGroup = subject.movedGroupId()
return filterNot { node ->
when (node) {
is ParameterNode.Param -> node.id in movedLeaves
is ParameterNode.Group -> node.id == movedGroup
}
}
}
/** This node list with [inserted] placed before [before] (or appended when [before] is null or absent). */
private fun List<ParameterNode>.withNodesInsertedBefore(inserted: List<ParameterNode>, before: ParameterNodeRef?): List<ParameterNode> {
val result = toMutableList()
val insertAt =
before?.let { ref ->
result.indexOfFirst { node -> node.matchesRef(ref) }
}?.takeIf { index -> index >= 0 } ?: result.size
result.addAll(insertAt, inserted)
return result
}
/** True when this node is the one [ref] names. */
private fun ParameterNode.matchesRef(ref: ParameterNodeRef): Boolean =
when {
this is ParameterNode.Param && ref is ParameterNodeRef.Leaf -> id == ref.id
this is ParameterNode.Group && ref is ParameterNodeRef.Group -> id == ref.id
else -> false
}
/**
* A copy of this model with [subject] relocated in the parameter-panel group tree: under
* [newParentGroupId] (null = the root level) and inserted before [before] there (null / absent =
* appended). The flat parameters list and the links are untouched - this is layout only. Materializes a
* flat tree first when the model has no groups, so one code path serves grouped and group-less models.
* The moved leaves are always re-inserted contiguously in [subject] order, so a linked pad keeps its
* two members adjacent regardless of a slightly-off UI anchor. Refuses - returning this same instance,
* so the session records no undo step - a group moved under any group (groups do not nest one level
* deep), an unknown destination group, and any no-op move.
*
* @param ParameterMoveSubject subject The leaves or group to move.
* @param ParameterGroupId? newParentGroupId The destination group, or null for the root level.
* @param ParameterNodeRef? before The sibling to insert before, or null to append.
* @return PuppetModel The model with the move applied, or this if it was a no-op or illegal.
*/
fun PuppetModel.withParameterRowMoved(
subject: ParameterMoveSubject,
newParentGroupId: ParameterGroupId?,
before: ParameterNodeRef?,
): PuppetModel {
// One level only: a group can be reordered among root nodes but never dropped inside another group.
if (subject is ParameterMoveSubject.Group && newParentGroupId != null) {
return this
}
val workingTree = materializedParameterTree()
if (newParentGroupId != null && newParentGroupId !in collectParameterGroupIds(workingTree)) {
return this
}
// Detached-first snapshot of what is being moved, resolved before the tree loses it.
val insertedNodes = collectSubjectNodes(workingTree, subject)
if (insertedNodes.isEmpty()) {
return this
}
// Detach at the root and inside every group.
val detachedRoot =
workingTree.detachSubject(subject).map { node ->
if (node is ParameterNode.Group) {
node.copy(children = node.children.detachSubject(subject))
} else {
node
}
}
val newTree: List<ParameterNode> =
if (newParentGroupId == null) {
detachedRoot.withNodesInsertedBefore(insertedNodes, before)
} else {
detachedRoot.map { node ->
if (node is ParameterNode.Group && node.id == newParentGroupId) {
node.copy(children = node.children.withNodesInsertedBefore(insertedNodes, before))
} else {
node
}
}
}
if (newTree == workingTree) {
return this
}
return copy(parameterTree = newTree)
}
/**
* The actual [ParameterNode]s named by [subject], found anywhere in [tree]. Leaves are returned as fresh
* [ParameterNode.Param]s in [subject] order (so a pad stays horizontal-then-vertical); a group is
* returned as its existing node with children intact. Empty when nothing matched.
*/
private fun collectSubjectNodes(tree: List<ParameterNode>, subject: ParameterMoveSubject): List<ParameterNode> =
when (subject) {
is ParameterMoveSubject.Leaves -> {
val present = collectLeafIds(tree)
subject.ids.filter { id -> id in present }.map { id -> ParameterNode.Param(id) }
}
is ParameterMoveSubject.Group -> {
val found = findGroupNode(tree, subject.id)
if (found == null) {
emptyList()
} else {
listOf(found)
}
}
}
/** Every leaf id anywhere in [nodes]. */
private fun collectLeafIds(nodes: List<ParameterNode>): Set<ParameterId> {
val ids = HashSet<ParameterId>()
fun walk(list: List<ParameterNode>) {
for (node in list) {
when (node) {
is ParameterNode.Param -> ids.add(node.id)
is ParameterNode.Group -> walk(node.children)
}
}
}
walk(nodes)
return ids
}
/** The group node with [groupId] anywhere in [nodes], or null. */
private fun findGroupNode(nodes: List<ParameterNode>, groupId: ParameterGroupId): ParameterNode.Group? {
for (node in nodes) {
if (node is ParameterNode.Group) {
if (node.id == groupId) {
return node
}
val nested = findGroupNode(node.children, groupId)
if (nested != null) {
return nested
}
}
}
return null
}
/**
* Moves a parameter row - one or two adjacent leaves, or a group - in the panel tree as one undo step.
* A refused or no-op move records nothing.
*
* @param ParameterMoveSubject subject The leaves or group to move.
* @param ParameterGroupId? newParentGroupId The destination group, or null for the root level.
* @param ParameterNodeRef? before The sibling to insert before, or null to append.
*/
fun EditorSession.moveParameterRow(subject: ParameterMoveSubject, newParentGroupId: ParameterGroupId?, before: ParameterNodeRef?) {
mutate(ParameterChange.MoveNode(subject, newParentGroupId)) { model ->
model.withParameterRowMoved(subject, newParentGroupId, before)
}
}
@@ -0,0 +1,17 @@
package org.umamo.edit
/**
* Platform polygon triangulation for Add Vertex Accept (closed draft rings).
*
* JVM/Android use poly2tri constrained Delaunay so diagonals zigzag (maximize min angle) instead of
* cascading ears along the boundary.
*/
internal expect object PolygonTriangulator {
/**
* Triangulates a simple polygon given as interleaved [x0,y0, x1,y1, …].
*
* @param DoubleArray xy Flat vertex coordinates (length = 2 × vertex count).
* @return IntArray Flat triangle indices into the polygon (groups of three); empty on refusal.
*/
fun triangulate(xy: DoubleArray): IntArray
}
@@ -0,0 +1,260 @@
package org.umamo.edit
import kotlin.math.sqrt
/* Proportional editing (Blender's O): a modal transform also pulls the UNSELECTED vertices within an
* influence radius, each weighted by a falloff curve over its distance to the nearest selected vertex,
* so mesh edits feel like sculpting instead of vertex-by-vertex CAD. This file holds the pure math
* (the falloff curves and the weight map); the session carries the on/off state and the gizmo overlay
* feeds the weights into the weighted MeshTransforms variants. */
/** The influence radius proportional editing starts with, in world units (canvas px). */
const val DEFAULT_PROPORTIONAL_RADIUS_WORLD: Float = 200f
/** The smallest allowed influence radius, in world units. */
const val MIN_PROPORTIONAL_RADIUS_WORLD: Float = 1f
/** The largest allowed influence radius, in world units. */
const val MAX_PROPORTIONAL_RADIUS_WORLD: Float = 100_000f
/**
* The geometric factor one scroll-wheel step multiplies (or divides) the influence radius by during a
* modal transform, so a step stays proportional at any scale (Blender resizes its proportional circle
* the same way).
*/
const val PROPORTIONAL_RADIUS_STEP_FACTOR: Float = 1.1f
/**
* The falloff curve shaping how a vertex's influence fades from 1 (at the selection) to 0 (at the
* radius edge) - Blender's proportional-editing falloff set, minus the randomized ones.
*
* プロポーショナル編集の減衰カーブの種類(Blender と同じ)。
*/
enum class ProportionalFalloff {
Smooth,
Sphere,
Root,
Sharp,
Linear,
Constant,
}
/**
* The proportional-editing configuration while it is enabled: the falloff curve, the influence
* radius, and whether influence spreads only through CONNECTED geometry (Blender's Connected Only -
* distances measured along mesh edges instead of straight-line, so the halo never leaps a gap to
* nearby-but-unconnected geometry). Transient session state like the tool latches (deliberately NOT
* part of EditorSnapshot); the last configuration is remembered across off/on toggles, the
* circle-select radius pattern.
*
* プロポーショナル編集の設定(減衰カーブ、影響半径、接続のみ)。オン・オフをまたいで記憶される一時状態。
*
* @property ProportionalFalloff falloff The falloff curve.
* @property Float radiusWorld The influence radius, in world units (canvas px).
* @property Boolean connectedOnly True to measure influence along mesh edges (geodesic) instead of
* straight-line distance.
*/
data class ProportionalEditState(
val falloff: ProportionalFalloff,
val radiusWorld: Float,
val connectedOnly: Boolean = false,
)
/** The proportional configuration a session starts with: the smooth falloff at the default radius. */
val DEFAULT_PROPORTIONAL_EDIT_STATE: ProportionalEditState = ProportionalEditState(ProportionalFalloff.Smooth, DEFAULT_PROPORTIONAL_RADIUS_WORLD)
/**
* The falloff weight at a normalized distance: 1 at the selection (distance 0), 0 at and beyond the
* radius edge (distance >= 1), shaped in between by the curve. The formulas match Blender's
* proportional falloffs over fade = 1 - distance: Smooth is the smoothstep 3·fade² - 2·fade³, Sphere is
* the quarter-circle sqrt(1 - distance²), Root is sqrt(fade), Sharp is fade², Linear is fade, and
* Constant is 1 everywhere inside the radius.
*
* @param ProportionalFalloff falloff The falloff curve.
* @param Float normalizedDistance The vertex's distance to the nearest selected vertex, divided by the
* influence radius (values below 0 clamp to full weight).
* @return Float The weight in [0, 1].
*/
fun proportionalWeight(falloff: ProportionalFalloff, normalizedDistance: Float): Float {
if (normalizedDistance >= 1f) {
return 0f
}
if (normalizedDistance <= 0f) {
return 1f
}
val fade = 1f - normalizedDistance
return when (falloff) {
ProportionalFalloff.Smooth -> fade * fade * (3f - 2f * fade)
ProportionalFalloff.Sphere -> sqrt(1f - normalizedDistance * normalizedDistance)
ProportionalFalloff.Root -> sqrt(fade)
ProportionalFalloff.Sharp -> fade * fade
ProportionalFalloff.Linear -> fade
ProportionalFalloff.Constant -> 1f
}
}
/**
* One influenced vertex's proportional-editing sample: its falloff weight and the covered vertex it
* measured its distance against. The nearest-covered identity is what lets Individual Origins anchor
* the influenced halo on the OWNING island's pivot instead of the shared gesture anchor - the weight
* alone cannot say which island a bystander vertex belongs with.
*
* @property Float weight The falloff weight in (0, 1].
* @property Int nearestCoveredIndex The covered vertex this vertex measured its distance to.
*/
data class ProportionalInfluence(
val weight: Float,
val nearestCoveredIndex: Int,
)
/**
* The proportional influence map for one mesh: every vertex NOT in [coveredIndices] whose distance to
* the nearest covered vertex is inside [radiusWorld] maps to its falloff weight plus that nearest
* covered vertex; covered vertices (they move at full strength through the pivot groups) and vertices
* outside the radius are absent. The distances are measured in whatever space [positions] lives in -
* the overlay passes the frozen world-posed shape, matching the world-unit radius.
*
* The nearest-covered scan is O(covered x uncovered), fine at rigging mesh sizes (hundreds of
* vertices); an acceleration structure can slot in here later without changing the contract.
*
* @param FloatArray positions The interleaved vertex positions the distances are measured in.
* @param Set<Int> coveredIndices The vertices the selection covers (excluded from the map).
* @param Float radiusWorld The influence radius, in the positions' units.
* @param ProportionalFalloff falloff The falloff curve shaping the weights.
* @return Map<Int, ProportionalInfluence> Vertex index to influence, for every influenced vertex.
*/
fun proportionalInfluences(
positions: FloatArray,
coveredIndices: Set<Int>,
radiusWorld: Float,
falloff: ProportionalFalloff,
): Map<Int, ProportionalInfluence> {
if (coveredIndices.isEmpty() || radiusWorld <= 0f) {
return emptyMap()
}
val radiusSquared = radiusWorld * radiusWorld
val influences = LinkedHashMap<Int, ProportionalInfluence>()
val vertexCount = positions.size / 2
for (vertexIndex in 0 until vertexCount) {
if (vertexIndex in coveredIndices) {
continue
}
val vertexX = positions[vertexIndex * 2]
val vertexY = positions[vertexIndex * 2 + 1]
var nearestSquared = Float.MAX_VALUE
var nearestCovered = -1
for (coveredIndex in coveredIndices) {
val deltaX = positions[coveredIndex * 2] - vertexX
val deltaY = positions[coveredIndex * 2 + 1] - vertexY
val distanceSquared = deltaX * deltaX + deltaY * deltaY
if (distanceSquared < nearestSquared) {
nearestSquared = distanceSquared
nearestCovered = coveredIndex
}
}
if (nearestSquared < radiusSquared && nearestCovered >= 0) {
val weight = proportionalWeight(falloff, sqrt(nearestSquared) / radiusWorld)
if (weight > 0f) {
influences[vertexIndex] = ProportionalInfluence(weight, nearestCovered)
}
}
}
return influences
}
/**
* The proportional weight map for one mesh - [proportionalInfluences] reduced to the weights, for
* callers that need no nearest-covered identity.
*
* @param FloatArray positions The interleaved vertex positions the distances are measured in.
* @param Set<Int> coveredIndices The vertices the selection covers (excluded from the map).
* @param Float radiusWorld The influence radius, in the positions' units.
* @param ProportionalFalloff falloff The falloff curve shaping the weights.
* @return Map<Int, Float> Vertex index to weight, for every influenced unselected vertex.
*/
fun proportionalWeights(
positions: FloatArray,
coveredIndices: Set<Int>,
radiusWorld: Float,
falloff: ProportionalFalloff,
): Map<Int, Float> = proportionalInfluences(positions, coveredIndices, radiusWorld, falloff).mapValues { entry -> entry.value.weight }
/**
* The CONNECTED-ONLY proportional influence map for one mesh: like [proportionalInfluences], but
* distance is geodesic - the shortest path along mesh edges (euclidean edge lengths) from the covered
* set - so influence flows through the surface and never leaps a gap to nearby-but-unconnected
* geometry (Blender's Connected Only). A vertex unreachable within [radiusWorld] takes no weight,
* and each influenced vertex reports the covered vertex its shortest path started from (the island
* ownership key, exactly like the straight-line variant).
*
* Dijkstra over the vertex adjacency, seeded at every covered vertex, with an early stop past the
* radius. The frontier scan is O(V) per settled vertex (no priority queue in common Kotlin) - fine
* at rigging mesh sizes, and the radius bound keeps the settled set local in practice.
*
* @param FloatArray positions The interleaved vertex positions (edge lengths measured here).
* @param Set<Int> coveredIndices The vertices the selection covers (the geodesic sources).
* @param Float radiusWorld The influence radius, along edges, in the positions' units.
* @param ProportionalFalloff falloff The falloff curve shaping the weights.
* @param IntArray triangleIndices The mesh's triangle vertex indices (the edge graph).
* @return Map<Int, ProportionalInfluence> Vertex index to influence, for every reachable vertex.
*/
fun proportionalInfluencesConnected(
positions: FloatArray,
coveredIndices: Set<Int>,
radiusWorld: Float,
falloff: ProportionalFalloff,
triangleIndices: IntArray,
): Map<Int, ProportionalInfluence> {
if (coveredIndices.isEmpty() || radiusWorld <= 0f) {
return emptyMap()
}
val vertexCount = positions.size / 2
val adjacency = MeshTopology.buildVertexAdjacency(vertexCount, triangleIndices)
val distance = FloatArray(vertexCount) { Float.MAX_VALUE }
val sourceCovered = IntArray(vertexCount) { -1 }
val settled = BooleanArray(vertexCount)
for (coveredIndex in coveredIndices) {
if (coveredIndex in 0 until vertexCount) {
distance[coveredIndex] = 0f
sourceCovered[coveredIndex] = coveredIndex
}
}
while (true) {
// The unsettled frontier vertex nearest the covered set; past the radius nothing can gain weight.
var frontier = -1
var frontierDistance = Float.MAX_VALUE
for (vertexIndex in 0 until vertexCount) {
if (!settled[vertexIndex] && distance[vertexIndex] < frontierDistance) {
frontierDistance = distance[vertexIndex]
frontier = vertexIndex
}
}
if (frontier < 0 || frontierDistance >= radiusWorld) {
break
}
settled[frontier] = true
for (neighbor in adjacency[frontier]) {
if (settled[neighbor]) {
continue
}
val deltaX = positions[neighbor * 2] - positions[frontier * 2]
val deltaY = positions[neighbor * 2 + 1] - positions[frontier * 2 + 1]
val candidate = frontierDistance + sqrt(deltaX * deltaX + deltaY * deltaY)
if (candidate < distance[neighbor]) {
distance[neighbor] = candidate
sourceCovered[neighbor] = sourceCovered[frontier]
}
}
}
val influences = LinkedHashMap<Int, ProportionalInfluence>()
for (vertexIndex in 0 until vertexCount) {
if (vertexIndex in coveredIndices || sourceCovered[vertexIndex] < 0 || distance[vertexIndex] >= radiusWorld) {
continue
}
val weight = proportionalWeight(falloff, distance[vertexIndex] / radiusWorld)
if (weight > 0f) {
influences[vertexIndex] = ProportionalInfluence(weight, sourceCovered[vertexIndex])
}
}
return influences
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,10 @@
package org.umamo.edit
/**
* Where a row drop lands relative to the target row: before it, into it (nesting inside a container
* row, when the panel's rules allow it), or after it. Shared by every row-dragging panel (outliner,
* parameters) so their drop rules and indicators speak one vocabulary.
*
* 行ドロップが対象行のどこに落ちるか(前・中・後)。行ドラッグを持つ各パネルで共有される。
*/
enum class RowDropBand { Before, Into, After }
@@ -0,0 +1,241 @@
package org.umamo.edit
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
/**
* A selectable rig entity, addressed by its typed id. A closed taxonomy (part, drawable, or deformer)
* so a `when` over a selection is exhaustive; adding a fourth selectable kind becomes a compile error
* until handled everywhere. This is object-mode selection — whole entities, not their interior mesh
* vertices or deformer control points (those belong to Edit mode, see [EditorMode]).
*/
sealed interface SelectionTarget {
/** An organizational tree part. */
data class Part(val id: PartId) : SelectionTarget
/** A textured drawable mesh. */
data class Drawable(val id: DrawableId) : SelectionTarget
/** A warp or rotation deformer. */
data class Deformer(val id: DeformerId) : SelectionTarget
}
/**
* An immutable object-mode selection: the set of selected targets plus the active (primary) one — the
* last target the user added, which the Inspector features when several are selected and which anchors
* future range operations. The active target is always a member of [targets], or null when the
* selection is empty.
*/
data class Selection(
/** The selected targets, empty when nothing is selected. */
val targets: Set<SelectionTarget> = emptySet(),
/** The primary target (last added), or null when [targets] is empty. */
val active: SelectionTarget? = null,
) {
/** True when nothing is selected. */
val isEmpty: Boolean get() = targets.isEmpty()
/** The number of selected targets. */
val size: Int get() = targets.size
/**
* Reports whether the given target is part of this selection.
*
* @param SelectionTarget target The target to test.
* @return Boolean True when [target] is selected.
*/
operator fun contains(target: SelectionTarget): Boolean = target in targets
}
/**
* The parameters currently targeted for keyform authoring: the selected set plus the active (primary) one.
*
* Separate from [Selection] because it addresses a different axis of the document - you pick WHICH OBJECT
* to key from the object selection, and WHICH PARAMETER to key it on from here, and the two move
* independently. Held on the session rather than a panel's view state because it is shared: a keyform
* sheet in one area follows the parameter chosen in a parameters panel in another.
*/
data class ParameterSelection(
/** The selected parameters, empty when none is targeted. */
val ids: Set<ParameterId> = emptySet(),
/** The primary parameter (last added), or null when [ids] is empty. */
val active: ParameterId? = null,
) {
/** True when no parameter is targeted. */
val isEmpty: Boolean get() = ids.isEmpty()
/**
* Reports whether the given parameter is selected.
*
* @param ParameterId id The parameter to test.
* @return Boolean True when [id] is selected.
*/
operator fun contains(id: ParameterId): Boolean = id in ids
companion object {
/**
* A selection of just [id], the plain-click result.
*
* @param ParameterId id The sole parameter to select.
* @return ParameterSelection A selection holding only [id], with it active.
*/
fun of(id: ParameterId): ParameterSelection = ParameterSelection(setOf(id), id)
}
/**
* This selection with [id] toggled (a Shift or primary-modifier click, matching [SelectionOps.toggle]).
*
* @param ParameterId id The parameter to toggle.
* @return ParameterSelection The resulting selection.
*/
fun toggled(id: ParameterId): ParameterSelection =
if (id in ids) {
val remaining = ids - id
ParameterSelection(remaining, remaining.lastOrNull())
} else {
ParameterSelection(ids + id, id)
}
/**
* This selection with every parameter not in [surviving] dropped - applied after a parameter is
* deleted, so the target can never dangle on an id the model no longer has.
*
* @param Set<ParameterId> surviving The parameter ids still present in the model.
* @return ParameterSelection The pruned selection, or this when nothing was dropped.
*/
fun prunedTo(surviving: Set<ParameterId>): ParameterSelection {
val kept = ids intersect surviving
return if (kept.size == ids.size) this else ParameterSelection(kept, active?.takeIf { it in kept } ?: kept.lastOrNull())
}
}
/**
* Pure transformations over a [Selection], one per selection gesture. Each returns a new immutable
* [Selection] and never mutates its input, so they are trivially unit-testable without Compose or a
* render context. The active target is maintained per the [Selection] invariant: it is always a member
* of the result's targets, or null when the result is empty.
*/
object SelectionOps {
/**
* Replaces the whole selection with a single target (a plain click).
*
* @param SelectionTarget target The sole target to select.
* @return Selection A selection holding only [target], with it active.
*/
fun replace(target: SelectionTarget): Selection = Selection(setOf(target), target)
/**
* Toggles a target's membership (a Shift or Ctrl / Cmd click, Blender-style): removes it when
* present, adds it otherwise. When added it becomes active; when removed the active target falls
* back to another remaining member, or null if the selection became empty.
*
* @param Selection selection The selection to modify.
* @param SelectionTarget target The target to toggle.
* @return Selection The resulting selection.
*/
fun toggle(selection: Selection, target: SelectionTarget): Selection =
if (target in selection.targets) {
val remaining = selection.targets - target
Selection(remaining, remaining.lastOrNull())
} else {
Selection(selection.targets + target, target)
}
/**
* Adds a target without removing anything (an additive gesture with no current default binding),
* making it active. Adding a target already present simply promotes it to active.
*
* @param Selection selection The selection to extend.
* @param SelectionTarget target The target to add.
* @return Selection The extended selection.
*/
fun add(selection: Selection, target: SelectionTarget): Selection = Selection(selection.targets + target, target)
/**
* Clears the selection.
*
* @return Selection An empty selection.
*/
fun clear(): Selection = Selection()
/**
* Every selectable entity in the model as a target set, in parts-then-deformers-then-drawables order.
* A locked entity (isSelectable == false) is excluded, matching the pointer picker. The full set
* [selectAll] fills and [invert] complements against.
*
* @param PuppetModel model The rig to enumerate.
* @return Set<SelectionTarget> Every selectable target.
*/
private fun allSelectableTargets(model: PuppetModel): Set<SelectionTarget> {
val targets = LinkedHashSet<SelectionTarget>()
for (part in model.parts) {
if (part.isSelectable) {
targets.add(SelectionTarget.Part(part.id))
}
}
for (deformer in model.deformers) {
if (deformer.isSelectable) {
targets.add(SelectionTarget.Deformer(deformer.id))
}
}
for (drawable in model.drawables) {
if (drawable.isSelectable) {
targets.add(SelectionTarget.Drawable(drawable.id))
}
}
return targets
}
/**
* Selects every selectable entity in the model (Blender's Select All in object mode). Keeps the current
* active target (it is necessarily still selected); with none, the last enumerated target becomes active.
*
* @param Selection selection The current selection (its active target is preserved when possible).
* @param PuppetModel model The rig whose entities to select.
* @return Selection The selection holding every selectable target.
*/
fun selectAll(selection: Selection, model: PuppetModel): Selection {
val allTargets = allSelectableTargets(model)
val active = selection.active?.takeIf { target -> target in allTargets } ?: allTargets.lastOrNull()
return Selection(allTargets, active)
}
/**
* Inverts the object selection (Blender's Ctrl+I): every selectable entity not currently selected
* becomes selected and vice versa. The active target is kept only when it survives the inversion, which
* in practice drops it (a selected active target is deselected by the inversion).
*
* @param Selection selection The selection to invert.
* @param PuppetModel model The rig whose entities define the domain.
* @return Selection The inverted selection.
*/
fun invert(selection: Selection, model: PuppetModel): Selection {
val inverted = allSelectableTargets(model) - selection.targets
return Selection(inverted, selection.active?.takeIf { target -> target in inverted })
}
/**
* Expands every selected target to its outliner subtree (the Select Hierarchy context action): a
* part adds its descendant parts and their drawables, a deformer its descendant deformers, a
* drawable just itself - exactly the rows the outliner shows beneath each (see
* [PuppetModel.subtreeTargets]). The active target is kept (still selected); an empty selection
* stays empty.
*
* @param Selection selection The selection whose targets to expand.
* @param PuppetModel model The rig the subtrees are read from.
* @return Selection The selection with every subtree included.
*/
fun selectHierarchy(selection: Selection, model: PuppetModel): Selection {
if (selection.isEmpty) {
return selection
}
val expanded = LinkedHashSet<SelectionTarget>()
for (target in selection.targets) {
expanded.addAll(model.subtreeTargets(target))
}
return Selection(expanded, selection.active ?: expanded.lastOrNull())
}
}
@@ -0,0 +1,524 @@
package org.umamo.edit
import org.umamo.runtime.model.AlphaBlendMode
import org.umamo.runtime.model.AtlasComposition
import org.umamo.runtime.model.AtlasPage
import org.umamo.runtime.model.AtlasPlacement
import org.umamo.runtime.model.AtlasTileId
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.ColorRgb
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.PartComposite
import org.umamo.runtime.model.PartGroupMode
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.RuntimeTarget
import org.umamo.runtime.model.SourceLayerRef
/*
* Scalar property edits on an EditorSession, mostly driven by the Properties panel's editable controls
* (the atlas edits at the end of the file are not: commitAtlasRepack is driven by the atlas repack
* flow, setAtlasPlacements by the UV editor's placement gizmo, and setAtlasPins by its pin commands). Each
* applies one field change as a single undo step via mutate, dispatching the typed Change plus its
* PuppetModelEdits transform, and short-circuits to nothing on a no-op (the builder returns the same
* model instance). These are the write half of the Properties panel: a checkbox / dropdown / numeric
* field commit calls exactly one of these, and a registry command flipping the same document field
* (document.toggleSourceArtworkDisplay) goes through the same entry point rather than mutating in
* parallel, so both routes produce the one identical undo step. Continuous numeric scrubbing previews
* in the widget and commits one of these on release, so there is no per-frame mutation and no
* history-side coalescing (the same single-commit-per-gesture granularity the parameter scrub documents
* in ParameterChange.SetValue).
*/
/**
* Sets drawable [id]'s color blend mode as one undo step.
*
* @param DrawableId id The drawable to retarget.
* @param BlendMode mode The new blend mode.
*/
fun EditorSession.setDrawableBlendMode(id: DrawableId, mode: BlendMode) {
mutate(DrawableChange.SetBlendMode(id, mode)) { model -> model.withDrawableBlendMode(id, mode) }
}
/**
* Sets drawable [id]'s alpha blend mode as one undo step.
*
* @param DrawableId id The drawable to retarget.
* @param AlphaBlendMode mode The new alpha blend mode.
*/
fun EditorSession.setDrawableAlphaBlendMode(id: DrawableId, mode: AlphaBlendMode) {
mutate(DrawableChange.SetAlphaBlendMode(id, mode)) { model -> model.withDrawableAlphaBlendMode(id, mode) }
}
/**
* Sets drawable [id]'s back-face culling as one undo step.
*
* @param DrawableId id The drawable to retarget.
* @param Boolean culling The new culling state.
*/
fun EditorSession.setDrawableCulling(id: DrawableId, culling: Boolean) {
mutate(DrawableChange.SetCulling(id, culling)) { model -> model.withDrawableCulling(id, culling) }
}
/**
* Sets drawable [id]'s mask-inversion flag as one undo step.
*
* @param DrawableId id The drawable to retarget.
* @param Boolean invert The new inverted-mask state.
*/
fun EditorSession.setDrawableInvertMask(id: DrawableId, invert: Boolean) {
mutate(DrawableChange.SetInvertMask(id, invert)) { model -> model.withDrawableInvertMask(id, invert) }
}
/**
* Sets drawable [id]'s static opacity as one undo step.
*
* @param DrawableId id The drawable to retarget.
* @param Float opacity The new opacity.
*/
fun EditorSession.setDrawableOpacity(id: DrawableId, opacity: Float) {
mutate(DrawableChange.SetOpacity(id, opacity)) { model -> model.withDrawableOpacity(id, opacity) }
}
/**
* Sets drawable [id]'s static draw order as one undo step.
*
* @param DrawableId id The drawable to retarget.
* @param Float drawOrder The new draw order.
*/
fun EditorSession.setDrawableDrawOrder(id: DrawableId, drawOrder: Float) {
mutate(DrawableChange.SetDrawOrder(id, drawOrder)) { model -> model.withDrawableDrawOrder(id, drawOrder) }
}
/**
* Sets deformer [id]'s static opacity as one undo step. Cascades onto every drawable beneath it.
*
* @param DeformerId id The deformer to retarget.
* @param Float opacity The new opacity.
*/
fun EditorSession.setDeformerOpacity(id: DeformerId, opacity: Float) {
mutate(DeformerChange.SetOpacity(id, opacity)) { model -> model.withDeformerOpacity(id, opacity) }
}
/**
* Sets deformer [id]'s static multiply color as one undo step. Cascades onto every drawable beneath it.
*
* @param DeformerId id The deformer to retint.
* @param ColorRgb color The new multiply color.
*/
fun EditorSession.setDeformerMultiplyColor(id: DeformerId, color: ColorRgb) {
mutate(DeformerChange.SetMultiplyColor(id, color)) { model -> model.withDeformerMultiplyColor(id, color) }
}
/**
* Sets deformer [id]'s static screen color as one undo step. Cascades onto every drawable beneath it.
*
* @param DeformerId id The deformer to retint.
* @param ColorRgb color The new screen color.
*/
fun EditorSession.setDeformerScreenColor(id: DeformerId, color: ColorRgb) {
mutate(DeformerChange.SetScreenColor(id, color)) { model -> model.withDeformerScreenColor(id, color) }
}
/**
* Sets rotation deformer [id]'s static horizontal reflection as one undo step.
*
* @param DeformerId id The deformer to retarget.
* @param Boolean flip The new reflection state.
*/
fun EditorSession.setDeformerFlipX(id: DeformerId, flip: Boolean) {
mutate(DeformerChange.SetFlipX(id, flip)) { model -> model.withDeformerFlipX(id, flip) }
}
/**
* Sets rotation deformer [id]'s static vertical reflection as one undo step.
*
* @param DeformerId id The deformer to retarget.
* @param Boolean flip The new reflection state.
*/
fun EditorSession.setDeformerFlipY(id: DeformerId, flip: Boolean) {
mutate(DeformerChange.SetFlipY(id, flip)) { model -> model.withDeformerFlipY(id, flip) }
}
/**
* Sets drawable [id]'s multiply color (the static value) as one undo step.
*
* @param DrawableId id The drawable to retint.
* @param ColorRgb color The new multiply color.
*/
fun EditorSession.setDrawableMultiplyColor(id: DrawableId, color: ColorRgb) {
mutate(DrawableChange.SetMultiplyColor(id, color)) { model -> model.withDrawableMultiplyColor(id, color) }
}
/**
* Sets drawable [id]'s screen color (the static value) as one undo step.
*
* @param DrawableId id The drawable to retint.
* @param ColorRgb color The new screen color.
*/
fun EditorSession.setDrawableScreenColor(id: DrawableId, color: ColorRgb) {
mutate(DrawableChange.SetScreenColor(id, color)) { model -> model.withDrawableScreenColor(id, color) }
}
/**
* Binds drawable [id] to the deformer that deforms it (null unbinds) as one undo step.
*
* @param DrawableId id The drawable to rebind.
* @param DeformerId? parentDeformerId The deformer that deforms it, or null to unbind.
*/
fun EditorSession.setDrawableParentDeformer(id: DrawableId, parentDeformerId: DeformerId?) {
mutate(DrawableChange.SetParentDeformer(id, parentDeformerId)) { model ->
model.withDrawableParentDeformer(id, parentDeformerId)
}
}
/**
* Replaces drawable [id]'s clip-mask list as one undo step, so adding or removing a single mask is one
* step.
*
* @param DrawableId id The drawable whose masks change.
* @param List maskedBy The drawables whose alpha now clips it.
*/
fun EditorSession.setDrawableMaskedBy(id: DrawableId, maskedBy: List<DrawableId>) {
mutate(DrawableChange.SetMaskedBy(id, maskedBy)) { model -> model.withDrawableMaskedBy(id, maskedBy) }
}
/**
* Binds deformer [id] to the organizational part that owns it (null clears it) as one undo step.
*
* @param DeformerId id The deformer to rebind.
* @param PartId? partId The part that owns it, or null to clear.
*/
fun EditorSession.setDeformerPart(id: DeformerId, partId: PartId?) {
mutate(DeformerChange.SetPart(id, partId)) { model -> model.withDeformerPart(id, partId) }
}
/**
* Sets rotation deformer [id]'s base angle as one undo step. A no-op on a warp deformer (it has no base
* angle), so the commit short-circuits.
*
* @param DeformerId id The deformer to retarget.
* @param Float angle The new base angle in degrees.
*/
fun EditorSession.setDeformerBaseAngle(id: DeformerId, angle: Float) {
mutate(DeformerChange.SetBaseAngle(id, angle)) { model -> model.withDeformerBaseAngle(id, angle) }
}
/**
* Sets warp deformer [id]'s FFD interpolation mode as one undo step. A no-op on a rotation deformer (it
* has no lattice), so the commit short-circuits.
*
* @param DeformerId id The deformer to retarget.
* @param Boolean quad The new quad-transform state.
*/
fun EditorSession.setDeformerQuadTransform(id: DeformerId, quad: Boolean) {
mutate(DeformerChange.SetQuadTransform(id, quad)) { model -> model.withDeformerQuadTransform(id, quad) }
}
/**
* Sets warp deformer [id]'s conversion-division grid as one undo step, resampling every lattice keyform
* so the art stays put. A no-op on a rotation deformer / missing lattice (see [withWarpDeformerGrid]).
*
* @param DeformerId id The deformer to retarget.
* @param Int rows The new conversion divisions vertically.
* @param Int columns The new conversion divisions horizontally.
*/
fun EditorSession.setDeformerWarpGrid(id: DeformerId, rows: Int, columns: Int) {
mutate(DeformerChange.SetGrid(id, rows, columns)) { model -> model.withWarpDeformerGrid(id, rows, columns) }
}
/**
* Sets part [id]'s guide-image (sketch) flag as one undo step.
*
* @param PartId id The part to retarget.
* @param Boolean sketch The new sketch state.
*/
fun EditorSession.setPartSketch(id: PartId, sketch: Boolean) {
mutate(PartChange.SetSketch(id, sketch)) { model -> model.withPartSketch(id, sketch) }
}
/**
* Sets part [id]'s own draw order as one undo step.
*
* @param PartId id The part to retarget.
* @param Int order The new draw order.
*/
fun EditorSession.setPartDrawOrder(id: PartId, order: Int) {
mutate(PartChange.SetDrawOrder(id, order)) { model -> model.withPartDrawOrder(id, order) }
}
/**
* Sets part [id]'s rendering group mode as one undo step. The [mode] carries the whole value, so a mode
* switch and any Isolated-composite sub-field edit both flow through here.
*
* @param PartId id The part to retarget.
* @param PartGroupMode mode The new group mode.
*/
fun EditorSession.setPartGroupMode(id: PartId, mode: PartGroupMode) {
mutate(PartChange.SetGroupMode(id, mode)) { model -> model.withPartGroupMode(id, mode) }
}
/**
* Sets part [id]'s latent compositing settings as one undo step. Stored independent of the group mode,
* so an isolated part's composite survives leaving and re-entering Isolated; applied only while Isolated.
*
* @param PartId id The part to retarget.
* @param PartComposite composite The new composite settings.
*/
fun EditorSession.setPartComposite(id: PartId, composite: PartComposite) {
mutate(PartChange.SetComposite(id, composite)) { model -> model.withPartComposite(id, composite) }
}
/**
* Sets the document canvas size (world units) as one undo step.
*
* @param Float width The new canvas width.
* @param Float height The new canvas height.
*/
fun EditorSession.setCanvasSize(width: Float, height: Float) {
mutate(DocumentChange.SetCanvasSize(width, height)) { model -> model.withCanvasSize(width, height) }
}
/**
* Sets the world origin (world space) as one undo step.
*
* @param Float x The new world-origin x.
* @param Float z The new world-origin z (up).
*/
fun EditorSession.setWorldOrigin(x: Float, z: Float) {
mutate(DocumentChange.SetWorldOrigin(x, z)) { model -> model.withWorldOrigin(x, z) }
}
/**
* Sets the document's runtime-compatibility target as one undo step.
*
* @param RuntimeTarget target The new runtime target.
*/
fun EditorSession.setRuntimeTarget(target: RuntimeTarget) {
mutate(DocumentChange.SetRuntimeTarget(target)) { model -> model.withRuntimeTarget(target) }
}
/**
* Switches the puppet between displaying from its source artwork and from the packed atlas, as one
* undo step.
*
* A display choice that is document content rather than an app preference: the source formats author
* it, so it round-trips and it marks the document dirty like any other authored value.
*
* @param Boolean fromSourceLayers True to display from the source artwork, false from the atlas.
*/
fun EditorSession.setSourceLayerDisplay(fromSourceLayers: Boolean) {
mutate(DocumentChange.SetSourceLayerDisplay(fromSourceLayers)) { model -> model.withSourceLayerDisplay(fromSourceLayers) }
}
/**
* Packs one piece of source art at [placement] as a single undo step, re-mapping every drawable over it
* so the art keeps meaning what it did - [setAtlasPlacements] over one tile.
*
* @param AtlasTileId tileId The tile to place.
* @param AtlasPlacement? placement Where its art now sits, or null to mark it unpacked.
*/
fun EditorSession.setAtlasPlacement(tileId: AtlasTileId, placement: AtlasPlacement?) {
setAtlasPlacements(mapOf(tileId to placement))
}
/**
* Packs several pieces of source art at once as ONE undo step - a placement gesture over a
* multi-tile selection is one edit, not one step per tile - re-mapping every drawable over them so
* the art keeps meaning what it did.
*
* The pages' PIXELS are session state derived from the model, not part of it: the session's page
* resolver composes the pages the new placements denote once this commit publishes (and re-composes
* them on undo), so nothing here touches a pixel and no snapshot ever carries one.
*
* @param Map placementByTile Each tile's new placement, keyed by tile, null to mark it unpacked.
* @param MeshOperatorKind? kind The placement operator that produced the move (it names the
* step), or null for a placement written by no gesture.
*/
fun EditorSession.setAtlasPlacements(
placementByTile: Map<AtlasTileId, AtlasPlacement?>,
kind: MeshOperatorKind? = null,
) {
mutate(DocumentChange.SetAtlasPlacement(placementByTile.keys.toList(), kind)) { model -> model.withAtlasPlacements(placementByTile) }
}
/**
* Pins or unpins the placed tiles among [tileIds] as one undo step, so a repack keeps (or may move)
* them - withAtlasPins under the one history push a pin command or checkbox should be.
*
* @param Collection<AtlasTileId> tileIds The tiles to pin or unpin.
* @param Boolean pinned True to pin, false to unpin.
*/
fun EditorSession.setAtlasPins(tileIds: Collection<AtlasTileId>, pinned: Boolean) {
mutate(DocumentChange.SetAtlasPin(tileIds.toList(), pinned)) { model -> model.withAtlasPins(tileIds, pinned) }
}
/**
* Rebinds one tile to a layer of a listed artwork file, or unbinds it, as one undo step -
* withTileSource under the one history push a relink should be.
*
* @param AtlasTileId tileId The tile to rebind.
* @param SourceLayerRef? source The new binding, or null to unbind.
*/
fun EditorSession.setTileSource(tileId: AtlasTileId, source: SourceLayerRef?) {
setTileSources(listOf(tileId), source)
}
/**
* Rebinds every tile in [tileIds] to one layer of a listed artwork file, or unbinds them all, as ONE
* undo step - what a review row's accepted proposal lands through when the layer's art cannot be
* pulled, so the tiles bound to a lost key move together. A tile the model refuses (unknown, or a
* binding to an unlisted file) is left as it is; a call that changes no tile pushes nothing.
*
* @param Collection<AtlasTileId> tileIds The tiles to rebind, in any order; empty pushes nothing.
* @param SourceLayerRef? source The new binding, or null to unbind.
*/
fun EditorSession.setTileSources(tileIds: Collection<AtlasTileId>, source: SourceLayerRef?) {
val first = tileIds.firstOrNull() ?: return
mutate(DocumentChange.SetTileSource(first, bound = source != null)) { model ->
tileIds.fold(model) { current, tileId -> current.withTileSource(tileId, source) }
}
}
/**
* Removes the tile [tileId] from the atlas as one undo step, when no drawable samples it; a tile some
* drawable still samples, or one the model lacks, pushes nothing. With [ignoreLayer] the layer the tile
* was bound to is marked ignored in the same step (the import setting's choice), so the next reload
* does not mint the art back; an unbound tile has no layer to mark, and a layer another tile still binds
* is left unmarked, since the reload matches it by key.
*
* @param AtlasTileId tileId The tile to remove.
* @param Boolean ignoreLayer Whether to keep the tile's layer out of the rig from now on.
*/
fun EditorSession.deleteTile(tileId: AtlasTileId, ignoreLayer: Boolean = false) {
val current = model.value
val binding = current.atlas.tileById[tileId]?.source
val shared =
binding != null &&
current.atlas.tiles.any { other -> other.id != tileId && other.source?.sourceId == binding.sourceId && other.source?.layerKey == binding.layerKey }
val marks = ignoreLayer && binding != null && !shared
mutate(DocumentChange.DeleteTile(tileId, ignoredLayer = marks)) { before ->
val deleted = before.withTileDeleted(tileId)
// marks already carries binding != null, and the compiler smart-casts through it.
if (marks && deleted !== before) {
deleted.withLayerIgnored(binding.sourceId, binding.layerKey, ignored = true)
} else {
deleted
}
}
}
/**
* Marks or clears the ignore on one inventory row as one undo step - withLayerIgnored under the one
* history push the Sources row's toggle should be; a row the model refuses (unknown, or a key some tile
* binds) pushes nothing.
*
* @param SourceLayerRef ref The file and layer key.
* @param Boolean ignored True to keep the layer out of the rig, false to let a reload mint it again.
*/
fun EditorSession.setLayerIgnored(ref: SourceLayerRef, ignored: Boolean) {
mutate(DocumentChange.SetLayerIgnored(ref.sourceId, ref.layerKey, ignored)) { before -> before.withLayerIgnored(ref.sourceId, ref.layerKey, ignored) }
}
/**
* Commits a model that already carries an artwork file's additions and their pack as ONE undo step.
*
* The orchestrator builds [added] off the UI thread (the bridge, the pack around the existing art,
* the re-derivation) from the model current when it started, checks nothing moved underneath it, and
* lands it here; the page pixels are session state it swaps in beside this commit, which is why the
* committed model comes back for the resolver's pre-warm.
*
* @param String sourceName The added file's display name, for the history label.
* @param Int drawableCount How many drawables it added.
* @param PuppetModel added The model with the additions and their pack applied.
* @return PuppetModel The committed model.
*/
fun EditorSession.commitArtworkAdded(sourceName: String, drawableCount: Int, added: PuppetModel): PuppetModel {
mutate(DocumentChange.AddArtwork(sourceName, drawableCount)) { added }
return added
}
/**
* Commits a model that already carries a reload of the document's artwork files and its pack as ONE
* undo step - the same contract as [commitArtworkAdded]: built off the UI thread from the model
* current when the reload started, checked against it, landed here, the page pixels swapped in
* beside it and the committed model returned for the resolver's pre-warm.
*
* @param DocumentChange.ReloadArtwork change The step's counts, for the history label.
* @param PuppetModel reloaded The model with the reload and its pack applied.
* @return PuppetModel The committed model.
*/
fun EditorSession.commitArtworkReloaded(change: DocumentChange.ReloadArtwork, reloaded: PuppetModel): PuppetModel {
mutate(change) { reloaded }
return reloaded
}
/**
* Commits a model that already carries one tile's rebinding with the layer's art pulled in, and its
* pack, as ONE undo step; see [commitArtworkAdded] for the contract.
*
* @param AtlasTileId tileId The rebound tile's id before the replacement.
* @param PuppetModel relinked The model with the relink and its pack applied.
* @return PuppetModel The committed model.
*/
fun EditorSession.commitArtworkRelinked(tileId: AtlasTileId, relinked: PuppetModel): PuppetModel {
mutate(DocumentChange.RelinkArtwork(tileId)) { relinked }
return relinked
}
/**
* Commits a model that already carries the matcher's accepted rebindings and their pack as ONE undo
* step; see [commitArtworkAdded] for the contract.
*
* @param DocumentChange.MatchArtwork change The step's counts, for the history label.
* @param PuppetModel matched The model with the rebindings and their pack applied.
* @return PuppetModel The committed model.
*/
fun EditorSession.commitArtworkMatched(change: DocumentChange.MatchArtwork, matched: PuppetModel): PuppetModel {
mutate(change) { matched }
return matched
}
/**
* Commits a model that already carries one record's replacement, the reload it resolved by key, and
* its pack as ONE undo step; see [commitArtworkAdded] for the contract.
*
* @param DocumentChange.ReplaceArtwork change The step's counts, for the history label.
* @param PuppetModel replaced The model with the replacement and its pack applied.
* @return PuppetModel The committed model.
*/
fun EditorSession.commitArtworkReplaced(change: DocumentChange.ReplaceArtwork, replaced: PuppetModel): PuppetModel {
mutate(change) { replaced }
return replaced
}
/**
* Repacks the whole atlas as a single undo step: the new page inventory and every tile's placement
* land together, with every bound drawable's coordinates re-derived over them - withAtlasRepack's
* one-pass edit under the one history push a repack should be.
*
* The page PIXELS are session state the caller swaps in beside this commit, which is why the
* committed model comes back: the orchestrator pre-warms the session's page resolver with the SAME
* atlas instance this publishes (the resolver memoizes by identity), so the commit resolves its
* pages by cache hit - and undo re-resolves them the same way.
*
* @param List pages The new page inventory.
* @param Map placementsByTile Every tile's new placement, keyed by tile, null for unpacked.
* @param AtlasComposition composition The trim and extrusion policy the pack composed under.
* @return PuppetModel? The committed model, or null when the repack restated the atlas exactly.
*/
fun EditorSession.commitAtlasRepack(
pages: List<AtlasPage>,
placementsByTile: Map<AtlasTileId, AtlasPlacement?>,
composition: AtlasComposition = model.value.atlas.composition,
): PuppetModel? {
val current = model.value
val repacked = current.withAtlasRepack(pages, placementsByTile, composition)
if (repacked === current) {
return null
}
val placedCount = placementsByTile.count { entry -> entry.value != null }
mutate(DocumentChange.RepackAtlas(placedCount, pages.size)) { repacked }
return repacked
}
@@ -0,0 +1,237 @@
package org.umamo.edit
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
/**
* The session's request buses: fire-and-forget signals from command handlers to the area that
* executes them - a viewport or UV editor overlay, or the UV editor space itself. Every one exists
* for the same reason - the operation needs something only the receiving area has (the pointer
* position, the projected geometry, the in-flight working positions, the area's own view state), so
* the session cannot execute it directly; it signals here and the observing collector executes.
* Pure plumbing with no other session state involved, hence a separate collaborator; [EditorSession]
* exposes each flow and request method unchanged.
*/
internal class SessionRequestBus {
private val mutableSnapRequests = MutableSharedFlow<SnapRequest>(extraBufferCapacity = 4)
/** The geometry-dependent snap requests (see [EditorSession.snapRequests]). */
val snapRequests: SharedFlow<SnapRequest> = mutableSnapRequests.asSharedFlow()
private val mutableSelectLinkedRequests = MutableSharedFlow<SelectLinkedRequest>(extraBufferCapacity = 4)
/** The Select Linked requests (see [EditorSession.selectLinkedRequests]). */
val selectLinkedRequests: SharedFlow<SelectLinkedRequest> = mutableSelectLinkedRequests.asSharedFlow()
private val mutableUvSnapRequests = MutableSharedFlow<UvSnapRequest>(extraBufferCapacity = 4)
/** The UV editor snap requests (see [EditorSession.uvSnapRequests]). */
val uvSnapRequests: SharedFlow<UvSnapRequest> = mutableUvSnapRequests.asSharedFlow()
private val mutableUvMirrorRequests = MutableSharedFlow<UvMirrorRequest>(extraBufferCapacity = 4)
/** The UV editor mirror requests (see [EditorSession.uvMirrorRequests]). */
val uvMirrorRequests: SharedFlow<UvMirrorRequest> = mutableUvMirrorRequests.asSharedFlow()
private val mutableViewportMirrorRequests = MutableSharedFlow<ViewportMirrorRequest>(extraBufferCapacity = 4)
/** The viewport geometry mirror requests (see [EditorSession.viewportMirrorRequests]). */
val viewportMirrorRequests: SharedFlow<ViewportMirrorRequest> = mutableViewportMirrorRequests.asSharedFlow()
private val mutableUvPageRequests = MutableSharedFlow<UvPageRequest>(extraBufferCapacity = 4)
/** The UV editor page-switch requests (see [EditorSession.uvPageRequests]). */
val uvPageRequests: SharedFlow<UvPageRequest> = mutableUvPageRequests.asSharedFlow()
private val mutableSwitchObjectRequests = MutableSharedFlow<String?>(extraBufferCapacity = 1)
/** The Alt+Q edited-mesh switch requests, each carrying its executing area (see [EditorSession.switchObjectRequests]). */
val switchObjectRequests: SharedFlow<String?> = mutableSwitchObjectRequests.asSharedFlow()
private val mutableRipRequests = MutableSharedFlow<String?>(extraBufferCapacity = 1)
/** The rip-at-pointer requests, each carrying its executing area (see [EditorSession.ripRequests]). */
val ripRequests: SharedFlow<String?> = mutableRipRequests.asSharedFlow()
private val mutableMeshConfirm = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
/** The modal-gesture confirm requests (see [EditorSession.meshConfirmRequests]). */
val meshConfirmRequests: SharedFlow<Unit> = mutableMeshConfirm.asSharedFlow()
private val mutableMeshGestureCancel = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
/** The selection-gesture cancel requests (see [EditorSession.meshGestureCancelRequests]). */
val meshGestureCancelRequests: SharedFlow<Unit> = mutableMeshGestureCancel.asSharedFlow()
/**
* Requests a geometry-dependent snap.
*
* @param SnapRequest request The snap to perform plus the dispatch-time resolved area.
*/
fun requestSnap(request: SnapRequest) {
mutableSnapRequests.tryEmit(request)
}
/**
* Requests a Select Linked for one area's overlay to execute.
*
* @param SelectLinkedRequest request The flood variant plus the dispatch-time resolved area.
*/
fun requestSelectLinked(request: SelectLinkedRequest) {
mutableSelectLinkedRequests.tryEmit(request)
}
/**
* Requests a UV snap for one UV editor area's overlay to execute.
*
* @param UvSnapRequest request The snap operation plus the dispatch-time resolved area.
*/
fun requestUvSnap(request: UvSnapRequest) {
mutableUvSnapRequests.tryEmit(request)
}
/**
* Requests a mirror for one UV editor area's overlay to execute.
*
* @param UvMirrorRequest request The mirror axis plus the dispatch-time resolved area.
*/
fun requestUvMirror(request: UvMirrorRequest) {
mutableUvMirrorRequests.tryEmit(request)
}
/**
* Requests a viewport geometry mirror for one area's overlay to execute.
*
* @param ViewportMirrorRequest request The axis plus the dispatch-time resolved area.
*/
fun requestViewportMirror(request: ViewportMirrorRequest) {
mutableViewportMirrorRequests.tryEmit(request)
}
/**
* Requests a page switch for one UV editor area to execute.
*
* @param UvPageRequest request The page operation plus the dispatch-time resolved area.
*/
fun requestUvPage(request: UvPageRequest) {
mutableUvPageRequests.tryEmit(request)
}
/**
* Requests an Alt+Q edited-mesh switch for one area's overlay to execute.
*
* @param String? areaId The dispatch-time resolved viewport area, or null when the pointer is elsewhere.
*/
fun requestSwitchObjectUnderCursor(areaId: String?) {
mutableSwitchObjectRequests.tryEmit(areaId)
}
/**
* Requests a rip at the pointer for one area's overlay to execute.
*
* @param String? areaId The dispatch-time resolved viewport area, or null when the pointer is elsewhere.
*/
fun requestRip(areaId: String?) {
mutableRipRequests.tryEmit(areaId)
}
/** Requests that the gizmo overlay confirm the in-flight modal gesture. */
fun requestMeshConfirm() {
mutableMeshConfirm.tryEmit(Unit)
}
/** Requests that the gizmo overlay abandon any in-flight box / circle selection gesture. */
fun requestMeshGestureCancel() {
mutableMeshGestureCancel.tryEmit(Unit)
}
}
/**
* One Select Linked request: which flood variant, and which area's overlay executes it. The area is
* resolved ONCE at command dispatch (the hovered surface at that instant) and carried in the payload,
* so two collectors reading a volatile independently can never double- or zero-execute when the
* pointer crosses areas between resumptions.
*
* @property Boolean fromSelection True to flood from the whole selection (Ctrl+L), false from the cursor (L).
* @property String? areaId The area whose overlay executes, or null when no surface was ever touched
* (then no collector matches and the request is a clean no-op).
*/
data class SelectLinkedRequest(val fromSelection: Boolean, val areaId: String?)
/**
* One UV snap request: which operation, and which UV editor area's overlay executes it. The area is
* resolved ONCE at command dispatch (the hovered surface at that instant) and carried in the payload,
* exactly like [SelectLinkedRequest] - there is no area answer anywhere else for a collector to fall back
* on, so gating on this id is the whole mechanism.
*
* @property UvSnapKind kind The snap operation to perform.
* @property String? areaId The UV editor area whose overlay executes, or null when the hovered surface
* was not a UV editor (then no collector matches and the request is a clean no-op).
*/
data class UvSnapRequest(val kind: UvSnapKind, val areaId: String?)
/**
* One UV mirror / reverse-swap request for a UV editor overlay.
*
* Geometric Mirror U/V reflects about a pivot ([reverseSwap] false). Toolbar Reverse Positions
* pairwise-swaps (u, v) among selected verts ([reverseSwap] true).
*
* @property Boolean mirrorU True to mirror horizontally, false vertically (ignored when [reverseSwap]).
* @property String? areaId The UV editor area whose overlay executes, or null when not over a UV editor.
* @property Boolean reverseSwap When true, pairwise-swap UV positions instead of reflecting about a pivot.
*/
data class UvMirrorRequest(val mirrorU: Boolean, val areaId: String?, val reverseSwap: Boolean = false)
/**
* One viewport geometry mirror request: which axis, and which viewport area's overlay executes it.
*
* Edit-mode mesh verts, Object-mode drawables, and warp-lattice control points all need posed world
* geometry only the overlay has, so the command signals here the same way snaps do.
*
* @property Boolean mirrorHorizontal True to mirror left↔right (world X), false top↔bottom (world Y).
* @property String? areaId The viewport area whose overlay executes, or null when the pointer is not on a
* viewport (then no collector matches and the request is a clean no-op).
*/
data class ViewportMirrorRequest(val mirrorHorizontal: Boolean, val areaId: String?)
/**
* The page operations a UV editor area's texture selection understands: cycling pins the next or
* previous atlas page with wrap-around from the currently shown page, and FollowSelection clears the
* pin back to the auto-follow default. These retarget a VIEW (the receiving area's per-area page
* pin), never the model, which is why they ride the request bus rather than the Change pipeline.
*/
enum class UvPageKind {
NextPage,
PreviousPage,
FollowSelection,
}
/**
* One page-switch request: which operation, and which UV editor area executes it. The area is
* resolved ONCE at command dispatch (the hovered surface at that instant) and carried in the payload,
* exactly like [UvSnapRequest] - there is no area answer anywhere else for a collector to fall back
* on, so gating on this id is the whole mechanism.
*
* @property UvPageKind kind The page operation to perform.
* @property String? areaId The UV editor area that executes, or null when the hovered surface was not
* a UV editor (then no collector matches and the request is a clean no-op).
*/
data class UvPageRequest(val kind: UvPageKind, val areaId: String?)
/**
* One world-space snap request: which operation, and which viewport area's overlay executes it. The area
* is resolved ONCE at command dispatch (the hovered surface at that instant) and carried in the payload,
* exactly like [SelectLinkedRequest] and [UvSnapRequest].
*
* The handlers ignore the area - a snap acts on the model, not on one viewport - so its only job here is
* ELECTION: every open viewport composes a collector, and without an id in the payload each would have to
* read a shared volatile to decide whether it is the one, which can double- or zero-execute when the
* pointer crosses areas between resumptions.
*
* @property SnapKind kind The snap operation to perform.
* @property String? areaId The viewport area whose overlay executes, or null when the pointer is not on a
* viewport (then no collector matches and the request is a clean no-op).
*/
data class SnapRequest(val kind: SnapKind, val areaId: String?)
@@ -0,0 +1,204 @@
package org.umamo.edit
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
/*
* Target-aware convenience edits on an EditorSession: a single selectable entity (part/drawable/deformer)
* is toggled or renamed as one undo step, and the subtree variants (a Blender-style Shift+Click on an
* outliner restriction icon) flip a whole outliner subtree in one step. These dispatch the right
* Change + transform per target kind so call sites (the outliner's per-row eye and inline rename) stay a
* thin one-liner. The selection-wide visibility toggle stays separate (see withSelectionVisibility) —
* that one flips the whole selection.
*
* 対象1件(パーツ/描画/デフォーマ)を1段の取り消し単位で切り替え・改名するセッション補助。サブツリー版
* (Shift クリック)は配下全体を1段で切り替える。
*/
/**
* Toggles the visibility of one [target] as a single undo step, dispatching the part- or drawable-specific
* change and transform. A deformer has no visibility flag, so it is a no-op.
*
* @param SelectionTarget target The entity whose eyeball to flip.
*/
fun EditorSession.toggleVisibility(target: SelectionTarget) {
val newVisible = !model.value.visibilityOf(target)
when (target) {
is SelectionTarget.Part ->
mutate(PartChange.SetVisibility(target.id, newVisible)) { model -> model.withPartVisibility(target.id, newVisible) }
is SelectionTarget.Drawable ->
mutate(DrawableChange.SetVisibility(target.id, newVisible)) { model -> model.withDrawableVisibility(target.id, newVisible) }
is SelectionTarget.Deformer -> {
// Deformers have no visibility flag; nothing to toggle.
}
}
}
/**
* Renames one [target] to [newName] as a single undo step, dispatching the per-kind change and transform.
* A blank name (after trimming) is ignored, so an empty commit keeps the old name.
*
* @param SelectionTarget target The entity to rename.
* @param String newName The requested new name.
*/
fun EditorSession.rename(target: SelectionTarget, newName: String) {
val trimmed = newName.trim()
if (trimmed.isEmpty()) {
return
}
when (target) {
is SelectionTarget.Part -> mutate(PartChange.Rename(target.id, trimmed)) { model -> model.withPartName(target.id, trimmed) }
is SelectionTarget.Drawable -> mutate(DrawableChange.Rename(target.id, trimmed)) { model -> model.withDrawableName(target.id, trimmed) }
is SelectionTarget.Deformer -> mutate(DeformerChange.Rename(target.id, trimmed)) { model -> model.withDeformerName(target.id, trimmed) }
}
}
/**
* Whether [target] is viewport-selectable in [this] model. A missing entity reports true (selectable).
*
* @param SelectionTarget target The entity to query.
* @return Boolean The entity's selectable state.
*/
fun PuppetModel.selectableOf(target: SelectionTarget): Boolean =
when (target) {
is SelectionTarget.Part -> parts.firstOrNull { it.id == target.id }?.isSelectable ?: true
is SelectionTarget.Drawable -> drawables.firstOrNull { it.id == target.id }?.isSelectable ?: true
is SelectionTarget.Deformer -> deformers.firstOrNull { it.id == target.id }?.isSelectable ?: true
}
/**
* Toggles the viewport selectability of one [target] as a single undo step, dispatching the per-kind
* change and transform. Unlike visibility, a deformer has a selectable flag too.
*
* @param SelectionTarget target The entity whose selectability to flip.
*/
fun EditorSession.toggleSelectable(target: SelectionTarget) {
val newSelectable = !model.value.selectableOf(target)
when (target) {
is SelectionTarget.Part ->
mutate(PartChange.SetSelectable(target.id, newSelectable)) { model -> model.withPartSelectable(target.id, newSelectable) }
is SelectionTarget.Drawable ->
mutate(DrawableChange.SetSelectable(target.id, newSelectable)) { model -> model.withDrawableSelectable(target.id, newSelectable) }
is SelectionTarget.Deformer ->
mutate(DeformerChange.SetSelectable(target.id, newSelectable)) { model -> model.withDeformerSelectable(target.id, newSelectable) }
}
}
/**
* Enumerates the outliner subtree rooted at [target], the target itself first, in tree order. Matches
* exactly what the outliner shows as children: a part yields itself plus every descendant part and every
* drawable in those parts' org-tree children; a deformer yields itself plus its descendant deformers only
* (never the drawables bound to them via parentDeformerId — those rows live under their parts); a
* drawable is a leaf, so it yields just itself. An id that no longer resolves is still yielded (the
* transforms no-op on it) but never descended into, and a malformed cycle is visited once. Pure over the
* model, so it unit-tests without Compose.
*
* @param SelectionTarget target The subtree root.
* @return List The subtree's targets, [target] first.
*/
fun PuppetModel.subtreeTargets(target: SelectionTarget): List<SelectionTarget> =
when (target) {
is SelectionTarget.Part -> {
val partsById = parts.associateBy { part -> part.id }
val visitedPartIds = HashSet<PartId>()
val collected = mutableListOf<SelectionTarget>()
fun visitPart(partId: PartId) {
if (!visitedPartIds.add(partId)) {
return
}
collected += SelectionTarget.Part(partId)
val part = partsById[partId] ?: return
for (childEntry in part.children) {
when (childEntry) {
is OrgChild.Part -> visitPart(childEntry.id)
is OrgChild.Drawable -> collected += SelectionTarget.Drawable(childEntry.id)
}
}
}
visitPart(target.id)
collected
}
is SelectionTarget.Drawable -> listOf(target)
is SelectionTarget.Deformer -> {
val deformersByParent = deformers.groupBy { deformer -> deformer.parent }
val visitedDeformerIds = HashSet<DeformerId>()
val collected = mutableListOf<SelectionTarget>()
fun visitDeformer(deformerId: DeformerId) {
if (!visitedDeformerIds.add(deformerId)) {
return
}
collected += SelectionTarget.Deformer(deformerId)
for (childDeformer in deformersByParent[deformerId].orEmpty()) {
visitDeformer(childDeformer.id)
}
}
visitDeformer(target.id)
collected
}
}
/**
* Returns a copy of [this] with every entity in [targets] set to [selectable], structurally sharing
* untouched entities. Unlike the visibility counterpart (withSelectionVisibility) this covers deformers
* too — they carry the flag. Folding all targets into one model makes a whole subtree toggle a single
* undo step.
*
* @param Set targets The targets to retoggle.
* @param Boolean selectable The new selectable state.
* @return PuppetModel The model with those entities' selectability updated.
*/
fun PuppetModel.withSelectionSelectable(targets: Set<SelectionTarget>, selectable: Boolean): PuppetModel {
var next = this
for (target in targets) {
next =
when (target) {
is SelectionTarget.Part -> next.withPartSelectable(target.id, selectable)
is SelectionTarget.Drawable -> next.withDrawableSelectable(target.id, selectable)
is SelectionTarget.Deformer -> next.withDeformerSelectable(target.id, selectable)
}
}
return next
}
/**
* Toggles viewport selectability for [target] and its whole outliner subtree as one undo step: the new
* value is the flip of the clicked target's current state, applied uniformly to every subtree entity (a
* Blender-style Shift+Click), so a mixed subtree lands on one state. Reuses the clicked target's
* per-kind SetSelectable change, mirroring the selection-wide visibility command.
*
* @param SelectionTarget target The clicked subtree root.
*/
fun EditorSession.toggleSelectableSubtree(target: SelectionTarget) {
val newSelectable = !model.value.selectableOf(target)
val change: Change =
when (target) {
is SelectionTarget.Part -> PartChange.SetSelectable(target.id, newSelectable)
is SelectionTarget.Drawable -> DrawableChange.SetSelectable(target.id, newSelectable)
is SelectionTarget.Deformer -> DeformerChange.SetSelectable(target.id, newSelectable)
}
mutate(change) { model -> model.withSelectionSelectable(model.subtreeTargets(target).toSet(), newSelectable) }
}
/**
* Toggles visibility for [target] and its whole outliner subtree as one undo step, applied uniformly like
* the selectable variant. Deformers have no visibility flag, so a deformer target is a no-op (the
* outliner shows no eye for one anyway) and any deformer inside a part subtree is skipped by
* withSelectionVisibility.
*
* @param SelectionTarget target The clicked subtree root.
*/
fun EditorSession.toggleVisibilitySubtree(target: SelectionTarget) {
val newVisible = !model.value.visibilityOf(target)
val change: Change =
when (target) {
is SelectionTarget.Part -> PartChange.SetVisibility(target.id, newVisible)
is SelectionTarget.Drawable -> DrawableChange.SetVisibility(target.id, newVisible)
// A deformer has no visibility flag; nothing to toggle.
is SelectionTarget.Deformer -> return
}
mutate(change) { model -> model.withSelectionVisibility(model.subtreeTargets(target).toSet(), newVisible) }
}
@@ -0,0 +1,141 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.firstEditableDrawableInPanelOrder
/**
* How a document was being worked on, as opposed to what it is: the session state a saved document carries so a
* rigger reopens it where they left off (docs/format/UMA.md § 7.4). None of it is document content - nothing here
* mints a model, so none of it marks a document dirty - and the pose rides beside it as the session's initial pose.
*
* Plain data with no format knowledge: whoever reads the file builds one, and the session validates it against
* the model it opens on ([fittedTo]), since a saved id can name an object the file no longer has.
*
* @property Selection selection The object selection.
* @property ParameterSelection parameterSelection The parameters targeted for keyform authoring.
* @property EditorMode mode The interaction mode; Edit holds only when it can be entered.
* @property MeshSelectMode selectMode The mesh select mode, meaningful in Edit mode.
* @property Cursor2d? cursor2d The 2D cursor, or null when never placed.
* @property UvCursor? uvCursor The UV cursor, or null when never placed.
* @property TransformPivotMode pivotMode What a modal Scale or Rotate turns about.
* @property Boolean proportionalEnabled Whether proportional editing is on.
* @property ProportionalEditState? proportionalSettings The proportional falloff, radius, and connected flag - kept
* while proportional editing is off, since a toggle brings them back - or null for the defaults.
* @property GridConfig? gridConfig The document's own grid, or null to follow the application's.
*/
data class SessionViewState(
val selection: Selection = Selection(),
val parameterSelection: ParameterSelection = ParameterSelection(),
val mode: EditorMode = EditorMode.Object,
val selectMode: MeshSelectMode = MeshSelectMode.Vertex,
val cursor2d: Cursor2d? = null,
val uvCursor: UvCursor? = null,
val pivotMode: TransformPivotMode = TransformPivotMode.MedianPoint,
val proportionalEnabled: Boolean = false,
val proportionalSettings: ProportionalEditState? = null,
val gridConfig: GridConfig? = null,
)
/**
* This state with every reference [model] cannot satisfy taken out: a selected target the model lacks is dropped,
* and an active that did not survive falls to one that did. A saved file can name an object deleted by another
* writer or by a hand edit, and a selection holding a ghost would hand every command a target that is not there.
*
* @param PuppetModel model The model the session opens on.
* @return SessionViewState The state that fits the model.
*/
internal fun SessionViewState.fittedTo(model: PuppetModel): SessionViewState {
val partIds = model.parts.mapTo(HashSet()) { part -> part.id }
val drawableIds = model.drawables.mapTo(HashSet()) { drawable -> drawable.id }
val deformerIds = model.deformers.mapTo(HashSet()) { deformer -> deformer.id }
val targets =
selection.targets.filterTo(LinkedHashSet()) { target ->
when (target) {
is SelectionTarget.Part -> target.id in partIds
is SelectionTarget.Drawable -> target.id in drawableIds
is SelectionTarget.Deformer -> target.id in deformerIds
}
}
val parameterIds = model.parameters.mapTo(HashSet()) { parameter -> parameter.id }
val targetedParameters = parameterSelection.ids.filterTo(LinkedHashSet()) { parameterId -> parameterId in parameterIds }
return copy(
selection = Selection(targets, selection.active?.takeIf { active -> active in targets } ?: targets.lastOrNull()),
parameterSelection =
ParameterSelection(
targetedParameters,
parameterSelection.active?.takeIf { active -> active in targetedParameters } ?: targetedParameters.lastOrNull(),
),
)
}
/**
* The meshes an Edit-mode session opens on, and which of them is active.
*
* @property List<DrawableId> drawableIds The session's meshes.
* @property DrawableId activeId The active mesh.
* @property Boolean activeSelected Whether [activeId] is the object selection's own active drawable, as opposed
* to a fallback the entry chose.
*/
internal class EditSeed(
val drawableIds: List<DrawableId>,
val activeId: DrawableId,
val activeSelected: Boolean,
)
/**
* What entering Edit mode opens on: every selected mesh-carrying drawable (multi-mesh edit, the object selection's
* active drawable becoming the active mesh), else the remembered drawable, else the topmost editable drawable in
* Parts-panel order - or null when the model has nothing editable, which refuses the entry.
*
* @param PuppetModel model The session's model.
* @param Selection selection The object selection.
* @param DrawableId? rememberedDrawableId The last drawable that was active, or null.
* @return EditSeed? The meshes to open on, or null when Edit mode cannot be entered.
*/
internal fun editSeedOf(model: PuppetModel, selection: Selection, rememberedDrawableId: DrawableId?): EditSeed? {
val selectedMeshedIds =
selection.targets
.filterIsInstance<SelectionTarget.Drawable>()
.map { target -> target.id }
.filter { candidateId -> model.drawables.any { drawable -> drawable.id == candidateId && drawable.mesh != null } }
val activeSelectedId = (selection.active as? SelectionTarget.Drawable)?.id?.takeIf { activeId -> activeId in selectedMeshedIds }
val remembered = rememberedDrawableId?.takeIf { candidateId -> model.drawables.any { drawable -> drawable.id == candidateId && drawable.mesh != null } }
val seedDrawableIds =
when {
selectedMeshedIds.isNotEmpty() -> selectedMeshedIds
remembered != null -> listOf(remembered)
else -> listOfNotNull(model.firstEditableDrawableInPanelOrder())
}
if (seedDrawableIds.isEmpty()) {
return null
}
return EditSeed(seedDrawableIds, activeSelectedId ?: seedDrawableIds.first(), activeSelectedId != null)
}
/**
* The snapshot a session opens on: the model and pose as given, with [viewState] fitted to the model laid in, so
* the state a document was saved with is where its history STARTS rather than a run of undo steps on top of it.
*
* A saved Edit mode holds only when it can be entered over the restored selection; when the model has nothing
* editable the session opens in Object mode, the same refusal [EditorSession.setMode] makes.
*
* @param PuppetModel model The document model at open.
* @param Pose pose The pose at open.
* @param SessionViewState? viewState The saved session state, already fitted, or null for a plain open.
* @return EditorSnapshot The session's first snapshot.
*/
internal fun openingSnapshotOf(model: PuppetModel, pose: Pose, viewState: SessionViewState?): EditorSnapshot {
if (viewState == null) {
return EditorSnapshot(model, Selection(), pose)
}
val editSeed = if (viewState.mode == EditorMode.Edit) editSeedOf(model, viewState.selection, rememberedDrawableId = null) else null
return EditorSnapshot(
model = model,
selection = viewState.selection,
pose = pose,
meshSelection = editSeed?.let { seed -> MeshSelection.editing(seed.drawableIds, seed.activeId).copy(selectMode = viewState.selectMode) } ?: MeshSelection(),
mode = if (editSeed != null) EditorMode.Edit else EditorMode.Object,
parameterSelection = viewState.parameterSelection,
)
}
@@ -0,0 +1,144 @@
package org.umamo.edit
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.deformerSelfAndDescendants
import org.umamo.runtime.model.partSelfAndDescendants
import org.umamo.runtime.model.withDerivedRenderRoot
/*
* Organizational-tree structure edits. The org tree (PuppetModel.rootChildren + Part.children - an ordered
* mix of sub-parts and drawables) is the single source of truth for the hierarchy AND the parts-panel
* order, and that order is the draw-order tiebreak. So one move - withOrgChildMoved - covers reparenting a
* part, re-homing a drawable, reordering siblings, and interleaving a drawable between parts; every move
* re-derives the render order from the tree. Deformer moves are separate (deformers live in the Armature,
* not the org tree).
*
* 組織ツリーの構造編集。ツリーが階層とパネル順の唯一の真実で、描画順のタイブレークでもある。移動は1つに統合。
*/
/** True when [child] is present somewhere in the org tree (the root level or some part's children). */
private fun PuppetModel.containsOrgChild(child: OrgChild): Boolean =
child in rootChildren || parts.any { child in it.children }
/** This child list with [child] inserted before [before] (or appended when [before] is null or absent). */
private fun List<OrgChild>.withChildInsertedBefore(child: OrgChild, before: OrgChild?): List<OrgChild> {
val result = toMutableList()
val insertAt = before?.let { result.indexOf(it) }?.takeIf { it >= 0 } ?: result.size
result.add(insertAt, child)
return result
}
/**
* Returns a copy of [this] with the org child [child] (a sub-part or a drawable) moved under [newParentId]
* (null = the top level) and positioned before [before] there (null / absent = appended). This is the one
* organizational move: a part reparent / reorder, a drawable re-home, and a cross-kind interleave (a
* drawable dropped between two parts) are the same edit. Because the parts-panel order is the draw-order
* tiebreak, the render order is re-derived. A move that would drop a part inside its own subtree (a cycle),
* or that changes nothing, returns the same instance.
*
* @param OrgChild child The sub-part or drawable to move.
* @param PartId? newParentId The destination part, or null for the top level.
* @param OrgChild? before The sibling to insert before, or null to append at the destination's end.
* @return PuppetModel The model with the child moved, or [this] if the move was a no-op or illegal.
*/
fun PuppetModel.withOrgChildMoved(child: OrgChild, newParentId: PartId?, before: OrgChild?): PuppetModel {
if (!containsOrgChild(child)) {
return this
}
// The subtree set contains the part itself, so this rejects self-parenting and any deeper cycle at once.
// The Properties picker filters its candidates against the same query, so an illegal target is not
// offered there rather than being silently refused here.
if (child is OrgChild.Part && newParentId != null && newParentId in partSelfAndDescendants(child.id)) {
return this
}
// Detach from wherever it currently sits (the root level and / or some part's children).
val detachedRoot = rootChildren.filter { it != child }
val detachedParts = parts.map { part -> if (child in part.children) part.copy(children = part.children - child) else part }
val newRoot: List<OrgChild>
val newParts: List<Part>
if (newParentId == null) {
newRoot = detachedRoot.withChildInsertedBefore(child, before)
newParts = detachedParts
} else {
newRoot = detachedRoot
newParts =
detachedParts.map { part ->
if (part.id == newParentId) part.copy(children = part.children.withChildInsertedBefore(child, before)) else part
}
}
if (newRoot == rootChildren && newParts == parts) {
return this
}
return copy(rootChildren = newRoot, parts = newParts).withDerivedRenderRoot()
}
/**
* Moves the org child [child] under [newParentId] (null = top level), before [before] (null = append), as
* one undo step. A cycle-forming or no-op move records nothing.
*
* @param OrgChild child The sub-part or drawable to move.
* @param PartId? newParentId The destination part, or null for the top level.
* @param OrgChild? before The sibling to insert before, or null to append.
*/
fun EditorSession.moveOrgChild(child: OrgChild, newParentId: PartId?, before: OrgChild?) {
val change: Change =
when (child) {
is OrgChild.Part -> PartChange.Move(child.id, newParentId, (before as? OrgChild.Part)?.id)
is OrgChild.Drawable -> DrawableChange.Move(child.id, newParentId)
}
mutate(change) { model -> model.withOrgChildMoved(child, newParentId, before) }
}
/** A copy of this deformer re-homed under [newParent] in the transform (nesting) hierarchy. */
private fun Deformer.withParent(newParent: DeformerId?): Deformer =
when (this) {
is Deformer.Warp -> copy(parent = newParent)
is Deformer.Rotation -> copy(parent = newParent)
}
/**
* Returns a copy of [this] with the deformer [id] re-nested under [newParentId] (null = an armature root)
* and re-positioned among the deformers list before [beforeId] (null = appended). Reparent and reorder are
* one move: [Deformer.parent] sets the transform nesting, and the deformers list order sets sibling order
* in the armature. When the parent actually changes, the deformer's keyed geometry is converted from the
* old parent-local space into the new one so the lattice keeps its world pose (otherwise canvas CPs under
* a UV parent - or the reverse - send it flying). A move that would nest the deformer inside its own
* subtree (a cycle) or that does nothing returns the same instance.
*
* @param DeformerId id The deformer to move.
* @param DeformerId? newParentId The destination parent deformer, or null for an armature root.
* @param DeformerId? beforeId The sibling to insert before, or null to append.
* @return PuppetModel The model with the deformer moved, or [this] if the move was a no-op or illegal.
*/
fun PuppetModel.withDeformerMoved(id: DeformerId, newParentId: DeformerId?, beforeId: DeformerId?): PuppetModel {
val deformer = deformers.firstOrNull { it.id == id } ?: return this
// The subtree set contains id itself, so this rejects self-parenting and any deeper cycle at once. The
// Properties picker filters its candidates against the same query, so an illegal target is not offered
// there rather than being silently refused here.
if (newParentId != null && newParentId in deformerSelfAndDescendants(id)) {
return this
}
val converted = withDeformerGeometryConvertedForReparent(deformer, deformer.parent, newParentId)
val moved = converted.withParent(newParentId)
val without = deformers.filter { it.id != id }.toMutableList()
val insertAt = beforeId?.let { target -> without.indexOfFirst { it.id == target } }?.takeIf { it >= 0 } ?: without.size
without.add(insertAt, moved)
return copy(deformers = without)
}
/**
* Moves the deformer [id] under [newParentId] (null = armature root), before [beforeId] (null = append),
* as one undo step. A cycle-forming or no-op move records nothing.
*
* @param DeformerId id The deformer to move.
* @param DeformerId? newParentId The destination parent deformer, or null for a root.
* @param DeformerId? beforeId The sibling to insert before, or null to append.
*/
fun EditorSession.moveDeformer(id: DeformerId, newParentId: DeformerId?, beforeId: DeformerId?) {
mutate(DeformerChange.Move(id, newParentId, beforeId)) { model -> model.withDeformerMoved(id, newParentId, beforeId) }
}
@@ -0,0 +1,537 @@
package org.umamo.edit
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import org.umamo.runtime.model.DrawableId
/**
* The session's transient tool state: the modal operator latches, the armed select tool, the zoom
* region, the axis constraint, the viewport-gesture flag, the stroke-preview selection, the pie
* menu, the 2D cursor, the pivot mode, and proportional editing - everything that coordinates the
* viewport overlays without ever being snapshotted or entering the change bus. The
* mutual-exclusion story (a transform operator owns the pointer, so arming anything drops the
* others) lives in [clearTransient]; [EditorSession] keeps the mode / selection / pose guards and
* delegates the state itself here, exposing every flow unchanged.
*
* セッションの一時的なツール状態(モーダル演算子・選択ツール・ズーム領域・軸拘束・パイメニュー・
* 2D カーソル・ピボット・プロポーショナル編集)。スナップショットには入らないオーバーレイ調整用。
* 相互排他の規則は clearTransient に集約する。
*
* @param Function notify Emits a transient user notice (the proportional toggles confirm through it).
*/
internal class ToolLatches(private val notify: (String, NoticePlacement) -> Unit) {
private val mutableActiveMeshOperator = MutableStateFlow<ActiveOperator?>(null)
/** The modal mesh operator currently running, or null (see [EditorSession.activeMeshOperator]). */
val activeMeshOperator: StateFlow<ActiveOperator?> = mutableActiveMeshOperator.asStateFlow()
private val mutableActiveObjectOperator = MutableStateFlow<ActiveOperator?>(null)
/** The modal object operator currently running, or null (see [EditorSession.activeObjectOperator]). */
val activeObjectOperator: StateFlow<ActiveOperator?> = mutableActiveObjectOperator.asStateFlow()
private val mutableActiveUvOperator = MutableStateFlow<ActiveOperator?>(null)
/** The modal UV operator currently running, or null (see [EditorSession.activeUvOperator]). */
val activeUvOperator: StateFlow<ActiveOperator?> = mutableActiveUvOperator.asStateFlow()
private val mutableActiveSelectTool = MutableStateFlow<ActiveSelectTool?>(null)
/** The armed Box / Circle / Add Vertex tool, or null (see [EditorSession.activeSelectTool]). */
val activeSelectTool: StateFlow<ActiveSelectTool?> = mutableActiveSelectTool.asStateFlow()
private val mutableZoomRegionArmedArea = MutableStateFlow<String?>(null)
/** The area id whose Zoom Region gesture is armed, or null (see [EditorSession.zoomRegionArmedArea]). */
val zoomRegionArmedArea: StateFlow<String?> = mutableZoomRegionArmedArea.asStateFlow()
private val mutableAxisConstraint = MutableStateFlow<TransformAxisConstraint?>(null)
/** The axis the in-flight modal transform is locked to, or null (see [EditorSession.axisConstraint]). */
val axisConstraint: StateFlow<TransformAxisConstraint?> = mutableAxisConstraint.asStateFlow()
private val mutableViewportGestureActive = MutableStateFlow(false)
/** True while a non-armed viewport gesture is in flight (see [EditorSession.viewportGestureActive]). */
val viewportGestureActive: StateFlow<Boolean> = mutableViewportGestureActive.asStateFlow()
private val mutablePreviewSelection = MutableStateFlow<Set<DrawableId>?>(null)
/** The transient circle-stroke preview selection, or null (see [EditorSession.previewSelection]). */
val previewSelection: StateFlow<Set<DrawableId>?> = mutablePreviewSelection.asStateFlow()
private val mutableActivePieMenu = MutableStateFlow<PieMenuKind?>(null)
/** The radial pie menu currently open, or null (see [EditorSession.activePieMenu]). */
val activePieMenu: StateFlow<PieMenuKind?> = mutableActivePieMenu.asStateFlow()
private val mutablePendingParameterChoice = MutableStateFlow<ParameterChoiceRequest?>(null)
/** The keyform edit waiting on an axis, or null (see [EditorSession.pendingParameterChoice]). */
val pendingParameterChoice: StateFlow<ParameterChoiceRequest?> = mutablePendingParameterChoice.asStateFlow()
private val mutableCursor2d = MutableStateFlow<Cursor2d?>(null)
/** The 2D cursor's world position, or null before any placement (see [EditorSession.cursor2d]). */
val cursor2d: StateFlow<Cursor2d?> = mutableCursor2d.asStateFlow()
private val mutableUvCursor = MutableStateFlow<UvCursor?>(null)
/** The UV editor's cursor in atlas coordinates, or null before any placement (see [EditorSession.uvCursor]). */
val uvCursor: StateFlow<UvCursor?> = mutableUvCursor.asStateFlow()
private val mutablePivotMode = MutableStateFlow(TransformPivotMode.MedianPoint)
/** What a modal Scale / Rotate turns the selection about (see [EditorSession.pivotMode]). */
val pivotMode: StateFlow<TransformPivotMode> = mutablePivotMode.asStateFlow()
private val mutableGridConfig = MutableStateFlow(GridConfig())
/** The viewport grid geometry driving the backdrop and grid snap (see [EditorSession.gridConfig]). */
val gridConfig: StateFlow<GridConfig> = mutableGridConfig.asStateFlow()
/**
* Sets the viewport grid geometry.
*
* @param GridConfig config The new grid scale and subdivisions.
*/
fun setGridConfig(config: GridConfig) {
mutableGridConfig.value = config
}
private val mutableProportionalEdit = MutableStateFlow<ProportionalEditState?>(null)
/** Proportional editing, non-null while enabled (see [EditorSession.proportionalEdit]). */
val proportionalEdit: StateFlow<ProportionalEditState?> = mutableProportionalEdit.asStateFlow()
// The configuration proportional editing re-enables with: the last falloff and radius survive an
// off/on toggle (the circle-select radius pattern), so O comes back the way it was left.
private var lastProportionalEdit = DEFAULT_PROPORTIONAL_EDIT_STATE
/**
* The proportional falloff, radius, and connected flag as they would apply now: the live state while
* proportional editing is on, else the configuration a toggle would bring back.
*/
val proportionalSettings: ProportionalEditState
get() = mutableProportionalEdit.value ?: lastProportionalEdit
// The Circle-select brush radius carried across re-entry (Blender remembers it). Deliberately NOT
// part of EditorSnapshot - re-arming the tool restores the last size.
private var lastCircleRadiusPx: Float = DEFAULT_CIRCLE_RADIUS_PX
/**
* True while the active mesh operator was latched with proportional editing suppressed - the
* duplicate / rip auto-grabs, which place fresh copies and must never drag bystander vertices.
* Reset whenever the operator latches or clears.
*/
var activeMeshOperatorSuppressesProportional: Boolean = false
private set
/**
* Clears the mutually-exclusive transient tool latches - the modal mesh / object / UV operators and
* the armed select tool - plus the optional extras the caller names. Every site that latches a tool,
* switches mode, or restores a snapshot funnels through here so the mutual-exclusion story lives in
* one place; a caller about to latch one of the four simply overwrites its own slot right after.
*
* @param Boolean clearZoomRegion True to also disarm the zoom region (the tool-latch sites; a mode
* switch or restore leaves it armed - the gesture is mode-agnostic).
* @param Boolean clearAxisConstraint True to also drop the axis lock (the operator begins and
* restore; an axis lock is meaningless without a live operator).
* @param Boolean clearViewportGesture True to also end the viewport-gesture flag (mode switches and
* restore, which tear down any in-flight gesture).
*/
fun clearTransient(
clearZoomRegion: Boolean = false,
clearAxisConstraint: Boolean = false,
clearViewportGesture: Boolean = false,
) {
mutableActiveMeshOperator.value = null
mutableActiveObjectOperator.value = null
mutableActiveUvOperator.value = null
mutableActiveSelectTool.value = null
if (clearZoomRegion) {
mutableZoomRegionArmedArea.value = null
}
if (clearAxisConstraint) {
mutableAxisConstraint.value = null
}
if (clearViewportGesture) {
mutableViewportGestureActive.value = false
}
}
/**
* Latches a modal mesh operator (the caller has already checked the Edit-mode preconditions).
* Drops any armed select tool / zoom region first (mutual exclusion), and publishes the
* suppression BEFORE the operator itself: the overlay's latch effect keys on the operator flow and
* must read a consistent flag when it fires.
*
* @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate).
* @param String areaId The initiating viewport's area id (only its overlay drives the gesture).
* @param Boolean suppressProportional True to ignore proportional editing for this gesture.
*/
fun latchMeshOperator(kind: MeshOperatorKind, areaId: String, suppressProportional: Boolean) {
clearTransient(clearZoomRegion = true, clearAxisConstraint = true)
activeMeshOperatorSuppressesProportional = suppressProportional
mutableActiveMeshOperator.value = ActiveOperator(kind, areaId)
}
/** Clears the active modal mesh operator (confirm or cancel), dropping the axis lock with it. */
fun clearMeshOperator() {
mutableActiveMeshOperator.value = null
mutableAxisConstraint.value = null
activeMeshOperatorSuppressesProportional = false
}
/**
* Latches a modal object operator (the caller has already checked the Object-mode preconditions),
* dropping any other latched tool first (mutual exclusion).
*
* @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate).
* @param String areaId The initiating viewport's area id (only its overlay drives the gesture).
*/
fun latchObjectOperator(kind: MeshOperatorKind, areaId: String) {
clearTransient(clearZoomRegion = true, clearAxisConstraint = true)
mutableActiveObjectOperator.value = ActiveOperator(kind, areaId)
}
/** Clears the active modal object operator (confirm or cancel), dropping the axis lock with it. */
fun clearObjectOperator() {
mutableActiveObjectOperator.value = null
mutableAxisConstraint.value = null
}
/**
* Latches a modal UV operator (the caller has already checked the Edit-mode and UV-validity
* preconditions), dropping any other latched tool first (mutual exclusion).
*
* @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate).
* @param String areaId The initiating UV editor's area id (only its overlay drives the gesture).
*/
fun latchUvOperator(kind: MeshOperatorKind, areaId: String) {
clearTransient(clearZoomRegion = true, clearAxisConstraint = true)
mutableActiveUvOperator.value = ActiveOperator(kind, areaId)
}
/** Clears the active modal UV operator (confirm or cancel), dropping the axis lock with it. */
fun clearUvOperator() {
mutableActiveUvOperator.value = null
mutableAxisConstraint.value = null
}
/**
* The one modal transform operator currently running, whichever family latched it, or null.
*
* Safe to collapse the three into one answer because [clearTransient] runs at every latch site, so at
* most one is ever non-null. A plain getter rather than a combined StateFlow: the callers that want
* "is any transform running" read it at an instant (the shell's key ladder) and never observe it, so a
* combine would advertise a reactivity nobody consumes.
*/
val activeOperator: ActiveOperator?
get() = activeMeshOperator.value ?: activeObjectOperator.value ?: activeUvOperator.value
/**
* Clears whichever operator family is running, if any.
*
* Dispatches to that family's own clear rather than blanking all three: only [clearMeshOperator]
* resets the proportional-suppression flag, so a three-way blank would quietly change the duplicate
* and rip auto-grab behavior.
*/
fun clearActiveOperator() {
when {
mutableActiveMeshOperator.value != null -> clearMeshOperator()
mutableActiveObjectOperator.value != null -> clearObjectOperator()
mutableActiveUvOperator.value != null -> clearUvOperator()
}
}
/**
* Arms the Box-select tool (the caller has already checked the mode preconditions).
*
* @param String areaId The arming viewport's area id (only its overlay drives the drag).
*/
fun armBoxSelect(areaId: String) {
clearTransient(clearZoomRegion = true)
mutableActiveSelectTool.value = ActiveSelectTool.BoxArmed(areaId)
}
/**
* Arms the Circle-select tool at the remembered radius (preconditions checked by the caller).
*
* @param String areaId The arming viewport's area id (only its overlay drives the brush).
*/
fun armCircleSelect(areaId: String) {
clearTransient(clearZoomRegion = true)
mutableActiveSelectTool.value = ActiveSelectTool.Circle(lastCircleRadiusPx, areaId)
}
/**
* Sets the Circle-select brush radius (clamped), remembering it for the next arm. When a Circle
* tool is live its radius updates in place so the overlay redraws; otherwise only the remembered
* value moves.
*
* @param Float radiusPx The requested radius in viewport pixels.
*/
fun setCircleRadius(radiusPx: Float) {
val clamped = radiusPx.coerceIn(MIN_CIRCLE_RADIUS_PX, MAX_CIRCLE_RADIUS_PX)
lastCircleRadiusPx = clamped
val current = mutableActiveSelectTool.value
if (current is ActiveSelectTool.Circle) {
// A resize keeps the brush in its arming area - only re-arming moves the tool.
mutableActiveSelectTool.value = ActiveSelectTool.Circle(clamped, current.areaId)
}
}
/** Grows the Circle-select radius by one step; a no-op unless a Circle tool is live. */
fun growCircleRadius() {
val current = mutableActiveSelectTool.value
if (current is ActiveSelectTool.Circle) {
setCircleRadius(current.radiusPx + CIRCLE_RADIUS_STEP_PX)
}
}
/** Shrinks the Circle-select radius by one step; a no-op unless a Circle tool is live. */
fun shrinkCircleRadius() {
val current = mutableActiveSelectTool.value
if (current is ActiveSelectTool.Circle) {
setCircleRadius(current.radiusPx - CIRCLE_RADIUS_STEP_PX)
}
}
/**
* Arms the Add Vertex draft tool on [drawableId]. Preconditions checked by the caller.
*
* @param String areaId The arming viewport's area id (only its overlay drives the clicks).
* @param DrawableId drawableId The session mesh the draft targets.
*/
fun armAddVertex(areaId: String, drawableId: DrawableId) {
clearTransient(clearZoomRegion = true)
mutableActiveSelectTool.value = ActiveSelectTool.AddVertex(areaId = areaId, drawableId = drawableId)
}
/**
* Replaces the live Add Vertex draft in place. A no-op unless Add Vertex is armed.
*
* @param ActiveSelectTool.AddVertex draft The updated draft (same area / drawable).
*/
fun setAddVertexDraft(draft: ActiveSelectTool.AddVertex) {
val current = mutableActiveSelectTool.value
if (current is ActiveSelectTool.AddVertex && current.areaId == draft.areaId && current.drawableId == draft.drawableId) {
mutableActiveSelectTool.value = draft
}
}
/** Clears any armed Box / Circle / Add Vertex tool. */
fun clearSelectTool() {
mutableActiveSelectTool.value = null
}
/**
* Arms the Zoom Region gesture for [areaId], clearing any latched tool so two overlays never
* capture at once.
*
* @param String areaId The viewport area the gesture will run in.
*/
fun armZoomRegion(areaId: String) {
clearTransient()
mutableZoomRegionArmedArea.value = areaId
}
/** Disarms the Zoom Region gesture. */
fun disarmZoomRegion() {
mutableZoomRegionArmedArea.value = null
}
/**
* Toggles the modal axis constraint (pressing a lock's own key again releases it; pressing the
* other axis switches). A no-op unless a Grab or Scale operator is in flight - Rotate has no axis
* to lock and idle keys must not arm a stale constraint.
*
* @param TransformAxisConstraint axis The axis whose lock to toggle.
*/
fun toggleAxisConstraint(axis: TransformAxisConstraint) {
val operator = mutableActiveMeshOperator.value ?: mutableActiveObjectOperator.value ?: mutableActiveUvOperator.value ?: return
if (operator.kind == MeshOperatorKind.Rotate) {
return
}
mutableAxisConstraint.value = if (mutableAxisConstraint.value == axis) null else axis
}
/**
* Publishes whether a non-armed viewport gesture is in flight.
*
* @param Boolean active True while the overlay's gesture owns the pointer.
*/
fun setViewportGestureActive(active: Boolean) {
mutableViewportGestureActive.value = active
}
/**
* Publishes the transient circle-stroke preview selection; pass null to clear it.
*
* @param Set<DrawableId>? drawableIds The drawables currently painted by the stroke, or null.
*/
fun setPreviewSelection(drawableIds: Set<DrawableId>?) {
mutablePreviewSelection.value = drawableIds
}
/**
* Opens a pie menu over the viewport.
*
* @param PieMenuKind kind The pie to open.
*/
fun openPieMenu(kind: PieMenuKind) {
mutableActivePieMenu.value = kind
}
/** Closes the open pie menu. */
fun closePieMenu() {
mutableActivePieMenu.value = null
}
/**
* Parks a keyform edit until the user picks the axis it writes on.
*
* @param ParameterChoiceRequest request The parked edit and the axes to choose between.
*/
fun openParameterChoice(request: ParameterChoiceRequest) {
mutablePendingParameterChoice.value = request
}
/** Discards the parked keyform edit (an axis was picked, or the prompt was dismissed). */
fun closeParameterChoice() {
mutablePendingParameterChoice.value = null
}
/**
* Places (or moves) the 2D cursor.
*
* @param Float worldX The cursor's new world-space x.
* @param Float worldZ The cursor's new world-space z (up).
*/
fun setCursor2d(worldX: Float, worldZ: Float) {
mutableCursor2d.value = Cursor2d(worldX, worldZ)
}
/**
* Places (or moves) the UV editor's cursor.
*
* @param Float u The cursor's new normalized atlas u coordinate.
* @param Float v The cursor's new normalized atlas v coordinate.
*/
fun setUvCursor(u: Float, v: Float) {
mutableUvCursor.value = UvCursor(u, v)
}
/**
* Selects the transform pivot mode.
*
* @param TransformPivotMode mode The pivot mode the next transforms anchor on.
*/
fun setPivotMode(mode: TransformPivotMode) {
mutablePivotMode.value = mode
}
/**
* Toggles proportional editing on or off (Blender's O), restoring the last falloff and radius on
* re-enable and confirming either way with a near-cursor notice (an idle toggle has no other
* visible effect - the influence circle only shows during a modal transform).
*/
fun toggleProportionalEdit() {
val current = mutableProportionalEdit.value
if (current != null) {
lastProportionalEdit = current
mutableProportionalEdit.value = null
notify("notice.proportional.off", NoticePlacement.NearCursor)
} else {
mutableProportionalEdit.value = lastProportionalEdit
notify("notice.proportional.on", NoticePlacement.NearCursor)
}
}
/**
* Toggles Connected Only for proportional editing (influence measured along mesh edges instead of
* straight-line, so the halo never leaps to unconnected geometry), enabling proportional editing
* if it was off - and then connected mode turns ON regardless of the remembered flag, since the
* command expresses the intent to use it. Confirms either way with a near-cursor notice.
*/
fun toggleProportionalConnected() {
val current = mutableProportionalEdit.value
val updated =
if (current == null) {
lastProportionalEdit.copy(connectedOnly = true)
} else {
current.copy(connectedOnly = !current.connectedOnly)
}
lastProportionalEdit = updated
mutableProportionalEdit.value = updated
notify(
if (updated.connectedOnly) "notice.proportional.connected.on" else "notice.proportional.connected.off",
NoticePlacement.NearCursor,
)
}
/**
* Selects the proportional falloff curve, enabling proportional editing if it was off - picking a
* falloff from the palette or header expresses the intent to use it, and silently updating a
* disabled state would look like the command did nothing.
*
* @param ProportionalFalloff falloff The falloff curve the influence weights follow.
*/
fun setProportionalFalloff(falloff: ProportionalFalloff) {
val updated = (mutableProportionalEdit.value ?: lastProportionalEdit).copy(falloff = falloff)
lastProportionalEdit = updated
mutableProportionalEdit.value = updated
}
/**
* Sets the proportional influence radius, clamped to the allowed range. A no-op while proportional
* editing is off (the radius only changes from the mid-gesture scroll, which requires it on).
*
* @param Float radiusWorld The influence radius in world units (canvas px).
*/
fun setProportionalRadius(radiusWorld: Float) {
val current = mutableProportionalEdit.value ?: return
val updated = current.copy(radiusWorld = radiusWorld.coerceIn(MIN_PROPORTIONAL_RADIUS_WORLD, MAX_PROPORTIONAL_RADIUS_WORLD))
lastProportionalEdit = updated
mutableProportionalEdit.value = updated
}
/**
* Sets proportional editing outright - on with [state] (its radius clamped), or off with null -
* silently, and remembering the configuration a later toggle restores. The operation settings
* strip's write-back: the proportional rows of an adjusted transform become the state the next
* gesture starts from, and the strip's rows are their own confirmation, so no notice fires.
*
* @param ProportionalEditState? state The state to set, or null to turn proportional editing off.
*/
fun setProportionalEdit(state: ProportionalEditState?) {
if (state == null) {
mutableProportionalEdit.value?.let { current -> lastProportionalEdit = current }
mutableProportionalEdit.value = null
return
}
val clamped = state.copy(radiusWorld = state.radiusWorld.coerceIn(MIN_PROPORTIONAL_RADIUS_WORLD, MAX_PROPORTIONAL_RADIUS_WORLD))
lastProportionalEdit = clamped
mutableProportionalEdit.value = clamped
}
/**
* Lays a saved session's tool state in, silently: the cursors, the pivot mode, proportional editing with the
* configuration it would re-enable with, and the document's own grid when it saved one. Called once, as the
* session is built, so nothing here is a gesture and nothing here posts a notice.
*
* @param SessionViewState viewState The saved state, already fitted to the model.
*/
fun seed(viewState: SessionViewState) {
mutableCursor2d.value = viewState.cursor2d
mutableUvCursor.value = viewState.uvCursor
mutablePivotMode.value = viewState.pivotMode
viewState.proportionalSettings?.let { settings ->
lastProportionalEdit = settings.copy(radiusWorld = settings.radiusWorld.coerceIn(MIN_PROPORTIONAL_RADIUS_WORLD, MAX_PROPORTIONAL_RADIUS_WORLD))
}
mutableProportionalEdit.value = lastProportionalEdit.takeIf { viewState.proportionalEnabled }
viewState.gridConfig?.let { config -> mutableGridConfig.value = config }
}
}
@@ -0,0 +1,23 @@
package org.umamo.edit
import org.umamo.runtime.model.ParameterId
/**
* One selected keyform key: the parameter section, the row, and WHICH key on that row.
*
* By ordinal rather than by parameter value. Two keys a hair apart are legal and useful, and resolving a
* value back to a key would then pick whichever happens to be nearer - dragging one of a pair of
* near-coincident marks would silently move the other instead. The parameter is part of the identity
* because a linked pair renders two sections at once and one item's row key is the same string in both.
*
* [rowKey] is an opaque string to this module, and deliberately so. It is the keyform sheet's row identity,
* built from the OWNER plus what the row edits (a channel, the geometry, a blend binding) - model identity
* throughout, so it survives every edit that does not delete the thing it names. Resolving it back to a
* track is the sheet's job because only the sheet knows which rows it is currently projecting; a session
* that tried to would have to duplicate that projection to answer.
*
* @property ParameterId parameterId The parameter whose section the key sits in.
* @property String rowKey The owning row's stable key.
* @property Int keyIndex The key's ordinal on that row's track.
*/
data class TrackKeyRef(val parameterId: ParameterId, val rowKey: String, val keyIndex: Int)
@@ -0,0 +1,350 @@
package org.umamo.edit
import kotlin.math.PI
/*
* The modal transforms' face on the operation settings strip - the half that knows no geometry: the
* numbers a Grab / Rotate / Scale (or a Vertex Slide) landed with as the strip's typed rows, the
* parameters those rows mean, and the proportional rows' state. The registrations that replay a
* frozen capture through the viewport's world geometry or the UV editor's frame live in :ui
* (viewport/TransformAdjustRegistration.kt) and cannot be here: :edit and :render are siblings over
* :runtime, and the world-to-base inverse needs :render's evaluator.
*
* There is no axis-constraint row, for the reason the placement gesture has none: a lock only zeroes
* one Grab component or pins one Scale factor at 1, so the per-component rows already say it.
*/
/**
* The numbers one modal transform applies, in the positions' units: a Grab's translation, a Scale's
* factors, a Rotate's angle, the rest at identity. During a drag the UI resolves one from each pointer
* frame; after the commit the operation settings strip shows it as rows and builds one back from them,
* so the same transform runs from a pointer or a typed value.
*
* @property Float deltaX The Grab translation's x (identity 0 for the other operators).
* @property Float deltaY The Grab translation's y, in the positions' sense (y up for world space).
* @property Float factorX The Scale factor along x (identity 1 for the other operators).
* @property Float factorY The Scale factor along y.
* @property Float rotationRadians The Rotate angle in the positions' sense (identity 0 for the others).
*/
class TransformGestureParameters(
val deltaX: Float,
val deltaY: Float,
val factorX: Float,
val factorY: Float,
val rotationRadians: Float,
) {
companion object {
/** The parameters that move nothing. */
val IDENTITY = TransformGestureParameters(0f, 0f, 1f, 1f, 0f)
}
}
/** The parameter keys the transform gestures' rows carry (the strip maps them to labels). */
object TransformParameterKeys {
const val MOVE_X = "transform.moveX"
const val MOVE_Y = "transform.moveY"
const val MOVE_Z = "transform.moveZ"
const val ANGLE = "transform.angle"
const val SCALE_X = "transform.scaleX"
const val SCALE_Y = "transform.scaleY"
const val SCALE_Z = "transform.scaleZ"
const val PROPORTIONAL = "transform.proportional"
const val FALLOFF = "transform.falloff"
const val PROPORTIONAL_SIZE = "transform.proportionalSize"
const val CONNECTED_ONLY = "transform.connectedOnly"
const val SLIDE_FACTOR = "transform.slideFactor"
/** The label-key prefix of the Falloff row's choices; the curve's [ProportionalFalloff.choiceKey] follows it. */
const val FALLOFF_CHOICE_PREFIX = "transform.falloff."
}
/** The widest angle an Angle row accepts, in degrees either way. */
const val TRANSFORM_ANGLE_LIMIT = 360f
/** The smallest factor a Scale row accepts - a zero scale would collapse the geometry. */
const val TRANSFORM_SCALE_MIN = 0.01f
/** The largest factor a Scale row accepts. */
const val TRANSFORM_SCALE_MAX = 100f
/** The Scale rows' scrub step. */
const val TRANSFORM_SCALE_STEP = 0.01f
/** The farthest a Move row reaches either way, in the gesture space's units (world px or texels). */
private const val TRANSFORM_MOVE_LIMIT = 100_000f
/** The Proportional Size row's scrub step, in the gesture space's units. */
private const val PROPORTIONAL_SIZE_STEP = 1f
/** The Vertex Slide Factor row's scrub step. */
private const val SLIDE_FACTOR_STEP = 0.01f
/**
* The space a transform's rows read in - which decides the axis labels and the sign conventions.
*/
enum class TransformRowSpace {
/**
* World units in a 2D viewport: y up, shown as the Z axis (the project presents the 2D plane as X
* and Z per the Y+ forward, Z+ up convention, and the axis-lock badge says "along Z").
*/
World,
/**
* Display texels in the UV editor: the vertical row reads y DOWN, as the page and the placement
* strip's rows do, and the angle's sign flips with it (the flip mirrors a rotation's sense).
*/
UvDisplay,
}
/**
* The proportional-editing rows' values: whether it applied, the curve, the radius in the gesture
* space's units, and Connected Only. Built from the session state at confirm and read back from the
* rows at each adjustment.
*
* @property Boolean enabled Whether the halo applies.
* @property ProportionalFalloff falloff The falloff curve.
* @property Float radius The influence radius, in the gesture space's units.
* @property Boolean connectedOnly Whether influence spreads only along mesh edges.
*/
class ProportionalRows(
val enabled: Boolean,
val falloff: ProportionalFalloff,
val radius: Float,
val connectedOnly: Boolean,
) {
/**
* The state the rows describe, or null while the flag is off - what the capture's halos re-derive
* from. The state's radius is [radius] in the gesture space's units; a caller writing it back to the
* session's WORLD radius from another space substitutes its own.
*
* @return ProportionalEditState? The state, or null.
*/
fun asState(): ProportionalEditState? = if (enabled) ProportionalEditState(falloff, radius, connectedOnly) else null
companion object {
/**
* The rows for the session's live state at confirm, with [radius] the radius the gesture actually
* used (the session's world radius in the viewport, the editor's texel radius in the UV editor)
* and the defaults standing in for the curve and the flag while the state is off.
*
* @param ProportionalEditState? state The session's proportional state, or null while off.
* @param Float radius The radius the gesture ran with, in the gesture space's units.
* @return ProportionalRows The rows.
*/
fun of(state: ProportionalEditState?, radius: Float): ProportionalRows =
ProportionalRows(
enabled = state != null,
falloff = state?.falloff ?: ProportionalFalloff.Smooth,
radius = radius,
connectedOnly = state?.connectedOnly ?: false,
)
}
}
/**
* The strip's rows for a Grab / Rotate / Scale that landed with [parameters]: the move's two
* components, the angle in degrees, or the two factors, followed by the proportional rows when the
* gesture could take weights. A Vertex Slide has no rows here (see [slideParameters]).
*
* @param MeshOperatorKind kind The operator that ran.
* @param TransformGestureParameters parameters The numbers it landed with, in the gesture space's units.
* @param TransformRowSpace space The space the rows read in.
* @param ProportionalRows? proportional The proportional rows, or null when the gesture took no
* weights (Object mode, a suppressed auto-grab).
* @return List The rows, empty for an operator that has none.
*/
fun transformParameters(
kind: MeshOperatorKind,
parameters: TransformGestureParameters,
space: TransformRowSpace,
proportional: ProportionalRows?,
): List<OperatorParameter> {
val rows = ArrayList<OperatorParameter>()
when (kind) {
MeshOperatorKind.Grab -> {
rows.add(moveRow(TransformParameterKeys.MOVE_X, parameters.deltaX))
rows.add(moveRow(space.verticalMoveKey, space.rowVertical(parameters.deltaY)))
}
MeshOperatorKind.Rotate ->
rows.add(
OperatorParameter.FloatParameter(
TransformParameterKeys.ANGLE,
TransformParameterKeys.ANGLE,
space.rowDegrees(parameters.rotationRadians),
-TRANSFORM_ANGLE_LIMIT,
TRANSFORM_ANGLE_LIMIT,
unit = ParameterUnit.Degrees,
),
)
MeshOperatorKind.Scale -> {
rows.add(scaleRow(TransformParameterKeys.SCALE_X, parameters.factorX))
rows.add(scaleRow(space.verticalScaleKey, parameters.factorY))
}
MeshOperatorKind.VertexSlide -> return emptyList()
}
if (proportional != null) {
rows.addAll(proportionalParameters(proportional))
}
return rows
}
/**
* The gesture parameters the strip's rows mean - the inverse of [transformParameters], back into the
* gesture space's form the operator math takes. A missing row reads as identity, so the rows of one
* operator never move another.
*
* @param MeshOperatorKind kind The operator the rows belong to.
* @param TransformRowSpace space The space the rows read in.
* @param List parameters The rows, possibly edited.
* @return TransformGestureParameters The parameters to apply.
*/
fun transformGestureParametersOf(
kind: MeshOperatorKind,
space: TransformRowSpace,
parameters: List<OperatorParameter>,
): TransformGestureParameters =
when (kind) {
MeshOperatorKind.Grab ->
TransformGestureParameters(
deltaX = parameters.floatValue(TransformParameterKeys.MOVE_X, 0f),
deltaY = space.rowVertical(parameters.floatValue(space.verticalMoveKey, 0f)),
factorX = 1f,
factorY = 1f,
rotationRadians = 0f,
)
MeshOperatorKind.Rotate ->
TransformGestureParameters(
deltaX = 0f,
deltaY = 0f,
factorX = 1f,
factorY = 1f,
rotationRadians = space.radiansOfRow(parameters.floatValue(TransformParameterKeys.ANGLE, 0f)),
)
MeshOperatorKind.Scale ->
TransformGestureParameters(
deltaX = 0f,
deltaY = 0f,
factorX = parameters.floatValue(TransformParameterKeys.SCALE_X, 1f),
factorY = parameters.floatValue(space.verticalScaleKey, 1f),
rotationRadians = 0f,
)
MeshOperatorKind.VertexSlide -> TransformGestureParameters.IDENTITY
}
/**
* The proportional rows the strip's rows carry, or null when the gesture registered none.
*
* @param List parameters The rows, possibly edited.
* @return ProportionalRows? The rows' values, or null.
*/
fun proportionalRowsOf(parameters: List<OperatorParameter>): ProportionalRows? {
if (parameters.none { parameter -> parameter.key == TransformParameterKeys.PROPORTIONAL }) {
return null
}
val falloffKey = parameters.choiceValue(TransformParameterKeys.FALLOFF, ProportionalFalloff.Smooth.choiceKey)
return ProportionalRows(
enabled = parameters.booleanValue(TransformParameterKeys.PROPORTIONAL, false),
falloff = ProportionalFalloff.entries.firstOrNull { falloff -> falloff.choiceKey == falloffKey } ?: ProportionalFalloff.Smooth,
radius = parameters.floatValue(TransformParameterKeys.PROPORTIONAL_SIZE, MIN_PROPORTIONAL_RADIUS_WORLD),
connectedOnly = parameters.booleanValue(TransformParameterKeys.CONNECTED_ONLY, false),
)
}
/**
* Re-derives [transform]'s proportional halos from its frozen positions under the rows' proportional
* settings, when the rows carry any: the entries' influence and moved sets change with the radius,
* curve, and flag. For a rerun over a RETAINED capture, which is no longer live, so rewriting its
* halos is safe.
*
* @param ModalTransformCapture transform The frozen capture.
* @param List parameters The rows, possibly edited.
* @return ProportionalRows? The rows the halos were derived under, or null when the rows carry none
* (the capture is left as it was).
*/
fun rederiveProportionalHalos(transform: ModalTransformCapture, parameters: List<OperatorParameter>): ProportionalRows? {
val rows = proportionalRowsOf(parameters) ?: return null
val state = rows.asState()
transform.applyProportional(state, state?.radiusWorld ?: 0f)
return rows
}
/**
* The strip's one row for a Vertex Slide: how far along its edge the vertex landed.
*
* @param Float factor The landed factor in [0, 1].
* @return List The Factor row.
*/
fun slideParameters(factor: Float): List<OperatorParameter> =
listOf(OperatorParameter.FloatParameter(TransformParameterKeys.SLIDE_FACTOR, TransformParameterKeys.SLIDE_FACTOR, factor, 0f, 1f, SLIDE_FACTOR_STEP))
/** The stable choice key of a falloff curve, as the Falloff row stores it. */
val ProportionalFalloff.choiceKey: String
get() = name.lowercase()
/** The proportional rows: the flag, the curve, the size, and Connected Only. */
private fun proportionalParameters(proportional: ProportionalRows): List<OperatorParameter> =
listOf(
OperatorParameter.BooleanParameter(TransformParameterKeys.PROPORTIONAL, TransformParameterKeys.PROPORTIONAL, proportional.enabled),
OperatorParameter.ChoiceParameter(
TransformParameterKeys.FALLOFF,
TransformParameterKeys.FALLOFF,
proportional.falloff.choiceKey,
ProportionalFalloff.entries.map { falloff -> ParameterChoice(falloff.choiceKey, TransformParameterKeys.FALLOFF_CHOICE_PREFIX + falloff.choiceKey) },
),
OperatorParameter.FloatParameter(
TransformParameterKeys.PROPORTIONAL_SIZE,
TransformParameterKeys.PROPORTIONAL_SIZE,
proportional.radius,
MIN_PROPORTIONAL_RADIUS_WORLD,
MAX_PROPORTIONAL_RADIUS_WORLD,
PROPORTIONAL_SIZE_STEP,
ParameterUnit.Pixels,
),
OperatorParameter.BooleanParameter(TransformParameterKeys.CONNECTED_ONLY, TransformParameterKeys.CONNECTED_ONLY, proportional.connectedOnly),
)
/** A Move row in the gesture space's pixel units. */
private fun moveRow(key: String, value: Float): OperatorParameter =
OperatorParameter.FloatParameter(key, key, value, -TRANSFORM_MOVE_LIMIT, TRANSFORM_MOVE_LIMIT, unit = ParameterUnit.Pixels)
/** A Scale row. */
private fun scaleRow(key: String, value: Float): OperatorParameter =
OperatorParameter.FloatParameter(key, key, value, TRANSFORM_SCALE_MIN, TRANSFORM_SCALE_MAX, TRANSFORM_SCALE_STEP)
/** The key of the vertical Move row: Z in world space, Y on the page. */
private val TransformRowSpace.verticalMoveKey: String
get() =
when (this) {
TransformRowSpace.World -> TransformParameterKeys.MOVE_Z
TransformRowSpace.UvDisplay -> TransformParameterKeys.MOVE_Y
}
/** The key of the vertical Scale row: Z in world space, Y on the page. */
private val TransformRowSpace.verticalScaleKey: String
get() =
when (this) {
TransformRowSpace.World -> TransformParameterKeys.SCALE_Z
TransformRowSpace.UvDisplay -> TransformParameterKeys.SCALE_Y
}
/**
* The vertical component as the row reads it - and, being its own inverse, as the gesture reads a
* row: world y is up and shown as-is; display y is flipped to read down like the page.
*/
private fun TransformRowSpace.rowVertical(value: Float): Float =
when (this) {
TransformRowSpace.World -> value
TransformRowSpace.UvDisplay -> -value
}
/** The angle row for a gesture rotation: degrees, with the page space's sign flip. */
private fun TransformRowSpace.rowDegrees(rotationRadians: Float): Float = rowVertical((rotationRadians * 180.0 / PI).toFloat())
/** The gesture rotation an angle row means: the inverse of [rowDegrees]. */
private fun TransformRowSpace.radiansOfRow(degrees: Float): Float = (rowVertical(degrees) * PI / 180.0).toFloat()
@@ -0,0 +1,325 @@
package org.umamo.edit
import org.umamo.runtime.model.PuppetModel
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.round
import kotlin.math.sin
/**
* The default major grid spacing in world units (canvas px): the built-in fallback value for
* [GridConfig.scale] when neither a settings default (settings key viewport.grid.scale) nor a per-file
* value has been resolved. The grid snaps round to the finest subdivision, not to this spacing
* directly - see [GridConfig.snapStep].
*/
const val SNAP_GRID_WORLD_UNITS = 100f
/**
* The default number of minor subdivisions per major grid cell: the built-in fallback for
* [GridConfig.subdivisions] (settings key viewport.grid.subdivisions).
*/
const val DEFAULT_GRID_SUBDIVISIONS = 10
/**
* The viewport grid's geometry: the major line spacing in world units and how many minor
* (subdivision) lines divide each major cell. Drives both the drawn backdrop grid and the grid snap.
* Held per document: seeded from the global-default settings, or from the document's own value when a `.uma`
* saved one (docs/format/UMA.md § 7.4); CMO3 and MOC3 store no grid and keep the default.
*
* @property Float scale The major grid line spacing, in world units.
* @property Int subdivisions The minor lines per major cell (must be at least 1).
*/
data class GridConfig(
val scale: Float = SNAP_GRID_WORLD_UNITS,
val subdivisions: Int = DEFAULT_GRID_SUBDIVISIONS,
) {
/**
* The grid snap increment in world units: the finest visible spacing (major / subdivisions), so
* Selection- and Cursor-to-Grid round to the minor grid lines the backdrop draws. Subdivisions is
* clamped to at least 1 so the step is always a positive, finite value.
*/
val snapStep: Float
get() = scale / subdivisions.coerceAtLeast(1)
}
/**
* Rounds a world coordinate to the nearest grid line, measured from [origin] (the world origin the grid
* is drawn around) rather than from world 0, so a snap lands on the same lines the backdrop grid draws.
*
* @param Float value The world coordinate to snap.
* @param Float origin The world origin the grid lattice is anchored on (a line passes through it).
* @param Float step The grid snap increment (see [GridConfig.snapStep]).
* @return Float The snapped world coordinate.
*/
fun snapToGrid(value: Float, origin: Float, step: Float): Float = round((value - origin) / step) * step + origin
/**
* Rounds a world point to the nearest intersection of the model's world grid - the lattice the backdrop
* draws, anchored on the world origin. Both axes in one call, so a caller cannot anchor x on the origin's
* z or the reverse.
*
* @param Float worldX The world x to snap.
* @param Float worldZ The world z (up) to snap.
* @param Float step The grid snap increment (see [GridConfig.snapStep]).
* @return Pair<Float, Float> The snapped world (x, z).
*/
fun PuppetModel.snapToWorldGrid(worldX: Float, worldZ: Float, step: Float): Pair<Float, Float> =
snapToGrid(worldX, worldOriginX, step) to snapToGrid(worldZ, worldOriginZ, step)
/**
* The 2D cursor: a placeable world-space anchor, the 2D analog of Blender's 3D cursor. Placed with
* Shift+RightClick in the viewport, drawn by the HUD overlay, usable as a transform pivot
* ([TransformPivotMode.Cursor]) and as the source / target of the Shift+S snap operations. Session
* state, transient by design: cursor moves are deliberately NOT undo steps (they ride outside
* [EditorSnapshot]), and the snap menu makes recovering a lost placement cheap.
*
* 2D カーソル。Blender の 3D カーソルの 2D 版。ピボットやスナップの基準点になるワールド座標の
* アンカー。取り消し履歴には乗らない一時状態。
*
* @property Float worldX The cursor's world-space x.
* @property Float worldZ The cursor's world-space z (up).
*/
data class Cursor2d(val worldX: Float, val worldZ: Float)
/**
* The UV editor's own 2D cursor: a placeable anchor in normalized atlas coordinates, the texture-space
* sibling of [Cursor2d] (Blender's UV editor likewise carries its own cursor, separate from the 3D
* one). Placed with Shift+RightClick in the UV editor, drawn by its overlay, and read as the UV
* transform pivot in [TransformPivotMode.Cursor]. Session state, transient by design like [Cursor2d]:
* cursor moves are deliberately NOT undo steps.
*
* UV エディタ専用の 2D カーソル。正規化アトラス座標のアンカーで、UV 変形のカーソルピボットになる。
* 取り消し履歴には乗らない一時状態。
*
* @property Float u The cursor's normalized atlas u coordinate.
* @property Float v The cursor's normalized atlas v coordinate.
*/
data class UvCursor(val u: Float, val v: Float)
/**
* What a modal Scale / Rotate turns the selection about (Blender's pivot point selector, the Period
* pie). MedianPoint is the covered vertices' centroid (the default); IndividualOrigins splits the
* selection into connectivity islands (edit mode) or per drawable (object mode), each turning about
* its own centroid; ActiveElement anchors on the active element (or active drawable); Cursor anchors
* on the 2D cursor.
*
* 変形の基準点の種類(Blender のピボットポイント)。中点・各自の原点・アクティブ要素・2D カーソル。
*/
enum class TransformPivotMode {
MedianPoint,
IndividualOrigins,
ActiveElement,
Cursor,
}
/**
* The axis a modal Grab / Scale is locked to, toggled by pressing X or Z during the gesture (Blender's
* axis constraint; Rotate is excluded - there is only one 2D rotation axis). Named by the DISPLAYED
* axes: the project presents the 2D plane as X (horizontal) and Z (vertical, world +y) per the
* Y+ forward, Z+ up convention, so AxisZ constrains the position arrays' y coordinates.
*
* モーダル変形の軸ロック(X / Z キー)。表示規約は Y+ 前、Z+ 上なので、AxisZ は配列の y 成分に対応する。
*/
enum class TransformAxisConstraint {
AxisX,
AxisZ,
}
/**
* Which radial pie menu is open over the viewport, or none (null in the session flow). The pie
* entries dispatch through the command registry; the session only coordinates which pie is showing
* (a transient latch like the modal operators).
*
* 表示中のパイメニューの種類。エントリはコマンドレジストリ経由で実行される。
*/
enum class PieMenuKind {
PivotMode,
Snap,
UvSnap,
MergeTarget,
}
/**
* A latched modal transform operator together with the viewport area that initiated it. The area id
* is an opaque workspace-leaf id (the same currency as [EditorSession.zoomRegionArmedArea]): the
* session never interprets it, but the UI gates gesture capture, HUD drawing, and confirm delivery to
* the initiating area, so a gesture latched in one split viewport can never be driven or committed
* from another. Both fields publish atomically in one flow emission - a paired flow could tear.
*
* ラッチされたモーダル変形操作と、それを開始したビューポートエリア。エリア ID は不透明な文字列で、
* UI 側がジェスチャの捕捉・HUD 描画・確定の配送を開始エリアに限定するために使う。
*
* @property MeshOperatorKind kind The latched operator (Grab / Scale / Rotate / VertexSlide).
* @property String areaId The initiating viewport's area id.
*/
data class ActiveOperator(
val kind: MeshOperatorKind,
val areaId: String,
)
/**
* The geometry-dependent snap operations (Blender's Shift+S) the viewport overlay executes: the
* cursor-to-geometry moves need the posed world projection and the selection-to-target moves edit the
* model through the deformer-chain inverse, both of which live with the overlay - so the session
* carries the request and the active mode's overlay performs it. The purely arithmetical snaps
* (cursor to world origin / to grid) are handled directly by their command handlers and never appear
* here.
*
* ジオメトリ依存のスナップ操作の種類。オーバーレイが実行する。
*/
enum class SnapKind {
CursorToSelected,
CursorToActive,
SelectionToCursor,
SelectionToCursorOffset,
SelectionToGrid,
SelectionToActive,
}
/**
* The UV editor's snap operations (its own Shift+S pie), the texture-space sibling of [SnapKind].
* Every one edits or reads in the UV editor's texel display space, so the UV overlay - which owns the
* shown page's dimensions and display geometry - executes them, the same request-through-overlay split
* as [SnapKind]. The op set differs from the world snaps by design: UV has pixel-corner snaps (a
* texel boundary is a natural target for artwork-edge accuracy) and no Active-element snaps, while the
* world grid has no meaning here (the UV grid subdivides the atlas page instead - see the UV editor's
* display mapping).
*
* UV エディタのスナップ操作の種類。テクセル表示空間で動作し、UV オーバーレイが実行する。
*/
enum class UvSnapKind {
SelectionToPixels,
SelectionToCursor,
SelectionToCursorOffset,
SelectionToGrid,
CursorToPixels,
CursorToSelected,
CursorToGrid,
}
/**
* One pivot group of a modal transform: a set of vertices turning about one pivot. Median / Active /
* Cursor pivot modes produce a single group per mesh (every covered vertex about the one shared
* anchor); IndividualOrigins produces one group per connectivity island (edit mode) or per drawable
* (object mode), each about its own centroid.
*
* 変形のピボットグループ。1つのピボットを共有する頂点集合。各自の原点モードでは島ごとに分かれる。
*
* @property Set<Int> vertexIndices The group's vertex indices (into the mesh's interleaved array).
* @property Float pivotX The group pivot's x, in the positions' coordinate space.
* @property Float pivotY The group pivot's y, in the positions' coordinate space.
*/
data class TransformPivotGroup(
val vertexIndices: Set<Int>,
val pivotX: Float,
val pivotY: Float,
)
/**
* Pure pivot-group builders for the modal transforms (the [TransformPivotMode] machinery).
*
* ピボットグループの純粋な構築関数。
*/
object TransformPivots {
/**
* One group turning every covered vertex about a shared anchor - the shape Median Point, Active
* Element, and Cursor pivots all reduce to (they differ only in where the anchor is).
*
* @param Set<Int> coveredIndices The vertices the gesture moves.
* @param Float pivotX The shared anchor's x.
* @param Float pivotY The shared anchor's y.
* @return List<TransformPivotGroup> The single shared-pivot group.
*/
fun sharedGroup(coveredIndices: Set<Int>, pivotX: Float, pivotY: Float): List<TransformPivotGroup> =
listOf(TransformPivotGroup(coveredIndices, pivotX, pivotY))
/**
* Per-island groups for Individual Origins in edit mode: the covered vertices split into
* connectivity islands (components of the sub-graph the selection induces), each turning about its
* own centroid.
*
* @param FloatArray positions The mesh's interleaved positions (the pivots' coordinate space).
* @param Set<Int> coveredIndices The vertices the gesture moves.
* @param IntArray triangleIndices The mesh triangle vertex indices (for connectivity).
* @return List<TransformPivotGroup> One group per island.
*/
fun islandGroups(
positions: FloatArray,
coveredIndices: Set<Int>,
triangleIndices: IntArray,
): List<TransformPivotGroup> {
val vertexCount = positions.size / 2
val adjacency = MeshTopology.buildVertexAdjacency(vertexCount, triangleIndices)
return MeshTopology.selectionIslands(adjacency, coveredIndices).map { island ->
val pivot = MeshTransforms.medianPivot(positions, island)
TransformPivotGroup(island, pivot.first, pivot.second)
}
}
/**
* Splits a proportional influence map into per-group weight maps, index-parallel to [groups]: each
* influenced vertex follows the pivot group that OWNS its nearest covered vertex, so with Individual
* Origins the halo around an island turns about that island's pivot, not the shared gesture anchor.
* With a single shared group everything lands in it (whose pivot IS the gesture anchor), so the
* shared-pivot modes keep their behavior. An influence whose nearest covered vertex is in no group
* (impossible today - the groups partition the covered set) falls into the first group rather than
* dropping motion.
*
* @param Map<Int, ProportionalInfluence> influences The influenced vertices (weight + nearest covered).
* @param List<TransformPivotGroup> groups The gesture's pivot groups.
* @return List<Map<Int, Float>> One weight map per group, parallel to [groups].
*/
fun partitionInfluencesByGroup(
influences: Map<Int, ProportionalInfluence>,
groups: List<TransformPivotGroup>,
): List<Map<Int, Float>> {
if (groups.isEmpty()) {
return emptyList()
}
val partitions = List(groups.size) { LinkedHashMap<Int, Float>() }
for ((vertexIndex, influence) in influences) {
val ownerIndex = groups.indexOfFirst { group -> influence.nearestCoveredIndex in group.vertexIndices }
partitions[if (ownerIndex >= 0) ownerIndex else 0][vertexIndex] = influence.weight
}
return partitions
}
}
/**
* Accumulates a modal rotate gesture's angle from per-move increments, each wrapped into (-pi, pi], so
* the total walks smoothly through the atan2 branch cut at +-pi and supports multi-turn rotation. A
* raw start-to-current atan2 subtraction cannot: a far pivot (the 2D cursor off to the side) places the
* start angle right AT the cut, where the difference jumps by ~2*pi and the gesture's arc direction
* latches (it can never reverse past its start). One tracker lives per gesture capture; feeding the
* same pointer angle twice adds zero, so re-derives without pointer motion are safe.
*/
class RotationAngleTracker {
private var previousPointerAngle: Float? = null
/** The accumulated gesture angle in radians (screen-space sign; the caller negates into world space). */
var totalAngle: Float = 0f
private set
/**
* Advances the accumulator to the pointer's current angle about the pivot and returns the total.
*
* @param Float pointerAngle The pointer's atan2 angle about the rotation pivot, radians.
* @return Float The accumulated gesture angle, radians.
*/
fun advance(pointerAngle: Float): Float {
val previous = previousPointerAngle
if (previous != null) {
totalAngle += wrapAngle(pointerAngle - previous)
}
previousPointerAngle = pointerAngle
return totalAngle
}
}
/**
* Wraps an angle difference into (-pi, pi] - the shortest signed arc between two angles.
*
* @param Float delta The raw angle difference, radians.
* @return Float The wrapped difference.
*/
fun wrapAngle(delta: Float): Float = atan2(sin(delta), cos(delta))
@@ -0,0 +1,81 @@
package org.umamo.edit
/**
* A change of texture-coordinate frame: how the stored uvs relate to the space an edit is authored in.
*
* The UV editor shows a drawable's mapping over two different surfaces - the packed atlas page it is
* stored against, and the source artwork it was authored against - and an operation expressed in
* normalized coordinates (Mirror is the only one) means something different in each. Handing the
* operation this pair lets it work in whichever frame the user is looking at while still committing
* the stored form.
*
* Both members are 2x3 affines (m00, m01, m02, m10, m11, m12) over normalized coordinates, mutual
* inverses. A page-view edit passes no frame at all rather than an identity pair, so that path stays
* bit-identical to having no frame concept.
*
* A plain class, not a data class: the fields are arrays, whose identity-based equals would make a
* generated structural equals quietly wrong. Never use one as a snapshot or effect key - key on the
* scalars it was built from.
*/
class UvFrame(private val toFrameAffine: FloatArray, private val fromFrameAffine: FloatArray) {
/**
* Maps stored coordinates into the authoring frame.
*
* @param FloatArray uvs The stored coordinates, interleaved (u, v).
* @return FloatArray The frame coordinates, a fresh array.
*/
fun toFrame(uvs: FloatArray): FloatArray = applyAffine(uvs, toFrameAffine)
/**
* Maps authoring-frame coordinates back to the stored form.
*
* @param FloatArray uvs The frame coordinates, interleaved (u, v).
* @return FloatArray The stored coordinates, a fresh array.
*/
fun fromFrame(uvs: FloatArray): FloatArray = applyAffine(uvs, fromFrameAffine)
/**
* Maps one stored point into the authoring frame.
*
* @param Float u The stored u.
* @param Float v The stored v.
* @return Pair<Float, Float> The point in frame coordinates.
*/
fun pointToFrame(u: Float, v: Float): Pair<Float, Float> =
(toFrameAffine[0] * u + toFrameAffine[1] * v + toFrameAffine[2]) to
(toFrameAffine[3] * u + toFrameAffine[4] * v + toFrameAffine[5])
/**
* Maps one authoring-frame point back to the stored form.
*
* @param Float u The frame u.
* @param Float v The frame v.
* @return Pair<Float, Float> The point in stored coordinates.
*/
fun pointFromFrame(u: Float, v: Float): Pair<Float, Float> =
(fromFrameAffine[0] * u + fromFrameAffine[1] * v + fromFrameAffine[2]) to
(fromFrameAffine[3] * u + fromFrameAffine[4] * v + fromFrameAffine[5])
/**
* Maps a whole interleaved uv array through a 2x3 row-major affine, into a fresh array.
*
* A trailing odd component is left out rather than half-mapped: the arrays are interleaved pairs, so
* an odd length is malformed input, and the callers' own guards reject it upstream.
*
* @param FloatArray uvs The interleaved (u, v) pairs to map.
* @param FloatArray affine The 2x3 row-major affine (m00, m01, m02, m10, m11, m12).
* @return FloatArray The mapped pairs, in a new array of the same length.
*/
private fun applyAffine(uvs: FloatArray, affine: FloatArray): FloatArray {
val mapped = FloatArray(uvs.size)
var componentIndex = 0
while (componentIndex + 1 < uvs.size) {
val u = uvs[componentIndex]
val v = uvs[componentIndex + 1]
mapped[componentIndex] = affine[0] * u + affine[1] * v + affine[2]
mapped[componentIndex + 1] = affine[3] * u + affine[4] * v + affine[5]
componentIndex += 2
}
return mapped
}
}
@@ -0,0 +1,47 @@
package org.umamo.edit
import org.umamo.runtime.model.PuppetModel
/*
* Selection-aware visibility helpers, bridging the object-mode Selection to the per-entity visibility
* transforms. Kept here (not in the UI) so the "toggle visibility of the selection" command is a thin
* dispatch and the model logic stays pure and testable.
*
* 選択に対する表示切り替えの補助。UI ではなくここに置き、コマンドは委譲だけにする。
*/
/**
* The current Parts-panel visibility of [target] in [this]. A deformer has no visibility flag, so it
* reports true (it is never "hidden"); a missing part/drawable also reports true.
*
* @param SelectionTarget target The entity to query.
* @return Boolean The entity's visibility (true when it has none).
*/
fun PuppetModel.visibilityOf(target: SelectionTarget): Boolean =
when (target) {
is SelectionTarget.Part -> parts.firstOrNull { it.id == target.id }?.isVisible ?: true
is SelectionTarget.Drawable -> drawables.firstOrNull { it.id == target.id }?.isVisible ?: true
is SelectionTarget.Deformer -> true
}
/**
* Returns a copy of [this] with every part and drawable in [targets] set to [visible], structurally
* sharing untouched entities; deformer targets are skipped (they have no visibility flag). Folding all
* targets into one model makes the whole multi-selection toggle a single undo step.
*
* @param Set targets The selected targets to retoggle.
* @param Boolean visible The new visibility.
* @return PuppetModel The model with those entities' visibility updated.
*/
fun PuppetModel.withSelectionVisibility(targets: Set<SelectionTarget>, visible: Boolean): PuppetModel {
var next = this
for (target in targets) {
next =
when (target) {
is SelectionTarget.Part -> next.withPartVisibility(target.id, visible)
is SelectionTarget.Drawable -> next.withDrawableVisibility(target.id, visible)
is SelectionTarget.Deformer -> next
}
}
return next
}
@@ -0,0 +1,243 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendShapeBinding
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.WarpForm
import org.umamo.runtime.model.WarpLatticeForm
import kotlin.math.min
/*
* Resizing a warp deformer's conversion-division grid: every keyform lattice (and every blend-shape
* absolute lattice) is resampled through the old surface so the art does not jump. Child drawable UVs
* stay in the deformer's unit square, so they need no rewrite.
*
* ワープ格子の分割数変更。旧格子をサンプリングしてキーフォームを再標本化する。
*/
/** Smallest conversion-division count the properties slider / create path allow. */
const val MIN_WARP_DIVISIONS = 2
/** Largest conversion-division count the properties slider allows (Cubism-style upper end). */
const val MAX_WARP_DIVISIONS = 16
/**
* Clamps a conversion-division count into [[MIN_WARP_DIVISIONS], [MAX_WARP_DIVISIONS]].
*
* @param Int divisions The requested count.
* @return Int The clamped count.
*/
fun clampWarpDivisions(divisions: Int): Int = divisions.coerceIn(MIN_WARP_DIVISIONS, MAX_WARP_DIVISIONS)
/**
* Samples an absolute warp lattice at normalized UV ([0,1] inclusive) through the same bilinear /
* triangle-split blend the runtime uses for in-grid points. Boundary UVs land on the last row /
* column (inclusive), which [org.umamo.render.eval.warpInGrid]'s half-open `[0,1)` path would miss.
*
* @param FloatArray controlPoints Old lattice, `(columns+1)×(rows+1)` interleaved x,y.
* @param Int columns Old conversion divisions horizontally.
* @param Int rows Old conversion divisions vertically.
* @param Boolean bilinear Quad blend (true) vs triangle split (false).
* @param Float u Normalized horizontal coordinate in `[0,1]`.
* @param Float v Normalized vertical coordinate in `[0,1]`.
* @param FloatArray out Destination for the sampled point.
* @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`).
*/
fun sampleWarpLattice(
controlPoints: FloatArray,
columns: Int,
rows: Int,
bilinear: Boolean,
u: Float,
v: Float,
out: FloatArray,
outIndex: Int,
) {
val cols = columns.coerceAtLeast(1)
val rowCount = rows.coerceAtLeast(1)
val uu = u.coerceIn(0f, 1f)
val vv = v.coerceIn(0f, 1f)
val pointsPerRow = cols + 1
val gridU = cols * uu
val gridV = rowCount * vv
val cellCol = min(gridU.toInt(), cols - 1)
val cellRow = min(gridV.toInt(), rowCount - 1)
val cellU = (gridU - cellCol).coerceIn(0f, 1f)
val cellV = (gridV - cellRow).coerceIn(0f, 1f)
val cellIndex = cellRow * pointsPerRow + cellCol
val p00 = cellIndex * 2
val p10 = (cellIndex + 1) * 2
val p01 = (cellIndex + pointsPerRow) * 2
val p11 = (cellIndex + pointsPerRow + 1) * 2
if (!bilinear) {
if (cellU + cellV <= 1f) {
out[outIndex] = controlPoints[p10] * cellU + controlPoints[p00] * (1 - cellU - cellV) + controlPoints[p01] * cellV
out[outIndex + 1] =
(1 - cellU - cellV) * controlPoints[p00 + 1] + controlPoints[p10 + 1] * cellU + controlPoints[p01 + 1] * cellV
} else {
val weight = (cellU - 1) + cellV
out[outIndex] = controlPoints[p01] * (1 - cellU) + controlPoints[p11] * weight + controlPoints[p10] * (1 - cellV)
out[outIndex + 1] =
weight * controlPoints[p11 + 1] + (1 - cellU) * controlPoints[p01 + 1] + (1 - cellV) * controlPoints[p10 + 1]
}
} else {
val invCellV = 1 - cellV
out[outIndex] =
controlPoints[p10] * cellU * invCellV +
controlPoints[p00] * (1 - cellU) * invCellV +
controlPoints[p01] * (1 - cellU) * cellV +
controlPoints[p11] * cellU * cellV
out[outIndex + 1] =
invCellV * controlPoints[p10 + 1] * cellU +
controlPoints[p00 + 1] * (1 - cellU) * invCellV +
(1 - cellU) * controlPoints[p01 + 1] * cellV +
cellU * controlPoints[p11 + 1] * cellV
}
}
/**
* Builds a new lattice by sampling [controlPoints] at the UV of every new control point.
*
* @param FloatArray controlPoints Old lattice control points.
* @param Int oldRows Old conversion divisions vertically.
* @param Int oldColumns Old conversion divisions horizontally.
* @param Boolean bilinear The warp's interpolation mode.
* @param Int newRows New conversion divisions vertically.
* @param Int newColumns New conversion divisions horizontally.
* @return FloatArray Fresh interleaved control points for the new grid.
*/
fun resampleWarpLatticeControlPoints(
controlPoints: FloatArray,
oldRows: Int,
oldColumns: Int,
bilinear: Boolean,
newRows: Int,
newColumns: Int,
): FloatArray {
val pointsPerRow = newColumns + 1
val pointsPerCol = newRows + 1
val out = FloatArray(pointsPerRow * pointsPerCol * 2)
val scratch = FloatArray(2)
for (row in 0 until pointsPerCol) {
val v = row.toFloat() / newRows.coerceAtLeast(1)
for (col in 0 until pointsPerRow) {
val u = col.toFloat() / newColumns.coerceAtLeast(1)
sampleWarpLattice(controlPoints, oldColumns, oldRows, bilinear, u, v, scratch, 0)
val index = (row * pointsPerRow + col) * 2
out[index] = scratch[0]
out[index + 1] = scratch[1]
}
}
return out
}
/**
* Returns a copy of [this] with warp deformer [id]'s conversion divisions set to [rows]×[columns],
* resampling every geometry-grid cell and every blend-shape lattice through the old surface. A no-op
* (missing / non-warp deformer, unchanged size, missing lattice, or a cell whose point count does not
* match the old grid) returns the same instance. Counts are clamped to [[MIN_WARP_DIVISIONS],
* [MAX_WARP_DIVISIONS]].
*
* @param DeformerId id The warp deformer to retarget.
* @param Int rows New conversion divisions vertically.
* @param Int columns New conversion divisions horizontally.
* @return PuppetModel The model with the resized warp, or [this] if nothing changed.
*/
fun PuppetModel.withWarpDeformerGrid(
id: DeformerId,
rows: Int,
columns: Int,
): PuppetModel {
val newRows = clampWarpDivisions(rows)
val newColumns = clampWarpDivisions(columns)
val index = deformers.indexOfFirst { deformer -> deformer.id == id }
if (index < 0) {
return this
}
val deformer = deformers[index] as? Deformer.Warp ?: return this
if (deformer.rows == newRows && deformer.columns == newColumns) {
return this
}
val grid = deformer.geometryGrid ?: return this
val expectedPoints = (deformer.columns + 1) * (deformer.rows + 1) * 2
if (grid.cells.any { cell -> cell.form.controlPoints.size != expectedPoints }) {
return this
}
val resampledGrid =
KeyformGrid(
grid.axes,
grid.cells.map { cell ->
KeyformCell(
cell.coordinate.copyOf(),
WarpLatticeForm(
resampleWarpLatticeControlPoints(
cell.form.controlPoints,
deformer.rows,
deformer.columns,
deformer.isQuadTransform,
newRows,
newColumns,
),
),
)
},
)
val resampledBlendShapes =
deformer.blendShapes.map { binding ->
resampleWarpBlendBinding(binding, deformer, newRows, newColumns, expectedPoints)
}
val updated = deformers.toMutableList()
updated[index] =
deformer.copy(
rows = newRows,
columns = newColumns,
geometryGrid = resampledGrid,
blendShapes = resampledBlendShapes,
)
return copy(deformers = updated)
}
/**
* Resamples one warp blend-shape binding's absolute lattices onto the new grid. Forms whose point
* count does not match the old grid are left untouched (same refuse rule as the geometry grid).
*
* @param BlendShapeBinding binding The binding to rewrite.
* @param Deformer.Warp deformer The warp before the resize (old dimensions / mode).
* @param Int newRows New conversion divisions vertically.
* @param Int newColumns New conversion divisions horizontally.
* @param Int expectedPoints Expected interleaved float count on the old grid.
* @return BlendShapeBinding The resampled binding.
*/
private fun resampleWarpBlendBinding(
binding: BlendShapeBinding<WarpForm>,
deformer: Deformer.Warp,
newRows: Int,
newColumns: Int,
expectedPoints: Int,
): BlendShapeBinding<WarpForm> =
binding.copy(
forms =
binding.forms.map { form ->
if (form == null || form.controlPoints.size != expectedPoints) {
form
} else {
WarpForm(
controlPoints =
resampleWarpLatticeControlPoints(
form.controlPoints,
deformer.rows,
deformer.columns,
deformer.isQuadTransform,
newRows,
newColumns,
),
opacity = form.opacity,
multiplyColor = form.multiplyColor,
screenColor = form.screenColor,
)
}
},
)
@@ -0,0 +1,69 @@
package org.umamo.edit.seed
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
/**
* The humanoid parameter set: the ids, ranges, and defaults of Live2D's published Standard Parameter
* List, which every Live2D-compatible runtime, tracker, and application keys on. The ids are
* format-level identifiers and stay verbatim; the display names are English document data the
* rigger may rename.
*/
object HumanoidParameters {
/**
* One standard parameter.
*
* @param String id The format-level id, e.g. `ParamAngleX`.
* @param String name The English display name.
* @param Float min The axis minimum.
* @param Float max The axis maximum.
* @param Float default The rest value.
* @return Parameter The parameter.
*/
private fun standard(id: String, name: String, min: Float, max: Float, default: Float = 0f): Parameter =
Parameter(id = ParameterId(id), name = name, min = min, max = max, default = default)
/** The set, in the order the official parameter palette lists it. */
val list: List<Parameter> =
listOf(
standard("ParamAngleX", "Angle X", -30f, 30f),
standard("ParamAngleY", "Angle Y", -30f, 30f),
standard("ParamAngleZ", "Angle Z", -30f, 30f),
standard("ParamEyeLOpen", "Eye L Open", 0f, 1f, default = 1f),
standard("ParamEyeLSmile", "Eye L Smile", 0f, 1f),
standard("ParamEyeROpen", "Eye R Open", 0f, 1f, default = 1f),
standard("ParamEyeRSmile", "Eye R Smile", 0f, 1f),
standard("ParamEyeBallX", "Eyeball X", -1f, 1f),
standard("ParamEyeBallY", "Eyeball Y", -1f, 1f),
standard("ParamBrowLY", "Brow L Y", -1f, 1f),
standard("ParamBrowRY", "Brow R Y", -1f, 1f),
standard("ParamBrowLX", "Brow L X", -1f, 1f),
standard("ParamBrowRX", "Brow R X", -1f, 1f),
standard("ParamBrowLAngle", "Brow L Angle", -1f, 1f),
standard("ParamBrowRAngle", "Brow R Angle", -1f, 1f),
standard("ParamBrowLForm", "Brow L Form", -1f, 1f),
standard("ParamBrowRForm", "Brow R Form", -1f, 1f),
standard("ParamMouthForm", "Mouth Form", -1f, 1f),
standard("ParamMouthOpenY", "Mouth Open", 0f, 1f),
standard("ParamCheek", "Cheek", 0f, 1f),
standard("ParamBodyAngleX", "Body Rotation X", -10f, 10f),
standard("ParamBodyAngleY", "Body Rotation Y", -10f, 10f),
standard("ParamBodyAngleZ", "Body Rotation Z", -10f, 10f),
standard("ParamBreath", "Breath", 0f, 1f),
standard("ParamArmLA", "Arm L A", -10f, 10f),
standard("ParamArmRA", "Arm R A", -10f, 10f),
standard("ParamArmLB", "Arm L B", -10f, 10f),
standard("ParamArmRB", "Arm R B", -10f, 10f),
standard("ParamHandL", "Hand L", -10f, 10f),
standard("ParamHandR", "Hand R", -10f, 10f),
standard("ParamHairFront", "Hair Move Front", -1f, 1f),
standard("ParamHairSide", "Hair Move Side", -1f, 1f),
standard("ParamHairBack", "Hair Move Back", -1f, 1f),
standard("ParamHairFluffy", "Hair Fluffy", 0f, 1f),
standard("ParamShoulderY", "Shoulder Y", -10f, 10f),
standard("ParamBustX", "Bust X", -1f, 1f),
standard("ParamBustY", "Bust Y", -1f, 1f),
standard("ParamBaseX", "Base X", -30f, 30f),
standard("ParamBaseY", "Base Y", -30f, 30f),
)
}
@@ -0,0 +1,44 @@
package org.umamo.edit.seed
import org.umamo.runtime.model.Parameter
/**
* The parameter set a new model is seeded with.
*
* An enum rather than a free list so the choice persists as one settings value and a later template
* (a quadruped, a prop) is one more entry. [key] is the stored value; the entry name is Umamo's, not
* a format's. The template is data only: whoever creates the model (an artwork import, a blank
* document) resolves it to [parameters] and seeds those.
*
* @property String key The value the settings key `import.parameterTemplate` stores.
*/
enum class ParameterTemplate(val key: String) {
/** No parameters; the rigger creates every axis by hand. */
None("none"),
/** The standard humanoid set every Live2D-compatible runtime and application expects. */
Humanoid("humanoid"),
;
/** The parameters the template seeds, in the order the panel lists them. */
val parameters: List<Parameter>
get() =
when (this) {
None -> emptyList()
Humanoid -> HumanoidParameters.list
}
companion object {
/** The template that seeds a new model when nothing else is configured. */
val Default: ParameterTemplate = Humanoid
/**
* Resolves a stored key, falling back to [Default] for an unknown or absent one so a stale
* setting never leaves a new model without a template.
*
* @param String? key The stored settings value.
* @return ParameterTemplate The template.
*/
fun fromKey(key: String?): ParameterTemplate = entries.firstOrNull { template -> template.key == key } ?: Default
}
}
@@ -0,0 +1,139 @@
package org.umamo.edit
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the session half of adjusting the last operation: a registration captures the base and the
* committed change, an adjustment re-runs from that base and rewrites the operation's own step, any
* other push or a restore clears the record, a stale amend after a clear is refused, an amended step
* dirties a saved document, and a registration against the wrong model or without a push is refused.
*/
class AdjustableOperationTest {
private val partId = PartId("a")
private val widthKey = "width"
private fun model(name: String): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = listOf(Part(partId, name, children = emptyList())),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = listOf(OrgChild.Part(partId)),
rootPartId = null,
)
private fun PuppetModel.renamed(name: String): PuppetModel = copy(parts = parts.map { part -> part.copy(name = name) })
private fun liveName(session: EditorSession): String = session.model.value.parts.first().name
private fun parameters(width: Int): List<OperatorParameter> = listOf(OperatorParameter.IntParameter(widthKey, "op.width", width, 0, 100))
/**
* Runs the test's stand-in operation: renames the part to "w<width>" as one commit and registers it
* as adjustable, its rerun renaming from the BASE to the width it is given.
*
* @param EditorSession session The session to run in.
* @param Int width The operation's one setting.
* @return AdjustableOperation The live record.
*/
private fun runOperation(session: EditorSession, width: Int): AdjustableOperation {
session.mutate(PartChange.Rename(partId, "w$width")) { current -> current.renamed("w$width") }
val committed = session.model.value
return assertNotNull(
session.registerAdjustableOperation(committed, areaId = "area-1", parameters = parameters(width)) { record ->
val newWidth = record.parameters.intValue(widthKey, -1)
session.amendLastCommit(record, record.baseSnapshot.model.renamed("w$newWidth"))
},
"a registration right after the commit succeeds",
)
}
@Test
fun aRegistrationCapturesTheBaseAndTheCommittedChange() {
val session = EditorSession(model("seed"))
val record = runOperation(session, 1)
assertEquals("seed", record.baseSnapshot.model.parts.first().name, "the base is the state the operation ran from")
assertEquals("change.part.rename", record.change.labelKey)
assertEquals("area-1", record.areaId)
assertSame(record, session.adjustableOperation.value)
}
@Test
fun anAdjustmentRerunsFromTheBaseAndRewritesTheStepInPlace() {
val session = EditorSession(model("seed"))
runOperation(session, 1)
val stepsBefore = session.historyView.value.steps.size
session.adjustLastOperation(parameters(7))
assertEquals("w7", liveName(session), "the rerun landed")
assertEquals(stepsBefore, session.historyView.value.steps.size, "the stack did not grow")
assertFalse(session.canRedo.value)
assertEquals(parameters(7), assertNotNull(session.adjustableOperation.value).parameters, "the record shows the new settings")
session.undo()
assertEquals("seed", liveName(session), "one undo returns to the base")
assertFalse(session.canUndo.value)
session.redo()
assertEquals("w7", liveName(session), "redo returns the adjusted result")
}
@Test
fun anyOtherPushClearsTheRecord() {
val session = EditorSession(model("seed"))
runOperation(session, 1)
session.mutate(PartChange.Rename(partId, "other")) { current -> current.renamed("other") }
assertNull(session.adjustableOperation.value, "another commit ends the adjustable operation")
}
@Test
fun aRestoreClearsTheRecordAndAStaleAmendIsRefused() {
val session = EditorSession(model("seed"))
val record = runOperation(session, 1)
session.undo()
assertNull(session.adjustableOperation.value, "undo ends the adjustable operation")
assertFalse(session.amendLastCommit(record, model("stale")), "a rerun completing after the clear is dropped")
assertEquals("seed", liveName(session), "nothing was published")
session.adjustLastOperation(parameters(9))
assertEquals("seed", liveName(session), "adjusting with no record is a no-op")
}
@Test
fun anAmendedStepDirtiesASavedDocument() {
val session = EditorSession(model("seed"))
runOperation(session, 1)
session.markSaved()
assertFalse(session.dirty.value)
session.adjustLastOperation(parameters(2))
assertTrue(session.dirty.value, "the adjusted result is unsaved content")
}
@Test
fun aRegistrationIsRefusedWithoutACommitOrAgainstAnotherModel() {
val fresh = EditorSession(model("seed"))
assertNull(fresh.registerAdjustableOperation(fresh.model.value, null, parameters(1)) {}, "nothing was pushed")
val session = EditorSession(model("seed"))
session.mutate(PartChange.Rename(partId, "w1")) { current -> current.renamed("w1") }
assertNull(session.registerAdjustableOperation(model("elsewhere"), null, parameters(1)) {}, "the live model is not the one claimed")
assertNotNull(session.registerAdjustableOperation(session.model.value, null, parameters(1)) {}, "the right model registers")
assertNull(session.registerAdjustableOperation(session.model.value, null, parameters(1)) {}, "a second registration for the same push is refused")
}
}
@@ -0,0 +1,335 @@
package org.umamo.edit
import org.umamo.runtime.model.ArtSource
import org.umamo.runtime.model.ArtSourceId
import org.umamo.runtime.model.ArtSourceLayer
import org.umamo.runtime.model.ArtworkAdditions
import org.umamo.runtime.model.ArtworkReload
import org.umamo.runtime.model.AtlasTile
import org.umamo.runtime.model.AtlasTileId
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.OrgInsertion
import org.umamo.runtime.model.OrgSlot
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetAtlas
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.RenderDrawable
import org.umamo.runtime.model.ReplacedTile
import org.umamo.runtime.model.SourceLayerRef
import org.umamo.runtime.model.deriveRenderRoot
import org.umamo.runtime.model.withDerivedRenderRoot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* The three artwork edits: rebinding a tile to a source layer, appending an artwork file's
* additions, and applying a reload. All refuse rather than half-apply - a binding to an unlisted
* file, an addition or replacement whose ids collide, a reload naming a tile or file the model lacks -
* so the Sources space and the artwork flows can trust a returned model.
*/
class ArtworkEditsTest {
private val sourceA = ArtSource(ArtSourceId("art-0"), "a.psd", "/a.psd", "psd", listOf(ArtSourceLayer("lyid:1", "L1", "", 0, 0, 4, 4, true)))
private val refA1 = SourceLayerRef(ArtSourceId("art-0"), "lyid:1", stableKey = true)
private fun quad(): DrawableMesh = DrawableMesh(floatArrayOf(0f, 0f, 4f, 0f, 4f, 4f, 0f, 4f), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3))
private fun drawable(id: String, tileId: String): Drawable =
Drawable(DrawableId(id), id, null, BlendMode.Normal, emptyList(), quad(), null, atlasTileId = AtlasTileId(tileId))
private fun model(): PuppetModel {
val drawable = drawable("ArtMesh1", "art-0/lyid:1")
return PuppetModel(
parameters = emptyList(),
parts = listOf(Part(PartId("Part1"), "Folder", listOf(OrgChild.Drawable(drawable.id)))),
deformers = emptyList(),
drawables = listOf(drawable),
rootChildren = listOf(OrgChild.Part(PartId("Part1"))),
rootPartId = null,
atlas = PuppetAtlas(tiles = listOf(AtlasTile(AtlasTileId("art-0/lyid:1"), "L1", 4, 4, source = refA1))),
sources = listOf(sourceA),
)
}
@Test
fun aTileRebindsToAListedSourceAndUnbinds() {
val base = model()
val other = SourceLayerRef(ArtSourceId("art-0"), "lyid:2", stableKey = true)
val rebound = base.withTileSource(AtlasTileId("art-0/lyid:1"), other)
assertEquals(other, rebound.atlas.tiles.single().source)
assertSame(base.drawables, rebound.drawables, "a rebind moves nothing else")
val unbound = rebound.withTileSource(AtlasTileId("art-0/lyid:1"), null)
assertNull(unbound.atlas.tiles.single().source)
}
@Test
fun tilesBoundToOneKeyRebindTogetherAsOneStep() {
// Two tiles under one lost key, the shape a review row's Accept acts on: they move as one edit,
// so one undo brings both back.
val second = AtlasTile(AtlasTileId("art-0/lyid:1~1"), "L1", 4, 4, source = refA1, replaces = AtlasTileId("art-0/lyid:1"))
val base = model().let { single -> single.copy(atlas = single.atlas.copy(tiles = single.atlas.tiles + second)) }
val session = EditorSession(base)
val both = base.atlas.tiles.map { tile -> tile.id }
session.setTileSources(both, null)
assertTrue(session.model.value.atlas.tiles.all { tile -> tile.source == null }, "both tiles unbound")
assertTrue(session.canUndo.value)
session.undo()
assertTrue(session.model.value.atlas.tiles.all { tile -> tile.source == refA1 }, "one undo restores both")
assertEquals(false, session.canUndo.value, "the two rebinds were one step")
session.setTileSources(emptyList(), null)
assertEquals(false, session.canUndo.value, "an empty call pushes nothing")
}
@Test
fun aRebindToAnUnlistedSourceOrAnUnknownTileIsRefused() {
val base = model()
assertSame(base, base.withTileSource(AtlasTileId("art-0/lyid:1"), SourceLayerRef(ArtSourceId("art-9"), "lyid:1", true)), "an unlisted file")
assertSame(base, base.withTileSource(AtlasTileId("nope"), refA1), "an unknown tile")
assertSame(base, base.withTileSource(AtlasTileId("art-0/lyid:1"), refA1), "the binding it already has")
}
@Test
fun artworkAdditionsAppendAfterTheExistingRigWithADerivedRenderRoot() {
val base = model()
val added = drawable("ArtMesh2", "art-1/uuid-7")
val additions =
ArtworkAdditions(
source = ArtSource(ArtSourceId("art-1"), "b.clip", null, "clip", listOf(ArtSourceLayer("uuid-7", "Wing", "", 2, 2, 4, 4, true))),
tiles = listOf(AtlasTile(AtlasTileId("art-1/uuid-7"), "Wing", 4, 4, source = SourceLayerRef(ArtSourceId("art-1"), "uuid-7", true))),
drawables = listOf(added),
parts = listOf(Part(PartId("Part2"), "Wings", listOf(OrgChild.Drawable(added.id)))),
rootChildren = listOf(OrgChild.Part(PartId("Part2"))),
)
val grown = base.withArtworkAdded(additions)
assertEquals(listOf("art-0", "art-1"), grown.sources.map { source -> source.id.raw })
assertEquals(listOf("ArtMesh1", "ArtMesh2"), grown.drawables.map { drawable -> drawable.id.raw })
assertEquals(listOf("Part1", "Part2"), grown.parts.map { part -> part.id.raw })
assertEquals(listOf(OrgChild.Part(PartId("Part1")), OrgChild.Part(PartId("Part2"))), grown.rootChildren, "the file's order follows the existing root children")
assertEquals(2, grown.atlas.tiles.size)
assertTrue(grown.renderRoot.children.isNotEmpty(), "the render root is re-derived over the grown tree")
assertEquals(base.atlas.pages, grown.atlas.pages, "the pages are untouched - the pack is a separate step")
}
@Test
fun artworkAdditionsThatCollideAreRefused() {
val base = model()
val collidingDrawable =
ArtworkAdditions(
source = ArtSource(ArtSourceId("art-1"), "b.clip", null, "clip"),
tiles = emptyList(),
drawables = listOf(drawable("ArtMesh1", "art-1/x")),
parts = emptyList(),
rootChildren = emptyList(),
)
assertSame(base, base.withArtworkAdded(collidingDrawable), "a drawable id the model already has")
val collidingSource =
ArtworkAdditions(source = sourceA, tiles = emptyList(), drawables = emptyList(), parts = emptyList(), rootChildren = emptyList())
assertSame(base, base.withArtworkAdded(collidingSource), "a source id the model already lists")
}
@Test
fun aReloadSwapsTheTileCarriesTheDrawablesAndAppendsTheAdditions() {
val base = model()
val newMesh = DrawableMesh(floatArrayOf(0f, 0f, 6f, 0f, 6f, 6f, 0f, 6f), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3))
val replacement = AtlasTile(AtlasTileId("art-0/lyid:1~1"), "L1", 6, 6, source = refA1, pinned = true, replaces = AtlasTileId("art-0/lyid:1"))
val added = drawable("ArtMesh2", "art-0/lyid:2")
val refreshed = sourceA.copy(layers = listOf(ArtSourceLayer("lyid:1", "L1", "", 0, 0, 6, 6, true), ArtSourceLayer("lyid:2", "L2", "", 9, 9, 4, 4, true)))
val reload =
ArtworkReload(
source = refreshed,
replacedTiles = listOf(ReplacedTile(AtlasTileId("art-0/lyid:1"), replacement)),
drawableMeshes = mapOf(DrawableId("ArtMesh1") to newMesh),
additions =
ArtworkAdditions(
source = refreshed,
tiles = listOf(AtlasTile(AtlasTileId("art-0/lyid:2"), "L2", 4, 4, source = SourceLayerRef(ArtSourceId("art-0"), "lyid:2", true))),
drawables = listOf(added),
parts = emptyList(),
rootChildren = listOf(OrgChild.Drawable(added.id)),
),
outgrown = emptyList(),
)
val reloaded = base.withArtworkReloaded(reload)
assertEquals(listOf("art-0/lyid:1~1", "art-0/lyid:2"), reloaded.atlas.tiles.map { tile -> tile.id.raw }, "the old tile is gone, the replacement and the addition appended")
assertSame(replacement, reloaded.atlas.tiles.first())
val carried = reloaded.drawables.first { drawable -> drawable.id.raw == "ArtMesh1" }
assertEquals(AtlasTileId("art-0/lyid:1~1"), carried.atlasTileId, "the drawable moved onto the replacement")
assertSame(newMesh, carried.mesh, "with the mesh the plan decided")
assertEquals(listOf("ArtMesh1", "ArtMesh2"), reloaded.drawables.map { drawable -> drawable.id.raw })
assertEquals(listOf(OrgChild.Part(PartId("Part1")), OrgChild.Drawable(added.id)), reloaded.rootChildren)
assertEquals(refreshed, reloaded.sources.single(), "the file's record takes the new inventory")
assertEquals(reloaded.deriveRenderRoot(), reloaded.renderRoot, "the render root is re-derived")
}
/**
* A delta's insertions place new children among the existing ones - before or after an anchor, at
* the end, and after a child the same delta placed just before - in the root and in a part the model
* already holds; an anchor the container lacks falls to the end; a container the model lacks refuses.
*/
@Test
fun insertionsPlaceNewChildrenAmongTheExistingOnes() {
val base = model()
val added = drawable("ArtMesh2", "art-0/lyid:2")
val second = drawable("ArtMesh3", "art-0/lyid:3")
val top = drawable("ArtMesh4", "art-0/lyid:4")
val kept = OrgChild.Drawable(DrawableId("ArtMesh1"))
val additions =
ArtworkAdditions(
source = sourceA,
tiles = listOf(added, second, top).map { drawable -> AtlasTile(drawable.atlasTileId!!, drawable.name, 4, 4, source = SourceLayerRef(ArtSourceId("art-0"), drawable.atlasTileId!!.raw.substringAfter('/'), true)) },
drawables = listOf(added, second, top),
parts = emptyList(),
rootChildren = emptyList(),
insertions =
listOf(
OrgInsertion(PartId("Part1"), OrgChild.Drawable(added.id), OrgSlot.Before(kept)),
OrgInsertion(PartId("Part1"), OrgChild.Drawable(second.id), OrgSlot.After(OrgChild.Drawable(added.id))),
OrgInsertion(null, OrgChild.Drawable(top.id), OrgSlot.Before(OrgChild.Part(PartId("Part1")))),
),
)
val reload = ArtworkReload(sourceA, replacedTiles = emptyList(), drawableMeshes = emptyMap(), additions = additions, outgrown = emptyList())
val reloaded = base.withArtworkReloaded(reload)
assertEquals(listOf(OrgChild.Drawable(added.id), OrgChild.Drawable(second.id), kept), reloaded.parts.single().children, "before the kept child, then after the one just placed")
assertEquals(listOf(OrgChild.Drawable(top.id), OrgChild.Part(PartId("Part1"))), reloaded.rootChildren, "a top-of-file layer lands first at the root")
assertEquals(listOf("ArtMesh1", "ArtMesh2", "ArtMesh3", "ArtMesh4"), reloaded.drawables.map { drawable -> drawable.id.raw })
assertEquals(RenderDrawable(DrawableId("ArtMesh4")), reloaded.renderRoot.children.last(), "and draws last of all, so in front (the render root runs back to front)")
val fallbacks = additions.copy(insertions = listOf(OrgInsertion(PartId("Part1"), OrgChild.Drawable(added.id), OrgSlot.After(OrgChild.Drawable(DrawableId("gone")))), OrgInsertion(null, OrgChild.Drawable(top.id), OrgSlot.End)))
val fallen = base.withArtworkReloaded(reload.copy(additions = fallbacks))
assertEquals(listOf(kept, OrgChild.Drawable(added.id)), fallen.parts.single().children, "a missing anchor falls to the end")
assertEquals(listOf(OrgChild.Part(PartId("Part1")), OrgChild.Drawable(top.id)), fallen.rootChildren)
val unknownPart = additions.copy(insertions = listOf(OrgInsertion(PartId("Part9"), OrgChild.Drawable(added.id), OrgSlot.End)))
assertSame(base, base.withArtworkReloaded(reload.copy(additions = unknownPart)), "a part the model lacks refuses the reload")
assertSame(base, base.withArtworkAdded(unknownPart.copy(source = sourceA.copy(id = ArtSourceId("art-1")))), "and the addition")
}
/** A tile no drawable samples can leave the atlas; one still sampled, or one the model lacks, cannot. */
@Test
fun anUnsampledTileCanBeDeletedAndASampledOneCannot() {
val base = model()
val orphan = AtlasTile(AtlasTileId("art-0/lyid:2"), "L2", 4, 4, source = SourceLayerRef(ArtSourceId("art-0"), "lyid:2", true))
val withOrphan = base.copy(atlas = base.atlas.copy(tiles = base.atlas.tiles + orphan))
val deleted = withOrphan.withTileDeleted(orphan.id)
assertEquals(listOf(AtlasTileId("art-0/lyid:1")), deleted.atlas.tiles.map { tile -> tile.id }, "the orphan is gone")
assertEquals(withOrphan.drawables, deleted.drawables, "and nothing else moved")
assertSame(withOrphan, withOrphan.withTileDeleted(AtlasTileId("art-0/lyid:1")), "a tile a drawable samples stays")
assertSame(withOrphan, withOrphan.withTileDeleted(AtlasTileId("nope")), "an unknown tile is a no-op")
}
/**
* The ignore mark sits on an inventory row no tile binds: a bound key, an unlisted file or key, and a
* mark already as asked are refused; the session toggles it as one step; Delete Art marks the deleted
* tile's layer only when asked, and never a key another tile still binds.
*/
@Test
fun aLayerIsIgnoredOnlyWhileUnboundAndDeleteArtMarksItOnRequest() {
val base = model()
val fileId = ArtSourceId("art-0")
assertSame(base, base.withLayerIgnored(fileId, "lyid:1", ignored = true), "a bound key is refused")
assertSame(base, base.withLayerIgnored(ArtSourceId("art-9"), "lyid:1", ignored = true), "an unlisted file")
assertSame(base, base.withLayerIgnored(fileId, "lyid:9", ignored = true), "an unlisted key")
val unbound = base.withTileSource(AtlasTileId("art-0/lyid:1"), null)
val marked = unbound.withLayerIgnored(fileId, "lyid:1", ignored = true)
assertTrue(marked.sources.single().layers.single().ignored)
assertSame(marked, marked.withLayerIgnored(fileId, "lyid:1", ignored = true), "already as asked")
assertEquals(false, marked.withLayerIgnored(fileId, "lyid:1", ignored = false).sources.single().layers.single().ignored, "cleared again")
val session = EditorSession(unbound)
session.setLayerIgnored(SourceLayerRef(fileId, "lyid:1", stableKey = true), ignored = true)
assertTrue(session.model.value.sources.single().layers.single().ignored)
assertTrue(session.canUndo.value)
session.undo()
assertSame(unbound, session.model.value)
session.setLayerIgnored(SourceLayerRef(fileId, "lyid:1", stableKey = true), ignored = false)
assertEquals(false, session.canUndo.value, "a mark already as asked pushes nothing")
// Delete Art: the orphan tile leaves; under the setting its layer is marked in the same step.
val orphan = AtlasTile(AtlasTileId("art-0/lyid:2"), "L2", 4, 4, source = SourceLayerRef(fileId, "lyid:2", true))
val withOrphan =
base.copy(
atlas = base.atlas.copy(tiles = base.atlas.tiles + orphan),
sources = listOf(sourceA.copy(layers = sourceA.layers + ArtSourceLayer("lyid:2", "L2", "", 0, 0, 4, 4, true))),
)
val plain = EditorSession(withOrphan)
plain.deleteTile(orphan.id)
assertEquals(listOf(false, false), plain.model.value.sources.single().layers.map { layer -> layer.ignored }, "a plain Delete Art marks nothing")
val marking = EditorSession(withOrphan)
marking.deleteTile(orphan.id, ignoreLayer = true)
assertEquals(listOf(AtlasTileId("art-0/lyid:1")), marking.model.value.atlas.tiles.map { tile -> tile.id })
assertEquals(listOf(false, true), marking.model.value.sources.single().layers.map { layer -> layer.ignored }, "the deleted tile's layer is marked in the same step")
marking.undo()
assertSame(withOrphan, marking.model.value, "one undo brings the tile and the unmarked row back")
// A key another tile still binds is left unmarked: the reload matches it by key.
val twin = AtlasTile(AtlasTileId("art-0/lyid:2~1"), "L2", 4, 4, source = SourceLayerRef(fileId, "lyid:2", true))
val shared = EditorSession(withOrphan.copy(atlas = withOrphan.atlas.copy(tiles = withOrphan.atlas.tiles + twin)))
shared.deleteTile(orphan.id, ignoreLayer = true)
assertEquals(listOf(false, false), shared.model.value.sources.single().layers.map { layer -> layer.ignored })
assertEquals(2, shared.model.value.atlas.tiles.size, "the tile still left")
}
/** A reload's visibility map reaches the drawables it names and no other. */
@Test
fun aReloadAppliesTheVisibilityItDecided() {
val base = model()
val reloaded = base.withArtworkReloaded(ArtworkReload(sourceA, emptyList(), emptyMap(), null, emptyList(), drawableVisibility = mapOf(DrawableId("ArtMesh1") to false)))
assertEquals(false, reloaded.drawables.single().isVisible)
assertEquals(base.atlas, reloaded.atlas, "nothing else moved")
assertEquals(true, base.withArtworkReloaded(ArtworkReload(sourceA, emptyList(), emptyMap(), null, emptyList())).drawables.single().isVisible, "an empty map changes nothing")
}
@Test
fun aReloadThatCollidesOrNamesTheUnknownIsRefused() {
val base = model()
val unknownOld =
ArtworkReload(sourceA, listOf(ReplacedTile(AtlasTileId("nope"), AtlasTile(AtlasTileId("nope~1"), "x", 1, 1))), emptyMap(), null, emptyList())
assertSame(base, base.withArtworkReloaded(unknownOld), "an unknown superseded tile")
val collidingNew =
ArtworkReload(sourceA, listOf(ReplacedTile(AtlasTileId("art-0/lyid:1"), AtlasTile(AtlasTileId("art-0/lyid:1"), "x", 1, 1))), emptyMap(), null, emptyList())
assertSame(base, base.withArtworkReloaded(collidingNew), "a replacement reusing an existing id")
val unlisted = ArtworkReload(ArtSource(ArtSourceId("art-9"), "z", null, "psd"), emptyList(), emptyMap(), null, emptyList())
assertSame(base, base.withArtworkReloaded(unlisted), "a file the model does not list")
}
/**
* A reload's retired tiles leave with their drawables and every reference to them scrubbed, the way a
* delete scrubs them; a retired tile the model lacks, or one the same delta also supersedes, refuses
* the whole delta.
*/
@Test
fun aReloadRetiresTheTilesItNamesWithTheirDrawables() {
val base = model()
val fresh = drawable("ArtMesh3", "art-0/lyid:3")
val freshTile = AtlasTile(AtlasTileId("art-0/lyid:3"), "L3", 4, 4, source = SourceLayerRef(ArtSourceId("art-0"), "lyid:3", true))
val withFresh =
base.copy(
drawables = listOf(base.drawables.single().copy(maskedBy = listOf(fresh.id)), fresh),
parts = listOf(base.parts.single().copy(children = base.parts.single().children + OrgChild.Drawable(fresh.id))),
atlas = base.atlas.copy(tiles = base.atlas.tiles + freshTile),
).withDerivedRenderRoot()
val reload = ArtworkReload(sourceA, replacedTiles = emptyList(), drawableMeshes = emptyMap(), additions = null, outgrown = emptyList(), retiredTiles = listOf(freshTile.id))
val retired = withFresh.withArtworkReloaded(reload)
assertEquals(listOf("ArtMesh1"), retired.drawables.map { drawable -> drawable.id.raw }, "the fresh drawable is gone")
assertEquals(listOf(AtlasTileId("art-0/lyid:1")), retired.atlas.tiles.map { tile -> tile.id }, "with its tile")
assertEquals(listOf(OrgChild.Drawable(DrawableId("ArtMesh1"))), retired.parts.single().children, "and its place in the part")
assertTrue(retired.drawables.single().maskedBy.isEmpty(), "and the mask that named it")
assertEquals(retired.deriveRenderRoot(), retired.renderRoot, "the render root is re-derived")
assertSame(withFresh, withFresh.withArtworkReloaded(reload.copy(retiredTiles = listOf(AtlasTileId("nope")))), "an unknown retired tile refuses")
val alsoReplaced = ArtworkReload(sourceA, listOf(ReplacedTile(freshTile.id, AtlasTile(AtlasTileId("art-0/lyid:3~1"), "L3", 4, 4))), emptyMap(), null, emptyList(), retiredTiles = listOf(freshTile.id))
assertSame(withFresh, withFresh.withArtworkReloaded(alsoReplaced), "a tile both superseded and retired refuses")
}
}
@@ -0,0 +1,335 @@
package org.umamo.edit
import org.umamo.runtime.model.AtlasPage
import org.umamo.runtime.model.AtlasPlacement
import org.umamo.runtime.model.AtlasTile
import org.umamo.runtime.model.AtlasTileId
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableLayerBinding
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.PuppetAtlas
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.applyUvAffine
import org.umamo.runtime.model.invertUvAffine
import org.umamo.runtime.model.layerUvAffineOf
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the multi-tile placement edit the gizmo commits through: every drawable over each moved tile
* re-maps in one pass (drawables sharing a tile move together), untouched drawables pass their arrays
* through by reference, one fault anywhere in the map refuses the whole edit, the session commit is
* ONE undo step, the step's label names the operator that ran, a pin lands only on a placed tile and
* leaves with its placement, and the Object-mode UV latch admits exactly the selections that have
* packed art to move.
*/
class AtlasPlacementEditsTest {
private val tileAId = AtlasTileId("tileA")
private val tileBId = AtlasTileId("tileB")
private val tileCId = AtlasTileId("tileC")
private val unpackedTileId = AtlasTileId("tileUnpacked")
private val page = AtlasPage(128, 128)
private fun placement(x: Float, y: Float, pageIndex: Int = 0): AtlasPlacement =
AtlasPlacement(pageIndex, x, y, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f)
private fun meshedDrawable(id: String, tileId: AtlasTileId?, uvs: FloatArray): Drawable =
Drawable(
id = DrawableId(id),
name = id,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 1f), uvs, intArrayOf(0, 0, 0)),
geometryGrid = null,
atlasTileId = tileId,
)
private fun storedUvsAt(artUvs: FloatArray, tileId: AtlasTileId, placed: AtlasPlacement?): FloatArray {
val binding = DrawableLayerBinding(tileId.raw, placed, page.width, page.height)
val storedToArt = assertNotNull(layerUvAffineOf(binding, 16, 16))
return applyUvAffine(artUvs, assertNotNull(invertUvAffine(storedToArt)))
}
private fun assertUvsClose(expected: FloatArray, actual: FloatArray, message: String) {
assertEquals(expected.size, actual.size, message)
for (componentIndex in expected.indices) {
assertTrue(
abs(expected[componentIndex] - actual[componentIndex]) < 1e-5f,
"$message: component $componentIndex expected ${expected[componentIndex]}, was ${actual[componentIndex]}",
)
}
}
private val placedA = placement(4f, 4f)
private val placedB = placement(40f, 40f)
private val placedC = placement(80f, 80f)
private val artUvsA1 = floatArrayOf(0.25f, 0.5f, 0.75f, 0.125f)
private val artUvsA2 = floatArrayOf(0f, 1f, 1f, 0f)
private val artUvsB = floatArrayOf(0f, 0f, 1f, 1f)
private val artUvsC = floatArrayOf(0.5f, 0.5f, 0.5f, 0.5f)
private fun baseModel(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = listOf(Deformer.Warp(DeformerId("w"), "W", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null)),
drawables =
listOf(
meshedDrawable("dA1", tileAId, storedUvsAt(artUvsA1, tileAId, placedA)),
meshedDrawable("dA2", tileAId, storedUvsAt(artUvsA2, tileAId, placedA)),
meshedDrawable("dB", tileBId, storedUvsAt(artUvsB, tileBId, placedB)),
meshedDrawable("dC", tileCId, storedUvsAt(artUvsC, tileCId, placedC)),
meshedDrawable("dUnpacked", unpackedTileId, artUvsB.copyOf()),
meshedDrawable("dLoose", null, artUvsB.copyOf()),
),
rootChildren = emptyList(),
rootPartId = null,
canvasWidth = 100f,
canvasHeight = 200f,
worldOriginX = 50f,
worldOriginZ = 100f,
atlas =
PuppetAtlas(
pages = listOf(page),
tiles =
listOf(
AtlasTile(tileAId, "A", 16, 16, placedA),
AtlasTile(tileBId, "B", 16, 16, placedB),
AtlasTile(tileCId, "C", 16, 16, placedC),
AtlasTile(unpackedTileId, "U", 16, 16, null),
),
),
)
private fun PuppetModel.uvsOf(id: String): FloatArray = drawables.first { drawable -> drawable.id.raw == id }.mesh!!.uvs
private fun PuppetModel.placementOf(tileId: AtlasTileId): AtlasPlacement? = atlas.tileById.getValue(tileId).placement
private fun target(id: String): SelectionTarget = SelectionTarget.Drawable(DrawableId(id))
@Test
fun aMultiTileMoveRemapsEveryDrawableOverEachMovedTileInOnePass() {
val base = baseModel()
val movedA = placement(20f, 8f)
val movedB = placement(60f, 44f)
val moved = base.withAtlasPlacements(mapOf(tileAId to movedA, tileBId to movedB))
assertEquals(movedA, moved.placementOf(tileAId), "tile A moved")
assertEquals(movedB, moved.placementOf(tileBId), "tile B moved")
assertEquals(placedC, moved.placementOf(tileCId), "tile C stayed")
assertUvsClose(storedUvsAt(artUvsA1, tileAId, movedA), moved.uvsOf("dA1"), "the first drawable over A follows the art")
assertUvsClose(storedUvsAt(artUvsA2, tileAId, movedA), moved.uvsOf("dA2"), "the second drawable over A follows too - a tile moves every drawable sharing it")
assertUvsClose(storedUvsAt(artUvsB, tileBId, movedB), moved.uvsOf("dB"), "the drawable over B follows the art")
assertSame(base.uvsOf("dC"), moved.uvsOf("dC"), "an untouched tile's drawable keeps its array by reference")
assertSame(base.uvsOf("dLoose"), moved.uvsOf("dLoose"), "an unbound drawable is untouched")
assertEquals(placedA, base.placementOf(tileAId), "the original model is immutable")
}
@Test
fun oneFaultAnywhereInTheMapRefusesTheWholeEdit() {
val base = baseModel()
val missingPage = base.withAtlasPlacements(mapOf(tileAId to placement(20f, 8f), tileBId to placement(0f, 0f, pageIndex = 3)))
assertSame(base, missingPage, "a placement naming a page the atlas lacks refuses the whole map, not just its tile")
val collapsed = base.withAtlasPlacements(mapOf(tileAId to placement(20f, 8f), tileBId to AtlasPlacement(0, 0f, 0f, 0f, 1f, 0f)))
assertSame(base, collapsed, "a placement that will not invert refuses the whole map")
val unknown = base.withAtlasPlacements(mapOf(tileAId to placement(20f, 8f), AtlasTileId("gone") to placement(1f, 1f)))
assertSame(base, unknown, "an unknown tile refuses the whole map")
}
@Test
fun aNoOpMapReturnsTheSameInstance() {
val base = baseModel()
assertSame(base, base.withAtlasPlacements(emptyMap()), "an empty map changes nothing")
assertSame(base, base.withAtlasPlacements(mapOf(tileAId to placedA, tileBId to placedB)), "restating every placement changes nothing")
}
@Test
fun theSessionCommitsAMultiTileMoveAsOneStep() {
val session = EditorSession(baseModel())
val movedA = placement(20f, 8f)
val movedB = placement(60f, 44f)
session.setAtlasPlacements(mapOf(tileAId to movedA, tileBId to movedB))
assertEquals(movedA, session.model.value.placementOf(tileAId))
assertEquals(movedB, session.model.value.placementOf(tileBId))
assertTrue(session.dirty.value, "a pack is document content, so it dirties")
assertEquals("change.document.atlasPlacement", DocumentChange.SetAtlasPlacement(listOf(tileAId, tileBId)).labelKey)
session.undo()
assertEquals(placedA, session.model.value.placementOf(tileAId), "one undo restores both tiles")
assertEquals(placedB, session.model.value.placementOf(tileBId), "one undo restores both tiles")
assertFalse(session.canUndo.value, "the whole gesture was one step")
assertFalse(session.dirty.value, "undo restores the saved model instance")
session.setAtlasPlacements(mapOf(tileAId to placedA))
assertFalse(session.canUndo.value, "a no-op commit records nothing")
}
@Test
fun thePlacementStepIsLabelledByTheOperatorThatRan() {
assertEquals("change.document.atlasPlacement", DocumentChange.SetAtlasPlacement(listOf(tileAId), MeshOperatorKind.Grab).labelKey)
assertEquals("change.document.atlasPlacement.rotate", DocumentChange.SetAtlasPlacement(listOf(tileAId), MeshOperatorKind.Rotate).labelKey)
assertEquals("change.document.atlasPlacement.scale", DocumentChange.SetAtlasPlacement(listOf(tileAId), MeshOperatorKind.Scale).labelKey)
assertEquals("change.document.atlasPlacement", DocumentChange.SetAtlasPlacement(listOf(tileAId), MeshOperatorKind.VertexSlide).labelKey, "a placement cannot slide; it moved")
val session = EditorSession(baseModel())
session.setAtlasPlacements(mapOf(tileAId to placement(20f, 8f)), MeshOperatorKind.Rotate)
assertEquals("change.document.atlasPlacement.rotate", session.historyView.value.steps.last().labelKey, "the session's step carries the kind")
}
@Test
fun aPinLandsOnPlacedTilesOnlyAndLeavesWithThePlacement() {
val base = baseModel()
val pinned = base.withAtlasPins(listOf(tileAId, unpackedTileId, AtlasTileId("gone")), pinned = true)
assertTrue(pinned.atlas.tileById.getValue(tileAId).pinned, "a placed tile pins")
assertFalse(pinned.atlas.tileById.getValue(unpackedTileId).pinned, "an unpacked tile has nothing to keep")
assertFalse(pinned.atlas.tileById.getValue(tileBId).pinned, "an unnamed tile is untouched")
assertSame(base.drawables, pinned.drawables, "a pin moves no coordinates")
assertSame(pinned, pinned.withAtlasPins(listOf(tileAId), pinned = true), "restating a pin changes nothing")
assertSame(base, base.withAtlasPins(listOf(unpackedTileId), pinned = true), "pinning only unpacked art changes nothing")
assertSame(base, base.withAtlasPins(emptyList(), pinned = true))
val moved = pinned.withAtlasPlacements(mapOf(tileAId to placement(20f, 8f)))
assertTrue(moved.atlas.tileById.getValue(tileAId).pinned, "a hand move keeps the pin")
val unpacked = pinned.withAtlasPlacements(mapOf(tileAId to null))
assertFalse(unpacked.atlas.tileById.getValue(tileAId).pinned, "packing a tile out drops its pin")
val repacked =
pinned.withAtlasRepack(
listOf(page),
pinned.atlas.tiles.associate { tile -> tile.id to (if (tile.id == tileBId) placement(60f, 44f) else tile.placement) },
)
assertTrue(repacked.atlas.tileById.getValue(tileAId).pinned, "a repack restating the placement keeps the pin")
}
@Test
fun theSessionPinsAsOneUndoStep() {
val session = EditorSession(baseModel())
session.setAtlasPins(listOf(tileAId, tileBId), pinned = true)
assertTrue(session.model.value.atlas.tileById.getValue(tileAId).pinned)
assertTrue(session.model.value.atlas.tileById.getValue(tileBId).pinned)
assertEquals("change.document.atlasPin", session.historyView.value.steps.last().labelKey)
assertTrue(session.dirty.value, "a pin is document content")
session.setAtlasPins(listOf(tileAId), pinned = false)
assertFalse(session.model.value.atlas.tileById.getValue(tileAId).pinned)
assertTrue(session.model.value.atlas.tileById.getValue(tileBId).pinned, "unpinning one leaves the other")
assertEquals("change.document.atlasUnpin", session.historyView.value.steps.last().labelKey)
session.undo()
session.undo()
assertFalse(session.model.value.atlas.tileById.getValue(tileBId).pinned, "two undos return to the unpinned model")
assertFalse(session.canUndo.value)
session.setAtlasPins(listOf(unpackedTileId), pinned = true)
assertFalse(session.canUndo.value, "a no-op pin records nothing")
}
@Test
fun placementDragTileIdsCoversPlacedTilesOfSelectedDrawablesOnly() {
val model = baseModel()
val selection =
Selection(
setOf(target("dA1"), target("dA2"), target("dUnpacked"), target("dLoose"), SelectionTarget.Deformer(DeformerId("w"))),
target("dA1"),
)
assertEquals(setOf(tileAId), model.placementDragTileIds(selection), "two drawables over one tile name it once; unpacked and unbound art contribute nothing")
assertEquals(emptySet(), model.placementDragTileIds(Selection()), "nothing selected, nothing to move")
assertEquals(setOf(tileAId, tileBId), model.placementDragTileIds(Selection(setOf(target("dB"), target("dA2")), target("dB"))).toSet())
}
@Test
fun objectModeLatchesAUvOperatorOverPackedArt() {
val session = EditorSession(baseModel())
assertEquals(EditorMode.Object, session.mode.value)
session.setSelection(Selection(setOf(target("dA1")), target("dA1")))
session.beginUvOperator(MeshOperatorKind.Grab, "uv-area")
assertEquals(ActiveOperator(MeshOperatorKind.Grab, "uv-area"), session.activeUvOperator.value, "a placed selection latches")
assertNull(session.notice.value, "no notice on success")
session.clearUvOperator()
session.beginUvOperator(MeshOperatorKind.Rotate, "uv-area")
assertEquals(MeshOperatorKind.Rotate, session.activeUvOperator.value?.kind, "rotate latches too")
session.clearUvOperator()
session.beginUvOperator(MeshOperatorKind.Scale, "uv-area")
assertEquals(MeshOperatorKind.Scale, session.activeUvOperator.value?.kind, "scale latches too")
session.clearUvOperator()
session.beginUvOperator(MeshOperatorKind.VertexSlide, "uv-area")
assertNull(session.activeUvOperator.value, "vertex slide is not a placement operation")
}
@Test
fun objectModeRefusesWithANoticeWhenNothingSelectedIsPacked() {
val session = EditorSession(baseModel())
session.beginUvOperator(MeshOperatorKind.Grab, "uv-area")
assertNull(session.activeUvOperator.value, "an empty selection has nothing to place")
assertEquals("notice.uv.placement.noPlacedArt", session.notice.value?.messageKey)
assertEquals(NoticePlacement.NearCursor, session.notice.value?.placement)
session.setSelection(Selection(setOf(target("dUnpacked"), target("dLoose")), target("dUnpacked")))
session.beginUvOperator(MeshOperatorKind.Grab, "uv-area")
assertNull(session.activeUvOperator.value, "unpacked and unbound art has nothing on a page to move")
assertEquals("notice.uv.placement.noPlacedArt", session.notice.value?.messageKey)
}
@Test
fun aPinHoldsAgainstTheGesture() {
val session = EditorSession(baseModel().withAtlasPins(listOf(tileAId), pinned = true))
val pinnedOnly = Selection(setOf(target("dA1"), target("dA2")), target("dA1"))
val mixed = Selection(setOf(target("dA1"), target("dB")), target("dB"))
assertEquals(emptySet(), session.model.value.placementDragTileIds(pinnedOnly), "a pinned tile is not a mover")
assertEquals(setOf(tileAId), session.model.value.placementSelectedTileIds(pinnedOnly), "but it is still the selection's placed tile - Unpin needs it")
assertEquals(setOf(tileBId), session.model.value.placementDragTileIds(mixed), "a mixed selection moves the unpinned tile alone")
session.setSelection(pinnedOnly)
session.beginUvOperator(MeshOperatorKind.Grab, "uv-area")
assertNull(session.activeUvOperator.value, "an all-pinned selection has nothing to move")
assertEquals("notice.uv.placement.pinned", session.notice.value?.messageKey, "and says why")
session.setSelection(mixed)
session.beginUvOperator(MeshOperatorKind.Grab, "uv-area")
assertEquals(MeshOperatorKind.Grab, session.activeUvOperator.value?.kind, "a mixed selection latches over its unpinned tile")
}
@Test
fun objectModeRefusesALayerAddressedDocument() {
val base = baseModel()
val session = EditorSession(base.copy(atlas = base.atlas.copy(storedUvsAddressPages = false)))
session.setSelection(Selection(setOf(target("dA1")), target("dA1")))
session.beginUvOperator(MeshOperatorKind.Grab, "uv-area")
assertNull(session.activeUvOperator.value, "coordinates that address the art have no page placement to move")
assertEquals("notice.uv.placement.layerAddressed", session.notice.value?.messageKey)
}
@Test
fun editModeStillNeedsAMeshSelection() {
val session = EditorSession(baseModel())
session.setSelection(Selection(setOf(target("dA1")), target("dA1")))
session.setMode(EditorMode.Edit)
session.beginUvOperator(MeshOperatorKind.Grab, "uv-area")
assertNull(session.activeUvOperator.value, "Edit mode moves texture coordinates and has none selected")
assertNull(session.notice.value, "an empty Edit selection stays a silent no-op")
}
}
@@ -0,0 +1,141 @@
package org.umamo.edit
import org.umamo.runtime.model.AtlasPlacement
import org.umamo.runtime.model.composeAffine
import org.umamo.runtime.model.placementAffine
import kotlin.math.PI
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Pins the placement gizmo's algebra: composing a gesture affine onto a placement yields a placement
* whose forward transform IS the product (so the preview and the commit agree to float precision),
* each operator's page-space affine lands on the TRS component it means to, a mirrored placement keeps
* its mirror, and the two products no placement can express - a page-axis non-uniform scale on a
* rotated tile, and a collapsed axis - are refused rather than approximated.
*/
class AtlasPlacementTransformsTest {
private fun placement(
x: Float,
y: Float,
scaleX: Float = 1f,
scaleY: Float = 1f,
rotationDegrees: Float = 0f,
): AtlasPlacement = AtlasPlacement(0, x, y, scaleX, scaleY, rotationDegrees)
private fun radians(degrees: Float): Float = (degrees.toDouble() * PI / 180.0).toFloat()
private fun assertClose(expected: Float, actual: Float, message: String) {
assertTrue(abs(expected - actual) < 1e-3f, "$message: expected $expected, was $actual")
}
private fun assertAffineClose(expected: FloatArray, actual: FloatArray, message: String) {
for (componentIndex in expected.indices) {
assertClose(expected[componentIndex], actual[componentIndex], "$message (component $componentIndex)")
}
}
/**
* Composes and asserts the load-bearing property: the result's forward affine is the product of the
* gesture and the original, so what the gizmo previewed is what the placement stores.
*
* @param AtlasPlacement original The placement before the gesture.
* @param FloatArray gesture The gesture's page-space affine.
* @return AtlasPlacement The composed placement.
*/
private fun assertComposesExactly(original: AtlasPlacement, gesture: FloatArray): AtlasPlacement {
val composed = assertNotNull(original.composedWith(gesture), "the product is a placement")
assertAffineClose(
composeAffine(gesture, placementAffine(original)),
placementAffine(composed),
"the composed placement's forward affine is the gesture applied after the original",
)
return composed
}
@Test
fun aTranslationMovesThePositionAndNothingElse() {
val moved = assertComposesExactly(placement(10f, 20f, rotationDegrees = 30f), translationAffine(5f, -3f))
assertClose(15f, moved.positionX, "x moved by the delta")
assertClose(17f, moved.positionY, "y moved by the delta")
assertClose(1f, moved.scaleX, "scale x untouched")
assertClose(1f, moved.scaleY, "scale y untouched")
assertClose(30f, moved.rotationDegrees, "rotation untouched")
}
@Test
fun aRotationAboutAPivotAddsToTheAngleAndOrbitsThePosition() {
val original = placement(10f, 20f, rotationDegrees = 30f)
val rotated = assertComposesExactly(original, rotationAboutAffine(50f, 60f, radians(90f)))
assertClose(120f, rotated.rotationDegrees, "the gesture angle adds to the placement's")
assertClose(1f, rotated.scaleX, "scale x untouched")
assertClose(1f, rotated.scaleY, "scale y untouched")
// The origin orbits the pivot: (10, 20) is (-40, -40) from it, a quarter turn lands at (40, -40).
assertClose(90f, rotated.positionX, "the origin orbited the pivot in x")
assertClose(20f, rotated.positionY, "the origin orbited the pivot in y")
}
@Test
fun aUniformScaleAboutAPivotMultipliesBothScalesAndKeepsTheAngle() {
val original = placement(10f, 20f, rotationDegrees = 45f)
val scaled = assertComposesExactly(original, scaleAboutAffine(50f, 60f, 2f, 2f))
assertClose(2f, scaled.scaleX, "scale x doubled")
assertClose(2f, scaled.scaleY, "scale y doubled")
assertClose(45f, scaled.rotationDegrees, "rotation untouched")
assertClose(-30f, scaled.positionX, "the origin moved away from the pivot in x")
assertClose(-20f, scaled.positionY, "the origin moved away from the pivot in y")
}
@Test
fun aLocalAxisScaleOnARotatedPlacementStaysExpressible() {
val original = placement(10f, 20f, rotationDegrees = 30f)
val gesture = localAxisScaleAboutAffine(original, 50f, 60f, 2f, 1f)
val scaled = assertComposesExactly(original, gesture)
assertClose(2f, scaled.scaleX, "the tile's own x axis scaled")
assertClose(1f, scaled.scaleY, "the tile's own y axis untouched")
assertClose(30f, scaled.rotationDegrees, "rotation untouched")
}
@Test
fun aLocalAxisScaleOnAnUnrotatedPlacementIsThePageAxisScale() {
val original = placement(10f, 20f)
assertAffineClose(
scaleAboutAffine(50f, 60f, 2f, 0.5f),
localAxisScaleAboutAffine(original, 50f, 60f, 2f, 0.5f),
"with no rotation the tile axes are the page axes",
)
}
@Test
fun aPageAxisNonUniformScaleOnARotatedPlacementIsRefused() {
val original = placement(10f, 20f, rotationDegrees = 30f)
assertNull(original.composedWith(scaleAboutAffine(50f, 60f, 2f, 1f)), "a shear is not a placement")
}
@Test
fun aMirroredPlacementKeepsItsMirrorThroughAMove() {
val original = placement(10f, 20f, scaleX = -1f, rotationDegrees = 15f)
val moved = assertComposesExactly(original, translationAffine(4f, 4f))
assertClose(-1f, moved.scaleX, "the mirror survives as a negative x scale, not as a half-turn")
assertClose(1f, moved.scaleY, "scale y untouched")
assertClose(15f, moved.rotationDegrees, "rotation untouched")
}
@Test
fun aReducedImportedPlacementComposesAtItsOwnScale() {
// The corpus packs art reduced (modelC scales most of its tiles); a nudge must keep that scale.
val original = placement(100f, 200f, scaleX = 0.5f, scaleY = 0.5f, rotationDegrees = 270f)
val moved = assertComposesExactly(original, translationAffine(-10f, 6f))
assertClose(0.5f, moved.scaleX, "scale x kept")
assertClose(0.5f, moved.scaleY, "scale y kept")
assertClose(-90f, moved.rotationDegrees, "the angle comes back normalized to (-180, 180]")
}
@Test
fun aDegenerateProductIsRefused() {
assertNull(placement(10f, 20f, scaleX = 0f).composedWith(translationAffine(1f, 1f)), "a collapsed axis cannot be placed")
}
}
@@ -0,0 +1,301 @@
package org.umamo.edit
import org.umamo.runtime.model.AtlasComposition
import org.umamo.runtime.model.AtlasPage
import org.umamo.runtime.model.AtlasPlacement
import org.umamo.runtime.model.AtlasTile
import org.umamo.runtime.model.AtlasTileId
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableLayerBinding
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.PuppetAtlas
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.applyUvAffine
import org.umamo.runtime.model.invertUvAffine
import org.umamo.runtime.model.layerUvAffineOf
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the whole-atlas repack edit: pages and placements install atomically with every bound
* drawable's coordinates re-derived against the NEW page inventory (the exact read a per-tile fold
* gets wrong), unchanged mappings pass arrays through by reference, the session commit is one undo
* step under its own label, and malformed input throws instead of half-applying.
*/
class AtlasRepackEditsTest {
private val tileAId = AtlasTileId("tileA")
private val tileBId = AtlasTileId("tileB")
private fun placement(pageIndex: Int, x: Float, y: Float): AtlasPlacement =
AtlasPlacement(pageIndex, x, y, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f)
private fun meshedDrawable(id: String, tileId: AtlasTileId, uvs: FloatArray): Drawable =
Drawable(
id = DrawableId(id),
name = id,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 1f), uvs, intArrayOf(0, 0, 0)),
geometryGrid = null,
atlasTileId = tileId,
)
private fun packedModel(atlas: PuppetAtlas, drawables: List<Drawable>): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = emptyList(),
drawables = drawables,
rootChildren = emptyList(),
rootPartId = null,
canvasWidth = 100f,
canvasHeight = 200f,
worldOriginX = 50f,
worldOriginZ = 100f,
atlas = atlas,
)
/**
* The stored coordinates a tile's art uvs take under one placement, built independently of the
* edit's internals from the same corpus-proven affine algebra.
*
* @param FloatArray artUvs Coordinates in the tile's own frame.
* @param AtlasTileId tileId The tile they belong to.
* @param AtlasPlacement? placed Where the tile sits.
* @param AtlasPage page The page the placement names.
* @param Int tileSide The square tile's side in pixels.
* @return FloatArray The page-addressed stored coordinates.
*/
private fun storedUvsAt(
artUvs: FloatArray,
tileId: AtlasTileId,
placed: AtlasPlacement?,
page: AtlasPage,
tileSide: Int,
): FloatArray {
val binding = DrawableLayerBinding(tileId.raw, placed, page.width, page.height)
val storedToArt = assertNotNull(layerUvAffineOf(binding, tileSide, tileSide))
return applyUvAffine(artUvs, assertNotNull(invertUvAffine(storedToArt)))
}
private fun assertUvsClose(expected: FloatArray, actual: FloatArray, message: String) {
assertEquals(expected.size, actual.size, message)
for (componentIndex in expected.indices) {
assertTrue(
abs(expected[componentIndex] - actual[componentIndex]) < 1e-5f,
"$message: component $componentIndex expected ${expected[componentIndex]}, was ${actual[componentIndex]}",
)
}
}
@Test
fun repackInstallsPagesAndPlacementsAndKeepsEveryVertexOnItsArtPixel() {
val oldPage = AtlasPage(64, 64)
val newPage = AtlasPage(128, 128)
val oldA = placement(0, 4f, 4f)
val oldB = placement(0, 40f, 40f)
val atlas =
PuppetAtlas(
pages = listOf(oldPage),
tiles = listOf(AtlasTile(tileAId, "A", 16, 16, oldA), AtlasTile(tileBId, "B", 16, 16, oldB)),
)
val artUvsA = floatArrayOf(0.25f, 0.5f, 0.75f, 0.125f)
val artUvsB = floatArrayOf(0f, 0f, 1f, 1f)
val base =
packedModel(
atlas,
listOf(
meshedDrawable("dA", tileAId, storedUvsAt(artUvsA, tileAId, oldA, oldPage, 16)),
meshedDrawable("dB", tileBId, storedUvsAt(artUvsB, tileBId, oldB, oldPage, 16)),
),
)
val newA = placement(0, 100f, 8f)
val newB = placement(0, 8f, 100f)
val repacked = base.withAtlasRepack(listOf(newPage), mapOf(tileAId to newA, tileBId to newB))
assertEquals(listOf(newPage), repacked.atlas.pages, "the page inventory was replaced")
assertEquals(newA, repacked.atlas.tiles[0].placement)
assertEquals(newB, repacked.atlas.tiles[1].placement)
assertUvsClose(
storedUvsAt(artUvsA, tileAId, newA, newPage, 16),
repacked.drawables[0].mesh!!.uvs,
"tile A's drawable still addresses the same art pixels at the new spot",
)
assertUvsClose(
storedUvsAt(artUvsB, tileBId, newB, newPage, 16),
repacked.drawables[1].mesh!!.uvs,
"tile B's drawable still addresses the same art pixels at the new spot",
)
assertSame(
base.drawables[0].mesh!!.positions,
repacked.drawables[0].mesh!!.positions,
"moving art on a page never moves the mesh",
)
}
@Test
fun repackRederivesAgainstTheNewPageDimensionsNotTheOld() {
// The placement does not move at all; only the page grows. A fold through the per-tile edit
// would read the new mapping off the old 64px inventory and leave these coordinates untouched.
val samePlacement = placement(0, 4f, 4f)
val atlas =
PuppetAtlas(
pages = listOf(AtlasPage(64, 64)),
tiles = listOf(AtlasTile(tileAId, "A", 16, 16, samePlacement)),
)
val artUvs = floatArrayOf(0.5f, 0.5f)
val base =
packedModel(
atlas,
listOf(meshedDrawable("dA", tileAId, storedUvsAt(artUvs, tileAId, samePlacement, AtlasPage(64, 64), 16))),
)
val repacked = base.withAtlasRepack(listOf(AtlasPage(128, 128)), mapOf(tileAId to samePlacement))
assertUvsClose(
storedUvsAt(artUvs, tileAId, samePlacement, AtlasPage(128, 128), 16),
repacked.drawables.single().mesh!!.uvs,
"the coordinates renormalized against the new page size",
)
}
@Test
fun anUnchangedMappingPassesItsCoordinateArraysThroughByReference() {
val oldPage = AtlasPage(64, 64)
val stayA = placement(0, 4f, 4f)
val oldB = placement(0, 40f, 40f)
val atlas =
PuppetAtlas(
pages = listOf(oldPage),
tiles = listOf(AtlasTile(tileAId, "A", 16, 16, stayA), AtlasTile(tileBId, "B", 16, 16, oldB)),
)
val base =
packedModel(
atlas,
listOf(
meshedDrawable("dA", tileAId, floatArrayOf(0.1f, 0.1f)),
meshedDrawable("dB", tileBId, floatArrayOf(0.7f, 0.7f)),
),
)
val repacked = base.withAtlasRepack(listOf(oldPage), mapOf(tileAId to stayA, tileBId to placement(0, 8f, 40f)))
assertSame(base.drawables[0].mesh, repacked.drawables[0].mesh, "an unmoved tile's drawable is untouched")
assertFalse(
base.drawables[1].mesh!!.uvs.contentEquals(repacked.drawables[1].mesh!!.uvs),
"the moved tile's drawable re-derived",
)
val unchanged = base.withAtlasRepack(listOf(oldPage), mapOf(tileAId to stayA, tileBId to oldB))
assertSame(base, unchanged, "restating the atlas exactly is a no-op")
}
@Test
fun anUnpackedTileLowersItsArtFrameCoordinatesOntoThePage() {
val page = AtlasPage(64, 64)
val atlas =
PuppetAtlas(
pages = listOf(page),
tiles = listOf(AtlasTile(tileAId, "A", 16, 16, placement = null)),
)
// Unpacked art stores its coordinates in the tile's own frame.
val artUvs = floatArrayOf(0.25f, 0.5f)
val base = packedModel(atlas, listOf(meshedDrawable("dA", tileAId, artUvs.copyOf())))
val placed = placement(0, 32f, 16f)
val repacked = base.withAtlasRepack(listOf(page), mapOf(tileAId to placed))
assertUvsClose(
storedUvsAt(artUvs, tileAId, placed, page, 16),
repacked.drawables.single().mesh!!.uvs,
"packing never-packed art lowers its coordinates onto the page",
)
}
@Test
fun sessionCommitIsOneUndoStepUnderItsOwnLabel() {
val oldPage = AtlasPage(64, 64)
val oldA = placement(0, 4f, 4f)
val atlas = PuppetAtlas(pages = listOf(oldPage), tiles = listOf(AtlasTile(tileAId, "A", 16, 16, oldA)))
val base = packedModel(atlas, listOf(meshedDrawable("dA", tileAId, floatArrayOf(0.2f, 0.3f))))
val session = EditorSession(base)
val storedBefore = session.model.value.drawables.single().mesh!!.uvs.copyOf()
session.commitAtlasRepack(listOf(AtlasPage(128, 128)), mapOf(tileAId to placement(0, 60f, 60f)))
assertEquals(listOf(AtlasPage(128, 128)), session.model.value.atlas.pages)
assertTrue(session.dirty.value, "a repack is document content, so it dirties")
assertEquals("change.document.atlasRepack", DocumentChange.RepackAtlas(1, 1).labelKey)
session.undo()
assertEquals(listOf(oldPage), session.model.value.atlas.pages, "one undo restores the whole repack")
assertContentEquals(storedBefore, session.model.value.drawables.single().mesh!!.uvs)
assertFalse(session.dirty.value, "undo restores the saved model instance")
// Restating the current state commits nothing.
session.commitAtlasRepack(listOf(oldPage), mapOf(tileAId to oldA))
assertFalse(session.canUndo.value)
}
@Test
fun theCompositionLandsOnTheAtlasAndRidesUndo() {
val oldPage = AtlasPage(64, 64)
val oldA = placement(0, 4f, 4f)
val atlas = PuppetAtlas(pages = listOf(oldPage), tiles = listOf(AtlasTile(tileAId, "A", 16, 16, oldA)))
val base = packedModel(atlas, listOf(meshedDrawable("dA", tileAId, floatArrayOf(0.2f, 0.3f))))
val session = EditorSession(base)
val policy = AtlasComposition(alphaThreshold = 64, extrude = 0)
session.commitAtlasRepack(listOf(AtlasPage(128, 128)), mapOf(tileAId to placement(0, 60f, 60f)), policy)
assertEquals(policy, session.model.value.atlas.composition, "the pack's policy is recorded beside its placements")
session.undo()
assertEquals(AtlasComposition.Default, session.model.value.atlas.composition, "undo restores the policy the earlier pages derive under")
// A repack that names no policy keeps the atlas's current one, and a policy change alone is a change.
val repacked = session.model.value.withAtlasRepack(listOf(AtlasPage(128, 128)), mapOf(tileAId to placement(0, 60f, 60f)))
assertEquals(AtlasComposition.Default, repacked.atlas.composition)
val recomposed = repacked.withAtlasRepack(repacked.atlas.pages, mapOf(tileAId to placement(0, 60f, 60f)), policy)
assertEquals(policy, recomposed.atlas.composition, "the same placements under a new policy still produce a new atlas")
}
@Test
fun malformedInputThrowsInsteadOfHalfApplying() {
val page = AtlasPage(64, 64)
val atlas =
PuppetAtlas(
pages = listOf(page),
tiles = listOf(AtlasTile(tileAId, "A", 16, 16, placement(0, 4f, 4f))),
)
val base = packedModel(atlas, listOf(meshedDrawable("dA", tileAId, floatArrayOf(0.2f, 0.3f))))
assertFailsWith<IllegalArgumentException>("a repack must restate every tile") {
base.withAtlasRepack(listOf(page), emptyMap())
}
assertFailsWith<IllegalArgumentException>("a placement must name a page the repack ships") {
base.withAtlasRepack(listOf(page), mapOf(tileAId to placement(3, 4f, 4f)))
}
// A bound tile whose old mapping cannot invert has no expressible re-derivation.
val degenerate =
base.copy(
atlas =
atlas.copy(
tiles = listOf(AtlasTile(tileAId, "A", 16, 16, AtlasPlacement(0, 4f, 4f, 0f, 0f, 0f))),
),
)
assertFailsWith<IllegalArgumentException>("a bound tile with a degenerate mapping is refused") {
degenerate.withAtlasRepack(listOf(page), mapOf(tileAId to placement(0, 8f, 8f)))
}
}
}
@@ -0,0 +1,241 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyableTarget
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.KeyformOwner
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* The two-phase contract behind a property field's drag-scrub: preview is transient, commit is one step.
*
* A scrub that only reported its value on release moved the number and nothing else, so the viewport sat
* still for the whole gesture; one that committed per frame would bury the history under drag noise.
*/
class ChannelPreviewEditsTest {
private val angleX = ParameterId("ParamAngleX")
private val drawableId = DrawableId("d")
private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY)
/** The descriptor a real opacity row supplies - the same one whichever branch stores the value. */
private fun opacityChange(opacity: Float): Change = DrawableChange.SetOpacity(drawableId, opacity)
/** A drawable whose opacity channel is keyed when [keyed], and bare otherwise. */
private fun model(keyed: Boolean): PuppetModel =
PuppetModel(
parameters = listOf(Parameter(angleX, "ParamAngleX", min = -30f, max = 30f, default = 0f)),
parts = emptyList(),
deformers = emptyList(),
drawables =
listOf(
Drawable(
id = drawableId,
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
opacity = 1f,
channelGrids =
if (!keyed) {
ChannelGrids.Empty
} else {
ChannelGrids(
mapOf(
FormChannel.OPACITY to
KeyformGrid(
axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f, 30f))),
cells =
listOf(
KeyformCell(intArrayOf(0), ChannelValue.Scalar(1f)),
KeyformCell(intArrayOf(1), ChannelValue.Scalar(1f)),
KeyformCell(intArrayOf(2), ChannelValue.Scalar(1f)),
),
),
),
)
},
),
),
rootChildren = emptyList(),
rootPartId = null,
)
/** A preview reaches the renderer's override map without touching the document or the history. */
@Test
fun previewIsTransientOnAnUnkeyedChannel() {
val session = EditorSession(model(keyed = false))
session.previewChannelEdit(target, ChannelValue.Scalar(0.25f))
assertEquals(ChannelValue.Scalar(0.25f), session.pendingChannelEdits.value[target])
assertEquals(1f, session.model.value.drawables.first().opacity, "the document is untouched")
assertTrue(!session.canUndo.value, "a preview records no undo step")
}
/**
* Committing an unkeyed channel writes the static AND retires the preview.
*
* Without the retire the stale pending value keeps shadowing the static just written, so the field
* stays tinted as an uncommitted edit even though the edit landed.
*/
@Test
fun commitOnAnUnkeyedChannelWritesTheStaticAndRetiresThePreview() {
val session = EditorSession(model(keyed = false))
session.previewChannelEdit(target, ChannelValue.Scalar(0.25f))
session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) {
session.setDrawableOpacity(drawableId, 0.25f)
}
assertEquals(0.25f, session.model.value.drawables.first().opacity)
assertEquals(null, session.pendingChannelEdits.value[target], "the preview is retired")
assertTrue(session.canUndo.value, "the commit is one undo step")
}
/** A whole scrub is ONE undo step however many frames it previewed through. */
@Test
fun aScrubIsOneUndoStep() {
val session = EditorSession(model(keyed = false))
for (frame in 1..20) {
session.previewChannelEdit(target, ChannelValue.Scalar(frame / 20f))
}
session.editKeyedChannel(target, ChannelValue.Scalar(1f), opacityChange(1f)) {
session.setDrawableOpacity(drawableId, 0.5f)
}
session.undo()
assertEquals(1f, session.model.value.drawables.first().opacity, "one undo returns to the start")
assertTrue(!session.canUndo.value, "and there was only ever one step")
}
/**
* On a KEYED channel a commit stays pending, because writing the static would be shadowed by the track.
*/
@Test
fun commitOnAKeyedChannelStaysPending() {
val session = EditorSession(model(keyed = true))
session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) {
session.setDrawableOpacity(drawableId, 0.25f)
}
assertEquals(ChannelValue.Scalar(0.25f), session.pendingChannelEdits.value[target])
assertEquals(1f, session.model.value.drawables.first().opacity, "the static is not the store here")
}
/**
* A pending edit is an undo step, and undoing it puts the previous pending value back.
*
* The value is transient - the next pose move discards it - but discarding is not the same as never
* having happened. It shows in the viewport the moment it is made, which is the whole test of whether
* something belongs in history; Blender records the equivalent edit and the panel promises the same.
*/
@Test
fun aPendingEditIsItsOwnUndoStep() {
val session = EditorSession(model(keyed = true))
session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) {
session.setDrawableOpacity(drawableId, 0.25f)
}
assertTrue(session.canUndo.value, "the commit is one undo step")
session.editKeyedChannel(target, ChannelValue.Scalar(0.5f), opacityChange(0.5f)) {
session.setDrawableOpacity(drawableId, 0.5f)
}
session.undo()
assertEquals(ChannelValue.Scalar(0.25f), session.pendingChannelEdits.value[target], "back one edit")
session.undo()
assertEquals(null, session.pendingChannelEdits.value[target], "and back to none")
}
/** Previewing per frame records nothing; only the gesture's end does. */
@Test
fun aScrubOnAKeyedChannelIsAlsoOneUndoStep() {
val session = EditorSession(model(keyed = true))
for (frame in 1..20) {
session.previewChannelEdit(target, ChannelValue.Scalar(frame / 20f))
}
assertTrue(!session.canUndo.value, "twenty preview frames are not twenty steps")
session.editKeyedChannel(target, ChannelValue.Scalar(1f), opacityChange(1f)) {
session.setDrawableOpacity(drawableId, 1f)
}
session.undo()
assertEquals(null, session.pendingChannelEdits.value[target], "one undo clears the whole scrub")
assertTrue(!session.canUndo.value, "and there was only ever one step")
}
/** A pose move still discards every pending value - undo restores them, a scrub does not. */
@Test
fun aPoseMoveStillDiscardsAPendingEdit() {
val session = EditorSession(model(keyed = true))
session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) {
session.setDrawableOpacity(drawableId, 0.25f)
}
session.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f))
assertEquals(null, session.pendingChannelEdits.value[target], "the value was chosen for the old pose")
session.undo()
assertEquals(ChannelValue.Scalar(0.25f), session.pendingChannelEdits.value[target], "undo brings it back")
}
/** Retiring one target's preview leaves every other target's alone. */
@Test
fun retiringOnePreviewLeavesTheOthers() {
val session = EditorSession(model(keyed = false))
val other = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.DRAW_ORDER)
session.previewChannelEdit(target, ChannelValue.Scalar(0.25f))
session.previewChannelEdit(other, ChannelValue.Scalar(720f))
session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) {
session.setDrawableOpacity(drawableId, 0.25f)
}
assertEquals(null, session.pendingChannelEdits.value[target])
assertEquals(ChannelValue.Scalar(720f), session.pendingChannelEdits.value[other], "the other survives")
}
/**
* Re-typing a value the live step already records still puts it back in the viewport.
*
* The commit's no-op guard asks history, not the live map, and that is right - a scrub has already
* written its last preview frame there. But the two DO diverge: a pose scrub retires pending edits
* through the preview path, which records nothing, so a scrub that ends where it began leaves history
* holding a value the live map no longer has. Returning outright then dropped the re-typed value on the
* floor: no override reached the renderer and the field showed none of its uncommitted-edit tint.
*/
@Test
fun reTypingAValueHistoryStillHoldsRepublishesIt() {
val session = EditorSession(model(keyed = true))
session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) {
session.setDrawableOpacity(drawableId, 0.25f)
}
// What a scrub away and back does: the preview path retires the pending edit without recording that
// it did, and the commit then declines because the pose came home.
session.clearPendingChannelEdits()
session.commitPose(ParameterChange.SetValue(listOf(angleX)), session.pose.value)
assertEquals(null, session.pendingChannelEdits.value[target], "the scrub retired it")
session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) {
session.setDrawableOpacity(drawableId, 0.25f)
}
assertEquals(
ChannelValue.Scalar(0.25f),
session.pendingChannelEdits.value[target],
"the re-typed value is live again even though the step records nothing new",
)
}
}
@@ -0,0 +1,276 @@
package org.umamo.edit
import org.umamo.runtime.eval.warpControlPointsAt
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.WarpLatticeForm
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Verifies warp-deformer create: lattice fit, drawable bind + UV remap, and the session selection /
* refuse paths.
*/
class DeformerCreateEditsTest {
private val drawableA = DrawableId("a")
private val drawableB = DrawableId("b")
private val partId = PartId("p")
private val angleX = ParameterId("ParamAngleX")
private fun mesh(positions: FloatArray): DrawableMesh =
DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2))
private fun drawable(id: DrawableId, positions: FloatArray, parent: DeformerId? = null, grid: KeyformGrid<MeshDeltaForm>? = null): Drawable =
Drawable(
id = id,
name = id.raw,
parentDeformerId = parent,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = mesh(positions),
geometryGrid = grid,
)
private fun model(drawables: List<Drawable>, deformers: List<Deformer> = emptyList()): PuppetModel =
PuppetModel(
parameters = listOf(Parameter(angleX, "Angle X", -1f, 1f, 0f)),
parts = listOf(Part(partId, "P", drawables.map { OrgChild.Drawable(it.id) })),
deformers = deformers,
drawables = drawables,
rootChildren = listOf(OrgChild.Part(partId)),
rootPartId = null,
)
/** A 1×1 lattice is four corners of the rect, row-major with Y ascending. */
@Test
fun rectLatticeIsRowMajorYAscending() {
val points = rectLatticeControlPoints(0f, 10f, 20f, 30f, rows = 1, columns = 1)
assertEquals(listOf(0f, 10f, 20f, 10f, 0f, 30f, 20f, 30f), points.toList())
}
/** Creating a warp wraps the drawable, remaps rest positions into UV, and keeps the art put. */
@Test
fun createWarpBindsAndRemapsDrawable() {
val start =
model(
listOf(
drawable(drawableA, floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f)),
),
)
val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp Deformer", listOf(drawableA))
val warp = after.deformers.filterIsInstance<Deformer.Warp>().single()
assertEquals(DeformerId("Warp"), warp.id)
assertEquals(partId, warp.partId)
assertNotNull(warp.geometryGrid)
val bound = after.drawables.single { it.id == drawableA }
assertEquals(DeformerId("Warp"), bound.parentDeformerId)
// With 5% padding on a 10×10 box from (0,0)-(10,10): lattice is (-0.5,-0.5)-(10.5,10.5).
// Corner (0,0) → ((0+0.5)/11, (0+0.5)/11).
val positions = assertNotNull(bound.mesh).positions
assertEquals((0.5f / 11f), positions[0], absoluteTolerance = 1e-5f)
assertEquals((0.5f / 11f), positions[1], absoluteTolerance = 1e-5f)
// The rest lattice samples at any pose (0-axis grid).
assertNotNull(warpControlPointsAt(warp.geometryGrid, { 0f }))
}
/** Keyed mesh deltas scale with the lattice extent so morphs stay correct after the UV remap. */
@Test
fun createWarpRemapsKeyedDeltas() {
val grid =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))),
listOf(
KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f))),
KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(11f, 0f, 11f, 0f, 11f, 0f))),
),
)
val start = model(listOf(drawable(drawableA, floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f), grid = grid)))
val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp", listOf(drawableA))
val remapped = assertNotNull(after.drawables.single().geometryGrid)
val high = remapped.cells.single { it.coordinate.single() == 1 }.form.positionDeltas
// width = 11 after padding; 11 / 11 = 1.
assertEquals(1f, high[0], absoluteTolerance = 1e-5f)
}
/** Already-parented drawables insert the new warp under their shared parent. */
@Test
fun alreadyParentedDrawableInsertsUnderSharedParent() {
val existing =
Deformer.Warp(
DeformerId("Existing"),
"Existing",
parent = null,
partId = partId,
rows = 1,
columns = 1,
isQuadTransform = true,
geometryGrid =
KeyformGrid(
emptyList(),
listOf(KeyformCell(IntArray(0), WarpLatticeForm(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f)))),
),
)
val start =
model(
listOf(drawable(drawableA, floatArrayOf(0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f), parent = DeformerId("Existing"))),
listOf(existing),
)
val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp", listOf(drawableA))
val warp = after.deformers.filterIsInstance<Deformer.Warp>().single { it.id == DeformerId("Warp") }
assertEquals(DeformerId("Existing"), warp.parent)
assertEquals(DeformerId("Warp"), after.drawables.single { it.id == drawableA }.parentDeformerId)
}
/**
* Cubism-style parented meshes keep canvas units in the rest buffer and land in parent UV only
* after default-pose deltas — the new lattice must fit that UV AABB, not the canvas rest.
*/
@Test
fun parentedKeyedMeshFitsLatticeInParentUv() {
val existing =
Deformer.Warp(
DeformerId("Existing"),
"Existing",
parent = null,
partId = partId,
rows = 1,
columns = 1,
isQuadTransform = true,
geometryGrid =
KeyformGrid(
emptyList(),
listOf(KeyformCell(IntArray(0), WarpLatticeForm(floatArrayOf(0f, 0f, 100f, 0f, 0f, 100f, 100f, 100f)))),
),
)
// Rest in canvas-ish units; deltas pull the default pose into parent UV ≈ (0.2,0.2)-(0.8,0.8).
val rest = floatArrayOf(20f, 20f, 80f, 20f, 20f, 80f)
val deltas = floatArrayOf(-19.8f, -19.8f, -79.2f, -19.8f, -19.8f, -79.2f)
val grid =
KeyformGrid(
emptyList(),
listOf(KeyformCell(IntArray(0), MeshDeltaForm(deltas))),
)
val start =
model(
listOf(drawable(drawableA, rest, parent = DeformerId("Existing"), grid = grid)),
listOf(existing),
)
val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp", listOf(drawableA))
val warp = after.deformers.filterIsInstance<Deformer.Warp>().single { it.id == DeformerId("Warp") }
val cps = assertNotNull(warpControlPointsAt(warp.geometryGrid) { 0f })
// UV fit of (0.2,0.2)-(0.8,0.8) with 5% pad → (0.17,0.17)-(0.83,0.83); all CPs stay in ~[0,1].
for (index in cps.indices) {
assertTrue(cps[index] in -0.05f..1.05f, "cp[$index]=${cps[index]} should be parent-UV, not canvas")
}
assertTrue(cps[0] < 0.25f)
assertTrue(cps[cps.size - 2] > 0.75f)
}
/** Mixed parent deformers among the create list refuse the whole op. */
@Test
fun mixedParentsRefuse() {
val parentA =
Deformer.Warp(
DeformerId("A"),
"A",
null,
partId,
1,
1,
true,
KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), WarpLatticeForm(FloatArray(8))))),
)
val parentB =
Deformer.Warp(
DeformerId("B"),
"B",
null,
partId,
1,
1,
true,
KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), WarpLatticeForm(FloatArray(8))))),
)
val start =
model(
listOf(
drawable(drawableA, floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), parent = DeformerId("A")),
drawable(drawableB, floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), parent = DeformerId("B")),
),
listOf(parentA, parentB),
)
assertTrue(start === start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp", listOf(drawableA, drawableB)))
}
/** Session create selects the new deformer; an empty selection notices and returns null. */
@Test
fun sessionCreateSelectsWarpAndRefusesEmpty() {
val session =
EditorSession(
model(
listOf(
drawable(drawableA, floatArrayOf(0f, 0f, 4f, 0f, 0f, 4f)),
drawable(drawableB, floatArrayOf(10f, 10f, 14f, 10f, 10f, 14f)),
),
),
)
assertNull(session.createWarpDeformerForSelection("Warp Deformer"))
assertEquals("notice.deformer.createWarp.none", session.notice.value?.messageKey)
session.setMode(EditorMode.Edit)
session.setSelection(Selection(setOf(SelectionTarget.Drawable(drawableA)), SelectionTarget.Drawable(drawableA)))
val id = assertNotNull(session.createWarpDeformerForSelection("Warp Deformer"))
assertEquals(SelectionTarget.Deformer(id), session.selection.value.active)
assertEquals(EditorMode.Object, session.mode.value)
assertEquals(id, session.model.value.drawables.first { it.id == drawableA }.parentDeformerId)
}
/** A part selection expands to its subtree meshes. */
@Test
fun partSelectionExpandsToMeshes() {
val start =
model(
listOf(
drawable(drawableA, floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f)),
drawable(drawableB, floatArrayOf(4f, 4f, 6f, 4f, 4f, 6f)),
),
)
val ids =
start.drawablesForWarpCreate(Selection(setOf(SelectionTarget.Part(partId)), SelectionTarget.Part(partId)))
assertEquals(listOf(drawableA, drawableB), ids)
}
/** freshDeformerId skips collisions. */
@Test
fun freshIdAvoidsCollision() {
val existing =
Deformer.Warp(
DeformerId("Warp"),
"Warp",
null,
null,
1,
1,
true,
KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), WarpLatticeForm(FloatArray(8))))),
)
assertEquals(DeformerId("Warp2"), model(emptyList(), listOf(existing)).freshDeformerId())
}
}
@@ -0,0 +1,99 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyableTarget
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.KeyformOwner
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* Pins the ONE keyable-row edit-routing rule: a KEYED channel's typed value goes pending (writing the
* static would be shadowed by the track, so the edit would appear silently rejected), and an unkeyed
* channel writes the static. Centralized here rather than hand-copied per row, since a rule duplicated
* across every row is exactly the kind of thing that drifts - some rows carry it correctly and others
* silently do not.
*/
class EditKeyedChannelTest {
private val angleX = ParameterId("ParamAngleX")
private val drawableId = DrawableId("d")
private val keyedTarget = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY)
private val unkeyedTarget = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.MULTIPLY_COLOR)
/** The descriptor a real opacity row supplies - the same one whichever branch stores the value. */
private fun change(opacity: Float): Change = DrawableChange.SetOpacity(drawableId, opacity)
private fun session(): EditorSession {
val opacityTrack =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))),
listOf<KeyformCell<ChannelValue>>(
KeyformCell(intArrayOf(0), ChannelValue.Scalar(0.25f)),
KeyformCell(intArrayOf(1), ChannelValue.Scalar(1f)),
),
)
val drawable =
Drawable(
id = drawableId,
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
channelGrids = ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack)),
)
return EditorSession(
PuppetModel(
parameters = listOf(Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f)),
parts = emptyList(),
deformers = emptyList(),
drawables = listOf(drawable),
rootChildren = emptyList(),
rootPartId = null,
),
)
}
/** A keyed channel's edit goes pending; the static write path must not run. */
@Test
fun aKeyedChannelGoesPending() {
val editorSession = session()
var staticWrites = 0
editorSession.editKeyedChannel(keyedTarget, ChannelValue.Scalar(0.5f), change(0.5f)) { staticWrites++ }
assertEquals(0, staticWrites, "the shadowed static must not be written")
assertEquals(
ChannelValue.Scalar(0.5f),
editorSession.pendingChannelEdits.value[keyedTarget],
"the typed value waits as a pending edit for `I`",
)
assertTrue(editorSession.canUndo.value, "and it is still one undo step")
}
/** An unkeyed channel has no track to shadow it, so the static is the real store. */
@Test
fun anUnkeyedChannelWritesTheStatic() {
val editorSession = session()
var staticWrites = 0
editorSession.editKeyedChannel(unkeyedTarget, ChannelValue.Scalar(0.5f), change(0.5f)) { staticWrites++ }
assertEquals(1, staticWrites, "the unkeyed path writes the static")
assertFalse(unkeyedTarget in editorSession.pendingChannelEdits.value, "nothing is left pending")
assertTrue(editorSession.pendingChannelEdits.value.isEmpty())
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,135 @@
package org.umamo.edit
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Pins Photoshop-style free-transform scale math: opposite-corner pivots, edge-only axes, Alt-from-center,
* and Shift-uniform on corners.
*/
class FreeTransformTest {
/** A 40 x 20 axis-aligned quad from (-10, -5) to (30, 15). */
private val quad =
floatArrayOf(
-10f,
-5f,
30f,
-5f,
30f,
15f,
-10f,
15f,
)
private val all = setOf(0, 1, 2, 3)
@Test
fun selectionBoundsReportsMinMax() {
val bounds = selectionBounds(quad, all)
assertEquals(-10f, bounds.minX)
assertEquals(-5f, bounds.minY)
assertEquals(30f, bounds.maxX)
assertEquals(15f, bounds.maxY)
assertEquals(40f, bounds.width)
assertEquals(20f, bounds.height)
}
@Test
fun cornerDragScalesAboutOppositeCorner() {
val start = selectionBounds(quad, all)
// Drag the max-x / max-y corner to twice the width and height from the opposite corner.
val targetX = start.minX + start.width * 2f
val targetY = start.minY + start.height * 2f
val scaled =
scaledByHandleDrag(
quad,
all,
start,
BoundsHandle.MaxXMaxY,
targetX,
targetY,
)
val bounds = selectionBounds(scaled, all)
assertEquals(start.minX, bounds.minX, 1e-4f)
assertEquals(start.minY, bounds.minY, 1e-4f)
assertEquals(start.width * 2f, bounds.width, 1e-4f)
assertEquals(start.height * 2f, bounds.height, 1e-4f)
}
@Test
fun edgeDragScalesOnlyOneAxis() {
val start = selectionBounds(quad, all)
val scaled =
scaledByHandleDrag(
quad,
all,
start,
BoundsHandle.MaxXMidY,
start.minX + start.width * 1.5f,
start.centerY,
)
val bounds = selectionBounds(scaled, all)
assertEquals(start.width * 1.5f, bounds.width, 1e-4f)
assertEquals(start.height, bounds.height, 1e-4f)
assertEquals(start.minX, bounds.minX, 1e-4f)
}
@Test
fun fromCenterKeepsBoundsCenterFixed() {
val start = selectionBounds(quad, all)
val scaled =
scaledByHandleDrag(
quad,
all,
start,
BoundsHandle.MaxXMaxY,
start.centerX + start.width,
start.centerY + start.height,
fromCenter = true,
)
val bounds = selectionBounds(scaled, all)
assertEquals(start.centerX, bounds.centerX, 1e-4f)
assertEquals(start.centerY, bounds.centerY, 1e-4f)
assertEquals(start.width * 2f, bounds.width, 1e-4f)
assertEquals(start.height * 2f, bounds.height, 1e-4f)
}
@Test
fun uniformCornerUsesSharedFactor() {
val start = selectionBounds(quad, all)
// Pull mostly in x; with uniform, y should match the x factor.
val scaled =
scaledByHandleDrag(
quad,
all,
start,
BoundsHandle.MaxXMaxY,
start.minX + start.width * 2f,
start.minY + start.height * 1.1f,
uniform = true,
)
val bounds = selectionBounds(scaled, all)
assertEquals(start.width * 2f, bounds.width, 1e-4f)
assertEquals(start.height * 2f, bounds.height, 1e-4f)
}
@Test
fun degenerateAxisStaysFinite() {
val flat = floatArrayOf(0f, 7f, 10f, 7f, 20f, 7f)
val indices = setOf(0, 1, 2)
val start = selectionBounds(flat, indices)
val scaled =
scaledByHandleDrag(
flat,
indices,
start,
BoundsHandle.MaxXMaxY,
40f,
100f,
)
assertTrue(scaled.all { it.isFinite() })
val bounds = selectionBounds(scaled, indices)
assertEquals(0f, bounds.height, 1e-4f)
}
}
@@ -0,0 +1,83 @@
package org.umamo.edit
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins [History.amendTop], the primitive behind adjusting the last operation: it rewrites the live
* step in place without growing the stack or moving the cursor, refuses while a redo branch exists,
* and works at the oldest entry under a cap of one.
*/
class HistoryAmendTest {
private val part = Part(PartId("a"), "A", children = emptyList())
private fun model(name: String): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = listOf(part.copy(name = name)),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = listOf(OrgChild.Part(PartId("a"))),
rootPartId = null,
)
private fun snapshot(name: String): EditorSnapshot = EditorSnapshot(model(name), Selection(), emptyMap())
private fun rename(name: String): PartChange.Rename = PartChange.Rename(PartId("a"), name)
private fun liveName(history: History): String = history.current.model.parts.first().name
@Test
fun amendingReplacesTheLiveStepWithoutGrowingTheStack() {
val history = History(snapshot("seed"))
history.push(snapshot("first"), rename("first"))
history.push(snapshot("second"), rename("second"))
val adjusted = rename("second-adjusted")
assertTrue(history.amendTop(snapshot("second-adjusted"), adjusted))
assertEquals(3, history.steps.size, "the stack did not grow")
assertEquals(2, history.cursorIndex, "the cursor stayed on the live step")
assertEquals("second-adjusted", liveName(history))
assertSame(adjusted, history.currentChange, "the entry carries the amended change")
history.undo()
assertEquals("first", liveName(history), "undo steps to the base the operation ran from")
history.redo()
assertEquals("second-adjusted", liveName(history), "redo returns to the amended result")
}
@Test
fun anAmendRefusesWhileARedoBranchExists() {
val history = History(snapshot("seed"))
history.push(snapshot("first"), rename("first"))
history.push(snapshot("second"), rename("second"))
history.undo()
assertFalse(history.amendTop(snapshot("first-adjusted"), rename("first-adjusted")))
assertEquals("first", liveName(history), "the refused amend changed nothing")
history.redo()
assertEquals("second", liveName(history), "the redo branch survived")
}
@Test
fun anAmendAtTheOldestEntryWorksUnderACapOfOne() {
val history = History(snapshot("seed"), initialLimit = 1)
history.push(snapshot("first"), rename("first"))
assertEquals(1, history.steps.size, "the cap dropped the seed")
assertEquals(0, history.cursorIndex)
assertTrue(history.amendTop(snapshot("first-adjusted"), rename("first-adjusted")))
assertEquals("first-adjusted", liveName(history))
assertEquals(1, history.steps.size)
assertFalse(history.canUndo, "no base survives in the stack - the record holds it instead")
}
}
@@ -0,0 +1,181 @@
package org.umamo.edit
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Verifies the retained-undo-step cap: that pushing past it drops the oldest steps while keeping the
* cursor on the live one, that a degenerate cap still retains a usable stack, and that reassigning the
* cap at runtime (what the History Steps preference does) trims immediately without ever discarding the
* live step or a reachable redo branch.
*/
class HistoryLimitTest {
private val part = Part(PartId("a"), "A", children = emptyList())
private fun model(name: String): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = listOf(part.copy(name = name)),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = listOf(OrgChild.Part(PartId("a"))),
rootPartId = null,
)
private fun snapshot(name: String): EditorSnapshot = EditorSnapshot(model(name), Selection(), emptyMap())
/**
* Pushes [count] distinguishable steps, numbered from 1 so a step's name identifies its ordinal.
*
* @param History history The stack to push onto.
* @param Int count The number of steps to record.
*/
private fun pushSteps(history: History, count: Int) {
for (stepNumber in 1..count) {
history.push(snapshot("step$stepNumber"), PartChange.Rename(PartId("a"), "step$stepNumber"))
}
}
/**
* The name carried by the live step, which identifies which push the cursor sits on.
*
* @param History history The stack to read.
* @return String The live snapshot's part name.
*/
private fun liveName(history: History): String = history.current.model.parts.first().name
/**
* Pushing past the cap drops the oldest steps from the front, leaving the stack exactly at the cap with
* the cursor still on the newest push.
*/
@Test
fun pushingPastTheCapDropsTheOldestSteps() {
val history = History(snapshot("seed"), 5)
pushSteps(history, 12)
assertEquals(5, history.steps.size)
assertEquals(4, history.cursorIndex)
assertEquals("step12", liveName(history))
// The seed and steps 1-7 are gone; the retained window starts at step 8.
assertEquals("step8", history.steps.first().snapshot.model.parts.first().name)
}
/**
* A cap below 1 clamps to a single retained step rather than emptying the stack, so the live state is
* always readable and the stack never indexes out of range.
*/
@Test
fun capBelowOneClampsToASingleRetainedStep() {
val history = History(snapshot("seed"), 0)
assertEquals(1, history.limit)
pushSteps(history, 3)
assertEquals(1, history.steps.size)
assertEquals(0, history.cursorIndex)
assertEquals("step3", liveName(history))
assertTrue(!history.canUndo && !history.canRedo, "a one-step stack has nothing to undo or redo")
history.limit = -10
assertEquals(1, history.limit)
assertEquals(1, history.steps.size)
}
/**
* Lowering the cap trims the stack there and then - the preference frees memory without waiting for the
* next edit - while the live step itself is untouched.
*/
@Test
fun loweringTheCapTrimsImmediately() {
val history = History(snapshot("seed"), 100)
pushSteps(history, 20)
val liveSnapshot = history.current
history.limit = 4
assertEquals(4, history.steps.size)
assertEquals(3, history.cursorIndex)
assertSame(liveSnapshot, history.current, "trimming must not move the live step")
assertEquals("step17", history.steps.first().snapshot.model.parts.first().name)
}
/**
* With the cursor mid-history the trim stops at the live step: the current state and every reachable
* redo step survive, so the stack may legitimately still exceed the cap until later pushes shed it.
*/
@Test
fun loweringTheCapNeverTrimsPastTheLiveStep() {
val history = History(snapshot("seed"), 100)
pushSteps(history, 20)
// Walk back five steps, so the cursor sits at index 15 with a five-entry redo branch ahead of it.
repeat(5) { history.undo() }
val liveSnapshot = history.current
assertEquals("step15", liveName(history))
history.limit = 2
assertSame(liveSnapshot, history.current, "the live step must survive any trim")
assertEquals(0, history.cursorIndex, "the trim stops once the live step reaches the front")
// Six entries remain: the live step plus the five redo steps it can still reach.
assertEquals(6, history.steps.size)
assertTrue(history.canRedo, "a reachable redo branch is never discarded by a trim")
assertTrue(!history.canUndo, "everything before the live step was trimmed away")
// The excess sheds on the next push, which discards the redo branch and applies the cap in full.
history.push(snapshot("after"), PartChange.Rename(PartId("a"), "after"))
assertEquals(2, history.steps.size)
assertEquals("after", liveName(history))
}
/**
* Raising the cap keeps every retained entry and simply allows the stack to grow further.
*/
@Test
fun raisingTheCapKeepsExistingSteps() {
val history = History(snapshot("seed"), 5)
pushSteps(history, 5)
assertEquals(5, history.steps.size)
history.limit = 10
assertEquals(5, history.steps.size, "raising the cap discards nothing")
assertEquals("step5", liveName(history))
pushSteps(history, 5)
assertEquals(10, history.steps.size)
}
/**
* The session's cap - the property the preference writes - trims the stack and republishes the derived
* state, so the history panel drops the same rows and canUndo reflects the shortened stack.
*/
@Test
fun sessionCapTrimsAndRepublishesTheHistoryView() {
val session = EditorSession(model("A"))
for (stepNumber in 1..8) {
session.mutate(PartChange.Rename(PartId("a"), "A$stepNumber")) { it.withPartName(PartId("a"), "A$stepNumber") }
}
// Seed plus eight edits.
assertEquals(9, session.historyView.value.steps.size)
assertTrue(session.canUndo.value)
session.historyLimit = 3
val view = session.historyView.value
assertEquals(3, view.steps.size)
assertEquals(2, view.cursor)
assertEquals("A8", session.model.value.parts.first().name, "trimming must not change the live model")
assertTrue(session.canUndo.value, "two older steps are still retained")
// Down to a single step: nothing is left to undo, and the panel shows exactly the live row.
session.historyLimit = 1
assertEquals(1, session.historyView.value.steps.size)
assertEquals(0, session.historyView.value.cursor)
assertTrue(!session.canUndo.value)
assertEquals("A8", session.model.value.parts.first().name)
}
}
@@ -0,0 +1,184 @@
package org.umamo.edit
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* The keyform sheet's key selection as session state, and the two ways of publishing one.
*
* The distinction under test is the whole reason [EditorSession.stageKeySelection] exists: a click on a mark
* both selects the key and scrubs the pose onto it, and recording those separately makes one click take two
* presses of Ctrl+Z to reverse. Staging folds the selection into the step the scrub is about to record.
*/
class KeySelectionTest {
private val angleX = ParameterId("ParamAngleX")
private fun session(): EditorSession =
EditorSession(
PuppetModel(
parameters = listOf(Parameter(angleX, angleX.raw, min = -30f, max = 30f, default = 0f)),
parts = emptyList(),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = emptyList(),
rootPartId = null,
),
)
private fun keyAt(keyIndex: Int): TrackKeyRef = TrackKeyRef(angleX, "drawable:d/OPACITY", keyIndex)
/** A fresh document has nothing selected. */
@Test
fun startsEmpty() {
assertTrue(session().keySelection.value.isEmpty())
}
/** Selecting keys is its own undo step, and undo brings the previous selection back. */
@Test
fun selectingIsItsOwnUndoStep() {
val editorSession = session()
editorSession.setKeySelection(setOf(keyAt(0)))
editorSession.setKeySelection(setOf(keyAt(0), keyAt(1)))
assertEquals(setOf(keyAt(0), keyAt(1)), editorSession.keySelection.value)
editorSession.undo()
assertEquals(setOf(keyAt(0)), editorSession.keySelection.value, "back to the first selection")
editorSession.undo()
assertTrue(editorSession.keySelection.value.isEmpty(), "and back to none")
}
/** Selecting what is already selected records nothing - a re-click is not an edit. */
@Test
fun reselectingTheSameKeysRecordsNothing() {
val editorSession = session()
editorSession.setKeySelection(setOf(keyAt(0)))
editorSession.setKeySelection(setOf(keyAt(0)))
editorSession.undo()
assertTrue(editorSession.keySelection.value.isEmpty(), "one undo, not two")
}
/** A selection is not a document change, so it must not mark the file unsaved. */
@Test
fun selectingDoesNotDirtyTheDocument() {
val editorSession = session()
editorSession.setKeySelection(setOf(keyAt(0)))
assertFalse(editorSession.dirty.value)
}
/**
* A staged selection publishes immediately but records nothing on its own - the commit that follows
* carries it, so the pair is ONE undo step.
*/
@Test
fun aStagedSelectionRidesTheFollowingCommit() {
val editorSession = session()
editorSession.stageKeySelection(setOf(keyAt(2)))
assertEquals(setOf(keyAt(2)), editorSession.keySelection.value, "it publishes at once")
assertFalse(editorSession.canUndo.value, "but records nothing by itself")
editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f))
editorSession.undo()
assertTrue(editorSession.keySelection.value.isEmpty(), "one undo reverses the click's selection")
assertEquals(0f, editorSession.pose.value[angleX], "and its scrub, together")
assertFalse(editorSession.canUndo.value, "because they were one step")
}
/**
* Clicking a mark selects it AND lands the pose on it, as one step named for the selection.
*
* The label matters: the entry used to read "Adjust Parameters", which described the consequence rather
* than the act - the rigger clicked a keyframe.
*/
@Test
fun selectingAtAPoseIsOneStepNamedForTheSelection() {
val editorSession = session()
editorSession.selectKeysAtPose(setOf(keyAt(1)), mapOf(angleX to 30f))
assertEquals(setOf(keyAt(1)), editorSession.keySelection.value)
assertEquals(30f, editorSession.pose.value[angleX])
assertEquals("change.keyform.select", editorSession.liveStepLabelKey(), "named for the selection")
editorSession.undo()
assertTrue(editorSession.keySelection.value.isEmpty(), "one undo reverses both")
assertEquals(0f, editorSession.pose.value[angleX])
assertFalse(editorSession.canUndo.value)
}
/**
* Clicking the key the pose ALREADY sits on still records the selection.
*
* The case that rules out staging the selection behind an ordinary pose commit: that commit
* short-circuits on an unchanged pose, so the selection would never reach history at all and the click
* would be silently unrecoverable.
*/
@Test
fun selectingWithoutMovingThePoseStillRecords() {
val editorSession = session()
editorSession.selectKeysAtPose(setOf(keyAt(0)), editorSession.pose.value)
assertTrue(editorSession.canUndo.value, "the selection is the whole step here")
editorSession.undo()
assertTrue(editorSession.keySelection.value.isEmpty())
}
/** Re-clicking the same key at the same pose records nothing. */
@Test
fun reselectingAtTheSamePoseRecordsNothing() {
val editorSession = session()
editorSession.selectKeysAtPose(setOf(keyAt(0)), editorSession.pose.value)
editorSession.selectKeysAtPose(setOf(keyAt(0)), editorSession.pose.value)
editorSession.undo()
assertTrue(editorSession.keySelection.value.isEmpty(), "one undo, not two")
}
/**
* A staged selection the following commit DECLINED to record is recorded by the confirming
* [EditorSession.setKeySelection] instead.
*
* The gesture is an empty-track press at the value the playhead already holds: it drops the selection and
* then scrubs nowhere, so the pose commit short-circuits. Staging alone left the selection changed with
* nothing in history to undo it - the one failure mode the stage / edit / confirm rule exists to close.
*/
@Test
fun aStagedSelectionTheCommitDroppedIsRecordedByTheConfirm() {
val editorSession = session()
editorSession.setKeySelection(setOf(keyAt(0), keyAt(1)))
editorSession.stageKeySelection(emptySet())
editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), editorSession.pose.value)
editorSession.setKeySelection(editorSession.keySelection.value)
assertTrue(editorSession.keySelection.value.isEmpty(), "the press dropped the selection")
editorSession.undo()
assertEquals(setOf(keyAt(0), keyAt(1)), editorSession.keySelection.value, "and undo brings it back")
}
/**
* The confirm is a no-op when the edit it follows already carried the staged selection - one gesture
* stays one undo step.
*/
@Test
fun confirmingASelectionTheCommitAlreadyCarriedRecordsNothing() {
val editorSession = session()
editorSession.stageKeySelection(setOf(keyAt(2)))
editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f))
editorSession.setKeySelection(setOf(keyAt(2)))
editorSession.undo()
assertTrue(editorSession.keySelection.value.isEmpty(), "one undo reverses the whole gesture")
assertEquals(0f, editorSession.pose.value[angleX], "selection and scrub together")
assertFalse(editorSession.canUndo.value, "so the confirm added no second step")
}
/** The label key of the live history step - what the History panel would show for it. */
private fun EditorSession.liveStepLabelKey(): String? = historyView.value.let { view -> view.steps[view.cursor].labelKey }
}
@@ -0,0 +1,257 @@
package org.umamo.edit
import org.umamo.runtime.keyform.axisIndexOf
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyableTarget
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.KeyformOwner
import org.umamo.runtime.model.KeyformTrackRef
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the keyform AIM semantics - which parameter an edit writes on, and whether it acts where the user
* pointed or where the pose stands.
*
* These rules used to live in the UI module taking a Compose hover type, where nothing could exercise them
* without a composition; both of the bugs they encode (an aimed edit landing on the targeted axis instead of
* the pointed-at one, and an aim at empty track space falling back to the pose) shipped because of that.
*/
class KeyformAimEditsTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
private val drawableId = DrawableId("d")
private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY)
private val track = KeyformTrackRef.Channel(target)
/** The sheet row the opacity track is drawn on - opaque to this module, and identity for a selected key. */
private val row = "drawable:d/OPACITY"
/**
* A session whose drawable has an opacity track keyed at the ends of [keyedOn]'s range, with both
* parameters present and [ParameterId] angleX targeted.
*/
private fun session(keyedOn: ParameterId = angleX): EditorSession {
val opacityTrack =
KeyformGrid(
listOf(KeyformAxis(keyedOn, floatArrayOf(-1f, 1f))),
listOf<KeyformCell<ChannelValue>>(
KeyformCell(intArrayOf(0), ChannelValue.Scalar(0.25f)),
KeyformCell(intArrayOf(1), ChannelValue.Scalar(1f)),
),
)
val drawable =
Drawable(
id = drawableId,
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
channelGrids = ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack)),
)
val editorSession =
EditorSession(
PuppetModel(
parameters =
listOf(
Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f),
Parameter(angleY, angleY.raw, min = -1f, max = 1f, default = 0f),
),
parts = emptyList(),
deformers = emptyList(),
drawables = listOf(drawable),
rootChildren = emptyList(),
rootPartId = null,
),
)
editorSession.setParameterSelection(ParameterSelection.of(angleX))
return editorSession
}
/** The opacity track's key positions on [parameterId]'s axis, or null when it is not keyed on it. */
private fun EditorSession.keysOn(parameterId: ParameterId): List<Float>? {
val grid = model.value.drawables.single().channelGrids[FormChannel.OPACITY] ?: return null
val axisIndex = grid.axisIndexOf(parameterId)
return if (axisIndex < 0) null else grid.axes[axisIndex].keys.toList()
}
/** An aimed capture keys WHERE it was aimed, not at the pose the rig happens to stand in. */
@Test
fun anAimedCaptureKeysWhereItWasAimed() {
val editorSession = session()
editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Position(0.5f, keyIndex = null))
assertEquals(listOf(-1f, 0.5f, 1f), editorSession.keysOn(angleX))
}
/** A capture at the pose stores the PENDING typed value and consumes it. */
@Test
fun aPoseCaptureStoresThePendingEdit() {
val editorSession = session()
editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f))
editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Pose)
assertEquals(listOf(-1f, 0f, 1f), editorSession.keysOn(angleX), "the pose's key was added")
assertEquals(
ChannelValue.Scalar(0.75f),
editorSession.model.value.channelValueAt(target, editorSession.pose.value),
"the key holds the value that was typed, not the value that was stored",
)
assertTrue(editorSession.pendingChannelEdits.value.isEmpty(), "the captured pending edit was consumed")
}
/**
* The capture's own history step records the pending edit as CONSUMED, so redo does not resurrect it.
*
* A snapshot defaults every field to live state, so clearing the pending edit after the capture pushed
* left the consumed value inside the step that consumed it: redoing the capture re-showed the
* uncommitted-edit warning over the very key that now stores the value, and left the session's live map
* disagreeing with its own history about what was still pending.
*/
@Test
fun redoingAPoseCaptureDoesNotResurrectTheConsumedEdit() {
val editorSession = session()
editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f))
editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Pose)
editorSession.undo()
editorSession.redo()
assertTrue(
editorSession.pendingChannelEdits.value.isEmpty(),
"the capture step holds no pending edit, because the capture is what consumed it",
)
assertEquals(listOf(-1f, 0f, 1f), editorSession.keysOn(angleX), "and the key it captured is back")
}
/**
* An aimed edit keeps the sheet's key selection on the key it named, as ONE undo step.
*
* Both directions of the same renumbering rule. An insert shifts every key at or above it up one
* ordinal, so a selected mark to the right of the insertion point must shift with it to keep naming the
* same key; a removal shifts every key above it down one ordinal, so a selected mark above a removed key
* must shift the same way rather than staying on the ordinal the removal freed.
*/
@Test
fun anAimedEditCarriesTheKeySelectionWithIt() {
val editorSession = session()
// Keys at [-1, 1] with the one at 1 selected; the insert at 0 lands between them.
editorSession.setKeySelection(setOf(TrackKeyRef(angleX, row, 1)))
editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Position(0f, keyIndex = null), row)
assertEquals(listOf(-1f, 0f, 1f), editorSession.keysOn(angleX))
assertEquals(
setOf(TrackKeyRef(angleX, row, 2)),
editorSession.keySelection.value,
"the selection follows its own key past the one just inserted below it",
)
// And back out again: the removal renumbers the other way.
editorSession.removeKeyOnTrack(track, angleX, KeyformAim.Position(0f, keyIndex = 1), row)
assertEquals(listOf(-1f, 1f), editorSession.keysOn(angleX))
assertEquals(
setOf(TrackKeyRef(angleX, row, 1)),
editorSession.keySelection.value,
"and back down again when the key below it goes",
)
}
/** An insert ABOVE the selection renumbers nothing, and the whole capture stays one undo step. */
@Test
fun anInsertAboveTheSelectionLeavesItAloneAndRecordsOneStep() {
val editorSession = session()
editorSession.setKeySelection(setOf(TrackKeyRef(angleX, row, 0)))
editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Position(0f, keyIndex = null), row)
assertEquals(setOf(TrackKeyRef(angleX, row, 0)), editorSession.keySelection.value, "nothing below it moved")
editorSession.undo()
assertEquals(listOf(-1f, 1f), editorSession.keysOn(angleX), "one undo reverses the whole capture")
assertEquals(setOf(TrackKeyRef(angleX, row, 0)), editorSession.keySelection.value)
}
/**
* Aiming at track space with no key there removes NOTHING - it must not fall back to the pose, which
* would destroy a key the user never pointed at.
*/
@Test
fun anAimAtEmptyTrackSpaceRemovesNothing() {
val editorSession = session()
// The pose stands exactly on a key, so a pose-fallback would have something to delete.
editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to -1f))
val modelBefore = editorSession.model.value
editorSession.removeKeyOnTrack(track, angleX, KeyformAim.Position(0.3f, keyIndex = null))
assertSame(modelBefore, editorSession.model.value, "aiming at nothing removed nothing")
assertEquals(listOf(-1f, 1f), editorSession.keysOn(angleX))
}
/** With no place aimed at, a removal takes the key the pose is standing on. */
@Test
fun aPoseRemovalTakesTheKeyUnderThePose() {
val editorSession = session()
editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to -1f))
editorSession.removeKeyOnTrack(track, angleX, KeyformAim.Pose)
assertEquals(null, editorSession.keysOn(angleX), "the last key went, so the channel is unkeyed again")
}
/**
* A named parameter beats the targeted one: a linked pad's second section is keyed on an axis that is
* not the selection's active member, and an edit aimed there must land on THAT axis.
*/
@Test
fun theNamedParameterBeatsTheTargetedOne() {
val editorSession = session(keyedOn = angleY)
assertEquals(angleX, editorSession.parameterSelection.value.active, "angleX is what is targeted")
editorSession.captureKeyOnTrack(track, angleY, KeyformAim.Position(0.5f, keyIndex = null))
assertEquals(listOf(-1f, 0.5f, 1f), editorSession.keysOn(angleY), "the key landed on the named axis")
assertEquals(null, editorSession.keysOn(angleX), "the targeted axis was not touched")
}
/** With no parameter named, the edit falls back to the targeted one. */
@Test
fun anUnnamedParameterFallsBackToTheTarget() {
val editorSession = session()
editorSession.captureKeyOnTrack(track, parameterId = null, aim = KeyformAim.Position(0.5f, keyIndex = null))
assertEquals(listOf(-1f, 0.5f, 1f), editorSession.keysOn(angleX))
}
/** With nothing named and nothing targeted there is no axis to write on, so the model is untouched. */
@Test
fun noParameterAtAllRefuses() {
val editorSession = session()
editorSession.setParameterSelection(ParameterSelection())
val modelBefore = editorSession.model.value
editorSession.captureKeyOnTrack(track, parameterId = null, aim = KeyformAim.Position(0.5f, keyIndex = null))
assertSame(modelBefore, editorSession.model.value)
assertNotNull(editorSession.notice.value, "the refusal is announced rather than silent")
}
}
@@ -0,0 +1,232 @@
package org.umamo.edit
import org.umamo.runtime.eval.scalarAt
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.ColorRgb
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyableTarget
import org.umamo.runtime.model.KeyformOwner
import org.umamo.runtime.model.KeyformTrackRef
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the scalar / color keyform authoring loop: bind, capture, remove, and undo.
*
* These channels come first precisely because they need no deformer-chain inverse - the capture always
* lands on a key, so the write is a plain assignment. What the tests below are really guarding is the two
* evaluator-forced invariants that make the difference between a key that works and one that makes art
* disappear: a seeded axis SPANS the parameter's range, and removal COLLAPSES below two keys.
*/
class KeyformChannelEditsTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
private val drawableId = DrawableId("d")
private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY)
private fun parameter(id: ParameterId): Parameter = Parameter(id, id.raw, min = -30f, max = 30f, default = 0f)
private fun model(): PuppetModel =
PuppetModel(
parameters = listOf(parameter(angleX), parameter(angleY)),
parts = emptyList(),
deformers = emptyList(),
drawables =
listOf(
Drawable(
id = drawableId,
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
opacity = 0.25f,
),
),
rootChildren = emptyList(),
rootPartId = null,
)
/** The opacity a model's drawable evaluates to at [value] on [parameterId]. */
private fun opacityAt(puppet: PuppetModel, parameterId: ParameterId, value: Float): Float {
val drawable = puppet.drawables.single()
return drawable.channelGrids.scalarAt(
FormChannel.OPACITY,
drawable.opacity,
paramValue = { id -> if (id == parameterId) value else 0f },
)
}
/**
* The first capture BINDS: it seeds an axis spanning min / default / max holding the entity's current
* static value, then writes the captured value at the pose.
*
* Spanning matters - an axis that stopped short would leave the channel falling back to its static at
* the ends of the slider, which reads as the key mysteriously not applying.
*/
@Test
fun theFirstCaptureBindsAnAxisSpanningTheRange() {
val captured =
model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f))
val track = assertNotNull(captured.drawables.single().channelGrids[FormChannel.OPACITY])
assertEquals(listOf(angleX), track.axes.map { it.parameterId })
assertEquals(listOf(-30f, 0f, 15f, 30f), track.axes.single().keys.toList(), "seeded min/default/max plus the captured key")
assertEquals(1f, opacityAt(captured, angleX, 15f), "the captured value lands at the pose")
assertEquals(0.25f, opacityAt(captured, angleX, -30f), "the static holds at the ends - binding alone changed nothing")
assertEquals(0.25f, opacityAt(captured, angleX, 30f))
}
/** Capturing on a second parameter adds an axis and preserves the motion already authored. */
@Test
fun capturingOnASecondParameterPreservesExistingMotion() {
val first = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 30f), ChannelValue.Scalar(1f))
val second = first.withChannelKeyCaptured(target, parameter(angleY), mapOf(angleY to 30f), ChannelValue.Scalar(0.5f))
val track = assertNotNull(second.drawables.single().channelGrids[FormChannel.OPACITY])
assertEquals(listOf(angleX, angleY), track.axes.map { it.parameterId }, "the new axis is appended")
// angleY sits at its default, so the angleX motion authored first must read back unchanged.
assertEquals(1f, opacityAt(second, angleX, 30f), "the first parameter's motion survives the second bind")
}
/** A capture at a pose already on a key overwrites that cell without reshaping the axis. */
@Test
fun capturingOnAnExistingKeyOverwrites() {
val first = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f))
val second = first.withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(0.5f))
val track = assertNotNull(second.drawables.single().channelGrids[FormChannel.OPACITY])
assertEquals(4, track.axes.single().keys.size, "no new key was added")
assertEquals(0.5f, opacityAt(second, angleX, 15f))
}
/**
* A capture on a parameter whose range cannot seed an axis (min == max) is refused ENTIRELY. The old
* receiver-returning refusal let the capture proceed and write keys onto the channel's OTHER axes -
* mutating motion on a parameter the user never targeted.
*/
@Test
fun aCaptureOnADegenerateParameterIsRefusedEntirely() {
val degenerate = Parameter(angleY, angleY.raw, min = 5f, max = 5f, default = 5f)
val first = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f))
val second = first.withChannelKeyCaptured(target, degenerate, mapOf(angleX to 30f, angleY to 5f), ChannelValue.Scalar(0.1f))
assertSame(first, second, "the refusal must not write onto the channel's other axes")
}
/**
* A capture whose pose falls in the window between EPS_KEY (not on a key) and EPS_SPAN (too close to
* insert beside one) refuses the WHOLE op. The old guard compared against the pre-seed grid, so a
* fresh bind whose capture then refused still committed the bare axis - the channel read as keyed while
* the typed value was silently dropped.
*/
@Test
fun aCaptureInTheEpsilonWindowCommitsNoBareBind() {
val start = model()
val captured = start.withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 0.00125f), ChannelValue.Scalar(1f))
assertSame(start, captured, "no bind-only commit: the channel must not read as keyed without the value")
}
/**
* An insert aimed past the parameter's ends clamps to the range - the lane's edge inset extrapolates
* pixel hits past the domain, and an unclamped insert would author a key no scrub can ever reach.
*/
@Test
fun anInsertPastTheRangeClampsToTheEnd() {
val editorSession =
EditorSession(model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f)))
editorSession.insertTrackKeyAt(KeyformTrackRef.Channel(target), parameter(angleX), -31.7f)
val axis = editorSession.model.value.drawables.single().channelGrids[FormChannel.OPACITY]!!.axes.single()
assertEquals(-30f, axis.keys.first(), "the clamped hit coincides with the min key, so nothing was added")
assertEquals(4, axis.keys.size, "no out-of-range key was authored")
}
/**
* Inserting past the last authored key copies that last value, not the static (render's out-of-span
* fallback). Keys at -30/0/15 with last value 1; insert at 30 must land 1, not opacity 0.25.
*/
@Test
fun insertingPastTheLastKeyCopiesTheLastChannelValue() {
val keyed =
model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f))
// Drop the seeded max key so 30 sits past the authored span (keys become -30, 0, 15).
val shortened = keyed.withChannelKeyRemoved(target, parameter(angleX), mapOf(angleX to 30f))
val session = EditorSession(shortened)
session.insertTrackKeyAt(KeyformTrackRef.Channel(target), parameter(angleX), 30f)
assertEquals(1f, opacityAt(session.model.value, angleX, 30f), "past-last insert holds the last authored value")
assertEquals(
listOf(-30f, 0f, 15f, 30f),
session.model.value.drawables.single().channelGrids[FormChannel.OPACITY]!!.axes.single().keys.toList(),
)
}
/** A value of the wrong kind for the channel is refused rather than silently stored. */
@Test
fun aMismatchedValueKindIsRefused() {
val start = model()
val colorIntoScalar =
start.withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Color(ColorRgb(1f, 0f, 0f)))
assertSame(start, colorIntoScalar)
}
/** Removing an interior key leaves the axis intact. */
@Test
fun removingAnInteriorKeyKeepsTheAxis() {
val captured = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f))
val removed = captured.withChannelKeyRemoved(target, parameter(angleX), mapOf(angleX to 15f))
val track = assertNotNull(removed.drawables.single().channelGrids[FormChannel.OPACITY])
assertEquals(listOf(-30f, 0f, 30f), track.axes.single().keys.toList())
}
/**
* Removing down past two keys collapses the axis, and collapsing the only axis drops the track - the
* channel goes back to its static rather than being left on a one-key axis that resolves nowhere.
*/
@Test
fun removingPastTwoKeysUnbindsTheChannel() {
var puppet = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f))
for (keyValue in listOf(15f, 0f, -30f)) {
puppet = puppet.withChannelKeyRemoved(target, parameter(angleX), mapOf(angleX to keyValue))
}
assertTrue(puppet.drawables.single().channelGrids.isEmpty, "the track is gone")
assertFalse(puppet.isChannelKeyedOn(target, angleX))
assertEquals(0.25f, opacityAt(puppet, angleX, 15f), "the channel reads its static again")
}
/** A pose that is not ON a key removes nothing - picking "the nearest" would be a guess. */
@Test
fun removingBetweenKeysIsARefusal() {
val captured = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f))
assertSame(captured, captured.withChannelKeyRemoved(target, parameter(angleX), mapOf(angleX to 7f)))
}
/** Capture and removal are each one undo step, and undo restores the prior track exactly. */
@Test
fun captureAndRemovalUndoAsSingleSteps() {
val session = EditorSession(model())
session.captureChannelKey(target, parameter(angleX), ChannelValue.Scalar(1f))
assertTrue(session.model.value.isChannelKeyedOn(target, angleX))
session.removeChannelKey(target, parameter(angleX))
session.undo()
assertTrue(session.model.value.isChannelKeyedOn(target, angleX), "undo restores the removed key")
session.undo()
assertFalse(session.model.value.isChannelKeyedOn(target, angleX), "undo again unbinds the channel")
}
}
@@ -0,0 +1,521 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.KeyformOwner
import org.umamo.runtime.model.KeyformTrackRef
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.WarpLatticeForm
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* The geometry-track key ops - the half of the keyform sheet that has no channel behind it.
*
* Worth its own suite because geometry is the majority of what a corpus rig puts on screen, and because
* its hide semantics differ per owner: a drawable falls back to its rest mesh when its grid goes away, a
* deformer has no rest lattice and would vanish.
*/
class KeyformGeometryEditsTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
private val drawableId = DrawableId("d")
private val deformerId = DeformerId("w")
private val parameter = Parameter(angleX, "ParamAngleX", min = -30f, max = 30f, default = 0f)
/** A three-key mesh-delta grid over ParamAngleX, one delta per key. */
private fun meshGrid(): KeyformGrid<MeshDeltaForm> =
KeyformGrid(
axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f, 30f))),
cells =
listOf(
KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(-1f, 0f))),
KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(0f, 0f))),
KeyformCell(intArrayOf(2), MeshDeltaForm(floatArrayOf(1f, 0f))),
),
)
private fun model(): PuppetModel =
PuppetModel(
parameters = listOf(parameter),
parts = emptyList(),
deformers =
listOf(
Deformer.Warp(
id = deformerId,
name = "w",
parent = null,
partId = null,
rows = 2,
columns = 2,
isQuadTransform = true,
geometryGrid =
KeyformGrid(
axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f, 30f))),
cells =
listOf(
KeyformCell(intArrayOf(0), WarpLatticeForm(FloatArray(8))),
KeyformCell(intArrayOf(1), WarpLatticeForm(FloatArray(8))),
KeyformCell(intArrayOf(2), WarpLatticeForm(FloatArray(8))),
),
),
),
),
drawables =
listOf(
Drawable(
id = drawableId,
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = meshGrid(),
),
),
rootChildren = emptyList(),
rootPartId = null,
)
/**
* A two-parameter model whose drawable keys on the VERTICAL axis only - the linked-pad shape.
*
* A pad targets both its axes but reports only the horizontal one as active, so this is the model where
* "write on the active parameter" and "write on the one the rigger meant" give different answers.
*/
private fun padModel(): PuppetModel {
val vertical = Parameter(angleY, "ParamAngleY", min = -30f, max = 30f, default = 0f)
val onVertical = KeyformGrid(listOf(KeyformAxis(angleY, floatArrayOf(-30f, 0f, 30f))), meshGrid().cells)
val base = model()
return base.copy(
parameters = listOf(parameter, vertical),
drawables = listOf(base.drawables.single().copy(geometryGrid = onVertical)),
)
}
/** The drawable's geometry axis keys after an edit. */
private fun keysOf(puppet: PuppetModel): List<Float> =
assertNotNull(puppet.drawables.single().geometryGrid).axes.single().keys.toList()
/** Moving a geometry key repositions it without touching the cells it addresses. */
@Test
fun movingAGeometryKeyRepositionsIt() {
val moved = model().withGeometryKeyMoved(KeyformOwner.Drawable(drawableId), parameter, keyIndex = 1, toValue = 12f)
assertEquals(listOf(-30f, 12f, 30f), keysOf(moved))
assertEquals(
listOf(-1f, 0f, 1f),
assertNotNull(moved.drawables.single().geometryGrid)
.cells
.sortedBy { cell -> cell.coordinate[0] }
.map { cell -> cell.form.positionDeltas[0] },
"a move changes key positions only - the cells stay where they were",
)
}
/**
* A key dragged past its neighbour CROSSES it, taking its own form along.
*
* The axis re-sorts and the cells permute to match, so the deformation the rigger authored stays with
* the key they dragged rather than staying at the ordinal it vacated.
*/
@Test
fun movingAGeometryKeyCrossesItsNeighbour() {
val moved = model().withGeometryKeyMoved(KeyformOwner.Drawable(drawableId), parameter, keyIndex = 1, toValue = 99f)
assertEquals(listOf(-30f, 30f, 99f), keysOf(moved), "the axis re-sorts")
assertEquals(
listOf(-1f, 1f, 0f),
assertNotNull(moved.drawables.single().geometryGrid)
.cells
.sortedBy { cell -> cell.coordinate[0] }
.map { cell -> cell.form.positionDeltas[0] },
"the moved key's own form (0) travelled to the end; the key it passed (1) shifted down",
)
}
/** Inserting a geometry key holds the interpolated form, so the deformation through it is unchanged. */
@Test
fun insertingAGeometryKeyHoldsTheInterpolatedForm() {
val inserted = model().withGeometryKeyInserted(KeyformOwner.Drawable(drawableId), parameter, 15f)
assertEquals(listOf(-30f, 0f, 15f, 30f), keysOf(inserted))
val grid = assertNotNull(inserted.drawables.single().geometryGrid)
// Halfway between the deltas at 0 and 30, which hold 0 and 1.
val insertedCell = assertNotNull(grid.cells.firstOrNull { cell -> cell.coordinate[0] == 2 })
assertEquals(0.5f, insertedCell.form.positionDeltas[0], 1e-5f)
}
/**
* Sheet/lane insert past the last key copies that last keyform (hold), not the first.
*
* Capture samples out of the key span before writing; without hold-extrapolation that sample was the
* first cell (or rest-zero), so the new end key looked like the start of the axis.
*/
@Test
fun insertingPastTheLastKeyCopiesTheLastForm() {
val shortGrid =
KeyformGrid(
axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f))),
cells =
listOf(
KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(-1f, 0f))),
KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(7f, 0f))),
),
)
val shortWarp =
KeyformGrid(
axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f))),
cells =
listOf(
KeyformCell(intArrayOf(0), WarpLatticeForm(FloatArray(8) { -1f })),
KeyformCell(intArrayOf(1), WarpLatticeForm(FloatArray(8) { 7f })),
),
)
val base = model()
val session =
EditorSession(
base.copy(
drawables = listOf(base.drawables.single().copy(geometryGrid = shortGrid)),
deformers =
listOf(
(base.deformers.single() as Deformer.Warp).copy(geometryGrid = shortWarp),
),
),
)
session.insertTrackKeyAt(KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)), parameter, 30f)
val meshGrid = assertNotNull(session.model.value.drawables.single().geometryGrid)
assertEquals(listOf(-30f, 0f, 30f), meshGrid.axes.single().keys.toList())
assertEquals(
7f,
meshGrid.cells.first { cell -> cell.coordinate[0] == 2 }.form.positionDeltas[0],
"drawable past-last insert copies the last keyform",
)
session.insertTrackKeyAt(KeyformTrackRef.Geometry(KeyformOwner.Deformer(deformerId)), parameter, 30f)
val warpGrid = assertNotNull((session.model.value.deformers.single() as Deformer.Warp).geometryGrid)
assertEquals(listOf(-30f, 0f, 30f), warpGrid.axes.single().keys.toList())
assertEquals(
7f,
warpGrid.cells.first { cell -> cell.coordinate[0] == 2 }.form.controlPoints[0],
"warp past-last insert copies the last lattice, not the first",
)
}
/** Removing down past two keys collapses a drawable's axis - it falls back to its rest mesh. */
@Test
fun removingCollapsesADrawablesAxis() {
val owner = KeyformOwner.Drawable(drawableId)
val once = model().withGeometryKeyRemoved(owner, parameter, keyIndex = 1)
assertEquals(listOf(-30f, 30f), keysOf(once))
val twice = once.withGeometryKeyRemoved(owner, parameter, keyIndex = 1)
assertNull(twice.drawables.single().geometryGrid, "below two keys the axis collapses entirely")
}
/** The same removal is REFUSED on a deformer, which has no rest lattice to fall back to. */
@Test
fun removingRefusesToUnkeyADeformer() {
val owner = KeyformOwner.Deformer(deformerId)
val once = model().withGeometryKeyRemoved(owner, parameter, keyIndex = 1)
val warp = once.deformers.single() as Deformer.Warp
assertEquals(listOf(-30f, 30f), assertNotNull(warp.geometryGrid).axes.single().keys.toList())
val refused = once.withGeometryKeyRemoved(owner, parameter, keyIndex = 1)
assertSame(once, refused, "collapsing a deformer's last axis would hide it, so it is refused")
}
/** A part carries no geometry, so every op leaves the model alone rather than throwing. */
@Test
fun ownersWithoutGeometryAreLeftAlone() {
val puppet = model()
val owner = KeyformOwner.Glue(drawableId, drawableId)
assertSame(puppet, puppet.withGeometryKeyMoved(owner, parameter, keyIndex = 0, toValue = 10f))
assertSame(puppet, puppet.withGeometryKeyInserted(owner, parameter, 10f))
assertSame(puppet, puppet.withGeometryKeyRemoved(owner, parameter, keyIndex = 0))
}
/**
* Two keys close enough to draw on the same pixel are still individually addressable.
*
* The case that made dragging one of a near-coincident pair move the other: a value-based lookup
* resolves to whichever key is nearer, and within EPS_KEY that is a coin toss. Nothing forbids keys
* this close - forbidding them would be the wrong cure - so the ordinal has to carry the identity.
*/
@Test
fun nearCoincidentKeysAreStillIndividuallyAddressable() {
val owner = KeyformOwner.Drawable(drawableId)
// Walk the middle key to within a hair of the last one, then move the LAST one and check the
// middle stayed put - a value-based lookup would have grabbed whichever it reached first.
val crowded = model().withGeometryKeyMoved(owner, parameter, keyIndex = 1, toValue = 30f)
val middle = keysOf(crowded)[1]
assertTrue(30f - middle < 0.01f, "the middle key should have clamped right up against the last (at $middle)")
val moved = crowded.withGeometryKeyMoved(owner, parameter, keyIndex = 2, toValue = 99f)
assertEquals(middle, keysOf(moved)[1], "moving the last key must not disturb the one beside it")
}
/**
* A pose resolves to the ordinal of the key it is standing on, and to nothing between keys.
*
* What `Alt+I` acts on. Removing "the nearest key" instead would guess at which one the user meant,
* and a wrong guess silently destroys authored work.
*/
@Test
fun aPoseResolvesToTheKeyItStandsOn() {
val puppet = model()
val geometry = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
assertEquals(1, puppet.trackKeyIndexAtPose(geometry, parameter, mapOf(angleX to 0f)))
assertEquals(2, puppet.trackKeyIndexAtPose(geometry, parameter, mapOf(angleX to 30f)))
assertEquals(-1, puppet.trackKeyIndexAtPose(geometry, parameter, mapOf(angleX to 15f)), "between keys")
}
/** An owner with no geometry resolves to nothing rather than throwing. */
@Test
fun aTrackWithNoGridResolvesToNothing() {
val glue = KeyformTrackRef.Geometry(KeyformOwner.Glue(drawableId, drawableId))
assertEquals(-1, model().trackKeyIndexAtPose(glue, parameter, mapOf(angleX to 0f)))
}
/**
* Moving several keys to one destination is ONE undo step, and each lands on its own track.
*
* The summary-row drag: marks stacked at a value stay stacked, and one Ctrl+Z restores all of them.
*/
@Test
fun movingSeveralKeysToOneValueIsOneStep() {
val session = EditorSession(model())
val drawableTrack = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
val deformerTrack = KeyformTrackRef.Geometry(KeyformOwner.Deformer(deformerId))
session.moveTrackKeys(
listOf(Triple(drawableTrack, parameter, 1), Triple(deformerTrack, parameter, 1)),
toValue = 12f,
)
assertEquals(listOf(-30f, 12f, 30f), keysOf(session.model.value), "the drawable's key moved")
val warp = session.model.value.deformers.single() as Deformer.Warp
assertEquals(
listOf(-30f, 12f, 30f),
assertNotNull(warp.geometryGrid).axes.single().keys.toList(),
"and so did the deformer's, to the same place",
)
session.undo()
assertEquals(listOf(-30f, 0f, 30f), keysOf(session.model.value), "one undo restores both")
assertTrue(!session.canUndo.value, "because there was only ever one step")
}
/**
* A key dragged ONTO its neighbour reports its own new ordinal, not the neighbour's.
*
* Dragging a group into the axis end piles the leading key onto the key already sitting there, and the
* collision nudge pushes it EPS_SPAN aside. EPS_SPAN is WIDER than the EPS_KEY tolerance an
* ordinal lookup uses, so asking "which key is at the value I requested" found the key that was already
* there and handed back ITS ordinal - moving the sheet's selection onto the wrong mark, and collapsing
* two selected keys into one entry when both resolved to it.
*/
@Test
fun aKeyDraggedOntoItsNeighbourReportsItsOwnOrdinal() {
val session = EditorSession(model())
val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
// Keys [-30, 0, 30] with 0 and 30 selected, dragged left until the key at 0 reaches the key at -30.
val landed = session.dragTrackKeys(listOf(Triple(track, parameter, 1), Triple(track, parameter, 2)), fraction = -0.5f)
val keys = keysOf(session.model.value)
assertEquals(-30f, keys[0], "the key already at the end did not move")
assertTrue(keys[1] > -30f && keys[1] < -29.99f, "the dragged key was nudged clear of it, at ${keys[1]}")
assertEquals(0f, keys[2])
assertEquals(listOf(1, 2), landed, "the dragged keys report THEIR ordinals, not the resident key's")
}
/**
* With two parameters targeted and no axis named, an unaimed key edit PARKS instead of guessing.
*
* The linked-pad case: a 2D pad targets both its axes but reports only the horizontal one as active, so
* writing on the active one would silently always key the horizontal parameter and leave the vertical
* section reading as unkeyed. Answering the prompt replays the very same edit with the axis filled in.
*/
@Test
fun anAmbiguousTargetParksTheEditUntilAnAxisIsPicked() {
// The drawable keys on the VERTICAL axis only, while the pad reports the horizontal one as active -
// so writing on the active parameter would refuse outright and the pick has to be what decides.
val session = EditorSession(padModel())
session.setParameterSelection(ParameterSelection(setOf(angleX, angleY), active = angleX))
val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
session.captureKeyOnTrack(track, parameterId = null, aim = KeyformAim.Position(15f, keyIndex = null))
val parked = assertNotNull(session.pendingParameterChoice.value, "the edit parks rather than guessing")
assertEquals(KeyformAction.Capture, parked.action)
assertContentEquals(listOf(angleX, angleY), parked.candidates, "listed in model order")
assertEquals(listOf(-30f, 0f, 30f), keysOf(session.model.value), "and nothing was written yet")
session.resolveParameterChoice(angleY)
assertNull(session.pendingParameterChoice.value, "answering clears the prompt")
assertEquals(listOf(-30f, 0f, 15f, 30f), keysOf(session.model.value), "the key landed on the PICKED axis")
}
/** A caller that names its axis - every sheet lane does - never sees the prompt. */
@Test
fun aNamedAxisBypassesTheChoicePrompt() {
val session = EditorSession(padModel())
session.setParameterSelection(ParameterSelection(setOf(angleX, angleY), active = angleX))
val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
session.captureKeyOnTrack(track, parameterId = angleY, aim = KeyformAim.Position(15f, keyIndex = null))
assertNull(session.pendingParameterChoice.value, "a named axis is the answer, so nothing is asked")
assertEquals(listOf(-30f, 0f, 15f, 30f), keysOf(session.model.value))
}
/**
* Dragging a multi-key selection moves every member by the same distance, keeping their spacing.
*
* The whole point of a group drag: a delta applied per key preserves the shape the rigger authored,
* where the summary drag's send-them-all-to-one-value deliberately does not.
*/
@Test
fun draggingASelectionMovesEveryKeyByTheSameDistance() {
val session = EditorSession(model())
val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
// -30 and 0, dragged a tenth of the 60-wide range: +6 each.
val landed = session.dragTrackKeys(listOf(Triple(track, parameter, 0), Triple(track, parameter, 1)), fraction = 0.1f)
assertEquals(listOf(-24f, 6f, 30f), keysOf(session.model.value))
assertEquals(listOf(0, 1), landed, "neither key crossed anything, so both keep their ordinals")
session.undo()
assertEquals(listOf(-30f, 0f, 30f), keysOf(session.model.value), "one undo restores the whole drag")
assertTrue(!session.canUndo.value, "because it was one step")
}
/**
* The drag stops at the MOST CONSTRAINED member rather than clamping each key on its own.
*
* Per-key clamping would let the keys nearest the end pile up while the rest kept travelling, silently
* destroying the spacing - which is exactly the thing a group drag exists to preserve.
*/
@Test
fun aGroupDragStopsAtItsMostConstrainedMember() {
val session = EditorSession(model())
val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
// The key at 30 is already at the maximum, so the whole drag is refused rather than collapsing the pair.
session.dragTrackKeys(listOf(Triple(track, parameter, 1), Triple(track, parameter, 2)), fraction = 0.5f)
assertEquals(listOf(-30f, 0f, 30f), keysOf(session.model.value), "nothing moved, so nothing piled up")
// Half of that is reachable: the key at 0 can take +15, the key at 30 cannot move at all.
session.dragTrackKeys(listOf(Triple(track, parameter, 0), Triple(track, parameter, 1)), fraction = 0.25f)
assertEquals(listOf(-15f, 15f, 30f), keysOf(session.model.value), "both moved the same 15, and the gap is intact")
}
/** A key that crosses a neighbour reports its NEW ordinal, so the caller's selection can follow it. */
@Test
fun aGroupDragReportsWhereEachKeyLanded() {
val session = EditorSession(model())
val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
// Only the FIRST key is selected; dragging it +40 carries it past the key at 0.
val landed = session.dragTrackKeys(listOf(Triple(track, parameter, 0)), fraction = 40f / 60f)
assertEquals(listOf(0f, 10f, 30f), keysOf(session.model.value), "it crossed the key at 0 and the axis re-sorted")
assertEquals(listOf(1), landed, "and it now sits at ordinal 1")
}
/** Each member is clamped to its OWN parameter's range, so a mixed batch cannot push one out of range. */
@Test
fun aBatchMoveClampsPerParameter() {
val session = EditorSession(model())
val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
session.moveTrackKeys(listOf(Triple(track, parameter, 1)), toValue = 9999f)
assertEquals(30f, keysOf(session.model.value).last(), "clamped to the parameter's maximum")
}
/**
* The landing QUERIES answer exactly what the edits they describe report.
*
* The sheet asks before the edit, because its key selection rides the edit's own snapshot and a selection
* re-pointed afterwards reaches no history entry at all. A query computed independently of the edit
* could disagree with what the edit actually produces, so both go through one planner: the landing a
* caller previews is guaranteed to be the landing the edit lands on.
*/
@Test
fun theLandingQueriesAgreeWithTheEditsTheyDescribe() {
val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId))
// A single key dragged past its neighbour: keys [-30, 0, 30], the first sent to +10.
val moveSession = EditorSession(model())
val predictedMove = moveSession.model.value.trackKeyIndexAfterMove(track, parameter, keyIndex = 0, toValue = 10f)
assertEquals(1, predictedMove, "it crosses the key at 0")
assertEquals(predictedMove, moveSession.moveTrackKey(track, parameter, keyIndex = 0, toValue = 10f))
// The same crossing as a group drag, and a clamp the drag refuses outright.
val dragSession = EditorSession(model())
val keys = listOf(Triple(track, parameter, 0))
val predictedDrag = dragSession.model.value.trackKeyDragLandings(keys, fraction = 40f / 60f)
assertEquals(listOf(1), predictedDrag)
assertEquals(predictedDrag, dragSession.dragTrackKeys(keys, fraction = 40f / 60f))
assertEquals(
listOf(1),
dragSession.model.value.trackKeyDragLandings(listOf(Triple(track, parameter, 1)), fraction = 0f),
"a drag that moves nothing reports the ordinals it was given",
)
}
/**
* Binding a warp's geometry to a parameter it did not yet key - any parameter, not a fixed set - seeds
* the axis and leaves the lattice looking the same at every pose until a later capture changes a cell.
*/
@Test
fun capturingInsertsOnADrawableMidPose() {
val owner = KeyformOwner.Drawable(drawableId)
val mid = model().withGeometryKeyCaptured(owner, parameter, mapOf(angleX to 15f))
assertEquals(listOf(-30f, 0f, 15f, 30f), keysOf(mid))
}
@Test
fun capturingBindsAWarpToAnyParameter() {
val angleYParam = Parameter(angleY, "ParamAngleY", min = -30f, max = 30f, default = 0f)
val puppet =
model().copy(parameters = listOf(parameter, angleYParam))
val owner = KeyformOwner.Deformer(deformerId)
assertFalse(puppet.isGeometryKeyedOn(owner, angleY), "precondition: not keyed on Angle Y")
val bound = puppet.withGeometryKeyCaptured(owner, angleYParam, mapOf(angleY to 0f))
assertTrue(bound.isGeometryKeyedOn(owner, angleY), "the warp is now keyed on Angle Y")
val warp = bound.deformers.single() as Deformer.Warp
val axis = assertNotNull(warp.geometryGrid).axes.first { it.parameterId == angleY }
assertEquals(listOf(-30f, 0f, 30f), axis.keys.toList(), "seeded across the parameter's range")
}
/** A second capture on an already-bound parameter at a mid pose inserts a shape-preserving key there. */
@Test
fun capturingOnAnExistingAxisInsertsAtThePose() {
val owner = KeyformOwner.Deformer(deformerId)
val mid = model().withGeometryKeyCaptured(owner, parameter, mapOf(angleX to 15f))
val warp = mid.deformers.single() as Deformer.Warp
assertEquals(
listOf(-30f, 0f, 15f, 30f),
assertNotNull(warp.geometryGrid).axes.single { it.parameterId == angleX }.keys.toList(),
)
}
/** Dragging lattice points commits an authored form into the cell at the live pose. */
@Test
fun writingAWarpLatticeFormOverwritesTheCellAtThePose() {
val owner = KeyformOwner.Deformer(deformerId)
val sculpted = WarpLatticeForm(FloatArray(8) { index -> index.toFloat() })
val written = model().withWarpLatticeCaptured(owner, parameter, mapOf(angleX to 0f), sculpted)
val warp = written.deformers.single() as Deformer.Warp
val grid = assertNotNull(warp.geometryGrid)
val axis = grid.axes.single { it.parameterId == angleX }
val keyIndex = axis.keys.indexOfFirst { key -> key == 0f }
assertTrue(keyIndex >= 0, "default pose lands on the middle key")
val cell = grid.cells.first { candidate -> candidate.coordinate[0] == keyIndex }
assertContentEquals(sculpted.controlPoints, cell.form.controlPoints)
}
}
@@ -0,0 +1,101 @@
package org.umamo.edit
import org.umamo.runtime.model.ParameterId
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* What a removal does to the keyform sheet's key selection.
*
* A removal renumbers every key above it, so the selection has to renumber the same way to keep naming what
* the user selected: dropping it wholesale loses a carefully built multi-key selection over one unrelated
* deletion, and leaving the refs untouched hands the freed ordinal to whichever key slides onto it. Three
* call sites need to agree on this - the aimed removal behind Alt+I and the lane menu, the selected-keys
* removal behind Delete, and the summary-mark removal - which is why the rule lives in one place.
*/
class KeyformKeySelectionTest {
private val angleX = ParameterId("ParamAngleX")
/** A key on the geometry row at [ordinal]. */
private fun key(ordinal: Int): TrackKeyRef = TrackKeyRef(angleX, "drawable:d/geometry", ordinal)
/** A key on a different row at [ordinal] - something a removal here must not disturb. */
private fun otherRowKey(ordinal: Int): TrackKeyRef = TrackKeyRef(angleX, "drawable:other/geometry", ordinal)
/** Deleting a mark the user did not select leaves their selection completely alone. */
@Test
fun removingAnUnselectedKeyLeavesTheSelectionAlone() {
val selection = setOf(key(0), key(1))
assertEquals(selection, selectionAfterKeyRemoval(selection, setOf(otherRowKey(3))))
assertEquals(selection, selectionAfterKeyRemoval(selection, emptySet()), "and so does removing nothing")
}
/** The removed keys drop out, and the ones after them slide down to the ordinals they now hold. */
@Test
fun theKeysAfterARemovalRenumber() {
assertEquals(
setOf(key(0), key(1), key(2), key(3)),
selectionAfterKeyRemoval(setOf(key(0), key(2), key(3), key(4)), setOf(key(1))),
"all four survive, and the three above the removal each slide down one place",
)
assertEquals(
setOf(key(0)),
selectionAfterKeyRemoval(setOf(key(0), key(2)), setOf(key(2))),
"a selected key that IS removed simply goes",
)
assertEquals(
setOf(key(1)),
selectionAfterKeyRemoval(setOf(key(0), key(3)), setOf(key(0), key(1))),
"two removed below it, and the removed one of its own",
)
}
/**
* A removal on one parameter's axis does not renumber another's.
*
* A linked pad renders the same row under two sections, so a row key alone does not identify the axis a
* key sits on - and shifting the other section's ordinals would move that selection onto the wrong marks.
*/
@Test
fun aRemovalOnlyRenumbersItsOwnAxis() {
val onAngleY = TrackKeyRef(ParameterId("ParamAngleY"), "drawable:d/geometry", 3)
assertEquals(setOf(onAngleY), selectionAfterKeyRemoval(setOf(onAngleY), setOf(key(0))))
}
/**
* An insert shifts the selection up from where it lands, and leaves everything below it alone.
*
* The asymmetry follows from the renumbering rule itself: an insert to the RIGHT of a selected mark
* renumbers nothing below it, so the selection already names the right key; an insert to the LEFT lands
* at or above the selected ordinal, so the selection must shift up by one to keep naming it.
*/
@Test
fun anInsertShiftsOnlyTheKeysAboveIt() {
assertEquals(
setOf(key(3)),
selectionAfterKeyInsertion(setOf(key(2)), key(0)),
"inserted below: the selected mark moves up one ordinal to stay on the same key",
)
assertEquals(
setOf(key(2)),
selectionAfterKeyInsertion(setOf(key(2)), key(3)),
"inserted above: nothing renumbers",
)
assertEquals(
setOf(key(3)),
selectionAfterKeyInsertion(setOf(key(2)), key(2)),
"inserted AT the selected ordinal: the new key takes it, so the selection moves up",
)
}
/** An insert on another row or another axis leaves the selection exactly as it was. */
@Test
fun anInsertOnlyRenumbersItsOwnRowAndAxis() {
val selection = setOf(key(2))
assertEquals(selection, selectionAfterKeyInsertion(selection, otherRowKey(0)))
assertEquals(
selection,
selectionAfterKeyInsertion(selection, TrackKeyRef(ParameterId("ParamAngleY"), "drawable:d/geometry", 0)),
)
}
}
@@ -0,0 +1,116 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
/**
* Pins the merge's face on the operation settings strip: a merge registers with its Merge At row,
* switching the row re-merges the SAME vertices from the base at the new target over the same step
* (the survivor keeps its index, so the selection the step carries stays valid), and an unknown
* choice falls back to the target the merge ran with.
*/
class MergeAdjustTest {
private val drawableId = DrawableId("a")
/** A quad: v0 (0,0), v1 (10,0), v2 (0,10), v3 (10,10), two triangles. */
private fun model(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = emptyList(),
drawables =
listOf(
Drawable(
id = drawableId,
name = "a",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = DrawableMesh(floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f, 10f, 10f), FloatArray(8), intArrayOf(0, 1, 2, 1, 3, 2)),
geometryGrid = null,
),
),
rootChildren = emptyList(),
rootPartId = null,
)
/** A session in Edit mode with v0 and v1 selected, v1 active (so First is v0 and Last is v1). */
private fun session(): EditorSession {
val session = EditorSession(model())
session.setMode(EditorMode.Edit)
session.setMeshSelection(
MeshSelection(
drawableIds = listOf(drawableId),
activeDrawableId = drawableId,
selectMode = MeshSelectMode.Vertex,
elementsByDrawable = mapOf(drawableId to setOf(MeshElement.Vertex(0), MeshElement.Vertex(1))),
activeElement = ActiveMeshElement(drawableId, MeshElement.Vertex(1)),
),
)
return session
}
private fun survivor(session: EditorSession): Pair<Float, Float> {
val positions = session.model.value.drawables.single().mesh!!.positions
// The survivor appends last: the two kept vertices come first.
return positions[4] to positions[5]
}
private fun targetRow(key: String): OperatorParameter =
OperatorParameter.ChoiceParameter(MergeParameterKeys.TARGET, MergeParameterKeys.TARGET, key, emptyList())
@Test
fun aMergeRegistersAndItsTargetCanBeSwitchedInPlace() {
val session = session()
session.mergeSelectedVertices(MergeTarget.AtCenter, areaId = "area-1")
val record = assertNotNull(session.adjustableOperation.value, "the merge registered")
assertEquals("area-1", record.areaId)
assertEquals("change.mesh.merge", record.change.labelKey)
assertEquals("center", record.parameters.choiceValue(MergeParameterKeys.TARGET, "?"))
assertEquals(5f to 0f, survivor(session), "landed at the center of v0 and v1")
assertEquals(3, session.model.value.drawables.single().mesh!!.vertexCount)
val stepsBefore = session.historyView.value.steps.size
val selectionBefore = session.meshSelection.value
session.adjustLastOperation(record.parameters.withParameter(MergeParameterKeys.TARGET, targetRow("first")))
assertEquals(0f to 0f, survivor(session), "re-merged from the base at the first vertex")
assertEquals(stepsBefore, session.historyView.value.steps.size, "the step was amended in place")
assertEquals(selectionBefore, session.meshSelection.value, "the survivor selection still names the same index")
session.adjustLastOperation(record.parameters.withParameter(MergeParameterKeys.TARGET, targetRow("last")))
assertEquals(10f to 0f, survivor(session), "and at the last (active) vertex")
assertNotNull(session.adjustableOperation.value, "the record stays live for the next adjustment")
session.undo()
assertEquals(4, session.model.value.drawables.single().mesh!!.vertexCount, "one undo returns to the unmerged quad")
assertNull(session.adjustableOperation.value)
}
@Test
fun anUnknownChoiceFallsBackToTheTargetTheMergeRanWith() {
assertEquals(MergeTarget.AtLast, mergeTargetOf(listOf(targetRow("elsewhere")), MergeTarget.AtLast))
assertEquals(MergeTarget.AtFirst, mergeTargetOf(emptyList(), MergeTarget.AtFirst))
assertEquals(MergeTarget.AtCenter, mergeTargetOf(mergeParameters(MergeTarget.AtCenter), MergeTarget.AtLast))
assertEquals(listOf("center", "first", "last"), mergeParameters(MergeTarget.AtCenter).filterIsInstance<OperatorParameter.ChoiceParameter>().single().choices.map { choice -> choice.key })
}
@Test
fun aRefusedMergeRegistersNothing() {
val session = EditorSession(model())
session.setMode(EditorMode.Edit)
session.setMeshSelection(MeshSelection(drawableIds = listOf(drawableId), activeDrawableId = drawableId, elementsByDrawable = mapOf(drawableId to setOf(MeshElement.Vertex(0)))))
session.mergeSelectedVertices(MergeTarget.AtCenter, areaId = "area-1")
assertNull(session.adjustableOperation.value, "one vertex merges nothing, so nothing is adjustable")
}
}
@@ -0,0 +1,410 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Verifies the pure element-selection gestures maintain the [MeshSelection] invariant (the active element
* is a member of its drawable's selected set, or null when nothing remains), keep the session meshes and
* select mode across every op, span multiple meshes correctly (elements are mesh-local), and that
* select-mode switches follow Blender's flush-down / derive-up conversion rules per mesh.
*/
class MeshSelectionOpsTest {
private val drawableD = DrawableId("d")
private val drawableE = DrawableId("e")
// A single-mesh session over d, and a two-mesh session over d + e.
private val base = MeshSelection.editing(listOf(drawableD))
private val dual = MeshSelection.editing(listOf(drawableD, drawableE))
// The "spoke" fixture: center triangle T (face 0, vertices 0-1-2) shares each of its three edges with
// exactly one neighbor - A (face 1) across (0,1), B (face 2) across (1,2), C (face 3) across (0,2).
private val spokeIndices = intArrayOf(0, 1, 2, 0, 1, 3, 1, 2, 4, 2, 0, 5)
private val spokeMesh = DrawableMesh(FloatArray(12), FloatArray(12), spokeIndices)
// Two triangles sharing the (1, 2) edge - the second session mesh's smaller topology.
private val stripIndices = intArrayOf(0, 1, 2, 1, 3, 2)
private val stripMesh = DrawableMesh(FloatArray(8), FloatArray(8), stripIndices)
// The mesh provider the whole-session ops resolve topology through.
private fun meshOf(drawableId: DrawableId): DrawableMesh? =
when (drawableId) {
drawableD -> spokeMesh
drawableE -> stripMesh
else -> null
}
/**
* Builds a vertex-domain element set from vertex indices, for terse assertions.
*
* @param IntArray vertexIndices The vertex indices.
* @return Set<MeshElement> The corresponding vertex elements.
*/
private fun vertices(vararg vertexIndices: Int): Set<MeshElement> =
vertexIndices.map { vertexIndex -> MeshElement.Vertex(vertexIndex) }.toSet()
/**
* A single-mesh selection over d with the given elements (and optionally an active element).
*
* @param Set<MeshElement> elements The selected elements on d.
* @param MeshElement? active The active element, or null.
* @param MeshSelectMode selectMode The select mode.
* @return MeshSelection The built selection.
*/
private fun selectionOnD(
elements: Set<MeshElement>,
active: MeshElement? = null,
selectMode: MeshSelectMode = MeshSelectMode.Vertex,
): MeshSelection =
base.copy(
selectMode = selectMode,
elementsByDrawable = if (elements.isEmpty()) emptyMap() else mapOf(drawableD to elements),
activeElement = active?.let { ActiveMeshElement(drawableD, it) },
)
/** fitsWithinMeshes accepts elements that still exist in their mesh and rejects the rest, per domain. */
@Test
fun fitsWithinMeshesValidatesEachDomain() {
// The spoke fixture has vertices 0..5, four faces, and no (3,4) edge.
assertTrue(MeshSelectionOps.fitsWithinMeshes(selectionOnD(vertices(0, 5)), ::meshOf), "in-range vertices fit")
assertTrue(
MeshSelectionOps.fitsWithinMeshes(selectionOnD(setOf(MeshElement.Edge.of(0, 1)), selectMode = MeshSelectMode.Edge), ::meshOf),
"an existing edge fits",
)
assertTrue(
MeshSelectionOps.fitsWithinMeshes(selectionOnD(setOf(MeshElement.Face(3)), selectMode = MeshSelectMode.Face), ::meshOf),
"an existing face fits",
)
assertTrue(MeshSelectionOps.fitsWithinMeshes(base, ::meshOf), "an empty selection always fits")
assertFalse(MeshSelectionOps.fitsWithinMeshes(selectionOnD(vertices(0, 6)), ::meshOf), "an out-of-range vertex does not fit")
assertFalse(
MeshSelectionOps.fitsWithinMeshes(selectionOnD(setOf(MeshElement.Edge.of(3, 4)), selectMode = MeshSelectMode.Edge), ::meshOf),
"an edge absent from the mesh does not fit even with in-range endpoints",
)
assertFalse(
MeshSelectionOps.fitsWithinMeshes(selectionOnD(setOf(MeshElement.Face(4)), selectMode = MeshSelectMode.Face), ::meshOf),
"an out-of-range face ordinal does not fit",
)
assertFalse(
MeshSelectionOps.fitsWithinMeshes(
base.copy(elementsByDrawable = mapOf(DrawableId("gone") to vertices(0))),
) { drawableId -> meshOf(drawableId) },
"a selection on a mesh the provider cannot resolve does not fit",
)
}
/** replace selects a single element and makes it (and its mesh) active, keeping the session. */
@Test
fun replaceSelectsSingleActive() {
val result = MeshSelectionOps.replace(base, drawableD, MeshElement.Vertex(3))
assertEquals(vertices(3), result.elementsOf(drawableD))
assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(3)), result.activeElement)
assertEquals(listOf(drawableD), result.drawableIds)
assertEquals(drawableD, result.activeDrawableId)
}
/** replace on one session mesh clears the other meshes' selections (a plain click replaces everything). */
@Test
fun replaceClearsOtherMeshes() {
val seeded = MeshSelectionOps.add(dual, drawableD, MeshElement.Vertex(1))
val result = MeshSelectionOps.replace(seeded, drawableE, MeshElement.Vertex(0))
assertTrue(result.elementsOf(drawableD).isEmpty(), "the other mesh's selection cleared")
assertEquals(vertices(0), result.elementsOf(drawableE))
assertEquals(drawableE, result.activeDrawableId, "the clicked mesh becomes active")
}
/** toggle adds a missing element (active) and removes a present one (active falls back or clears). */
@Test
fun toggleAddsThenRemoves() {
val added = MeshSelectionOps.toggle(MeshSelectionOps.toggle(base, drawableD, MeshElement.Vertex(1)), drawableD, MeshElement.Vertex(2))
assertEquals(vertices(1, 2), added.elementsOf(drawableD))
assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(2)), added.activeElement)
val removed = MeshSelectionOps.toggle(added, drawableD, MeshElement.Vertex(2))
assertEquals(vertices(1), removed.elementsOf(drawableD))
val removedActive = removed.activeElement
assertTrue(
removedActive != null && removed.contains(removedActive.drawableId, removedActive.element),
"active stays a member after removal",
)
val emptied = MeshSelectionOps.toggle(removed, drawableD, MeshElement.Vertex(1))
assertTrue(emptied.isEmpty)
assertNull(emptied.activeElement, "active clears when the set empties")
}
/** add extends the set and promotes the added element to active. */
@Test
fun addExtendsAndActivates() {
val result = MeshSelectionOps.add(MeshSelectionOps.add(base, drawableD, MeshElement.Vertex(0)), drawableD, MeshElement.Vertex(5))
assertEquals(vertices(0, 5), result.elementsOf(drawableD))
assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(5)), result.activeElement)
}
/** box replaces (or unions when additive) and keeps the active element only when it remains selected. */
@Test
fun boxReplacesOrUnionsAndMaintainsActive() {
val seeded = MeshSelectionOps.replace(base, drawableD, MeshElement.Vertex(0))
val replaced = MeshSelectionOps.box(seeded, mapOf(drawableD to vertices(2, 3)), additive = false)
assertEquals(vertices(2, 3), replaced.elementsOf(drawableD))
assertNull(replaced.activeElement, "active drops when it is no longer selected")
val additive = MeshSelectionOps.box(seeded, mapOf(drawableD to vertices(2, 3)), additive = true)
assertEquals(vertices(0, 2, 3), additive.elementsOf(drawableD))
assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(0)), additive.activeElement, "active kept when it stays selected")
}
/** A box spanning two session meshes selects on both; a non-additive box replaces both. */
@Test
fun boxSpansSessionMeshes() {
val seeded = MeshSelectionOps.add(dual, drawableD, MeshElement.Vertex(5))
val boxed =
MeshSelectionOps.box(
seeded,
mapOf(drawableD to vertices(0, 1), drawableE to vertices(2, 3)),
additive = false,
)
assertEquals(vertices(0, 1), boxed.elementsOf(drawableD))
assertEquals(vertices(2, 3), boxed.elementsOf(drawableE))
assertEquals(4, boxed.size, "size sums across meshes")
val additive =
MeshSelectionOps.box(seeded, mapOf(drawableE to vertices(0)), additive = true)
assertEquals(vertices(5), additive.elementsOf(drawableD), "the additive box keeps the other mesh's selection")
assertEquals(vertices(0), additive.elementsOf(drawableE))
}
/** clear empties every mesh's element set but keeps the session and mode (the Edit session stays open). */
@Test
fun clearKeepsSessionAndMode() {
val edgeMode = dual.copy(selectMode = MeshSelectMode.Edge)
val result = MeshSelectionOps.clear(MeshSelectionOps.add(edgeMode, drawableD, MeshElement.Edge.of(1, 0)))
assertTrue(result.isEmpty)
assertNull(result.activeElement)
assertEquals(listOf(drawableD, drawableE), result.drawableIds)
assertEquals(MeshSelectMode.Edge, result.selectMode)
}
/** The gestures work identically over edge and face elements, and Edge.of canonicalizes endpoint order. */
@Test
fun gesturesAreDomainAgnosticAndEdgesCanonicalize() {
val edgeSelection = MeshSelectionOps.replace(base.copy(selectMode = MeshSelectMode.Edge), drawableD, MeshElement.Edge.of(2, 1))
assertEquals(setOf<MeshElement>(MeshElement.Edge(1, 2)), edgeSelection.elementsOf(drawableD), "(2,1) and (1,2) are one identity")
assertTrue(edgeSelection.contains(drawableD, MeshElement.Edge.of(1, 2)))
val faceSelection = MeshSelectionOps.toggle(base.copy(selectMode = MeshSelectMode.Face), drawableD, MeshElement.Face(3))
assertEquals(setOf<MeshElement>(MeshElement.Face(3)), faceSelection.elementsOf(drawableD))
assertEquals(ActiveMeshElement(drawableD, MeshElement.Face(3)), faceSelection.activeElement)
}
/** A same-mode switch is a no-op returning the same instance; a converting switch nulls the active element. */
@Test
fun changeSelectModeSameModeIsIdentityAndConversionDropsActive() {
val selection = MeshSelectionOps.add(base, drawableD, MeshElement.Vertex(0))
assertSame(selection, MeshSelectionOps.changeSelectMode(selection, MeshSelectMode.Vertex) { spokeIndices })
val converted = MeshSelectionOps.changeSelectMode(selection, MeshSelectMode.Edge) { spokeIndices }
assertEquals(MeshSelectMode.Edge, converted.selectMode)
assertNull(converted.activeElement, "no single last-touched element survives a domain change")
assertEquals(listOf(drawableD), converted.drawableIds)
}
/** A mode switch converts EVERY session mesh's elements against its own topology. */
@Test
fun changeSelectModeConvertsPerMesh() {
val selection =
dual.copy(
elementsByDrawable =
mapOf(
// All of spoke face 0's vertices on d; all of strip face 0's vertices on e.
drawableD to vertices(0, 1, 2),
drawableE to vertices(0, 1, 2),
),
)
val converted = MeshSelectionOps.changeSelectMode(selection, MeshSelectMode.Face) { drawableId -> meshOf(drawableId)?.indices }
assertEquals(setOf<MeshElement>(MeshElement.Face(0)), converted.elementsOf(drawableD), "the spoke's face 0 derives on d")
assertEquals(setOf<MeshElement>(MeshElement.Face(0)), converted.elementsOf(drawableE), "the strip's face 0 derives on e")
}
/** Vertex-to-edge derives only edges whose both endpoints were selected. */
@Test
fun vertexToEdgeRequiresBothEndpoints() {
val converted = MeshSelectionOps.changeSelectMode(selectionOnD(vertices(0, 1, 3)), MeshSelectMode.Edge) { spokeIndices }
assertEquals(
setOf<MeshElement>(MeshElement.Edge.of(0, 1), MeshElement.Edge.of(0, 3), MeshElement.Edge.of(1, 3)),
converted.elementsOf(drawableD),
)
}
/** Vertex-to-face derives only faces whose all three vertices were selected. */
@Test
fun vertexToFaceRequiresAllVertices() {
val allOfT = MeshSelectionOps.changeSelectMode(selectionOnD(vertices(0, 1, 2)), MeshSelectMode.Face) { spokeIndices }
assertEquals(setOf<MeshElement>(MeshElement.Face(0)), allOfT.elementsOf(drawableD))
val twoOfThree = MeshSelectionOps.changeSelectMode(selectionOnD(vertices(0, 1, 4)), MeshSelectMode.Face) { spokeIndices }
assertTrue(twoOfThree.isEmpty, "two of three vertices never derive a face")
}
/**
* The headline Blender rule: edges of the neighbors can cover every vertex of the center triangle T
* without selecting T - a face derives only from all three of its OWN edges, never from vertex coverage.
*/
@Test
fun edgeToFaceRequiresOwnEdgesNotVertexCoverage() {
val neighborEdges =
setOf<MeshElement>(
MeshElement.Edge.of(0, 3),
MeshElement.Edge.of(1, 3),
MeshElement.Edge.of(1, 4),
MeshElement.Edge.of(2, 4),
)
// Sanity: these four edges cover all of T's vertices {0, 1, 2}.
assertTrue(MeshTopology.coveredVertexIndices(neighborEdges, spokeIndices).containsAll(setOf(0, 1, 2)))
val converted =
MeshSelectionOps.changeSelectMode(
selectionOnD(neighborEdges, selectMode = MeshSelectMode.Edge),
MeshSelectMode.Face,
) { spokeIndices }
assertTrue(converted.isEmpty, "no face owns all three of its edges here (T owns none, A and B own two)")
val ownEdges =
setOf<MeshElement>(
MeshElement.Edge.of(0, 1),
MeshElement.Edge.of(1, 2),
MeshElement.Edge.of(0, 2),
)
val face =
MeshSelectionOps.changeSelectMode(
selectionOnD(ownEdges, selectMode = MeshSelectMode.Edge),
MeshSelectMode.Face,
) { spokeIndices }
assertEquals(setOf<MeshElement>(MeshElement.Face(0)), face.elementsOf(drawableD), "all three own edges derive exactly T")
}
/** Face-to-edge flushes down to the selected faces' own edges. */
@Test
fun faceToEdgeFlushesToOwnEdges() {
val converted =
MeshSelectionOps.changeSelectMode(
selectionOnD(setOf(MeshElement.Face(1)), selectMode = MeshSelectMode.Face),
MeshSelectMode.Edge,
) { spokeIndices }
assertEquals(
setOf<MeshElement>(MeshElement.Edge.of(0, 1), MeshElement.Edge.of(1, 3), MeshElement.Edge.of(0, 3)),
converted.elementsOf(drawableD),
)
}
/**
* The documented lossy round-trip (Blender-faithful): selecting T's three neighbors, flushing down to
* vertices, then deriving back up to faces gains T - the flush covers all six vertices, and T's three
* vertices are among them.
*/
@Test
fun faceToVertexToFaceRoundTripGainsTheEnclosedFace() {
val neighbors =
selectionOnD(
setOf(MeshElement.Face(1), MeshElement.Face(2), MeshElement.Face(3)),
selectMode = MeshSelectMode.Face,
)
val flushed = MeshSelectionOps.changeSelectMode(neighbors, MeshSelectMode.Vertex) { spokeIndices }
assertEquals(vertices(0, 1, 2, 3, 4, 5), flushed.elementsOf(drawableD), "flush-down covers every vertex of the selected faces")
val derived = MeshSelectionOps.changeSelectMode(flushed, MeshSelectMode.Face) { spokeIndices }
assertEquals(
setOf<MeshElement>(MeshElement.Face(0), MeshElement.Face(1), MeshElement.Face(2), MeshElement.Face(3)),
derived.elementsOf(drawableD),
"deriving back up now includes the enclosed face T",
)
}
/** Edge-to-vertex flushes down to the selected edges' endpoints. */
@Test
fun edgeToVertexFlushesToEndpoints() {
val converted =
MeshSelectionOps.changeSelectMode(
selectionOnD(setOf(MeshElement.Edge.of(1, 3), MeshElement.Edge.of(2, 4)), selectMode = MeshSelectMode.Edge),
MeshSelectMode.Vertex,
) { spokeIndices }
assertEquals(vertices(1, 2, 3, 4), converted.elementsOf(drawableD))
}
/** selectAll fills the current mode's whole domain on every session mesh, keeping the active element. */
@Test
fun selectAllFillsDomainPerModeAcrossMeshes() {
val seeded = selectionOnD(vertices(2), active = MeshElement.Vertex(2)).copy(drawableIds = dual.drawableIds)
val allVertices = MeshSelectionOps.selectAll(seeded, ::meshOf)
assertEquals(vertices(0, 1, 2, 3, 4, 5), allVertices.elementsOf(drawableD), "the spoke's six vertices")
assertEquals(vertices(0, 1, 2, 3), allVertices.elementsOf(drawableE), "the strip's four vertices")
assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(2)), allVertices.activeElement, "active kept - it is still selected")
val allFaces = MeshSelectionOps.selectAll(base.copy(selectMode = MeshSelectMode.Face), ::meshOf)
assertEquals(
setOf<MeshElement>(MeshElement.Face(0), MeshElement.Face(1), MeshElement.Face(2), MeshElement.Face(3)),
allFaces.elementsOf(drawableD),
)
val allEdges = MeshSelectionOps.selectAll(base.copy(selectMode = MeshSelectMode.Edge), ::meshOf)
assertEquals(MeshTopology.uniqueEdges(spokeIndices).toSet(), allEdges.elementsOf(drawableD))
}
/** invert flips membership per session mesh and drops a now-deselected active element. */
@Test
fun invertComplementsDomainAndDropsDeselectedActive() {
val selection =
dual.copy(
elementsByDrawable = mapOf(drawableD to vertices(0, 1)),
activeElement = ActiveMeshElement(drawableD, MeshElement.Vertex(0)),
)
val inverted = MeshSelectionOps.invert(selection, ::meshOf)
assertEquals(vertices(2, 3, 4, 5), inverted.elementsOf(drawableD))
assertEquals(vertices(0, 1, 2, 3), inverted.elementsOf(drawableE), "an untouched session mesh inverts from empty to all")
assertNull(inverted.activeElement, "the active element was deselected by the inversion")
}
/** selectLinked unions a connectivity island's elements in the current domain, additively. */
@Test
fun selectLinkedUnionsIslandPerDomain() {
// The strip mesh (vertices 0-3, faces 0-1) as one island; seed a selection elsewhere to prove union.
val stripSelection = MeshSelection.editing(listOf(drawableE))
val island = setOf(0, 1, 2, 3)
val vertexResult = MeshSelectionOps.selectLinked(stripSelection, drawableE, island, stripIndices)
assertEquals(vertices(0, 1, 2, 3), vertexResult.elementsOf(drawableE), "vertex mode adds every island vertex")
val edgeResult =
MeshSelectionOps.selectLinked(stripSelection.copy(selectMode = MeshSelectMode.Edge), drawableE, island, stripIndices)
assertEquals(MeshTopology.uniqueEdges(stripIndices).toSet(), edgeResult.elementsOf(drawableE), "edge mode adds the island's edges")
val faceResult =
MeshSelectionOps.selectLinked(stripSelection.copy(selectMode = MeshSelectMode.Face), drawableE, island, stripIndices)
assertEquals(setOf<MeshElement>(MeshElement.Face(0), MeshElement.Face(1)), faceResult.elementsOf(drawableE))
// Additive: an existing selection on another vertex survives the union.
val seeded = MeshSelectionOps.add(stripSelection, drawableE, MeshElement.Vertex(3))
val grown = MeshSelectionOps.selectLinked(seeded, drawableE, setOf(0, 1, 2), stripIndices)
assertEquals(vertices(0, 1, 2, 3), grown.elementsOf(drawableE), "the union keeps prior members")
assertEquals(ActiveMeshElement(drawableE, MeshElement.Vertex(3)), grown.activeElement, "the active element is untouched")
}
/** remove deselects per mesh and keeps the active element only when it survives. */
@Test
fun removeDropsElementsAndFixesActive() {
val selection = selectionOnD(vertices(0, 1, 2), active = MeshElement.Vertex(2))
val afterActiveGone = MeshSelectionOps.remove(selection, mapOf(drawableD to vertices(2)))
assertEquals(vertices(0, 1), afterActiveGone.elementsOf(drawableD))
assertNull(afterActiveGone.activeElement, "active drops when it is removed")
val afterOtherGone = MeshSelectionOps.remove(selection, mapOf(drawableD to vertices(0)))
assertEquals(vertices(1, 2), afterOtherGone.elementsOf(drawableD))
assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(2)), afterOtherGone.activeElement, "active kept when it survives")
}
}
@@ -0,0 +1,704 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.Glue
import org.umamo.runtime.model.GluePair
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Verifies the topology-edit infrastructure and the op builders: withMeshTopologyEdit rebuilds every
* keyform cell's deltas per VertexSource (copy / average / lerp) and remaps or drops glue pairs;
* duplicate appends copies with copied faces; merge collapses onto the survivor per target and drops
* degenerate triangles; rip splits a fan by the side predicate; connect cuts crossed triangles at
* lerped vertices and refuses degenerate requests; object-mode duplicate inserts after its source with
* a unique id; and the session commits model + selection as one undo step.
*/
class MeshTopologyEditsTest {
private val paramA = ParameterId("A")
// The strip: a unit-ish quad of two triangles sharing edge (1, 2).
// v0 (0,0), v1 (2,0), v2 (0,2), v3 (2,2).
private val stripPositions = floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 2f, 2f)
private val stripUvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f)
private val stripIndices = intArrayOf(0, 1, 2, 1, 3, 2)
private val stripMesh = DrawableMesh(stripPositions, stripUvs, stripIndices)
// Per-vertex deltas 10*(index+1) on x, 0 on y - distinguishable per vertex.
private fun stripForm(): MeshDeltaForm = MeshDeltaForm(floatArrayOf(10f, 0f, 20f, 0f, 30f, 0f, 40f, 0f))
private fun stripDrawable(id: String): Drawable =
Drawable(
id = DrawableId(id),
name = id,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = stripMesh,
geometryGrid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(0f))), listOf(KeyformCell(intArrayOf(0), stripForm()))),
)
private fun model(): PuppetModel =
PuppetModel(
parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)),
parts = emptyList(),
deformers = emptyList(),
drawables = listOf(stripDrawable("d"), stripDrawable("other")),
rootChildren = listOf(OrgChild.Drawable(DrawableId("d")), OrgChild.Drawable(DrawableId("other"))),
rootPartId = null,
glues =
listOf(
Glue(
meshA = DrawableId("d"),
meshB = DrawableId("other"),
pairs = listOf(GluePair(1, 1, 0.5f, 0.5f), GluePair(3, 3, 0.5f, 0.5f)),
),
),
)
/** withMeshTopologyEdit rebuilds keyform deltas per source kind and remaps / drops glue pairs. */
@Test
fun topologyEditRemapsDeltasAndGlue() {
// New mesh: keep v0 and v1, average v2+v3 into a survivor, and add a lerp point on (0, 1).
val newMesh =
DrawableMesh(
floatArrayOf(0f, 0f, 2f, 0f, 1f, 2f, 1f, 0f),
FloatArray(8),
intArrayOf(0, 1, 2),
)
val edit =
MeshTopologyEdit(
newMesh,
listOf(
VertexSource.FromOld(0),
VertexSource.FromOld(1),
VertexSource.AverageOf(listOf(2, 3)),
VertexSource.LerpOf(0, 1, 0.25f),
),
)
val edited = model().withMeshTopologyEdit(DrawableId("d"), edit)
val editedDrawable = edited.drawables.first { it.id == DrawableId("d") }
assertSame(newMesh, editedDrawable.mesh, "the replacement mesh swaps in")
val deltas = editedDrawable.geometryGrid!!.cells.single().form.positionDeltas
assertEquals(10f, deltas[0], "v0 copies its delta")
assertEquals(20f, deltas[2], "v1 copies its delta")
assertEquals(35f, deltas[4], "the merge survivor averages v2 and v3 (30 + 40) / 2")
assertEquals(12.5f, deltas[6], 1e-4f, "the split point lerps v0 and v1 by t = 0.25")
// Glue: pair on old v1 remaps to new v1 (same slot); pair on old v3 collapses onto the survivor.
val glue = edited.glues.single()
assertEquals(listOf(1, 2), glue.pairs.map { pair -> pair.indexA }, "old v1 keeps its slot; old v3 remaps to the survivor")
assertEquals(listOf(1, 3), glue.pairs.map { pair -> pair.indexB }, "the other mesh's indices are untouched")
// A malformed edit (source list size mismatch) is a no-op, never a corruption.
val malformed = MeshTopologyEdit(newMesh, listOf(VertexSource.FromOld(0)))
assertSame(model().let { it to it.withMeshTopologyEdit(DrawableId("d"), malformed) }.let { (before, after) -> before === after }, true)
}
/** duplicateElements appends copies of the covered vertices plus every fully-covered face. */
@Test
fun duplicateAppendsCopiesAndFaces() {
val result = MeshTopologyOps.duplicateElements(stripMesh, setOf(0, 1, 2))!!
val mesh = result.edit.newMesh
assertEquals(7, mesh.vertexCount, "three copies append after the four originals")
assertEquals(3, mesh.indices.size / 3, "only the fully-covered triangle duplicates")
assertEquals(listOf(4, 5, 6), mesh.indices.toList().subList(6, 9), "the copied face uses the copies")
assertEquals(0f, mesh.positions[8], "copy of v0 keeps its position x")
assertEquals(stripUvs[0], mesh.uvs[8], "copy of v0 keeps its uv")
assertEquals(VertexSource.FromOld(0), result.edit.vertexSources[4], "the copy's deltas copy from its source")
assertEquals(
setOf<MeshElement>(MeshElement.Vertex(4), MeshElement.Vertex(5), MeshElement.Vertex(6)),
result.newElements,
"the copies are the new selection",
)
assertNull(MeshTopologyOps.duplicateElements(stripMesh, emptySet()), "nothing covered refuses")
}
/** mergeVertices collapses per target, drops degenerate triangles, and keeps the survivor selected. */
@Test
fun mergeCollapsesPerTarget() {
// Merge v1 and v3 (the strip's right edge) at center: survivor at (2, 1).
val atCenter = MeshTopologyOps.mergeVertices(stripMesh, listOf(1, 3), MergeTarget.AtCenter)!!
val centerMesh = atCenter.edit.newMesh
assertEquals(3, centerMesh.vertexCount, "four vertices merge into three")
val survivor = 2
assertEquals(2f, centerMesh.positions[survivor * 2], "survivor x is the midpoint")
assertEquals(1f, centerMesh.positions[survivor * 2 + 1], "survivor y is the midpoint")
// Triangle (1, 3, 2) held BOTH merged vertices, so it degenerates and drops; (0, 1, 2) survives.
assertEquals(1, centerMesh.indices.size / 3, "the triangle that held both merged vertices drops")
assertEquals(setOf<MeshElement>(MeshElement.Vertex(survivor)), atCenter.newElements)
assertTrue(atCenter.edit.vertexSources[survivor] is VertexSource.AverageOf, "the survivor averages its members")
// AtFirst keeps v1's position verbatim.
val atFirst = MeshTopologyOps.mergeVertices(stripMesh, listOf(1, 3), MergeTarget.AtFirst)!!
assertEquals(2f, atFirst.edit.newMesh.positions[4], "survivor x = v1.x")
assertEquals(0f, atFirst.edit.newMesh.positions[5], "survivor y = v1.y")
assertEquals(VertexSource.FromOld(1), atFirst.edit.vertexSources[2])
// AtLast keeps v3's position.
val atLast = MeshTopologyOps.mergeVertices(stripMesh, listOf(1, 3), MergeTarget.AtLast)!!
assertEquals(2f, atLast.edit.newMesh.positions[4])
assertEquals(2f, atLast.edit.newMesh.positions[5])
// Merging two corners of ONE triangle degenerates it: only the other triangle survives.
val degenerate = MeshTopologyOps.mergeVertices(stripMesh, listOf(0, 1), MergeTarget.AtCenter)!!
assertEquals(1, degenerate.edit.newMesh.indices.size / 3, "the triangle that collapsed drops")
assertNull(MeshTopologyOps.mergeVertices(stripMesh, listOf(1), MergeTarget.AtCenter), "one vertex refuses")
}
/** ripElements duplicates only vertices whose fan splits, re-pointing the marked side. */
@Test
fun ripSplitsFanBySidePredicate() {
// Rip the shared edge's vertices (1, 2), marking triangle 1 as the side that takes the copies.
val result = MeshTopologyOps.ripElements(stripMesh, setOf(1, 2)) { triangleIndex -> triangleIndex == 1 }!!
val mesh = result.edit.newMesh
assertEquals(6, mesh.vertexCount, "both shared vertices duplicate")
// Triangle 0 keeps the originals; triangle 1 re-points at the copies.
assertEquals(listOf(0, 1, 2), mesh.indices.toList().subList(0, 3))
assertEquals(listOf(4, 3, 5), mesh.indices.toList().subList(3, 6), "the marked triangle uses the copies (v1 -> 4, v2 -> 5)")
assertEquals(setOf<MeshElement>(MeshElement.Vertex(4), MeshElement.Vertex(5)), result.newElements)
// Every adjacent triangle marked (or none): nothing to split, refused.
assertNull(MeshTopologyOps.ripElements(stripMesh, setOf(1, 2)) { true }, "a one-sided rip refuses")
}
/** connectVertices cuts the crossed shared edge at a lerped vertex and retriangulates both sides. */
@Test
fun connectCutsAcrossTheSharedEdge() {
// Connect v0 (0,0) and v3 (2,2): the diagonal crosses the shared edge (1,2) at its midpoint.
val result = MeshTopologyOps.connectVertices(stripMesh, 0, 3)!!
val mesh = result.edit.newMesh
assertEquals(5, mesh.vertexCount, "one crossing vertex appends")
assertEquals(1f, mesh.positions[8], 1e-4f, "the crossing sits at the shared edge's midpoint x")
assertEquals(1f, mesh.positions[9], 1e-4f, "and midpoint y")
assertEquals(4, mesh.indices.size / 3, "each crossed triangle splits in two")
val crossingSource = result.edit.vertexSources[4]
assertTrue(crossingSource is VertexSource.LerpOf && absDiff(crossingSource.t, 0.5f) < 1e-4f, "the crossing lerps at t = 0.5")
assertTrue(MeshElement.Vertex(4) in result.newElements, "the cut path is selected")
// Already-connected vertices (an existing edge) refuse.
assertNull(MeshTopologyOps.connectVertices(stripMesh, 1, 2), "an existing edge refuses")
assertNull(MeshTopologyOps.connectVertices(stripMesh, 0, 0), "a self-connect refuses")
}
/** Object-mode duplicate: a unique .001 id, org-tree insertion after the source, no glue membership. */
@Test
fun withDrawableDuplicatedInsertsAfterSource() {
val (edited, copyId) = model().withDrawableDuplicated(DrawableId("d"))!!
assertEquals(DrawableId("d.001"), copyId)
assertEquals(3, edited.drawables.size)
assertEquals(
listOf<OrgChild>(OrgChild.Drawable(DrawableId("d")), OrgChild.Drawable(copyId), OrgChild.Drawable(DrawableId("other"))),
edited.rootChildren,
"the copy sits immediately after its source",
)
val copy = edited.drawables.first { it.id == copyId }
val source = edited.drawables.first { it.id == DrawableId("d") }
assertTrue(copy.mesh!!.positions !== source.mesh!!.positions, "positions are a fresh array")
assertSame(source.mesh!!.uvs, copy.mesh!!.uvs, "uvs share by reference (COW)")
assertTrue(edited.glues.single().meshA != copyId && edited.glues.single().meshB != copyId, "the copy joins no glue")
assertEquals(DrawableId("d"), copy.textureSourceId, "the copy resolves its atlas binding through its source")
// A second duplicate of the same source lands at .002.
val (again, secondId) = edited.withDrawableDuplicated(DrawableId("d"))!!
assertEquals(DrawableId("d.002"), secondId)
assertEquals(4, again.drawables.size)
// Duplicating the COPY still binds the texture through the ORIGINAL (the id the atlas map knows).
val (chained, chainedId) = again.withDrawableDuplicated(copyId)!!
val chainedCopy = chained.drawables.first { it.id == chainedId }
assertEquals(DrawableId("d"), chainedCopy.textureSourceId, "a copy of a copy inherits the original's atlas binding")
}
/** The session commits a topology edit and its result selection as ONE undo step. */
@Test
fun sessionCommitsTopologyAtomically() {
val session = EditorSession(model())
session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d"))))
session.setMode(EditorMode.Edit)
session.setMeshSelection(
MeshSelectionOps.add(MeshSelectionOps.add(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0)), DrawableId("d"), MeshElement.Vertex(1)),
)
val stepsBefore = session.historyView.value.steps.size
session.duplicateSelectedElements()
assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "duplicate is one undo step")
assertEquals(6, session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount, "two copies appended")
assertEquals(
setOf<MeshElement>(MeshElement.Vertex(4), MeshElement.Vertex(5)),
session.meshSelection.value.elementsOf(DrawableId("d")),
"the copies are selected",
)
assertTrue(session.dirty.value, "a topology edit dirties the document")
session.undo()
assertEquals(4, session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount, "undo restores the topology")
assertEquals(
setOf<MeshElement>(MeshElement.Vertex(0), MeshElement.Vertex(1)),
session.meshSelection.value.elementsOf(DrawableId("d")),
"undo restores the selection the edit replaced - never torn from the topology",
)
}
/** A face-mode duplicate keeps face mode, leaving the new face selected (Blender keeps the mode). */
@Test
fun faceModeDuplicateKeepsFaceMode() {
val session = EditorSession(model())
session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d"))))
session.setMode(EditorMode.Edit)
session.setMeshSelectMode(MeshSelectMode.Face)
session.setMeshSelection(MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Face(0)))
session.duplicateSelectedElements()
// Face 0's three vertices copied to 4..6 plus one new triangle appended at index 2.
assertEquals(MeshSelectMode.Face, session.meshSelection.value.selectMode, "duplicate never switches the select mode")
assertEquals(
setOf<MeshElement>(MeshElement.Face(2)),
session.meshSelection.value.elementsOf(DrawableId("d")),
"the copied face is selected in face mode",
)
assertEquals(
ActiveMeshElement(DrawableId("d"), MeshElement.Face(2)),
session.meshSelection.value.activeElement,
"the copied face becomes active",
)
}
/** An edge-mode duplicate covering a whole face keeps edge mode with the copied edges selected. */
@Test
fun edgeModeDuplicateKeepsEdgeMode() {
val session = EditorSession(model())
session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d"))))
session.setMode(EditorMode.Edit)
session.setMeshSelectMode(MeshSelectMode.Edge)
// All three edges of face 0, so the whole triangle duplicates.
var withEdges = MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Edge(0, 1))
withEdges = MeshSelectionOps.add(withEdges, DrawableId("d"), MeshElement.Edge(1, 2))
withEdges = MeshSelectionOps.add(withEdges, DrawableId("d"), MeshElement.Edge(0, 2))
session.setMeshSelection(withEdges)
session.duplicateSelectedElements()
assertEquals(MeshSelectMode.Edge, session.meshSelection.value.selectMode, "duplicate never switches the select mode")
assertEquals(
setOf<MeshElement>(MeshElement.Edge(4, 5), MeshElement.Edge(5, 6), MeshElement.Edge(4, 6)),
session.meshSelection.value.elementsOf(DrawableId("d")),
"the copied triangle's edges are selected in edge mode",
)
}
/**
* An edge-mode duplicate of one lone edge copies two loose vertices no edge covers, so the result
* falls back to vertex mode - stranding the copies unselected would hide them and starve the
* follow-up auto-grab.
*/
@Test
fun looseEdgeDuplicateFallsBackToVertexMode() {
val session = EditorSession(model())
session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d"))))
session.setMode(EditorMode.Edit)
session.setMeshSelectMode(MeshSelectMode.Edge)
session.setMeshSelection(MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Edge(0, 1)))
session.duplicateSelectedElements()
assertEquals(MeshSelectMode.Vertex, session.meshSelection.value.selectMode, "loose copies exist only in the vertex domain")
assertEquals(
setOf<MeshElement>(MeshElement.Vertex(4), MeshElement.Vertex(5)),
session.meshSelection.value.elementsOf(DrawableId("d")),
"the loose vertex copies are selected",
)
}
/** Add Vertex stages floats without touching the model; Accept commits once; Esc discards. */
@Test
fun addVertexDraftStagesThenAccepts() {
val session = EditorSession(model())
session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d"))))
session.setMode(EditorMode.Edit)
val before = session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount
session.beginAddVertex("area-a")
assertTrue(session.activeSelectTool.value is ActiveSelectTool.AddVertex)
session.addVertexDraftClick(1f, 0f, snapEdge = MeshElement.Edge.of(0, 1), snapT = 0.5f)
session.addVertexDraftClick(1f, 1f)
val draft = session.activeSelectTool.value as ActiveSelectTool.AddVertex
assertEquals(2, draft.verts.size, "two floats staged")
assertEquals(1, draft.edges.size, "auto-edge from tip")
assertEquals(before, session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount, "document untouched while staging")
session.deleteAddVertexDraftVert(1)
assertEquals(1, (session.activeSelectTool.value as ActiveSelectTool.AddVertex).verts.size, "RMB delete removes a float")
session.addVertexDraftClick(1f, 1f)
session.acceptAddVertexDraft()
assertNull(session.activeSelectTool.value, "accept clears the tool")
assertTrue(
session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount > before,
"accept appends staged verts",
)
val afterAccept = session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount
session.beginAddVertex("area-a")
session.addVertexDraftClick(0.5f, 0.5f)
session.clearSelectTool()
assertEquals(
afterAccept,
session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount,
"discard leaves the accepted mesh alone",
)
}
/** deleteVertices drops the vert and every incident triangle, compacting survivors. */
@Test
fun deleteVerticesRemovesIncidentTriangles() {
val result = MeshTopologyOps.deleteVertices(stripMesh, listOf(1))!!
val mesh = result.edit.newMesh
assertEquals(3, mesh.vertexCount, "one vert removed")
assertEquals(0, mesh.indices.size / 3, "both triangles used v1 and drop")
assertNull(MeshTopologyOps.deleteVertices(stripMesh, emptyList()), "empty delete refuses")
assertNull(MeshTopologyOps.deleteVertices(stripMesh, listOf(99)), "missing index refuses")
}
/** applyAddVertexDraft edge-snaps and appends free floats in one TopologyOpResult. */
@Test
fun applyAddVertexDraftSnapsAndAppends() {
val result =
MeshTopologyOps.applyAddVertexDraft(
stripMesh,
listOf(
DraftVert(1f, 0f, snapEdge = MeshElement.Edge.of(0, 1), snapT = 0.5f),
DraftVert(1f, 1f),
),
listOf(DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!),
)!!
assertEquals(6, result.edit.newMesh.vertexCount, "snap + free append")
assertTrue(MeshElement.Vertex(4) in result.newElements || MeshElement.Vertex(5) in result.newElements)
}
/**
* Closing line on a triangular hole (mesh edge base + two draft sides to an orphan) fills exactly
* one face.
*/
@Test
fun applyAddVertexDraftClosingLineFillsHole() {
// Face (0,1,2) plus orphan v3; draft edges 1-3 and 2-3 close triangle (1,2,3).
val mesh =
DrawableMesh(
floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 2f, 2f),
FloatArray(8),
intArrayOf(0, 1, 2),
)
val result =
MeshTopologyOps.applyAddVertexDraft(
mesh,
emptyList(),
listOf(
DraftEdge.of(DraftEndpoint.Existing(1), DraftEndpoint.Existing(3))!!,
DraftEdge.of(DraftEndpoint.Existing(2), DraftEndpoint.Existing(3))!!,
),
)
assertTrue(result != null, "closing lines must commit")
assertEquals(2, result!!.edit.newMesh.indices.size / 3, "exactly one new face fills the hole")
}
/** Drawing the second diagonal of an already-filled quad must not stack overlapping faces. */
@Test
fun applyAddVertexDraftRejectsCrossedQuadDiagonal() {
val mesh =
DrawableMesh(
floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 2f, 2f),
FloatArray(8),
intArrayOf(0, 1, 2, 0, 2, 3),
)
val result =
MeshTopologyOps.applyAddVertexDraft(
mesh,
emptyList(),
listOf(DraftEdge.of(DraftEndpoint.Existing(1), DraftEndpoint.Existing(3))!!),
)
// Knife may still run; faces must stay at the original two.
assertEquals(2, (result?.edit?.newMesh ?: mesh).indices.size / 3, "no stacked / crossed faces")
}
/** A closed draft triangle over existing faces still fills (pure-draft skips centroid-inside reject). */
@Test
fun applyAddVertexDraftPureDraftTriangleOverExistingFills() {
val result =
MeshTopologyOps.applyAddVertexDraft(
stripMesh,
listOf(DraftVert(0.5f, 0.5f), DraftVert(1.5f, 0.5f), DraftVert(1f, 1.5f)),
listOf(
DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!,
DraftEdge.of(DraftEndpoint.Draft(1), DraftEndpoint.Draft(2))!!,
DraftEdge.of(DraftEndpoint.Draft(2), DraftEndpoint.Draft(0))!!,
),
)
assertTrue(result != null, "closed draft triangle must commit")
assertEquals(7, result!!.edit.newMesh.vertexCount, "four originals + three floats")
assertEquals(3, result.edit.newMesh.indices.size / 3, "two original faces + one draft face")
}
/** Three draft edges among orphan verts (no mesh faces) still form a triangle on Accept. */
@Test
fun applyAddVertexDraftAllDraftTriangleFillsFace() {
val mesh = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), FloatArray(6), IntArray(0))
val edges =
listOf(
DraftEdge.of(DraftEndpoint.Existing(0), DraftEndpoint.Existing(1))!!,
DraftEdge.of(DraftEndpoint.Existing(1), DraftEndpoint.Existing(2))!!,
DraftEdge.of(DraftEndpoint.Existing(2), DraftEndpoint.Existing(0))!!,
)
val result = MeshTopologyOps.applyAddVertexDraft(mesh, emptyList(), edges)
assertTrue(result != null, "all-draft triangle must commit")
assertEquals(1, result!!.edit.newMesh.indices.size / 3, "one face from three draft edges")
}
/**
* Concave closed draft ring must CDT-fill (not fan from vert 0). A C-shaped notch would be covered
* by fan triangles from the first vertex; Delaunay keeps faces inside the polygon only.
*/
@Test
fun applyAddVertexDraftConcaveRingCdtsWithoutFan() {
val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0))
// C outline, CCW: notch opens to the right around (2.5, 2).
val verts =
listOf(
DraftVert(0f, 0f),
DraftVert(4f, 0f),
DraftVert(4f, 1f),
DraftVert(1f, 1f),
DraftVert(1f, 3f),
DraftVert(4f, 3f),
DraftVert(4f, 4f),
DraftVert(0f, 4f),
)
val edges =
verts.indices.map { index ->
DraftEdge.of(DraftEndpoint.Draft(index), DraftEndpoint.Draft((index + 1) % verts.size))!!
}
val result = MeshTopologyOps.applyAddVertexDraft(empty, verts, edges)
assertTrue(result != null, "concave ring must commit")
val mesh = result!!.edit.newMesh
assertEquals(8, mesh.vertexCount)
assertEquals(6, mesh.triangleCount, "CDT of 8-gon C yields 6 tris, not a fan covering the notch")
// Notch probe (2.5, 2) must not land inside any accepted face.
fun pointInTri(px: Float, py: Float, a: Int, b: Int, c: Int): Boolean {
val ax = mesh.positions[a * 2]
val ay = mesh.positions[a * 2 + 1]
val bx = mesh.positions[b * 2]
val by = mesh.positions[b * 2 + 1]
val cx = mesh.positions[c * 2]
val cy = mesh.positions[c * 2 + 1]
val v0x = cx - ax
val v0y = cy - ay
val v1x = bx - ax
val v1y = by - ay
val v2x = px - ax
val v2y = py - ay
val dot00 = v0x * v0x + v0y * v0y
val dot01 = v0x * v1x + v0y * v1y
val dot02 = v0x * v2x + v0y * v2y
val dot11 = v1x * v1x + v1y * v1y
val dot12 = v1x * v2x + v1y * v2y
val denom = dot00 * dot11 - dot01 * dot01
if (kotlin.math.abs(denom) < 1e-12f) {
return false
}
val u = (dot11 * dot02 - dot01 * dot12) / denom
val v = (dot00 * dot12 - dot01 * dot02) / denom
return u >= -1e-4f && v >= -1e-4f && u + v <= 1f + 1e-4f
}
for (tri in 0 until mesh.triangleCount) {
val a = mesh.indices[tri * 3]
val b = mesh.indices[tri * 3 + 1]
val c = mesh.indices[tri * 3 + 2]
assertTrue(
!pointInTri(2.5f, 2f, a, b, c),
"notch (2.5,2) must stay empty; fan-from-0 would cover it (tri $tri = $a,$b,$c)",
)
}
}
/**
* Convex octagon: CDT must not put every face on one apex (fan / cascading-ear). Incident face
* counts should be spread — a pure fan from vert 0 would hit all 6 triangles on that vert.
*/
@Test
fun applyAddVertexDraftConvexRingZigzagsNotAFan() {
val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0))
val verts =
listOf(
DraftVert(2f, 0f),
DraftVert(3f, 1f),
DraftVert(3f, 3f),
DraftVert(2f, 4f),
DraftVert(0f, 4f),
DraftVert(-1f, 3f),
DraftVert(-1f, 1f),
DraftVert(0f, 0f),
)
val edges =
verts.indices.map { index ->
DraftEdge.of(DraftEndpoint.Draft(index), DraftEndpoint.Draft((index + 1) % verts.size))!!
}
val result = MeshTopologyOps.applyAddVertexDraft(empty, verts, edges)
assertTrue(result != null)
val mesh = result!!.edit.newMesh
assertEquals(6, mesh.triangleCount)
val incident = IntArray(mesh.vertexCount)
for (tri in 0 until mesh.triangleCount) {
incident[mesh.indices[tri * 3]]++
incident[mesh.indices[tri * 3 + 1]]++
incident[mesh.indices[tri * 3 + 2]]++
}
assertTrue(
incident.max() < mesh.triangleCount,
"no apex should own every face (fan); maxIncident=${incident.max()} tris=${mesh.triangleCount}",
)
assertTrue(incident.count { count -> count >= 3 } >= 2, "at least two verts should share the load")
}
/**
* Three chained clicks without click-back on the first vert still fill on Accept (auto-close).
*/
@Test
fun applyAddVertexDraftOpenPolylineAutoClosesOnAccept() {
val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0))
val result =
MeshTopologyOps.applyAddVertexDraft(
empty,
listOf(DraftVert(0f, 0f), DraftVert(2f, 0f), DraftVert(1f, 2f)),
listOf(
DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!,
DraftEdge.of(DraftEndpoint.Draft(1), DraftEndpoint.Draft(2))!!,
),
)
assertTrue(result != null, "open drawn verts must still commit")
assertEquals(3, result!!.edit.newMesh.vertexCount, "three free floats append")
assertEquals(1, result.edit.newMesh.indices.size / 3, "Accept auto-closes a 3-click triangle")
}
/**
* Legacy fallback: empty mesh + [FreeVertUvContext] (no UV seed) still samples art UVs so Accept
* cannot land UV(0,0) when the Edit-enter seed is missing.
*/
@Test
fun applyAddVertexDraftEmptyMeshSamplesArtUv() {
val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0))
val uvContext =
FreeVertUvContext(
layerLeft = 100f,
layerTop = 200f,
tileWidth = 100f,
tileHeight = 100f,
frame = null,
)
val result =
MeshTopologyOps.applyAddVertexDraft(
empty,
listOf(DraftVert(100f, 200f), DraftVert(200f, 200f), DraftVert(100f, 300f)),
listOf(
DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!,
DraftEdge.of(DraftEndpoint.Draft(1), DraftEndpoint.Draft(2))!!,
DraftEdge.of(DraftEndpoint.Draft(2), DraftEndpoint.Draft(0))!!,
),
uvContext,
)
assertTrue(result != null, "closed wipe rebuild must commit")
val mesh = result!!.edit.newMesh
assertEquals(1, mesh.triangleCount, "one face")
assertTrue(absDiff(mesh.uvs[0], 0f) < 1e-4f && absDiff(mesh.uvs[1], 0f) < 1e-4f, "top-left corner")
assertTrue(absDiff(mesh.uvs[2], 1f) < 1e-4f && absDiff(mesh.uvs[3], 0f) < 1e-4f, "top-right corner")
assertTrue(absDiff(mesh.uvs[4], 0f) < 1e-4f && absDiff(mesh.uvs[5], 1f) < 1e-4f, "bottom-left corner")
}
/**
* Wipe-and-rebuild prefers a pre-wipe [uvSeedMesh] (Edit-enter snapshot) so stored atlas UVs stay
* correct even when the tile has no source binding for art projection.
*/
@Test
fun applyAddVertexDraftEmptyMeshSamplesUvSeed() {
val seed =
DrawableMesh(
floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f),
floatArrayOf(0.25f, 0.5f, 0.75f, 0.5f, 0.25f, 0.9f),
intArrayOf(0, 1, 2),
)
val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0))
val result =
MeshTopologyOps.applyAddVertexDraft(
empty,
listOf(DraftVert(0f, 0f), DraftVert(2f, 0f), DraftVert(0f, 2f)),
listOf(
DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!,
DraftEdge.of(DraftEndpoint.Draft(1), DraftEndpoint.Draft(2))!!,
DraftEdge.of(DraftEndpoint.Draft(2), DraftEndpoint.Draft(0))!!,
),
uvSeedMesh = seed,
)
assertTrue(result != null, "seeded wipe rebuild must commit")
val mesh = result!!.edit.newMesh
assertTrue(absDiff(mesh.uvs[0], 0.25f) < 1e-4f && absDiff(mesh.uvs[1], 0.5f) < 1e-4f)
assertTrue(absDiff(mesh.uvs[2], 0.75f) < 1e-4f && absDiff(mesh.uvs[3], 0.5f) < 1e-4f)
assertTrue(absDiff(mesh.uvs[4], 0.25f) < 1e-4f && absDiff(mesh.uvs[5], 0.9f) < 1e-4f)
}
/** A stale edge-snap after faces were deleted demotes to a free float instead of aborting Accept. */
@Test
fun applyAddVertexDraftStaleSnapDemotesToFree() {
val emptyFaces = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), FloatArray(6), IntArray(0))
val result =
MeshTopologyOps.applyAddVertexDraft(
emptyFaces,
listOf(DraftVert(1f, 0f, snapEdge = MeshElement.Edge.of(0, 1), snapT = 0.5f), DraftVert(1f, 1f)),
listOf(DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!),
)
assertTrue(result != null, "stale snap must not abort Accept")
assertEquals(5, result!!.edit.newMesh.vertexCount, "orphan verts kept + two free appends")
}
/** Object-mode duplicateSelectedDrawables selects the copies as one undo step. */
@Test
fun sessionDuplicatesDrawablesAndSelectsCopies() {
val session = EditorSession(model())
session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d"))))
val stepsBefore = session.historyView.value.steps.size
val copies = session.duplicateSelectedDrawables()
assertEquals(listOf(DrawableId("d.001")), copies)
assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "one undo step")
assertEquals(
setOf<SelectionTarget>(SelectionTarget.Drawable(DrawableId("d.001"))),
session.selection.value.targets,
"the copies become the selection",
)
session.undo()
assertEquals(2, session.model.value.drawables.size, "undo removes the copy")
assertEquals(
setOf<SelectionTarget>(SelectionTarget.Drawable(DrawableId("d"))),
session.selection.value.targets,
"undo restores the prior selection",
)
}
private fun absDiff(left: Float, right: Float): Float = if (left > right) left - right else right - left
}
@@ -0,0 +1,149 @@
package org.umamo.edit
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Verifies the pure topology queries: edge deduplication and canonicalization, per-element vertex
* coverage, and the three derive-up rules the select-mode conversions and display highlights share.
*/
class MeshTopologyTest {
// Two triangles sharing the (1, 2) edge - the minimal mesh with an interior edge.
private val stripIndices = intArrayOf(0, 1, 2, 1, 3, 2)
// The "spoke" fixture: center triangle T (face 0, vertices 0-1-2) shares each of its three edges with
// exactly one neighbor - A (face 1) across (0,1), B (face 2) across (1,2), C (face 3) across (0,2).
private val spokeIndices = intArrayOf(0, 1, 2, 0, 1, 3, 1, 2, 4, 2, 0, 5)
/** uniqueEdges canonicalizes to (low, high) and emits a shared interior edge once. */
@Test
fun uniqueEdgesDedupsAndCanonicalizes() {
val edges = MeshTopology.uniqueEdges(stripIndices)
assertEquals(5, edges.size, "two triangles sharing one edge have five unique edges")
assertEquals(
setOf(
MeshElement.Edge(0, 1),
MeshElement.Edge(1, 2),
MeshElement.Edge(0, 2),
MeshElement.Edge(1, 3),
MeshElement.Edge(2, 3),
),
edges.toSet(),
)
assertTrue(edges.all { edge -> edge.endpointLow <= edge.endpointHigh }, "every edge is canonical")
}
/** edgesOfTriangle and verticesOfTriangle read one triangle's corners. */
@Test
fun perTriangleAccessors() {
assertEquals(setOf(1, 2, 3), MeshTopology.verticesOfTriangle(stripIndices, 1))
assertEquals(
setOf(MeshElement.Edge(1, 3), MeshElement.Edge(2, 3), MeshElement.Edge(1, 2)),
MeshTopology.edgesOfTriangle(stripIndices, 1).toSet(),
)
}
/** coveredVertexIndices resolves each element kind: a vertex itself, an edge its endpoints, a face its corners. */
@Test
fun coveredVertexIndicesResolvesEachElementKind() {
val elements =
setOf(
MeshElement.Vertex(5),
MeshElement.Edge.of(3, 1),
MeshElement.Face(0),
)
assertEquals(setOf(0, 1, 2, 3, 5), MeshTopology.coveredVertexIndices(elements, spokeIndices))
}
/** An edge derives from a vertex set only when both endpoints are selected. */
@Test
fun edgesWithBothEndpointsSelectedIsStrict() {
val edges = MeshTopology.edgesWithBothEndpointsSelected(spokeIndices, setOf(0, 1, 3))
assertEquals(
setOf(MeshElement.Edge(0, 1), MeshElement.Edge(0, 3), MeshElement.Edge(1, 3)),
edges,
)
}
/** A face derives from a vertex set only when all three of its vertices are selected. */
@Test
fun facesWithAllVerticesSelectedIsStrict() {
assertEquals(
setOf(MeshElement.Face(0)),
MeshTopology.facesWithAllVerticesSelected(spokeIndices, setOf(0, 1, 2)),
)
assertTrue(
MeshTopology.facesWithAllVerticesSelected(spokeIndices, setOf(0, 1, 4)).isEmpty(),
"two of three vertices never derive a face",
)
}
/** A face derives from an edge set only when all three of its OWN edges are selected, never by coverage. */
@Test
fun facesWithAllEdgesSelectedIgnoresVertexCoverage() {
val neighborEdges =
setOf(
MeshElement.Edge.of(0, 3),
MeshElement.Edge.of(1, 3),
MeshElement.Edge.of(1, 4),
MeshElement.Edge.of(2, 4),
)
assertTrue(
MeshTopology.facesWithAllEdgesSelected(spokeIndices, neighborEdges).isEmpty(),
"edges covering T's vertices do not select T",
)
assertEquals(
setOf(MeshElement.Face(0)),
MeshTopology.facesWithAllEdgesSelected(
spokeIndices,
setOf(MeshElement.Edge.of(0, 1), MeshElement.Edge.of(1, 2), MeshElement.Edge.of(0, 2)),
),
)
}
// Two disconnected components: the strip (vertices 0-3) plus a lone triangle (vertices 4-6).
private val twoIslandIndices = intArrayOf(0, 1, 2, 1, 3, 2, 4, 5, 6)
/** buildVertexAdjacency lists each vertex's edge-sharing neighbors once, empty for unused vertices. */
@Test
fun adjacencyListsEdgeNeighborsOnce() {
val adjacency = MeshTopology.buildVertexAdjacency(5, stripIndices)
assertEquals(setOf(1, 2), adjacency[0].toSet(), "vertex 0 neighbors")
assertEquals(setOf(0, 2, 3), adjacency[1].toSet(), "vertex 1 neighbors")
assertEquals(setOf(0, 1, 3), adjacency[2].toSet(), "vertex 2 neighbors; the shared (1,2) edge appears once")
assertEquals(setOf(1, 2), adjacency[3].toSet(), "vertex 3 neighbors")
assertEquals(emptySet(), adjacency[4].toSet(), "a vertex outside every triangle has no neighbors")
}
/** connectedVertices floods a whole component and never crosses to a disconnected one. */
@Test
fun connectedVerticesFloodsOneComponent() {
val adjacency = MeshTopology.buildVertexAdjacency(7, twoIslandIndices)
assertEquals(setOf(0, 1, 2, 3), MeshTopology.connectedVertices(adjacency, 0), "the strip floods from vertex 0")
assertEquals(setOf(4, 5, 6), MeshTopology.connectedVertices(adjacency, 5), "the lone triangle floods from vertex 5")
assertEquals(emptySet(), MeshTopology.connectedVertices(adjacency, 99), "an out-of-range seed yields nothing")
}
/** selectionIslands splits by connectivity WITHIN the subset: an unselected bridge vertex separates islands. */
@Test
fun selectionIslandsSplitOnUnselectedBridges() {
val adjacency = MeshTopology.buildVertexAdjacency(7, twoIslandIndices)
// The whole strip selected is one island; adding the lone triangle's vertices makes a second.
val islands = MeshTopology.selectionIslands(adjacency, setOf(0, 1, 2, 3, 4, 5, 6))
assertEquals(2, islands.size, "two mesh components make two islands")
assertEquals(setOf(setOf(0, 1, 2, 3), setOf(4, 5, 6)), islands.toSet())
// Selecting the strip's two ends WITHOUT the middle vertices splits them: 0 and 3 share no
// direct edge, so the sub-graph induced on {0, 3} is two singleton islands.
val split = MeshTopology.selectionIslands(adjacency, setOf(0, 3))
assertEquals(setOf(setOf(0), setOf(3)), split.toSet(), "an unselected bridge separates the ends")
// A connected sub-selection stays one island even when more of the mesh exists around it.
val joined = MeshTopology.selectionIslands(adjacency, setOf(0, 1, 3))
assertEquals(setOf(setOf(0, 1, 3)), joined.toSet(), "0-1 and 1-3 edges join all three")
assertEquals(emptyList(), MeshTopology.selectionIslands(adjacency, emptySet()), "an empty selection has no islands")
}
}
@@ -0,0 +1,185 @@
package org.umamo.edit
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.sqrt
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Verifies the pure modal-operator math: each operator moves only the selected vertices by the expected
* amount about the median pivot, leaves the unselected coordinates and the input array untouched
* (purity / copy-on-write), and the pivot is the centroid of the selection.
*/
class MeshTransformsTest {
// Four vertices of a 2x2 square: (0,0) (2,0) (0,2) (2,2), interleaved.
private fun square(): FloatArray = floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 2f, 2f)
private fun assertClose(expected: Float, actual: Float, message: String) {
assertTrue(abs(expected - actual) < 1e-4f, "$message (expected $expected, was $actual)")
}
/** The median pivot is the centroid of the selected vertices. */
@Test
fun medianPivotIsCentroidOfSelection() {
val (allX, allY) = MeshTransforms.medianPivot(square(), setOf(0, 1, 2, 3))
assertClose(1f, allX, "median x of all four")
assertClose(1f, allY, "median y of all four")
val (rightX, rightY) = MeshTransforms.medianPivot(square(), setOf(1, 3))
assertClose(2f, rightX, "median x of the right edge")
assertClose(1f, rightY, "median y of the right edge")
}
/** Translate moves only the selected vertices; the rest and the input array are untouched. */
@Test
fun translateMovesOnlySelected() {
val input = square()
val result = MeshTransforms.translateVertices(input, setOf(1), deltaX = 1f, deltaY = -1f)
assertEquals(3f, result[2], "vertex 1 x moved by +1")
assertEquals(-1f, result[3], "vertex 1 y moved by -1")
assertEquals(0f, result[0], "vertex 0 untouched")
assertEquals(2f, result[6], "vertex 3 untouched")
// Purity: the input array is unchanged.
assertEquals(2f, input[2], "input vertex 1 x unchanged")
assertEquals(0f, input[3], "input vertex 1 y unchanged")
}
/** Collapse piles every selected vertex onto the target (no offsets kept); the rest are untouched. */
@Test
fun collapsePilesSelectedOntoTarget() {
val input = square()
val result = MeshTransforms.collapseVertices(input, setOf(0, 1, 3), targetX = 5f, targetY = 7f)
// Unlike translateVertices, the inter-vertex offsets are gone: all three land on (5,7).
for (vertexIndex in setOf(0, 1, 3)) {
assertEquals(5f, result[vertexIndex * 2], "vertex $vertexIndex x piled on the target")
assertEquals(7f, result[vertexIndex * 2 + 1], "vertex $vertexIndex y piled on the target")
}
assertEquals(0f, result[4], "vertex 2 x untouched")
assertEquals(2f, result[5], "vertex 2 y untouched")
// Purity: the input array is unchanged.
assertEquals(0f, input[0], "input vertex 0 x unchanged")
}
/** Scale expands selected vertices about the pivot; unselected vertices stay put. */
@Test
fun scaleAboutPivot() {
val input = square()
val result = MeshTransforms.scaleVertices(input, setOf(0, 3), factor = 2f, pivotX = 1f, pivotY = 1f)
// (0,0) about (1,1) by 2 -> (-1,-1); (2,2) -> (3,3).
assertClose(-1f, result[0], "vertex 0 x scaled")
assertClose(-1f, result[1], "vertex 0 y scaled")
assertClose(3f, result[6], "vertex 3 x scaled")
assertClose(3f, result[7], "vertex 3 y scaled")
assertEquals(2f, result[2], "vertex 1 untouched")
assertEquals(0f, input[0], "input unchanged")
}
/** Rotate turns selected vertices about the pivot; a 90 degree turn maps (2,0) about origin to (0,2). */
@Test
fun rotateAboutPivot() {
val input = square()
val result = MeshTransforms.rotateVertices(input, setOf(1), radians = (PI / 2).toFloat(), pivotX = 0f, pivotY = 0f)
assertClose(0f, result[2], "vertex 1 x after 90 degree turn")
assertClose(2f, result[3], "vertex 1 y after 90 degree turn")
assertEquals(0f, result[0], "vertex 0 untouched")
assertEquals(2f, input[2], "input unchanged")
}
/** The combined centroid across arrays is the mean of every vertex, weighted by vertex count. */
@Test
fun combinedCentroidIsVertexWeightedMean() {
// One array centerd at (1,1) with four vertices, plus a single-vertex array at (10,10). The mean of the
// five vertices is ((0+2+0+2+10)/5, (0+0+2+2+10)/5) = (2.8, 2.8), pulled toward the denser square.
val single = floatArrayOf(10f, 10f)
val (centroidX, centroidY) = MeshTransforms.combinedCentroid(listOf(square(), single))
assertClose(2.8f, centroidX, "combined centroid x weighted by vertex count")
assertClose(2.8f, centroidY, "combined centroid y weighted by vertex count")
}
/** The combined centroid of an empty collection (or only empty arrays) is the origin. */
@Test
fun combinedCentroidEmptyIsOrigin() {
val (emptyX, emptyY) = MeshTransforms.combinedCentroid(emptyList())
assertEquals(0f, emptyX, "empty collection centroid x")
assertEquals(0f, emptyY, "empty collection centroid y")
val (blankX, blankY) = MeshTransforms.combinedCentroid(listOf(FloatArray(0), FloatArray(0)))
assertEquals(0f, blankX, "only-empty-arrays centroid x")
assertEquals(0f, blankY, "only-empty-arrays centroid y")
}
/** Weighted translate moves each vertex by its share of the delta; unweighted vertices stay put. */
@Test
fun weightedTranslateScalesTheDeltaPerVertex() {
val input = square()
val result = MeshTransforms.translateVerticesWeighted(input, mapOf(1 to 0.5f, 2 to 1f), deltaX = 4f, deltaY = -2f)
assertClose(4f, result[2], "half-weight vertex 1 x moved by +2")
assertClose(-1f, result[3], "half-weight vertex 1 y moved by -1")
assertClose(4f, result[4], "full-weight vertex 2 x moved by +4")
assertClose(0f, result[5], "full-weight vertex 2 y moved by -2")
assertEquals(0f, result[0], "unweighted vertex 0 untouched")
assertEquals(2f, input[2], "input unchanged")
}
/** Weighted scale lerps each vertex toward its fully-scaled position by its weight. */
@Test
fun weightedScaleLerpsTowardTheScaledPosition() {
val input = square()
val result = MeshTransforms.scaleVerticesWeighted(input, mapOf(0 to 0.5f), factorX = 3f, factorY = 3f, pivotX = 1f, pivotY = 1f)
// (0,0) fully scaled about (1,1) by 3 lands on (-2,-2); half weight stops halfway at (-1,-1)
// (the effective factor is 1 + (3-1) x 0.5 = 2).
assertClose(-1f, result[0], "half-weight vertex 0 x scaled by the effective factor")
assertClose(-1f, result[1], "half-weight vertex 0 y scaled by the effective factor")
assertEquals(2f, result[2], "unweighted vertex 1 untouched")
}
/** Horizontal reverse-swap exchanges x only: 0↔last, 1↔last-1; y stays on each vert. */
@Test
fun reverseSwapPositionsHorizontalSwapsXOnly() {
val input = floatArrayOf(0f, 10f, 1f, 11f, 2f, 12f, 3f, 13f, 4f, 14f, 5f, 15f)
val result = MeshTransforms.reverseSwapPositions(input, listOf(0, 1, 2, 3, 4, 5), horizontal = true)
assertEquals(5f, result[0])
assertEquals(10f, result[1], "y0 stays")
assertEquals(4f, result[2])
assertEquals(11f, result[3], "y1 stays")
assertEquals(0f, result[10])
assertEquals(15f, result[11], "y5 stays")
assertEquals(0f, input[0], "input untouched")
}
/** Vertical reverse-swap exchanges y only; x stays on each vert. */
@Test
fun reverseSwapPositionsVerticalSwapsYOnly() {
val input = floatArrayOf(0f, 10f, 1f, 11f, 2f, 12f, 3f, 13f, 4f, 14f, 5f, 15f)
val result = MeshTransforms.reverseSwapPositions(input, listOf(0, 1, 2, 3, 4, 5), horizontal = false)
assertEquals(0f, result[0], "x0 stays")
assertEquals(15f, result[1])
assertEquals(1f, result[2], "x1 stays")
assertEquals(14f, result[3])
assertEquals(5f, result[10], "x5 stays")
assertEquals(10f, result[11])
}
/** Weighted rotate scales the ANGLE (arc), preserving each vertex's distance from the pivot. */
@Test
fun weightedRotateScalesTheAngleNotTheChord() {
val input = square()
val result = MeshTransforms.rotateVerticesWeighted(input, mapOf(1 to 0.5f), radians = (PI / 2).toFloat(), pivotX = 0f, pivotY = 0f)
// (2,0) with half the 90 degree turn lands at 45 degrees: (sqrt(2), sqrt(2)) - still 2 from the
// pivot, which a positional lerp (the chord midpoint (1,1)) would not be.
val expected = (2.0 / sqrt(2.0)).toFloat()
assertClose(expected, result[2], "half-weight vertex 1 x at 45 degrees")
assertClose(expected, result[3], "half-weight vertex 1 y at 45 degrees")
assertClose(2f, sqrt(result[2] * result[2] + result[3] * result[3]), "distance from the pivot preserved")
assertEquals(0f, result[0], "unweighted vertex 0 untouched")
}
}
@@ -0,0 +1,68 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableMesh
import kotlin.test.Test
import kotlin.test.assertTrue
/**
* Wipe-and-rebuild UV projection: barycentric inside seed faces, affine outside, projectAll rewrites.
*/
class MeshUvFieldTest {
private fun absDiff(a: Float, b: Float): Float = kotlin.math.abs(a - b)
@Test
fun barycentricInsideFaceMatchesSeedVerts() {
val seed =
DrawableMesh(
floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f),
floatArrayOf(0.1f, 0.2f, 0.9f, 0.2f, 0.1f, 0.8f),
intArrayOf(0, 1, 2),
)
val field = MeshUvField(seed)
val (u0, v0) = field.uvAt(0f, 0f)
val (u1, v1) = field.uvAt(2f, 0f)
val (u2, v2) = field.uvAt(0f, 2f)
assertTrue(absDiff(u0, 0.1f) < 1e-4f && absDiff(v0, 0.2f) < 1e-4f)
assertTrue(absDiff(u1, 0.9f) < 1e-4f && absDiff(v1, 0.2f) < 1e-4f)
assertTrue(absDiff(u2, 0.1f) < 1e-4f && absDiff(v2, 0.8f) < 1e-4f)
val (uMid, vMid) = field.uvAt(2f / 3f, 2f / 3f)
assertTrue(absDiff(uMid, (0.1f + 0.9f + 0.1f) / 3f) < 1e-3f)
assertTrue(absDiff(vMid, (0.2f + 0.2f + 0.8f) / 3f) < 1e-3f)
}
@Test
fun projectAllRewritesEveryUvFromRest() {
val seed =
DrawableMesh(
floatArrayOf(0f, 0f, 4f, 0f, 0f, 4f),
floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f),
intArrayOf(0, 1, 2),
)
val rebuilt =
DrawableMesh(
floatArrayOf(0f, 0f, 4f, 0f, 0f, 4f, 1f, 1f),
floatArrayOf(9f, 9f, 9f, 9f, 9f, 9f, 9f, 9f),
intArrayOf(0, 1, 2, 0, 1, 3),
)
val projected = MeshUvField(seed).projectAll(rebuilt)
assertTrue(absDiff(projected.uvs[0], 0f) < 1e-4f && absDiff(projected.uvs[1], 0f) < 1e-4f)
assertTrue(absDiff(projected.uvs[2], 1f) < 1e-4f && absDiff(projected.uvs[3], 0f) < 1e-4f)
assertTrue(absDiff(projected.uvs[4], 0f) < 1e-4f && absDiff(projected.uvs[5], 1f) < 1e-4f)
val (u, v) = MeshUvField(seed).uvAt(1f, 1f)
assertTrue(absDiff(projected.uvs[6], u) < 1e-4f && absDiff(projected.uvs[7], v) < 1e-4f)
}
@Test
fun affineOutsideFaceIsContinuousWithBoundary() {
val seed =
DrawableMesh(
floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f),
floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f),
intArrayOf(0, 1, 2),
)
val field = MeshUvField(seed)
// Just outside the hypotenuse should still be near the affine plane of the triangle.
val (u, v) = field.uvAt(1.2f, 1.2f)
assertTrue(u in -0.2f..1.2f && v in -0.2f..1.2f, "affine outside stays near atlas")
}
}
@@ -0,0 +1,186 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Pins the pure gesture-capture builder the three gizmo overlays share. This logic - the covered-vertex
* anchor, the pivot-mode fallback chain, the per-mesh pivot-group derivation, and the proportional halo -
* lived open-coded in three Compose overlays with no test coverage of its own; the overlays' own tests could
* not reach it. These assertions are that missing gate.
*/
class ModalTransformCaptureTest {
private val meshA = DrawableId("a")
private val meshB = DrawableId("b")
/** A single square mesh (4 verts, 2 tris) whose vertices span (0,0)-(2,2), so its centroid is (1,1). */
private fun square(id: DrawableId, offsetX: Float = 0f, offsetY: Float = 0f): ModalCaptureSource =
ModalCaptureSource(
drawableId = id,
positions =
floatArrayOf(
offsetX + 0f,
offsetY + 0f,
offsetX + 2f,
offsetY + 0f,
offsetX + 2f,
offsetY + 2f,
offsetX + 0f,
offsetY + 2f,
),
triangleIndices = intArrayOf(0, 1, 2, 0, 2, 3),
coveredIndices = setOf(0, 1, 2, 3),
)
private fun build(
sources: List<ModalCaptureSource>,
pivotMode: TransformPivotMode = TransformPivotMode.MedianPoint,
scope: IndividualOriginScope = IndividualOriginScope.ConnectivityIsland,
activeAnchor: Pair<Float, Float>? = null,
cursorAnchor: Pair<Float, Float>? = null,
): ModalTransformCapture? =
buildModalTransformCapture(sources, pivotMode, scope, MeshOperatorKind.Grab, activeAnchor, cursorAnchor)
/** The median anchor is the covered-vertex mean pooled across every moving mesh, not a per-mesh average. */
@Test
fun medianAnchorIsTheCoveredMeanAcrossMeshes() {
// One square at origin (centroid 1,1) and one shifted to (10,10)-(12,12) (centroid 11,11); the pooled
// mean of all eight vertices is (6,6). A per-mesh average would give the midpoint (6,6) too, so make
// the mesh sizes differ to tell them apart.
val small = square(meshA)
val wide =
ModalCaptureSource(
drawableId = meshB,
positions = floatArrayOf(10f, 10f, 12f, 10f), // just two vertices -> pulls the pooled mean less
triangleIndices = intArrayOf(),
coveredIndices = setOf(0, 1),
)
val capture = build(listOf(small, wide))!!
// Pooled: (0+2+2+0 + 10+12) / 6 = 26/6, (0+0+2+2 + 10+10) / 6 = 24/6 = 4.
assertEquals(26f / 6f, capture.anchor.first, 1e-4f)
assertEquals(24f / 6f, capture.anchor.second, 1e-4f)
}
/** Active Element and Cursor each fall back to the median when the caller resolved no anchor. */
@Test
fun activeAndCursorFallBackToMedian() {
val sources = listOf(square(meshA))
assertEquals(1f to 1f, build(sources, TransformPivotMode.ActiveElement, activeAnchor = null)!!.anchor)
assertEquals(1f to 1f, build(sources, TransformPivotMode.Cursor, cursorAnchor = null)!!.anchor)
// A resolved anchor is used verbatim.
assertEquals(5f to 7f, build(sources, TransformPivotMode.ActiveElement, activeAnchor = 5f to 7f)!!.anchor)
assertEquals(9f to 3f, build(sources, TransformPivotMode.Cursor, cursorAnchor = 9f to 3f)!!.anchor)
}
/** A shared-pivot mode makes one group per mesh, pivoted at the shared anchor. */
@Test
fun sharedPivotModesMakeOneGroupAtTheAnchor() {
val capture = build(listOf(square(meshA), square(meshB, offsetX = 10f)), TransformPivotMode.MedianPoint)!!
assertEquals(2, capture.entries.size)
for (entry in capture.entries) {
assertEquals(1, entry.groups.size, "shared pivot is a single group")
assertEquals(capture.anchor.first, entry.groups.single().pivotX, 1e-4f)
assertEquals(capture.anchor.second, entry.groups.single().pivotY, 1e-4f)
assertEquals(setOf(0, 1, 2, 3), entry.groups.single().vertexIndices)
}
}
/** WholeMesh Individual Origins pivots each mesh about its OWN centroid, not the shared anchor. */
@Test
fun individualOriginsWholeMeshUsesEachMeshOwnCentroid() {
val capture =
build(
listOf(square(meshA), square(meshB, offsetX = 10f)),
TransformPivotMode.IndividualOrigins,
scope = IndividualOriginScope.WholeMesh,
)!!
val groupA = capture.entries.first { it.drawableId == meshA }.groups.single()
val groupB = capture.entries.first { it.drawableId == meshB }.groups.single()
assertEquals(1f, groupA.pivotX, 1e-4f)
assertEquals(11f, groupB.pivotX, 1e-4f) // shifted square's own centroid, not the shared (6,1) anchor
}
/** ConnectivityIsland Individual Origins splits one mesh's disjoint islands into separate groups. */
@Test
fun individualOriginsConnectivityIslandSplitsDisjointIslands() {
// Two disjoint triangles in one mesh (verts 0-2 and 3-5, no shared edge).
val twoIslands =
ModalCaptureSource(
drawableId = meshA,
positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 10f, 10f, 11f, 10f, 10f, 11f),
triangleIndices = intArrayOf(0, 1, 2, 3, 4, 5),
coveredIndices = setOf(0, 1, 2, 3, 4, 5),
)
val groups =
build(listOf(twoIslands), TransformPivotMode.IndividualOrigins, scope = IndividualOriginScope.ConnectivityIsland)!!
.entries
.single()
.groups
assertEquals(2, groups.size, "two disjoint islands -> two pivot groups")
assertEquals(setOf(setOf(0, 1, 2), setOf(3, 4, 5)), groups.map { it.vertexIndices }.toSet())
}
/** A source with no covered vertices is dropped; an all-empty source list returns null (no gesture). */
@Test
fun emptyCoveredSourcesAreDroppedAndAllEmptyReturnsNull() {
val empty = ModalCaptureSource(meshB, floatArrayOf(5f, 5f), intArrayOf(), emptySet())
val capture = build(listOf(square(meshA), empty))!!
assertEquals(listOf(meshA), capture.drawableIds, "the empty source does not become an entry")
assertNull(build(listOf(empty)), "no covered vertices anywhere -> no capture")
assertNull(build(emptyList()))
}
/** With proportional off, every mesh's moved set is exactly its covered set. */
@Test
fun noProportionalLeavesMovedSetEqualToCovered() {
val capture = build(listOf(square(meshA)))!!
capture.applyProportional(null, 100f)
val entry = capture.entries.single()
assertTrue(entry.influence.isEmpty())
assertEquals(entry.coveredIndices, entry.movedIndices)
}
/** Proportional editing with a wide radius pulls unselected neighbours into the moved set. */
@Test
fun proportionalHaloAddsInfluencedNeighboursToTheMovedSet() {
// One selected vertex at the origin, one unselected vertex a short hop away, on a shared edge.
val mesh =
ModalCaptureSource(
drawableId = meshA,
positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f),
triangleIndices = intArrayOf(0, 1, 2),
coveredIndices = setOf(0),
)
val capture = build(listOf(mesh))!!
capture.applyProportional(ProportionalEditState(ProportionalFalloff.Linear, radiusWorld = 5f), 5f)
val entry = capture.entries.single()
assertTrue(entry.influence.isNotEmpty(), "neighbours within the radius take weight")
assertTrue(entry.movedIndices.containsAll(entry.coveredIndices))
assertTrue(entry.movedIndices.size > entry.coveredIndices.size, "the halo grew the moved set")
// Re-deriving from the same frozen positions is idempotent, never compounding.
val movedOnce = entry.movedIndices
capture.applyProportional(ProportionalEditState(ProportionalFalloff.Linear, radiusWorld = 5f), 5f)
assertEquals(movedOnce, entry.movedIndices)
}
/** Connected Only measures the halo geodesically, so it cannot leap to a disjoint island. */
@Test
fun connectedOnlyHaloDoesNotLeapToADisjointIsland() {
// Selected vertex 0 on the first triangle; the second triangle (verts 3-5) sits close in space but
// shares no edge, so a geodesic halo must never reach it.
val mesh =
ModalCaptureSource(
drawableId = meshA,
positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 0.5f, 0.5f, 1.5f, 0.5f, 0.5f, 1.5f),
triangleIndices = intArrayOf(0, 1, 2, 3, 4, 5),
coveredIndices = setOf(0),
)
val capture = build(listOf(mesh))!!
capture.applyProportional(ProportionalEditState(ProportionalFalloff.Linear, radiusWorld = 100f, connectedOnly = true), 100f)
val influenced = capture.entries.single().influence.keys
assertTrue(influenced.all { it in setOf(1, 2) }, "geodesic halo stays on the connected island: $influenced")
}
}
@@ -0,0 +1,123 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the pure bounds geometry behind the Properties panel's Position and Size rows: the rows READ
* meshBounds and WRITE through these ops, so the invariant that matters is that asking for a value makes
* the measurement become exactly that value. Also pins the bounds center as the resize pivot (which is
* what keeps the Position row from jumping when Size changes) and the degenerate-axis guard.
*
* These are space-agnostic - the Properties panel feeds them WORLD positions, and the session-level round
* trip through the deformer chain is covered in :ui by DrawableWorldTransformTest.
*/
class ObjectBoundsEditsTest {
private val drawableId = DrawableId("d")
/** A 40 x 20 quad centered on (10, 5), deliberately asymmetric in x so the vertex mean is NOT the bounds center. */
private val quadPositions =
floatArrayOf(
-10f,
-5f,
30f,
-5f,
30f,
15f,
-10f,
15f,
// A fifth vertex clustered left, to pull the vertex centroid away from the bounds center.
-9f,
14f,
)
private fun drawable(positions: FloatArray?): Drawable =
Drawable(
id = drawableId,
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = positions?.let { DrawableMesh(it, FloatArray(it.size), intArrayOf(0, 1, 2)) },
geometryGrid = null,
)
private fun model(positions: FloatArray? = quadPositions.copyOf()): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = emptyList(),
drawables = listOf(drawable(positions)),
rootChildren = emptyList(),
rootPartId = null,
)
@Test
fun boundsReportsTheCenterAndExtents() {
val bounds = meshBounds(quadPositions)
assertEquals(10f, bounds.centerX)
assertEquals(5f, bounds.centerY)
assertEquals(40f, bounds.width)
assertEquals(20f, bounds.height)
// An empty or single-coordinate array degrades to a zero box rather than throwing.
val empty = meshBounds(floatArrayOf())
assertEquals(0f, empty.width)
assertEquals(0f, empty.height)
}
@Test
fun movingLandsTheBoundsCenterExactlyOnTheRequestedPoint() {
val moved = movedToBoundsCenter(quadPositions, -100f, 250f)
val bounds = meshBounds(moved)
// The whole contract of the Position row: what you type is what the readout becomes.
assertEquals(-100f, bounds.centerX)
assertEquals(250f, bounds.centerY)
// Rigid: the extents are untouched.
assertEquals(40f, bounds.width)
assertEquals(20f, bounds.height)
}
@Test
fun movingToTheCurrentCenterIsANoOp() {
assertSame(quadPositions, movedToBoundsCenter(quadPositions, 10f, 5f))
// An empty mesh has no center to move, so it comes back untouched (the same instance it was given).
val empty = floatArrayOf()
assertSame(empty, movedToBoundsCenter(empty, 1f, 1f))
}
@Test
fun resizingLandsTheExtentsAndHoldsThePositionStill() {
val resized = resizedAboutBoundsCenter(quadPositions, 80f, 5f)
val bounds = meshBounds(resized)
assertEquals(80f, bounds.width)
assertEquals(5f, bounds.height)
// The bounds center is the pivot, so the Position row does not move when Size is edited. This is
// what a vertex-centroid pivot would break: the extra clustered vertex pulls that mean off-center.
assertEquals(10f, bounds.centerX)
assertEquals(5f, bounds.centerY)
}
@Test
fun resizingToTheCurrentExtentsIsANoOp() {
assertSame(quadPositions, resizedAboutBoundsCenter(quadPositions, 40f, 20f))
}
@Test
fun aDegenerateAxisIsLeftAloneRatherThanScaledByInfinity() {
// Every vertex on one horizontal line: height is 0, so no factor exists for it.
val flat = floatArrayOf(0f, 7f, 10f, 7f, 20f, 7f)
val resized = resizedAboutBoundsCenter(flat, 40f, 100f)
val bounds = meshBounds(resized)
assertEquals(40f, bounds.width, "the well-defined axis still scales")
assertEquals(0f, bounds.height, "the degenerate axis stays degenerate, not NaN or infinite")
assertTrue(resized.all { coordinate -> coordinate.isFinite() }, "no infinity leaked into the geometry")
}
}
@@ -0,0 +1,186 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Verifies the Object-mode session surface: the select-tool guards relaxed for Object mode, the object
* operator's eligibility guard and single-step commit, and the transient-tool clears that keep an armed
* object tool from leaking across a mode switch or an undo.
*/
class ObjectOperatorSessionTest {
private fun meshDrawable(id: String, positions: FloatArray): Drawable =
Drawable(
id = DrawableId(id),
name = id,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2)),
geometryGrid = null,
)
private val warp = Deformer.Warp(DeformerId("w"), "W", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null)
private fun model(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = listOf(warp),
drawables = listOf(meshDrawable("a", floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f)), meshDrawable("b", floatArrayOf(2f, 2f, 3f, 2f, 2f, 3f))),
rootChildren = emptyList(),
rootPartId = null,
)
private fun session(): EditorSession = EditorSession(model())
private val drawableA = SelectionTarget.Drawable(DrawableId("a"))
/** Box / Circle select arm in Object mode with no drawable required (the box builds a whole-object selection). */
@Test
fun selectToolsArmInObjectModeWithoutDrawable() {
val session = session()
assertEquals(EditorMode.Object, session.mode.value)
session.beginBoxSelect("area-test")
assertTrue(session.activeSelectTool.value is ActiveSelectTool.BoxArmed, "box arms in Object mode")
session.beginCircleSelect("area-test")
assertTrue(session.activeSelectTool.value is ActiveSelectTool.Circle, "circle arms in Object mode")
}
/** An object operator latches on an eligible drawable selection. */
@Test
fun objectOperatorArmsOnEligibleSelection() {
val session = session()
session.setSelection(Selection(setOf(drawableA), drawableA))
session.beginObjectOperator(MeshOperatorKind.Grab, "area-test")
assertEquals(MeshOperatorKind.Grab, session.activeObjectOperator.value?.kind)
}
/** An object operator blocks (stays null) when the selection holds nothing transformable at all. */
@Test
fun objectOperatorBlocksOnIneligibleSelection() {
val session = session()
// Empty selection.
session.beginObjectOperator(MeshOperatorKind.Grab, "area-test")
assertNull(session.activeObjectOperator.value, "empty selection blocks")
assertEquals("notice.transform.onlyDrawables", session.notice.value?.messageKey, "the block explains itself")
assertEquals(NoticePlacement.NearCursor, session.notice.value?.placement, "the note shows near the pointer")
// A selection of only a deformer blocks (nothing transformable).
session.setSelection(Selection(setOf(SelectionTarget.Deformer(DeformerId("w"))), null))
session.beginObjectOperator(MeshOperatorKind.Grab, "area-test")
assertNull(session.activeObjectOperator.value, "an only-deformer selection blocks")
}
/** A deformer beside a drawable is silently skipped: the operator still arms for the drawable. */
@Test
fun objectOperatorSkipsIneligibleTargetsBesideDrawables() {
val session = session()
session.setSelection(Selection(setOf(drawableA, SelectionTarget.Deformer(DeformerId("w"))), drawableA))
session.beginObjectOperator(MeshOperatorKind.Grab, "area-test")
assertEquals(MeshOperatorKind.Grab, session.activeObjectOperator.value?.kind, "the drawable beside the deformer still transforms")
}
/** An object operator refuses to start while any parameter is scrubbed away from its default. */
@Test
fun objectOperatorBlocksWhilePoseIsDeformed() {
val angle = Parameter(ParameterId("angle"), "Angle", min = -1f, max = 1f, default = 0f)
val session = EditorSession(model().copy(parameters = listOf(angle)))
session.setSelection(Selection(setOf(drawableA), drawableA))
// Scrub the parameter away from its default, then try to transform.
session.commitPose(ParameterChange.SetValue(listOf(angle.id)), mapOf(angle.id to 0.5f))
session.beginObjectOperator(MeshOperatorKind.Grab, "area-test")
assertNull(session.activeObjectOperator.value, "a deformed pose blocks the transform")
assertEquals("notice.transform.deformed", session.notice.value?.messageKey, "the guard explains itself")
assertEquals(NoticePlacement.NearCursor, session.notice.value?.placement, "the note shows near the pointer")
// Back at defaults the same gesture arms.
session.commitPose(ParameterChange.SetValue(listOf(angle.id)), mapOf(angle.id to 0f))
session.beginObjectOperator(MeshOperatorKind.Grab, "area-test")
assertEquals(MeshOperatorKind.Grab, session.activeObjectOperator.value?.kind, "a neutral pose arms")
}
/** An object operator only arms in Object mode. */
@Test
fun objectOperatorRequiresObjectMode() {
val session = session()
session.setSelection(Selection(setOf(drawableA), drawableA))
session.setMode(EditorMode.Edit)
session.beginObjectOperator(MeshOperatorKind.Grab, "area-test")
assertNull(session.activeObjectOperator.value, "no object operator in Edit mode")
}
/** commitObjectPositions writes the new base positions as exactly one undo step. */
@Test
fun commitObjectPositionsIsOneUndoStep() {
val session = session()
assertFalse(session.canUndo.value)
val moved = floatArrayOf(10f, 10f, 11f, 10f, 10f, 11f)
session.commitObjectPositions(MeshChange.TransformDrawables(listOf(DrawableId("a")), MeshOperatorKind.Grab), mapOf(DrawableId("a") to moved))
assertTrue(session.canUndo.value, "the commit is undoable")
assertTrue(session.dirty.value, "a rest-geometry edit dirties the document")
assertEquals(moved.toList(), session.model.value.drawables.first { it.id == DrawableId("a") }.mesh!!.positions.toList())
// Exactly one step: a single undo returns to the original geometry with nothing left to undo.
session.undo()
assertFalse(session.canUndo.value, "exactly one step was recorded")
assertEquals(listOf(0f, 0f, 1f, 0f, 0f, 1f), session.model.value.drawables.first { it.id == DrawableId("a") }.mesh!!.positions.toList())
}
/** commitObjectPositions with the drawable's existing positions is a no-op that records nothing. */
@Test
fun commitObjectPositionsIdentityRecordsNothing() {
val session = session()
val current = session.model.value.drawables.first { it.id == DrawableId("a") }.mesh!!.positions
session.commitObjectPositions(MeshChange.TransformDrawables(listOf(DrawableId("a")), MeshOperatorKind.Grab), mapOf(DrawableId("a") to current))
assertFalse(session.canUndo.value, "committing the same positions records nothing")
}
// (The object change's history label is pinned across every operator kind in TransformChangeLabelTest.)
/** Switching to Edit mode clears an armed object select tool, so it cannot leak into the Edit overlay. */
@Test
fun switchingToEditClearsArmedObjectTool() {
val session = session()
session.beginBoxSelect("area-test")
assertTrue(session.activeSelectTool.value is ActiveSelectTool.BoxArmed)
session.setMode(EditorMode.Edit)
assertNull(session.activeSelectTool.value, "the armed object tool is cleared entering Edit mode")
}
/** An undo (restore) ends any armed transient tool regardless of the restored mode. */
@Test
fun undoClearsArmedObjectTool() {
val session = session()
// A committed step so there is something to undo.
session.commitObjectPositions(MeshChange.TransformDrawables(listOf(DrawableId("a")), MeshOperatorKind.Grab), mapOf(DrawableId("a") to floatArrayOf(9f, 9f, 9f, 9f, 9f, 9f)))
session.beginBoxSelect("area-test")
assertTrue(session.activeSelectTool.value is ActiveSelectTool.BoxArmed)
session.undo()
assertNull(session.activeSelectTool.value, "restore clears the armed tool")
}
}
@@ -0,0 +1,128 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Verifies [eligibleTransformDrawables] - the gate that decides what an Object-mode G / S / R may run
* over: mesh-carrying drawables from the selection, with selected parts expanded to their subtree
* meshes, and deformers / mesh-less drawables silently skipped; null only when the selection holds
* nothing transformable at all (so the caller blocks the gesture with a note). Also verifies
* [isPoseNeutral], the guard that refuses an Object-mode transform while any parameter is scrubbed
* away from its default.
*/
class ObjectTransformsTest {
private fun mesh(): DrawableMesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), intArrayOf(0, 1, 2))
private fun drawable(id: String, withMesh: Boolean): Drawable =
Drawable(
DrawableId(id),
id.uppercase(),
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = if (withMesh) mesh() else null,
geometryGrid = null,
)
// A model with two mesh-carrying drawables, one mesh-less drawable, a part that owns drawable a,
// an empty part, and a deformer.
private fun model(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts =
listOf(
Part(PartId("p"), "P", children = listOf(OrgChild.Drawable(DrawableId("a")))),
Part(PartId("empty"), "Empty", children = emptyList()),
),
deformers = listOf(Deformer.Warp(DeformerId("w"), "W", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null)),
drawables = listOf(drawable("a", withMesh = true), drawable("b", withMesh = true), drawable("empty", withMesh = false)),
rootChildren = listOf(OrgChild.Part(PartId("p")), OrgChild.Part(PartId("empty")), OrgChild.Drawable(DrawableId("b"))),
rootPartId = null,
)
private val drawableA = SelectionTarget.Drawable(DrawableId("a"))
private val drawableB = SelectionTarget.Drawable(DrawableId("b"))
/** All targets are mesh-carrying drawables: the ids are returned (order-independent). */
@Test
fun allMeshDrawablesAreEligible() {
val ids = eligibleTransformDrawables(Selection(setOf(drawableA, drawableB), drawableB), model())
assertEquals(setOf(DrawableId("a"), DrawableId("b")), ids?.toSet(), "both drawable ids are eligible")
}
/** An empty selection has nothing to transform. */
@Test
fun emptySelectionIsIneligible() {
assertNull(eligibleTransformDrawables(Selection(), model()))
}
/** A selected part expands to the mesh drawables in its outliner subtree. */
@Test
fun partSelectionExpandsToSubtreeMeshes() {
val selection = Selection(setOf(SelectionTarget.Part(PartId("p"))), SelectionTarget.Part(PartId("p")))
assertEquals(listOf(DrawableId("a")), eligibleTransformDrawables(selection, model()))
}
/** A part and one of its drawables in the same selection do not double-list the mesh. */
@Test
fun partAndOwnDrawableDedup() {
val selection = Selection(setOf(drawableA, SelectionTarget.Part(PartId("p"))), drawableA)
assertEquals(listOf(DrawableId("a")), eligibleTransformDrawables(selection, model()))
}
/** A deformer in the selection is silently skipped; the drawable beside it still transforms. */
@Test
fun deformerInSelectionIsSkipped() {
val selection = Selection(setOf(drawableA, SelectionTarget.Deformer(DeformerId("w"))), drawableA)
assertEquals(listOf(DrawableId("a")), eligibleTransformDrawables(selection, model()))
}
/** A mesh-less drawable in the selection is silently skipped: it has no positions to move. */
@Test
fun meshlessDrawableInSelectionIsSkipped() {
val selection = Selection(setOf(drawableA, SelectionTarget.Drawable(DrawableId("empty"))), drawableA)
assertEquals(listOf(DrawableId("a")), eligibleTransformDrawables(selection, model()))
}
/** A selection holding nothing transformable at all (empty part + deformer) blocks. */
@Test
fun onlyIneligibleTargetsBlock() {
val selection = Selection(setOf(SelectionTarget.Part(PartId("empty")), SelectionTarget.Deformer(DeformerId("w"))), null)
assertNull(eligibleTransformDrawables(selection, model()))
}
private fun parameter(id: String, default: Float): Parameter = Parameter(ParameterId(id), id, min = -1f, max = 1f, default = default)
private fun modelWithParameters(): PuppetModel = model().copy(parameters = listOf(parameter("angle", 0f), parameter("breath", 0.5f)))
/** Every parameter at its default (explicitly or by omission) is neutral. */
@Test
fun poseAtDefaultsIsNeutral() {
val model = modelWithParameters()
assertTrue(isPoseNeutral(model, mapOf(ParameterId("angle") to 0f, ParameterId("breath") to 0.5f)), "explicit defaults are neutral")
assertTrue(isPoseNeutral(model, emptyMap()), "an omitted parameter counts as neutral")
}
/** Any parameter scrubbed away from its default makes the pose non-neutral. */
@Test
fun scrubbedPoseIsNotNeutral() {
val model = modelWithParameters()
assertFalse(isPoseNeutral(model, mapOf(ParameterId("angle") to 0.25f)))
}
}
@@ -0,0 +1,221 @@
package org.umamo.edit
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class OutlinerTreeEditsTest {
private val partA = PartId("A")
private val partB = PartId("B")
private val drawable1 = DrawableId("d1")
private val drawable2 = DrawableId("d2")
private val drawable3 = DrawableId("d3")
private val warpRoot = DeformerId("w1")
private val warpSibling = DeformerId("w2")
private val warpNested = DeformerId("w3")
/**
* A minimal tree model: part A holds drawables d1 + d2, part B is empty, d3 sits at the root; the
* armature has roots w1 + w2 with w3 nested under w1. Only the fields the drop resolution walks
* (parts, rootChildren, deformers) are populated.
*
* @return PuppetModel The fixture model.
*/
private fun model(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts =
listOf(
Part(partA, "A", children = listOf(OrgChild.Drawable(drawable1), OrgChild.Drawable(drawable2))),
Part(partB, "B", children = emptyList()),
),
deformers =
listOf(
rotation(warpRoot, parent = null),
rotation(warpSibling, parent = null),
rotation(warpNested, parent = warpRoot),
),
drawables = emptyList(),
rootChildren = listOf(OrgChild.Part(partA), OrgChild.Part(partB), OrgChild.Drawable(drawable3)),
rootPartId = null,
)
/**
* A minimal rotation deformer for armature-shape tests (the kind is irrelevant to drop routing).
*
* @param DeformerId id The deformer's id.
* @param DeformerId? parent Its nesting parent, or null at the armature root.
* @return Deformer The deformer.
*/
private fun rotation(id: DeformerId, parent: DeformerId?): Deformer =
Deformer.Rotation(id, id.raw, parent = parent, partId = null, baseAngle = 0f, geometryGrid = null)
private fun PuppetModel.band(dragged: SelectionTarget, target: SelectionTarget, fraction: Float): RowDropBand? =
outlinerDropBandFor(dragged, OutlinerDropTarget.Entity(target), fraction)
private fun PuppetModel.drop(dragged: SelectionTarget, target: SelectionTarget, fraction: Float): OutlinerDrop? =
resolveOutlinerDrop(dragged, OutlinerDropTarget.Entity(target), fraction)
@Test
fun bandRefusesCrossDomainDrops() {
val model = model()
assertNull(model.band(SelectionTarget.Deformer(warpRoot), SelectionTarget.Drawable(drawable1), 0.5f))
assertNull(model.band(SelectionTarget.Drawable(drawable1), SelectionTarget.Deformer(warpRoot), 0.5f))
}
@Test
fun drawableTargetSplitsAtMidlineAndNeverNests() {
val model = model()
val dragged = SelectionTarget.Drawable(drawable3)
val target = SelectionTarget.Drawable(drawable1)
assertEquals(RowDropBand.Before, model.band(dragged, target, 0.4f))
assertEquals(RowDropBand.After, model.band(dragged, target, 0.6f))
}
@Test
fun partTargetHasWideIntoBandForDrawables() {
val model = model()
val dragged = SelectionTarget.Drawable(drawable3)
val target = SelectionTarget.Part(partB)
assertEquals(RowDropBand.Before, model.band(dragged, target, 0.2f))
assertEquals(RowDropBand.Into, model.band(dragged, target, 0.5f))
assertEquals(RowDropBand.After, model.band(dragged, target, 0.8f))
}
@Test
fun partOnPartOnlyReordersAtMidline() {
// Folders on folders match the parameters panel: before / after only, so sibling reorder is not
// fighting a middle "into" band. Nesting a part is dropping beside a child inside the destination.
val model = model()
val dragged = SelectionTarget.Part(partB)
val target = SelectionTarget.Part(partA)
assertEquals(RowDropBand.Before, model.band(dragged, target, 0.4f))
assertEquals(RowDropBand.After, model.band(dragged, target, 0.6f))
assertEquals(
OutlinerDrop.MoveOrgChild(OrgChild.Part(partB), newParentId = null, before = OrgChild.Part(partA), expandTarget = false),
model.drop(dragged, target, 0.2f),
)
// Midline is After (not Into): next root sibling after A is B itself, which the move treats as append.
assertEquals(
OutlinerDrop.MoveOrgChild(OrgChild.Part(partB), newParentId = null, before = OrgChild.Part(partB), expandTarget = false),
model.drop(dragged, target, 0.5f),
)
}
@Test
fun beforeDropAnchorsOnTargetInsideItsParent() {
val drop = model().drop(SelectionTarget.Drawable(drawable3), SelectionTarget.Drawable(drawable1), 0.1f)
assertEquals(
OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable3), partA, before = OrgChild.Drawable(drawable1), expandTarget = false),
drop,
)
}
@Test
fun afterDropAnchorsOnNextSibling() {
val drop = model().drop(SelectionTarget.Drawable(drawable3), SelectionTarget.Drawable(drawable1), 0.9f)
assertEquals(
OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable3), partA, before = OrgChild.Drawable(drawable2), expandTarget = false),
drop,
)
}
@Test
fun afterDropOnLastSiblingAppends() {
val drop = model().drop(SelectionTarget.Drawable(drawable3), SelectionTarget.Drawable(drawable2), 0.9f)
assertEquals(
OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable3), partA, before = null, expandTarget = false),
drop,
)
}
@Test
fun intoPartNestsAndExpands() {
val drop = model().drop(SelectionTarget.Drawable(drawable3), SelectionTarget.Part(partB), 0.5f)
assertEquals(
OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable3), partB, before = null, expandTarget = true),
drop,
)
}
@Test
fun rootLevelTargetResolvesRootSiblings() {
// Dropping d1 after part B at the root: the next root sibling is d3.
val drop = model().drop(SelectionTarget.Drawable(drawable1), SelectionTarget.Part(partB), 0.9f)
assertEquals(
OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable1), newParentId = null, before = OrgChild.Drawable(drawable3), expandTarget = false),
drop,
)
}
@Test
fun puppetRootDropMovesOrgChildToTopLevel() {
val model = model()
val dragged = SelectionTarget.Drawable(drawable1)
assertEquals(
OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable1), newParentId = null, before = OrgChild.Part(partA), expandTarget = false),
model.resolveOutlinerDrop(dragged, OutlinerDropTarget.PuppetRoot, 0.2f),
)
assertEquals(
OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable1), newParentId = null, before = null, expandTarget = false),
model.resolveOutlinerDrop(dragged, OutlinerDropTarget.PuppetRoot, 0.8f),
)
assertNull(model.resolveOutlinerDrop(SelectionTarget.Deformer(warpRoot), OutlinerDropTarget.PuppetRoot, 0.5f))
}
@Test
fun armatureDropMakesDeformerARoot() {
val model = model()
assertEquals(
OutlinerDrop.MoveDeformer(warpNested, newParentId = null, beforeId = null, expandTarget = true),
model.resolveOutlinerDrop(SelectionTarget.Deformer(warpNested), OutlinerDropTarget.Armature, 0.5f),
)
assertNull(model.resolveOutlinerDrop(SelectionTarget.Part(partA), OutlinerDropTarget.Armature, 0.5f))
}
@Test
fun cycleOntoOwnDescendantIsRefused() {
// Nest B under A, then dragging A onto B (or into B via a child) must not resolve.
val nested =
model().copy(
parts =
listOf(
Part(partA, "A", children = listOf(OrgChild.Part(partB), OrgChild.Drawable(drawable1))),
Part(partB, "B", children = emptyList()),
),
rootChildren = listOf(OrgChild.Part(partA), OrgChild.Drawable(drawable3)),
)
assertNull(nested.drop(SelectionTarget.Part(partA), SelectionTarget.Part(partB), 0.2f))
assertNull(nested.drop(SelectionTarget.Part(partA), SelectionTarget.Drawable(drawable1), 0.9f))
}
@Test
fun deformerBeforeAndAfterAnchorWithinParent() {
val model = model()
// w2 dropped before w3 (nested under w1): parent w1, anchored on w3.
assertEquals(
OutlinerDrop.MoveDeformer(warpSibling, warpRoot, beforeId = warpNested, expandTarget = false),
model.drop(SelectionTarget.Deformer(warpSibling), SelectionTarget.Deformer(warpNested), 0.1f),
)
// w2 dropped after w3, the last of w1's children: append (null anchor).
assertEquals(
OutlinerDrop.MoveDeformer(warpSibling, warpRoot, beforeId = null, expandTarget = false),
model.drop(SelectionTarget.Deformer(warpSibling), SelectionTarget.Deformer(warpNested), 0.9f),
)
}
@Test
fun deformerIntoNestsAndExpands() {
assertEquals(
OutlinerDrop.MoveDeformer(warpSibling, warpRoot, beforeId = null, expandTarget = true),
model().drop(SelectionTarget.Deformer(warpSibling), SelectionTarget.Deformer(warpRoot), 0.5f),
)
}
}
@@ -0,0 +1,423 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.BlendShapeBinding
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.Glue
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.MeshForm
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.ParameterKind
import org.umamo.runtime.model.ParameterLink
import org.umamo.runtime.model.ParameterNode
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartGroupMode
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.RenderGroup
import org.umamo.runtime.model.withDerivedRenderRoot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the parameter document edits: create mints a fresh animatable axis at the top and returns its id,
* rename changes the display name (id-stable) with blank / unchanged no-ops, and delete removes the axis
* from the parameters list, the panel tree, any link, and every keyform grid - collapsing a grid to the
* deleted parameter's default slice or to null when it was the last axis. Also pins the generic
* withAxisCollapsed coordinate math, and that each edit undoes.
*/
class ParameterCrudEditsTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
/** An animatable parameter over -1..1 with the given [default]. */
private fun parameter(id: ParameterId, default: Float = 0f): Parameter =
Parameter(id, id.raw, min = -1f, max = 1f, default = default)
/** A drawable-less model holding [parameters], [links], [tree], and optional [drawables]. */
private fun model(
parameters: List<Parameter>,
links: List<ParameterLink> = emptyList(),
tree: List<ParameterNode> = emptyList(),
drawables: List<Drawable> = emptyList(),
): PuppetModel =
PuppetModel(
parameters = parameters,
parts = emptyList(),
deformers = emptyList(),
drawables = drawables,
rootChildren = emptyList(),
rootPartId = null,
parameterLinks = links,
parameterTree = tree,
)
/**
* A drawable keyed on angleX (keys -1, 0, 1) then angleY (keys 0, 1) - a 3x2 grid whose every cell's
* MeshForm carries a distinctive value (xIndex*10 + yIndex), so a collapse can be traced by payload.
*/
private fun keyedDrawable(): Drawable {
val axes = listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f)), KeyformAxis(angleY, floatArrayOf(0f, 1f)))
val cells =
buildList {
for (xIndex in 0..2) {
for (yIndex in 0..1) {
add(KeyformCell(intArrayOf(xIndex, yIndex), MeshDeltaForm(floatArrayOf(xIndex * 10f + yIndex))))
}
}
}
return Drawable(
id = DrawableId("d"),
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = KeyformGrid(axes, cells),
)
}
/** Create appends the axis, prepends its leaf at the top, and returns the minted id. */
@Test
fun createAppendsAxisAndPrependsLeaf() {
val session = EditorSession(model(listOf(parameter(angleX))))
val id = session.createParameter("New Parameter")
assertEquals(ParameterId("Param"), id, "the first minted id is Param")
val created = session.model.value.parameters.first { it.id == id }
assertEquals("New Parameter", created.name)
assertTrue(created.min < created.max, "the new parameter is animatable")
assertEquals(ParameterNode.Param(id), session.model.value.parameterTree.first(), "the leaf is at the top")
assertEquals(ParameterKind.NORMAL, created.kind, "the default kind is a key-form parameter")
session.undo()
assertTrue(session.model.value.parameters.none { it.id == id }, "undo removes the new parameter")
}
/** Create carries the requested kind (a blend-shape parameter authored with no keys yet). */
@Test
fun createUsesRequestedKind() {
val session = EditorSession(model(listOf(parameter(angleX))))
val normalId = session.createParameter("A", ParameterKind.NORMAL)
val blendId = session.createParameter("B", ParameterKind.BLEND_SHAPE)
assertEquals(
ParameterKind.NORMAL,
session.model.value.parameters.first { it.id == normalId }.kind,
"explicit NORMAL stays a key-form parameter",
)
val blend = session.model.value.parameters.first { it.id == blendId }
assertEquals(ParameterKind.BLEND_SHAPE, blend.kind, "BLEND_SHAPE is carried through to the model")
assertTrue(session.model.value.drawables.all { it.blendShapes.isEmpty() }, "a fresh blend parameter keys nothing yet")
}
/** The minted parameter id skips ids already present. */
@Test
fun freshIdAvoidsCollision() {
val existing = model(listOf(parameter(ParameterId("Param")), parameter(ParameterId("Param2"))))
assertEquals(ParameterId("Param3"), existing.freshParameterId())
}
/** Rename changes the display name; blank and unchanged names are no-ops. */
@Test
fun renameChangesNameBlankAndUnchangedAreNoOps() {
val start = model(listOf(parameter(angleX)))
val renamed = start.withParameterRenamed(angleX, " Eyes ")
assertEquals("Eyes", renamed.parameters.single().name)
assertSame(start, start.withParameterRenamed(angleX, " "), "a blank rename is a no-op")
assertSame(renamed, renamed.withParameterRenamed(angleX, "Eyes"), "an unchanged rename is a no-op")
}
/** Delete scrubs the parameters list, the tree leaf, and any link containing it. */
@Test
fun deleteRemovesFromParametersTreeAndLink() {
val tree = listOf(ParameterNode.Param(angleX), ParameterNode.Param(angleY))
val links = listOf(ParameterLink(angleX, angleY))
val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY)), links, tree))
session.deleteParameter(angleX)
val after = session.model.value
assertTrue(after.parameters.none { it.id == angleX }, "the axis is gone")
assertTrue(after.parameterTree.none { it is ParameterNode.Param && it.id == angleX }, "the leaf is gone")
assertTrue(after.parameterLinks.isEmpty(), "the link that contained it is gone")
session.undo()
assertTrue(session.model.value.parameters.any { it.id == angleX }, "undo restores the parameter")
assertEquals(1, session.model.value.parameterLinks.size, "undo restores the link")
}
/** Delete collapses a multi-axis grid to the deleted axis's default slice, re-projecting coordinates. */
@Test
fun deleteCollapsesGridToDefaultSlice() {
// default 0 on angleX -> keeps key index 1 (the value-0 key) of [-1, 0, 1].
val session = EditorSession(model(listOf(parameter(angleX, default = 0f), parameter(angleY)), drawables = listOf(keyedDrawable())))
session.deleteParameter(angleX)
val grid = session.model.value.drawables.single().geometryGrid!!
assertEquals(listOf(angleY), grid.axes.map { it.parameterId }, "only angleY remains")
assertEquals(2, grid.cells.size, "the 3x2 grid collapsed to the 2 cells of the kept slice")
// The surviving forms are the angleX-index-1 slice: xIndex*10 + yIndex = 10 and 11.
val byCoordinate = grid.cells.associate { it.coordinate.single() to it.form.positionDeltas.single() }
assertEquals(10f, byCoordinate[0], "cell (angleY key 0) kept the default-slice form")
assertEquals(11f, byCoordinate[1], "cell (angleY key 1) kept the default-slice form")
}
/** Deleting the sole axis of a grid leaves the entity unkeyed (null grid). */
@Test
fun deleteSoleAxisGridBecomesNull() {
val singleAxis =
keyedDrawable().copy(
geometryGrid =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f))),
listOf(
KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f))),
KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(1f))),
KeyformCell(intArrayOf(2), MeshDeltaForm(floatArrayOf(2f))),
),
),
)
val session = EditorSession(model(listOf(parameter(angleX)), drawables = listOf(singleAxis)))
session.deleteParameter(angleX)
assertNull(session.model.value.drawables.single().geometryGrid, "the last-axis grid becomes null")
}
/** Deleting a parameter not present in a grid leaves that grid's entity untouched by identity. */
@Test
fun deleteUnkeyedParamLeavesGridsUntouched() {
val drawable = keyedDrawable()
// angleZ exists as a parameter but is not an axis of the drawable's grid.
val angleZ = ParameterId("ParamAngleZ")
val start = model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ)), drawables = listOf(drawable))
val after = start.withParameterDeleted(angleZ)
assertSame(drawable.geometryGrid, after.drawables.single().geometryGrid, "an untouched grid keeps its instance")
}
/** Deleting an unknown parameter is a no-op (same instance, no undo step). */
@Test
fun deleteUnknownIsNoOp() {
val start = model(listOf(parameter(angleX)))
assertSame(start, start.withParameterDeleted(ParameterId("ParamNope")))
}
/** A single-axis channel track over angleX with one [ChannelValue.Scalar] per key of [-1, 0, 1]. */
private fun scalarTrack(vararg values: Float): KeyformGrid<ChannelValue> =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f))),
values.mapIndexed { keyIndex, value -> KeyformCell<ChannelValue>(intArrayOf(keyIndex), ChannelValue.Scalar(value)) },
)
/**
* Dropping a channel track whose only axis is the deleted parameter lifts the kept slice's value into
* the owner's static, so the neutral look survives the drop instead of snapping back to the static.
*/
@Test
fun deleteLiftsCollapsedOpacityTrackIntoStatic() {
val drawable =
keyedDrawable().copy(
geometryGrid = null,
opacity = 1f,
channelGrids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0.5f, 0.3f, 0.9f))),
)
// angleX's default is 0, whose key is index 1 - the neutral look renders opacity 0.3.
val start = model(listOf(parameter(angleX, default = 0f)), drawables = listOf(drawable))
val after = start.withParameterDeleted(angleX)
val scrubbed = after.drawables.single()
assertNull(scrubbed.channelGrids[FormChannel.OPACITY], "the sole-axis track is dropped")
assertEquals(0.3f, scrubbed.opacity, "the kept slice's value took over the static")
}
/** The same lift for a glue: the kept slice's intensity replaces the full-weld static. */
@Test
fun deleteLiftsGlueIntensityIntoStatic() {
val glue =
Glue(
meshA = DrawableId("a"),
meshB = DrawableId("b"),
pairs = emptyList(),
channelGrids = ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to scalarTrack(0.2f, 0.4f, 0.8f))),
)
val start = model(listOf(parameter(angleX, default = 0f))).copy(glues = listOf(glue))
val after = start.withParameterDeleted(angleX)
val scrubbed = after.glues.single()
assertNull(scrubbed.channelGrids[FormChannel.GLUE_INTENSITY], "the sole-axis track is dropped")
assertEquals(0.4f, scrubbed.intensity, "the kept slice's intensity took over the static")
}
/**
* A fractional part draw order cannot lift into the Int static slot, so it stays behind as a zero-axis
* constant track; an integral one lifts.
*/
@Test
fun deletePartDrawOrderLiftsIntegralKeepsFractionalAsConstant() {
val fractionalPart =
Part(
id = PartId("pFractional"),
name = "pFractional",
children = emptyList(),
groupMode = PartGroupMode.Grouped,
channelGrids = ChannelGrids(mapOf(FormChannel.DRAW_ORDER to scalarTrack(500f, 550.5f, 600f))),
)
val integralPart =
Part(
id = PartId("pIntegral"),
name = "pIntegral",
children = emptyList(),
groupMode = PartGroupMode.Grouped,
channelGrids = ChannelGrids(mapOf(FormChannel.DRAW_ORDER to scalarTrack(500f, 600f, 700f))),
)
val start =
model(listOf(parameter(angleX, default = 0f)))
.copy(parts = listOf(fractionalPart, integralPart))
val after = start.withParameterDeleted(angleX)
val fractional = after.parts.first { part -> part.id == PartId("pFractional") }
val constantTrack = fractional.channelGrids[FormChannel.DRAW_ORDER]!!
assertTrue(constantTrack.axes.isEmpty(), "the fractional value stays as a zero-axis constant track")
assertEquals(550.5f, (constantTrack.cells.single().form as ChannelValue.Scalar).value)
assertEquals(500, fractional.drawOrder, "the Int static keeps its value rather than rounding")
val integral = after.parts.first { part -> part.id == PartId("pIntegral") }
assertNull(integral.channelGrids[FormChannel.DRAW_ORDER], "the integral track is dropped")
assertEquals(600, integral.drawOrder, "the kept slice's value lifted into the Int static")
}
/**
* The render root's per-group copies of the part tracks are re-derived after the delete, so the
* evaluator (which samples renderRoot, not the parts list) cannot keep blending a ghost axis.
*/
@Test
fun deleteRederivesRenderRootPartTracks() {
val twoAxisTrack =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))),
buildList {
for (xIndex in 0..2) {
for (yIndex in 0..1) {
add(KeyformCell<ChannelValue>(intArrayOf(xIndex, yIndex), ChannelValue.Scalar(500f + xIndex * 10f + yIndex)))
}
}
},
)
val part =
Part(
id = PartId("p"),
name = "p",
children = emptyList(),
groupMode = PartGroupMode.Grouped,
channelGrids = ChannelGrids(mapOf(FormChannel.DRAW_ORDER to twoAxisTrack)),
)
val start =
model(listOf(parameter(angleX, default = 0f), parameter(angleY)))
.copy(parts = listOf(part), rootChildren = listOf(OrgChild.Part(PartId("p"))))
.withDerivedRenderRoot()
val staleAxes = start.renderRoot.children.filterIsInstance<RenderGroup>().single().channelGrids[FormChannel.DRAW_ORDER]!!.axes
assertEquals(listOf(angleX, angleY), staleAxes.map { axis -> axis.parameterId }, "precondition: the group carries both axes")
val after = start.withParameterDeleted(angleX)
val group = after.renderRoot.children.filterIsInstance<RenderGroup>().single()
val survivingAxes = group.channelGrids[FormChannel.DRAW_ORDER]!!.axes
assertEquals(listOf(angleY), survivingAxes.map { axis -> axis.parameterId }, "the render tree lost the deleted axis too")
}
/**
* A glue's intensity TRACK is scrubbed too, so a deleted parameter leaves no dangling axis behind.
* Glue was the one owner the original scrub walk missed entirely.
*/
@Test
fun deleteScrubsGlueIntensityTrack() {
val intensityTrack =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))),
buildList {
for (xIndex in 0..2) {
for (yIndex in 0..1) {
add(KeyformCell<ChannelValue>(intArrayOf(xIndex, yIndex), ChannelValue.Scalar(xIndex * 10f + yIndex)))
}
}
},
)
val glue =
Glue(
meshA = DrawableId("a"),
meshB = DrawableId("b"),
pairs = emptyList(),
channelGrids = ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to intensityTrack)),
)
val start = model(listOf(parameter(angleX), parameter(angleY))).copy(glues = listOf(glue))
val after = start.withParameterDeleted(angleX)
val collapsed = after.glues.single().channelGrids[FormChannel.GLUE_INTENSITY]!!
assertEquals(listOf(angleY), collapsed.axes.map { axis -> axis.parameterId }, "the deleted axis is gone")
// angleX's default is 0, whose nearest key is index 1 - so the surviving intensities are 10 and 11.
assertEquals(listOf(10f, 11f), collapsed.cells.map { cell -> (cell.form as ChannelValue.Scalar).value })
}
/** Moving keys onto another parameter retargets grid axes instead of collapsing them. */
@Test
fun deleteMoveKeysRetargetsGridOntoDestination() {
val session =
EditorSession(model(listOf(parameter(angleX), parameter(angleY)), drawables = listOf(keyedDrawable())))
session.deleteParameter(angleX, moveKeysTo = angleY)
val after = session.model.value
assertTrue(after.parameters.none { it.id == angleX }, "source parameter is gone")
assertTrue(after.parameters.any { it.id == angleY }, "destination parameter remains")
val grid = after.drawables.single().geometryGrid!!
assertEquals(listOf(angleY), grid.axes.map { it.parameterId }, "the source axis now keys the destination")
assertTrue(grid.axes.single().keys.contentEquals(floatArrayOf(-1f, 0f, 1f)), "key values are kept absolute")
assertEquals(3, grid.cells.size, "destination's prior axis collapsed; source's three keys remain")
session.undo()
assertTrue(session.model.value.parameters.any { it.id == angleX }, "undo restores the source parameter")
assertEquals(
listOf(angleX, angleY),
session.model.value.drawables.single().geometryGrid!!.axes.map { it.parameterId },
)
}
/** Discarding a blend-shape driver drops its binding; moving retargets it onto the destination. */
@Test
fun deleteScrubsOrMovesBlendShapeBindings() {
val binding =
BlendShapeBinding<MeshForm>(
parameterId = angleX,
keys = floatArrayOf(0f, 1f),
neutralIndex = 0,
forms = listOf(null, MeshForm(floatArrayOf(1f, 2f))),
)
val drawable = keyedDrawable().copy(geometryGrid = null, blendShapes = listOf(binding))
val start = model(listOf(parameter(angleX), parameter(angleY)), drawables = listOf(drawable))
val discarded = start.withParameterDeleted(angleX)
assertTrue(discarded.drawables.single().blendShapes.isEmpty(), "discard drops the binding")
val moved = start.withParameterDeleted(angleX, moveKeysTo = angleY)
val movedBinding = moved.drawables.single().blendShapes.single()
assertEquals(angleY, movedBinding.parameterId, "move retargets the binding onto the destination")
assertTrue(movedBinding.keys.contentEquals(floatArrayOf(0f, 1f)))
}
/** A missing or self moveKeysTo is a no-op (same instance). */
@Test
fun deleteMoveKeysInvalidDestinationIsNoOp() {
val start = model(listOf(parameter(angleX), parameter(angleY)), drawables = listOf(keyedDrawable()))
assertSame(start, start.withParameterDeleted(angleX, moveKeysTo = ParameterId("ParamNope")))
assertSame(start, start.withParameterDeleted(angleX, moveKeysTo = angleX))
}
}
@@ -0,0 +1,106 @@
package org.umamo.edit
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterGroupId
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.ParameterLink
import org.umamo.runtime.model.ParameterNode
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the parameter-group document edits: create mints a fresh expanded group at the top, delete
* unwraps (splicing children to the root, leaving parameters and links untouched), rename changes the
* label, a blank rename is a no-op, the id mint avoids collisions, and each undoes.
*/
class ParameterGroupEditsTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
/** An animatable parameter over -1..1. */
private fun parameter(id: ParameterId): Parameter = Parameter(id, id.raw, min = -1f, max = 1f, default = 0f)
/** A drawable-less model holding [parameters], [links], and an optional group [tree]. */
private fun model(
parameters: List<Parameter>,
links: List<ParameterLink> = emptyList(),
tree: List<ParameterNode> = emptyList(),
): PuppetModel =
PuppetModel(
parameters = parameters,
parts = emptyList(),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = emptyList(),
rootPartId = null,
parameterLinks = links,
parameterTree = tree,
)
/** A group node with the given children. */
private fun group(id: ParameterGroupId, children: List<ParameterNode>): ParameterNode.Group =
ParameterNode.Group(id, id.raw, initiallyOpen = true, children = children)
/** Create prepends a fresh expanded group and materializes the flat tree beneath it. */
@Test
fun createPrependsFreshExpandedGroupAtTop() {
val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY))))
val id = session.createParameterGroup("New Group")
val tree = session.model.value.parameterTree
val head = tree.first() as ParameterNode.Group
assertEquals(id, head.id)
assertEquals("New Group", head.name)
assertTrue(head.initiallyOpen)
assertTrue(head.children.isEmpty())
// The former flat parameters materialized as root leaves beneath the new group.
assertEquals(listOf(angleX, angleY), tree.filterIsInstance<ParameterNode.Param>().map { it.id })
session.undo()
assertTrue(session.model.value.parameterTree.isEmpty(), "undo restores the group-less tree")
}
/** The minted id skips ids already present. */
@Test
fun freshIdAvoidsCollision() {
val existing = model(emptyList(), tree = listOf(group(ParameterGroupId("ParamGroup"), emptyList()), group(ParameterGroupId("ParamGroup2"), emptyList())))
assertEquals(ParameterGroupId("ParamGroup3"), existing.freshParameterGroupId())
}
/** Delete unwraps: children splice to the root at the group's position; parameters and links untouched. */
@Test
fun deleteSplicesChildrenToRootAtPosition() {
val links = listOf(ParameterLink(angleX, angleY))
val tree =
listOf(
ParameterNode.Param(angleX),
group(ParameterGroupId("ParamGroup"), listOf(ParameterNode.Param(angleY))),
)
val startModel = model(listOf(parameter(angleX), parameter(angleY)), links, tree)
val session = EditorSession(startModel)
session.deleteParameterGroup(ParameterGroupId("ParamGroup"))
val newModel = session.model.value
assertEquals(listOf(angleX, angleY), newModel.parameterTree.filterIsInstance<ParameterNode.Param>().map { it.id })
assertTrue(newModel.parameterTree.none { it is ParameterNode.Group }, "the group node is gone")
assertSame(startModel.parameters, newModel.parameters, "the axis list is untouched")
assertSame(startModel.parameterLinks, newModel.parameterLinks, "the links are untouched")
session.undo()
assertTrue(session.model.value.parameterTree.any { it is ParameterNode.Group }, "undo restores the group")
}
/** Rename changes the name; a blank rename is a no-op. */
@Test
fun renameChangesNameAndBlankIsNoOp() {
val groupId = ParameterGroupId("ParamGroup")
val startModel = model(emptyList(), tree = listOf(group(groupId, emptyList())))
val renamed = startModel.withParameterGroupRenamed(groupId, " Eyes ")
assertEquals("Eyes", (renamed.parameterTree.single() as ParameterNode.Group).name)
assertSame(startModel, startModel.withParameterGroupRenamed(groupId, " "), "a blank rename is a no-op")
}
}
@@ -0,0 +1,135 @@
package org.umamo.edit
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Pins the keyform-authoring target: which parameter an insert would write a key on.
*
* It lives on the session rather than a panel's view state because it is SHARED - a keyform sheet in one
* area has to follow the parameter picked in a parameters panel in another - and it rides the undo stack
* like the object and mesh selections, so undoing back across a keyform edit restores the target that edit
* was made against.
*/
class ParameterSelectionTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
private fun parameter(id: ParameterId): Parameter = Parameter(id, id.raw, min = -1f, max = 1f, default = 0f)
private fun session(ids: List<ParameterId>): EditorSession =
EditorSession(
PuppetModel(
parameters = ids.map { id -> parameter(id) },
parts = emptyList(),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = emptyList(),
rootPartId = null,
),
)
/** Nothing is targeted until the user picks something - a fresh document keys nowhere. */
@Test
fun startsEmpty() {
assertTrue(session(listOf(angleX)).parameterSelection.value.isEmpty)
assertNull(session(listOf(angleX)).parameterSelection.value.active)
}
/** Picking a parameter targets it, and the pick is its own undo step. */
@Test
fun selectingIsItsOwnUndoStep() {
val editorSession = session(listOf(angleX, angleY))
editorSession.setParameterSelection(ParameterSelection.of(angleX))
assertEquals(angleX, editorSession.parameterSelection.value.active)
editorSession.setParameterSelection(ParameterSelection.of(angleY))
assertEquals(angleY, editorSession.parameterSelection.value.active)
editorSession.undo()
assertEquals(angleX, editorSession.parameterSelection.value.active, "undo restores the previous target")
editorSession.redo()
assertEquals(angleY, editorSession.parameterSelection.value.active)
}
/** Re-picking the same target records nothing, so repeated clicks do not pile up undo steps. */
@Test
fun reselectingTheSameTargetIsANoOp() {
val editorSession = session(listOf(angleX))
editorSession.setParameterSelection(ParameterSelection.of(angleX))
val stepsAfterFirst = editorSession.historyView.value.steps.size
editorSession.setParameterSelection(ParameterSelection.of(angleX))
assertEquals(stepsAfterFirst, editorSession.historyView.value.steps.size)
}
/** Toggling extends and contracts the set, keeping the active member inside it. */
@Test
fun togglingExtendsAndContracts() {
val both = ParameterSelection.of(angleX).toggled(angleY)
assertEquals(setOf(angleX, angleY), both.ids)
assertEquals(angleY, both.active, "the newly added member becomes active")
val backToOne = both.toggled(angleY)
assertEquals(setOf(angleX), backToOne.ids)
assertEquals(angleX, backToOne.active, "the active target stays inside the set")
}
/**
* Deleting a parameter drops it from the target, so an insert can never aim at an id the model no
* longer has. This is the one way the two could silently diverge - the target is session state, the
* parameter list is document state, and only the delete path touches both.
*/
@Test
fun deletingAParameterPrunesTheTarget() {
val editorSession = session(listOf(angleX, angleY))
editorSession.setParameterSelection(ParameterSelection(setOf(angleX, angleY), angleY))
editorSession.deleteParameter(angleY)
val target = editorSession.parameterSelection.value
assertFalse(angleY in target, "the deleted parameter is no longer targeted")
assertEquals(setOf(angleX), target.ids)
assertEquals(angleX, target.active, "the active target falls back to a surviving member")
}
/**
* The prune rides INSIDE the delete's history entry: redo (or a History jump to the entry) restores
* the pruned target, never the dangling id the panel recorded before the delete.
*/
@Test
fun redoOfADeleteRestoresThePrunedTarget() {
val editorSession = session(listOf(angleX, angleY))
editorSession.setParameterSelection(ParameterSelection(setOf(angleX, angleY), angleY))
editorSession.deleteParameter(angleY)
editorSession.undo()
assertTrue(editorSession.model.value.parameters.any { it.id == angleY }, "undo restores the parameter")
editorSession.redo()
val target = editorSession.parameterSelection.value
assertFalse(angleY in target, "redo restores the pruned target, not the dangling id")
assertEquals(angleX, target.active)
}
/** The unlink's narrowing rides its history entry the same way, so redo cannot restore the pad target. */
@Test
fun redoOfAnUnlinkRestoresTheNarrowedTarget() {
val editorSession = session(listOf(angleX, angleY))
editorSession.setParameterLink(angleX, angleY, true)
editorSession.setParameterSelection(ParameterSelection(setOf(angleX, angleY), angleX))
editorSession.setParameterLink(angleX, angleY, false)
assertEquals(setOf(angleX), editorSession.parameterSelection.value.ids, "the target narrows on unlink")
editorSession.undo()
editorSession.redo()
assertEquals(setOf(angleX), editorSession.parameterSelection.value.ids, "redo restores the narrowed target")
assertEquals(angleX, editorSession.parameterSelection.value.active)
}
}
@@ -0,0 +1,186 @@
package org.umamo.edit
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterGroupId
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.ParameterNode
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the pure parameter-tree move surgery: reorder within the root, move a parameter into / out of a
* group, reorder a group among root nodes, the atomic linked-pair move, materialize-on-empty, and the
* one-level and no-op refusals (which record no undo step).
*/
class ParameterTreeEditsTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
private val angleZ = ParameterId("ParamAngleZ")
private val breath = ParameterId("ParamBreath")
private val groupA = ParameterGroupId("ParamGroup")
private val groupB = ParameterGroupId("ParamGroup2")
/** An animatable parameter over -1..1. */
private fun parameter(id: ParameterId): Parameter = Parameter(id, id.raw, min = -1f, max = 1f, default = 0f)
/**
* A drawable-less model holding [parameters] and an optional group [tree].
*
* @param List parameters The parameters (the id-keyed axis list).
* @param List tree The group tree (empty = the flat fallback).
* @return PuppetModel The fixture model.
*/
private fun model(parameters: List<Parameter>, tree: List<ParameterNode> = emptyList()): PuppetModel =
PuppetModel(
parameters = parameters,
parts = emptyList(),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = emptyList(),
rootPartId = null,
parameterTree = tree,
)
/** The flat leaf-id sequence of a tree's root level (groups are not leaves). */
private fun rootLeafIds(tree: List<ParameterNode>): List<ParameterId> =
tree.filterIsInstance<ParameterNode.Param>().map { leaf -> leaf.id }
/** A group node with the given children. */
private fun group(id: ParameterGroupId, children: List<ParameterNode>): ParameterNode.Group =
ParameterNode.Group(id, id.raw, initiallyOpen = true, children = children)
/** Reordering within the root moves the leaf and leaves the others in place. */
@Test
fun reorderWithinRoot() {
val tree = listOf(ParameterNode.Param(angleX), ParameterNode.Param(angleY), ParameterNode.Param(angleZ))
val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ)), tree))
session.moveParameterRow(
ParameterMoveSubject.Leaves(listOf(angleX)),
newParentGroupId = null,
before = ParameterNodeRef.Leaf(angleZ),
)
assertEquals(listOf(angleY, angleX, angleZ), rootLeafIds(session.model.value.parameterTree))
session.undo()
assertEquals(listOf(angleX, angleY, angleZ), rootLeafIds(session.model.value.parameterTree))
}
/** Moving a root leaf into a group re-homes it as that group's child and removes it from the root. */
@Test
fun moveLeafIntoGroup() {
val tree = listOf(ParameterNode.Param(angleX), group(groupA, listOf(ParameterNode.Param(angleY))))
val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY)), tree))
session.moveParameterRow(ParameterMoveSubject.Leaves(listOf(angleX)), newParentGroupId = groupA, before = null)
val newTree = session.model.value.parameterTree
assertTrue(rootLeafIds(newTree).isEmpty(), "the leaf left the root")
val destination = newTree.filterIsInstance<ParameterNode.Group>().single()
assertEquals(listOf(angleY, angleX), destination.children.filterIsInstance<ParameterNode.Param>().map { it.id })
}
/** Moving a group child out to the root inserts it at the chosen root position. */
@Test
fun moveLeafOutToRoot() {
val tree = listOf(group(groupA, listOf(ParameterNode.Param(angleX), ParameterNode.Param(angleY))))
val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY)), tree))
session.moveParameterRow(
ParameterMoveSubject.Leaves(listOf(angleX)),
newParentGroupId = null,
before = ParameterNodeRef.Group(groupA),
)
val newTree = session.model.value.parameterTree
assertEquals(listOf(angleX), rootLeafIds(newTree), "the leaf is now a root sibling before the group")
val remaining = newTree.filterIsInstance<ParameterNode.Group>().single()
assertEquals(listOf(angleY), remaining.children.filterIsInstance<ParameterNode.Param>().map { it.id })
}
/** A group reorders among root nodes, carrying its children. */
@Test
fun reorderGroupAmongRootNodes() {
val tree =
listOf(
ParameterNode.Param(angleX),
group(groupA, listOf(ParameterNode.Param(angleY))),
ParameterNode.Param(angleZ),
)
val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ)), tree))
session.moveParameterRow(
ParameterMoveSubject.Group(groupA),
newParentGroupId = null,
before = ParameterNodeRef.Leaf(angleX),
)
val newTree = session.model.value.parameterTree
assertTrue(newTree.first() is ParameterNode.Group, "the group leads the root now")
assertEquals(groupA, (newTree.first() as ParameterNode.Group).id)
assertEquals(listOf(angleX, angleZ), rootLeafIds(newTree))
}
/** A linked pair moves as one contiguous run, keeping horizontal-then-vertical order. */
@Test
fun pairMoveKeepsLeavesAdjacent() {
val tree =
listOf(
ParameterNode.Param(angleX),
ParameterNode.Param(angleY),
ParameterNode.Param(angleZ),
ParameterNode.Param(breath),
)
val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ), parameter(breath)), tree))
// angleY (horizontal) + angleZ (vertical) are a linked pad; move them to the front.
session.moveParameterRow(
ParameterMoveSubject.Leaves(listOf(angleY, angleZ)),
newParentGroupId = null,
before = ParameterNodeRef.Leaf(angleX),
)
assertEquals(listOf(angleY, angleZ, angleX, breath), rootLeafIds(session.model.value.parameterTree))
}
/** A group-less model materializes a flat tree on the first real move; a no-op leaves the tree empty. */
@Test
fun materializeOnEmptyTreeThenMove() {
val base = model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ)))
val moved =
base.withParameterRowMoved(
ParameterMoveSubject.Leaves(listOf(angleX)),
newParentGroupId = null,
before = ParameterNodeRef.Leaf(angleZ),
)
assertEquals(listOf(angleY, angleX, angleZ), rootLeafIds(moved.parameterTree), "the flat tree materialized and the move applied")
// A move that changes nothing must not materialize a tree - the model stays group-less.
val noOp =
base.withParameterRowMoved(
ParameterMoveSubject.Leaves(listOf(angleX)),
newParentGroupId = null,
before = ParameterNodeRef.Leaf(angleY),
)
assertSame(base, noOp)
assertTrue(noOp.parameterTree.isEmpty())
}
/** A group cannot be dropped inside another group (one level only) - same instance, no step. */
@Test
fun refusesGroupUnderGroup() {
val tree = listOf(group(groupA, emptyList()), group(groupB, emptyList()))
val session = EditorSession(model(emptyList(), tree))
session.moveParameterRow(ParameterMoveSubject.Group(groupA), newParentGroupId = groupB, before = null)
assertFalse(session.canUndo.value, "a refused move records no undo step")
assertEquals(tree, session.model.value.parameterTree)
}
/** A move that changes nothing returns the same instance. */
@Test
fun noOpReturnsSameInstance() {
val tree = listOf(ParameterNode.Param(angleX), ParameterNode.Param(angleY))
val base = model(listOf(parameter(angleX), parameter(angleY)), tree)
val result =
base.withParameterRowMoved(
ParameterMoveSubject.Leaves(listOf(angleX)),
newParentGroupId = null,
before = ParameterNodeRef.Leaf(angleY),
)
assertSame(base, result)
}
}
@@ -0,0 +1,146 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyableTarget
import org.umamo.runtime.model.KeyformOwner
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Pins the unkeyed-edit buffer: a value typed into a keyed property but not yet keyed.
*
* The behaviour it encodes is Blender's, and the discarding is the point rather than a shortcoming - a
* pending value was chosen FOR a pose, so carrying it to a different one would apply an edit somewhere it
* was never meant. What must never happen is a pending edit surviving into the undo history, which would
* bury the real edits under a step per keystroke.
*/
class PendingChannelEditTest {
private val angleX = ParameterId("ParamAngleX")
private val drawableId = DrawableId("d")
private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY)
private fun session(): EditorSession =
EditorSession(
PuppetModel(
parameters = listOf(Parameter(angleX, angleX.raw, min = -30f, max = 30f, default = 0f)),
parts = emptyList(),
deformers = emptyList(),
drawables =
listOf(
Drawable(
id = drawableId,
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
opacity = 0.25f,
),
),
rootChildren = emptyList(),
rootPartId = null,
),
)
/** A pending edit is held for reading but records no history step and no model change. */
@Test
fun aPendingEditIsTransient() {
val editorSession = session()
val stepsBefore = editorSession.historyView.value.steps.size
val modelBefore = editorSession.model.value
editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f))
assertEquals(ChannelValue.Scalar(0.75f), editorSession.pendingChannelEdits.value[target])
assertEquals(stepsBefore, editorSession.historyView.value.steps.size, "no undo step is recorded")
assertTrue(modelBefore === editorSession.model.value, "the document is untouched")
assertTrue(!editorSession.dirty.value, "an unkeyed edit does not dirty the document")
}
/** Moving the pose discards it - the value was chosen for the pose being left. */
@Test
fun aPoseMoveDiscardsIt() {
val editorSession = session()
editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f))
editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f))
assertTrue(editorSession.pendingChannelEdits.value.isEmpty(), "the pending edit did not survive the scrub")
}
/** A history jump lands on a pose the pending value was never chosen for, so it goes too. */
@Test
fun anUndoDiscardsIt() {
val editorSession = session()
editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f))
editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f))
editorSession.undo()
assertTrue(editorSession.pendingChannelEdits.value.isEmpty())
}
/** Capturing consumes it: the captured key holds the typed value, and nothing stays pending. */
@Test
fun capturingConsumesIt() {
val editorSession = session()
val parameter = editorSession.model.value.parameters.single()
editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f))
val pending = editorSession.pendingChannelEdits.value.getValue(target)
editorSession.captureChannelKey(target, parameter, pending)
editorSession.clearPendingChannelEdits()
assertTrue(editorSession.pendingChannelEdits.value.isEmpty())
assertTrue(editorSession.model.value.isChannelKeyedOn(target, angleX), "the channel is now keyed")
assertEquals(
ChannelValue.Scalar(0.75f),
editorSession.model.value.channelValueAt(target, editorSession.pose.value),
"the key holds the value that was typed, not the value that was stored",
)
}
/** Several properties can be pending at once, each keyed independently. */
@Test
fun severalTargetsCanBePendingAtOnce() {
val editorSession = session()
val multiplyTarget = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.MULTIPLY_COLOR)
editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f))
editorSession.setPendingChannelEdit(multiplyTarget, ChannelValue.Color(org.umamo.runtime.model.ColorRgb(1f, 0f, 0f)))
assertEquals(2, editorSession.pendingChannelEdits.value.size)
}
/**
* Capturing one target consumes only ITS pending edit: the pose did not move, so every other target's
* typed value is still the value its user chose and must survive for its own insert.
*/
@Test
fun capturingOneTargetKeepsOthersPending() {
val editorSession = session()
val parameter = editorSession.model.value.parameters.single()
val multiplyTarget = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.MULTIPLY_COLOR)
val multiplyValue = ChannelValue.Color(org.umamo.runtime.model.ColorRgb(1f, 0f, 0f))
editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f))
editorSession.setPendingChannelEdit(multiplyTarget, multiplyValue)
val pending = editorSession.pendingChannelEdits.value.getValue(target)
editorSession.captureChannelKey(target, parameter, pending)
editorSession.clearPendingChannelEdit(target)
assertEquals(
mapOf<KeyableTarget, ChannelValue>(multiplyTarget to multiplyValue),
editorSession.pendingChannelEdits.value,
"the uncaptured target's typed value survives",
)
}
}
@@ -0,0 +1,496 @@
package org.umamo.edit
import org.umamo.runtime.model.AlphaBlendMode
import org.umamo.runtime.model.AtlasPage
import org.umamo.runtime.model.AtlasPlacement
import org.umamo.runtime.model.AtlasTile
import org.umamo.runtime.model.AtlasTileId
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.ColorRgb
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartComposite
import org.umamo.runtime.model.PartGroupMode
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetAtlas
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.RenderGroup
import org.umamo.runtime.model.RenderNode
import org.umamo.runtime.model.RuntimeTarget
import org.umamo.runtime.model.multiplyColor
import org.umamo.runtime.model.opacity
import org.umamo.runtime.model.screenColor
import org.umamo.runtime.model.withDerivedRenderRoot
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the scalar property edits behind the Properties panel: each PuppetModelEdits builder round-trips
* its field and returns the SAME instance on a no-op (unchanged value or a missing id), the deformer
* builders guard on kind (base angle only on Rotation, quad transform only on Warp), the part group-mode
* builder carries a whole Isolated composite, and a session setter commits exactly one undo step (or
* nothing when it is a no-op).
*/
class PropertyScalarEditsTest {
private val drawableId = DrawableId("d")
private val rotationId = DeformerId("rot")
private val warpId = DeformerId("warp")
private val partId = PartId("p")
private val drawable =
Drawable(
id = drawableId,
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
)
private val rotation =
Deformer.Rotation(id = rotationId, name = "rot", parent = null, partId = null, baseAngle = 0f, geometryGrid = null)
private val warp =
Deformer.Warp(
id = warpId,
name = "warp",
parent = null,
partId = null,
rows = 2,
columns = 2,
isQuadTransform = false,
geometryGrid = null,
)
private val part = Part(partId, "p", children = emptyList())
private fun model(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = listOf(part),
deformers = listOf(rotation, warp),
drawables = listOf(drawable),
rootChildren = emptyList(),
rootPartId = null,
canvasWidth = 100f,
canvasHeight = 200f,
worldOriginX = 50f,
worldOriginZ = 100f,
)
@Test
fun drawableScalarBuildersRoundTripAndNoOp() {
val base = model()
assertEquals(BlendMode.Multiply, base.withDrawableBlendMode(drawableId, BlendMode.Multiply).drawables.first().blendMode)
assertEquals(AlphaBlendMode.Atop, base.withDrawableAlphaBlendMode(drawableId, AlphaBlendMode.Atop).drawables.first().alphaBlendMode)
assertTrue(base.withDrawableCulling(drawableId, true).drawables.first().culling)
assertTrue(base.withDrawableInvertMask(drawableId, true).drawables.first().invertMask)
// Unchanged value and missing id are both no-ops (same instance).
assertSame(base, base.withDrawableBlendMode(drawableId, BlendMode.Normal))
assertSame(base, base.withDrawableCulling(drawableId, false))
assertSame(base, base.withDrawableInvertMask(DrawableId("missing"), true))
}
@Test
fun deformerBaseAngleOnlyAffectsRotation() {
val base = model()
val edited = base.withDeformerBaseAngle(rotationId, 45f)
assertEquals(45f, (edited.deformers.first { it.id == rotationId } as Deformer.Rotation).baseAngle)
// A warp has no base angle, and an unchanged angle is a no-op.
assertSame(base, base.withDeformerBaseAngle(warpId, 45f))
assertSame(base, base.withDeformerBaseAngle(rotationId, 0f))
}
@Test
fun deformerQuadTransformOnlyAffectsWarp() {
val base = model()
val edited = base.withDeformerQuadTransform(warpId, true)
assertTrue((edited.deformers.first { it.id == warpId } as Deformer.Warp).isQuadTransform)
// A rotation has no lattice, and an unchanged flag is a no-op.
assertSame(base, base.withDeformerQuadTransform(rotationId, true))
assertSame(base, base.withDeformerQuadTransform(warpId, false))
}
@Test
fun partScalarBuildersRoundTripAndNoOp() {
val base = model()
assertTrue(base.withPartSketch(partId, true).parts.first().isSketch)
assertEquals(700, base.withPartDrawOrder(partId, 700).parts.first().drawOrder)
assertSame(base, base.withPartSketch(partId, false))
assertSame(base, base.withPartDrawOrder(partId, 500))
}
@Test
fun partCompositeIsStoredAndSurvivesModeRoundTrip() {
val base = model()
val custom = PartComposite(opacity = 0.5f)
// The composite is stored on the part independent of the mode.
val withComposite = base.withPartComposite(partId, custom)
assertEquals(custom, withComposite.parts.first().composite)
// Only applied while Isolated: activeComposite is null until the mode is Isolated.
assertEquals(null, withComposite.parts.first().activeComposite)
val isolated = withComposite.withPartGroupMode(partId, PartGroupMode.Isolated)
assertEquals(custom, isolated.parts.first().activeComposite)
// Leaving and re-entering Isolated does NOT reset the composite (the whole point).
val roundTripped =
isolated
.withPartGroupMode(partId, PartGroupMode.PassThrough)
.withPartGroupMode(partId, PartGroupMode.Isolated)
assertEquals(custom, roundTripped.parts.first().composite)
assertEquals(custom, roundTripped.parts.first().activeComposite)
// No-op composite / mode edits return the same instance.
assertSame(withComposite, withComposite.withPartComposite(partId, custom))
assertSame(base, base.withPartGroupMode(partId, PartGroupMode.PassThrough))
}
/**
* The part in the org tree (so deriveRenderRoot emits a RenderGroup for it), Isolated by default so
* its composite resolves onto the group, with a freshly derived renderRoot.
*/
private fun modelWithPartInTree(groupMode: PartGroupMode = PartGroupMode.Isolated): PuppetModel =
model()
.copy(parts = listOf(part.copy(groupMode = groupMode)), rootChildren = listOf(OrgChild.Part(partId)))
.withDerivedRenderRoot()
/** The derived render group owning [id], or null when the part is not a render-tree boundary. */
private fun groupFor(model: PuppetModel, id: PartId): RenderGroup? {
fun search(node: RenderNode): RenderGroup? {
if (node !is RenderGroup) {
return null
}
if (node.partId == id) {
return node
}
for (child in node.children) {
search(child)?.let { return it }
}
return null
}
return search(model.renderRoot)
}
@Test
fun partCompositeEditsReDeriveTheRenderRoot() {
// The renderer reads composite/draw-order/group structure from renderRoot, not from parts, so a
// composite property edit that does not re-derive renderRoot never reaches the viewport (the bug
// this pins): resolvedComposite bakes the composite into RenderGroup.composite at derive time.
val base = modelWithPartInTree()
assertEquals(PartComposite(), groupFor(base, partId)?.composite)
val edited = base.withPartComposite(partId, PartComposite(opacity = 0.5f))
assertEquals(0.5f, groupFor(edited, partId)?.composite?.opacity)
// A part draw-order edit updates the group's sort key in the render tree.
assertEquals(700, groupFor(base.withPartDrawOrder(partId, 700), partId)?.drawOrder)
// PassThrough removes the group boundary entirely (its children hoist into the enclosing group).
assertEquals(null, groupFor(base.withPartGroupMode(partId, PartGroupMode.PassThrough), partId))
}
/**
* The 5.3 per-art-mesh tint is now a STATIC channel value, so the builders write one field instead of
* rewriting every keyform cell.
*
* That is the point of the split: the old builder flattened any authored per-keyform color animation
* and, by replacing the grid, tripped the renderer's identity check into re-uploading geometry for a
* color change. Neither is possible now - the color never touches the geometry grid.
*/
@Test
fun drawableColorBuildersWriteTheStaticAndNoOp() {
val base = model().copy(drawables = listOf(drawable))
val red = ColorRgb(1f, 0f, 0f)
val tinted = base.withDrawableMultiplyColor(drawableId, red)
assertEquals(red, tinted.drawables.first().multiplyColor, "the static multiply color is set")
assertSame(
base.drawables.first().geometryGrid,
tinted.drawables.first().geometryGrid,
"a color edit leaves the geometry grid untouched by identity, so no re-upload is triggered",
)
// Already-set and missing-id are no-ops (same instance).
assertSame(tinted, tinted.withDrawableMultiplyColor(drawableId, red))
assertSame(base, base.withDrawableMultiplyColor(drawableId, ColorRgb.MultiplyIdentity))
assertSame(base, base.withDrawableScreenColor(DrawableId("missing"), ColorRgb.ScreenIdentity))
}
@Test
fun canvasAndOriginBuildersRoundTripAndNoOp() {
val base = model()
assertEquals(300f, base.withCanvasSize(300f, 400f).canvasWidth)
assertEquals(400f, base.withCanvasSize(300f, 400f).canvasHeight)
assertEquals(7f, base.withWorldOrigin(7f, 8f).worldOriginX)
assertSame(base, base.withCanvasSize(100f, 200f))
assertSame(base, base.withWorldOrigin(50f, 100f))
}
@Test
fun sessionEditIsOneUndoStepThatDirtiesAndReverses() {
val session = EditorSession(model())
assertFalse(session.canUndo.value)
session.setDrawableCulling(drawableId, true)
assertTrue(session.canUndo.value)
assertTrue(session.dirty.value)
assertTrue(session.model.value.drawables.first().culling)
session.undo()
assertFalse(session.canUndo.value)
assertFalse(session.model.value.drawables.first().culling)
}
@Test
fun sessionNoOpEditRecordsNothing() {
val session = EditorSession(model())
// The drawable is already Normal, so this edit changes nothing.
session.setDrawableBlendMode(drawableId, BlendMode.Normal)
assertFalse(session.canUndo.value)
assertFalse(session.dirty.value)
}
@Test
fun sessionGroupModeAndCanvasEditsCommit() {
val session = EditorSession(model())
session.setPartGroupMode(partId, PartGroupMode.Grouped)
assertEquals(PartGroupMode.Grouped, session.model.value.parts.first().groupMode)
session.setCanvasSize(640f, 480f)
assertEquals(640f, session.model.value.canvasWidth)
// Two distinct edits, so two undo steps back to the original.
session.undo()
session.undo()
assertEquals(PartGroupMode.PassThrough, session.model.value.parts.first().groupMode)
assertEquals(100f, session.model.value.canvasWidth)
}
@Test
fun sessionRuntimeTargetEditCommitsUndoesAndNoOps() {
val session = EditorSession(model())
session.setRuntimeTarget(RuntimeTarget.Cubism50)
assertEquals(RuntimeTarget.Cubism50, session.model.value.runtimeTarget)
assertTrue(session.dirty.value, "a target change is document content, so it dirties")
assertEquals("change.document.runtimeTarget", DocumentChange.SetRuntimeTarget(RuntimeTarget.Cubism50).labelKey)
session.undo()
assertEquals(RuntimeTarget.NoTarget, session.model.value.runtimeTarget)
assertFalse(session.dirty.value, "undo restores the saved model instance")
// The target is already NoTarget, so this edit changes nothing.
session.setRuntimeTarget(RuntimeTarget.NoTarget)
assertFalse(session.canUndo.value)
assertFalse(session.dirty.value)
}
/** The display mode is document content: one undo step, dirties, and a no-op change records nothing. */
@Test
fun sessionSetSourceLayerDisplayCommitsOneStep() {
val session = EditorSession(model())
assertFalse(session.model.value.rendersFromSourceLayers, "documents display from the atlas by default")
session.setSourceLayerDisplay(true)
assertTrue(session.model.value.rendersFromSourceLayers)
assertTrue(session.dirty.value, "a display-mode change is document content, so it dirties")
assertEquals("change.document.sourceLayerDisplay", DocumentChange.SetSourceLayerDisplay(true).labelKey)
session.undo()
assertFalse(session.model.value.rendersFromSourceLayers)
assertFalse(session.dirty.value, "undo restores the saved model instance")
// Already displaying from the atlas, so this edit changes nothing.
session.setSourceLayerDisplay(false)
assertFalse(session.canUndo.value)
assertFalse(session.dirty.value)
}
/**
* Packing art at a new spot is one undo step, and the coordinates over it follow.
*
* The mesh's uvs address the PAGE, so moving the art without moving them would silently re-point the
* mesh at whatever now sits at the old spot. Asserting the round trip - move, then move back - is
* what pins that: the coordinates must land where they started.
*/
@Test
fun sessionSetAtlasPlacementCommitsOneStepAndCarriesTheCoordinates() {
val tileId = AtlasTileId("tile0")
val original = AtlasPlacement(0, 0f, 0f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f)
val moved = AtlasPlacement(0, 32f, 16f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f)
val meshed =
drawable.copy(
mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 1f), floatArrayOf(0f, 0f, 0.25f, 0.5f), intArrayOf(0, 0, 0)),
atlasTileId = tileId,
)
val packed =
model().copy(
drawables = listOf(meshed),
atlas =
PuppetAtlas(
pages = listOf(AtlasPage(64, 64)),
tiles = listOf(AtlasTile(tileId, "Art", 16, 16, original)),
),
)
val session = EditorSession(packed)
val storedBefore = session.model.value.drawables.single().mesh!!.uvs.copyOf()
session.setAtlasPlacement(tileId, moved)
assertEquals(moved, session.model.value.atlas.tiles.single().placement, "the tile moved")
assertTrue(session.dirty.value, "a pack is document content, so it dirties")
assertEquals("change.document.atlasPlacement", DocumentChange.SetAtlasPlacement(listOf(tileId)).labelKey)
assertFalse(
session.model.value.drawables.single().mesh!!.uvs.contentEquals(storedBefore),
"the stored coordinates followed the art rather than staying put",
)
session.setAtlasPlacement(tileId, original)
assertContentEquals(
storedBefore,
session.model.value.drawables.single().mesh!!.uvs,
"moving the art back restores the coordinates it started with",
)
session.undo()
session.undo()
assertEquals(original, session.model.value.atlas.tiles.single().placement)
assertFalse(session.dirty.value, "undo restores the saved model instance")
// The tile is already there, so this edit changes nothing.
session.setAtlasPlacement(tileId, original)
assertFalse(session.canUndo.value)
// An unknown tile is refused rather than half-applied.
session.setAtlasPlacement(AtlasTileId("gone"), moved)
assertFalse(session.canUndo.value)
}
@Test
fun sessionSetPartCompositeCommitsOneStep() {
val session = EditorSession(model())
val custom = PartComposite(opacity = 0.25f)
session.setPartComposite(partId, custom)
assertEquals(custom, session.model.value.parts.first().composite)
session.undo()
assertEquals(PartComposite(), session.model.value.parts.first().composite)
}
/** The drawable's new scalar statics round-trip, and refuse a no-op the same way the others do. */
@Test
fun drawableScalarChannelBuildersWriteTheStaticAndNoOp() {
val base = model()
val faded = base.withDrawableOpacity(drawableId, 0.25f)
assertEquals(0.25f, faded.drawables.first().opacity)
val reordered = base.withDrawableDrawOrder(drawableId, 720f)
assertEquals(720f, reordered.drawables.first().drawOrder)
assertSame(base, base.withDrawableOpacity(drawableId, 1f), "the default opacity is already 1")
assertSame(base, base.withDrawableDrawOrder(DrawableId("missing"), 720f))
assertSame(
base.drawables.first().geometryGrid,
faded.drawables.first().geometryGrid,
"a scalar-static edit leaves the geometry grid untouched by identity, so no re-upload is triggered",
)
}
/**
* A drawable's draw order does NOT re-derive the render root, unlike a part's.
*
* A part's draw order is baked into the derived group tree; a drawable's is resolved per pose at render
* time as its channel's static, so re-deriving would be work with no output.
*/
@Test
fun drawableDrawOrderLeavesTheRenderRootAlone() {
val base = model()
val reordered = base.withDrawableDrawOrder(drawableId, 720f)
assertSame(base.renderRoot, reordered.renderRoot)
}
/** The deformer render statics round-trip on BOTH subtypes and refuse a no-op. */
@Test
fun deformerRenderStaticBuildersCoverBothSubtypes() {
val base = model()
for (id in listOf(rotationId, warpId)) {
val faded = base.withDeformerOpacity(id, 0.5f)
assertEquals(0.5f, faded.deformerNamed(id).opacity, "opacity on $id")
val tinted = base.withDeformerMultiplyColor(id, ColorRgb(0.5f, 0.5f, 0.5f))
assertEquals(ColorRgb(0.5f, 0.5f, 0.5f), tinted.deformerNamed(id).multiplyColor, "multiply on $id")
val screened = base.withDeformerScreenColor(id, ColorRgb(0.25f, 0f, 0f))
assertEquals(ColorRgb(0.25f, 0f, 0f), screened.deformerNamed(id).screenColor, "screen on $id")
assertSame(base, base.withDeformerOpacity(id, 1f), "the default opacity is already 1")
}
assertSame(base, base.withDeformerOpacity(DeformerId("missing"), 0.5f))
}
/** The flip flags exist only on a rotation deformer; a warp refuses them. */
@Test
fun deformerFlipsOnlyAffectRotation() {
val base = model()
val flipped = base.withDeformerFlipX(rotationId, true)
assertEquals(true, (flipped.deformers.first { it.id == rotationId } as Deformer.Rotation).flipX)
val flippedY = base.withDeformerFlipY(rotationId, true)
assertEquals(true, (flippedY.deformers.first { it.id == rotationId } as Deformer.Rotation).flipY)
assertSame(base, base.withDeformerFlipX(warpId, true), "a warp has no reflection")
assertSame(base, base.withDeformerFlipY(warpId, true), "a warp has no reflection")
assertSame(base, base.withDeformerFlipX(rotationId, false), "already false")
}
/** Each new session setter is one undo step that reverses cleanly. */
@Test
fun newSessionSettersAreOneUndoStepEach() {
val session = EditorSession(model())
session.setDrawableOpacity(drawableId, 0.25f)
session.setDeformerOpacity(rotationId, 0.5f)
session.setDeformerFlipX(rotationId, true)
assertEquals(0.25f, session.model.value.drawables.first().opacity)
assertEquals(0.5f, session.model.value.deformerNamed(rotationId).opacity)
session.undo()
session.undo()
session.undo()
assertEquals(1f, session.model.value.drawables.first().opacity)
assertEquals(1f, session.model.value.deformerNamed(rotationId).opacity)
}
/** A no-op setter records nothing, so an unchanged value cannot pad the history. */
@Test
fun newSessionNoOpSettersRecordNothing() {
val session = EditorSession(model())
session.setDrawableOpacity(drawableId, 1f)
session.setDeformerFlipX(warpId, true)
assertEquals(false, session.canUndo.value)
}
/** The deformer with [id], for reading a static through the sealed-type accessors. */
private fun PuppetModel.deformerNamed(id: DeformerId): Deformer = deformers.first { candidate -> candidate.id == id }
}
@@ -0,0 +1,120 @@
package org.umamo.edit
import kotlin.math.sqrt
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
// Tests for the proportional-editing math: the falloff curves and the per-mesh weight map.
class ProportionalEditingTest {
private val allFalloffs = ProportionalFalloff.entries
@Test
fun everyFalloffIsFullAtZeroAndZeroAtRadiusEdge() {
for (falloff in allFalloffs) {
assertEquals(1f, proportionalWeight(falloff, 0f), "$falloff at distance 0")
assertEquals(0f, proportionalWeight(falloff, 1f), "$falloff at the radius edge")
assertEquals(0f, proportionalWeight(falloff, 1.5f), "$falloff beyond the radius")
assertEquals(1f, proportionalWeight(falloff, -0.5f), "$falloff clamps negative distances to full weight")
}
}
@Test
fun falloffCurvesMatchTheirFormulasAtMidpoint() {
// fade = 0.5 at the midpoint; each curve's closed form evaluated by hand.
assertEquals(0.5f, proportionalWeight(ProportionalFalloff.Smooth, 0.5f), 1e-6f, "smoothstep is 0.5 at its midpoint")
assertEquals(sqrt(0.75f), proportionalWeight(ProportionalFalloff.Sphere, 0.5f), 1e-6f, "sphere is sqrt(1 - 0.25)")
assertEquals(sqrt(0.5f), proportionalWeight(ProportionalFalloff.Root, 0.5f), 1e-6f, "root is sqrt(fade)")
assertEquals(0.25f, proportionalWeight(ProportionalFalloff.Sharp, 0.5f), 1e-6f, "sharp is fade squared")
assertEquals(0.5f, proportionalWeight(ProportionalFalloff.Linear, 0.5f), 1e-6f, "linear is fade")
assertEquals(1f, proportionalWeight(ProportionalFalloff.Constant, 0.5f), "constant is full inside the radius")
}
@Test
fun everyFalloffIsMonotonicallyNonIncreasing() {
val sampleCount = 20
for (falloff in allFalloffs) {
var previousWeight = proportionalWeight(falloff, 0f)
for (sampleIndex in 1..sampleCount) {
val weight = proportionalWeight(falloff, sampleIndex / sampleCount.toFloat())
assertTrue(weight <= previousWeight + 1e-6f, "$falloff must not increase with distance (sample $sampleIndex)")
previousWeight = weight
}
}
}
// A horizontal strip of vertices spaced 10 units apart: (0,0), (10,0), (20,0), (30,0), (40,0).
private val stripPositions = floatArrayOf(0f, 0f, 10f, 0f, 20f, 0f, 30f, 0f, 40f, 0f)
@Test
fun weightsExcludeCoveredVerticesAndThoseOutsideTheRadius() {
val weights = proportionalWeights(stripPositions, setOf(0), radiusWorld = 25f, falloff = ProportionalFalloff.Linear)
assertFalse(0 in weights, "the covered vertex moves at full strength through its pivot group, not the weight map")
assertEquals(setOf(1, 2), weights.keys, "only the vertices strictly inside the radius take a weight")
}
@Test
fun weightsMeasureDistanceToTheNearestCoveredVertex() {
// Covering both ends, the middle vertex is 20 from either end; the second and fourth are 10 from
// their nearer end - the nearest covered vertex, not the first one iterated.
val weights = proportionalWeights(stripPositions, setOf(0, 4), radiusWorld = 25f, falloff = ProportionalFalloff.Linear)
assertEquals(1f - 10f / 25f, weights.getValue(1), 1e-6f, "vertex 1 is 10 from covered vertex 0")
assertEquals(1f - 20f / 25f, weights.getValue(2), 1e-6f, "vertex 2 is 20 from either covered end")
assertEquals(1f - 10f / 25f, weights.getValue(3), 1e-6f, "vertex 3 is 10 from covered vertex 4")
}
@Test
fun weightsAreEmptyWithNoCoverageOrNoRadius() {
assertTrue(proportionalWeights(stripPositions, emptySet(), 25f, ProportionalFalloff.Smooth).isEmpty())
assertTrue(proportionalWeights(stripPositions, setOf(0), 0f, ProportionalFalloff.Smooth).isEmpty())
}
@Test
fun influencesCarryTheNearestCoveredVertexIdentity() {
// The identity is the Individual Origins ownership key: vertex 1 belongs with covered end 0,
// vertex 3 with covered end 4 (each measured to its NEARER end).
val influences = proportionalInfluences(stripPositions, setOf(0, 4), radiusWorld = 25f, falloff = ProportionalFalloff.Linear)
assertEquals(0, influences.getValue(1).nearestCoveredIndex, "vertex 1's nearest covered vertex is 0")
assertEquals(4, influences.getValue(3).nearestCoveredIndex, "vertex 3's nearest covered vertex is 4")
assertEquals(1f - 10f / 25f, influences.getValue(1).weight, 1e-6f, "the weight rides along unchanged")
}
@Test
fun connectedOnlyMeasuresAlongEdgesAndSkipsUnreachableIslands() {
// A bent sheet: 0=(0,0), 1=(0,4), 2=(3,0), 3=(3,4); triangles (0,1,2) and (1,2,3). Vertex 3 is
// 5 from vertex 0 straight-line but 7 along edges (0-1-3 or 0-2-3; there is no 0-3 edge).
val positions = floatArrayOf(0f, 0f, 0f, 4f, 3f, 0f, 3f, 4f)
val indices = intArrayOf(0, 1, 2, 1, 2, 3)
val straight = proportionalInfluences(positions, setOf(0), radiusWorld = 6f, falloff = ProportionalFalloff.Linear)
val connected = proportionalInfluencesConnected(positions, setOf(0), radiusWorld = 6f, falloff = ProportionalFalloff.Linear, triangleIndices = indices)
assertTrue(3 in straight, "straight-line influence reaches vertex 3 (distance 5, radius 6)")
assertFalse(3 in connected, "along edges vertex 3 is 7 away - outside the radius")
assertEquals(1f - 4f / 6f, connected.getValue(1).weight, 1e-6f, "a direct edge matches the straight-line distance")
assertEquals(0, connected.getValue(1).nearestCoveredIndex, "the geodesic source rides along")
// A nearby-but-unconnected island takes no weight at ANY radius (the feature's point).
val twoIslands = floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 5f, 0f, 7f, 0f, 5f, 2f)
val islandIndices = intArrayOf(0, 1, 2, 3, 4, 5)
val islandConnected =
proportionalInfluencesConnected(twoIslands, setOf(0), radiusWorld = 100f, falloff = ProportionalFalloff.Constant, triangleIndices = islandIndices)
assertEquals(setOf(1, 2), islandConnected.keys, "influence never leaps to the unconnected island")
}
@Test
fun influencesPartitionByTheOwningPivotGroup() {
// Two single-vertex "islands" at the strip's ends: each influenced vertex must follow the group
// owning its nearest covered vertex, so the halos turn about their own island pivots.
val influences = proportionalInfluences(stripPositions, setOf(0, 4), radiusWorld = 25f, falloff = ProportionalFalloff.Linear)
val groups =
listOf(
TransformPivotGroup(setOf(0), pivotX = 0f, pivotY = 0f),
TransformPivotGroup(setOf(4), pivotX = 40f, pivotY = 0f),
)
val partitions = TransformPivots.partitionInfluencesByGroup(influences, groups)
assertEquals(setOf(1, 2), partitions[0].keys, "vertices nearest end 0 follow the first island (2 ties to 0, iterated first)")
assertEquals(setOf(3), partitions[1].keys, "vertex 3 follows the second island")
assertEquals(influences.getValue(3).weight, partitions[1].getValue(3), "weights carry into the partitions")
}
}
@@ -0,0 +1,134 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the relation edits the Properties panel's pickers write through: each binds a flat cross-link field
* (no tree surgery), returns the SAME instance on a no-op (unchanged value or a missing id), works on both
* deformer subtypes, and commits exactly one undo step through its session op.
*/
class RelationEditsTest {
private val drawableId = DrawableId("d")
private val otherDrawableId = DrawableId("d2")
private val rotationId = DeformerId("rot")
private val warpId = DeformerId("warp")
private val partId = PartId("p")
private fun drawable(id: DrawableId): Drawable =
Drawable(
id = id,
name = id.raw,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
)
private val rotation =
Deformer.Rotation(id = rotationId, name = "rot", parent = null, partId = null, baseAngle = 0f, geometryGrid = null)
private val warp =
Deformer.Warp(
id = warpId,
name = "warp",
parent = null,
partId = null,
rows = 2,
columns = 2,
isQuadTransform = false,
geometryGrid = null,
)
private fun model(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = listOf(Part(partId, "p", children = emptyList())),
deformers = listOf(rotation, warp),
drawables = listOf(drawable(drawableId), drawable(otherDrawableId)),
rootChildren = emptyList(),
rootPartId = null,
)
@Test
fun drawableParentDeformerRoundTripsAndNoOps() {
val base = model()
val bound = base.withDrawableParentDeformer(drawableId, warpId)
assertEquals(warpId, bound.drawables.first { it.id == drawableId }.parentDeformerId)
// Unbinding is a real edit back to null.
assertNull(bound.withDrawableParentDeformer(drawableId, null).drawables.first { it.id == drawableId }.parentDeformerId)
// Unchanged value and missing id are both no-ops (same instance).
assertSame(base, base.withDrawableParentDeformer(drawableId, null))
assertSame(bound, bound.withDrawableParentDeformer(drawableId, warpId))
assertSame(base, base.withDrawableParentDeformer(DrawableId("missing"), warpId))
}
@Test
fun drawableMaskedByRoundTripsAndNoOps() {
val base = model()
val masks = listOf(otherDrawableId)
val masked = base.withDrawableMaskedBy(drawableId, masks)
assertEquals(masks, masked.drawables.first { it.id == drawableId }.maskedBy)
// Clearing back to empty is a real edit.
assertTrue(masked.withDrawableMaskedBy(drawableId, emptyList()).drawables.first { it.id == drawableId }.maskedBy.isEmpty())
assertSame(base, base.withDrawableMaskedBy(drawableId, emptyList()))
assertSame(masked, masked.withDrawableMaskedBy(drawableId, masks))
assertSame(base, base.withDrawableMaskedBy(DrawableId("missing"), masks))
}
@Test
fun deformerPartRoundTripsOnBothSubtypes() {
val base = model()
// The copy is per-subtype, so both a rotation and a warp must rebind.
val boundRotation = base.withDeformerPart(rotationId, partId)
assertEquals(partId, boundRotation.deformers.first { it.id == rotationId }.partId)
assertTrue(boundRotation.deformers.first { it.id == rotationId } is Deformer.Rotation, "subtype is preserved")
val boundWarp = base.withDeformerPart(warpId, partId)
assertEquals(partId, boundWarp.deformers.first { it.id == warpId }.partId)
assertTrue(boundWarp.deformers.first { it.id == warpId } is Deformer.Warp, "subtype is preserved")
assertSame(base, base.withDeformerPart(rotationId, null))
assertSame(boundWarp, boundWarp.withDeformerPart(warpId, partId))
assertSame(base, base.withDeformerPart(DeformerId("missing"), partId))
}
@Test
fun sessionRelationEditsAreOneUndoStepEach() {
val session = EditorSession(model())
session.setDrawableParentDeformer(drawableId, warpId)
assertEquals(warpId, session.model.value.drawables.first { it.id == drawableId }.parentDeformerId)
session.setDrawableMaskedBy(drawableId, listOf(otherDrawableId))
assertEquals(listOf(otherDrawableId), session.model.value.drawables.first { it.id == drawableId }.maskedBy)
session.setDeformerPart(rotationId, partId)
assertEquals(partId, session.model.value.deformers.first { it.id == rotationId }.partId)
// Three distinct edits, so three undo steps back to the original.
session.undo()
session.undo()
session.undo()
assertNull(session.model.value.drawables.first { it.id == drawableId }.parentDeformerId)
assertTrue(session.model.value.drawables.first { it.id == drawableId }.maskedBy.isEmpty())
assertNull(session.model.value.deformers.first { it.id == rotationId }.partId)
}
}
@@ -0,0 +1,184 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Verifies the pure [SelectionOps] gesture transforms and the [Selection] invariant that the active
* target is always a member of the selection, or null when empty.
*/
class SelectionOpsTest {
private val partA = SelectionTarget.Part(PartId("a"))
private val drawableB = SelectionTarget.Drawable(DrawableId("b"))
private val drawableC = SelectionTarget.Drawable(DrawableId("c"))
/**
* A fresh selection is empty with no active target.
*/
@Test
fun emptySelectionHasNoActive() {
val selection = Selection()
assertTrue(selection.isEmpty)
assertEquals(0, selection.size)
assertNull(selection.active)
}
/**
* replace drops any prior selection and makes the new target the sole, active member.
*/
@Test
fun replaceSelectsOnlyTheTarget() {
val first = SelectionOps.replace(partA)
val second = SelectionOps.replace(drawableB)
assertEquals(setOf(drawableB), second.targets)
assertEquals(drawableB, second.active)
assertFalse(partA in second)
// The original is untouched (immutability).
assertEquals(setOf(partA), first.targets)
}
/**
* toggle adds an absent target (making it active) and removes a present one.
*/
@Test
fun toggleAddsThenRemoves() {
val added = SelectionOps.toggle(Selection(), partA)
assertEquals(setOf(partA), added.targets)
assertEquals(partA, added.active)
val removed = SelectionOps.toggle(added, partA)
assertTrue(removed.isEmpty)
assertNull(removed.active)
}
/**
* Removing the active target by toggle falls the active back to a remaining member, never dangling.
*/
@Test
fun toggleRemovingActiveFallsBackToRemaining() {
val twoSelected = SelectionOps.add(SelectionOps.replace(partA), drawableB)
assertEquals(drawableB, twoSelected.active)
val afterRemove = SelectionOps.toggle(twoSelected, drawableB)
assertEquals(setOf(partA), afterRemove.targets)
assertEquals(partA, afterRemove.active, "active must remain a member of the selection")
}
/**
* add extends the selection without removing anything and promotes the added target to active.
*/
@Test
fun addExtendsAndActivates() {
val selection = SelectionOps.add(SelectionOps.add(SelectionOps.replace(partA), drawableB), drawableC)
assertEquals(setOf(partA, drawableB, drawableC), selection.targets)
assertEquals(drawableC, selection.active)
assertEquals(3, selection.size)
}
/**
* Adding an already-present target keeps the set unchanged but re-promotes it to active.
*/
@Test
fun addExistingPromotesToActive() {
val start = SelectionOps.add(SelectionOps.replace(partA), drawableB)
val reAdded = SelectionOps.add(start, partA)
assertEquals(setOf(partA, drawableB), reAdded.targets)
assertEquals(partA, reAdded.active)
}
/**
* clear returns an empty selection regardless of input.
*/
@Test
fun clearEmptiesSelection() {
assertTrue(SelectionOps.clear().isEmpty)
}
/**
* contains reflects membership for the operator-in form used by panels and the highlight bridge.
*/
@Test
fun containsReflectsMembership() {
val selection = SelectionOps.add(SelectionOps.replace(partA), drawableB)
assertTrue(partA in selection)
assertTrue(drawableB in selection)
assertFalse(drawableC in selection)
}
// A small model for the object Select All / Invert domain: one selectable part, one selectable deformer,
// one selectable drawable, and one LOCKED drawable that must be excluded.
private fun model(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = listOf(Part(PartId("a"), "A", children = emptyList())),
deformers =
listOf(
Deformer.Warp(DeformerId("w"), "W", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null),
),
drawables =
listOf(
Drawable(DrawableId("b"), "B", parentDeformerId = null, blendMode = BlendMode.Normal, maskedBy = emptyList(), mesh = null, geometryGrid = null),
Drawable(
DrawableId("c"),
"C",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
isSelectable = false,
),
),
rootChildren = emptyList(),
rootPartId = null,
)
/** selectAll gathers every selectable entity (a locked one is excluded), with the active a member. */
@Test
fun selectAllGathersSelectableEntities() {
val all = SelectionOps.selectAll(Selection(), model())
assertEquals(
setOf<SelectionTarget>(
SelectionTarget.Part(PartId("a")),
SelectionTarget.Deformer(DeformerId("w")),
SelectionTarget.Drawable(DrawableId("b")),
),
all.targets,
"the locked drawable c is excluded",
)
assertTrue(all.active in all.targets, "active is a member of the selection")
}
/** selectAll keeps the current active target when it stays selected. */
@Test
fun selectAllKeepsExistingActive() {
val all = SelectionOps.selectAll(SelectionOps.replace(SelectionTarget.Part(PartId("a"))), model())
assertEquals(SelectionTarget.Part(PartId("a")), all.active)
}
/** invert complements within the selectable domain and drops the now-deselected active target. */
@Test
fun invertComplementsSelectableDomainAndDropsActive() {
val inverted = SelectionOps.invert(SelectionOps.replace(SelectionTarget.Part(PartId("a"))), model())
assertEquals(
setOf<SelectionTarget>(SelectionTarget.Deformer(DeformerId("w")), SelectionTarget.Drawable(DrawableId("b"))),
inverted.targets,
)
assertNull(inverted.active, "the previously active (now deselected) target drops")
}
}
@@ -0,0 +1,170 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.withDerivedRenderRoot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Pins how a session opens on the state a document was saved with (docs/format/UMA.md § 7.4): it is where the
* history STARTS - never an undo step, never a dirty mark - it is fitted to the model first, and what the session
* gathers for the next save is what it was opened with.
*/
class SessionViewStateTest {
/**
* A drawable with or without a mesh.
*
* @param String id The drawable id.
* @param Boolean meshed Whether it carries a one-triangle mesh.
* @return Drawable The drawable.
*/
private fun drawable(id: String, meshed: Boolean): Drawable =
Drawable(
id = DrawableId(id),
name = id,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = if (meshed) DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), FloatArray(6), intArrayOf(0, 1, 2)) else null,
geometryGrid = null,
)
/**
* A model of one part, the given drawables at the root, and one parameter.
*
* @param List drawables The model's drawables.
* @return PuppetModel The model.
*/
private fun model(drawables: List<Drawable>): PuppetModel =
PuppetModel(
parameters = listOf(Parameter(ParameterId("ParamAngleX"), "Angle X", -30f, 30f, 0f)),
parts = listOf(Part(PartId("face"), "Face", children = emptyList())),
deformers = emptyList(),
drawables = drawables,
rootChildren = listOf(OrgChild.Part(PartId("face"))) + drawables.map { drawable -> OrgChild.Drawable(drawable.id) },
rootPartId = null,
).withDerivedRenderRoot()
private val meshedModel = model(listOf(drawable("a", meshed = true), drawable("b", meshed = true)))
/** A restored selection, parameter target, and tool state are the session's opening state, not steps on top of it. */
@Test
fun aSavedStateIsWhereTheHistoryStarts() {
val saved =
SessionViewState(
selection = Selection(setOf(SelectionTarget.Drawable(DrawableId("a")), SelectionTarget.Part(PartId("face"))), SelectionTarget.Drawable(DrawableId("a"))),
parameterSelection = ParameterSelection(setOf(ParameterId("ParamAngleX")), ParameterId("ParamAngleX")),
cursor2d = Cursor2d(12f, -8f),
uvCursor = UvCursor(0.25f, 0.75f),
pivotMode = TransformPivotMode.Cursor,
proportionalEnabled = true,
proportionalSettings = ProportionalEditState(ProportionalFalloff.Sharp, 64f, connectedOnly = true),
)
val session = EditorSession(meshedModel, initialViewState = saved)
assertEquals(saved.selection, session.selection.value)
assertEquals(saved.parameterSelection, session.parameterSelection.value)
assertEquals(Cursor2d(12f, -8f), session.cursor2d.value)
assertEquals(UvCursor(0.25f, 0.75f), session.uvCursor.value)
assertEquals(TransformPivotMode.Cursor, session.pivotMode.value)
assertEquals(ProportionalEditState(ProportionalFalloff.Sharp, 64f, connectedOnly = true), session.proportionalEdit.value)
assertFalse(session.canUndo.value, "nothing restored is an undo step")
assertFalse(session.dirty.value, "and nothing restored is a change to the document")
assertNull(session.notice.value, "and nothing restored posts a notice")
assertEquals(saved, session.viewState(), "what the session gathers is what it opened with")
}
/** Proportional editing saved OFF keeps the configuration a toggle brings back. */
@Test
fun aDisabledProportionalConfigurationComesBackOnToggle() {
val saved = SessionViewState(proportionalSettings = ProportionalEditState(ProportionalFalloff.Root, 48f))
val session = EditorSession(meshedModel, initialViewState = saved)
assertNull(session.proportionalEdit.value)
session.toggleProportionalEdit()
assertEquals(ProportionalEditState(ProportionalFalloff.Root, 48f), session.proportionalEdit.value)
}
/** A saved id the model no longer has is dropped, and the active falls to a target that survived. */
@Test
fun referencesTheModelLacksAreDropped() {
val saved =
SessionViewState(
selection = Selection(setOf(SelectionTarget.Drawable(DrawableId("a")), SelectionTarget.Drawable(DrawableId("gone"))), SelectionTarget.Drawable(DrawableId("gone"))),
parameterSelection = ParameterSelection(setOf(ParameterId("ParamGone")), ParameterId("ParamGone")),
)
val session = EditorSession(meshedModel, initialViewState = saved)
assertEquals(Selection(setOf(SelectionTarget.Drawable(DrawableId("a"))), SelectionTarget.Drawable(DrawableId("a"))), session.selection.value)
assertTrue(session.parameterSelection.value.isEmpty)
}
/** A saved Edit mode opens the session in Edit over the restored selection, with the saved select mode. */
@Test
fun aSavedEditModeOpensOverTheRestoredSelection() {
val saved =
SessionViewState(
selection = Selection(setOf(SelectionTarget.Drawable(DrawableId("b"))), SelectionTarget.Drawable(DrawableId("b"))),
mode = EditorMode.Edit,
selectMode = MeshSelectMode.Face,
)
val session = EditorSession(meshedModel, initialViewState = saved)
assertEquals(EditorMode.Edit, session.mode.value)
assertEquals(listOf(DrawableId("b")), session.meshSelection.value.drawableIds)
assertEquals(DrawableId("b"), session.meshSelection.value.activeDrawableId)
assertEquals(MeshSelectMode.Face, session.meshSelection.value.selectMode)
assertFalse(session.canUndo.value, "opening in Edit is not a mode-change step")
session.setMode(EditorMode.Object)
assertTrue(session.canUndo.value, "leaving it is an ordinary step")
session.undo()
assertEquals(EditorMode.Edit, session.mode.value, "and undo returns to the mode the document opened in")
}
/** A saved Edit mode the model cannot satisfy opens in Object, the refusal setMode makes. */
@Test
fun anEditModeWithNothingEditableOpensInObject() {
val session = EditorSession(model(listOf(drawable("flat", meshed = false))), initialViewState = SessionViewState(mode = EditorMode.Edit))
assertEquals(EditorMode.Object, session.mode.value)
assertTrue(session.meshSelection.value.drawableIds.isEmpty())
}
/** The grid follows the application unless the document brought its own, and only a document-owned grid is gathered. */
@Test
fun aDocumentOwnedGridHoldsAgainstTheApplicationDefault() {
val plain = EditorSession(meshedModel)
assertTrue(plain.gridFollowsApplication)
assertNull(plain.viewState().gridConfig, "a grid that merely mirrors the setting is not the document's to save")
val owned = EditorSession(meshedModel, initialViewState = SessionViewState(gridConfig = GridConfig(50f, 4)))
assertFalse(owned.gridFollowsApplication)
assertEquals(GridConfig(50f, 4), owned.gridConfig.value)
assertEquals(GridConfig(50f, 4), owned.viewState().gridConfig)
}
/** A plain open is untouched: no saved state means the defaults the session always had. */
@Test
fun aPlainOpenKeepsTheDefaults() {
val session = EditorSession(meshedModel)
assertEquals(SessionViewState(proportionalSettings = DEFAULT_PROPORTIONAL_EDIT_STATE), session.viewState())
}
}
@@ -0,0 +1,139 @@
package org.umamo.edit
import kotlin.math.PI
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Pins the transform gestures' rows on the operation settings strip: they carry the gesture's numbers
* in each space's convention (world y up as Z, page y down with the angle's sense flipped), read back
* to the same parameters, the proportional rows appear only when the gesture could take weights and
* read back as a state, and the slide's one row carries its factor.
*/
class TransformAdjustTest {
private fun parameters(deltaX: Float = 0f, deltaY: Float = 0f, factorX: Float = 1f, factorY: Float = 1f, rotation: Float = 0f): TransformGestureParameters =
TransformGestureParameters(deltaX, deltaY, factorX, factorY, rotation)
private fun List<OperatorParameter>.float(key: String): Float = assertNotNull(firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.FloatParameter, key).value
private fun assertClose(expected: Float, actual: Float, message: String) {
assertTrue(abs(expected - actual) < 1e-4f, "$message: expected $expected, got $actual")
}
@Test
fun grabRowsReadTheVerticalAxisPerSpace() {
val gesture = parameters(deltaX = 12f, deltaY = 5f)
val worldRows = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, proportional = null)
assertEquals(listOf(TransformParameterKeys.MOVE_X, TransformParameterKeys.MOVE_Z), worldRows.map { row -> row.key }, "world space names the vertical axis Z")
assertEquals(5f, worldRows.float(TransformParameterKeys.MOVE_Z), "world y is shown as-is (up)")
val pageRows = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.UvDisplay, proportional = null)
assertEquals(listOf(TransformParameterKeys.MOVE_X, TransformParameterKeys.MOVE_Y), pageRows.map { row -> row.key }, "the page names it Y")
assertEquals(-5f, pageRows.float(TransformParameterKeys.MOVE_Y), "page y reads down")
for (space in TransformRowSpace.entries) {
val rows = transformParameters(MeshOperatorKind.Grab, gesture, space, proportional = null)
val back = transformGestureParametersOf(MeshOperatorKind.Grab, space, rows)
assertEquals(12f, back.deltaX, "$space round-trips x")
assertEquals(5f, back.deltaY, "$space round-trips y")
assertEquals(1f, back.factorX)
assertEquals(0f, back.rotationRadians)
}
}
@Test
fun rotateRowsFlipTheirSenseWithThePage() {
val gesture = parameters(rotation = (PI / 2).toFloat())
val worldRows = transformParameters(MeshOperatorKind.Rotate, gesture, TransformRowSpace.World, proportional = null)
assertClose(90f, worldRows.float(TransformParameterKeys.ANGLE), "world degrees keep the gesture's sense")
val pageRows = transformParameters(MeshOperatorKind.Rotate, gesture, TransformRowSpace.UvDisplay, proportional = null)
assertClose(-90f, pageRows.float(TransformParameterKeys.ANGLE), "page degrees flip with the y axis")
for (space in TransformRowSpace.entries) {
val rows = transformParameters(MeshOperatorKind.Rotate, gesture, space, proportional = null)
assertClose((PI / 2).toFloat(), transformGestureParametersOf(MeshOperatorKind.Rotate, space, rows).rotationRadians, "$space round-trips the angle")
}
}
@Test
fun scaleRowsNameTheVerticalAxisPerSpaceAndRoundTrip() {
val gesture = parameters(factorX = 2f, factorY = 0.5f)
val worldRows = transformParameters(MeshOperatorKind.Scale, gesture, TransformRowSpace.World, proportional = null)
assertEquals(listOf(TransformParameterKeys.SCALE_X, TransformParameterKeys.SCALE_Z), worldRows.map { row -> row.key })
val pageRows = transformParameters(MeshOperatorKind.Scale, gesture, TransformRowSpace.UvDisplay, proportional = null)
assertEquals(listOf(TransformParameterKeys.SCALE_X, TransformParameterKeys.SCALE_Y), pageRows.map { row -> row.key })
for (space in TransformRowSpace.entries) {
val back = transformGestureParametersOf(MeshOperatorKind.Scale, space, transformParameters(MeshOperatorKind.Scale, gesture, space, proportional = null))
assertEquals(2f, back.factorX, "$space round-trips x")
assertEquals(0.5f, back.factorY, "$space round-trips y")
}
assertTrue(transformParameters(MeshOperatorKind.VertexSlide, gesture, TransformRowSpace.World, proportional = null).isEmpty(), "a slide has rows of its own")
assertEquals(0.25f, slideParameters(0.25f).float(TransformParameterKeys.SLIDE_FACTOR))
}
@Test
fun proportionalRowsFollowTheGestureAndReadBackAsAState() {
val gesture = parameters(deltaX = 1f)
val without = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, proportional = null)
assertNull(proportionalRowsOf(without), "no proportional rows registered, none read back")
val rows = ProportionalRows.of(ProportionalEditState(ProportionalFalloff.Sharp, 40f, connectedOnly = true), radius = 40f)
val with = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, rows)
assertEquals(
listOf(TransformParameterKeys.MOVE_X, TransformParameterKeys.MOVE_Z, TransformParameterKeys.PROPORTIONAL, TransformParameterKeys.FALLOFF, TransformParameterKeys.PROPORTIONAL_SIZE, TransformParameterKeys.CONNECTED_ONLY),
with.map { row -> row.key },
)
val read = assertNotNull(proportionalRowsOf(with))
assertEquals(ProportionalEditState(ProportionalFalloff.Sharp, 40f, connectedOnly = true), read.asState(), "the rows read back as the state")
val off = ProportionalRows.of(state = null, radius = 200f)
val offRead = assertNotNull(proportionalRowsOf(transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, off)))
assertNull(offRead.asState(), "an off flag is no state")
assertEquals(ProportionalFalloff.Smooth, offRead.falloff, "the defaults stand in while off")
assertEquals(200f, offRead.radius, "the radius the gesture would have used is shown")
val switchedOff = with.withParameter(TransformParameterKeys.PROPORTIONAL, OperatorParameter.BooleanParameter(TransformParameterKeys.PROPORTIONAL, TransformParameterKeys.PROPORTIONAL, false))
assertNull(assertNotNull(proportionalRowsOf(switchedOff)).asState(), "unticking the flag turns the halo off")
}
/** The halos re-derive on the capture from the rows: a wider radius pulls the bystander in, an off flag drops it. */
@Test
fun rederivingTheHalosFollowsTheRows() {
// Two vertices 10 apart, the first covered: at radius 5 the second is outside, at 20 it is inside.
val capture =
assertNotNull(
buildModalTransformCapture(
sources = listOf(ModalCaptureSource(org.umamo.runtime.model.DrawableId("a"), floatArrayOf(0f, 0f, 10f, 0f), intArrayOf(0, 1, 1), setOf(0))),
pivotMode = TransformPivotMode.MedianPoint,
individualOriginScope = IndividualOriginScope.ConnectivityIsland,
operatorKind = MeshOperatorKind.Grab,
activeAnchor = null,
cursorAnchor = null,
),
)
val entry = capture.entries.single()
val gesture = parameters(deltaX = 1f)
assertNull(rederiveProportionalHalos(capture, transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, proportional = null)), "no rows, no re-derivation")
val narrow = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, ProportionalRows(enabled = true, ProportionalFalloff.Linear, radius = 5f, connectedOnly = false))
assertNotNull(rederiveProportionalHalos(capture, narrow))
assertEquals(setOf(0), entry.movedIndices, "outside the radius nothing joins")
val wide = narrow.withParameter(TransformParameterKeys.PROPORTIONAL_SIZE, OperatorParameter.FloatParameter(TransformParameterKeys.PROPORTIONAL_SIZE, TransformParameterKeys.PROPORTIONAL_SIZE, 20f, 1f, 100f))
assertNotNull(rederiveProportionalHalos(capture, wide))
assertEquals(setOf(0, 1), entry.movedIndices, "inside the radius the bystander joins")
assertClose(0.5f, assertNotNull(entry.influence[1]).weight, "linear falloff at half the radius")
val off = wide.withParameter(TransformParameterKeys.PROPORTIONAL, OperatorParameter.BooleanParameter(TransformParameterKeys.PROPORTIONAL, TransformParameterKeys.PROPORTIONAL, false))
assertNull(assertNotNull(rederiveProportionalHalos(capture, off)).asState())
assertEquals(setOf(0), entry.movedIndices, "off clears the halo")
}
}
@@ -0,0 +1,91 @@
package org.umamo.edit
import org.umamo.runtime.model.DrawableId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Pins the history label every whole-gesture transform reports, across all three domains and every
* [MeshOperatorKind].
*
* Two things are being protected. First, the domain has to be readable at a glance in the history panel -
* an object transform, an Edit-mode mesh transform, and a UV transform must never share a label, which is
* why the keys sit in three separate namespaces rather than being distinguished only by the operator.
* Second, each key must have a matching arm in the history panel's resource lookup: an unmapped key does
* not fail anywhere, it silently renders as the generic "Edit" label, so the exhaustive table below is what
* makes a forgotten string visible.
*/
class TransformChangeLabelTest {
private val drawableIds = listOf(DrawableId("a"))
private val vertexIndices = mapOf(DrawableId("a") to listOf(0, 1))
/** Edit mode names all four of its operators, Vertex Slide included. */
@Test
fun meshTransformLabelsPerOperator() {
assertEquals("change.mesh.move", MeshChange.TransformVertices(vertexIndices, MeshOperatorKind.Grab).labelKey)
assertEquals("change.mesh.scale", MeshChange.TransformVertices(vertexIndices, MeshOperatorKind.Scale).labelKey)
assertEquals("change.mesh.rotate", MeshChange.TransformVertices(vertexIndices, MeshOperatorKind.Rotate).labelKey)
assertEquals("change.mesh.slide", MeshChange.TransformVertices(vertexIndices, MeshOperatorKind.VertexSlide).labelKey)
}
/** Object mode has no Vertex Slide of its own, so a slide reads as a plain move rather than an unmapped key. */
@Test
fun objectTransformLabelsPerOperator() {
assertEquals("change.object.move", MeshChange.TransformDrawables(drawableIds, MeshOperatorKind.Grab).labelKey)
assertEquals("change.object.scale", MeshChange.TransformDrawables(drawableIds, MeshOperatorKind.Scale).labelKey)
assertEquals("change.object.rotate", MeshChange.TransformDrawables(drawableIds, MeshOperatorKind.Rotate).labelKey)
assertEquals("change.object.move", MeshChange.TransformDrawables(drawableIds, MeshOperatorKind.VertexSlide).labelKey)
}
/** The UV editor's slide is unimplemented (see TODO § UV Editor); until it lands it degrades to the move label. */
@Test
fun uvTransformLabelsPerOperator() {
assertEquals("change.uv.move", MeshChange.TransformUvs(vertexIndices, MeshOperatorKind.Grab).labelKey)
assertEquals("change.uv.scale", MeshChange.TransformUvs(vertexIndices, MeshOperatorKind.Scale).labelKey)
assertEquals("change.uv.rotate", MeshChange.TransformUvs(vertexIndices, MeshOperatorKind.Rotate).labelKey)
assertEquals("change.uv.move", MeshChange.TransformUvs(vertexIndices, MeshOperatorKind.VertexSlide).labelKey)
}
/**
* No two domains share a key for the same operator. This is the requirement the labels exist for: a
* glance at the history panel has to say whether a step was an object, mesh, or UV operation, and three
* domains reusing one key would read identically no matter how the strings were worded.
*/
@Test
fun theThreeDomainsNeverShareALabelKey() {
for (kind in MeshOperatorKind.entries) {
val keys =
setOf(
MeshChange.TransformVertices(vertexIndices, kind).labelKey,
MeshChange.TransformDrawables(drawableIds, kind).labelKey,
MeshChange.TransformUvs(vertexIndices, kind).labelKey,
)
assertEquals(3, keys.size, "$kind produced a shared label key across domains: $keys")
}
}
/** Mirror keeps its own key in the UV namespace - it is not a G / S / R gesture. */
@Test
fun mirrorKeepsItsOwnUvKey() {
assertEquals("change.uv.mirror", MeshChange.MirrorUvs(drawableIds, mirrorU = true).labelKey)
assertEquals("change.uv.mirror", MeshChange.MirrorUvs(drawableIds, mirrorU = false).labelKey)
}
/** Viewport geometry mirrors keep mesh / object keys (not Scale). */
@Test
fun viewportMirrorKeepsOwnKeys() {
assertEquals("change.mesh.mirror", MeshChange.MirrorVertices(vertexIndices, mirrorHorizontal = true).labelKey)
assertEquals("change.object.mirror", MeshChange.MirrorDrawables(drawableIds, mirrorHorizontal = false).labelKey)
}
/** Every transform label is undoable - a gesture the user cannot step back over would be a trap. */
@Test
fun everyTransformIsUndoable() {
for (kind in MeshOperatorKind.entries) {
assertTrue(MeshChange.TransformVertices(vertexIndices, kind).undoability == Undoability.Undoable, "$kind vertices")
assertTrue(MeshChange.TransformDrawables(drawableIds, kind).undoability == Undoability.Undoable, "$kind drawables")
assertTrue(MeshChange.TransformUvs(vertexIndices, kind).undoability == Undoability.Undoable, "$kind uvs")
}
}
}
@@ -0,0 +1,327 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Verifies the modal-transform infrastructure: the axis-locked scale, the pivot-group builders
* (shared anchor vs per-island Individual Origins), and the session's axis-constraint / pivot / cursor
* / pie latches (toggle semantics, the Rotate exclusion, and the clear-on-latch discipline).
*/
class TransformStateTest {
/** scaleVerticesAxis scales each axis independently about the pivot. */
@Test
fun scaleVerticesAxisScalesPerAxis() {
val positions = floatArrayOf(2f, 3f, 4f, 5f)
val scaled = MeshTransforms.scaleVerticesAxis(positions, setOf(0, 1), factorX = 2f, factorY = 1f, pivotX = 1f, pivotY = 1f)
assertEquals(listOf(3f, 3f, 7f, 5f), scaled.toList(), "x doubles about the pivot, y is untouched")
assertEquals(listOf(2f, 3f, 4f, 5f), positions.toList(), "the input array is never mutated")
}
/** sharedGroup wraps every covered vertex about one anchor; islandGroups split by connectivity. */
@Test
fun pivotGroupBuilders() {
val shared = TransformPivots.sharedGroup(setOf(0, 1, 2), pivotX = 5f, pivotY = 6f)
assertEquals(1, shared.size)
assertEquals(setOf(0, 1, 2), shared.single().vertexIndices)
assertEquals(5f, shared.single().pivotX)
// Two disconnected triangles: vertices 0-2 at x=0..2, vertices 3-5 at x=10..12 (y = 0).
val positions = floatArrayOf(0f, 0f, 2f, 0f, 1f, 2f, 10f, 0f, 12f, 0f, 11f, 2f)
val triangles = intArrayOf(0, 1, 2, 3, 4, 5)
val islands = TransformPivots.islandGroups(positions, setOf(0, 1, 2, 3, 4, 5), triangles)
assertEquals(2, islands.size, "two components make two islands")
val leftIsland = islands.first { group -> 0 in group.vertexIndices }
assertEquals(setOf(0, 1, 2), leftIsland.vertexIndices)
assertEquals(1f, leftIsland.pivotX, 1e-4f, "each island pivots about its own centroid")
}
private fun meshedSession(): EditorSession {
val mesh = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), FloatArray(6), intArrayOf(0, 1, 2))
val drawable =
Drawable(
id = DrawableId("d"),
name = "d",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = mesh,
geometryGrid = null,
)
val model =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = emptyList(),
drawables = listOf(drawable),
rootChildren = emptyList(),
rootPartId = null,
)
return EditorSession(model)
}
/** The axis constraint toggles only while a Grab / Scale is live, never for Rotate, and clears with the operator. */
@Test
fun axisConstraintTogglesOnlyDuringGrabOrScale() {
val session = meshedSession()
val target = SelectionTarget.Drawable(DrawableId("d"))
session.setSelection(Selection(setOf(target), target))
// Idle: nothing to lock.
session.toggleAxisConstraint(TransformAxisConstraint.AxisX)
assertNull(session.axisConstraint.value, "no constraint arms while idle")
session.beginObjectOperator(MeshOperatorKind.Grab, "area-test")
session.toggleAxisConstraint(TransformAxisConstraint.AxisX)
assertEquals(TransformAxisConstraint.AxisX, session.axisConstraint.value)
session.toggleAxisConstraint(TransformAxisConstraint.AxisZ)
assertEquals(TransformAxisConstraint.AxisZ, session.axisConstraint.value, "the other axis switches the lock")
session.toggleAxisConstraint(TransformAxisConstraint.AxisZ)
assertNull(session.axisConstraint.value, "the same axis releases the lock")
session.toggleAxisConstraint(TransformAxisConstraint.AxisX)
session.clearObjectOperator()
assertNull(session.axisConstraint.value, "clearing the operator clears the lock")
// Rotate has no 2D axis to lock.
session.beginObjectOperator(MeshOperatorKind.Rotate, "area-test")
session.toggleAxisConstraint(TransformAxisConstraint.AxisX)
assertNull(session.axisConstraint.value, "Rotate refuses the lock")
}
/** The cursor, pivot mode, and pie latches hold their values; undo clears the transient pie latch. */
@Test
fun cursorPivotAndPieState() {
val session = meshedSession()
assertNull(session.cursor2d.value, "no cursor before placement")
session.setCursor2d(12f, 34f)
assertEquals(Cursor2d(12f, 34f), session.cursor2d.value)
assertEquals(TransformPivotMode.MedianPoint, session.pivotMode.value, "median is the default pivot")
session.setPivotMode(TransformPivotMode.Cursor)
assertEquals(TransformPivotMode.Cursor, session.pivotMode.value)
session.openPieMenu(PieMenuKind.Snap)
assertEquals(PieMenuKind.Snap, session.activePieMenu.value)
session.closePieMenu()
assertNull(session.activePieMenu.value)
// A restore (undo) drops the pie latch but keeps the cursor and pivot mode (persistent editor state).
val target = SelectionTarget.Drawable(DrawableId("d"))
session.setSelection(Selection(setOf(target), target))
session.openPieMenu(PieMenuKind.PivotMode)
session.undo()
assertNull(session.activePieMenu.value, "restore closes an open pie")
assertEquals(Cursor2d(12f, 34f), session.cursor2d.value, "the cursor survives undo")
assertEquals(TransformPivotMode.Cursor, session.pivotMode.value, "the pivot mode survives undo")
assertTrue(session.canRedo.value)
}
/** Proportional editing toggles off/on remembering its configuration; falloff selection enables it. */
@Test
fun proportionalEditToggleAndConfiguration() {
val session = meshedSession()
assertNull(session.proportionalEdit.value, "proportional editing starts off")
session.toggleProportionalEdit()
val enabled = session.proportionalEdit.value
assertEquals(ProportionalFalloff.Smooth, enabled?.falloff, "smooth is the default falloff")
assertEquals(DEFAULT_PROPORTIONAL_RADIUS_WORLD, enabled?.radiusWorld, "the default radius applies on first enable")
assertEquals("notice.proportional.on", session.notice.value?.messageKey, "the toggle confirms with a notice")
// Reconfigure, toggle off, toggle back on: the configuration is remembered.
session.setProportionalFalloff(ProportionalFalloff.Sharp)
session.setProportionalRadius(500f)
session.toggleProportionalEdit()
assertNull(session.proportionalEdit.value, "the second toggle disables")
session.toggleProportionalEdit()
assertEquals(ProportionalEditState(ProportionalFalloff.Sharp, 500f), session.proportionalEdit.value, "the configuration survives an off/on cycle")
// The radius clamps to its bounds; a falloff pick while off re-enables.
session.setProportionalRadius(0f)
assertEquals(MIN_PROPORTIONAL_RADIUS_WORLD, session.proportionalEdit.value?.radiusWorld, "the radius clamps at the minimum")
session.toggleProportionalEdit()
session.setProportionalFalloff(ProportionalFalloff.Linear)
assertEquals(ProportionalFalloff.Linear, session.proportionalEdit.value?.falloff, "picking a falloff while off enables proportional editing")
}
/** The rotate accumulator crosses the atan2 branch cut, reverses through zero, and multi-turns. */
@Test
fun rotationAngleTrackerUnwrapsAndAccumulates() {
val pi = kotlin.math.PI.toFloat()
// Start right AT the branch cut (a far pivot's typical start) and sweep across it: the raw
// difference would jump ~2*pi, the tracker advances by the small increments actually travelled.
val tracker = RotationAngleTracker()
assertEquals(0f, tracker.advance(pi - 0.1f), 1e-5f, "the first sample anchors at zero")
assertEquals(0.15f, tracker.advance(-pi + 0.05f), 1e-5f, "crossing the cut adds the short arc, not ~2*pi")
assertEquals(-0.05f, tracker.advance(pi - 0.15f), 1e-5f, "reversing walks back through zero into the other sign")
assertEquals(-0.05f, tracker.advance(pi - 0.15f), 1e-5f, "the same sample twice adds nothing (re-derives are safe)")
// A full circle in quarter steps accumulates ~2*pi (a raw subtraction could never exceed pi).
val multiTurn = RotationAngleTracker()
multiTurn.advance(0f)
multiTurn.advance(pi / 2)
multiTurn.advance(pi)
multiTurn.advance(-pi / 2)
assertEquals(2 * pi, multiTurn.advance(0f), 1e-4f, "a full sweep accumulates a whole turn")
assertEquals(0f, wrapAngle(2 * pi), 1e-5f, "wrapAngle folds a whole turn to zero")
assertEquals(-pi + 0.2f, wrapAngle(pi + 0.2f), 1e-5f, "wrapAngle folds past +pi into the negative side")
}
/** Connected Only toggles with a notice, enabling proportional editing when it was off. */
@Test
fun proportionalConnectedOnlyToggle() {
val session = meshedSession()
session.toggleProportionalConnected()
assertEquals(true, session.proportionalEdit.value?.connectedOnly, "toggling while off enables proportional editing, connected on")
assertEquals("notice.proportional.connected.on", session.notice.value?.messageKey, "the toggle confirms with a notice")
session.toggleProportionalConnected()
assertEquals(false, session.proportionalEdit.value?.connectedOnly, "the second toggle turns connected off")
assertTrue(session.proportionalEdit.value != null, "proportional editing itself stays on")
// Off/on cycles remember the flag with the rest of the configuration.
session.toggleProportionalConnected()
session.toggleProportionalEdit()
session.toggleProportionalEdit()
assertEquals(true, session.proportionalEdit.value?.connectedOnly, "connected only survives an off/on cycle")
}
/** A suppressed latch (the duplicate / rip auto-grab) opts the gesture out of proportional editing. */
@Test
fun suppressedMeshOperatorLatch() {
val session = meshedSession()
session.setMode(EditorMode.Edit)
session.setMeshSelection(MeshSelectionOps.add(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0)))
session.beginMeshOperator(MeshOperatorKind.Grab, "area-test", suppressProportional = true)
assertTrue(session.activeMeshOperatorSuppressesProportional, "the suppressed latch publishes its flag")
// Clearing the operator resets the flag; a plain latch never inherits it.
session.clearMeshOperator()
assertTrue(!session.activeMeshOperatorSuppressesProportional, "clearing the operator resets the suppression")
session.beginMeshOperator(MeshOperatorKind.Grab, "area-test")
assertTrue(!session.activeMeshOperatorSuppressesProportional, "a plain latch is never suppressed")
}
/** Operator latches record the initiating area; re-latching moves ownership atomically. */
@Test
fun operatorLatchesCarryTheInitiatingArea() {
val session = meshedSession()
val target = SelectionTarget.Drawable(DrawableId("d"))
session.setSelection(Selection(setOf(target), target))
session.beginObjectOperator(MeshOperatorKind.Grab, "area-a")
assertEquals(ActiveOperator(MeshOperatorKind.Grab, "area-a"), session.activeObjectOperator.value)
session.beginObjectOperator(MeshOperatorKind.Scale, "area-b")
assertEquals(ActiveOperator(MeshOperatorKind.Scale, "area-b"), session.activeObjectOperator.value, "re-latching replaces both the kind and the owner")
session.clearObjectOperator()
session.setMode(EditorMode.Edit)
session.setMeshSelection(MeshSelectionOps.add(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0)))
session.beginMeshOperator(MeshOperatorKind.Grab, "area-a")
assertEquals(ActiveOperator(MeshOperatorKind.Grab, "area-a"), session.activeMeshOperator.value)
}
/** The armed select tools carry their arming area; a resize keeps it, a re-arm moves it. */
@Test
fun selectToolsCarryTheArmingArea() {
val session = meshedSession()
session.beginBoxSelect("area-a")
assertEquals(ActiveSelectTool.BoxArmed("area-a"), session.activeSelectTool.value)
session.beginCircleSelect("area-a")
val armed = session.activeSelectTool.value as ActiveSelectTool.Circle
assertEquals("area-a", armed.areaId)
session.setCircleRadius(armed.radiusPx + 10f)
val resized = session.activeSelectTool.value as ActiveSelectTool.Circle
assertEquals("area-a", resized.areaId, "a resize keeps the brush in its arming area")
// Re-arming from another viewport moves the tool there, restoring the remembered radius.
session.beginCircleSelect("area-b")
val rearmed = session.activeSelectTool.value as ActiveSelectTool.Circle
assertEquals("area-b", rearmed.areaId)
assertEquals(resized.radiusPx, rearmed.radiusPx, "the remembered radius survives the re-arm")
}
/** Mutual exclusion crosses areas: a latch in one viewport drops a tool armed in another. */
@Test
fun latchingDropsToolsArmedInOtherAreas() {
val session = meshedSession()
val target = SelectionTarget.Drawable(DrawableId("d"))
session.setSelection(Selection(setOf(target), target))
session.beginCircleSelect("area-a")
session.beginObjectOperator(MeshOperatorKind.Grab, "area-b")
assertNull(session.activeSelectTool.value, "latching an operator drops the other area's armed tool")
assertEquals("area-b", session.activeObjectOperator.value?.areaId)
// A restore (undo) clears the area-carrying latch entirely, whoever owned it.
session.undo()
assertNull(session.activeObjectOperator.value, "restore clears the latched operator")
}
/** snapToGrid rounds relative to the world origin, so a snap lands on the origin-anchored grid lines. */
@Test
fun snapToGridRoundsRelativeToOrigin() {
// Origin 0: plain rounding to the nearest multiple of the step.
assertEquals(100f, snapToGrid(120f, origin = 0f, step = 100f), "120 -> nearest 100")
assertEquals(200f, snapToGrid(160f, origin = 0f, step = 100f), "160 -> nearest 200")
// Offset origin (the canvas-center case): the lattice shifts with it, so 120 snaps to origin + 100.
assertEquals(150f, snapToGrid(120f, origin = 50f, step = 100f), "grid at 50,150,... -> 120 snaps to 150")
assertEquals(50f, snapToGrid(60f, origin = 50f, step = 100f), "60 snaps to the origin line at 50")
}
/** snapToWorldGrid anchors each axis on its own origin component, so both land on the drawn grid lines. */
@Test
fun snapToWorldGridAnchorsEachAxisOnTheOrigin() {
// The origin a 1200 x 800 canvas derives: world (600, -400).
val model = meshedSession().model.value.copy(worldOriginX = 600f, worldOriginZ = -400f)
// x 630 is 30 right of the origin line, so it rounds back onto it; z -345 is 55 above, so up to -300.
assertEquals(600f to -300f, model.snapToWorldGrid(630f, -345f, step = 100f))
// A point already on the lattice stays put.
assertEquals(700f to -500f, model.snapToWorldGrid(700f, -500f, step = 100f))
}
/** An unplaced cursor resolves to the world origin for every operation, without being placed. */
@Test
fun unplacedCursorResolvesToTheWorldOrigin() {
val session = EditorSession(meshedSession().model.value.copy(worldOriginX = 600f, worldOriginZ = -600f))
assertEquals(Cursor2d(600f, -600f), session.cursor2dOrWorldOrigin(), "an unplaced cursor rests on the world axes")
assertNull(session.cursor2d.value, "resolving it does not place it, so it stays undrawn and unpersisted")
session.setCursor2d(12f, 34f)
assertEquals(Cursor2d(12f, 34f), session.cursor2dOrWorldOrigin(), "a placed cursor is its own point")
}
/** GridConfig.snapStep is the finest visible spacing: scale divided by the subdivision count. */
@Test
fun gridConfigSnapStepIsScaleOverSubdivisions() {
assertEquals(10f, GridConfig(scale = 100f, subdivisions = 10).snapStep, "100 / 10 = 10")
assertEquals(25f, GridConfig(scale = 100f, subdivisions = 4).snapStep, "100 / 4 = 25")
// A defaulted config keeps the built-in fallbacks (SNAP_GRID_WORLD_UNITS / DEFAULT_GRID_SUBDIVISIONS).
assertEquals(SNAP_GRID_WORLD_UNITS / DEFAULT_GRID_SUBDIVISIONS, GridConfig().snapStep, "default step")
// subdivisions is clamped to at least 1, so a degenerate 0 never divides by zero.
assertEquals(100f, GridConfig(scale = 100f, subdivisions = 0).snapStep, "0 subdivisions clamps to 1")
}
/** setGridConfig publishes the new geometry on the session's gridConfig flow (transient, not snapshotted). */
@Test
fun setGridConfigPublishesAndIsNotUndoable() {
val session = meshedSession()
assertEquals(GridConfig(), session.gridConfig.value, "starts at the default grid")
session.setGridConfig(GridConfig(scale = 50f, subdivisions = 5))
assertEquals(GridConfig(scale = 50f, subdivisions = 5), session.gridConfig.value, "the new config publishes")
assertTrue(!session.canUndo.value, "a grid-config change is transient, never an undo step")
}
}
@@ -0,0 +1,366 @@
package org.umamo.edit
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotSame
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Verifies the UV write path: the withMeshUvs copy-on-write op and its
* no-op guards, the commitMeshUvs undo integration, the activeUvOperator latch semantics (area
* ownership, mutual exclusion, the Vertex Slide and mode refusals, the axis-constraint hookup), the
* UV cursor, and the Mirror U / V command math. The load-bearing invariant throughout is the mesh/UV
* decoupling seen from the UV side: a UV edit shares the positions and indices arrays by reference
* and never disturbs rest geometry.
*/
class UvEditsTest {
private fun meshedDrawable(id: String, uvs: FloatArray): Drawable =
Drawable(
id = DrawableId(id),
name = id,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), uvs, intArrayOf(0, 1, 2)),
geometryGrid = null,
)
private fun uvModel(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = emptyList(),
drawables =
listOf(
meshedDrawable("a", floatArrayOf(0.2f, 0.1f, 0.4f, 0.1f, 0.6f, 0.4f)),
meshedDrawable("b", floatArrayOf(0.1f, 0.8f, 0.3f, 0.8f, 0.1f, 0.9f)),
),
rootChildren = emptyList(),
rootPartId = null,
)
/** Asserts two interleaved uv arrays match element-wise within float tolerance. */
private fun assertUvsEqual(expected: List<Float>, actual: FloatArray, message: String) {
assertEquals(expected.size, actual.size, message)
for (componentIndex in expected.indices) {
assertEquals(expected[componentIndex], actual[componentIndex], 1e-5f, "$message (component $componentIndex)")
}
}
/** Enters Edit mode with every vertex of drawable "a" selected (and optionally "b" too). */
private fun editSession(selectBothDrawables: Boolean = false): EditorSession {
val session = EditorSession(uvModel())
session.setMode(EditorMode.Edit)
var selection = session.meshSelection.value
for (vertexIndex in 0..2) {
selection = MeshSelectionOps.add(selection, DrawableId("a"), MeshElement.Vertex(vertexIndex))
}
if (selectBothDrawables) {
for (vertexIndex in 0..2) {
selection = MeshSelectionOps.add(selection, DrawableId("b"), MeshElement.Vertex(vertexIndex))
}
}
session.setMeshSelection(selection)
return session
}
/** withMeshUvs rebuilds only the touched mesh leaf, sharing positions / indices and every sibling. */
@Test
fun withMeshUvsSharesEverythingButTheUvArray() {
val model = uvModel()
val originalMesh = model.drawables[0].mesh!!
val untouchedDrawable = model.drawables[1]
val newUvs = floatArrayOf(0.5f, 0.5f, 0.6f, 0.5f, 0.5f, 0.6f)
val updated = model.withMeshUvs(DrawableId("a"), newUvs)
assertNotSame(model, updated, "a real edit produces a new model instance")
val updatedMesh = updated.drawables[0].mesh!!
assertSame(newUvs, updatedMesh.uvs, "the new uv array is adopted as-is")
assertSame(originalMesh.positions, updatedMesh.positions, "positions are shared by reference (the decoupling invariant)")
assertSame(originalMesh.indices, updatedMesh.indices, "indices are shared by reference")
assertSame(untouchedDrawable, updated.drawables[1], "the other drawable is shared by reference")
assertSame(originalMesh, model.drawables[0].mesh, "the input model is never mutated")
}
/** Every withMeshUvs no-op guard returns the same model instance so the session records nothing. */
@Test
fun withMeshUvsNoOpGuards() {
val model = uvModel()
val mesh = model.drawables[0].mesh!!
assertSame(model, model.withMeshUvs(DrawableId("missing"), FloatArray(6)), "an unknown drawable is a no-op")
assertSame(model, model.withMeshUvs(DrawableId("a"), mesh.uvs), "the live array instance is a no-op")
assertSame(model, model.withMeshUvs(DrawableId("a"), FloatArray(4)), "a length mismatch is a no-op")
val meshless =
model.copy(drawables = listOf(model.drawables[0].copy(mesh = null)))
assertSame(meshless, meshless.withMeshUvs(DrawableId("a"), FloatArray(6)), "a mesh-less drawable is a no-op")
}
/** commitMeshUvs folds several drawables into ONE undo step; undo restores the exact prior arrays. */
@Test
fun commitMeshUvsIsOneUndoStepAndUndoRestoresTheArrayReferences() {
val session = editSession(selectBothDrawables = true)
val originalUvsA = session.model.value.drawables[0].mesh!!.uvs
val originalUvsB = session.model.value.drawables[1].mesh!!.uvs
val stepsBefore = session.historyView.value.steps.size
assertFalse(session.dirty.value, "selection setup never dirties the document")
session.commitMeshUvs(
MeshChange.TransformUvs(mapOf(DrawableId("a") to listOf(0, 1, 2), DrawableId("b") to listOf(0, 1, 2)), MeshOperatorKind.Grab),
mapOf(
DrawableId("a") to floatArrayOf(0.3f, 0.2f, 0.5f, 0.2f, 0.7f, 0.5f),
DrawableId("b") to floatArrayOf(0.2f, 0.7f, 0.4f, 0.7f, 0.2f, 0.8f),
),
)
assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "both drawables commit as one step")
assertEquals("change.uv.move", session.historyView.value.steps.last().labelKey)
assertTrue(session.dirty.value, "a UV edit is document content")
assertNotSame(originalUvsA, session.model.value.drawables[0].mesh!!.uvs)
session.undo()
assertSame(originalUvsA, session.model.value.drawables[0].mesh!!.uvs, "undo restores the exact prior uv array")
assertSame(originalUvsB, session.model.value.drawables[1].mesh!!.uvs)
assertFalse(session.dirty.value, "undo returns to the saved baseline")
}
/** A commit whose every entry no-ops (mismatch / same instance / empty) records nothing. */
@Test
fun commitMeshUvsNoOpRecordsNothing() {
val session = editSession()
val modelBefore = session.model.value
val stepsBefore = session.historyView.value.steps.size
session.commitMeshUvs(MeshChange.TransformUvs(emptyMap(), MeshOperatorKind.Grab), emptyMap())
session.commitMeshUvs(MeshChange.TransformUvs(mapOf(DrawableId("a") to emptyList()), MeshOperatorKind.Grab), mapOf(DrawableId("a") to FloatArray(4)))
session.commitMeshUvs(
MeshChange.TransformUvs(mapOf(DrawableId("a") to emptyList()), MeshOperatorKind.Grab),
mapOf(DrawableId("a") to modelBefore.drawables[0].mesh!!.uvs),
)
assertSame(modelBefore, session.model.value, "no-op commits leave the model instance untouched")
assertEquals(stepsBefore, session.historyView.value.steps.size, "no-op commits record no history step")
assertFalse(session.dirty.value)
}
/** The UV latch records the initiating area, refuses Vertex Slide, and requires Edit mode. */
@Test
fun uvOperatorLatchSemantics() {
val session = editSession()
session.beginUvOperator(MeshOperatorKind.Grab, "area-uv")
assertEquals(ActiveOperator(MeshOperatorKind.Grab, "area-uv"), session.activeUvOperator.value)
session.beginUvOperator(MeshOperatorKind.Scale, "area-other")
assertEquals(
ActiveOperator(MeshOperatorKind.Scale, "area-other"),
session.activeUvOperator.value,
"re-latching replaces both the kind and the owner",
)
session.clearUvOperator()
assertNull(session.activeUvOperator.value)
session.beginUvOperator(MeshOperatorKind.VertexSlide, "area-uv")
assertNull(session.activeUvOperator.value, "Vertex Slide is rest-geometry math and is refused")
session.setMode(EditorMode.Object)
session.beginUvOperator(MeshOperatorKind.Grab, "area-uv")
assertNull(session.activeUvOperator.value, "Object mode refuses the UV latch")
}
/** The three operator latches are mutually exclusive, and a restore (undo) clears the UV latch. */
@Test
fun uvOperatorMutualExclusionAndRestoreTeardown() {
val session = editSession()
session.beginMeshOperator(MeshOperatorKind.Grab, "area-a")
session.beginUvOperator(MeshOperatorKind.Grab, "area-uv")
assertNull(session.activeMeshOperator.value, "latching UV drops the mesh operator")
assertEquals("area-uv", session.activeUvOperator.value?.areaId)
session.beginMeshOperator(MeshOperatorKind.Grab, "area-a")
assertNull(session.activeUvOperator.value, "latching mesh drops the UV operator")
session.clearMeshOperator()
session.beginBoxSelect("area-a")
session.beginUvOperator(MeshOperatorKind.Grab, "area-uv")
assertNull(session.activeSelectTool.value, "latching UV drops the armed select tool")
session.undo()
assertNull(session.activeUvOperator.value, "restore clears the latched UV operator")
}
/** The X / Z axis constraint toggles during a UV Grab / Scale, never for Rotate, and clears with the latch. */
@Test
fun uvOperatorAxisConstraint() {
val session = editSession()
session.beginUvOperator(MeshOperatorKind.Grab, "area-uv")
session.toggleAxisConstraint(TransformAxisConstraint.AxisX)
assertEquals(TransformAxisConstraint.AxisX, session.axisConstraint.value)
session.clearUvOperator()
assertNull(session.axisConstraint.value, "clearing the UV operator clears the lock")
session.beginUvOperator(MeshOperatorKind.Rotate, "area-uv")
session.toggleAxisConstraint(TransformAxisConstraint.AxisX)
assertNull(session.axisConstraint.value, "Rotate refuses the lock")
}
/** A selection whose meshes carry no editable UV array refuses the latch with an explanatory notice. */
@Test
fun uvOperatorRefusesWithoutEditableUvs() {
val model =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = emptyList(),
drawables = listOf(meshedDrawable("a", FloatArray(0))),
rootChildren = emptyList(),
rootPartId = null,
)
val session = EditorSession(model)
session.setMode(EditorMode.Edit)
session.setMeshSelection(MeshSelectionOps.add(session.meshSelection.value, DrawableId("a"), MeshElement.Vertex(0)))
session.beginUvOperator(MeshOperatorKind.Grab, "area-uv")
assertNull(session.activeUvOperator.value, "an empty uv array cannot be edited")
assertEquals("notice.uv.noUvs", session.notice.value?.messageKey, "the refusal explains itself")
session.mirrorSelectedUvs(mirrorU = true)
assertFalse(session.dirty.value, "the mirror refuses for the same reason")
}
/** The UV cursor latch holds its placement and survives undo (transient by design, like cursor2d). */
@Test
fun uvCursorPlacement() {
val session = editSession()
assertNull(session.uvCursor.value, "no cursor before placement")
session.setUvCursor(0.25f, 0.75f)
assertEquals(UvCursor(0.25f, 0.75f), session.uvCursor.value)
session.undo()
assertEquals(UvCursor(0.25f, 0.75f), session.uvCursor.value, "the UV cursor survives undo")
}
/** Mirror U flips u about the covered median leaving v (and rest geometry) untouched; Mirror V is the converse. */
@Test
fun mirrorSelectedUvsAboutTheMedian() {
val session = editSession()
val originalPositions = session.model.value.drawables[0].mesh!!.positions
// Covered u values are 0.2 / 0.4 / 0.6, so the median pivot's u is 0.4.
session.mirrorSelectedUvs(mirrorU = true)
val mirroredU = session.model.value.drawables[0].mesh!!.uvs
assertUvsEqual(listOf(0.6f, 0.1f, 0.4f, 0.1f, 0.2f, 0.4f), mirroredU, "u reflects about 0.4, v is untouched")
assertSame(originalPositions, session.model.value.drawables[0].mesh!!.positions, "rest geometry is untouched by reference")
assertEquals("change.uv.mirror", session.historyView.value.steps.last().labelKey)
// Covered v values are now 0.1 / 0.1 / 0.4, so the median pivot's v is 0.2.
session.mirrorSelectedUvs(mirrorU = false)
val mirroredV = session.model.value.drawables[0].mesh!!.uvs
assertEquals(0.3f, mirroredV[1], 1e-5f, "v reflects about the median")
assertEquals(0.6f, mirroredV[0], 1e-5f, "u is untouched by a V mirror")
session.undo()
session.undo()
assertEquals(listOf(0.2f, 0.1f, 0.4f, 0.1f, 0.6f, 0.4f), session.model.value.drawables[0].mesh!!.uvs.toList(), "two undos restore the original mapping")
}
/** The Cursor pivot mode mirrors about the UV cursor, falling back to the median before any placement. */
@Test
fun mirrorSelectedUvsAboutTheCursor() {
val session = editSession()
session.setPivotMode(TransformPivotMode.Cursor)
// No cursor placed yet: the median fallback keeps the command effective.
session.mirrorSelectedUvs(mirrorU = true)
assertEquals(0.6f, session.model.value.drawables[0].mesh!!.uvs[0], 1e-5f, "an unplaced cursor falls back to the median")
session.undo()
session.setUvCursor(0.5f, 0.5f)
session.mirrorSelectedUvs(mirrorU = true)
val mirrored = session.model.value.drawables[0].mesh!!.uvs
assertUvsEqual(listOf(0.8f, 0.1f, 0.6f, 0.1f, 0.4f, 0.4f), mirrored, "u reflects about the cursor's 0.5")
}
/**
* A quarter-turn frame: stored (u, v) reads as (v, -u) in the authoring space. Enough to catch a
* mirror that reflects about the STORED axis while claiming to reflect about the shown one - under
* this frame the two are perpendicular, so the mistake cannot pass.
*/
private fun quarterTurnFrame(): UvFrame =
UvFrame(toFrameAffine = floatArrayOf(0f, 1f, 0f, -1f, 0f, 0f), fromFrameAffine = floatArrayOf(0f, -1f, 0f, 1f, 0f, 0f))
/** With no frame the mirror is exactly what it always was - the page view must not shift at all. */
@Test
fun mirrorWithoutAFrameIsUnchanged() {
val withoutFrame = editSession()
withoutFrame.mirrorSelectedUvs(mirrorU = true)
val plain = withoutFrame.model.value.drawables[0].mesh!!.uvs
val withIdentity = editSession()
withIdentity.mirrorSelectedUvs(mirrorU = true, frame = null)
assertUvsEqual(plain.toList(), withIdentity.model.value.drawables[0].mesh!!.uvs, "an absent frame changes nothing")
}
/**
* Under a frame the mirror reflects about the AUTHORING axis, not the stored one. Mirroring
* horizontally through a quarter turn therefore moves v and leaves u alone - the opposite of what
* the same command does with no frame.
*/
@Test
fun mirrorReflectsAboutTheAuthoringAxis() {
val session = editSession()
val original = session.model.value.drawables[0].mesh!!.uvs.copyOf()
session.mirrorSelectedUvs(mirrorU = true, frame = quarterTurnFrame())
val mirrored = session.model.value.drawables[0].mesh!!.uvs
// Frame u is stored v, so a horizontal mirror in the frame reflects the stored v about its own
// covered median (0.1 / 0.1 / 0.4 -> 0.2) and leaves stored u untouched.
assertEquals(original[0], mirrored[0], 1e-5f, "stored u is untouched by a frame-horizontal mirror")
assertEquals(original[2], mirrored[2], 1e-5f, "stored u is untouched by a frame-horizontal mirror")
assertEquals(0.3f, mirrored[1], 1e-5f, "stored v reflects about the covered median")
assertEquals(0.3f, mirrored[3], 1e-5f, "stored v reflects about the covered median")
assertEquals(0.0f, mirrored[5], 1e-5f, "stored v reflects about the covered median")
}
/** The Cursor pivot converts into the frame too, so the anchor means the same place in both spaces. */
@Test
fun mirrorResolvesTheCursorPivotInTheFrame() {
val session = editSession()
session.setPivotMode(TransformPivotMode.Cursor)
session.setUvCursor(0.5f, 0.25f)
session.mirrorSelectedUvs(mirrorU = true, frame = quarterTurnFrame())
val mirrored = session.model.value.drawables[0].mesh!!.uvs
// The cursor's stored (0.5, 0.25) is frame (0.25, -0.5); a frame-horizontal mirror reflects the
// frame u - stored v - about 0.25.
assertEquals(0.4f, mirrored[1], 1e-5f, "stored v reflects about the cursor's frame position")
assertEquals(0.1f, mirrored[5], 1e-5f, "stored v reflects about the cursor's frame position")
}
/** A frame round trip must not disturb a vertex the mirror never moved. */
@Test
fun mirrorLeavesUnselectedVerticesBitIdentical() {
val session = editSession()
// Select only vertex 0, so vertices 1 and 2 must survive the frame conversion untouched.
session.setMeshSelection(MeshSelectionOps.replace(MeshSelection(), DrawableId("a"), MeshElement.Vertex(0)))
val original = session.model.value.drawables[0].mesh!!.uvs.copyOf()
session.mirrorSelectedUvs(mirrorU = true, frame = quarterTurnFrame())
val mirrored = session.model.value.drawables[0].mesh!!.uvs
for (componentIndex in 2 until original.size) {
assertEquals(
original[componentIndex].toRawBits(),
mirrored[componentIndex].toRawBits(),
"untouched component $componentIndex must keep its exact stored value",
)
}
}
}
@@ -0,0 +1,71 @@
package org.umamo.edit
import org.umamo.runtime.eval.warpControlPointsAt
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.DrawableMesh
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.WarpLatticeForm
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class WarpCreateVisibilityTest {
private val partId = PartId("p")
private val drawableA = DrawableId("a")
private fun parentWarp(): Deformer.Warp {
val points = rectLatticeControlPoints(0f, 0f, 1f, 1f, 1, 1)
return Deformer.Warp(
id = DeformerId("Parent"),
name = "Parent",
parent = null,
partId = partId,
rows = 1,
columns = 1,
isQuadTransform = true,
geometryGrid = KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), WarpLatticeForm(points)))),
)
}
@Test
fun nestedCreateYieldsSampleableLattice() {
val parent = parentWarp()
val start =
PuppetModel(
parameters = emptyList(),
parts = listOf(Part(partId, "P", listOf(OrgChild.Drawable(drawableA)))),
deformers = listOf(parent),
drawables =
listOf(
Drawable(
id = drawableA,
name = "a",
parentDeformerId = DeformerId("Parent"),
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = DrawableMesh(floatArrayOf(0.2f, 0.2f, 0.8f, 0.2f, 0.2f, 0.8f), FloatArray(6), intArrayOf(0, 1, 2)),
geometryGrid = null,
),
),
rootChildren = listOf(OrgChild.Part(partId)),
rootPartId = null,
)
val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Child"), "Child", listOf(drawableA))
val child = after.deformers.filterIsInstance<Deformer.Warp>().single { it.id == DeformerId("Child") }
assertEquals(DeformerId("Parent"), child.parent)
val points = assertNotNull(warpControlPointsAt(child.geometryGrid) { 0f })
assertTrue(points.size >= 8, "points=${points.size}")
assertTrue(points.max() > 0.1f, "max=${points.max()}")
}
}
@@ -0,0 +1,97 @@
package org.umamo.edit
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.OrgChild
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PartId
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.WarpLatticeForm
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Warp lattice grid resize: resampling densifies the control points without moving the surface, and
* out-of-range counts clamp to the properties slider's 2–16 band.
*/
class WarpLatticeGridEditsTest {
private val partId = PartId("p")
private fun identityWarp(rows: Int, columns: Int): Deformer.Warp {
val points = rectLatticeControlPoints(0f, 0f, 10f, 20f, rows, columns)
return Deformer.Warp(
id = DeformerId("Warp"),
name = "Warp",
parent = null,
partId = partId,
rows = rows,
columns = columns,
isQuadTransform = true,
geometryGrid =
KeyformGrid(
emptyList(),
listOf(KeyformCell(IntArray(0), WarpLatticeForm(points))),
),
)
}
private fun modelWith(warp: Deformer.Warp): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = listOf(Part(partId, "P", emptyList())),
deformers = listOf(warp),
drawables = emptyList(),
rootChildren = listOf(OrgChild.Part(partId)),
rootPartId = null,
)
@Test
fun resamplingIdentityLatticeKeepsCornersAndMidpoint() {
val start = identityWarp(rows = 2, columns = 2)
val old = assertNotNull(start.geometryGrid).cells.single().form.controlPoints
val resized = modelWith(start).withWarpDeformerGrid(start.id, rows = 5, columns = 5)
val warp = resized.deformers.single() as Deformer.Warp
assertEquals(5, warp.rows)
assertEquals(5, warp.columns)
val points = assertNotNull(warp.geometryGrid).cells.single().form.controlPoints
assertEquals((5 + 1) * (5 + 1) * 2, points.size)
assertEquals(old[0], points[0], absoluteTolerance = 1e-4f)
assertEquals(old[1], points[1], absoluteTolerance = 1e-4f)
val oldLast = old.size - 2
val newLast = points.size - 2
assertEquals(old[oldLast], points[newLast], absoluteTolerance = 1e-4f)
assertEquals(old[oldLast + 1], points[newLast + 1], absoluteTolerance = 1e-4f)
val expected = FloatArray(2)
// row 2, col 2 of a 6×6 point grid (5 divisions) sits at UV (2/5, 2/5).
sampleWarpLattice(old, columns = 2, rows = 2, bilinear = true, u = 2f / 5f, v = 2f / 5f, out = expected, outIndex = 0)
val midIndex = (2 * 6 + 2) * 2
assertEquals(expected[0], points[midIndex], absoluteTolerance = 1e-4f)
assertEquals(expected[1], points[midIndex + 1], absoluteTolerance = 1e-4f)
}
@Test
fun clampAndNoOp() {
val start = identityWarp(2, 2)
val model = modelWith(start)
assertTrue(model === model.withWarpDeformerGrid(start.id, 2, 2))
val clamped = model.withWarpDeformerGrid(start.id, 99, 0)
val warp = clamped.deformers.single() as Deformer.Warp
assertEquals(MAX_WARP_DIVISIONS, warp.rows)
assertEquals(MIN_WARP_DIVISIONS, warp.columns)
}
@Test
fun sessionCommitResizesSelectedWarp() {
val start = identityWarp(2, 2)
val session = EditorSession(modelWith(start))
session.setDeformerWarpGrid(start.id, 8, 8)
val warp = session.model.value.deformers.single() as Deformer.Warp
assertEquals(8, warp.rows)
assertEquals(8, warp.columns)
assertEquals((8 + 1) * (8 + 1) * 2, assertNotNull(warp.geometryGrid).cells.single().form.controlPoints.size)
}
}
@@ -0,0 +1,39 @@
package org.umamo.edit.seed
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Pins the seed templates: the stored-key round trip and its stale-key fallback, and the humanoid
* dataset's shape - verbatim standard ids, no repeats - since every Live2D-compatible consumer keys
* on exactly those ids.
*/
class ParameterTemplateTest {
@Test
fun aStoredKeyResolvesAndAStaleOneFallsBackToTheDefault() {
assertEquals(ParameterTemplate.Humanoid, ParameterTemplate.fromKey("humanoid"))
assertEquals(ParameterTemplate.None, ParameterTemplate.fromKey("none"))
assertEquals(ParameterTemplate.Default, ParameterTemplate.fromKey("not-a-template"), "a stale setting falls back to the default")
assertEquals(ParameterTemplate.Default, ParameterTemplate.fromKey(null), "an absent setting falls back to the default")
for (template in ParameterTemplate.entries) {
assertEquals(template, ParameterTemplate.fromKey(template.key), "every entry's key round-trips")
}
}
@Test
fun noneSeedsNothingAndHumanoidSeedsTheStandardSet() {
assertTrue(ParameterTemplate.None.parameters.isEmpty())
assertEquals(HumanoidParameters.list, ParameterTemplate.Humanoid.parameters)
assertEquals("ParamAngleX", HumanoidParameters.list.first().id.raw, "the standard ids are verbatim")
assertEquals(
HumanoidParameters.list.size,
HumanoidParameters.list.map { parameter -> parameter.id }.toSet().size,
"no id repeats",
)
for (parameter in HumanoidParameters.list) {
assertTrue(parameter.min < parameter.max, "${parameter.id.raw} is animatable")
assertTrue(parameter.default in parameter.min..parameter.max, "${parameter.id.raw} rests inside its range")
}
}
}
@@ -0,0 +1,64 @@
package org.umamo.edit
import org.poly2tri.Poly2Tri
import org.poly2tri.geometry.polygon.Polygon
import org.poly2tri.geometry.polygon.PolygonPoint
import org.poly2tri.triangulation.TriangulationPoint
import java.util.IdentityHashMap
/**
* JVM/Android [PolygonTriangulator]: poly2tri constrained Delaunay (zigzag diagonals).
*/
internal actual object PolygonTriangulator {
actual fun triangulate(xy: DoubleArray): IntArray {
val count = xy.size / 2
if (count < 3) {
return IntArray(0)
}
// poly2tri rejects duplicate coordinates; drop consecutive duplicates and a closing repeat.
val points = ArrayList<PolygonPoint>(count)
val indexOf = IdentityHashMap<TriangulationPoint, Int>()
var prevX = Double.NaN
var prevY = Double.NaN
for (i in 0 until count) {
val x = xy[i * 2]
val y = xy[i * 2 + 1]
if (i > 0 && x == prevX && y == prevY) {
continue
}
prevX = x
prevY = y
val point = PolygonPoint(x, y)
indexOf[point] = i
points.add(point)
}
if (points.size >= 2) {
val first = points.first()
val last = points.last()
if (first.x == last.x && first.y == last.y) {
points.removeAt(points.lastIndex)
}
}
if (points.size < 3) {
return IntArray(0)
}
return try {
val polygon = Polygon(points)
Poly2Tri.triangulate(polygon)
val triangles = polygon.triangles
val out = IntArray(triangles.size * 3)
var offset = 0
for (triangle in triangles) {
val a = indexOf[triangle.points[0]] ?: return IntArray(0)
val b = indexOf[triangle.points[1]] ?: return IntArray(0)
val c = indexOf[triangle.points[2]] ?: return IntArray(0)
out[offset++] = a
out[offset++] = b
out[offset++] = c
}
out
} catch (_: RuntimeException) {
IntArray(0)
}
}
}
@@ -0,0 +1,70 @@
package org.umamo.edit
import org.umamo.format.cmo3.Cmo3
import org.umamo.format.cmo3.model.custom.CModelSource
import org.umamo.interop.cmo3.Cmo3Import
import org.umamo.render.eval.warpLatticeLocalAt
import org.umamo.render.eval.warpLatticeSpaceMapping
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.DeformerId
import java.io.File
import kotlin.math.max
import kotlin.math.min
import kotlin.test.Test
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Corpus gate: creating a warp under an existing parent must keep the lattice mappable into a
* canvas-scale world AABB (not millions of units from treating canvas rest as parent UV).
*/
class WarpCreateViewportDiagTest {
private val sample: File? =
sequenceOf(
System.getProperty("cmo3.sample"),
"/home/litruv/dev/vtsmaker/Bear_.cmo3",
).mapNotNull { path -> path?.let(::File)?.takeIf { file -> file.isFile } }.firstOrNull()
private fun aabb(points: FloatArray): Pair<Float, Float> {
var minX = Float.POSITIVE_INFINITY
var minY = Float.POSITIVE_INFINITY
var maxX = Float.NEGATIVE_INFINITY
var maxY = Float.NEGATIVE_INFINITY
var index = 0
while (index + 1 < points.size) {
minX = min(minX, points[index])
maxX = max(maxX, points[index])
minY = min(minY, points[index + 1])
maxY = max(maxY, points[index + 1])
index += 2
}
return (maxX - minX) to (maxY - minY)
}
@Test
fun nestedCreateLatticeIsMappableOnBear() {
val file = sample ?: return
val root = Cmo3.read(file).root as? CModelSource ?: error("not CModelSource")
val puppet = Cmo3Import.fromModelSource(root)
val pick = puppet.drawables.first { drawable -> drawable.parentDeformerId != null && drawable.mesh != null }
val after =
puppet.withWarpDeformerCreatedForDrawables(
DeformerId("DiagWarp"),
"DiagWarp",
listOf(pick.id),
)
val created = after.deformers.filterIsInstance<Deformer.Warp>().single { it.id == DeformerId("DiagWarp") }
assertNotNull(created.parent)
val pose = after.parameters.associate { it.id to it.default }
val local = assertNotNull(warpLatticeLocalAt(after, pose, created.id))
val mapping = assertNotNull(warpLatticeSpaceMapping(after, pose, created.id))
val world = mapping.localToWorld(local)
val (spanX, spanY) = aabb(world)
// Parent warp covers ~canvas; a fitted child lattice must stay on that order of magnitude.
assertTrue(spanX in 1f..10_000f, "world spanX=$spanX")
assertTrue(spanY in 1f..10_000f, "world spanY=$spanY")
for (index in local.indices) {
assertTrue(local[index] in -0.5f..1.5f, "local[$index]=${local[index]} should be parent UV")
}
}
}
@@ -0,0 +1,76 @@
package org.umamo.edit
import org.umamo.format.cmo3.Cmo3
import org.umamo.format.cmo3.model.custom.CModelSource
import org.umamo.interop.cmo3.Cmo3Import
import org.umamo.render.eval.drawableLocalPosed
import org.umamo.render.eval.drawableSpaceMapping
import org.umamo.runtime.model.partByDrawable
import java.io.File
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Deformer delete must unwrap (bake) without removing parts or destroying the drawable's world pose.
*/
class WarpDeleteKeepsPartTest {
private fun span(points: FloatArray): Pair<Float, Float> {
var minX = Float.POSITIVE_INFINITY
var minY = Float.POSITIVE_INFINITY
var maxX = Float.NEGATIVE_INFINITY
var maxY = Float.NEGATIVE_INFINITY
var index = 0
while (index + 1 < points.size) {
minX = min(minX, points[index])
maxX = max(maxX, points[index])
minY = min(minY, points[index + 1])
maxY = max(maxY, points[index + 1])
index += 2
}
return (maxX - minX) to (maxY - minY)
}
@Test
fun createThenDeleteWarpKeepsPartAndWorldPose() {
val file = File("/home/litruv/dev/vtsmaker/Bear_.cmo3")
if (!file.isFile) {
return
}
val puppet = Cmo3Import.fromModelSource(Cmo3.read(file).root as CModelSource)
// A smaller mesh under Warp16 so an unbaked unwrap would stretch it across the parent lattice.
val pick =
puppet.drawables.first { drawable ->
drawable.parentDeformerId?.raw == "Warp16" &&
drawable.mesh != null &&
drawable.id.raw != "Jumper"
}
val owner = assertNotNull(puppet.partByDrawable()[pick.id])
val partsBefore = puppet.parts.map { it.id }.toSet()
val pose = puppet.parameters.associate { it.id to it.default }
val beforeWorld =
drawableSpaceMapping(puppet, pose, pick.id)!!.localToWorld(drawableLocalPosed(puppet, pose, pick.id)!!)
val (beforeSpanX, beforeSpanY) = span(beforeWorld)
val session = EditorSession(puppet)
session.setSelection(Selection(setOf(SelectionTarget.Drawable(pick.id)), SelectionTarget.Drawable(pick.id)))
val warpId = assertNotNull(session.createWarpDeformerForSelection("Warp Deformer"))
session.deleteDeformer(warpId)
val after = session.model.value
assertEquals(partsBefore, after.parts.map { it.id }.toSet())
assertTrue(after.parts.any { it.id == owner })
assertTrue(after.deformers.none { it.id == warpId })
assertEquals(pick.parentDeformerId, after.drawables.first { it.id == pick.id }.parentDeformerId)
val afterWorld =
drawableSpaceMapping(after, pose, pick.id)!!.localToWorld(drawableLocalPosed(after, pose, pick.id)!!)
val (afterSpanX, afterSpanY) = span(afterWorld)
assertTrue(abs(afterSpanX - beforeSpanX) / beforeSpanX < 0.05f, "spanX before=$beforeSpanX after=$afterSpanX")
assertTrue(abs(afterSpanY - beforeSpanY) / beforeSpanY < 0.05f, "spanY before=$beforeSpanY after=$afterSpanY")
}
}

Some files were not shown because too many files have changed in this diff Show More