Animation blend: add algorithm "freeform directional" (#14203)

* Animation blend: add algorithm "freeform directional"

* Update comment

* Fix
This commit is contained in:
Leslie Leigh (李的序)
2023-04-03 13:34:53 +08:00
committed by GitHub
parent 18c27f293a
commit eb8be7e5bb
4 changed files with 834 additions and 75 deletions
@@ -22,12 +22,12 @@
THE SOFTWARE.
*/
import { Vec2, _decorator, ccenum } from '../../core';
import { Vec2, _decorator, ccenum, assertIsTrue, editable } from '../../core';
import { createEval } from './create-eval';
import { AnimationBlend, AnimationBlendEval, AnimationBlendItem } from './animation-blend';
import { MotionEvalContext } from './motion';
import { BindableNumber, bindOr, VariableType } from './parametric';
import { sampleFreeformCartesian, sampleFreeformDirectional, blendSimpleDirectional } from './blend-2d';
import { sampleFreeformCartesian, blendSimpleDirectional, PolarSpaceGradientBandInterpolator2D } from './blend-2d';
import { CLASS_NAME_PREFIX_ANIM } from '../define';
import { AnimationGraphLayerWideBindingContext } from './animation-graph-context';
import { ReadonlyClipOverrideMap } from './graph-eval';
@@ -66,8 +66,18 @@ export class AnimationBlend2D extends AnimationBlend {
public static Item = AnimationBlend2DItem;
@serializable
public algorithm = Algorithm.SIMPLE_DIRECTIONAL;
@editable
public get algorithm () {
return this._algorithm;
}
public set algorithm (value) {
if (value === this._algorithm) {
return;
}
this._algorithm = value;
this._tryReconstructPolarSpaceInterpolator();
}
@serializable
private _items: AnimationBlend2DItem[] = [];
@@ -84,6 +94,7 @@ export class AnimationBlend2D extends AnimationBlend {
set items (items) {
this._items = Array.from(items);
this._tryReconstructPolarSpaceInterpolator();
}
public clone () {
@@ -92,19 +103,42 @@ export class AnimationBlend2D extends AnimationBlend {
that._items = this._items.map((item) => item?.clone() ?? null);
that.paramX = this.paramX.clone();
that.paramY = this.paramY.clone();
that.algorithm = this._algorithm;
return that;
}
public [createEval] (context: AnimationGraphLayerWideBindingContext, clipOverrides: ReadonlyClipOverrideMap | null) {
const evaluation = new AnimationBlend2DEval(
context,
clipOverrides,
this,
this._items,
this._items.map(({ threshold }) => threshold),
this.algorithm,
[0.0, 0.0],
);
const { algorithm } = this;
let evaluation: AnimationBlendEval;
switch (algorithm) {
case Algorithm.FREEFORM_DIRECTIONAL:
assertIsTrue(this._polarSpaceGBI, `The polar space interpolator is not setup correctly!`);
evaluation = new PolarSpaceGradientBandBlend2DEval(
context,
clipOverrides,
this,
this._items,
this._polarSpaceGBI,
[0.0, 0.0],
);
break;
default:
assertIsTrue(false);
// fallthrough
case Algorithm.SIMPLE_DIRECTIONAL:
case Algorithm.FREEFORM_CARTESIAN:
evaluation = new AnimationBlend2DEval(
context,
clipOverrides,
this,
this._items,
this._items.map(({ threshold }) => threshold),
algorithm,
[0.0, 0.0],
);
break;
}
const initialValueX = bindOr(
context.outerContext,
this.paramX,
@@ -125,6 +159,19 @@ export class AnimationBlend2D extends AnimationBlend {
evaluation.setInput(initialValueY, 1);
return evaluation;
}
@serializable
private _algorithm = Algorithm.SIMPLE_DIRECTIONAL;
private _polarSpaceGBI: PolarSpaceGradientBandInterpolator2D | undefined = undefined;
private _tryReconstructPolarSpaceInterpolator () {
if (this._algorithm === Algorithm.FREEFORM_DIRECTIONAL) {
this._polarSpaceGBI = new PolarSpaceGradientBandInterpolator2D(this._items.map((item) => item.threshold));
} else {
this._polarSpaceGBI = undefined;
}
}
}
export declare namespace AnimationBlend2D {
@@ -135,7 +182,7 @@ export declare namespace AnimationBlend2D {
class AnimationBlend2DEval extends AnimationBlendEval {
private _thresholds: readonly Vec2[];
private _algorithm: Algorithm;
private _algorithm: Algorithm.SIMPLE_DIRECTIONAL | Algorithm.FREEFORM_CARTESIAN;
private _value = new Vec2();
constructor (
@@ -144,7 +191,7 @@ class AnimationBlend2DEval extends AnimationBlendEval {
base: AnimationBlend,
items: AnimationBlendItem[],
thresholds: readonly Vec2[],
algorithm: Algorithm,
algorithm: Algorithm.SIMPLE_DIRECTIONAL | Algorithm.FREEFORM_CARTESIAN,
inputs: [number, number],
) {
super(context, clipOverrides, base, items, inputs);
@@ -163,11 +210,32 @@ class AnimationBlend2DEval extends AnimationBlendEval {
case Algorithm.FREEFORM_CARTESIAN:
sampleFreeformCartesian(weights, this._thresholds, this._value);
break;
case Algorithm.FREEFORM_DIRECTIONAL:
sampleFreeformDirectional(weights, this._thresholds, this._value);
break;
default:
break;
}
}
}
class PolarSpaceGradientBandBlend2DEval extends AnimationBlendEval {
private _interpolator: PolarSpaceGradientBandInterpolator2D;
private _value = new Vec2();
constructor (
context: AnimationGraphLayerWideBindingContext,
clipOverrides: ReadonlyClipOverrideMap | null,
base: AnimationBlend,
items: AnimationBlendItem[],
interpolator: PolarSpaceGradientBandInterpolator2D,
inputs: [number, number],
) {
super(context, clipOverrides, base, items, inputs);
this._interpolator = interpolator;
this.doEval();
}
protected eval (weights: number[], [x, y]: [number, number]) {
Vec2.set(this._value, x, y);
weights.fill(0);
this._interpolator.interpolate(weights, this._value);
}
}
+210 -54
View File
@@ -22,7 +22,7 @@
THE SOFTWARE.
*/
import { assertIsTrue, Vec2, Vec3 } from '../../core';
import { approx, assertIsTrue, Vec2, Vec3 } from '../../core';
/**
* Blends given samples using simple directional algorithm.
@@ -165,6 +165,26 @@ export class SimpleDirectionalIssueSameDirection {
public constructor (public samples: readonly number[]) { }
}
//#region Gradient Band Interpolation
/**
* In the following, two interpolation methods are implemented based on paper
* [rune_skovbo_johansen_thesis.pdf](https://runevision.com/thesis/rune_skovbo_johansen_thesis.pdf).
*
* - Gradient brand interpolation in Cartesian space.
*
* - Gradient brand interpolation in polar space.
*
* This is a variety of standard gradient brand interpolation
* which is suitable for velocity interpolation(the Cartesian one is not **WELL** suited as pointed out by the paper).
*
* This type of method requires a motion to be placed at origin and
* the angles between adjacent points to be greater than 180°.
*/
const _DEV_NOTE = false;
//#endregion
/**
* Cartesian Gradient Band Interpolation.
* @param weights
@@ -175,16 +195,6 @@ export function sampleFreeformCartesian (weights: number[], thresholds: readonly
sampleFreeform(weights, thresholds, value, getGradientBandCartesianCoords);
}
/**
* Polar Gradient Band Interpolation.
* @param weights
* @param thresholds
* @param value
*/
export function sampleFreeformDirectional (weights: number[], thresholds: readonly Vec2[], value: Readonly<Vec2>) {
sampleFreeform(weights, thresholds, value, getGradientBandPolarCoords);
}
function sampleFreeform (weights: number[], samples: readonly Vec2[], value: Readonly<Vec2>, getGradientBandCoords: GetGradientBandCoords) {
weights.fill(0.0);
const pIpInput = new Vec2(0, 0);
@@ -256,50 +266,196 @@ const getGradientBandCartesianCoords: GetGradientBandCoords = (pI, pJ, input, pI
Vec2.subtract(pIpJ, pJ, pI);
};
const getGradientBandPolarCoords = ((): GetGradientBandCoords => {
const axis = new Vec3(0, 0, 0); // buffer for axis
const tmpV3 = new Vec3(0, 0, 0); // buffer for temp vec3
const pQueriedProjected = new Vec3(0, 0, 0); // buffer for pQueriedProjected
const pi3 = new Vec3(0, 0, 0); // buffer for pi3
const pj3 = new Vec3(0, 0, 0); // buffer for pj3
const pQueried3 = new Vec3(0, 0, 0); // buffer for pQueried3
return (pI, pJ, input, pIpInput, pIpJ) => {
let aIJ = 0.0;
let aIQ = 0.0;
let angleMultiplier = 2.0;
Vec3.set(pQueriedProjected, input.x, input.y, 0.0);
if (Vec2.equals(pI, Vec2.ZERO)) {
aIJ = Vec2.angle(input, pJ);
aIQ = 0.0;
angleMultiplier = 1.0;
} else if (Vec2.equals(pJ, Vec2.ZERO)) {
aIJ = Vec2.angle(input, pI);
aIQ = aIJ;
angleMultiplier = 1.0;
const PRECOMPUTED_VIJ_DATA_STRIDE = 3;
/**
* The class tracking the polar space gradient band interpolation.
* For code readers, throughout the implementation:
* - Variable names like `V_IJ` denotes a vector pointing from example motion "I" to example motion "J";
* - Variable names like `V_IX` denotes a vector pointing from example motion "I" to new velocity being queried, which is properly named "X".
* For detail definitions see section 6.3 in [paper](https://runevision.com/thesis/rune_skovbo_johansen_thesis.pdf) .
*/
export class PolarSpaceGradientBandInterpolator2D {
private static _CACHE_INPUT_DIRECTION = new Vec2();
private static _CACHE_VIJ = new Vec2();
private static _CACHE_VIX = new Vec2();
private static _ANGLE_MULTIPLIER = 1.0;
constructor (examples: readonly Readonly<Vec2>[]) {
const {
_ANGLE_MULTIPLIER: angleMultiplier,
} = PolarSpaceGradientBandInterpolator2D;
const nExamples = examples.length;
const exampleMagnitudes = this._exampleMagnitudes = new Array<number>(nExamples).fill(0.0);
const exampleDirections = this._exampleDirections = examples.map((example, iExample) => {
const direction = Vec2.copy(new Vec2(), example);
const magnitude = Vec2.len(direction);
exampleMagnitudes[iExample] = magnitude;
if (!approx(magnitude, 0.0, 1e-5)) {
Vec2.multiplyScalar(direction, direction, 1.0 / magnitude);
}
return direction;
});
const precomputedVIJs = this._precomputedVIJs = new Float32Array(PRECOMPUTED_VIJ_DATA_STRIDE * nExamples * nExamples);
for (let iExample = 0; iExample < nExamples; ++iExample) {
const magnitudeI = exampleMagnitudes[iExample];
const directionI = exampleDirections[iExample];
for (let jExample = 0; jExample < nExamples; ++jExample) {
if (iExample === jExample) {
continue;
}
const magnitudeJ = exampleMagnitudes[jExample];
const directionJ = exampleDirections[jExample];
const averagedMagnitude = (magnitudeI + magnitudeJ) / 2;
const pOutput = PRECOMPUTED_VIJ_DATA_STRIDE * (nExamples * iExample + jExample);
precomputedVIJs[pOutput + 0] = (magnitudeJ - magnitudeI) / averagedMagnitude;
precomputedVIJs[pOutput + 1] = signedAngle(directionI, directionJ) * angleMultiplier;
precomputedVIJs[pOutput + 2] = averagedMagnitude;
}
}
this._cacheVIXAngles = new Float32Array(nExamples);
}
public interpolate (weights: number[], input: Readonly<Vec2>) {
const {
_exampleDirections: exampleDirections,
_exampleMagnitudes: exampleMagnitudes,
_precomputedVIJs: precomputedVIJs,
_cacheVIXAngles: cacheVIXAngles,
} = this;
const {
_CACHE_INPUT_DIRECTION: cacheInputDirection,
_CACHE_VIJ: cacheVIJ,
_CACHE_VIX: cacheVIX,
_ANGLE_MULTIPLIER: angleMultiplier,
} = PolarSpaceGradientBandInterpolator2D;
const nExamples = exampleDirections.length;
assertIsTrue(weights.length === nExamples);
// Specially handle 0/1 sample case, the algorithm is not defined for them.
if (nExamples === 0) {
return;
} else if (nExamples === 1) {
weights[0] = 1.0;
return;
}
const vX = input;
const magnitudeX = Vec2.len(vX);
// Calculate $\angle(v_i, v_x) * \alpha$ for each example.
// If either vector is zero, the angle is defined as zero.
const vIXAngles = cacheVIXAngles;
if (Vec2.equals(vX, Vec2.ZERO)) {
for (let iExample = 0; iExample < nExamples; ++iExample) {
vIXAngles[iExample] = 0.0;
}
} else {
aIJ = Vec2.angle(pI, pJ);
if (aIJ <= 0.0) {
aIQ = 0.0;
} else if (Vec2.equals(input, Vec2.ZERO)) {
aIQ = aIJ;
} else {
Vec3.set(pi3, pI.x, pI.y, 0);
Vec3.set(pj3, pJ.x, pJ.y, 0);
Vec3.set(pQueried3, input.x, input.y, 0);
Vec3.cross(axis, pi3, pj3);
Vec3.projectOnPlane(pQueriedProjected, pQueried3, axis);
aIQ = Vec3.angle(pi3, pQueriedProjected);
if (aIJ < Math.PI * 0.99) {
if (Vec3.dot(Vec3.cross(tmpV3, pi3, pQueriedProjected), axis) < 0) {
aIQ = -aIQ;
}
const directionX = Vec2.multiplyScalar(cacheInputDirection, vX, 1.0 / magnitudeX);
for (let iExample = 0; iExample < nExamples; ++iExample) {
const directionI = exampleDirections[iExample];
if (Vec2.equals(directionI, Vec2.ZERO)) {
vIXAngles[iExample] = 0.0;
} else {
vIXAngles[iExample] = signedAngle(directionI, directionX) * angleMultiplier;
}
}
}
const lenPI = Vec2.len(pI);
const lenPJ = Vec2.len(pJ);
const deno = (lenPJ + lenPI) / 2;
Vec2.set(pIpJ, (lenPJ - lenPI) / deno, aIJ * angleMultiplier);
Vec2.set(pIpInput, (Vec3.len(pQueriedProjected) - lenPI) / deno, aIQ * angleMultiplier);
};
})();
// The polar space gradient band interpolation.
let totalWeight = 0.0;
for (let iExample = 0; iExample < nExamples; ++iExample) {
const magnitudeI = exampleMagnitudes[iExample];
const directionI = exampleDirections[iExample];
let minInfluence = Number.POSITIVE_INFINITY; // 1 - Math.abs(vIXAngles[iExample]) / Math.PI;
for (let jExample = 0; jExample < nExamples; ++jExample) {
if (iExample === jExample) {
continue;
}
const directionJ = exampleDirections[jExample];
const precomputedDataIndex = PRECOMPUTED_VIJ_DATA_STRIDE * (nExamples * iExample + jExample);
const {
[precomputedDataIndex + 0]: vIJMag,
[precomputedDataIndex + 1]: vIJAnglePrecomputed,
[precomputedDataIndex + 2]: averagedMagnitude,
} = precomputedVIJs;
let vIJAngle = vIJAnglePrecomputed;
let vIXAngle = vIXAngles[iExample];
// Handle zero cases:
// - If $v_i$(or $v_j$) is zero vector,
// the angle between v_i_j is defined to be the angle between $v_x$ and $v_j$(or $v_i$).
// - If $v_x$ is zero vector,
// the angle between v_i_x is defined to be the angle between $v_i$ and $v_j$.
if (Vec2.equals(directionI, Vec2.ZERO)) {
vIJAngle = vIXAngles[jExample];
// And `vIXAngle` is 0 as computed above.
} else if (Vec2.equals(directionJ, Vec2.ZERO)) {
vIJAngle = vIXAngles[iExample];
} else if (Vec2.equals(vX, Vec2.ZERO)) {
vIXAngle = vIJAngle;
}
const vIJ = Vec2.set(cacheVIJ, vIJMag, vIJAngle);
const vIX = Vec2.set(
cacheVIX,
(magnitudeX - magnitudeI) / averagedMagnitude,
vIXAngle,
);
// Calculate the influence.
// Note we can't cache `len(vIJ)` due to above process of `vIJ.y`!
const influence = 1.0 - Vec2.dot(vIX, vIJ) / Vec2.lengthSqr(vIJ);
if (influence <= 0) { // The input is outside hull.
minInfluence = 0.0;
break; // No more iteration.
}
minInfluence = Math.min(minInfluence, influence);
}
weights[iExample] = minInfluence;
totalWeight += minInfluence;
}
// Normalize the weights.
if (totalWeight > 0) {
for (let iExample = 0; iExample < nExamples; ++iExample) {
weights[iExample] /= totalWeight;
}
} else {
// This can happen if there no example at origin and the input is origin.
// Just average weight to all examples.
const averaged = 1.0 / nExamples;
for (let iExample = 0; iExample < nExamples; ++iExample) {
weights[iExample] = averaged;
}
}
}
private declare _exampleDirections: Vec2[];
private declare _exampleMagnitudes: number[];
/**
* n*n Precomputed (\vec{p_i}{p_j}, (|p_i| + |p_j|) / 2).
*/
private declare _precomputedVIJs: Float32Array;
private declare _cacheVIXAngles: Float32Array;
}
function signedAngle (v1: Readonly<Vec2>, v2: Readonly<Vec2>) {
const angle = Vec2.angle(v1, v2);
const determinate = v1.x * v2.y - v1.y * v2.x;
return determinate < 0 ? -angle : angle;
}
@@ -0,0 +1,213 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Polar space gradient brand interpolation Algorithm The input's direction is between two different direction examples The examples have different magnitude 1`] = `
Object {
"Equal to the bigger magnitude": Object {
"ccw": 0.3168596289437383,
"cw": 0.6502105566924706,
"origin": 0.03292981436379107,
},
"Equal to the middle magnitude": Object {
"ccw": 0.2989265859181596,
"cw": 0.5902714914805254,
"origin": 0.110801922601315,
},
"Equal to the minor magnitude": Object {
"ccw": 0.28366638688732265,
"cw": 0.5392660896894322,
"origin": 0.17706752342324497,
},
"Greater than the bigger magnitude": Object {
"ccw": 0.30491192209599804,
"cw": 0.695088077904002,
},
"Less than both magnitudes": Object {
"ccw": 0.16486765633781594,
"cw": 0.15973168002542656,
"origin": 0.6754006636367574,
},
}
`;
exports[`Polar space gradient brand interpolation Algorithm The input's direction is between two different direction examples The examples have same magnitude 1`] = `
Object {
"Greater than the mag": Object {
"ccw": 0.33333333333333337,
"cw": 0.6666666666666667,
},
"Greater than the mag again": Object {
"ccw": 0.33333333333333337,
"cw": 0.6666666666666667,
},
"Input at just the mag": Object {
"ccw": 0.3205352705404605,
"cw": 0.641070541080921,
"origin": 0.03839418837861866,
},
"Less then the mag.": Object {
"ccw": 0.1648595779760476,
"cw": 0.1965831709644441,
"origin": 0.6385572510595082,
},
}
`;
exports[`Polar space gradient brand interpolation Algorithm There are multiple examples along the input's direction 1`] = `
Object {
"Input at 1/3 minor mag": Object {
"ccw": 0.08602309330508458,
"cw": 0.05841787524451817,
"origin": 0.5703726924902929,
"same_dir_example_1": 0.2851863389601044,
},
"Input at bigger mag example": Object {
"same_dir_example_2": 0.9999999767855615,
},
"Input at minor mag example": Object {
"same_dir_example_1": 0.9999999717541427,
},
"Input between the examples": Object {
"same_dir_example_1": 0.6666666589285206,
"same_dir_example_2": 0.3333333410714793,
},
"Input beyond bigger mag example": Object {
"same_dir_example_2": 1,
},
}
`;
exports[`Polar space gradient brand interpolation Algorithm There is and is only one example along the input's direction The adjacent examples have different mag 1`] = `
Object {
"Input at 1/3 mag": Object {
"cw": 0.02054480721915246,
"origin": 0.6529701236555586,
"the_dir": 0.32648506912528885,
},
"Input at the example": Object {
"the_dir": 0.9999999848019046,
},
"Input beyond the example": Object {
"the_dir": 1,
},
}
`;
exports[`Polar space gradient brand interpolation Algorithm There is and is only one example along the input's direction The adjacent examples have same mag 1`] = `
Object {
"Input at 1/3 mag": Object {
"origin": 0.6666666616996132,
"the_dir": 0.33333333830038686,
},
"Input at the example": Object {
"the_dir": 0.9999999850988393,
},
"Input beyond the example": Object {
"the_dir": 1,
},
}
`;
exports[`Polar space gradient brand interpolation Algorithm There is and is only one example along the input's direction the adjacent examples have different mag, the direction is on axis 1`] = `
Object {
"Input at 1/3 mag": Object {
"origin": 0.6666666616996132,
"the_dir": 0.33333333830038686,
},
"Input at the example": Object {
"the_dir": 0.9999999850988393,
},
"Input beyond the example": Object {
"cw_adjacent": 0.31394171978396535,
"the_dir": 0.6860582802160347,
},
}
`;
exports[`Polar space gradient brand interpolation There is more than 180° between two adjacent examples points: Between 1, 2 1`] = `
Object {
"Equal magnitude": Object {
"example_1": 0.7939990314904765,
"example_2": 0.19849978329369805,
"origin": 0.007501185215825347,
},
"Longer magnitude": Object {
"example_1": 0.7999999795094334,
"example_2": 0.20000002049056667,
},
"Shorter magnitude": Object {
"example_1": 0.6616280659241143,
"example_2": 0.1666666856394138,
"origin": 0.171705248436472,
},
}
`;
exports[`Polar space gradient brand interpolation There is more than 180° between two adjacent examples points: Between 2, 3 1`] = `
Object {
"Equal magnitude": Object {
"example_2": 0.7443741424354346,
"example_3": 0.24812467177667524,
"origin": 0.007501185787890177,
},
"Longer magnitude": Object {
"example_2": 0.7500000320165141,
"example_3": 0.24999996798348595,
},
"Shorter magnitude": Object {
"example_2": 0.6218666935060354,
"example_3": 0.20728886243978442,
"origin": 0.17084444405418012,
},
}
`;
exports[`Polar space gradient brand interpolation There is more than 180° between two adjacent examples points: In the more-than-180 range, in the middle 1`] = `
Object {
"Equal magnitude": Object {
"example_1": 0.09981031755884037,
"example_2": 0.8982930455035218,
"origin": 0.0018966369376378289,
},
"Longer magnitude": Object {
"example_1": 0.09999998121697959,
"example_2": 0.9000000187830204,
},
"Shorter magnitude": Object {
"example_1": 0.0909090739747374,
"example_2": 0.7258907473599425,
"origin": 0.18320017866531998,
},
}
`;
exports[`Polar space gradient brand interpolation There is more than 180° between two adjacent examples points: In the more-than-180 range, tending to 1 1`] = `
Object {
"Equal magnitude": Object {
"example_3": 0.8400637213479694,
"origin": 0.15993627865203064,
},
"Longer magnitude": Object {
"example_3": 1,
},
"Shorter magnitude": Object {
"example_3": 0.6720509770783756,
"origin": 0.3279490229216244,
},
}
`;
exports[`Polar space gradient brand interpolation There is more than 180° between two adjacent examples points: In the more-than-180 range, tending to 3 1`] = `
Object {
"Equal magnitude": Object {
"example_3": 0.8400637213479694,
"origin": 0.15993627865203064,
},
"Longer magnitude": Object {
"example_3": 1,
},
"Shorter magnitude": Object {
"example_3": 0.6720509770783756,
"origin": 0.3279490229216244,
},
}
`;
@@ -1,6 +1,7 @@
import { Vec2 } from "../../../../cocos/core";
import { sampleFreeformDirectional, blendSimpleDirectional } from "../../../../cocos/animation/marionette/blend-2d";
import { approx, clamp01, lerp, toRadian, v2, Vec2 } from "../../../../cocos/core";
import { blendSimpleDirectional, PolarSpaceGradientBandInterpolator2D } from "../../../../cocos/animation/marionette/blend-2d";
import '../../../utils/matcher-deep-close-to';
import '../../../utils/matchers/value-type-asymmetric-matchers';
const EXPECT_NUM_DIGITS = 5;
@@ -190,4 +191,325 @@ describe('Simple directional 2D', () => {
sampleTriangleVertexB: 0.3781,
}), EXPECT_NUM_DIGITS);
});
});
});
describe(`Polar space gradient brand interpolation`, () => {
test(`No example`, () => {
runInPlace(Vec2.ZERO, []);
runInPlace(v2(1., 2.), []);
});
test(`Single example`, () => {
/**
* ### Spec
*
* If there is only one example, that example is used with full weight regardless of the input.
*/
const _SPEC = undefined;
runInPlace(Vec2.ZERO, [[Vec2.ZERO, 1.0]]);
runInPlace(Vec2.ZERO, [[v2(1., 2.), 1.0]]);
runInPlace(v2(1., -2.), [[Vec2.ZERO, 1.0]]);
runInPlace(v2(1., -2.), [[v2(3., 4.), 1.0]]);
});
test.todo(`Two examples`);
describe(`Zero vector input`, () => {
/**
* ### Spec
*
* If the input is zero vector, then:
* - if there is an example at origin, that motion has full weight.
* - otherwise, all motion has even weight.
*/
const _SPEC = undefined;
test(`Having example at origin`, () => {
runInPlace(Vec2.ZERO, [
[v2(1.0, 0.0), 0.0],
[v2(0.0, 0.0), 1.0],
[v2(-1.0, 0.0), 0.0],
[v2(0.0, 1.0), 0.0],
[v2(0.0, -1.0), 0.0],
]);
});
test(`No example at origin`, () => {
runInPlace(Vec2.ZERO, [
[v2(1.0, 0.0), 0.25],
[v2(-1.0, 0.0), 0.25],
[v2(0.0, 1.0), 0.25],
[v2(0.0, -1.0), 0.25],
]);
});
});
describe(`Algorithm`, () => {
describe(`There is and is only one example along the input's direction`, () => {
test(`The adjacent examples have different mag`, () => {
const fixture = {
input_dir: 30.,
example_magnitude: 0.8,
ccw: { mag: 0.8, dir: 30. + 160. },
cw: { mag: 0.8 * 0.8, dir: 30. + 200. },
};
const examples = {
origin: polar(0.0, 0.0),
the_dir: polar(fixture.example_magnitude, fixture.input_dir),
cw: polar(fixture.cw.mag, fixture.cw.dir),
ccw: polar(fixture.ccw.mag, fixture.ccw.dir),
} as const;
expect(groupByMagnitude(
(mag) => sampleNamed(examples, polar(mag, fixture.input_dir)),
[fixture.example_magnitude / 3., 'Input at 1/3 mag'],
[fixture.example_magnitude, 'Input at the example'],
[fixture.example_magnitude * 1.1, 'Input beyond the example'],
)).toMatchSnapshot();
});
test(`The adjacent examples have same mag`, () => {
const fixture = {
input_dir: 30.,
example_magnitude: 0.8,
};
const examples = {
origin: polar(0.0, 0.0),
the_dir: polar(fixture.example_magnitude, fixture.input_dir),
_1: polar(fixture.example_magnitude, fixture.input_dir + 160.),
_2: polar(fixture.example_magnitude, fixture.input_dir + 200.),
} as const;
expect(groupByMagnitude(
(mag) => sampleNamed(examples, polar(mag, fixture.input_dir)),
[fixture.example_magnitude / 3., 'Input at 1/3 mag'],
[fixture.example_magnitude, 'Input at the example'],
[fixture.example_magnitude * 5., 'Input beyond the example'],
)).toMatchSnapshot();
});
test(`the adjacent examples have different mag, the direction is on axis`, () => {
const fixture = {
input_dir: 0.0,
example_magnitude: 0.8,
ccw_adjacent_magnitude: 0.8,
cw_adjacent_magnitude: 1.0,
};
const examples = {
origin: polar(0.0, 0.0),
the_dir: polar(fixture.example_magnitude, fixture.input_dir),
ccw_adjacent: polar(fixture.ccw_adjacent_magnitude, fixture.input_dir + 90.),
_2: polar(fixture.example_magnitude, fixture.input_dir + 180.),
cw_adjacent: polar(fixture.cw_adjacent_magnitude, fixture.input_dir + 270.),
} as const;
expect(groupByMagnitude(
(mag) => sampleNamed(examples, polar(mag, fixture.input_dir)),
[fixture.example_magnitude / 3., 'Input at 1/3 mag'],
[fixture.example_magnitude, 'Input at the example'],
[fixture.example_magnitude * 5., 'Input beyond the example'],
)).toMatchSnapshot();
});
});
test(`There are multiple examples along the input's direction`, () => {
const fixture = {
input_dir: 30.,
mag_1: 0.7,
mag_2: 1.2,
ccw: { mag: 0.5, dir: 120.0 },
cw: { mag: 0.5, dir: -80.0 },
};
const examples = {
origin: polar(0.0, 0.0),
same_dir_example_1: polar(fixture.mag_1, fixture.input_dir),
same_dir_example_2: polar(fixture.mag_2, fixture.input_dir),
ccw: polar(fixture.ccw.mag, fixture.ccw.dir),
cw: polar(fixture.cw.mag, fixture.cw.dir),
} as const;
expect(groupByMagnitude(
(mag) => sampleNamed(examples, polar(mag, fixture.input_dir)),
[fixture.mag_1 / 3., 'Input at 1/3 minor mag'],
[fixture.mag_1, 'Input at minor mag example'],
[fixture.mag_1 + (fixture.mag_2 - fixture.mag_1) / 3, 'Input between the examples'],
[fixture.mag_2, 'Input at bigger mag example'],
[fixture.mag_2 * 1.2, 'Input beyond bigger mag example'],
)).toMatchSnapshot();
});
describe(`The input's direction is between two different direction examples`, () => {
test(`The examples have same magnitude`, () => {
const fixture = {
cw_ccw_mag: 0.8,
ccw_dir: 90.0,
ccw_adjacent: { dir: 95.0, mag: 1.0 },
cw_dir: 0.0,
cw_adjacent: { dir: -20.0, mag: 0.7 },
input_dir_1_ratio: clamp01(1. / 3.),
input_dir_2_ratio: clamp01(2. / 3.),
};
const inputDir1 = (fixture.ccw_dir - fixture.cw_dir) * fixture.input_dir_1_ratio;
const inputDir2 = (fixture.ccw_dir - fixture.cw_dir) * fixture.input_dir_2_ratio;
const examples = {
origin: polar(0.0, 0.0),
ccw: polar(fixture.cw_ccw_mag, fixture.ccw_dir),
ccw_adjacent: polar(fixture.ccw_adjacent.mag, fixture.ccw_adjacent.dir),
cw: polar(fixture.cw_ccw_mag, fixture.cw_dir),
cw_adjacent: polar(fixture.cw_adjacent.mag, fixture.cw_adjacent.dir),
_1: polar(0.65, 180.0),
_2: polar(1.0, 270.0),
} as const;
expect(groupByMagnitude(
(mag) => sampleNamed(examples, polar(mag, inputDir1)),
[fixture.cw_ccw_mag / 4., 'Less then the mag.'],
[fixture.cw_ccw_mag, 'Input at just the mag'],
[fixture.cw_ccw_mag * 1.1, `Greater than the mag`],
// This also suggests when the input has magnitude greater than examples', only direction takes effect.
[fixture.cw_ccw_mag * 1.25, `Greater than the mag again`],
)).toMatchSnapshot();
// Input at just the mag, at dir 2.
expect(sampleNamed(examples, polar(fixture.cw_ccw_mag, inputDir2))).toMatchInlineSnapshot(`
Object {
"ccw": 0.6264824128043105,
"cw": 0.31324120640215525,
"origin": 0.060276380793534215,
}
`);
});
test(`The examples have different magnitude`, () => {
const fixture = {
cw: { mag: 0.8, dir: 90.0 },
ccw: { mag: 0.65, dir: 180.0 },
input_dir: 120.0,
};
const examples = {
origin: polar(0.0, 0.0),
ccw: polar(fixture.ccw.mag, fixture.ccw.dir),
cw: polar(fixture.cw.mag, fixture.cw.dir),
_1: polar(0.8, 0.0),
_2: polar(1.0, 270.0),
} as const;
expect(fixture.ccw.mag).toBeLessThan(fixture.cw.mag);
expect(groupByMagnitude(
(mag) => sampleNamed(examples, polar(mag, fixture.input_dir)),
[fixture.ccw.mag / 4, 'Less than both magnitudes'],
[fixture.ccw.mag, 'Equal to the minor magnitude'],
[fixture.ccw.mag + (fixture.cw.mag - fixture.ccw.mag) / 2, 'Equal to the middle magnitude'],
[fixture.cw.mag, 'Equal to the bigger magnitude'],
[fixture.cw.mag * 1.25, 'Greater than the bigger magnitude'],
)).toMatchSnapshot();
});
});
});
test(`There is more than 180° between two adjacent examples points`, () => {
const fixture = {
example_1: { mag: 0.5, dir: 40.0 },
example_2: { mag: 0.5, dir: 90.0 },
example_3: { mag: 0.5, dir: 130.0 },
} as const;
const examples = {
origin: polar(0., 0.),
example_1: polar(fixture.example_1.mag, fixture.example_1.dir),
example_2: polar(fixture.example_2.mag, fixture.example_2.dir),
example_3: polar(fixture.example_3.mag, fixture.example_3.dir),
} as const;
const sampleAtEachMag = (direction: number) => {
return groupByMagnitude(
(mag) => sampleNamed(examples, polar(mag, direction)),
[fixture.example_2.mag * 0.8, 'Shorter magnitude'],
[fixture.example_2.mag, 'Equal magnitude'],
[fixture.example_2.mag * 1.2, `Longer magnitude`],
);
};
expect(sampleAtEachMag(50.0)).toMatchSnapshot(`Between 1, 2`);
expect(sampleAtEachMag(100.0)).toMatchSnapshot(`Between 2, 3`);
expect(sampleAtEachMag(180.0)).toMatchSnapshot(`In the more-than-180 range, tending to 3`);
expect(sampleAtEachMag(lerp(fixture.example_3.dir, fixture.example_1.dir, 0.5))).toMatchSnapshot(
`In the more-than-180 range, in the middle`,
);
expect(sampleAtEachMag(180.0)).toMatchSnapshot(`In the more-than-180 range, tending to 1`);
});
function runInPlace(input: Readonly<Vec2>, examplePositionAndExpectedWeights: readonly [position: Readonly<Vec2>, expectedWeight: number][]) {
const examplePositions = examplePositionAndExpectedWeights.map(([position]) => position);
const expectedWeights = examplePositionAndExpectedWeights.map(([_, weight]) => weight);
const interpolation = new PolarSpaceGradientBandInterpolator2D(examplePositions);
const actualWeights = new Array<number>(examplePositions.length);
interpolation.interpolate(actualWeights, input);
expect(actualWeights).toMatchObject(expectedWeights.map((w) => expect.toBeAround(w, EXPECT_NUM_DIGITS)));
}
function sampleNamed<TExampleName extends string>(
examples: Readonly<Record<TExampleName, Readonly<Vec2>>>,
input: Readonly<Vec2>,
) {
return sample2DNamed(
(weights, examplePositions, input) => {
const interpolation = new PolarSpaceGradientBandInterpolator2D(examplePositions);
interpolation.interpolate(weights, input);
},
examples,
input,
);
}
function polar(magnitude: number, thetaDeg: number) {
const theta = toRadian(thetaDeg);
return v2(magnitude * Math.cos(theta), magnitude * Math.sin(theta));
}
function groupByMagnitude<T>(mapper: (mag: number) => T, ...magnitudes: (number | readonly [mag: number, title: string])[]) {
return magnitudes.reduce((result, mag) => {
const k = Array.isArray(mag) ? mag[1] : `Magnitude ${mag}`;
result[k] = mapper(Array.isArray(mag) ? mag[0] : mag);
return result;
}, {} as Record<string, T>);
}
});
function sample2DNamed<TExampleName extends string>(
fn: (weights: number[], examplePositions: readonly Readonly<Vec2>[], input: Readonly<Vec2>) => void,
examples: Readonly<Record<TExampleName, Readonly<Vec2>>>,
input: Readonly<Vec2>,
) {
const exampleEntries = Object.entries(examples) as [TExampleName, Readonly<Vec2>][];
const examplePositions = exampleEntries.map(([_, position]) => position);
const actualWeights = new Array<number>(examplePositions.length);
actualWeights.fill(0.0);
fn(actualWeights, examplePositions, input);
const actualWeightsNamed = exampleEntries.reduce((result, [name], index) => {
const actualWeight = actualWeights[index];
if (approx(actualWeight, 0.0, 1e-5)) {
return result;
}
result[name] = actualWeight;
return result;
}, {} as Record<string, number>);
return actualWeightsNamed;
}