rk_island/game/math.py

76 lines
2.3 KiB
Python

# Copyright (C) 2022 RozK
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from math import hypot
vec3_right = (1.0, 0.0, 0.0)
vec3_forward = (0.0, 1.0, 0.0)
vec3_up = (0.0, 0.0, 1.0)
def vec3_add(a, b):
return (a[0] + b[0], a[1] + b[1], a[2] + b[2])
def vec3_sub(a, b):
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def vec3_normalize(v):
l = hypot(*v)
return (v[0] / l, v[1] / l, v[2] / l)
def vec3_direction(a, b):
v = (b[0] - a[0], b[1] - a[1], b[2] - a[2])
l = hypot(*v)
return (v[0] / l, v[1] / l, v[2] / l)
def vec3_scale(v, s):
return (v[0] * s, v[1] * s, v[2] * s)
def vec3_mul(a, b):
return (a[0] * b[0], a[1] * b[1], a[2] * b[2])
def vec3_dot(a, b):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def vec3_cross(a, b):
return (a[1] * b[2] - a[2] * b[1], -(a[0] * b[2] - a[2] * b[0]), a[0] * b[1] - a[1] * b[0])
# Texture formats
def float_s8(f):
return round((f ** (1.0 / 2.2)) * 255.0) #TODO: more accurate
def vec3_srgb8a8(v):
p = 1.0 / 2.2 #TODO: more accurate
return (round((v[0] ** p) * 255.0), round((v[1] ** p) * 255.0), round((v[2] ** p) * 255.0), 255)
def vec3_rgba8(v):
return (round(v[0] * 255.0), round(v[1] * 255.0), round(v[2] * 255.0), 255)
def vec3_normal_rgba8(n):
l = max(abs(n[0]), abs(n[1]), abs(n[2]))
return (
round((0.5 + (n[0] / l) * 0.5) * 255.0),
round((0.5 + (n[1] / l) * 0.5) * 255.0),
round((n[2] / l) * 255.0), 0)
def vec3_normal_rgb10a2(n):
l = max(abs(n[0]), abs(n[1]), abs(n[2]))
return \
round((0.5 + (n[0] / l) * 0.5) * 1023.0) | \
round((0.5 + (n[1] / l) * 0.5) * 1023.0) << 10 | \
round((n[2] / l) * 1023.0) << 20
# Vertex formats