Skip to content
Verified contractPartialApache-2.0

PencilRenderer

Address0xb2c0fc9247b20b455ea05600020ce916d3e55cc3
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
Apache-2.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,267,246
Creation transaction
0x364d5a8b1a…5529d6ac49
Libraries
src/PencilRenderer.sol:PencilRaster0xd2e6…04967e

src/PencilRenderer.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

pragma solidity ^0.8.13;

import "./ITokenRenderer.sol";
import "./raster/PencilRaster.sol";
import "./png/graphics/IPNGEncoder.sol";
import "./png/graphics/Animation.sol";
import "./png/vendor/DynamicBuffer.sol";

/* =============================================================================
 *  PENCILRENDERER · the pencil family's ITokenRenderer and window lane
 * =============================================================================
 *
 * A registry binds one interpreter and one image renderer to each project.
 * The interpreter turns a program into a draw stream. The image renderer
 * turns that stream into ERC721 metadata. Each renderer serves ONE family.
 * This renderer serves the pencil family (render family 6). It renders the
 * canonical draw stream with PencilRaster, the on-chain rasterizer of the
 * family, byte for byte equal to the reference oracle.
 *
 * ROLE. A registry requires an image renderer at publish time and binds it
 * WRITE-ONCE. This contract fills that role for pencil pieces. A pencil
 * render is per-pixel work with per-pixel state (paper tooth, wax,
 * per-channel density) that every stroke carries forward, plus a paper of
 * 2,600 fibres walked in Fix64. `tokenDataURI` renders the whole frame in
 * one call, so it fits only a small canvas in the gas of one eth_call. A
 * real sheet comes through `renderWindow`, one tile per call.
 *
 * TILES AND THE APRON. Pencil state crosses records, so a tile renders over
 * a work window that is `apron` px larger on every side (clamped to the
 * canvas), and the tile is cut out of it. A tile equals the full frame
 * exactly where the apron covers the dependency depth: 2 px for each stroke
 * that overlaps the edge region of the tile, plus 1 px for the softening of
 * the scanner. A zero window is the whole canvas, exact everywhere. That is
 * what `tokenDataURI` renders.
 *
 * REVERT, NEVER SUBSTITUTE. A record outside the family (background, path,
 * stamp, field, mesh) reverts. A frame too large for the gas of the call
 * reverts. It never returns an image that is not the canonical render.
 *
 * NO CONFIGURATION. PencilRaster is a linked library and takes no render
 * options. The stream fully determines the image.
 */
contract PencilRenderer is ITokenRenderer {
    /// The shared PNG encoder, resolved by chain id (mainnet and mainnet forks
    /// to the mainnet deployment, Sepolia to its twin). No local copy.
    IPNGEncoder public immutable png;

    constructor() {
        png = IPNGEncoder(pngEncoderFor(block.chainid));
    }

    /// @notice Full ERC721 metadata as a data:application/json;base64 URI.
    ///         The image is a data:image/png;base64 URI, rendered on chain
    ///         from the token's canonical draw stream.
    /// @dev Reverts on a record outside the pencil family, or if the frame
    ///      needs more gas than the call has.
    /// @param tokenId     Added to the metadata name as " #<tokenId>".
    /// @param projectName The collection name, escaped, placed before the
    ///                    token id.
    /// @param stream      The token's canonical draw stream.
    /// @return The metadata JSON as a self-contained data URI.
    function tokenDataURI(uint256 tokenId, string calldata projectName, bytes calldata stream)
        external
        view
        returns (string memory)
    {
        bytes memory pngUri;
        {
            (uint32 w, uint32 h, bytes memory rgba) = PencilRaster.render(stream, 0, 0, 0, 0, 0);
            pngUri = _png(w, h, rgba);
        }

        bytes memory name = _jsonEscape(bytes(projectName));
        bytes memory idStr = _toString(tokenId);
        bytes memory json = DynamicBuffer.allocate(64 + name.length + idStr.length + pngUri.length);
        DynamicBuffer.appendSafe(json, '{"name":"');
        DynamicBuffer.appendSafe(json, name);
        DynamicBuffer.appendSafe(json, " #");
        DynamicBuffer.appendSafe(json, idStr);
        DynamicBuffer.appendSafe(json, '","image":"');
        DynamicBuffer.appendSafe(json, pngUri);
        DynamicBuffer.appendSafe(json, '"}');

        bytes memory uri = DynamicBuffer.allocate(29 + 4 * ((json.length + 2) / 3) + 4);
        DynamicBuffer.appendSafe(uri, "data:application/json;base64,");
        DynamicBuffer.appendSafeBase64(uri, json, false, false);
        return string(uri);
    }

    /// @notice One window of the canonical frame as top-down RGBA, for many
    ///         small eth_calls that stitch to the one-shot frame.
    /// @dev Reverts on a record outside the pencil family, a malformed
    ///      stream, or a window that needs more gas than the call has. The
    ///      window equals the full frame exactly where the apron covers the
    ///      dependency depth (see the header).
    /// @param stream The token's canonical draw stream.
    /// @param wx     Window origin x, in absolute canvas pixels.
    /// @param wy     Window origin y, in absolute canvas pixels.
    /// @param ww     Window width; 0 means the whole canvas.
    /// @param wh     Window height.
    /// @param apron  Px the work window extends past the tile on every side.
    /// @return width  The full canvas width, not the window's.
    /// @return height The full canvas height.
    /// @return rgba   The window's pixels, top-down RGBA, ww * wh * 4 bytes.
    function renderWindow(bytes calldata stream, int256 wx, int256 wy, int256 ww, int256 wh, int256 apron)
        external
        view
        returns (uint32 width, uint32 height, bytes memory rgba)
    {
        return PencilRaster.render(stream, wx, wy, ww, wh, apron);
    }

    // ---- internals ----------------------------------------------------------

    function _png(uint32 w, uint32 h, bytes memory rgba) private view returns (bytes memory) {
        Animation memory anim;
        anim.frameCount = 1;
        anim.width = uint16(w);
        anim.height = uint16(h);
        anim.frames = new bytes[](1);
        anim.frames[0] = rgba;
        return png.getDataUri(anim, 1);
    }

    /*
     * The two helpers below copy KohiRenderer's. A shared library would
     * change the bytecode of KohiRenderer, which is deployed. The copies
     * could drift, so the tests compare them with KohiRenderer's output on
     * the same inputs.
     */

    /// Escape a collection name for JSON. Prefix a quote or backslash with a
    /// backslash. DROP an ASCII control byte (this function does not escape
    /// it). KohiRenderer does the same, so one project name gives one
    /// metadata document in every family.
    function _jsonEscape(bytes memory s) private pure returns (bytes memory out) {
        // worst case: every byte is a quote or backslash, 2 bytes each
        out = DynamicBuffer.allocate(2 * s.length);
        for (uint256 i = 0; i < s.length; i++) {
            bytes1 c = s[i];
            if (c == bytes1(0x22) || c == bytes1(0x5c)) {
                bytes memory esc = new bytes(2);
                esc[0] = bytes1(0x5c);
                esc[1] = c;
                DynamicBuffer.appendSafe(out, esc);
            } else if (uint8(c) >= 0x20) {
                bytes memory one = new bytes(1);
                one[0] = c;
                DynamicBuffer.appendSafe(out, one);
            }
            // else: ASCII control byte (< 0x20), dropped
        }
    }

    function _toString(uint256 value) private pure returns (bytes memory) {
        if (value == 0) return "0";
        uint256 digits;
        for (uint256 t = value; t != 0; t /= 10) ++digits;
        bytes memory b = new bytes(digits);
        for (uint256 i = digits; i > 0; --i) {
            b[i - 1] = bytes1(uint8(48 + (value % 10)));
            value /= 10;
        }
        return b;
    }
}

lib/kohi-fixmath/src/Errors.sol

// SPDX-License-Identifier: MIT
/* Copyright (c) Kohi Art Community, Inc. All rights reserved. */

/*
/*
///////////////////////////////////////////////////////////////////////////////////
//                                                                               //
//     @@@@@@@@@@@@@@                        @@@@                                // 
//               @@@@                        @@@@ @@@@@@@@                       // 
//               @@@@    @@@@@@@@@@@@@@@@    @@@@@@@          @@@@@@@@@@@@@@@@   // 
//               @@@@                        @@@@                                // 
//     @@@@@@@@@@@@@@                        @@@@@@@@@@@@@                       // 
//               @@@@                          @@@@@@@@@@@                       // 
//                                                                               //
///////////////////////////////////////////////////////////////////////////////////
*/

pragma solidity ^0.8.13;

/// @notice Custom errors shared by the Fix64 / Trig256 fixed-point library.

/// @notice An index or argument fell outside the range a function accepts.
error ArgumentOutOfRange();

/// @notice A division was attempted with a zero divisor.
error AttemptedToDivideByZero();

/// @notice A function that requires a non-negative input received a negative one.
error NegativeValuePassed();

lib/kohi-fixmath/src/Fix64.sol

// SPDX-License-Identifier: MIT
/* Copyright (c) Kohi Art Community, Inc. All rights reserved. */

/*
/*
///////////////////////////////////////////////////////////////////////////////////
//                                                                               //
//     @@@@@@@@@@@@@@                        @@@@                                //
//               @@@@                        @@@@ @@@@@@@@                       //
//               @@@@    @@@@@@@@@@@@@@@@    @@@@@@@          @@@@@@@@@@@@@@@@   //
//               @@@@                        @@@@                                //
//     @@@@@@@@@@@@@@                        @@@@@@@@@@@@@                       //
//               @@@@                          @@@@@@@@@@@                       //
//                                                                               //
///////////////////////////////////////////////////////////////////////////////////
*/

pragma solidity ^0.8.13;

/*
    Fix64: signed fixed-point arithmetic in Q31.32 format (a 64-bit two's
    complement integer with 32 fractional bits, so 1.0 is represented as
    1 << 32). This library provides the core operators, add/sub/mul/div,
    floor/round, sign/abs, min/max, and clamping/mapping helpers, that the
    rest of this codebase's trigonometric and logarithmic functions build on.

    exp: Adapted from Petteri Aimonen's libfixmath

    See: https://github.com/PetteriAimonen/libfixmath
         https://github.com/PetteriAimonen/libfixmath/blob/master/LICENSE

    other functions: Adapted from Andre Slupik's FixedMath.NET
                     https://github.com/asik/FixedMath.Net/blob/master/LICENSE.txt

    THIRD PARTY NOTICES:
    ====================

    libfixmath is Copyright (c) 2011-2021 Flatmush <[email protected]>,
    Petteri Aimonen <[email protected]>, & libfixmath AUTHORS

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

    Copyright 2012 André Slupik

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    This project uses code from the log2fix library, which is under the following license:
    The MIT License (MIT)

    Copyright (c) 2015 Dan Moulding

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    IN THE SOFTWARE.
*/

/*
    The arithmetic below runs inside `unchecked` blocks so that int64/uint64
    operations wrap on overflow (two's complement), matching the original
    FixedMath.NET reference behavior. Solidity's default checked arithmetic
    would revert on exactly the wraps and saturations this format relies on.
*/

import "./Errors.sol";

/// @notice Signed fixed-point arithmetic in Q31.32 format (32 fractional bits).
library Fix64 {
    /// @notice Number of fractional bits in the Q31.32 representation.
    int64 public constant FRACTIONAL_PLACES = 32;
    /// @notice The fixed-point representation of 1.0 (1 << FRACTIONAL_PLACES).
    int64 public constant ONE = 4294967296; // 1 << FRACTIONAL_PLACES
    int64 public constant TWO = ONE * 2;
    int64 public constant THREE = ONE * 3;
    /// @notice Pi, in Q31.32.
    int64 public constant PI = 0x3243F6A88;
    /// @notice 2*Pi, in Q31.32.
    int64 public constant TWO_PI = 0x6487ED511;
    /// @notice The largest representable Fix64 value.
    int64 public constant MAX_VALUE = type(int64).max;
    /// @notice The smallest representable Fix64 value.
    int64 public constant MIN_VALUE = type(int64).min;
    /// @notice Pi / 2, in Q31.32.
    int64 public constant PI_OVER_2 = 0x1921FB544;

    /// @dev Counts leading zero bits in a 64-bit word, for bit-scan style
    /// routines. Does not handle x == 0 (the scan never terminates).
    function countLeadingZeros(uint64 x) internal pure returns (int64) {
        unchecked {
            int64 result = 0;
            while ((x & 0xF000000000000000) == 0) {
                result += 4;
                x <<= 4;
            }
            while ((x & 0x8000000000000000) == 0) {
                result += 1;
                x <<= 1;
            }
            return result;
        }
    }

    /*
     * div() and mul() are closed forms of the original FixedMath.NET
     * loop/decomposition implementations, bit-identical for every input:
     * the long division computes exactly floor(|x|*2^33/|y|) with
     * saturation and half-up rounding of the extra bit, and mul_256's
     * four-part decomposition absorbs its intermediate wraps mod 2^64.
     */

    /// @notice Divides x by y in Q31.32, rounding the result half up.
    /// @dev Saturates to MAX_VALUE/MIN_VALUE on overflow.
    /// @return The fixed-point quotient x / y.
    /// @custom:reverts AttemptedToDivideByZero if y == 0.
    function div(int64 x, int64 y) internal pure returns (int64) {
        unchecked {
            if (y == 0) {
                revert AttemptedToDivideByZero();
            }

            uint256 ax = uint64(x >= 0 ? x : -x);
            uint256 ay = uint64(y >= 0 ? y : -y);
            uint256 q = (ax << 33) / ay;
            if (q > type(uint64).max) {
                return ((x ^ y) & MIN_VALUE) == 0 ? MAX_VALUE : MIN_VALUE;
            }
            int64 result = int64(uint64((q + 1) >> 1));
            if (((x ^ y) & MIN_VALUE) != 0) {
                result = -result;
            }

            return result;
        }
    }

    /// @notice Multiplies x by y in Q31.32.
    /// @dev Widens to int256 for the multiply, then rescales; wraps on
    /// overflow rather than saturating (matches the original reference).
    /// @return The fixed-point product x * y.
    function mul(int64 x, int64 y) internal pure returns (int64) {
        unchecked {
            return int64(int256((int256(x) * int256(y)) >> 32));
        }
    }

    /// @notice Multiplies two Q31.32 values without truncating to int64.
    /// @dev Splits each operand into high/low 32-bit halves and sums the
    /// four partial products, so the result stays exact in int256 instead
    /// of wrapping the way mul() does. Used where intermediate precision
    /// matters, e.g. squaring a value repeatedly in log2().
    /// @return The fixed-point product x * y as an int256.
    function mul_256(int256 x, int256 y) internal pure returns (int256) {
        unchecked {
            int256 xl = x;
            int256 yl = y;

            uint256 xlo = uint256((xl & int256(0x00000000FFFFFFFF)));
            int256 xhi = xl >> 32; // FRACTIONAL_PLACES
            uint256 ylo = uint256(yl & int256(0x00000000FFFFFFFF));
            int256 yhi = yl >> 32; // FRACTIONAL_PLACES

            uint256 lolo = xlo * ylo;
            int256 lohi = int256(xlo) * yhi;
            int256 hilo = xhi * int256(ylo);
            int256 hihi = xhi * yhi;

            uint256 loResult = lolo >> 32; // FRACTIONAL_PLACES
            int256 midResult1 = lohi;
            int256 midResult2 = hilo;
            int256 hiResult = hihi << 32; // FRACTIONAL_PLACES

            int256 sum = int256(loResult) + midResult1 + midResult2 + hiResult;

            return sum;
        }
    }

    /// @notice Truncates a Q31.32 value down to the nearest whole number.
    /// @dev Zeroes the fractional bits; rounds toward negative infinity.
    function floor(int256 x) internal pure returns (int64) {
        unchecked {
            return int64(x & 0xFFFFFFFF00000000);
        }
    }

    /// @notice Rounds a Q31.32 value to the nearest whole number.
    /// @dev Ties (fractional part exactly 0.5) round to even, matching
    /// IEEE-754 banker's rounding.
    function round(int256 x) internal pure returns (int256) {
        unchecked {
            int256 fractionalPart = x & 0x00000000FFFFFFFF;
            int256 integralPart = floor(x);
            if (fractionalPart < 0x80000000) return integralPart;
            if (fractionalPart > 0x80000000) return integralPart + ONE;
            if ((integralPart & ONE) == 0) return integralPart;
            return integralPart + ONE;
        }
    }

    /// @notice Subtracts y from x, saturating instead of wrapping on overflow.
    /// @return x - y, clamped to [MIN_VALUE, MAX_VALUE].
    function sub(int64 x, int64 y) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            int64 yl = y;
            int64 diff = xl - yl;
            if (((xl ^ yl) & (xl ^ diff) & MIN_VALUE) != 0)
                diff = xl < 0 ? MIN_VALUE : MAX_VALUE;
            return diff;
        }
    }

    /// @notice Adds x and y, saturating instead of wrapping on overflow.
    /// @return x + y, clamped to [MIN_VALUE, MAX_VALUE].
    function add(int64 x, int64 y) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            int64 yl = y;
            int64 sum = xl + yl;
            if ((~(xl ^ yl) & (xl ^ sum) & MIN_VALUE) != 0)
                sum = xl > 0 ? MAX_VALUE : MIN_VALUE;
            return sum;
        }
    }

    /// @notice The sign of x.
    /// @return -1, 0, or 1.
    function sign(int64 x) internal pure returns (int8) {
        return x == int8(0) ? int8(0) : x > int8(0) ? int8(1) : int8(-1);
    }

    /// @notice The absolute value of x.
    /// @dev Branchless via the sign-mask trick; MIN_VALUE has no positive
    /// counterpart and wraps back to itself under the unchecked negation.
    function abs(int64 x) internal pure returns (int64) {
        unchecked {
            int64 mask = x >> 63;
            return (x + mask) ^ mask;
        }
    }

    /// @notice The larger of a and b.
    function max(int64 a, int64 b) internal pure returns (int64) {
        return a >= b ? a : b;
    }

    /// @notice The smaller of a and b.
    function min(int64 a, int64 b) internal pure returns (int64) {
        return a < b ? a : b;
    }

    /// @notice Linearly maps n from the range [start1, stop1] to [start2, stop2],
    /// then clamps the result to that output range.
    /// @return The mapped and clamped value.
    /// @custom:reverts AttemptedToDivideByZero if start1 == stop1.
    function map(
        int64 n,
        int64 start1,
        int64 stop1,
        int64 start2,
        int64 stop2
    ) internal pure returns (int64) {
        int64 value = mul(
            div(sub(n, start1), sub(stop1, start1)),
            add(sub(stop2, start2), start2)
        );

        return
            start2 < stop2
                ? constrain(value, start2, stop2)
                : constrain(value, stop2, start2);
    }

    /// @notice Clamps n to the inclusive range [low, high].
    function constrain(
        int64 n,
        int64 low,
        int64 high
    ) internal pure returns (int64) {
        return max(min(n, high), low);
    }
}

lib/kohi-fixmath/src/SinLut256.sol

// SPDX-License-Identifier: MIT
/* Copyright (c) wattsy. Portions Copyright (c) Kohi Art Community, Inc. (MIT). */

/*
 * This is a generated Solidity artifact of Kohi's MIT SinLut256: a 256-entry
 * Q31.32 sine table over [0, PI/2]. The table values are Kohi's MIT-licensed
 * work; this generated file is released under MIT, retaining the original Kohi
 * MIT notice as MIT requires.
 */

/*
/*
///////////////////////////////////////////////////////////////////////////////////
//                                                                               //
//     @@@@@@@@@@@@@@                        @@@@                                //
//               @@@@                        @@@@ @@@@@@@@                       //
//               @@@@    @@@@@@@@@@@@@@@@    @@@@@@@          @@@@@@@@@@@@@@@@   //
//               @@@@                        @@@@                                //
//     @@@@@@@@@@@@@@                        @@@@@@@@@@@@@                       //
//               @@@@                          @@@@@@@@@@@                       //
//                                                                               //
///////////////////////////////////////////////////////////////////////////////////
*/

