• Трехмерный движок внутри запроса SQL

    • Tutorial
    Несколько лет назад на форуме SQL.ru решили провести сравнение реализаций трассировщиков лучей на разных языках программирования. К сожалению, моя заявка не может участвовать т.к. она не выводит надпись «PIXAR», поэтому публикую ее здесь.

    Для чистоты эксперимента я использовал SQLite без расширений. Оказалось, что там нет даже функции SQRT.

    WITH RECURSIVE numbers AS (SELECT 0 AS n UNION ALL SELECT n+1 FROM numbers WHERE n<89),
    pixels AS (SELECT rows.n as row, cols.n as col FROM numbers as rows CROSS JOIN
    numbers as cols WHERE rows.n > 4 AND rows.n < 38 AND cols.n > 9 AND cols.n < 89),
    rawRays AS (SELECT row, col, -0.9049 + col * 0.0065 + row * 0.0057 as x,
    -0.1487 + row * -0.0171 as y, 0.6713 + col * 0.0045 + row * -0.0081 as z FROM pixels),
    norms AS (SELECT row, col, x, y, z, (1 + x * x + y * y + z * z) / 2 as n FROM rawRays),
    rays AS (SELECT row, col, x / n AS x, y / n AS y, z / n AS z FROM norms),
    iters AS (SELECT row, col, 0 as it, 0 as v FROM rays UNION ALL
    SELECT rays.row, rays.col, it + 1 AS it, v + MAX(ABS(0.7+v*x) - 0.3,
    ABS(0.7+v*y) - 0.3, ABS(-1.1+v*z) - 0.3, -((0.7+v*x) * (0.7+v*x) +
    (0.7+v*y) * (0.7+v*y) + (-1.1+v*z) * (-1.1+v*z)) * 1.78 + 0.28) AS v
    FROM iters JOIN rays ON rays.row = iters.row AND rays.col = iters.col WHERE it < 15),
    lastIters AS (SELECT it0.row, it0.col, it0.v AS v0, it1.v AS v1, it2.v AS v2
    FROM iters as it0 JOIN iters AS it1 ON it0.col = it1.col AND it0.row = it1.row
    JOIN iters AS it2 ON it0.col = it2.col AND it0.row = it2.row
    WHERE it0.it = 15 AND it1.it = 14 AND it2.it = 13),
    res AS (SELECT col, (v0 - v1) / (v1 - v2) as v FROM lastIters)
    SELECT group_concat(
    substr('$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,"^. ',
    round(1 + max(0, min(66, v * 67))), 1) || CASE WHEN col=88 THEN X'0A' ELSE '' END, '')
    FROM res;
    



    Здесь можно покрутить кубик

    Под катом построчный разбор запроса. Как обычно, достаточно знания основ SQL и школьной математики.
    Читать дальше →