
Shadoka
The Ray Tracer Challenge: Gradient pattern is not a gradient
Hello @jamis and everyone,
I’ve implemented the gradient pattern as described in the book and it gives me this output:
The code for pattern_at (I’ve renamed it to ColorAt) is the following:
func (gp *GradientPattern) ColorAt(point math.Point) math.Color {
distance := gp.ColorB.Subtract(gp.ColorA)
fraction := point.X - gomath.Floor(point.X)
return gp.ColorA.Add(distance.Mul(fraction))
}
As you can see it is not exactly a gradient, but the output makes sense to me.
Our spheres are centered at 0, 0, 0 in object space and at x = 0 the fraction evaluates to 0, which in turn means that we just return colorA.
But I highly suspect that this function is supposed to return an image of a smooth gradient from A to B.
I’m going mildly insane about this issue and if anyone got any advice I would greatly appreciate that.
Thanks!
Marked As Solved

jamis
The issue here is that your pattern space needs to be translated and scaled so that the [0,1] range fits the object you’re applying it to. If your sphere has radius 1, and is centered at (0,0), then the pattern (by default) will be covering [-1, 1] (from -x to +x), which means the gradient will be doubled (running once from [-1,0] and again from [0,1]). If you scale the pattern space by 2 (so the gradient runs from [0,2]) and then translate it by -x (so it runs from [-1,1]), it should look more like what you’re expecting.
Hopefully that helps! If you’d like me to restate/clarify anything, let me know.
Also Liked

Shadoka
Thank you so much, that indeed fixes it!
I am facepalming really hard right now, because I already tried scaling by 2 and translating by -1, but I never thought of having to combine those two…
Thanks again for your help and for writing that book, having a blast with it!
Popular Prag Prog topics







Modern Front-End Development for Rails - application does not start after run bin/setup (page xviii)


Modern front-end development for Rails, second edition - Struggling to get the first chapter to work

Other popular topics










Latest in PragProg
Latest (all)
Categories:
Popular Portals
- /elixir
- /rust
- /wasm
- /ruby
- /erlang
- /phoenix
- /keyboards
- /js
- /rails
- /python
- /security
- /go
- /swift
- /vim
- /clojure
- /haskell
- /java
- /emacs
- /svelte
- /onivim
- /typescript
- /crystal
- /c-plus-plus
- /tailwind
- /kotlin
- /gleam
- /react
- /flutter
- /elm
- /ocaml
- /vscode
- /opensuse
- /ash
- /centos
- /php
- /deepseek
- /scala
- /zig
- /html
- /debian
- /nixos
- /lisp
- /agda
- /textmate
- /sublime-text
- /react-native
- /arch-linux
- /ubuntu
- /revery
- /manjaro
- /spring
- /django
- /diversity
- /nodejs
- /lua
- /slackware
- /c
- /julia
- /neovim
- /markdown