光线追踪加速

光线追踪加速_第1张图片
光线追踪加速_第2张图片
光线追踪加速_第3张图片
光线追踪加速_第4张图片
光线追踪加速_第5张图片

(1) void Renderer::Render(const Scene& scene) { std::vector framebuffer(scene.width * scene.height);
 float scale = tan(deg2rad(scene.fov * 0.5)); 
 float imageAspectRatio = scene.width / (float)scene.height; Vector3f eye_pos(-1, 5, 10); int m = 0; for (uint32_t j = 0; j < scene.height; ++j) { for (uint32_t i = 0; i < scene.width; ++i) { float x; float y; float nx = (i + 0.5f) * 2 / scene.width - 1.0f; float ny = (j + 0.5f) * 2 / scene.height - 1.0f; x = nx * scale * imageAspectRatio; y = -ny * scale; Vector3f dir = Vector3f(x, y, -1); dir = normalize(dir); framebuffer[m++] = scene.castRay(Ray(eye_pos, dir), 0.0f); }UpdateProgress(j / (float)scene.height); }UpdateProgress(1.f);
// save framebuffer to file FILE* fp = fopen("binary.ppm", "wb"); (void)fprintf(fp, "P6\n%d %d\n255\n", scene.width, scene.height); for (auto i = 0; i < scene.height * scene.width; ++i) { static unsigned char color[3]; color[0] = (unsigned char)(255 * clamp(0, 1, framebuffer[i].x)); color[1] = (unsigned char)(255 * clamp(0, 1, framebuffer[i].y)); color[2] = (unsigned char)(255 * clamp(0, 1, framebuffer[i].z)); fwrite(color, 1, 3, fp); }fclose(fp); }(2) inline bool Bounds3::IntersectP(const Ray& ray, const Vector3f& invDir, const std::array& dirIsNeg) const { // invDir: ray direction(x,y,z), invDir=(1.0/x,1.0/y,1.0/z), use this because Multiply is faster that D ivision // dirIsNeg: ray direction(x,y,z), dirIsNeg=[int(x>0),int(y>0),int(z>0)], use this to simplify your log ic // TODO test if ray bound intersects const auto& origin = ray.origin; float tEnter = -std::numeric_limits::infinity(); float tExit = std::numeric_limits::infinity(); for (int i = 0; i < 3; i++) { float min = (pMin[i] - origin[i]) * invDir[i]; float max = (pMax[i] - origin[i]) * invDir[i]; if (!dirIsNeg[i]) { std::swap(min, max); }tEnter = std::max(min, tEnter); tExit = std::min(max, tExit); }return tEnter < tExit && tExit >= 0; }(3) Intersection BVHAccel::getIntersection(BVHBuildNode* node, const Ray& ray) const { // TODO Traverse the BVH to find intersection
Intersection isect; std::array dirIsNeg; dirIsNeg[0] = int(ray.direction.x >= 0); dirIsNeg[1] = int(ray.direction.y >= 0); dirIsNeg[2] = int(ray.direction.z >= 0); // 不相交 if (!node->bounds.IntersectP(ray, ray.direction_inv, dirIsNeg)) return isect; // 叶子节点 if (node->left == nullptr && node->right == nullptr) { isect = node->object->getIntersection(ray); return isect; }auto hit1 = getIntersection(node->left, ray); auto hit2 = getIntersection(node->right, ray); //返回小的 return hit1.distance < hit2.distance ? hit1 : hit2; }

你可能感兴趣的:(课程学习,图形学,人工智能,计算机视觉)