Skip to content

Commit

Permalink
add Texture, TextureMaterial classes
Browse files Browse the repository at this point in the history
  • Loading branch information
via8 committed Feb 2, 2021
1 parent abf01e2 commit 3914d81
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
21 changes: 21 additions & 0 deletions pyrt/material/texture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""
Texture
"""
from PIL import Image
from numpy import asarray
from ..math import Vec3


class Texture:

"""Texture Class"""

def __init__(self, path: str):
image = Image.open(path)
self._pixels = asarray(image.getdata())
self._w, self._h = image.size

def color(self, u: float, v: float):
rgb = self._pixels[int(v * self._h)][int(u * self._w)]
return Vec3(rgb[0], rgb[1], rgb[2])
50 changes: 50 additions & 0 deletions pyrt/material/texturematerial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""
Texture Material
For texture shading
"""
from .texture import Texture
from .material import Material
from ..math import Vec3, Ray, HitRecord, dot3, reflect3, normalize3, clamp3
from ..camera import Camera


class TextureMaterial(Material):

"""Texture Material Class"""

def __init__(self, color: Vec3 = Vec3(1.,1.,1.), shininess: float = 10.0, reflectivity: float = 0.0, refraction: float = 1.0):
Material.__init__(self, color, shininess, reflectivity, refraction)
self.texture = None

def setTexture(self, texture: Texture):
self.texture = texture

def shade(self, camera: Camera, ray: Ray, hitrecord: HitRecord, lights: list) -> Vec3:
"""
Shade method: Texture
texture shader
"""
colorsum = Vec3(0.,0.,0.)

if len(lights)>0:
for light in lights:
N = hitrecord.normal_g
L = normalize3(hitrecord.point - light.position)
E = normalize3(camera.position - hitrecord.point)
R = normalize3(-reflect3(L, N))
diffuse = max(1. - dot3(N, L), 0.0)
specular = pow(max(dot3(R, E), 0.0), 0.3 * self.shininess)

# TODO: just take color from self.texture.color(hitrecord.texcoord.x, hitrecord.texcoord.y)?
color = self.color * 0.5 * (diffuse + specular) * hitrecord.color
colorsum += color
colorsum /= len(lights)
colorsum = clamp3(colorsum, Vec3(0.,0.,0.), Vec3(1.,1.,1.))
else:
# no light in scene, use material color
colorsum = self.color * hitrecord.color

return colorsum

0 comments on commit 3914d81

Please sign in to comment.