summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRosyid Haryadi <rosyid_haryadi@protonmail.com>2025-03-01 12:20:33 +0700
committerRosyid Haryadi <rosyid_haryadi@protonmail.com>2025-03-01 12:20:33 +0700
commit60e688d89e822f74058e726f67f6ac804f9e2ca8 (patch)
tree2af36cf9514de269f2ba21bd29ea40f6a0124fa2
parentfea1e609e6003f68a351438ebd9d00e109e930cc (diff)
upd simple shader
-rw-r--r--src/renderer.rs21
1 files changed, 17 insertions, 4 deletions
diff --git a/src/renderer.rs b/src/renderer.rs
index 3f94437..d27edb4 100644
--- a/src/renderer.rs
+++ b/src/renderer.rs
@@ -2,8 +2,17 @@ use crate::calculus::calculus::{Point3, Ray, Vec3};
use crate::global::{Color, DisplayBuffer, Pixel, CAMERA_CENTER, FOCAL_LENGTH, IMG_HEIGHT, IMG_WIDTH, VIEWPORT_HEIGHT, VIEWPORT_WIDTH};
fn ray_color(ray: &Ray) -> Color {
- if hit_sphere(&Point3 {x: 0f32, y: 0f32, z: -1f32}, 0.5, ray) {
- return Color {r: 1f32, g: 0f32, b: 0f32}
+ let t = hit_sphere(&Point3 {x: 0.0, y: 0.0, z: -1.0}, 0.5, ray);
+ if t > 0.0 {
+ let normal = ray
+ .at(t)
+ .sub(&Vec3 {x: 0.0, y: 0.0, z: -1.0})
+ .unit();
+ return Color::new(
+ normal.x + 1.0,
+ normal.y + 1.0,
+ normal.z + 1.0,
+ ).mul_scalar(0.5);
}
let unit_direction = ray.direction.unit();
let a = 0.5 * (unit_direction.y + 1.0);
@@ -12,13 +21,17 @@ fn ray_color(ray: &Ray) -> Color {
color1.add(&color2)
}
-fn hit_sphere(center: &Point3, radius: f32, ray: &Ray) -> bool {
+fn hit_sphere(center: &Point3, radius: f32, ray: &Ray) -> f32 {
let oc = center.sub(&ray.origin);
let a = ray.direction.dot_prod(&ray.direction);
let b = -2.0 * ray.direction.dot_prod(&oc);
let c = oc.dot_prod(&oc) - radius * radius;
let discriminant = b * b - 4.0 * a * c;
- discriminant >= 0.0
+ if discriminant < 0.0 {
+ -1.0
+ } else {
+ (-b - discriminant.sqrt()) / (2.0 * a)
+ }
}
pub fn render(display_buffer: &mut DisplayBuffer) {