Last active
October 11, 2019 15:10
-
-
Save ajbeach2/2dbc34ca0f7964928d8389952fe3909f to your computer and use it in GitHub Desktop.
ray_trace_postgres.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- ported to postgres from https://observablehq.com/@pallada-92/sql-3d-engine | |
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 > 2 AND rows.n < 40 AND cols.n > -1 AND cols.n < 89 | |
), rawRays AS ( | |
SELECT | |
row, col, | |
-0.9105 + col * 0.0065 + row * 0.0057 as x, | |
-0.1315 + row * -0.0171 as y, | |
0.6794 + col * 0.0045 + row * -0.0081 as z | |
FROM pixels | |
), normsSq AS ( | |
SELECT row, col, x, y, z, x * x + y * y + z * z AS n2 FROM rawRays | |
), norms AS ( | |
SELECT row, col, x, y, z, (1 + n2) / 2.0 as n FROM normsSq | |
), 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.0 as v FROM rays | |
UNION ALL | |
SELECT rays.row, rays.col, it + 1 AS it, | |
v + GREATEST(ABS(0.75+v*x) - 0.3, ABS(0.75+v*y) - 0.3, ABS(-1.06+v*z) - 0.3, -(0.28 + ((0.75+v*x) * (0.75+v*x) + (0.75+v*y) * (0.75+v*y) + (-1.06+v*z) * (-1.06+v*z)) / 0.28) / 2.0 + 0.42) 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.row = it1.row AND it0.col = it1.col | |
JOIN iters AS it2 ON it0.row = it2.row AND it0.col = it2.col | |
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 string_agg( | |
substring('$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,"^. '::text, CAST (round(1 + GREATEST(0, LEAST(66, v * 67))) AS INTEGER), 1) | |
|| CASE WHEN col = 88 THEN X'0A' ELSE '' END | |
, '') | |
FROM res; |
Author
ajbeach2
commented
Oct 10, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment