gpt4 book ai didi

Python 光线追踪

转载 作者:太空狗 更新时间:2023-10-30 00:52:09 26 4
gpt4 key购买 nike

我正在使用纯 Python 构建一个简单的 Python 光线追踪器(只是为了它),但我遇到了障碍。

目前我的场景设置是这样的:

  1. 相机位于 0, -10, 0,指向 y 轴。
  2. 半径为 1 的球体位于 0, 0, 0
  3. 成像平面物体与相机的距离为 1,宽度和高度为 0.5

我正在通过成像平面以均匀随机分布的方式发射光子,如果光子恰好与物体相交,我会在图像 Canvas 上绘制一个红点,对应于图像平面上光线穿过的点.

我的相交代码(我只有球体):

def intersection(self, ray):
cp = self.pos - ray.origin
v = cp.dot(ray.direction)
discriminant = self.radius**2 - cp.dot(cp) + v * v

if discriminant < 0:
return False
else:
return ray.position(v - sqrt(discriminant)) # Position of ray at time t

还有我的渲染代码(它渲染一定数量的光子,而不是逐个像素):

def bake(self, rays):
self.image = Image.new('RGB', [int(self.camera.focalplane.width * 800), int(self.camera.focalplane.height * 800)])
canvas = ImageDraw.Draw(self.image)

for i in xrange(rays):
x = random.uniform(-camera.focalplane.width / 2.0, camera.focalplane.width / 2.0)
z = random.uniform(-camera.focalplane.height / 2.0, camera.focalplane.height / 2.0)

ray = Ray(camera.pos, Vector(x, 1, z))

for name in scene.objects.keys():
result = scene.objects[name].intersection(ray)

if result:
n = Vector(0, 1, 0)
d = ((ray.origin - Point(self.camera.pos.x, self.camera.pos.y + self.camera.focalplane.offset, self.camera.pos.z)).dot(n)) / (ray.direction.dot(n))
pos = ray.position(d)

x = pos.x
y = pos.y

canvas.point([int(self.camera.focalplane.width * 800) * (self.camera.focalplane.width / 2 + x) / self.camera.focalplane.width,
int(self.camera.focalplane.height * 800) * (self.camera.focalplane.height / 2 + z) / self.camera.focalplane.height],
fill = 128)

它应该可以正常工作,但是当我渲染测试图像时,我没有得到任何看起来像球体轮廓的东西:

enter image description here

我期待这样的事情:

enter image description here

有人知道为什么我的代码不能正常运行吗?我调整和重写这一部分已经太久了......

最佳答案

您要对射线的方向矢量进行归一化吗?

关于Python 光线追踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5408669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com