All files transform.mjs

93.93% Statements 62/66
72.22% Branches 13/18
83.33% Functions 15/18
93.33% Lines 56/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228                  13x 5x   13x                       5x 5x                         2x                       12x 12x 12x 22x 22x 22x 27x   22x         12x     1x         1x                                                   13x                 7x 7x 13x           13x 13x   7x                           12x 12x 12x 12x 3x                           3x 3x   3x 3x 3x                                         12x 12x 12x 12x     3x   3x 3x   2x             1x 1x         1x           1x 5x 25x 25x   25x   25x 25x 25x 25x 25x         1x            
import { Matrix } from "./matrix.mjs";
import { setPixel, getPixel } from "./bitmap.mjs";
 
/**
 * 
 * @param {number} x
 * @param {number} y
 */
export function scale(x, y) {
    if (y === undefined) {
        y = x;
    }
    return new Matrix(3, 3, new Float32Array([
        x, 0, 0,
        0, y, 0,
        0, 0, 1,
    ]));
}
 
/**
 * 
 * @param {number} degrees 
 */
export function rotate(degrees) {
    const radians = degrees * Math.PI / 180;
    return new Matrix(3, 3, new Float32Array([
        Math.cos(radians), -Math.sin(radians), 0,
        Math.sin(radians), Math.cos(radians), 0,
        0, 0, 1,
    ]));
}
 
/**
 * 
 * @param {number} x 
 * @param {number} y 
 */
export function translate(x, y) {
    return new Matrix(3, 3, new Float32Array([
        1, 0, x,
        0, 1, y,
        0, 0, 1,
    ]));
}
 
/**
 * 
 * @param {string} commands 
 */
export function parseTransformCommands(commands) {
    const matches = commands.matchAll(/(\w+)\(([^\)]*)\)/g);
    const commandList = [];
    for (let match of matches) {
        const inputMatches =  match[2].matchAll(/(\-?\d+\.?\d*)(\s*,|\s*$)/g);
        const inputs = [];
        for (let inputMatch of inputMatches) {
            inputs.push(parseFloat(inputMatch[1]));
        }
        commandList.push({
            name: match[1],
            inputs: /** @type {[number, number]} */ (inputs),
        });
    }
    return commandList;
}
 
const commandMap = {
    'scale': scale,
    /**
     * @param {number} x 
     */
    'scaleX': (x) => scale(x, 1),
    /**
     * @param {number} y 
     */
    'scaleY': (y) => scale(1, y),
    'rotate': rotate,
    'translate': translate,
    /**
     * @param {number} x 
     */
    'translateX': (x) => translate(x, 0),
    /**
     * @param {number} y 
     */
    'translateY': (y) => translate(0, y),
}
 
/**
 * @typedef {keyof typeof commandMap} CommandName
 */
 
/**
 * @param {string} name
 * @returns {name is CommandName} 
 */
function isValidCommand(name) {
    return name in commandMap;
}
 
/**
 * 
 * @param {string} commands
 * @return {Matrix}
 */
export function computeTransformMatrix(commands) {
    let transformMatrix = scale(1, 1);
    for (const {inputs, name} of parseTransformCommands(commands)) {
        Iif (!isValidCommand(name)) {
            throw Error(`Unsupported command provided to transform: ${name}`);
        }
        /**
         * @type {Matrix}
         */
        const rightMatrix = commandMap[name](...(inputs));
        transformMatrix = transformMatrix.multiply(rightMatrix);
    }
    return transformMatrix;
}
 
/**
 * 
 * @param {Matrix[]} extrema
 * @returns {{
 *  top: number;
 *  right: number;
 *  bottom: number;
 *  left: number;
 * }}
 */
export function computeBoundingBox(extrema) {
    const left = Math.min(...extrema.map(m => m.get(0, 0)))|0;
    const top = Math.min(...extrema.map(m => m.get(0, 1)))|0;
    const right = Math.ceil(Math.max(...extrema.map(m => m.get(0, 0))));
    const bottom = Math.ceil(Math.max(...extrema.map(m => m.get(0, 1))));
    return {
        top,
        right,
        bottom,
        left,
    }
}
 
/**
 * @param {ImageData} imageData
 * @param {string} commands 
 * @param {[number, number]=} origin 
 */
export function transform(imageData, commands, origin) {
    Eif (!origin) {
        origin = [(imageData.width/2)|0, (imageData.height/2)|0];
    }
    const transformMatrix = computeTransformMatrix(commands);
    const [originX, originY] = origin;
    const extrema = [
        new Matrix(3, 1, new Float32Array([
            0 - originX,
            0 - originY,
            1,
        ])),
        new Matrix(3, 1, new Float32Array([
            imageData.width - 1 - originX,
            0 - originY,
            1,
        ])),
        new Matrix(3, 1, new Float32Array([
            0 - originX,
            imageData.height - 1 - originY,
            1,
        ])),
        new Matrix(3, 1, new Float32Array([
            imageData.width - 1 - originX,
            imageData.height - 1 - originY,
            1,
        ])),
    ].map(m => transformMatrix.multiply(m)).map(m => {
        m.set(0, 0, m.get(0, 0) + originX);
        m.set(0, 1, m.get(0, 1) + originY);
        return m;
    });
 
    const {top, right, bottom, left} = computeBoundingBox(extrema);
    // The ImageData constructor doesn't permit images with a dimension of 0
    const newImageData = new ImageData((right - left + 1) || 1, (bottom - top + 1) || 1);
    if (Math.abs(transformMatrix.det()) < Number.EPSILON) {
        // The transform matrix is singular. This can only occur if it's scaled to 0.
        return {
            newImageData,
            left,
            top,
        }
    }
 
    const inverseTransformMatrix = transformMatrix.inverse();
    const positionVector = new Matrix(3, 1, new Float32Array([
        0,
        0,
        1,
    ]));
    const originalPosition = new Matrix(3, 1, new Float32Array([
        0,
        0,
        1,
    ]));
 
    for (let row = top; row <= bottom; row++) {
        for (let col = left; col <= right; col++) {
            positionVector.set(0, 0, col - originX);
            positionVector.set(0, 1, row - originY);
 
            inverseTransformMatrix.multiply(positionVector, originalPosition);
 
            const originalX = Math.round(originalPosition.get(0, 0) + originX);
            const originalY = Math.round(originalPosition.get(0, 1) + originY);
            const outsideImageBounds = originalX < 0 || originalY < 0 || originalX >= imageData.width || originalY >= imageData.height;
            Eif (!outsideImageBounds) {
                setPixel(newImageData, col - left, row - top, getPixel(imageData, originalX, originalY));
            }
        }
    }
 
    return {
        newImageData,
        left,
        top,
    };
}