TableTower/tools/theme_art/scene_floor.py

66 lines
3.1 KiB
Python
Raw Permalink Normal View History

"""A CSS-style perspective grid floor (a plane tilted back by rotateX), drawn as flat SVG polygons.
All numbers are in the mockup's 960 x 450 spread space; the caller scales the result.
"""
import math
from svg_common import num
class PerspectiveFloor:
"""Projects points of a flat grid that is tilted back around its bottom edge."""
def __init__(self, left, right, height, perspective, tilt_degrees, spread_height=450):
self.left, self.right, self.height = left, right, height
self.perspective = perspective
self.tilt = math.radians(tilt_degrees)
self.top = spread_height - height
self.centre_x = (left + right) / 2
def project(self, x, y):
"""Map a point on the flat grid (y = 0 at its far edge) to the screen."""
distance_from_bottom = self.height - y
rotated_y = self.height - distance_from_bottom * math.cos(self.tilt)
depth = distance_from_bottom * math.sin(self.tilt)
shrink = self.perspective / (self.perspective + depth)
screen_x = self.centre_x + (x - self.centre_x) * shrink
screen_y = self.top + self.height / 2 + (rotated_y - self.height / 2) * shrink
return screen_x, screen_y
def quad(self, x0, y0, x1, y1):
"""SVG points text for a grid rectangle after projection."""
corners = [self.project(x0, y0), self.project(x1, y0), self.project(x1, y1), self.project(x0, y1)]
return " ".join(f"{num(x)},{num(y)}" for x, y in corners)
def outline(self):
return self.quad(self.left, 0, self.right, self.height)
def grid_lines(self, row_spacing, row_line, column_spacing, column_line):
"""Polygons for the grid: a line at the end of each row period, and at the start of each column period."""
shapes = []
row_start = row_spacing - row_line
while row_start < self.height:
shapes.append(self.quad(self.left, row_start, self.right, min(row_start + row_line, self.height)))
row_start += row_spacing
column_start = self.left
while column_start < self.right:
shapes.append(self.quad(column_start, 0, column_start + column_line, self.height))
column_start += column_spacing
return shapes
def floor_svg(floor, colour, row_spacing, row_line, column_spacing, column_line,
opacity=1.0, glow_width=0.0, ground_colour=None):
"""SVG text for a projected grid, with an optional ground fill and a faked glow (wide faint outline)."""
shapes = floor.grid_lines(row_spacing, row_line, column_spacing, column_line)
text = f'<g opacity="{num(opacity)}">'
if ground_colour:
text += f'<polygon points="{floor.outline()}" fill="{ground_colour}"/>'
if glow_width:
glow = "".join(f'<polygon points="{points}"/>' for points in shapes)
text += (f'<g fill="{colour}" stroke="{colour}" stroke-width="{num(glow_width)}" '
f'stroke-linejoin="round" opacity=".28">{glow}</g>')
text += f'<g fill="{colour}">' + "".join(f'<polygon points="{points}"/>' for points in shapes) + "</g>"
return text + "</g>"