pragma solidity ^0.8.13;

/*
 * Generated: do not hand-edit. Value-identical to the original Kohi
 * SinLut256 table (256-entry Q31.32 sine LUT over [0, PI/2]), repacked
 * 4 entries per uint256 word so it inlines compactly. Boundary behavior
 * matches the original table's fallthrough: a negative index reads entry 1,
 * an index above 255 reads entry 255.
 */
library SinLut256 {
    /**
     * @notice Lookup table for computing the sine value for a given angle.
     * @param i The clamped and rounded angle integral to index into the table.
     * @return The sine value in fixed-point (Q31.32) space.
     */
    function sinlut(int256 i) internal pure returns (int64) {
        unchecked {
            if (i < 0) i = 1; // original tree fallthrough for negatives
            if (i > 255) i = 255; // and for overflow
            uint256 w = uint256(i) >> 2;
            uint256 lane = uint256(i) & 3;
            return int64(uint64(_word(w) >> ((3 - lane) << 6)));
        }
    }

    function _word(uint256 w) private pure returns (uint256) {
        if (w <= 31) {
            if (w <= 15) {
                if (w <= 7) {
                    if (w <= 3) {
                        if (w <= 1) {
                            if (w <= 0) {
                                return 0x0000000000000000000000000193b2c100000000032761960000000004bb0894;
                            } else {
                                return 0x00000000064ea3ce0000000007e22f59000000000975a749000000000b0907b3;
                            }
                        } else {
                            if (w <= 2) {
                                return 0x000000000c9c4cab000000000e2f7248000000000fc2749e0000000011554fc3;
                            } else {
                                return 0x0000000012e7ffce00000000147a80d400000000160cceee00000000179ee632;
                            }
                        }
                    } else {
                        if (w <= 5) {
                            if (w <= 4) {
                                return 0x000000001930c2b9000000001ac2609b000000001c53bbf1000000001de4d0d7;
                            } else {
                                return 0x000000001f759b6500000000210617b800000000229641eb000000002426161c;
                            }
                        } else {
                            if (w <= 6) {
                                return 0x0000000025b59067000000002744aced0000000028d367cb000000002a61bd23;
                            } else {
                                return 0x000000002befa917000000002d7d27c7000000002f0a3559000000003096cdf1;
                            }
                        }
                    }
                } else {
                    if (w <= 11) {
                        if (w <= 9) {
                            if (w <= 8) {
                                return 0x000000003222edb30000000033ae90c8000000003539b3580000000036c4518b;
                            } else {
                                return 0x00000000384e678d0000000039d7f18a000000003b60ebae000000003ce95229;
                            }
                        } else {
                            if (w <= 10) {
                                return 0x000000003e71212a000000003ff854e400000000417ee98a000000004304db50;
                            } else {
                                return 0x00000000448a266d00000000460ec718000000004792b98b000000004915fa02;
                            }
                        }
                    } else {
                        if (w <= 13) {
                            if (w <= 12) {
                                return 0x000000004a9884b9000000004c1a55ef000000004d9b69e5000000004f1bbcdc;
                            } else {
                                return 0x00000000509b4b1a00000000521a10e50000000053980a840000000055153442;
                            }
                        } else {
                            if (w <= 14) {
                                return 0x0000000056918a6b00000000580d094d000000005987ad38000000005b01727f;
                            } else {
                                return 0x000000005c7a5576000000005df25274000000005f6965d20000000060df8bec;
                            }
                        }
                    }
                }
            } else {
                if (w <= 23) {
                    if (w <= 19) {
                        if (w <= 17) {
                            if (w <= 16) {
                                return 0x000000006254c11e0000000063c901ca00000000653c4a500000000066ae9716;
                            } else {
                                return 0x00000000681fe4840000000069902f01000000006aff72fc000000006c6dace2;
                            }
                        } else {
                            if (w <= 18) {
                                return 0x000000006ddad924000000006f46f4370000000070b1fa9200000000721be8ac;
                            } else {
                                return 0x000000007384bb030000000074ec6e15000000007652fe630000000077b86873;
                            }
                        }
                    } else {
                        if (w <= 21) {
                            if (w <= 20) {
                                return 0x00000000791ca8ca000000007a7fbbf4000000007be19e7c000000007d424cf4;
                            } else {
                                return 0x000000007ea1c3ee000000007fffffff00000000815cfdc20000000082b8b9d3;
                            }
                        } else {
                            if (w <= 22) {
                                return 0x00000000841330cf00000000856c5f5b0000000086c4421b00000000881ad5b8;
                            } else {
                                return 0x00000000897016df000000008ac4023e000000008c169489000000008d67ca76;
                            }
                        }
                    }
                } else {
                    if (w <= 27) {
                        if (w <= 25) {
                            if (w <= 24) {
                                return 0x000000008eb7a0bd000000009006141d000000009153215400000000929ec527;
                            } else {
                                return 0x0000000093e8fc5e000000009531c3c200000000967918230000000097bef652;
                            }
                        } else {
                            if (w <= 26) {
                                return 0x0000000099035b26000000009a464376000000009b87ac21000000009cc79207;
                            } else {
                                return 0x000000009e05f20c000000009f42c91a00000000a07e141b00000000a1b7d000;
                            }
                        }
                    } else {
                        if (w <= 29) {
                            if (w <= 28) {
                                return 0x00000000a2eff9bc00000000a4268e4800000000a55b8a9f00000000a68eebc1;
                            } else {
                                return 0x00000000a7c0aeb100000000a8f0d07700000000aa1f4e1e00000000ab4c24b7;
                            }
                        } else {
                            if (w <= 30) {
                                return 0x00000000ac77515400000000ada0d11000000000aec8a10400000000afeebe52;
                            } else {
                                return 0x00000000b113261f00000000b235d59300000000b356c9db00000000b476002a;
                            }
                        }
                    }
                }
            }
        } else {
            if (w <= 47) {
                if (w <= 39) {
                    if (w <= 35) {
                        if (w <= 33) {
                            if (w <= 32) {
                                return 0x00000000b59375b300000000b6af27b300000000b7c9136600000000b8e13611;
                            } else {
                                return 0x00000000b9f78cfb00000000bb0c156e00000000bc1eccbd00000000bd2fb03a;
                            }
                        } else {
                            if (w <= 34) {
                                return 0x00000000be3ebd4100000000bf4bf12f00000000c057496600000000c160c34d;
                            } else {
                                return 0x00000000c2685c5100000000c36e11e200000000c471e17400000000c573c883;
                            }
                        }
                    } else {
                        if (w <= 37) {
                            if (w <= 36) {
                                return 0x00000000c673c48d00000000c771d31400000000c86df1a200000000c9681dc3;
                            } else {
                                return 0x00000000ca60550900000000cb56950b00000000cc4adb6400000000cd3d25b6;
                            }
                        } else {
                            if (w <= 38) {
                                return 0x00000000ce2d71a500000000cf1bbcdc00000000d008050b00000000d0f247e5;
                            } else {
                                return 0x00000000d1da832500000000d2c0b48800000000d3a4d9d300000000d486f0ce;
                            }
                        }
                    }
                } else {
                    if (w <= 43) {
                        if (w <= 41) {
                            if (w <= 40) {
                                return 0x00000000d566f74600000000d644eb0f00000000d720ca0100000000d7fa91f8;
                            } else {
                                return 0x00000000d8d240d800000000d9a7d48800000000da7b4af500000000db4ca210;
                            }
                        } else {
                            if (w <= 42) {
                                return 0x00000000dc1bd7d300000000dce8ea3800000000ddb3d74200000000de7c9cf9;
                            } else {
                                return 0x00000000df43396900000000e007aaa500000000e0c9eec300000000e18a03e1;
                            }
                        }
                    } else {
                        if (w <= 45) {
                            if (w <= 44) {
                                return 0x00000000e247e82100000000e30399ab00000000e3bd16ad00000000e4745d57;
                            } else {
                                return 0x00000000e5296be400000000e5dc409100000000e68cd9a100000000e73b355d;
                            }
                        } else {
                            if (w <= 46) {
                                return 0x00000000e7e7521300000000e8912e1800000000e938c7c400000000e9de1d77;
                            } else {
                                return 0x00000000ea812d9700000000eb21f68d00000000ebc076ca00000000ec5cacc3;
                            }
                        }
                    }
                }
            } else {
                if (w <= 55) {
                    if (w <= 51) {
                        if (w <= 49) {
                            if (w <= 48) {
                                return 0x00000000ecf696f400000000ed8e33df00000000ee23820900000000eeb68001;
                            } else {
                                return 0x00000000ef472c5800000000efd585a700000000f0618a8c00000000f0eb39aa;
                            }
                        } else {
                            if (w <= 50) {
                                return 0x00000000f17291ab00000000f1f7913e00000000f27a371900000000f2fa81f8;
                            } else {
                                return 0x00000000f378709a00000000f3f401c600000000f46d344a00000000f4e406f8;
                            }
                        }
                    } else {
                        if (w <= 53) {
                            if (w <= 52) {
                                return 0x00000000f55878a900000000f5ca883b00000000f63a349100000000f6a77c98;
                            } else {
                                return 0x00000000f7125f3e00000000f77adb7a00000000f7e0f04900000000f8449cac;
                            }
                        } else {
                            if (w <= 54) {
                                return 0x00000000f8a5dfab00000000f904b85500000000f96125bd00000000f9bb26ff;
                            } else {
                                return 0x00000000fa12bb3900000000fa67e19300000000faba993900000000fb0ae15c;
                            }
                        }
                    }
                } else {
                    if (w <= 59) {
                        if (w <= 57) {
                            if (w <= 56) {
                                return 0x00000000fb58b93500000000fba4200300000000fbed150b00000000fc339795;
                            } else {
                                return 0x00000000fc77a6f500000000fcb9427f00000000fcf8699100000000fd351b8e;
                            }
                        } else {
                            if (w <= 58) {
                                return 0x00000000fd6f57df00000000fda71df300000000fddc6d4000000000fe0f4540;
                            } else {
                                return 0x00000000fe3fa57600000000fe6d8d6900000000fe98fca700000000fec1f2c4;
                            }
                        }
                    } else {
                        if (w <= 61) {
                            if (w <= 60) {
                                return 0x00000000fee86f5a00000000ff0c720a00000000ff2dfa7900000000ff4d0855;
                            } else {
                                return 0x00000000ff699b4f00000000ff83b32200000000ff9b4f8d00000000ffb07054;
                            }
                        } else {
                            if (w <= 62) {
                                return 0x00000000ffc3154300000000ffd33e2b00000000ffe0eae500000000ffec1b4f;
                            } else {
                                return 0x00000000fff4cf4c00000000fffb06c700000000fffec1b10000000100000000;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @notice sinlut() against a memory-resident copy of the table (entry i
     *         at lutPtr + i*8, big-endian: the table() blob staged verbatim,
     *         with >= 24 bytes of readable slack after it for the tail mload).
     *         Value- and boundary-identical to sinlut(i); costs one mload
     *         instead of the ~2.6 KB selection tree, for callers that need
     *         to stay under a contract size limit such as EIP-170.
     */
    function sinlut(uint256 lutPtr, int256 i) internal pure returns (int64 v) {
        unchecked {
            if (i < 0) i = 1; // original tree fallthrough for negatives
            if (i > 255) i = 255; // and for overflow
            assembly {
                v := shr(192, mload(add(lutPtr, shl(3, i))))
            }
        }
    }

    /// @notice The full table as one blob (entry i at byte i*8, big-endian),
    ///         for staging into an SSTORE2 data contract at deploy time.
    ///         Reference it from constructors only, so the 2 KB rides in
    ///         initcode and never counts against the runtime size limit.
    function table() internal pure returns (bytes memory) {
        return
            hex"0000000000000000000000000193b2c100000000032761960000000004bb089400000000064ea3ce0000000007e22f59000000000975a749000000000b0907b3000000000c9c4cab000000000e2f7248000000000fc2749e0000000011554fc30000000012e7ffce00000000147a80d400000000160cceee00000000179ee632000000001930c2b9000000001ac2609b000000001c53bbf1000000001de4d0d7000000001f759b6500000000210617b800000000229641eb000000002426161c0000000025b59067000000002744aced0000000028d367cb000000002a61bd23000000002befa917000000002d7d27c7000000002f0a3559000000003096cdf1000000003222edb30000000033ae90c8000000003539b3580000000036c4518b00000000384e678d0000000039d7f18a000000003b60ebae000000003ce95229000000003e71212a000000003ff854e400000000417ee98a000000004304db5000000000448a266d00000000460ec718000000004792b98b000000004915fa02000000004a9884b9000000004c1a55ef000000004d9b69e5000000004f1bbcdc00000000509b4b1a00000000521a10e50000000053980a8400000000551534420000000056918a6b00000000580d094d000000005987ad38000000005b01727f000000005c7a5576000000005df25274000000005f6965d20000000060df8bec000000006254c11e0000000063c901ca00000000653c4a500000000066ae971600000000681fe4840000000069902f01000000006aff72fc000000006c6dace2000000006ddad924000000006f46f4370000000070b1fa9200000000721be8ac000000007384bb030000000074ec6e15000000007652fe630000000077b8687300000000791ca8ca000000007a7fbbf4000000007be19e7c000000007d424cf4000000007ea1c3ee000000007fffffff00000000815cfdc20000000082b8b9d300000000841330cf00000000856c5f5b0000000086c4421b00000000881ad5b800000000897016df000000008ac4023e000000008c169489000000008d67ca76000000008eb7a0bd000000009006141d000000009153215400000000929ec5270000000093e8fc5e000000009531c3c200000000967918230000000097bef6520000000099035b26000000009a464376000000009b87ac21000000009cc79207000000009e05f20c000000009f42c91a00000000a07e141b00000000a1b7d00000000000a2eff9bc00000000a4268e4800000000a55b8a9f00000000a68eebc100000000a7c0aeb100000000a8f0d07700000000aa1f4e1e00000000ab4c24b700000000ac77515400000000ada0d11000000000aec8a10400000000afeebe5200000000b113261f00000000b235d59300000000b356c9db00000000b476002a00000000b59375b300000000b6af27b300000000b7c9136600000000b8e1361100000000b9f78cfb00000000bb0c156e00000000bc1eccbd00000000bd2fb03a00000000be3ebd4100000000bf4bf12f00000000c057496600000000c160c34d00000000c2685c5100000000c36e11e200000000c471e17400000000c573c88300000000c673c48d00000000c771d31400000000c86df1a200000000c9681dc300000000ca60550900000000cb56950b00000000cc4adb6400000000cd3d25b600000000ce2d71a500000000cf1bbcdc00000000d008050b00000000d0f247e500000000d1da832500000000d2c0b48800000000d3a4d9d300000000d486f0ce00000000d566f74600000000d644eb0f00000000d720ca0100000000d7fa91f800000000d8d240d800000000d9a7d48800000000da7b4af500000000db4ca21000000000dc1bd7d300000000dce8ea3800000000ddb3d74200000000de7c9cf900000000df43396900000000e007aaa500000000e0c9eec300000000e18a03e100000000e247e82100000000e30399ab00000000e3bd16ad00000000e4745d5700000000e5296be400000000e5dc409100000000e68cd9a100000000e73b355d00000000e7e7521300000000e8912e1800000000e938c7c400000000e9de1d7700000000ea812d9700000000eb21f68d00000000ebc076ca00000000ec5cacc300000000ecf696f400000000ed8e33df00000000ee23820900000000eeb6800100000000ef472c5800000000efd585a700000000f0618a8c00000000f0eb39aa00000000f17291ab00000000f1f7913e00000000f27a371900000000f2fa81f800000000f378709a00000000f3f401c600000000f46d344a00000000f4e406f800000000f55878a900000000f5ca883b00000000f63a349100000000f6a77c9800000000f7125f3e00000000f77adb7a00000000f7e0f04900000000f8449cac00000000f8a5dfab00000000f904b85500000000f96125bd00000000f9bb26ff00000000fa12bb3900000000fa67e19300000000faba993900000000fb0ae15c00000000fb58b93500000000fba4200300000000fbed150b00000000fc33979500000000fc77a6f500000000fcb9427f00000000fcf8699100000000fd351b8e00000000fd6f57df00000000fda71df300000000fddc6d4000000000fe0f454000000000fe3fa57600000000fe6d8d6900000000fe98fca700000000fec1f2c400000000fee86f5a00000000ff0c720a00000000ff2dfa7900000000ff4d085500000000ff699b4f00000000ff83b32200000000ff9b4f8d00000000ffb0705400000000ffc3154300000000ffd33e2b00000000ffe0eae500000000ffec1b4f00000000fff4cf4c00000000fffb06c700000000fffec1b10000000100000000";
    }
}

lib/kohi-fixmath/src/Trig256.sol

// SPDX-License-Identifier: MIT
/* Copyright (c) Kohi Art Community, Inc. All rights reserved. */

/*
/*
///////////////////////////////////////////////////////////////////////////////////
//                                                                               //
//     @@@@@@@@@@@@@@                        @@@@                                //
//               @@@@                        @@@@ @@@@@@@@                       //
//               @@@@    @@@@@@@@@@@@@@@@    @@@@@@@          @@@@@@@@@@@@@@@@   //
//               @@@@                        @@@@                                //
//     @@@@@@@@@@@@@@                        @@@@@@@@@@@@@                       //
//               @@@@                          @@@@@@@@@@@                       //
//                                                                               //
///////////////////////////////////////////////////////////////////////////////////
*/
pragma solidity ^0.8.13;

import "./Fix64.sol";
import "./SinLut256.sol";

/*
    Trig256: trigonometric, logarithmic, and exponential functions over the
    Fix64 Q31.32 fixed-point format. sin/cos are computed via range reduction
    plus a 256-entry lookup table with linear interpolation (see SinLut256.sol);
    log2/log/exp use the power-series and binary-logarithm algorithms below;
    acos/atan/atan2 are series approximations adapted from FixedMath.NET.

    exp: Adapted from Petteri Aimonen's libfixmath

    See: https://github.com/PetteriAimonen/libfixmath
         https://github.com/PetteriAimonen/libfixmath/blob/master/LICENSE

    other functions: Adapted from Andre Slupik's FixedMath.NET
                     https://github.com/asik/FixedMath.Net/blob/master/LICENSE.txt

    THIRD PARTY NOTICES:
    ====================

    libfixmath is Copyright (c) 2011-2021 Flatmush <[email protected]>,
    Petteri Aimonen <[email protected]>, & libfixmath AUTHORS

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

    Copyright 2012 André Slupik

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    This project uses code from the log2fix library, which is under the following license:
    The MIT License (MIT)

    Copyright (c) 2015 Dan Moulding

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    IN THE SOFTWARE.
*/

/*
    sin/cos/sqrt/clamp bodies below run inside `unchecked` blocks so
    int64/uint64 arithmetic wraps on overflow, matching the original
    reference implementation. See Fix64.sol for the same convention.
*/

/// @notice Trigonometric, logarithmic, and exponential functions over Fix64.
library Trig256 {
    int64 private constant LARGE_PI = 7244019458077122842;
    /// @dev ln(2) in Q31.32, used to convert log2() results to natural log.
    int64 private constant LN2 = 0xB17217F7;
    /// @dev Largest input to exp() that does not saturate the Q31.32 range.
    int64 private constant LN_MAX = 0x157CD0E702;
    /// @dev Smallest input to exp() before the result underflows to zero.
    int64 private constant LN_MIN = -0x162E42FEFA;
    /// @dev The value exp() returns as a fast-path shortcut for x == ONE,
    /// preserved bit-for-bit from the reference implementation.
    int64 private constant E = -0x2B7E15162;

    // Fix64.div((256 - 1) * Fix64.ONE, Fix64.PI_OVER_2), precomputed: the
    // long-division routine is far too expensive to rerun per sin() call.
    int64 private constant LUT_INTERVAL = 697236581115;

    /// @notice Sine of x, computed via range reduction into [0, PI/2] and a
    /// 256-entry lookup table with linear interpolation between entries.
    /// @param x Angle in radians, Q31.32.
    /// @return Sine of x, Q31.32, in [-ONE, ONE].
    function sin(int64 x) internal pure returns (int64) {
        unchecked {
            (int64 clamped, bool flipHorizontal, bool flipVertical) = clamp(x);

            int64 lutInterval = LUT_INTERVAL;
            int256 rawIndex = Fix64.mul_256(clamped, lutInterval);
            int64 roundedIndex = int64(Fix64.round(rawIndex));
            int64 indexError = Fix64.sub(int64(rawIndex), roundedIndex);

            roundedIndex = roundedIndex >> 32; /* FRACTIONAL_PLACES */

            int64 nearestValueIndex = flipHorizontal
                ? (256 - 1) - roundedIndex
                : roundedIndex;

            int64 nearestValue = SinLut256.sinlut(nearestValueIndex);

            int64 secondNearestValue = SinLut256.sinlut(
                flipHorizontal
                    ? (256 - 1) - roundedIndex - Fix64.sign(indexError)
                    : roundedIndex + Fix64.sign(indexError)
            );

            int64 delta = Fix64.mul(
                indexError,
                Fix64.abs(Fix64.sub(nearestValue, secondNearestValue))
            );
            int64 interpolatedValue = nearestValue +
                (flipHorizontal ? -delta : delta);
            int64 finalValue = flipVertical
                ? -interpolatedValue
                : interpolatedValue;

            return finalValue;
        }
    }

    /// @notice Cosine of x, via a phase shift into sin().
    /// @param x Angle in radians, Q31.32.
    /// @return Cosine of x, Q31.32, in [-ONE, ONE].
    function cos(int64 x) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            int64 angle;
            if (xl > 0) {
                angle = Fix64.add(xl, Fix64.sub(0 - Fix64.PI, Fix64.PI_OVER_2));
            } else {
                angle = Fix64.add(xl, Fix64.PI_OVER_2);
            }
            return sin(angle);
        }
    }

    /*
     * sin/cos against a memory-resident copy of the SinLut256 table (see
     * SinLut256.table()), for callers that cannot afford the ~2.6 KB inlined
     * selection tree that sinlut(int256) compiles to, e.g. contracts close to
     * the EIP-170 runtime size limit. Statement-for-statement identical to
     * sin(x)/cos(x) above; only the LUT access differs, and results are
     * bit-identical. If you change one variant, mirror the other.
     */
    /// @notice Sine of x, reading the sine table from memory at lutPtr instead
    /// of the inlined selection tree (see SinLut256.table()).
    /// @param x Angle in radians, Q31.32.
    /// @param lutPtr Pointer to a 256*8-byte, big-endian copy of the sine table.
    /// @return Sine of x, Q31.32, bit-identical to sin(x).
    function sin(int64 x, uint256 lutPtr) internal pure returns (int64) {
        unchecked {
            (int64 clamped, bool flipHorizontal, bool flipVertical) = clamp(x);

            int64 lutInterval = LUT_INTERVAL;
            int256 rawIndex = Fix64.mul_256(clamped, lutInterval);
            int64 roundedIndex = int64(Fix64.round(rawIndex));
            int64 indexError = Fix64.sub(int64(rawIndex), roundedIndex);

            roundedIndex = roundedIndex >> 32; /* FRACTIONAL_PLACES */

            int64 nearestValueIndex = flipHorizontal
                ? (256 - 1) - roundedIndex
                : roundedIndex;

            int64 nearestValue = SinLut256.sinlut(lutPtr, nearestValueIndex);

            int64 secondNearestValue = SinLut256.sinlut(
                lutPtr,
                flipHorizontal
                    ? (256 - 1) - roundedIndex - Fix64.sign(indexError)
                    : roundedIndex + Fix64.sign(indexError)
            );

            int64 delta = Fix64.mul(
                indexError,
                Fix64.abs(Fix64.sub(nearestValue, secondNearestValue))
            );
            int64 interpolatedValue = nearestValue +
                (flipHorizontal ? -delta : delta);
            int64 finalValue = flipVertical
                ? -interpolatedValue
                : interpolatedValue;

            return finalValue;
        }
    }

    /// @notice Cosine of x, reading the sine table from memory at lutPtr.
    /// @param x Angle in radians, Q31.32.
    /// @param lutPtr Pointer to a 256*8-byte, big-endian copy of the sine table.
    /// @return Cosine of x, Q31.32, bit-identical to cos(x).
    function cos(int64 x, uint256 lutPtr) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            int64 angle;
            if (xl > 0) {
                angle = Fix64.add(xl, Fix64.sub(0 - Fix64.PI, Fix64.PI_OVER_2));
            } else {
                angle = Fix64.add(xl, Fix64.PI_OVER_2);
            }
            return sin(angle, lutPtr);
        }
    }

    /// @notice Square root of a Q31.32 value.
    /// @dev Digit-by-digit binary square root, run twice over the 64-bit
    /// word (once per 32-bit half) so the result comes out correctly
    /// scaled in Q31.32 rather than needing a separate rescale step.
    /// @custom:reverts NegativeValuePassed if x < 0.
    function sqrt(int64 x) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            if (xl < 0) revert NegativeValuePassed();

            uint64 num = uint64(xl);
            uint64 result = uint64(0);
            uint64 bit = uint64(1) << (64 - 2);

            while (bit > num) bit >>= 2;
            for (uint8 i = 0; i < 2; ++i) {
                while (bit != 0) {
                    if (num >= result + bit) {
                        num -= result + bit;
                        result = (result >> 1) + bit;
                    } else {
                        result = result >> 1;
                    }

                    bit >>= 2;
                }

                if (i == 0) {
                    if (num > (uint64(1) << (64 / 2)) - 1) {
                        num -= result;
                        num = (num << (64 / 2)) - uint64(0x80000000);
                        result = (result << (64 / 2)) + uint64(0x80000000);
                    } else {
                        num <<= 64 / 2;
                        result <<= 64 / 2;
                    }

                    bit = uint64(1) << (64 / 2 - 2);
                }
            }

            if (num > result) ++result;
            return int64(result);
        }
    }

    /// @notice Base-2 logarithm of x, computed at int256 precision.
    /// @param x A positive Q31.32 value.
    /// @return log2(x) in Q31.32.
    /// @custom:reverts NegativeValuePassed if x <= 0.
    function log2_256(int256 x) public pure returns (int256) {
        if (x <= 0) {
            revert NegativeValuePassed();
        }

        // This implementation is based on Clay. S. Turner's fast binary logarithm
        // algorithm (C. S. Turner,  "A Fast Binary Logarithm Algorithm", IEEE Signal
        //     Processing Mag., pp. 124,140, Sep. 2010.)

        int256 b = 1 << 31; // FRACTIONAL_PLACES - 1
        int256 y = 0;

        int256 rawX = x;
        while (rawX < Fix64.ONE) {
            rawX <<= 1;
            y -= Fix64.ONE;
        }

        while (rawX >= Fix64.ONE << 1) {
            rawX >>= 1;
            y += Fix64.ONE;
        }

        int256 z = rawX;

        for (uint8 i = 0; i < 32 /* FRACTIONAL_PLACES */; i++) {
            z = Fix64.mul_256(z, z);
            if (z >= Fix64.ONE << 1) {
                z = z >> 1;
                y += b;
            }
            b >>= 1;
        }

        return y;
    }

    /// @notice Natural logarithm of x, computed at int256 precision.
    /// @param x A positive Q31.32 value.
    /// @return ln(x) in Q31.32.
    /// @custom:reverts NegativeValuePassed if x <= 0.
    function log_256(int256 x) public pure returns (int256) {
        return Fix64.mul_256(log2_256(x), LN2);
    }

    /// @notice Base-2 logarithm of x.
    /// @param x A positive Q31.32 value.
    /// @return log2(x) in Q31.32.
    /// @custom:reverts NegativeValuePassed if x <= 0.
    function log2(int64 x) public pure returns (int64) {
        if (x <= 0) revert NegativeValuePassed();

        // This implementation is based on Clay. S. Turner's fast binary logarithm
        // algorithm (C. S. Turner,  "A Fast Binary Logarithm Algorithm", IEEE Signal
        //     Processing Mag., pp. 124,140, Sep. 2010.)

        int64 b = 1 << 31; // FRACTIONAL_PLACES - 1
        int64 y = 0;

        int64 rawX = x;
        while (rawX < Fix64.ONE) {
            rawX <<= 1;
            y -= Fix64.ONE;
        }

        while (rawX >= Fix64.ONE << 1) {
            rawX >>= 1;
            y += Fix64.ONE;
        }

        int64 z = rawX;

        for (int32 i = 0; i < Fix64.FRACTIONAL_PLACES; i++) {
            z = Fix64.mul(z, z);
            if (z >= Fix64.ONE << 1) {
                z = z >> 1;
                y += b;
            }

            b >>= 1;
        }

        return y;
    }

    /// @notice Natural logarithm of x.
    /// @param x A positive Q31.32 value.
    /// @return ln(x) in Q31.32.
    /// @custom:reverts NegativeValuePassed if x <= 0.
    function log(int64 x) public pure returns (int64) {
        return Fix64.mul(log2(x), LN2);
    }

    /// @notice e raised to the power of x.
    /// @param x Exponent, Q31.32.
    /// @return exp(x) in Q31.32; MAX_VALUE if x is large enough to overflow,
    /// 0 if x is small enough to underflow.
    function exp(int64 x) public pure returns (int64) {
        if (x == 0) return Fix64.ONE;
        if (x == Fix64.ONE) return E;
        if (x >= LN_MAX) return Fix64.MAX_VALUE;
        if (x <= LN_MIN) return 0;

        /* The algorithm is based on the power series for exp(x):
         * http://en.wikipedia.org/wiki/Exponential_function#Formal_definition
         *
         * From term n, we get term n+1 by multiplying with x/n.
         * When the sum term drops to zero, we can stop summing.
         */

        // The power-series converges much faster on positive values
        // and exp(-x) = 1/exp(x).

        bool neg = (x < 0);
        if (neg) x = -x;

        int64 result = Fix64.add(int64(x), Fix64.ONE);
        int64 term = x;

        for (uint32 i = 2; i < 40; i++) {
            term = Fix64.mul(x, Fix64.div(term, int32(i) * Fix64.ONE));
            result = Fix64.add(result, int64(term));
            if (term == 0) break;
        }

        if (neg) {
            result = Fix64.div(Fix64.ONE, result);
        }

        return result;
    }

    /*
     * Compact cross-contract stubs for this library's cold `public` fns.
     * The functions stay public (deployed once in the linked Trig256
     * library); these wrappers replace solc's per-site delegatecall stubs
     * with one shared staticcall sequence: the callees are pure, so a
     * direct staticcall against the library address returns identical
     * bytes with none of the generated ABI ceremony. The fixed callees
     * always return exactly 32 bytes on success, so returndata length
     * needs no validation; failures bubble verbatim.
     */
    /// @dev Calls a single-int-argument public function on this library's own
    /// deployed code via staticcall, bypassing the ABI-encoded delegatecall
    /// stub solc would otherwise generate at each call site.
    function _ext1(bytes4 sel, int256 x) private view returns (int256 r) {
        address a = address(Trig256);
        assembly {
            let p := mload(0x40)
            mstore(p, sel)
            mstore(add(p, 4), x)
            if iszero(staticcall(gas(), a, p, 36, p, 32)) {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
            r := mload(p)
        }
    }

    /// @dev Cross-contract call to log(), see _ext1.
    function extLog(int64 x) internal view returns (int64) {
        return int64(_ext1(Trig256.log.selector, x));
    }

    /// @dev Cross-contract call to exp(), see _ext1.
    function extExp(int64 x) internal view returns (int64) {
        return int64(_ext1(Trig256.exp.selector, x));
    }

    /// @dev Cross-contract call to acos(), see _ext1.
    function extAcos(int64 x) internal view returns (int64) {
        return int64(_ext1(Trig256.acos.selector, x));
    }

    /// @dev Cross-contract call to log_256(), see _ext1.
    function extLog256(int256 x) internal view returns (int256) {
        return _ext1(Trig256.log_256.selector, x);
    }

    /// @dev Cross-contract call to atan2(), same staticcall approach as
    /// _ext1 but inlined for the two-argument signature.
    function extAtan2(int64 y, int64 x) internal view returns (int64 r) {
        address a = address(Trig256);
        bytes4 sel = Trig256.atan2.selector;
        assembly {
            let p := mload(0x40)
            mstore(p, sel)
            mstore(add(p, 4), y)
            mstore(add(p, 36), x)
            if iszero(staticcall(gas(), a, p, 68, p, 32)) {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
            r := mload(p)
        }
    }

    /// @dev Range-reduces x into [0, PI/2], the domain the sine lookup table
    /// covers, and records which reflections are needed to reconstruct the
    /// value in the original quadrant.
    /// @return clamped x reduced into [0, PI/2].
    /// @return flipHorizontal True if x fell in the second half of [0, PI].
    /// @return flipVertical True if x fell in [PI, 2*PI).
    function clamp(int64 x) internal pure returns (int64, bool, bool) {
        unchecked {
            int64 clamped2Pi = x;
            for (uint8 i = 0; i < 29; ++i) {
                clamped2Pi %= LARGE_PI >> i;
            }
            if (x < 0) {
                clamped2Pi += Fix64.TWO_PI;
            }

            bool flipVertical = clamped2Pi >= Fix64.PI;
            int64 clampedPi = clamped2Pi;
            while (clampedPi >= Fix64.PI) {
                clampedPi -= Fix64.PI;
            }

            bool flipHorizontal = clampedPi >= Fix64.PI_OVER_2;

            int64 clampedPiOver2 = clampedPi;
            if (clampedPiOver2 >= Fix64.PI_OVER_2)
                clampedPiOver2 -= Fix64.PI_OVER_2;

            return (clampedPiOver2, flipHorizontal, flipVertical);
        }
    }

    /// @notice Arc cosine of x, via atan(sqrt(1 - x^2) / x).
    /// @param x A Q31.32 value in [-ONE, ONE].
    /// @return result Angle in radians, Q31.32, in [0, PI].
    /// @custom:reverts "invalid range for x" if x is outside [-ONE, ONE].
    function acos(int64 x) public pure returns (int64 result) {
        if (x < -Fix64.ONE || x > Fix64.ONE) revert("invalid range for x");
        if (x == 0) return Fix64.PI_OVER_2;

        int64 t1 = Fix64.ONE - Fix64.mul(x, x);
        int64 t2 = Fix64.div(sqrt(t1), x);

        result = atan(t2);
        return x < 0 ? result + Fix64.PI : result;
    }

    /// @notice Arc tangent of z, via a continued-fraction series. Values
    /// with |z| > 1 are computed as PI/2 - atan(1/z) for faster convergence.
    /// @param z Q31.32.
    /// @return result Angle in radians, Q31.32, in (-PI/2, PI/2).
    function atan(int64 z) public pure returns (int64 result) {
        if (z == 0) return 0;

        bool neg = z < 0;
        if (neg) z = -z;

        int64 two = Fix64.TWO;
        int64 three = Fix64.THREE;

        bool invert = z > Fix64.ONE;
        if (invert) z = Fix64.div(Fix64.ONE, z);

        result = Fix64.ONE;
        int64 term = Fix64.ONE;

        int64 zSq = Fix64.mul(z, z);
        int64 zSq2 = Fix64.mul(zSq, two);
        int64 zSqPlusOne = Fix64.add(zSq, Fix64.ONE);
        int64 zSq12 = Fix64.mul(zSqPlusOne, two);
        int64 dividend = zSq2;
        int64 divisor = Fix64.mul(zSqPlusOne, three);

        for (uint8 i = 2; i < 30; ++i) {
            term = Fix64.mul(term, Fix64.div(dividend, divisor));
            result = Fix64.add(result, term);

            dividend = Fix64.add(dividend, zSq2);
            divisor = Fix64.add(divisor, zSq12);

            if (term == 0) break;
        }

        result = Fix64.mul(result, Fix64.div(z, zSqPlusOne));

        if (invert) {
            result = Fix64.sub(Fix64.PI_OVER_2, result);
        }

        if (neg) {
            result = -result;
        }

        return result;
    }

    /// @notice Angle of the point (x, y) from the positive x-axis, via a
    /// rational polynomial approximation (a separate algorithm from atan()).
    /// @param y Q31.32.
    /// @param x Q31.32.
    /// @return result Angle in radians, Q31.32, in (-PI, PI].
    function atan2(int64 y, int64 x) public pure returns (int64 result) {
        int64 e = 1202590848; /* 0.28 */
        int64 yl = y;
        int64 xl = x;

        if (xl == 0) {
            if (yl > 0) {
                return Fix64.PI_OVER_2;
            }
            if (yl == 0) {
                return 0;
            }
            return -Fix64.PI_OVER_2;
        }

        int64 z = Fix64.div(y, x);

        if (
            Fix64.add(Fix64.ONE, Fix64.mul(e, Fix64.mul(z, z))) ==
            type(int64).max
        ) {
            return y < 0 ? -Fix64.PI_OVER_2 : Fix64.PI_OVER_2;
        }

        if (Fix64.abs(z) < Fix64.ONE) {
            result = Fix64.div(
                z,
                Fix64.add(Fix64.ONE, Fix64.mul(e, Fix64.mul(z, z)))
            );
            if (xl < 0) {
                if (yl < 0) {
                    return Fix64.sub(result, Fix64.PI);
                }

                return Fix64.add(result, Fix64.PI);
            }
        } else {
            result = Fix64.sub(
                Fix64.PI_OVER_2,
                Fix64.div(z, Fix64.add(Fix64.mul(z, z), e))
            );

            if (yl < 0) {
                return Fix64.sub(result, Fix64.PI);
            }
        }
    }
}

lib/kohi/Fix64.sol

// SPDX-License-Identifier: MIT
// Re-export shim. The Fix64 fixed-point math is the kohi-fixmath library (MIT).
// This file gives its consumers (AggRaster, KohiStroke, KVMRender, KVMRenderV1,
// KVMVerts, Mesh3D, StampRaster) one stable import path for it.
//
// It exports Fix64 and the three custom errors of kohi-fixmath. Other code
// refers to AttemptedToDivideByZero by its selector. Each symbol is named
// explicitly.
pragma solidity ^0.8.13;

import {Fix64} from "kohi-fixmath/src/Fix64.sol";
import {ArgumentOutOfRange, AttemptedToDivideByZero, NegativeValuePassed} from "kohi-fixmath/src/Errors.sol";

lib/kohi/Trig256.sol

// SPDX-License-Identifier: MIT
// Re-export shim. The Trig256 trig, log and exp math is the kohi-fixmath library
// (MIT). This file gives its consumers (KVM, KVMInteractive, KVMStep, KVMTraits,
// KohiStroke, Mesh3D, StampRaster) one stable import path for it.
//
// It exports Trig256, Fix64, SinLut256 and the three custom errors. Some
// consumers (KVM, KVMInteractive, KVMStep, KVMTraits) use `Fix64.*` through this
// path only, so Fix64 is re-exported here. Every path resolves to the same
// kohi-fixmath declarations, so a symbol that also arrives through another shim
// does not collide.
pragma solidity ^0.8.13;

import {Trig256} from "kohi-fixmath/src/Trig256.sol";
import {Fix64} from "kohi-fixmath/src/Fix64.sol";
import {SinLut256} from "kohi-fixmath/src/SinLut256.sol";
import {ArgumentOutOfRange, AttemptedToDivideByZero, NegativeValuePassed} from "kohi-fixmath/src/Errors.sol";

src/ITokenRenderer.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */
pragma solidity ^0.8.13;

/// @notice An optional on-chain image and metadata renderer for registry
///         tokens. One call runs the full image path of the family.
/// @dev KohiRenderer, Mesh3DRenderer, MeshTraceRenderer, and
///      MeshVectorRenderer implement this surface (`is ITokenRenderer`). A
///      renderer serves one render family. The registry that stores the
///      renderer address does the dispatch per family.
interface ITokenRenderer {
    /// @notice Return the full ERC721 metadata as a
    ///         data:application/json;base64 URI.
    /// @dev The image is a data URI rendered on-chain from the canonical draw
    ///      stream: data:image/png;base64 for the raster families,
    ///      data:image/svg+xml;base64 for the vector family. An
    ///      implementation must revert on a fault. It must not return a
    ///      partial or corrupt image. The caller must pass a stream of the
    ///      family that the renderer serves: KohiRenderer always rasterizes
    ///      with AGG.
    ///      KohiRenderer reverts with KVMRenderError() on a rasterizer fault.
    /// @param tokenId     Added to the metadata name as " #<tokenId>".
    /// @param projectName The collection name. It goes before the token id in
    ///                    the metadata name.
    /// @param stream      The token's canonical draw stream.
    /// @return The metadata JSON as a self-contained data URI.
    function tokenDataURI(uint256 tokenId, string calldata projectName, bytes calldata stream)
        external
        view
        returns (string memory);
}

src/SinLutSingleton.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */
pragma solidity ^0.8.13;

/* =============================================================================
 *  SINLUT · one sine table, one address, every network
 * =============================================================================
 *
 * The KVM uses fixed-point trigonometry. All of it reads one 2048-byte table:
 * sin(x) at 256 points across a quarter wave, in Q31.32. The interpreter folds
 * each angle into [0, pi/2). At sample time it mirrors and negates the table
 * entries to rebuild the full period. The table never changes and every
 * backend reads the same bytes. On chain, the table is deployed once, as pure
 * data, at an address that any chain can reproduce. This file holds that
 * address and its derivation. The address commits to the table bytes. The
 * constants below let a reader check the commitment.
 *
 * Every KVM runner (KVMRunner, KVMStepCore, KVMStepRunner,
 * KVMInteractiveRunner, KVMTraitsRunner) reads its sine table from the SSTORE2
 * data contract at SINLUT. The deployed code is `STOP ++ SinLut256.table()`:
 *
 *       0    1                                                     2049
 *       +----+-------------------------------------------------------+
 *       |STOP| SinLut256.table(): 256 entries x 8 bytes, entry i at  |
 *       |0x00| table byte i*8, big-endian Q31.32                     |
 *       +----+-------------------------------------------------------+
 *
 * The 0x00 prefix is STOP, so the blob never executes as code. The runtime
 * read is an EXTCODECOPY that skips the prefix.
 *
 * One blob serves every runner. Each runner constructor stores
 * `sinLut = SINLUT`. No runner holds a private copy of the table. This saves
 * four 2 KB data contracts and about 2 KB of initcode per runner (the table
 * and the SSTORE2.write helper). The runtime read is an EXTCODECOPY of
 * `sinLut`, whatever that address holds.
 *
 * DERIVATION, reproducible on any chain:
 *
 *   proxy    = 0x4e59b44847b379578588920cA78FbF26c0B4956C
 *              the canonical deterministic-deployment proxy: it executes
 *              CREATE2(0, initcode, salt) with the first 32 calldata bytes
 *              as the salt, and is already present on mainnet, sepolia,
 *              anvil, and the forge test/script EVM
 *
 *   salt     = keccak256("kohi.sinlut.v1")
 *            = 0x2f069f27506488b699fe2e6321f2e31e737bf677c92426f475d84207c4f9af96
 *
 *   initcode = 0x61 ++ uint16(2049) ++ 0x3d81600a3d39f3 ++ 0x00
 *                   ++ SinLut256.table()
 *              (2059 bytes, the exact bytes SSTORE2.write(SinLut256.table())
 *              would CREATE); keccak256(initcode)
 *            = 0xe83f3fbd7fa53d2241a16e77cd0dd0f73365b0575cbbfef9e203cabf15128308
 *
 *   SINLUT   = keccak256(0xff ++ proxy ++ salt ++ keccak256(initcode))[12:]
 *            = 0x425Ea1bE9bFd353d7539a918b913f59289b028b8
 *
 * The deployed code at SINLUT is `STOP ++ SinLut256.table()` (2049 bytes),
 * codehash
 * 0x639034a1143ed727142506b4017fafc3fa9e1f811a62c77a25bfca61870bdd2b.
 *
 * The table bytes, the proxy and the salt are fixed. SINLUT is therefore the
 * SAME address on every network. The deploy tooling rebuilds the initcode,
 * runs it through the proxy, and asserts that the result equals this
 * constant. It MUST run before any runner, so that the runtime EXTCODECOPY
 * finds the table.
 *
 * The runners reference only SINLUT. SINLUT_CREATE2_PROXY and SINLUT_SALT are
 * the derivation inputs, shared by the deploy tooling and the test fixture.
 * All three are file-level constants with no getter. They add no bytecode to a
 * contract that does not reference them.
 */
address constant SINLUT = 0x425Ea1bE9bFd353d7539a918b913f59289b028b8;

// Canonical deterministic-deployment proxy. Present on mainnet, sepolia,
// anvil, and the forge test/script EVM.
address constant SINLUT_CREATE2_PROXY = 0x4e59b44847b379578588920cA78FbF26c0B4956C;

// keccak256("kohi.sinlut.v1"), as a literal. No hash runs at compile time.
bytes32 constant SINLUT_SALT = 0x2f069f27506488b699fe2e6321f2e31e737bf677c92426f475d84207c4f9af96;

src/png/graphics/Animation.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

/// @notice The frame container that the deployed PNG encoder reads: canvas
///         size, and the pixel buffer and placement of each frame.
/// @dev The struct matches the ABI of the mainnet PNGEncoder. Each frame is
///      one pixel buffer (`bytes`), not a layered frame struct. The field
///      order is the same as the deployed struct, so calls ABI-encode
///      directly.
struct Animation {
    uint16 frameCount;
    uint16 width;
    uint16 height;
    bytes[] frames;
    uint16[] delays;
    uint16[] xOffsets;
    uint16[] yOffsets;
    uint16[] widths;
    uint16[] heights;
}

src/png/graphics/IPNGEncoder.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import "./Animation.sol";

// The PNGEncoder deployed on Ethereum mainnet. It is the shared, immutable
// on-chain encoder that KohiRenderer uses. There is no local copy. Tests and
// scripts fork mainnet to reach this code. It uses MCOPY, so callers build
// for the Cancun EVM or later.
address constant PNG_ENCODER = 0xAF8f886Df2285a4Ca847AAA1a3223d420d79e886;

// The Sepolia twin of the same encoder (same source, same compiled bytecode).
// It lets KohiRenderer and its consumers run end to end on a public test
// chain.
//
// The constructor picks the address by chain id (see pngEncoderFor).
// `KohiRenderer.png` is an immutable, so the deploy writes the address into
// the runtime code. On chain id 1 (also a mainnet fork) the value is
// PNG_ENCODER.
address constant PNG_ENCODER_SEPOLIA = 0xbF91c1168034ca77A41DBc904552a3F7625bB923;

uint256 constant CHAIN_SEPOLIA = 11155111;

/// The PNG encoder for the chain that runs this code. Mainnet (and a fork of
/// it, which keeps chain id 1) gets the mainnet encoder. Sepolia gets its
/// twin.
function pngEncoderFor(uint256 chainId) pure returns (address) {
    return chainId == CHAIN_SEPOLIA ? PNG_ENCODER_SEPOLIA : PNG_ENCODER;
}

/// @title  IPNGEncoder
/// @notice The part of the deployed PNG encoder that KohiRenderer calls. It
///         is the true-colour (RGBA) path, which encodes an Animation inside
///         a view call. `animation.frames[i]` is one RGBA pixel buffer.
/// @dev The interface declares only this part. The behaviour, including the
///      reverts, belongs to the deployed encoder.
interface IPNGEncoder {
    /// @notice Encode an Animation as PNG file bytes.
    /// @param animation   The frames to encode. A frameCount of 1 is a
    ///                    still image.
    /// @param scaleFactor The encoder's integer upscale factor.
    /// @return buffer The encoded PNG file bytes.
    function getImageBuffer(Animation memory animation, uint8 scaleFactor)
        external
        view
        returns (bytes memory buffer);

    /// @notice Encode an Animation and return it as a data:image/png;base64
    ///         URI.
    /// @param animation   The frames to encode.
    /// @param scaleFactor The encoder's integer upscale factor.
    /// @return uri The image as a self-contained data URI.
    function getDataUri(Animation memory animation, uint8 scaleFactor) external view returns (bytes memory uri);
}

src/png/vendor/DynamicBuffer.sol

// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
// Vendored verbatim from @divergencetech/ethier/contracts/utils/DynamicBuffer.sol

pragma solidity >=0.8.0;

/// @title DynamicBuffer
/// @author David Huber (@cxkoda) and Simon Fremaux (@dievardump). See also
///         https://raw.githubusercontent.com/dievardump/solidity-dynamic-buffer
/// @notice This library is used to allocate a big amount of container memory
//          which will be subsequently filled without needing to reallocate
///         memory.
/// @dev First, allocate memory.
///      Then use `buffer.appendUnchecked(theBytes)` or `appendSafe()` if
///      bounds checking is required.
library DynamicBuffer {
    /// @notice Allocates container space for the DynamicBuffer
    /// @param capacity_ The intended max amount of bytes in the buffer
    /// @return buffer The memory location of the buffer
    /// @dev Allocates `capacity_ + 0x60` bytes of space
    ///      The buffer array starts at the first container data position,
    ///      (i.e. `buffer = container + 0x20`)
    function allocate(uint256 capacity_)
        internal
        pure
        returns (bytes memory buffer)
    {
        assembly {
            // Get next-free memory address
            let container := mload(0x40)

            // Allocate memory by setting a new next-free address
            {
                // Add 2 x 32 bytes in size for the two length fields
                // Add 32 bytes safety space for 32B chunked copy
                let size := add(capacity_, 0x60)
                let newNextFree := add(container, size)
                mstore(0x40, newNextFree)
            }

            // Set the correct container length
            {
                let length := add(capacity_, 0x40)
                mstore(container, length)
            }

            // The buffer starts at idx 1 in the container (0 is length)
            buffer := add(container, 0x20)

            // Init content with length 0
            mstore(buffer, 0)
        }

        return buffer;
    }

    /// @notice Appends data to buffer, and update buffer length
    /// @param buffer the buffer to append the data to
    /// @param data the data to append
    /// @dev Does not perform out-of-bound checks (container capacity)
    ///      for efficiency.
    function appendUnchecked(bytes memory buffer, bytes memory data)
        internal
        pure
    {
        assembly {
            let length := mload(data)
            for {
                data := add(data, 0x20)
                let dataEnd := add(data, length)
                let copyTo := add(buffer, add(mload(buffer), 0x20))
            } lt(data, dataEnd) {
                data := add(data, 0x20)
                copyTo := add(copyTo, 0x20)
            } {
                // Copy 32B chunks from data to buffer.
                // This may read over data array boundaries and copy invalid
                // bytes, which doesn't matter in the end since we will
                // later set the correct buffer length, and have allocated an
                // additional word to avoid buffer overflow.
                mstore(copyTo, mload(data))
            }

            // Update buffer length
            mstore(buffer, add(mload(buffer), length))
        }
    }

    /// @notice Appends data to buffer, and update buffer length
    /// @param buffer the buffer to append the data to
    /// @param data the data to append
    /// @dev Performs out-of-bound checks and calls `appendUnchecked`.
    function appendSafe(bytes memory buffer, bytes memory data) internal pure {
        checkOverflow(buffer, data.length);
        appendUnchecked(buffer, data);
    }

    /// @notice Appends data encoded as Base64 to buffer.
    /// @param fileSafe  Whether to replace '+' with '-' and '/' with '_'.
    /// @param noPadding Whether to strip away the padding.
    /// @dev Encodes `data` using the base64 encoding described in RFC 4648.
    /// See: https://datatracker.ietf.org/doc/html/rfc4648
    /// Author: Modified from Solady (https://github.com/vectorized/solady/blob/main/src/utils/Base64.sol)
    /// Author: Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Base64.sol)
    /// Author: Modified from (https://github.com/Brechtpd/base64/blob/main/base64.sol) by Brecht Devos.
    function appendSafeBase64(
        bytes memory buffer,
        bytes memory data,
        bool fileSafe,
        bool noPadding
    ) internal pure {
        uint256 dataLength = data.length;

        if (data.length == 0) {
            return;
        }

        uint256 encodedLength;
        uint256 r;
        assembly {
            // For each 3 bytes block, we will have 4 bytes in the base64
            // encoding: `encodedLength = 4 * divCeil(dataLength, 3)`.
            // The `shl(2, ...)` is equivalent to multiplying by 4.
            encodedLength := shl(2, div(add(dataLength, 2), 3))

            r := mod(dataLength, 3)
            if noPadding {
                // if r == 0 => no modification
                // if r == 1 => encodedLength -= 2
                // if r == 2 => encodedLength -= 1
                encodedLength := sub(
                    encodedLength,
                    add(iszero(iszero(r)), eq(r, 1))
                )
            }
        }

        checkOverflow(buffer, encodedLength);

        assembly {
            let nextFree := mload(0x40)

            // Store the table into the scratch space.
            // Offsetted by -1 byte so that the `mload` will load the character.
            // We will rewrite the free memory pointer at `0x40` later with
            // the allocated size.
            mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
            mstore(
                0x3f,
                sub(
                    "ghijklmnopqrstuvwxyz0123456789-_",
                    // The magic constant 0x0230 will translate "-_" + "+/".
                    mul(iszero(fileSafe), 0x0230)
                )
            )

            // Skip the first slot, which stores the length.
            let ptr := add(add(buffer, 0x20), mload(buffer))
            let end := add(data, dataLength)

            // Run over the input, 3 bytes at a time.
            // prettier-ignore
            // solhint-disable-next-line no-empty-blocks
            for {} 1 {} {
                    data := add(data, 3) // Advance 3 bytes.
                    let input := mload(data)

                    // Write 4 bytes. Optimized for fewer stack operations.
                    mstore8(    ptr    , mload(and(shr(18, input), 0x3F)))
                    mstore8(add(ptr, 1), mload(and(shr(12, input), 0x3F)))
                    mstore8(add(ptr, 2), mload(and(shr( 6, input), 0x3F)))
                    mstore8(add(ptr, 3), mload(and(        input , 0x3F)))

                    ptr := add(ptr, 4) // Advance 4 bytes.
                    // prettier-ignore
                    if iszero(lt(data, end)) { break }
                }

            if iszero(noPadding) {
                // Offset `ptr` and pad with '='. We can simply write over the end.
                mstore8(sub(ptr, iszero(iszero(r))), 0x3d) // Pad at `ptr - 1` if `r > 0`.
                mstore8(sub(ptr, shl(1, eq(r, 1))), 0x3d) // Pad at `ptr - 2` if `r == 1`.
            }

            mstore(buffer, add(mload(buffer), encodedLength))
            mstore(0x40, nextFree)
        }
    }

    /// @notice Returns the capacity of a given buffer.
    function capacity(bytes memory buffer) internal pure returns (uint256) {
        uint256 cap;
        assembly {
            cap := sub(mload(sub(buffer, 0x20)), 0x40)
        }
        return cap;
    }

    /// @notice Reverts if the buffer will overflow after appending a given
    /// number of bytes.
    function checkOverflow(bytes memory buffer, uint256 addedLength)
        internal
        pure
    {
        uint256 cap = capacity(buffer);
        uint256 newLength = buffer.length + addedLength;
        if (cap < newLength) {
            revert("DynamicBuffer: Appending out of bounds.");
        }
    }
}

src/raster/PencilCore.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

pragma solidity ^0.8.13;

import "../../lib/kohi/Fix64.sol";

/* =============================================================================
 *  PencilCore · the shared integer half of the pencil family
 * =============================================================================
 *
 * The pencil family (PENCIL 0xb0, render family 6) draws its paper from one
 * seeded generator and clips and shades by regions. This library holds the
 * parts that the rasterizer and the interpreter share: the paper's
 * index-addressable mulberry32, its draw layout, value-noise sampling, the
 * exp table reader, and the region inside and shade math. It is internal
 * only (no deployed code of its own).
 *
 * It is bit-exact with the shared module of the reference, which states
 * every quantity as an exact integer under 2^53 with FLOOR semantics. Here
 * every intermediate is an int256, and every division or shift that can see
 * a negative operand floors explicitly (`fdiv`, and `>>` on a signed int,
 * which is arithmetic).
 *
 *     format  1.0 =    use
 *     ------  -------  ------------------------------------------------------
 *     Q16     65536    unit quantities, pressures, tooth, wax, vary,
 *                      density, and positions in the stream records
 *                      (device px)
 *     Q12     4096     positions for the shade distances (1/4096 px)
 *     Q20     1048576  the unit vectors of region edges
 *
 * MULBERRY32 BY INDEX. The paper is drawn from mulberry32(seed). Its state
 * after k steps is seed + k * 0x6D2B79F5 (mod 2^32), so draw k is a pure
 * function of (seed, k), and a tile computes only the draws it needs.
 *
 * THE LAYOUT. A W x H canvas that spans `sheet16` mm (Q16) lays out its
 * draws in the order of the reference pencil engine:
 *
 *     lat  draws                     layer
 *     ---  ------------------------  ----------------------------------
 *      0   2 per cell                Worley grain
 *      1   1 per cell                tooth, value noise (3 layers)
 *      2   1 per cell
 *      3   1 per cell
 *      -   5 + steps per fibre       2,600 laid fibres (the step count
 *                                    comes from the 4th draw of the
 *                                    fibre, through Fix64)
 *      4   1 per cell                paper brightness (2 layers)
 *      5   1 per cell
 *      6   1 per cell                vary (2 layers)
 *      7   1 per cell
 *      -   256                       striation table
 *
 * The cell of a lattice is den/num * 65536 px exactly (num = 1000 * sheet16,
 * den = milli * W), counted exactly from the sheet width.
 */

/// One value-noise (or Worley) lattice.
struct PencilLat {
    int256 num;
    int256 den;
    int256 cell; // Q16 px, floored (the Worley distance ratio only)
    int256 gw;
    int256 gh;
    int256 off; // first draw index
    int256 amp; // Q16 amplitude
}

/// The draw layout of the paper. lat: 0 Worley, 1..3 tooth, 4..5
/// brightness, 6..7 vary. fib[i] = first draw of fibre i << 32 | its step
/// count (filled on request).
struct PencilLayout {
    int256 W;
    int256 H;
    int256 sheet16;
    int64 px; // px per mm, Fix64
    uint256 seed; // u32
    PencilLat[8] lat;
    uint256[] fib;
    int256 striOff;
    int256 draws;
}

/// A region ready to sample. Per polygon, per edge: (ex, ey) the inward unit
/// vector in Q20 and (px, py) the start of the edge in Q16. Per term, 8
/// words: kind, ax, ay, ex, ey (Q12), ee, a (Q16), b (Q12 for an occlusion,
/// Q16 for a sliver).
struct PencilRegion {
    bool set;
    int256 kv;
    int256 wobAmp;
    int256 wobBias;
    int256 tolL;
    int256[][] edges;
    int256[] terms;
    uint256 nt;
    uint256 verts;
}

library PencilCore {
    int256 internal constant Q = 65536;
    int256 internal constant Q20 = 1048576;
    int256 internal constant SHADE_MAX = 256 * 65536;
    int256 internal constant DMAX = 33554432; // 2^25: an offset from a term's segment clamps here (Q12)
    uint256 internal constant FIBRES = 2600;
    int256 internal constant LOG2E16 = 94548;

    // Fix64 constants of the fibre walk (raw = floor(x * 2^32))
    int64 internal constant F_0_7 = 3006477107;
    int64 internal constant F_0_8 = 3435973836;
    int64 internal constant F_2_7 = 11596411699;

    // ---- integers -----------------------------------------------------------

    /// Floor division (Math.floor(a / b) of the reference). Reverts on
    /// b == 0.
    function fdiv(int256 a, int256 b) internal pure returns (int256 q) {
        q = a / b;
        unchecked {
            if ((a % b != 0) && ((a ^ b) < 0)) q -= 1;
        }
    }

    /// floor(sqrt(n)) for any n >= 0.
    function isqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            if (a == 0) return 0;
            uint256 r = 1;
            uint256 t = a;
            if (t >> 128 > 0) { t >>= 128; r <<= 64; }
            if (t >> 64 > 0) { t >>= 64; r <<= 32; }
            if (t >> 32 > 0) { t >>= 32; r <<= 16; }
            if (t >> 16 > 0) { t >>= 16; r <<= 8; }
            if (t >> 8 > 0) { t >>= 8; r <<= 4; }
            if (t >> 4 > 0) { t >>= 4; r <<= 2; }
            if (t >> 2 > 0) { r <<= 1; }
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            uint256 s = a / r;
            return r < s ? r : s;
        }
    }

    /// Hermite smoothstep of a Q16 t in [0, Q].
    function smooth16(int256 t) internal pure returns (int256) {
        unchecked {
            return (((t * t) >> 16) * (3 * Q - 2 * t)) >> 16;
        }
    }

    /// Draw k (0-based) of mulberry32(seed), as a u32.
    function mb32(uint256 seed, uint256 k) internal pure returns (uint256 r) {
        assembly {
            let a := and(add(seed, mul(add(k, 1), 0x6d2b79f5)), 0xffffffff)
            let t := and(mul(xor(a, shr(15, a)), or(a, 1)), 0xffffffff)
            t := xor(and(add(t, mul(xor(t, shr(7, t)), or(t, 61))), 0xffffffff), t)
            r := xor(t, shr(14, t))
        }
    }

    /// hash2(a, b) = fmix32(a ^ imul(b + 1, 0x9e3779b1)), a and b as u32.
    function hash2(uint256 a, uint256 b) internal pure returns (uint256 h) {
        assembly {
            let m := and(xor(and(a, 0xffffffff), and(mul(and(add(and(b, 0xffffffff), 1), 0xffffffff), 0x9e3779b1), 0xffffffff)), 0xffffffff)
            m := and(mul(xor(m, shr(16, m)), 0x85ebca6b), 0xffffffff)
            m := and(mul(xor(m, shr(13, m)), 0xc2b2ae35), 0xffffffff)
            h := and(xor(m, shr(16, m)), 0xffffffff)
        }
    }

    // ---- layout -------------------------------------------------------------

    function _ceil(uint256 a, uint256 b) private pure returns (int256) {
        return int256((a + b - 1) / b);
    }

    function _vn(PencilLayout memory L, uint256 i, uint256 milli, int256 amp, uint256 extra, int256 off)
        private
        pure
        returns (int256)
    {
        unchecked {
            uint256 S = uint256(L.sheet16);
            uint256 W = uint256(L.W);
            uint256 H = uint256(L.H);
            PencilLat memory t = L.lat[i];
            t.num = int256(1000 * S);
            t.den = int256(milli * W);
            t.cell = int256((milli * W * 65536 * 65536) / (1000 * S));
            t.gw = _ceil(1000 * S, milli * 65536) + int256(extra);
            t.gh = _ceil(1000 * S * H, milli * 65536 * W) + int256(extra);
            t.off = off;
            t.amp = amp;
            return off + t.gw * t.gh * (extra == 1 ? int256(2) : int256(1));
        }
    }

    /// The steps of the fibre whose first draw is `base`: the count of
    /// k >= 0 with k * 0.7 < len, where len = mm(0.8 + 2.7 g) in Fix64 px
    /// and g is the 4th draw of the fibre.
    function fibreSteps(uint256 seed, uint256 base, int64 px) internal pure returns (uint256) {
        int64 g = int64(uint64(mb32(seed, base + 3)));
        int64 len = Fix64.mul(Fix64.add(F_0_8, Fix64.mul(g, F_2_7)), px);
        if (len <= 0) return 0;
        unchecked {
            return uint256(int256((len - 1) / F_0_7)) + 1;
        }
    }

    /// The layout of the paper. With `withFibres`, also record the draw base
    /// and the step count of every fibre.
    function paperLayout(int256 W, int256 H, int256 sheet16, uint256 seed, bool withFibres)
        internal
        pure
        returns (PencilLayout memory L)
    {
        unchecked {
            L.W = W;
            L.H = H;
            L.sheet16 = sheet16;
            L.seed = seed & 0xffffffff;
            int256 off = _vn(L, 0, 220, 39322, 1, 0);
            off = _vn(L, 1, 160, 7864, 2, off);
            off = _vn(L, 2, 400, 14418, 2, off);
            off = _vn(L, 3, 1600, 3932, 2, off);
            L.px = Fix64.div(int64(W << 32), int64(sheet16 << 16));
            if (withFibres) L.fib = new uint256[](FIBRES);
            for (uint256 i; i < FIBRES; ++i) {
                uint256 n = fibreSteps(L.seed, uint256(off), L.px);
                if (withFibres) L.fib[i] = (uint256(off) << 32) | n;
                off += int256(5 + n);
            }
            off = _vn(L, 4, 5000, 655, 2, off);
            off = _vn(L, 5, 28000, 1049, 2, off);
            off = _vn(L, 6, 2200, 14418, 2, off);
            off = _vn(L, 7, 7000, 17039, 2, off);
            L.striOff = off;
            L.draws = off + 256;
        }
    }

    /// The value-noise axis parameter of pixel p: (lattice index,
    /// smoothstepped fraction Q16).
    function vnAxis(int256 p, PencilLat memory L) internal pure returns (int256 i, int256 s) {
        unchecked {
            int256 f = fdiv(p * L.num, L.den);
            i = f >> 16;
            s = smooth16(f - i * Q);
        }
    }

    /// A lattice value from its draw: g * 2 - 1 in Q16, [-Q, Q).
    function latQ16(uint256 u) internal pure returns (int256) {
        unchecked {
            return int256(u >> 15) - Q;
        }
    }

    // ---- exp ----------------------------------------------------------------

    /// e^(-x) for x >= 0, both Q16, through the EXP2 table at `t` (memory,
    /// u16 entries). A negative x keeps the int32 shift semantics of the
    /// reference (f >> (ip & 31)).
    function expNeg16(int256 x, uint256 t) internal pure returns (int256 f) {
        unchecked {
            int256 y = (x * LOG2E16) >> 16;
            int256 ip = y >> 16;
            if (ip >= 17) return 0;
            assembly {
                let fp := sub(y, mul(ip, 65536))
                let j := shr(8, fp)
                let r := and(fp, 255)
                let p := add(t, shl(1, j))
                let a := add(shr(240, mload(p)), 32768)
                let b := add(shr(240, mload(add(p, 2))), 32768)
                f := shr(and(ip, 31), shr(8, add(mul(a, sub(256, r)), mul(b, r))))
            }
        }
    }

    // ---- regions ------------------------------------------------------------

    /// Build a region from Q16 polygons (x, y interleaved) and Q16 terms (7
    /// words each).
    function buildRegion(
        int256 kv,
        int256 wobAmp,
        int256 wobBias,
        int256 tolL,
        int256[][] memory polys,
        int256[] memory terms7
    ) internal pure returns (PencilRegion memory R) {
        unchecked {
            R.set = true;
            R.kv = kv;
            R.wobAmp = wobAmp;
            R.wobBias = wobBias;
            R.tolL = tolL;
            R.edges = new int256[][](polys.length);
            uint256 verts;
            for (uint256 p; p < polys.length; ++p) {
                int256[] memory poly = polys[p];
                uint256 n = poly.length >> 1;
                verts += n;
                int256 a2;
                for (uint256 i; i < n; ++i) {
                    uint256 j = (i + 1) % n;
                    a2 += (poly[2 * i] >> 8) * (poly[2 * j + 1] >> 8) - (poly[2 * j] >> 8) * (poly[2 * i + 1] >> 8);
                }
                int256 sgn = a2 > 0 ? int256(1) : int256(-1);
                int256[] memory e = new int256[](n * 4);
                for (uint256 i; i < n; ++i) {
                    uint256 j = (i + 1) % n;
                    int256 px = poly[2 * i];
                    int256 py = poly[2 * i + 1];
                    int256 dx = (poly[2 * j] - px) * sgn;
                    int256 dy = (poly[2 * j + 1] - py) * sgn;
                    int256 len = int256(isqrt(uint256(dx * dx + dy * dy)));
                    if (len != 0) {
                        e[4 * i] = fdiv(dx * Q20, len);
                        e[4 * i + 1] = fdiv(dy * Q20, len);
                    }
                    e[4 * i + 2] = px;
                    e[4 * i + 3] = py;
                }
                R.edges[p] = e;
            }
            R.verts = verts;
            uint256 nt = terms7.length / 7;
            R.nt = nt;
            R.terms = new int256[](nt * 8);
            int256[] memory T = R.terms;
            for (uint256 k; k < nt; ++k) {
                uint256 s = 7 * k;
                uint256 o = 8 * k;
                int256 ax = terms7[s + 1] >> 4;
                int256 ay = terms7[s + 2] >> 4;
                int256 ex = (terms7[s + 3] >> 4) - ax;
                int256 ey = (terms7[s + 4] >> 4) - ay;
                T[o] = terms7[s];
                T[o + 1] = ax;
                T[o + 2] = ay;
                T[o + 3] = ex;
                T[o + 4] = ey;
                T[o + 5] = ex * ex + ey * ey;
                T[o + 6] = terms7[s + 5];
                if (terms7[s] == 0) {
                    int256 b = terms7[s + 6] >> 4;
                    T[o + 7] = b > 1 ? b : int256(1);
                } else {
                    T[o + 7] = terms7[s + 6];
                }
            }
        }
    }

    /// The inside test at Q16 point (x, y), with tolerance tol (Q16 px) and
    /// the vary of the pixel.
    function regionInside(PencilRegion memory R, int256 x, int256 y, int256 tol, int256 vary16)
        internal
        pure
        returns (bool)
    {
        unchecked {
            int256 lim = (tol + (((vary16 - Q / 2) * R.wobAmp) >> 16) + R.wobBias) * Q20;
            int256[][] memory E = R.edges;
            for (uint256 p; p < E.length; ++p) {
                int256[] memory e = E[p];
                bool ok = true;
                uint256 m = e.length;
                for (uint256 i; i < m; i += 4) {
                    if ((x - e[i + 2]) * e[i + 1] - (y - e[i + 3]) * e[i] > lim) {
                        ok = false;
                        break;
                    }
                }
                if (ok) return true;
            }
            return false;
        }
    }

    /// The distance (Q12) from Q12 point (x, y) to the term at word o. The
    /// projection is an exact long division in four 4-bit steps.
    function _termDist(int256[] memory T, uint256 o, int256 x, int256 y) private pure returns (int256) {
        unchecked {
            int256 ex = T[o + 3];
            int256 ey = T[o + 4];
            int256 ee = T[o + 5];
            int256 dx = x - T[o + 1];
            int256 dy = y - T[o + 2];
            if (dx > DMAX) dx = DMAX;
            else if (dx < -DMAX) dx = -DMAX;
            if (dy > DMAX) dy = DMAX;
            else if (dy < -DMAX) dy = -DMAX;
            int256 dot = dx * ex + dy * ey;
            int256 t = Q;
            if (ee == 0 || dot <= 0) {
                t = 0;
            } else if (dot < ee) {
                int256 r = dot;
                t = 0;
                for (uint256 k; k < 4; ++k) {
                    int256 q = (r * 16) / ee;
                    t = t * 16 + q;
                    r = r * 16 - q * ee;
                }
            }
            int256 rx = dx - ((ex * t) >> 16);
            int256 ry = dy - ((ey * t) >> 16);
            return int256(isqrt(uint256(rx * rx + ry * ry)));
        }
    }

    /// The shade at Q12 point (x, y), Q16: max(0, 1 + kv (vary - 1/2)) times
    /// each term in record order.
    function regionShade(PencilRegion memory R, int256 x12, int256 y12, int256 vary16, uint256 exp2)
        internal
        pure
        returns (int256 s)
    {
        unchecked {
            s = Q + ((R.kv * (vary16 - Q / 2)) >> 16);
            if (s < 0) s = 0;
            int256[] memory T = R.terms;
            uint256 nt = R.nt;
            for (uint256 k; k < nt; ++k) {
                uint256 o = k * 8;
                int256 d = _termDist(T, o, x12, y12);
                if (T[o] == 0) {
                    int256 v = (s * (Q + ((T[o + 6] * expNeg16(fdiv(d * Q, T[o + 7]), exp2)) >> 16))) >> 16;
                    s = v < SHADE_MAX ? v : SHADE_MAX;
                } else {
                    int256 e0 = T[o + 6];
                    int256 t = fdiv((d * 16 - e0) * Q, T[o + 7] - e0);
                    if (t < 0) t = 0;
                    if (t > Q) t = Q;
                    s = (s * smooth16(t)) >> 16;
                }
            }
        }
    }
}

src/raster/PencilRaster.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

pragma solidity ^0.8.13;

import "../../lib/kohi/Fix64.sol";
import "../../lib/kohi/Trig256.sol";
import "../SinLutSingleton.sol";
import "./PencilCore.sol";
import "./PencilTables.sol";

/* =============================================================================
 *  PencilRaster · render family 6, wax color pencil and graphite on paper
 * =============================================================================
 *
 * The pencil family (PENCIL 0xb0) draws with per-pixel state: paper tooth,
 * wax, and per-channel optical density. This library is the on-chain
 * rasterizer of the family. It renders a window of a pencil draw stream
 * byte for byte equal to the reference oracle (the reference PencilSink).
 *
 * THE STREAM. Every number is big-endian. Every i32 is a Q16 value.
 *
 *   begin   b0 | u16 width | u16 height
 *   paper   0c | u8 r | u8 g | u8 b | u32 seed | i32 sheetMm
 *              (sheetMm: the canvas width in mm)
 *   region  0d | u8 slot | i32 kv wobAmp wobBias tolL
 *              | u16 npoly | npoly x (u8 n | n x (i32 x | i32 y))
 *              | u16 nterm | nterm x (u8 kind | i32 ax ay bx by a b)
 *   stroke  0e | u8 flags | u8 slot | i32 abR abG abB reach strength wax
 *              | i32 r | i32 off | u16 n | n x (i32 x | i32 y | i32 p)
 *   trait   02 | u8 id | i64 value          (skipped)
 *   end     b1
 *
 * Any other record (background, path, stamp, field, mesh) REVERTS. A
 * family-6 render draws pencil records only, never a partial or substituted
 * picture.
 *
 * THE RENDER, in the order of the oracle:
 *
 *   paper   the tooth: a Worley grain, three value-noise layers, and 2,600
 *           laid fibres walked in Fix64 with the shared sine table,
 *           equalized through the pinned 65-knot CDF. The brightness: two
 *           value-noise layers and the falloff of a scanner. vary: two
 *           layers. The 256-entry striation table (Fix64 exp and log, from
 *           the Trig256 library).
 *      |
 *      v
 *   stroke  a coverage mask of round stamps along the polyline
 *           (max-combined, striated), clipped and shaded by the region of
 *           the slot when flagged. Then a TWO-PASS wax deposit: pass 1
 *           against the wax before the stroke, pass 2 for real. Pass 2
 *           reads the wax of pass 1 to the left and above, and the wax
 *           before the stroke to the right and below. The jitter is
 *           hash2(pixel, stroke index).
 *      |
 *      v
 *   end     Beer-Lambert of the per-channel density over the paper, the
 *           linear -> sRGB table, then the [1 2 1] softening of a scanner
 *           each way (edge pixels kept).
 *
 * Every per-pixel quantity is an exact integer with floor semantics. The
 * per-pixel state that the oracle keeps in 32-bit typed arrays (density,
 * wax, the footprint coverage) wraps to int32 on store, exactly as there.
 *
 * TILES. Pencil state crosses records, so a window renders over a WORK
 * window: the requested tile grown by `apron` px on every side, clamped to
 * the canvas. The paper is pointwise (every lattice value and fibre is
 * index-addressable), so only the work window gets paper, and only the
 * fibres whose start is within reach of it are walked (a fibre moves at
 * most 0.7 px a step). Strokes replay in stream order and touch only
 * work-window pixels. A neighbor outside the work window reads as 0, as
 * off-canvas does in the oracle. The composite and the [1 2 1] pass run
 * over the work window, and the tile is cut out of it.
 *
 * A tile equals the full render where the apron covers the dependency
 * depth. Each stroke spreads wax influence at most 2 px past a pixel, so
 * the dependency radius of a pixel is 2 px per overlapping stroke plus 1 px
 * for the softening. A zero window renders the whole canvas, exact
 * everywhere.
 *
 * DEPLOYMENT. A separately deployed library with no state. PencilRenderer
 * reaches `render` by DELEGATECALL. It links Trig256 (MIT).
 */
library PencilRaster {
    /// The one error. Codes: 1 malformed stream · 2 not a pencil record ·
    /// 3 canvas too large · 4 a second paper · 5 a stroke before the paper ·
    /// 6 a stroke on an empty slot · 7 bad window.
    error PencilError(uint256 code);

    int256 internal constant Q = 65536;
    int256 internal constant P_MIN = 262;
    int256 internal constant RR_BASE = 40632;
    int256 internal constant RR_PRESS = 24904;
    int256 internal constant DEP_C0 = 29491;
    int256 internal constant DEP_V0 = 22938;
    int256 internal constant DEP_V1 = 42598;
    int256 internal constant JIT_0 = 60948;
    int256 internal constant JIT_1 = 9175;
    int256 internal constant PL_TOOTH0 = 62390;
    int256 internal constant PL_TOOTH1 = 3932;
    int256 internal constant FALLOFF = 2294;
    int256 internal constant FALLOFF_CY = 31457;

    int64 internal constant F_0_04 = 171798691;
    int64 internal constant F_0_08 = 343597383;
    int64 internal constant F_0_15 = 644245094;
    int64 internal constant F_0_7 = 3006477107;
    int64 internal constant F_0_8 = 3435973836;
    int64 internal constant F_HALF = 2147483648;
    int64 internal constant F_QUARTER = 1073741824;
    int64 internal constant F_0_75 = 3221225472;

    /// The state of the render. Per-pixel arrays are raw word arrays over the
    /// work window, index (y - Y0) * WW + (x - X0). dens holds 3 words per
    /// pixel.
    struct Ctx {
        int256 W;
        int256 H;
        int256 X0;
        int256 Y0;
        int256 X1;
        int256 Y1;
        int256 WW;
        int256 WH;
        uint256 tooth;
        uint256 paperL;
        uint256 vary;
        uint256 wax;
        uint256 dens;
        uint256 mask;
        uint256 wp;
        uint256 fpI;
        uint256 fpV;
        bool paper;
        int256 PL0;
        int256 PL1;
        int256 PL2;
        uint256 stri;
        uint256 exp2;
        uint256 pow06;
        uint256 l2s;
        uint256 cdf;
        uint256 lut;
        PencilRegion[] slots;
        uint256 strokes;
    }

    /// One stroke record, plus its box clipped to the work window.
    struct Stroke {
        uint256 flags;
        uint256 slot;
        int256 abR;
        int256 abG;
        int256 abB;
        int256 reach;
        int256 strength;
        int256 wax;
        int256 r;
        int256 off;
        uint256 n;
        uint256 pts; // absolute calldata offset of point 0
        int256 bx0;
        int256 by0;
        int256 bx1;
        int256 by1;
        int256 bw;
        uint256 k; // stroke index
    }

    /// The Worley cells around the work window and their feature points.
    struct WGrid {
        int256 wdq;
        int256 cxa;
        int256 cya;
        int256 cw;
        uint256 fxs;
        uint256 fys;
    }

    /// A value-noise layer's axes over the work window and its lattice values.
    struct VGrid {
        uint256 colI;
        uint256 colS;
        uint256 rowI;
        uint256 rowS;
        int256 ixa;
        int256 iya;
        int256 cw;
        uint256 g;
    }

    /// One stamp: its pixel range and the values the inner loop reads.
    struct Stamp {
        int256 Xa;
        int256 Xb;
        int256 Ya;
        int256 Yb;
        int256 cx8;
        int256 cy8;
        int256 rr2;
        int256 p;
        int256 nx;
        int256 ny;
        int256 off24;
        int256 bx0;
        int256 by0;
        int256 bw;
        uint256 mask;
        uint256 stri;
        // the segment the stamps walk (after the fields the inner loop reads)
        int256 ax;
        int256 ay;
        int256 dx;
        int256 dy;
        int256 ap;
        int256 dp;
        int256 steps;
    }

    // ---- entry -------------------------------------------------------------

    /// @notice Render a window of a pencil draw stream as top-down RGBA.
    /// @dev The work window is the tile grown by `apron` px on every side,
    ///      clamped to the canvas (see the header for when a tile is exact).
    ///      Reverts PencilError: 1 on a malformed or truncated stream, 2 on a
    ///      record outside the family, 3 on a canvas side over 4096, 4 on a
    ///      second paper, 5 on a stroke before the paper, 6 on a clip or
    ///      shade stroke with an empty slot, 7 on a window outside the canvas
    ///      or a negative apron. A frame too large for the gas of the call
    ///      runs out of gas.
    /// @param stream The canonical draw stream (begin through end).
    /// @param wx     Window origin x, in absolute canvas pixels.
    /// @param wy     Window origin y, in absolute canvas pixels.
    /// @param ww     Window width; 0 means the whole canvas (and then wx,
    ///               wy and wh are ignored).
    /// @param wh     Window height.
    /// @param apron  Px the work window extends past the tile on every side.
    /// @return width  The full canvas width.
    /// @return height The full canvas height.
    /// @return rgba   The window's pixels, top-down RGBA, ww * wh * 4 bytes.
    function render(bytes calldata stream, int256 wx, int256 wy, int256 ww, int256 wh, int256 apron)
        external
        view
        returns (uint32 width, uint32 height, bytes memory rgba)
    {
        Ctx memory c;
        if (stream.length < 5 || _u(stream, 0, 1) != 0xb0) revert PencilError(1);
        c.W = int256(_u(stream, 1, 2));
        c.H = int256(_u(stream, 3, 2));
        if (c.W > 4096 || c.H > 4096) revert PencilError(3);
        if (ww == 0) {
            wx = 0;
            wy = 0;
            ww = c.W;
            wh = c.H;
        }
        if (wx < 0 || wy < 0 || ww <= 0 || wh <= 0 || wx + ww > c.W || wy + wh > c.H || apron < 0) {
            revert PencilError(7);
        }
        c.X0 = wx > apron ? wx - apron : int256(0);
        c.Y0 = wy > apron ? wy - apron : int256(0);
        c.X1 = wx + ww + apron < c.W ? wx + ww + apron : c.W;
        c.Y1 = wy + wh + apron < c.H ? wy + wh + apron : c.H;
        c.WW = c.X1 - c.X0;
        c.WH = c.Y1 - c.Y0;
        uint256 N = uint256(c.WW * c.WH);
        c.wax = _alloc(N, true);
        c.dens = _alloc(3 * N, true);
        c.mask = _alloc(N, false);
        c.wp = _alloc(N, false);
        c.fpI = _alloc(N, false);
        c.fpV = _alloc(N, false);
        c.slots = new PencilRegion[](256);
        _replay(c, stream);
        rgba = _finish(c, wx - c.X0, wy - c.Y0, ww, wh);
        width = uint32(uint256(c.W));
        height = uint32(uint256(c.H));
    }

    function _replay(Ctx memory c, bytes calldata stream) private view {
        uint256 p = 5;
        while (true) {
            uint256 tag = _u(stream, p, 1);
            p += 1;
            if (tag == 0xb1) return;
            if (tag == 0x02) {
                _u(stream, p + 8, 1); // bounds
                p += 9;
            } else if (tag == 0x0c) {
                p = _paperRecord(c, stream, p);
            } else if (tag == 0x0d) {
                p = _regionRecord(c, stream, p);
            } else if (tag == 0x0e) {
                p = _strokeRecord(c, stream, p);
            } else {
                revert PencilError(2);
            }
        }
    }

    // ---- stream reads ------------------------------------------------------

    function _u(bytes calldata s, uint256 off, uint256 n) private pure returns (uint256 v) {
        if (off + n > s.length) revert PencilError(1);
        assembly {
            v := shr(sub(256, shl(3, n)), calldataload(add(s.offset, off)))
        }
    }

    function _i32(bytes calldata s, uint256 off) private pure returns (int256 v) {
        if (off + 4 > s.length) revert PencilError(1);
        assembly {
            v := signextend(3, shr(224, calldataload(add(s.offset, off))))
        }
    }

    /// i32 at an absolute calldata offset (bounds checked by the caller).
    function _cd32(uint256 at) private pure returns (int256 v) {
        assembly {
            v := signextend(3, shr(224, calldataload(at)))
        }
    }

    // ---- memory ------------------------------------------------------------

    function _alloc(uint256 words, bool zero) private pure returns (uint256 ptr) {
        assembly {
            ptr := mload(0x40)
            let len := shl(5, words)
            mstore(0x40, add(ptr, add(len, 0x20)))
            if zero { calldatacopy(ptr, calldatasize(), len) }
        }
    }

    function _ld(uint256 base, uint256 i) private pure returns (int256 v) {
        assembly {
            v := mload(add(base, shl(5, i)))
        }
    }

    function _st(uint256 base, uint256 i, int256 v) private pure {
        assembly {
            mstore(add(base, shl(5, i)), v)
        }
    }

    /// int32 wrap (the oracle's typed-array store)
    function _w32(int256 v) private pure returns (int256 r) {
        assembly {
            r := signextend(3, v)
        }
    }

    function _table(bytes memory t) private pure returns (uint256 p) {
        assembly {
            p := add(t, 0x20)
        }
    }

    // ---- paper -------------------------------------------------------------

    function _paperRecord(Ctx memory c, bytes calldata s, uint256 p) private view returns (uint256) {
        uint256 r = _u(s, p, 1);
        uint256 g = _u(s, p + 1, 1);
        uint256 b = _u(s, p + 2, 1);
        uint256 seed = _u(s, p + 3, 4);
        int256 sheet = _i32(s, p + 7);
        if (c.paper) revert PencilError(4);
        c.paper = true;
        c.exp2 = _table(PencilTables.EXP2);
        c.pow06 = _table(PencilTables.POW06);
        c.l2s = _table(PencilTables.L2S);
        c.cdf = _table(PencilTables.CDF);
        {
            uint256 s2l = _table(PencilTables.S2L);
            c.PL0 = _s2l(s2l, r);
            c.PL1 = _s2l(s2l, g);
            c.PL2 = _s2l(s2l, b);
        }
        address lutAddr = SINLUT;
        uint256 lut;
        assembly {
            lut := mload(0x40)
            mstore(0x40, add(lut, 0x820))
            extcodecopy(lutAddr, lut, 1, 0x800)
        }
        c.lut = lut;
        _makePaper(c, seed, sheet);
        return p + 11;
    }

    function _makePaper(Ctx memory c, uint256 seed, int256 sheet) private pure {
        PencilLayout memory L = PencilCore.paperLayout(c.W, c.H, sheet, seed, true);
        uint256 N = uint256(c.WW * c.WH);
        c.tooth = _alloc(N, true);
        _worley(c, L);
        for (uint256 i = 1; i <= 3; ++i) _addVn(c, c.tooth, L.lat[i], L.seed);
        _fibres(c, L);
        _equalise(c, N);
        c.paperL = _alloc(N, false);
        for (uint256 i; i < N; ++i) _st(c.paperL, i, Q);
        _addVn(c, c.paperL, L.lat[4], L.seed);
        _addVn(c, c.paperL, L.lat[5], L.seed);
        _falloff(c);
        c.vary = _alloc(N, false);
        for (uint256 i; i < N; ++i) _st(c.vary, i, Q / 2);
        _addVn(c, c.vary, L.lat[6], L.seed);
        _addVn(c, c.vary, L.lat[7], L.seed);
        c.stri = _striation(L);
    }

    function _s2l(uint256 t, uint256 i) private pure returns (int256 v) {
        assembly {
            v := shr(232, mload(add(t, mul(i, 3))))
        }
    }

    /// Worley grain: the feature point of each cell (exact, in Q16 px), the
    /// nearest of the 3 x 3 cells around the cell of the pixel.
    function _worley(Ctx memory c, PencilLayout memory L) private pure {
        unchecked {
            PencilLat memory Wl = L.lat[0];
            WGrid memory g;
            g.wdq = Wl.den * Q;
            g.cxa = (c.X0 * Wl.num) / g.wdq - 1;
            g.cya = (c.Y0 * Wl.num) / g.wdq - 1;
            {
                int256 cxb = ((c.X1 - 1) * Wl.num) / g.wdq + 1;
                int256 cyb = ((c.Y1 - 1) * Wl.num) / g.wdq + 1;
                if (g.cxa < 0) g.cxa = 0;
                if (g.cya < 0) g.cya = 0;
                if (cxb > Wl.gw - 1) cxb = Wl.gw - 1;
                if (cyb > Wl.gh - 1) cyb = Wl.gh - 1;
                g.cw = cxb - g.cxa + 1;
                uint256 nc = uint256(g.cw * (cyb - g.cya + 1));
                g.fxs = _alloc(nc, false);
                g.fys = _alloc(nc, false);
                _features(g, Wl, L.seed, cyb);
            }
            uint256 wi;
            for (int256 y = c.Y0; y < c.Y1; ++y) {
                for (int256 x = c.X0; x < c.X1; ++x) {
                    _st(c.tooth, wi, _ld(c.tooth, wi) + _worleyAt(g, Wl, x, y));
                    ++wi;
                }
            }
        }
    }

    function _worleyAt(WGrid memory g, PencilLat memory Wl, int256 x, int256 y) private pure returns (int256) {
        unchecked {
            int256 q = (int256(PencilCore.isqrt(uint256(_nearest(g, Wl, x, y)))) * Q) / Wl.cell;
            if (q > Q) q = Q;
            return (Wl.amp * (Q - q)) >> 16;
        }
    }

    /// The feature point of each cell, exact in Q16 px:
    /// (k * 2^32 + U) * den / num.
    function _features(WGrid memory g, PencilLat memory Wl, uint256 seed, int256 cyb) private pure {
        unchecked {
            uint256 j;
            uint256 den = uint256(Wl.den);
            uint256 num = uint256(Wl.num);
            int256 cxb = g.cxa + g.cw - 1;
            for (int256 yy = g.cya; yy <= cyb; ++yy) {
                for (int256 xx = g.cxa; xx <= cxb; ++xx) {
                    uint256 base = uint256(Wl.off) + 2 * uint256(yy * Wl.gw + xx);
                    _st(g.fxs, j, int256((((uint256(xx) << 32) + PencilCore.mb32(seed, base)) * den) / num));
                    _st(g.fys, j, int256((((uint256(yy) << 32) + PencilCore.mb32(seed, base + 1)) * den) / num));
                    ++j;
                }
            }
        }
    }

    /// The squared distance (Q16 px) to the nearest feature point of the
    /// 3 x 3 cells.
    function _nearest(WGrid memory g, PencilLat memory Wl, int256 x, int256 y) private pure returns (int256 best) {
        unchecked {
            int256 cx = (x * Wl.num) / g.wdq;
            int256 cy = (y * Wl.num) / g.wdq;
            best = type(int256).max;
            for (int256 yy = cy - 1; yy <= cy + 1; ++yy) {
                if (yy < 0 || yy >= Wl.gh) continue;
                for (int256 xx = cx - 1; xx <= cx + 1; ++xx) {
                    if (xx < 0 || xx >= Wl.gw) continue;
                    uint256 k = uint256((yy - g.cya) * g.cw + (xx - g.cxa));
                    int256 dx = _ld(g.fxs, k) - x * Q;
                    int256 dy = _ld(g.fys, k) - y * Q;
                    int256 d = dx * dx + dy * dy;
                    if (d < best) best = d;
                }
            }
        }
    }

    /// Add one value-noise layer over the work window into the word array at
    /// `out`.
    function _addVn(Ctx memory c, uint256 out, PencilLat memory L, uint256 seed) private pure {
        unchecked {
            VGrid memory v = _vnGrid(c, L, seed);
            uint256 WW = uint256(c.WW);
            uint256 WH = uint256(c.WH);
            uint256 wi;
            for (uint256 y; y < WH; ++y) {
                uint256 r0 = uint256((_ld(v.rowI, y) - v.iya) * v.cw);
                int256 ty = _ld(v.rowS, y);
                for (uint256 x; x < WW; ++x) {
                    _st(out, wi, _ld(out, wi) + _vnPx(v, L.amp, r0, x, ty));
                    ++wi;
                }
            }
        }
    }

    function _vnPx(VGrid memory v, int256 amp, uint256 r0, uint256 x, int256 ty) private pure returns (int256) {
        unchecked {
            uint256 i = uint256(_ld(v.colI, x) - v.ixa);
            int256 sx = _ld(v.colS, x);
            uint256 g = v.g;
            uint256 r1 = r0 + uint256(v.cw);
            int256 a = _ld(g, r0 + i);
            int256 top = a + (((_ld(g, r0 + i + 1) - a) * sx) >> 16);
            int256 cc = _ld(g, r1 + i);
            int256 bot = cc + (((_ld(g, r1 + i + 1) - cc) * sx) >> 16);
            return (amp * (top + (((bot - top) * ty) >> 16))) >> 16;
        }
    }

    /// Per-axis parameters over the work window and the lattice values they
    /// read.
    function _vnGrid(Ctx memory c, PencilLat memory L, uint256 seed) private pure returns (VGrid memory v) {
        unchecked {
            uint256 WW = uint256(c.WW);
            uint256 WH = uint256(c.WH);
            v.colI = _alloc(WW, false);
            v.colS = _alloc(WW, false);
            v.rowI = _alloc(WH, false);
            v.rowS = _alloc(WH, false);
            for (uint256 i; i < WW; ++i) {
                (int256 a, int256 b) = PencilCore.vnAxis(c.X0 + int256(i), L);
                _st(v.colI, i, a);
                _st(v.colS, i, b);
            }
            for (uint256 i; i < WH; ++i) {
                (int256 a, int256 b) = PencilCore.vnAxis(c.Y0 + int256(i), L);
                _st(v.rowI, i, a);
                _st(v.rowS, i, b);
            }
            v.ixa = _ld(v.colI, 0);
            v.iya = _ld(v.rowI, 0);
            v.cw = _ld(v.colI, WW - 1) + 2 - v.ixa;
            int256 ch = _ld(v.rowI, WH - 1) + 2 - v.iya;
            v.g = _alloc(uint256(v.cw * ch), false);
            uint256 j;
            for (int256 iy = v.iya; iy < v.iya + ch; ++iy) {
                uint256 rowOff = uint256(L.off + iy * L.gw);
                for (int256 ix = v.ixa; ix < v.ixa + v.cw; ++ix) {
                    _st(v.g, j, PencilCore.latQ16(PencilCore.mb32(seed, rowOff + uint256(ix))));
                    ++j;
                }
            }
        }
    }

    /// The laid fibres, faintly raised. Only the fibres whose start is within
    /// reach of the work window are walked.
    function _fibres(Ctx memory c, PencilLayout memory L) private pure {
        unchecked {
            uint256 seed = L.seed;
            for (uint256 f; f < PencilCore.FIBRES; ++f) {
                uint256 fb = L.fib[f];
                uint256 n = fb & 0xffffffff;
                if (n == 0) continue;
                uint256 base = fb >> 32;
                int256 x = int256(PencilCore.mb32(seed, base) * uint256(c.W));
                int256 y = int256(PencilCore.mb32(seed, base + 1) * uint256(c.H));
                if (_away(c, x, y, n)) continue;
                _walk(c, seed, base, n, int64(x), int64(y));
            }
        }
    }

    function _walk(Ctx memory c, uint256 seed, uint256 base, uint256 n, int64 x, int64 y) private pure {
        unchecked {
            int64 a = Fix64.mul(int64(uint64(PencilCore.mb32(seed, base + 2))), Fix64.TWO_PI);
            int256 amp = int256(Fix64.add(F_0_04, Fix64.mul(int64(uint64(PencilCore.mb32(seed, base + 4))), F_0_08))) >> 16;
            for (uint256 s; s < n; ++s) {
                a = Fix64.add(a, Fix64.mul(int64(uint64(PencilCore.mb32(seed, base + 5 + s))) - F_HALF, F_0_15));
                x = Fix64.add(x, Fix64.mul(Trig256.cos(a, c.lut), F_0_7));
                y = Fix64.add(y, Fix64.mul(Trig256.sin(a, c.lut), F_0_7));
                if (x >= 0 && y >= 0) _lay(c, x, y, amp);
                // a fibre that cannot reach the work window again is done
                // with it
                if (_away(c, x, y, n - s - 1)) break;
            }
        }
    }

    /// True when a fibre at Fix64 (x, y) with `rem` steps left cannot reach
    /// the work window: a step moves at most 0.7 px per axis
    /// (|cos|, |sin| <= 1).
    function _away(Ctx memory c, int256 x, int256 y, uint256 rem) private pure returns (bool) {
        unchecked {
            int256 reach = int256((rem * 7) / 10) + 2;
            int256 px = x >> 32;
            int256 py = y >> 32;
            return px + reach < c.X0 || px - reach >= c.X1 || py + reach < c.Y0 || py - reach >= c.Y1;
        }
    }

    function _lay(Ctx memory c, int64 x, int64 y, int256 amp) private pure {
        unchecked {
            int256 px = int256(x >> 32);
            int256 py = int256(y >> 32);
            // on the canvas (x < W, y < H in Fix64 is px < W) and in the
            // work window
            if (px >= c.X0 && px < c.X1 && py >= c.Y0 && py < c.Y1) {
                uint256 wi = uint256((py - c.Y0) * c.WW + (px - c.X0));
                _st(c.tooth, wi, _ld(c.tooth, wi) + amp);
            }
        }
    }

    function _cdf(uint256 t, uint256 k) private pure returns (int256 v) {
        assembly {
            v := signextend(3, shr(224, mload(add(t, shl(2, k)))))
        }
    }

    /// Map each raw tooth value to its quantile through the pinned CDF.
    function _equalise(Ctx memory c, uint256 N) private pure {
        unchecked {
            uint256 t = c.cdf;
            int256 k0 = _cdf(t, 0);
            int256 kK = _cdf(t, 64);
            for (uint256 i; i < N; ++i) {
                int256 v = _ld(c.tooth, i);
                int256 e;
                if (v <= k0) {
                    e = 0;
                } else if (v >= kK) {
                    e = Q;
                } else {
                    uint256 lo = 0;
                    uint256 hi = 64;
                    while (hi - lo > 1) {
                        uint256 m = (lo + hi) >> 1;
                        if (_cdf(t, m) <= v) lo = m;
                        else hi = m;
                    }
                    int256 klo = _cdf(t, lo);
                    e = (int256(lo) * Q + ((v - klo) * Q) / (_cdf(t, hi) - klo)) / 64;
                }
                _st(c.tooth, i, e);
            }
        }
    }

    /// The falloff of the scanner over the brightness layers.
    function _falloff(Ctx memory c) private pure {
        unchecked {
            uint256 wi;
            for (int256 y = c.Y0; y < c.Y1; ++y) {
                int256 dy = (y * Q) / c.H - FALLOFF_CY;
                for (int256 x = c.X0; x < c.X1; ++x) {
                    int256 dx = (x * Q) / c.W - Q / 2;
                    int256 v = _ld(c.paperL, wi);
                    _st(c.paperL, wi, (v * (Q - ((FALLOFF * ((dx * dx + dy * dy) >> 16)) >> 16))) >> 16);
                    ++wi;
                }
            }
        }
    }

    /// The striation of the tip: 256 draws, [1 2 1]-smoothed, raised to 0.8
    /// in Fix64.
    function _striation(PencilLayout memory L) private pure returns (uint256 st) {
        unchecked {
            uint256 raw = _alloc(256, false);
            for (uint256 i; i < 256; ++i) _st(raw, i, int256(PencilCore.mb32(L.seed, uint256(L.striOff) + i)));
            st = _alloc(256, false);
            for (uint256 i; i < 256; ++i) {
                int256 v = (_ld(raw, (i + 255) & 255) + 2 * _ld(raw, i) + _ld(raw, (i + 1) & 255)) >> 2;
                int64 pw = v > 0 ? Trig256.exp(Fix64.mul(F_0_8, Trig256.log(int64(v)))) : int64(0);
                _st(st, i, int256(Fix64.add(F_QUARTER, Fix64.mul(F_0_75, pw))) >> 16);
            }
        }
    }

    // ---- regions -----------------------------------------------------------

    function _regionRecord(Ctx memory c, bytes calldata s, uint256 p) private pure returns (uint256) {
        uint256 slot = _u(s, p, 1);
        int256 kv = _i32(s, p + 1);
        int256 wobAmp = _i32(s, p + 5);
        int256 wobBias = _i32(s, p + 9);
        int256 tolL = _i32(s, p + 13);
        uint256 npoly = _u(s, p + 17, 2);
        p += 19;
        int256[][] memory polys = new int256[][](npoly);
        for (uint256 i; i < npoly; ++i) {
            uint256 n = _u(s, p, 1);
            p += 1;
            int256[] memory poly = new int256[](2 * n);
            for (uint256 j; j < 2 * n; ++j) {
                poly[j] = _i32(s, p);
                p += 4;
            }
            polys[i] = poly;
        }
        uint256 nt = _u(s, p, 2);
        p += 2;
        int256[] memory terms = new int256[](7 * nt);
        for (uint256 k; k < nt; ++k) {
            terms[7 * k] = int256(_u(s, p, 1));
            p += 1;
            for (uint256 j = 1; j < 7; ++j) {
                terms[7 * k + j] = _i32(s, p);
                p += 4;
            }
        }
        c.slots[slot] = PencilCore.buildRegion(kv, wobAmp, wobBias, tolL, polys, terms);
        return p;
    }

    // ---- strokes -----------------------------------------------------------

    function _strokeRecord(Ctx memory c, bytes calldata s, uint256 p) private pure returns (uint256) {
        Stroke memory k;
        k.flags = _u(s, p, 1);
        k.slot = _u(s, p + 1, 1);
        k.abR = _i32(s, p + 2);
        k.abG = _i32(s, p + 6);
        k.abB = _i32(s, p + 10);
        k.reach = _i32(s, p + 14);
        k.strength = _i32(s, p + 18);
        k.wax = _i32(s, p + 22);
        k.r = _i32(s, p + 26);
        k.off = _i32(s, p + 30);
        k.n = _u(s, p + 34, 2);
        p += 36;
        if (p + 12 * k.n > s.length) revert PencilError(1);
        uint256 base;
        assembly {
            base := s.offset
        }
        k.pts = base + p;
        k.k = c.strokes++;
        if (!c.paper) revert PencilError(5);
        _stroke(c, k);
        return p + 12 * k.n;
    }

    function _pt(Stroke memory k, uint256 i, uint256 f) private pure returns (int256) {
        return _cd32(k.pts + 12 * i + 4 * f);
    }

    function _stroke(Ctx memory c, Stroke memory k) private pure {
        unchecked {
            uint256 n = k.n;
            if (n == 0) return;
            int256 minx = type(int256).max;
            int256 miny = type(int256).max;
            int256 maxx = type(int256).min;
            int256 maxy = type(int256).min;
            for (uint256 i; i < n; ++i) {
                int256 x = _pt(k, i, 0);
                int256 y = _pt(k, i, 1);
                if (x < minx) minx = x;
                if (x > maxx) maxx = x;
                if (y < miny) miny = y;
                if (y > maxy) maxy = y;
            }
            {
                int256 pad = -PencilCore.fdiv(-k.r, Q) + 2;
                int256 x0 = (minx >> 16) - pad;
                int256 y0 = (miny >> 16) - pad;
                int256 x1 = -PencilCore.fdiv(-maxx, Q) + pad;
                int256 y1 = -PencilCore.fdiv(-maxy, Q) + pad;
                if (x0 < 0) x0 = 0;
                if (y0 < 0) y0 = 0;
                if (x1 > c.W - 1) x1 = c.W - 1;
                if (y1 > c.H - 1) y1 = c.H - 1;
                if (x1 < x0 || y1 < y0) return;
                if ((k.flags & 5) != 0 && !c.slots[k.slot].set) revert PencilError(6);
                // the box, cut to the work window
                if (x0 < c.X0) x0 = c.X0;
                if (y0 < c.Y0) y0 = c.Y0;
                if (x1 > c.X1 - 1) x1 = c.X1 - 1;
                if (y1 > c.Y1 - 1) y1 = c.Y1 - 1;
                if (x1 < x0 || y1 < y0) return;
                k.bx0 = x0;
                k.by0 = y0;
                k.bx1 = x1;
                k.by1 = y1;
                k.bw = x1 - x0 + 1;
            }
            uint256 nb = uint256(k.bw * (k.by1 - k.by0 + 1));
            {
                uint256 m = c.mask;
                assembly {
                    calldatacopy(m, calldatasize(), shl(5, nb))
                }
            }
            _rasterize(c, k);
            uint256 nf = _footprint(c, k);
            if (nf == 0) return;
            _pass1(c, k, nf);
            _pass2(c, k, nf);
        }
    }

    /// Round stamps along the polyline into the mask (max-combined), striated.
    function _rasterize(Ctx memory c, Stroke memory k) private pure {
        unchecked {
            Stamp memory sp;
            sp.off24 = k.off * 256;
            sp.bx0 = k.bx0;
            sp.by0 = k.by0;
            sp.bw = k.bw;
            sp.mask = c.mask;
            sp.stri = c.stri;
            int256 r3 = 3 * (k.r >> 8);
            uint256 n = k.n;
            for (uint256 i; i + 1 < n; ++i) {
                sp.ax = _pt(k, i, 0);
                sp.ay = _pt(k, i, 1);
                sp.dx = _pt(k, i + 1, 0) - sp.ax;
                sp.dy = _pt(k, i + 1, 1) - sp.ay;
                int256 len8;
                {
                    int256 dx8 = sp.dx >> 8;
                    int256 dy8 = sp.dy >> 8;
                    len8 = int256(PencilCore.isqrt(uint256(dx8 * dx8 + dy8 * dy8)));
                    if (len8 == 0) continue;
                    sp.nx = PencilCore.fdiv(-dy8 * Q, len8);
                    sp.ny = PencilCore.fdiv(dx8 * Q, len8);
                }
                int256 steps = -PencilCore.fdiv(-len8 * 10, r3);
                if (steps < 1) steps = 1;
                sp.steps = steps;
                sp.ap = _pt(k, i, 2);
                sp.dp = _pt(k, i + 1, 2) - sp.ap;
                int256 end = steps + (i + 2 == n ? int256(1) : int256(0));
                for (int256 st; st < end; ++st) _stampStep(k, sp, st);
            }
        }
    }

    function _stampStep(Stroke memory k, Stamp memory sp, int256 st) private pure {
        unchecked {
            int256 steps = sp.steps;
            int256 p = sp.ap + PencilCore.fdiv(sp.dp * st, steps);
            if (p <= P_MIN) return;
            _stampAt(k, sp, sp.ax + PencilCore.fdiv(sp.dx * st, steps), sp.ay + PencilCore.fdiv(sp.dy * st, steps), p);
        }
    }

    function _stampAt(Stroke memory k, Stamp memory sp, int256 cx, int256 cy, int256 p) private pure {
        unchecked {
            int256 rr = (k.r * (RR_BASE + ((RR_PRESS * (p < Q ? p : Q)) >> 16))) >> 16;
            int256 rr8 = rr >> 8;
            sp.rr2 = rr8 * rr8;
            if (sp.rr2 == 0) return;
            sp.cx8 = cx >> 8;
            sp.cy8 = cy >> 8;
            sp.p = p;
            int256 Xa = (cx - rr) >> 16;
            int256 Xb = -PencilCore.fdiv(-(cx + rr), Q);
            int256 Ya = (cy - rr) >> 16;
            int256 Yb = -PencilCore.fdiv(-(cy + rr), Q);
            sp.Xa = Xa > k.bx0 ? Xa : k.bx0;
            sp.Xb = Xb < k.bx1 ? Xb : k.bx1;
            sp.Ya = Ya > k.by0 ? Ya : k.by0;
            sp.Yb = Yb < k.by1 ? Yb : k.by1;
            _stampLoop(sp);
        }
    }

    /// The pixels of the stamp: solid inside 0.45 of the squared radius, then
    /// a linear fall to its edge, times the striation at the offset of the
    /// pixel across the stroke.
    function _stampLoop(Stamp memory sp) private pure {
        assembly {
            // coverage of one pixel at (ddx, ddy) from the stamp center,
            // dd2 < rr2
            function cov(p, ddx, ddy, dd2) -> v {
                let d2 := sdiv(mul(dd2, 65536), mload(add(p, 0xc0)))
                let fall := 65536
                if iszero(slt(d2, 29491)) { fall := sar(16, mul(sub(65536, d2), 119144)) }
                v := sar(16, mul(mload(add(p, 0xe0)), fall))
                // u = floor((ddx nx + ddy ny + off24) * 17 / 20)
                let num :=
                    mul(add(add(mul(ddx, mload(add(p, 0x100))), mul(ddy, mload(add(p, 0x120)))), mload(add(p, 0x140))), 17)
                let u := sdiv(num, 20)
                if and(slt(num, 0), iszero(iszero(smod(num, 20)))) { u := sub(u, 1) }
                let ui := sar(24, u)
                let uf := and(u, 0xffffff)
                let sti := mload(add(p, 0x1e0))
                let s0 := mload(add(sti, shl(5, and(ui, 255))))
                let s1 := mload(add(sti, shl(5, and(add(ui, 1), 255))))
                v := sar(16, mul(v, sar(24, add(mul(s0, sub(16777216, uf)), mul(s1, uf)))))
            }
            let Xb := mload(add(sp, 0x20))
            let Yb := mload(add(sp, 0x60))
            for { let yy := mload(add(sp, 0x40)) } iszero(sgt(yy, Yb)) { yy := add(yy, 1) } {
                let ddy := sub(mul(yy, 256), mload(add(sp, 0xa0)))
                // row base: mask + ((yy - by0) * bw - bx0) words
                let row :=
                    add(
                        mload(add(sp, 0x1c0)),
                        shl(5, sub(mul(sub(yy, mload(add(sp, 0x180))), mload(add(sp, 0x1a0))), mload(add(sp, 0x160))))
                    )
                for { let xx := mload(sp) } iszero(sgt(xx, Xb)) { xx := add(xx, 1) } {
                    let ddx := sub(mul(xx, 256), mload(add(sp, 0x80)))
                    let dd2 := add(mul(ddx, ddx), mul(ddy, ddy))
                    if slt(dd2, mload(add(sp, 0xc0))) {
                        let v := cov(sp, ddx, ddy, dd2)
                        let slotp := add(row, shl(5, xx))
                        if sgt(v, mload(slotp)) { mstore(slotp, v) }
                    }
                }
            }
        }
    }

    /// The footprint: covered pixels, clipped and shaded by the region of the
    /// slot.
    function _footprint(Ctx memory c, Stroke memory k) private pure returns (uint256 nf) {
        unchecked {
            PencilRegion memory R = c.slots[k.slot];
            int256 tol = (k.flags & 2) != 0 && R.set ? R.tolL : int256(0);
            uint256 o;
            for (int256 yy = k.by0; yy <= k.by1; ++yy) {
                for (int256 xx = k.bx0; xx <= k.bx1; ++xx) {
                    int256 v = _ld(c.mask, o);
                    ++o;
                    if (v <= P_MIN) continue;
                    uint256 wi = uint256((yy - c.Y0) * c.WW + (xx - c.X0));
                    v = _cover(c, k.flags, R, tol, xx, yy, v, wi);
                    if (v <= P_MIN) continue;
                    _st(c.fpI, nf, int256(wi));
                    _st(c.fpV, nf, _w32(v));
                    ++nf;
                }
            }
        }
    }

    /// The coverage of a covered pixel after the clip and the shade (0 when
    /// clipped).
    function _cover(Ctx memory c, uint256 flags, PencilRegion memory R, int256 tol, int256 xx, int256 yy, int256 v, uint256 wi)
        private
        pure
        returns (int256)
    {
        unchecked {
            if ((flags & 1) != 0 && !PencilCore.regionInside(R, xx * Q, yy * Q, tol, _ld(c.vary, wi))) return 0;
            if ((flags & 4) != 0) v = (v * PencilCore.regionShade(R, xx * 4096, yy * 4096, _ld(c.vary, wi), c.exp2)) >> 16;
            return v;
        }
    }

    /// The wax at a neighbor of work-window pixel wi: 0 off the canvas or off
    /// the work window. `pre` reads the wax before the stroke, otherwise the
    /// wax of pass 1 inside the box.
    function _nbr(Ctx memory c, Stroke memory k, int256 x, int256 y, bool pre) private pure returns (int256) {
        unchecked {
            if (x < c.X0 || y < c.Y0 || x >= c.X1 || y >= c.Y1) return 0;
            if (!pre && x >= k.bx0 && x <= k.bx1 && y >= k.by0 && y <= k.by1) {
                return _ld(c.wp, uint256((y - k.by0) * k.bw + x - k.bx0));
            }
            return _ld(c.wax, uint256((y - c.Y0) * c.WW + (x - c.X0)));
        }
    }

    function _pass1(Ctx memory c, Stroke memory k, uint256 nf) private pure {
        unchecked {
            // wp: the wax before the stroke over the box
            {
                uint256 o;
                for (int256 yy = k.by0; yy <= k.by1; ++yy) {
                    uint256 row = uint256((yy - c.Y0) * c.WW + (k.bx0 - c.X0));
                    for (int256 j; j < k.bw; ++j) {
                        _st(c.wp, o, _ld(c.wax, row + uint256(j)));
                        ++o;
                    }
                }
            }
            for (uint256 f; f < nf; ++f) {
                (uint256 wi, int256 w, int256 a) = _dep(c, k, f, false);
                int256 nw = w + ((a * k.wax) >> 16);
                int256 bi = (c.Y0 + int256(wi / uint256(c.WW)) - k.by0) * k.bw + c.X0 + int256(wi % uint256(c.WW)) - k.bx0;
                _st(c.wp, uint256(bi), _w32(nw < Q ? nw : Q));
            }
        }
    }

    function _pass2(Ctx memory c, Stroke memory k, uint256 nf) private pure {
        unchecked {
            for (uint256 f; f < nf; ++f) {
                (uint256 wi, int256 w, int256 a) = _dep(c, k, f, true);
                if (a == 0) continue;
                uint256 d = 3 * wi;
                _st(c.dens, d, _w32(_ld(c.dens, d) + ((k.abR * a) >> 16)));
                _st(c.dens, d + 1, _w32(_ld(c.dens, d + 1) + ((k.abG * a) >> 16)));
                _st(c.dens, d + 2, _w32(_ld(c.dens, d + 2) + ((k.abB * a) >> 16)));
                int256 nw = w + ((a * k.wax) >> 16);
                _st(c.wax, wi, _w32(nw < Q ? nw : Q));
            }
        }
    }

    /// The deposit of footprint entry f. Pass 1 reads the wax before the
    /// stroke all round. Pass 2 reads the wax of pass 1 to the left and above.
    function _dep(Ctx memory c, Stroke memory k, uint256 f, bool second)
        private
        pure
        returns (uint256 wi, int256 w, int256 a)
    {
        unchecked {
            wi = uint256(_ld(c.fpI, f));
            w = _ld(c.wax, wi);
            int256 wn = _wn(c, k, c.X0 + int256(wi % uint256(c.WW)), c.Y0 + int256(wi / uint256(c.WW)), second);
            a = _deposit(c, k, wi, f, w, wn);
        }
    }

    function _wn(Ctx memory c, Stroke memory k, int256 x, int256 y, bool second) private pure returns (int256) {
        unchecked {
            return (_nbr(c, k, x - 1, y, !second) + _nbr(c, k, x, y - 1, !second) + _nbr(c, k, x + 1, y, true)
                + _nbr(c, k, x, y + 1, true)) >> 2;
        }
    }

    function _pow06(uint256 t, int256 v) private pure returns (int256 r) {
        unchecked {
            int256 j = v >> 6;
            int256 f = v & 63;
            if (j >= 1024) return Q;
            if (j < 0) revert PencilError(1);
            int256 a = _p06(t, uint256(j));
            int256 b = j + 1 == 1024 ? Q : _p06(t, uint256(j) + 1);
            return (a * (64 - f) + b * f) >> 6;
        }
    }

    function _p06(uint256 t, uint256 j) private pure returns (int256 v) {
        assembly {
            v := shr(240, mload(add(t, shl(1, j))))
        }
    }

    /// How much a deposit lays down (Q16): reach into the tooth, then
    /// pressure, pen, wax and jitter.
    function _deposit(Ctx memory c, Stroke memory k, uint256 wi, uint256 f, int256 w, int256 wn)
        private
        pure
        returns (int256 a)
    {
        unchecked {
            int256 v = _ld(c.fpV, f);
            {
                int256 cc;
                {
                    int256 t = _ld(c.tooth, wi);
                    int256 h = t + PencilCore.fdiv((Q - t) * (w > wn ? w : wn) * 17, 20 * Q);
                    int256 reach = (_pow06(c.pow06, v < Q ? v : Q) * k.reach) >> 16;
                    cc = PencilCore.fdiv((h - Q + reach) * 12, 5) + DEP_C0;
                }
                if (cc <= 0) return 0;
                cc = cc >= Q ? Q : PencilCore.smooth16(cc);
                a = (cc * (DEP_V0 + ((DEP_V1 * v) >> 16))) >> 16;
            }
            a = (a * k.strength) >> 16;
            a = (a * (Q - w)) >> 16;
            a = (a * (Q - (w >> 1))) >> 16;
            // jitter: hash2(pixel index, stroke index) >>> 16
            uint256 i = uint256((c.Y0 + int256(wi / uint256(c.WW))) * c.W + c.X0 + int256(wi % uint256(c.WW)));
            a = (a * (JIT_0 + ((JIT_1 * int256(PencilCore.hash2(i, k.k) >> 16)) >> 16))) >> 16;
        }
    }

    // ---- end ---------------------------------------------------------------

    /// Composite the work window, soften it, and cut the tile out (top-down
    /// RGBA).
    function _finish(Ctx memory c, int256 ox, int256 oy, int256 tw, int256 th) private pure returns (bytes memory out) {
        unchecked {
            uint256 WW = uint256(c.WW);
            uint256 N = WW * uint256(c.WH);
            bytes memory img = new bytes(4 * N);
            if (!c.paper) {
                for (uint256 i; i < N; ++i) img[4 * i + 3] = 0xff;
            } else {
                for (uint256 i; i < N; ++i) {
                    int256 pl = (_ld(c.paperL, i) * (PL_TOOTH0 + ((PL_TOOTH1 * _ld(c.tooth, i)) >> 16))) >> 16;
                    _px(c, img, i, pl);
                }
                _scan(img, WW, uint256(c.WH));
            }
            out = new bytes(uint256(4 * tw * th));
            uint256 rowBytes = uint256(4 * tw);
            for (uint256 y; y < uint256(th); ++y) {
                uint256 src = ((uint256(oy) + y) * WW + uint256(ox)) * 4;
                uint256 dst = y * rowBytes;
                assembly {
                    let s := add(add(img, 0x20), src)
                    let d := add(add(out, 0x20), dst)
                    mcopy(d, s, rowBytes)
                }
            }
        }
    }

    function _px(Ctx memory c, bytes memory img, uint256 i, int256 pl) private pure {
        unchecked {
            uint256 d = 3 * i;
            uint256 e = c.exp2;
            uint256 l2s = c.l2s;
            int256 l0 = (((c.PL0 * pl) >> 16) * PencilCore.expNeg16(_ld(c.dens, d), e)) >> 16;
            int256 l1 = (((c.PL1 * pl) >> 16) * PencilCore.expNeg16(_ld(c.dens, d + 1), e)) >> 16;
            int256 l2 = (((c.PL2 * pl) >> 16) * PencilCore.expNeg16(_ld(c.dens, d + 2), e)) >> 16;
            assembly {
                // L2S[lin >= Q ? 4095 : (lin * 4095) >> 16], decoded from the
                // step thresholds of the table: the count of thresholds <= the
                // index
                function srgb(t, l) -> n {
                    let j := 4095
                    if slt(l, 65536) { j := sar(16, mul(l, 4095)) }
                    let hi := 255
                    for {} lt(n, hi) {} {
                        let m := shr(1, add(n, hi))
                        switch gt(shr(240, mload(add(t, shl(1, m)))), j)
                        case 1 { hi := m }
                        default { n := add(m, 1) }
                    }
                }
                let o := add(add(img, 0x20), shl(2, i))
                mstore8(o, srgb(l2s, l0))
                mstore8(add(o, 1), srgb(l2s, l1))
                mstore8(add(o, 2), srgb(l2s, l2))
                mstore8(add(o, 3), 0xff)
            }
        }
    }

    /// The optics of a flatbed scanner: [1 2 1] horizontally then
    /// vertically, rounded, with the edge pixels of the window kept.
    function _scan(bytes memory d, uint256 W, uint256 H) private pure {
        if (W < 3 || H < 3) return;
        bytes memory tmp = new bytes(d.length);
        assembly {
            let row := shl(2, W)
            let dp := add(d, 0x20)
            let tp := add(tmp, 0x20)
            for { let y := 0 } lt(y, H) { y := add(y, 1) } {
                for { let x := 1 } lt(add(x, 1), W) { x := add(x, 1) } {
                    let o := add(mul(y, row), shl(2, x))
                    for { let k := 0 } lt(k, 3) { k := add(k, 1) } {
                        let a := byte(0, mload(add(dp, sub(add(o, k), 4))))
                        let b := byte(0, mload(add(dp, add(o, k))))
                        let cc := byte(0, mload(add(dp, add(add(o, k), 4))))
                        mstore8(add(tp, add(o, k)), shr(2, add(add(add(a, shl(1, b)), cc), 2)))
                    }
                }
            }
            for { let y := 1 } lt(add(y, 1), H) { y := add(y, 1) } {
                for { let x := 1 } lt(add(x, 1), W) { x := add(x, 1) } {
                    let o := add(mul(y, row), shl(2, x))
                    for { let k := 0 } lt(k, 3) { k := add(k, 1) } {
                        let a := byte(0, mload(add(tp, sub(add(o, k), row))))
                        let b := byte(0, mload(add(tp, add(o, k))))
                        let cc := byte(0, mload(add(tp, add(add(o, k), row))))
                        mstore8(add(dp, add(o, k)), shr(2, add(add(add(a, shl(1, b)), cc), 2)))
                    }
                }
            }
        }
    }
}

src/raster/PencilTables.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

pragma solidity ^0.8.13;

/* =============================================================================
 *  PencilTables · the pinned tables of the pencil family
 * =============================================================================
 *
 * The rasterizer of render family 6 reads five integer tables. A generator
 * writes this file from the tables of the reference implementation. Do not
 * edit it by hand. Every entry is the integer of the reference, byte for
 * byte.
 *
 *     table  entries  width   contents
 *     -----  -------  ------  ----------------------------------------------
 *     EXP2   257      u16 BE  T[j] = round(65536 * 2^(-j/256)), j = 0..256,
 *                             stored as T[j] - 32768 (T[j] is in
 *                             [32768, 65536])
 *     S2L    256      u24 BE  sRGB u8 -> linear Q16
 *     L2S    255      u16 BE  linear (4096 steps) -> sRGB u8, as the step
 *                             thresholds of the table: entry v-1 is the
 *                             first index i with L2S[i] >= v, so L2S[i] is
 *                             the count of thresholds <= i (the table does
 *                             not decrease)
 *     POW06  1024     u16 BE  round(65536 * (j/1024)^0.6), j = 0..1023. The
 *                             readers hold j = 1024 (65536) as a constant.
 *     CDF    65       i32 BE  the equal-quantile knots of the tooth, Q16
 *
 * The readers (PencilCore, PencilRaster) copy a table into memory once per
 * render (one CODECOPY) and index it with MLOAD.
 */
library PencilTables {
    bytes internal constant EXP2 =
        hex"80007f4f7e9e7dee7d3e7c8f7be07b327a8479d67929787d77d17725767a75d07525747c73d3732a728171da7132708b"
        hex"6fe56f3f6e996df46d4f6cab6c076b646ac16a1e697c68db6839679966f8665865b9651a647b63dd634062a262056169"
        hex"60cd60315f965efb5e615dc75d2e5c945bfc5b635acc5a34599d5906587057da574556b0561b558754f3546053cd533a"
        hex"52a85216518550f450634fd34f434eb44e254d964d084c7a4bec4b5f4ad24a4649ba492e48a34818478d4703467a45f0"
        hex"456744df445643ce434742c0423941b2412c40a740213f9c3f183e933e0f3d8c3d093c863c033b813aff3a7e39fd397c"
        hex"38fc387c37fc377d36fe367f3601358335053488340b338e33123296321a319f312430a9302f2fb52f3b2ec22e492dd1"
        hex"2d582ce02c692bf12b7a2b042a8d2a1729a1292c28b7284227ce275926e6267225ff258c251924a7243523c3235222e1"
        hex"227022002190212020b020411fd21f641ef51e871e191dac1d3f1cd21c651bf91b8d1b221ab61a4b19e01976190c18a2"
        hex"183817cf176516fd1694162c15c4155c14f5148e142713c0135a12f4128e122911c4115f10fa109610320fce0f6b0f07"
        hex"0ea40e410ddf0d7d0d1b0cb90c580bf70b960b350ad50a750a1509b5095608f70898083a07db077d071f06c206650608"
        hex"05ab054e04f20496043a03df0383032802ce0273021901bf0165010b00b200590000";

    bytes internal constant S2L =
        hex"00000000001400002800003c00005000006300007700008b00009f0000b30000c70000db0000f1000108000120000139"
        hex"00015400016f00018c0001ab0001ca0001eb00020e00023200025700027d0002a50002ce0002f9000325000353000382"
        hex"0003b30003e500041800044d0004840004bc0004f600053200056f0005ad0005ed00062f0006730006b80006ff000747"
        hex"0007910007dd00082a00087a0008ca00091d0009720009c8000a20000a79000ad5000b32000b91000bf2000c55000cba"
        hex"000d20000d88000df2000e5e000ecc000f3c000fae00102100109700110e001188001203001280001300001381001404"
        hex"00148900151000159a0016250016b20017410017d30018660018fb001993001a2d001ac8001b66001c06001ca8001d4c"
        hex"001df2001e9a001f44001ff10020a00021510022040022b900237000242a0024e60025a40026640027260027eb0028b2"
        hex"00297b002a46002b14002be4002cb6002d8a002e61002f3a0030150030f30031d20032b5003399003480003569003655"
        hex"003743003833003925003a1a003b12003c0c003d08003e06003f0700400a00411000421800432300443000453f004651"
        hex"00476600487c004996004ab1004bd0004cf0004e14004f3900506200518c0052ba0053e900551c0056500057880058c2"
        hex"0059fe005b3d005c7f005dc3005f0900605300619f0062ed00643e0065920066e800684100699c006afb006c5b006dbf"
        hex"006f2500708d0071f90073670074d700764b0077c1007939007ab5007c33007db4007f370080bd0082460083d2008560"
        hex"0086f1008885008a1b008bb5008d51008eef0090910092350093dc0095860097330098e2009a94009c49009e01009fbc"
        hex"00a17900a33a00a4fd00a6c300a88b00aa5700ac2500adf600afcb00b1a200b37b00b55800b73800b91a00baff00bce8"
        hex"00bed300c0c100c2b200c4a600c69c00c89600ca9300cc9200ce9400d09a00d2a200d4ad00d6bc00d8cd00dae100dcf8"
        hex"00df1200e12f00e34f00e57200e79800e9c100ebed00ee1c00f04e00f28300f4bb00f6f600f93400fb7500fdb9010000";

    bytes internal constant L2S =
        hex"0001000200040005000600070009000a000b000c000e000f001000120013001500170018001a001c001e002000220025"
        hex"0027002a002c002f003100340037003a003d004000440047004a004e005200550059005d00610066006a006e00730077"
        hex"007c00810086008b00900095009a00a000a500ab00b100b700bd00c300c900cf00d600dc00e300ea00f100f800ff0106"
        hex"010e0115011d0125012c0134013d0145014d0156015e0167017001790182018b0195019e01a801b201bc01c601d001da"
        hex"01e501ef01fa02050210021b02260232023d024902550261026d027902850292029e02ab02b802c502d202e002ed02fb"
        hex"030903160325033303410350035e036d037c038b039a03aa03b903c903d903e903f904090419042a043b044c045d046e"
        hex"047f049104a204b404c604d804eb04fd0510052205350548055c056f0582059605aa05be05d205e605fb061006240639"
        hex"064f06640679068f06a506bb06d106e706fe0714072b0742075907700788079f07b707cf07e7080008180831084a0862"
        hex"087c089508ae08c808e208fc09160930094b09660981099c09b709d209ee0a0a0a250a420a5e0a7a0a970ab40ad10aee"
        hex"0b0b0b290b460b640b820ba10bbf0bde0bfc0c1b0c3a0c5a0c790c990cb90cd90cf90d1a0d3a0d5b0d7c0d9d0dbe0de0"
        hex"0e020e240e460e680e8a0ead0ed00ef30f160f390f5d0f810fa50fc90fed";

    bytes internal constant POW06 =
        hex"00000400061007bc09310a820bb80cdb0dee0ef30fed10dd11c412a4137d144f151d15e516a81768182318db198f1a3f"
        hex"1aed1b981c401ce61d891e2a1ec91f6520002099212f21c5225822ea237a24082496252125ac263526bd274327c9284d"
        hex"28d0295229d32a532ad22b502bcd2c4a2cc52d3f2db92e312ea92f202f96300c308130f5316831db324d32be332f339f"
        hex"340e347d34eb355835c53632369e3709377437de384738b13919398139e93a503ab73b1d3b833be83c4d3cb23d163d79"
        hex"3ddd3e3f3ea23f043f653fc64027408840e8414741a74206426442c34320437e43db4438449544f1454d45a84604465f"
        hex"46b94714476e47c84821487a48d3492c498449dc4a344a8c4ae34b3a4b914be74c3d4c934ce94d3f4d944de94e3e4e92"
        hex"4ee64f3a4f8e4fe25035508850db512e518051d35225527752c8531a536b53bc540d545d54ad54fe554e559d55ed563c"
        hex"568c56db572a577857c75815586358b158ff594c599a59e75a345a815ace5b1a5b675bb35bff5c4b5c975ce25d2e5d79"
        hex"5dc45e0f5e5a5ea45eef5f395f835fcd6017606160aa60f4613d618661cf6218626162a962f2633a638263ca6412645a"
        hex"64a264e96530657865bf6606664d669366da6720676767ad67f36839687f68c5690a6950699569da6a1f6a646aa96aee"
        hex"6b336b776bbc6c006c446c886ccc6d106d546d986ddb6e1f6e626ea56ee86f2b6f6e6fb16ff47036707970bb70fd7140"
        hex"718271c472067247728972cb730c734e738f73d074117452749374d475157555759675d676177657769776d777177757"
        hex"779777d778167856789678d579147953799379d27a117a4f7a8e7acd7b0c7b4a7b897bc77c057c437c827cc07cfe7d3b"
        hex"7d797db77df57e327e707ead7eea7f287f657fa27fdf801c8059809680d2810f814c818881c58201823d827a82b682f2"
        hex"832e836a83a683e1841d8459849484d0850b8547858285bd85f88633866e86a986e4871f875a879587cf880a8844887f"
        hex"88b988f3892e896889a289dc8a168a508a8a8ac48afd8b378b718baa8be48c1d8c568c908cc98d028d3b8d748dad8de6"
        hex"8e1f8e588e918ec98f028f3b8f738fac8fe4901c9055908d90c590fd9135916d91a591dd9215924d928492bc92f4932b"
        hex"9363939a93d294099440947894af94e6951d9554958b95c295f996309666969d96d4970a9741977797ae97e4981b9851"
        hex"988798bd98f4992a9960999699cc9a029a379a6d9aa39ad99b0e9b449b7a9baf9be59c1a9c4f9c859cba9cef9d249d5a"
        hex"9d8f9dc49df99e2e9e639e979ecc9f019f369f6a9f9f9fd4a008a03da071a0a6a0daa10ea143a177a1aba1dfa213a247"
        hex"a27ba2afa2e3a317a34ba37fa3b3a3e6a41aa44ea481a4b5a4e8a51ca54fa582a5b6a5e9a61ca650a683a6b6a6e9a71c"
        hex"a74fa782a7b5a7e8a81ba84da880a8b3a8e6a918a94ba97da9b0a9e2aa15aa47aa7aaaacaadeab11ab43ab75aba7abd9"
        hex"ac0bac3dac6faca1acd3ad05ad37ad69ad9badccadfeae30ae61ae93aec4aef6af27af59af8aafbcafedb01eb04fb081"
        hex"b0b2b0e3b114b145b176b1a7b1d8b209b23ab26bb29cb2cdb2fdb32eb35fb38fb3c0b3f1b421b452b482b4b3b4e3b513"
        hex"b544b574b5a4b5d5b605b635b665b695b6c5b6f5b725b755b785b7b5b7e5b815b845b875b8a5b8d4b904b934b963b993"
        hex"b9c2b9f2ba21ba51ba80bab0badfbb0fbb3ebb6dbb9cbbccbbfbbc2abc59bc88bcb7bce6bd15bd44bd73bda2bdd1be00"
        hex"be2fbe5ebe8cbebbbeeabf18bf47bf76bfa4bfd3c001c030c05ec08dc0bbc0eac118c146c175c1a3c1d1c1ffc22ec25c"
        hex"c28ac2b8c2e6c314c342c370c39ec3ccc3fac428c456c483c4b1c4dfc50dc53ac568c596c5c3c5f1c61ec64cc679c6a7"
        hex"c6d4c702c72fc75dc78ac7b7c7e5c812c83fc86cc89ac8c7c8f4c921c94ec97bc9a8c9d5ca02ca2fca5cca89cab6cae3"
        hex"cb0fcb3ccb69cb96cbc3cbefcc1ccc49cc75cca2ccceccfbcd27cd54cd80cdadcdd9ce06ce32ce5ece8bceb7cee3cf0f"
        hex"cf3ccf68cf94cfc0cfecd018d045d071d09dd0c9d0f5d121d14cd178d1a4d1d0d1fcd228d254d27fd2abd2d7d302d32e"
        hex"d35ad385d3b1d3ddd408d434d45fd48bd4b6d4e2d50dd538d564d58fd5bad5e6d611d63cd667d693d6bed6e9d714d73f"
        hex"d76ad795d7c0d7ebd816d841d86cd897d8c2d8edd918d943d96ed999d9c3d9eeda19da44da6eda99dac4daeedb19db43"
        hex"db6edb99dbc3dbeedc18dc42dc6ddc97dcc2dcecdd16dd41dd6bdd95ddc0ddeade14de3ede69de93debddee7df11df3b"
        hex"df65df8fdfb9dfe3e00de037e061e08be0b5e0dfe109e133e15ce186e1b0e1dae203e22de257e280e2aae2d4e2fde327"
        hex"e351e37ae3a4e3cde3f7e420e44ae473e49ce4c6e4efe519e542e56be595e5bee5e7e610e63ae663e68ce6b5e6dee707"
        hex"e731e75ae783e7ace7d5e7fee827e850e879e8a2e8cbe8f3e91ce945e96ee997e9c0e9e9ea11ea3aea63ea8beab4eadd"
        hex"eb06eb2eeb57eb7feba8ebd1ebf9ec22ec4aec73ec9becc4ececed14ed3ded65ed8eedb6eddeee07ee2fee57ee7feea8"
        hex"eed0eef8ef20ef49ef71ef99efc1efe9f011f039f061f089f0b1f0d9f101f129f151f179f1a1f1c9f1f1f219f241f268"
        hex"f290f2b8f2e0f308f32ff357f37ff3a6f3cef3f6f41df445f46df494f4bcf4e3f50bf533f55af582f5a9f5d0f5f8f61f"
        hex"f647f66ef696f6bdf6e4f70cf733f75af781f7a9f7d0f7f7f81ef846f86df894f8bbf8e2f909f930f958f97ff9a6f9cd"
        hex"f9f4fa1bfa42fa69fa90fab7fadefb05fb2bfb52fb79fba0fbc7fbeefc14fc3bfc62fc89fcb0fcd6fcfdfd24fd4afd71"
        hex"fd98fdbefde5fe0cfe32fe59fe7ffea6feccfef3ff19ff40ff66ff8dffb3ffda";

    bytes internal constant CDF =
        hex"ffffab720000005c00000b7e000012d20000187600001d2400002130000024ca0000280d00002b1000002ddd0000307f"
        hex"000032fb0000355a0000379d000039c900003be500003dec00003fe6000041d4000043b60000458e0000475c00004923"
        hex"00004ae300004c9e00004e5400005005000051b30000535d00005506000056ae00005854000059fa00005ba100005d48"
        hex"00005ef00000609a00006248000063fa000065af000067690000692900006af000006cc000006e980000707b00007269"
        hex"000074650000766f0000788d00007abf00007d0900007f6f000081f7000084a70000878900008aa600008e14000091e9"
        hex"0000965100009b980000a25c0000ac7b00011148";
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/PencilRenderer.sol": {
      "PencilRaster": "0xd2e66fdc4efde8384293f222b1be39a30704967e"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "kohi-fixmath/=lib/kohi-fixmath/",
    "lib/kohi-noise-lgpl/:kohi-fixmath/=lib/kohi-fixmath/",
    "lib/kohi-noise-lgpl/:kohi-fixmath/=lib/kohi-fixmath/",
    "kohi-noise-lgpl/=lib/kohi-noise-lgpl/",
    "kohi/=lib/kohi/",
    "test/=lib/kohi-noise-lgpl/test/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.