Ray Tracing in One Weekend Part3

完成到第七章抗锯齿的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include<fstream>
#include<string>
#include "v3d.h"
#include "ray.h"
#include "color.h"
#include "rtweekend.h"
#include "hittable_list.h"
#include "sphere.h"
#include"camera.h"
using namespace std;
// Type aliases for vec3
using point3 = vec3;   // 3D point
using color = vec3;    // RGB color
 
 
double hit_sphere(const point3& center, double radius, const ray& r) {
    vec3 oc = r.origin() - center;
    auto a = r.direction().length_squared();//t2b⋅b+2tb⋅(A−C)+(A−C)⋅(A−C)−r2=0 函数关于t, P(t)=A+tb
    auto half_b = dot(oc, r.direction());
    auto c = oc.length_squared() - radius * radius;
    auto discriminant = half_b * half_b - a * c;
    if (discriminant < 0) {
        return -1.0;
    }
    else {
        return (-half_b - sqrt(discriminant)) / a;
    }
}
 
 
 
color ray_color(const ray& r ,const hittable& world) {
    hit_record rec;
    if (world.hit(r, 0, infinity, rec)){//如果打中了球,在球的范围内,就变成彩色
        return 0.5 * (rec.normal + color(1, 1, 1));
    }
    vec3 unit_direction = unit_vector(r.direction());
    //显示蓝色背景
    auto back = 0.5 * (unit_direction.y() + 1.0);
    return (1.0 - back) * color(1.0, 1.0, 1.0) + back * color(0.5, 0.7, 1.0);
}
 
int main()
{
    // Image
    const auto aspect_ratio = 16.0 / 9.0;
    const int image_width = 400;
    const int image_height = static_cast<int>(image_width / aspect_ratio);
    const int sample_per_pixel = 100;//采样次数
 
    // World
    hittable_list world;
    world.add(make_shared<sphere>(point3(0, 0, -1), 0.5));
    world.add(make_shared<sphere>(point3(0, -100.5, -1), 100));
 
    // Camera
    camera cam;//定义函数放到头文件里面了
 
    // Render
    ofstream file("graph1-2.ppm");
    file << "P3\n" << image_width << ' ' << image_height << "\n255\n";
 
    for (int j = image_height - 1; j >= 0; --j) {
        std::cerr << "\rScanlines remaining: " << j << ' ' << std::flush;
        for (int i = 0; i < image_width; ++i) {
            color pix_color(0, 0, 0);
            for (int s = 0; s < sample_per_pixel; s++) {//采样100次,即图片的每个点位都发出的光通过random随机不同方向,取样100次求平均值
                auto u = (i + random_double()) / (image_width - 1);
                auto v = (j + random_double()) / (image_height - 1);
                ray r = cam.get_ray(u, v);
                pix_color += ray_color(r, world);
            }
            write_color(file, pix_color,sample_per_pixel);
        }
    }
 
    std::cerr << "\nDone.\n";
}

  

 

 

 

posted @   LOFU  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示