Draw Lines Over a Circle - math

There's a line A-B and C at the center between A and B. It forms a circle as in the figure. If we assume A-B line as a diameter of the circle and then C is it's center. My problem is I have no idea how to draw another three lines (in blue) each 45 degree away from AC or AB. No, this is not a homework, it's part of my complex geometry in a rendering.
alt text http://www.freeimagehosting.net/uploads/befcd84d8c.png

There are a few ways to solve this problem, one of which is to find the angle of the line and then add 45 degrees to this a few times. Here's an example, it's in Python, but translating the math should be easy (and I've tried to write the Python in a simplistic way).
Here's the output for a few lines:
The main function is calc_points, the rest is just to give it A and B that intersect the circle, and make the plots.
from math import atan2, sin, cos, sqrt, pi
from matplotlib import pyplot
def calc_points(A, B, C):
dx = C[0]-A[0]
dy = C[1]-A[1]
line_angle = atan2(dy, dx)
radius = sqrt(dy*dy + dx*dx)
new_points = []
# now go around the circle and find the points
for i in range(3):
angle = line_angle + (i+1)*45*(pi/180) # new angle in radians
x = radius*cos(angle) + C[0]
y = radius*sin(angle) + C[1]
new_points.append([x, y])
return new_points
# test this with some reasonable values
pyplot.figure()
for i, a in enumerate((-20, 20, 190)):
radius = 5
C = [2, 2]
# find an A and B on the circle and plot them
angle = a*(pi/180)
A = [radius*cos(pi+angle)+C[0], radius*sin(pi+angle)+C[1]]
B = [radius*cos(angle)+C[0], radius*sin(angle)+C[1]]
pyplot.subplot(1,3,i+1)
pyplot.plot([A[0], C[0]], [A[1], C[1]], 'r')
pyplot.plot([B[0], C[0]], [B[1], C[1]], 'r')
# now run these through the calc_points function and the new lines
new_points = calc_points(A, B, C)
for np in new_points:
pyplot.plot([np[0], C[0]], [np[1], C[1]], 'b')
pyplot.xlim(-8, 8)
pyplot.ylim(-8, 8)
for x, X in (("A", A), ("B", B), ("C", C)):
pyplot.text(X[0], X[1], x)
pyplot.show()

If you want to find coordinates of blue lines, may be you will find helpful some information about tranformations (rotations):
http://en.wikipedia.org/wiki/Rotation_matrix
You need to rotate for example vector AC and then you can find coordinate of end point of blue line.

start with this and add a button with code:
private void btnCircleLined_Click(object sender, System.EventArgs e)
{
Graphics graph = Graphics.FromImage(DrawArea);
int x = 100, y = 100, diameter = 50;
myPen.Color = Color.Green;
myPen.Width = 10;
graph.DrawEllipse(myPen, x, y, diameter, diameter);
myPen.Color = Color.Red;
double radian = 45 * Math.PI / 180;
int xOffSet = (int)(Math.Cos(radian) * diameter / 2);
int yOffSet = (int)(Math.Sin(radian) * diameter / 2);
graph.DrawLine(myPen, x, y + yOffSet + myPen.Width + diameter / 2, x + xOffSet + myPen.Width + diameter / 2, y);
graph.DrawLine(myPen, x, y, x + xOffSet + myPen.Width + diameter / 2, y + yOffSet + myPen.Width + diameter / 2);
graph.Dispose();
this.Invalidate();
}
edit: could not see your picture so I misinterpeted your question, but this should get you started.

Translate A with C at the origin (i.e. A-C), rotate CW 45°, then translate back. Repeat three more times.

If I were doing this I'd use polar co-ordinates (apologies for including the link if you are already well aware what they are) as an easy way of figuring out the co-ordinates of the points on the circumference that you need. Then draw lines to there from the centre of the circle.

Related

draw arc using start, end and initial direction

I am trying to draw a railway in the way it is implemented in railroad tycoon 3. I have understood some of the patterns by which this is done, but I cannot find a formula for their application. I am trying to build an arc using only two points and some initial direction. For simplicity, let's assume that I can only plot a path in the range from 0 to 90 degrees. The arc should always start in the direction of "Initial direction". I need a method that would implement this. I tried to depict the idea in the drawings. Any pseudocode would do I guess.
general idea
borderline case at alpha = 0
borderline case at alpha = 90 degrees
Center C lies at middle perpendicular to SE segment, so we should find vectors
se = (E.x - S.x, E.y - S.y)
perp = (-se.y, se.x) = (S.y - E.y, E.x - S.x) //MC direction
and middle point
M = ((E.x + S.x)/2, (E.y - S.y)/2)
and express C coordinates using parametric equation
C = M + perp*t
Note that initial arc direction d is perpendicular to radius CS, so their dot product is zero:
(C - S).dot.d = 0
(M.x + perp.x * t - S.x)*d.x + (M.y + perp.y * t - S.y)*d.y = 0
This is linear equation for unknown parameter t, after solving it we know center C and can build the arc.
Python code. Perhaps examples are too simple to reveal bugs, but the first with half-circle gives R=L/2, center at M, and the second one shows correct C position and R.
from math import hypot, atan2
def arcfromptsdir(sx, sy, ex, ey, dx, dy):
sex = ex - sx
sey = ey - sy
perpx = -sey
perpy = sex
mx = (ex + sx) / 2
my = (ey + sy) / 2
#equation
#(sex/2 + perpx * t )*dx + (sey/2 + perp.y * t )*dy = 0
p = perpx * dx + perpy * dy
if p:
t = -0.5*(sex*dx + sey*dx) / p
else:
return None
#centerx, centery, radius
cx = mx + perpx * t
cy = my + perpy * t
radius = hypot(cx-sx, cy-sy)
arcangle = atan2((sx-cx) * (ey-cy) - (sy-cy) * (ex-cx),
(sx-cx) * (ex-cx) + (sy-cy) * (ey-cy))
return (cx, cy, radius, arcangle)
print(arcfromptsdir(0, 0, 2, 0, 0, 1))
print(arcfromptsdir(0, 0, 2, 0, 0.7071, 0.7071))
(1.0, 0.0, 1.0, -3.141592653589793)
(1.0, -1.0, 1.4142135623730951, -1.5707963267948966)

Check logic for altitude of a triangle using d3

I have this jsbin that shows my working.
In the jsbin, I am trying to draw a line through the altitude through point A (1, 1) that is perpendicular to Line BC which has points B (6, 18) and C (14, 6).
The way I have worked this out is to try and get 2 equations into the form y = mx + c and then rearrange them to y -mx = c and then solve them through simultaneous equations using matrices.
I have this altitude function that does the work:
function altitude(vertex, a, b) {
var slope = gradient(a, b),
x1 = - slope,
y1 = 1,
c1 = getYIntercept(a, slope),
perpendicularSlope = perpendicularGradient(a, b),
x2 = - perpendicularSlope,
y2 = 1,
c2 = getYIntercept(vertex, perpendicularSlope);
var matrix = [
[x1, y1],
[x2, y2]
];
var result = solve(matrix, [c1, c2]);
var g = svg.append('g');
g.append('line')
.style('stroke', 'red')
.attr('class', 'line')
.attr('x1', xScale(vertex.x))
.attr('y1', yScale(vertex.y))
.attr('x2', xScale(result.x))
.attr('y2', yScale(result.y));
}
I first of all get the gradient of BC using this function
var gradient = function(a, b) {
return (b.y - a.y) / (b.x - a.x);
};
Which is -1.5 and from that I can get the perpendicular gradient using this function:
var perpendicularGradient = function (a, b) {
return -1 / gradient(a, b);
};
I make that to be 0.66666 or (2/3).
I get the 2 equations to look like this:
y + 1.5 = 27
y -0.6666666666666666 = 0.33333333333333337
I have some functions in the jsbin that will solve these simultaneously using matrices and cramer's rule, the main one being solve:
function solve(matrix, r) {
var determinant = det(matrix);
var x = det([
[r[0], matrix[0][1]],
[r[1], matrix[1][1]]
]) / determinant;
var y = det([
[matrix[0][0], r[0]],
[matrix[1][0], r[1]]
]) / determinant;
return {x: Math.approx(x), y: Math.approx(y)};
}
function det(matrix) {
return (matrix[0][0]*matrix[1][1])-(matrix[0][1]*matrix[1][0]);
}
I get the coordinates of the intercept to be roughly (12.31, 8.54).
The problem is, it does not look right on the diagram.
Have I taken a wrong step somewhere? I think my calculations are right but I would not rule out them being wrong. It might be down to scale perhaps.
You want to find projection of point A onto line BC.
Let's make vectors
Q = C - B
P = A - B
normalized (unit length):
uQ = Q/ |Q|
Needed projection point D is
D = B + uQ * DotProduct(P, uQ)
For your example A(1,1), B(6,18), C(14,6)
Q = (8, -12)
|Q| = Sqrt(8*8+12*12)~14.4
uQ= (0.55, -0.83)
P=(-5,-17)
DotProduct(P, uQ)=0.55*(-5) -(0.83*-17)=11.39
D = (6+0.55*11.39, 18-0.83*11.39) = (12.26, 8,54)
So your calculation gives right result (though approach is not very efficient), but picture is not exact - different scales of X and Y axes deform angles.
P.S: Second line width = 660 - margin.left - margin.right, makes the picture more reliable

Uniformly distribute x points inside a circle

I would like to uniformly distribute a predetermined set of points within a circle. By uniform distribution, I mean they should all be equally distanced from each other (hence a random approach won't work). I tried a hexagonal approach, but I had problems consistently reaching the outermost radius.
My current approach is a nested for loop where each outer iteration reduces the radius & number of points, and each inner loop evenly drops points on the new radius. Essentially, it's a bunch of nested circles. Unfortunately, it's far from even. Any tips on how to do this correctly?
The goals of having a uniform distribution within the area and a uniform distribution on the boundary conflict; any solution will be a compromise between the two. I augmented the sunflower seed arrangement with an additional parameter alpha that indicates how much one cares about the evenness of boundary.
alpha=0 gives the typical sunflower arrangement, with jagged boundary:
With alpha=2 the boundary is smoother:
(Increasing alpha further is problematic: Too many points end up on the boundary).
The algorithm places n points, of which the kth point is put at distance sqrt(k-1/2) from the boundary (index begins with k=1), and with polar angle 2*pi*k/phi^2 where phi is the golden ratio. Exception: the last alpha*sqrt(n) points are placed on the outer boundary of the circle, and the polar radius of other points is scaled to account for that. This computation of the polar radius is done in the function radius.
It is coded in MATLAB.
function sunflower(n, alpha) % example: n=500, alpha=2
clf
hold on
b = round(alpha*sqrt(n)); % number of boundary points
phi = (sqrt(5)+1)/2; % golden ratio
for k=1:n
r = radius(k,n,b);
theta = 2*pi*k/phi^2;
plot(r*cos(theta), r*sin(theta), 'r*');
end
end
function r = radius(k,n,b)
if k>n-b
r = 1; % put on the boundary
else
r = sqrt(k-1/2)/sqrt(n-(b+1)/2); % apply square root
end
end
Might as well tag on my Python translation.
from math import sqrt, sin, cos, pi
phi = (1 + sqrt(5)) / 2 # golden ratio
def sunflower(n, alpha=0, geodesic=False):
points = []
angle_stride = 360 * phi if geodesic else 2 * pi / phi ** 2
b = round(alpha * sqrt(n)) # number of boundary points
for k in range(1, n + 1):
r = radius(k, n, b)
theta = k * angle_stride
points.append((r * cos(theta), r * sin(theta)))
return points
def radius(k, n, b):
if k > n - b:
return 1.0
else:
return sqrt(k - 0.5) / sqrt(n - (b + 1) / 2)
# example
if __name__ == '__main__':
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
points = sunflower(500, alpha=2, geodesic=False)
xs = [point[0] for point in points]
ys = [point[1] for point in points]
ax.scatter(xs, ys)
ax.set_aspect('equal') # display as square plot with equal axes
plt.show()
Stumbled across this question and the answer above (so all cred to user3717023 & Matt).
Just adding my translation into R here, in case someone else needed that :)
library(tibble)
library(dplyr)
library(ggplot2)
sunflower <- function(n, alpha = 2, geometry = c('planar','geodesic')) {
b <- round(alpha*sqrt(n)) # number of boundary points
phi <- (sqrt(5)+1)/2 # golden ratio
r <- radius(1:n,n,b)
theta <- 1:n * ifelse(geometry[1] == 'geodesic', 360*phi, 2*pi/phi^2)
tibble(
x = r*cos(theta),
y = r*sin(theta)
)
}
radius <- function(k,n,b) {
ifelse(
k > n-b,
1,
sqrt(k-1/2)/sqrt(n-(b+1)/2)
)
}
# example:
sunflower(500, 2, 'planar') %>%
ggplot(aes(x,y)) +
geom_point()
Building on top of #OlivelsAWord , here is a Python implementation using numpy:
import numpy as np
import matplotlib.pyplot as plt
def sunflower(n: int, alpha: float) -> np.ndarray:
# Number of points respectively on the boundary and inside the cirlce.
n_exterior = np.round(alpha * np.sqrt(n)).astype(int)
n_interior = n - n_exterior
# Ensure there are still some points in the inside...
if n_interior < 1:
raise RuntimeError(f"Parameter 'alpha' is too large ({alpha}), all "
f"points would end-up on the boundary.")
# Generate the angles. The factor k_theta corresponds to 2*pi/phi^2.
k_theta = np.pi * (3 - np.sqrt(5))
angles = np.linspace(k_theta, k_theta * n, n)
# Generate the radii.
r_interior = np.sqrt(np.linspace(0, 1, n_interior))
r_exterior = np.ones((n_exterior,))
r = np.concatenate((r_interior, r_exterior))
# Return Cartesian coordinates from polar ones.
return r * np.stack((np.cos(angles), np.sin(angles)))
# NOTE: say the returned array is called s. The layout is such that s[0,:]
# contains X values and s[1,:] contains Y values. Change the above to
# return r.reshape(n, 1) * np.stack((np.cos(angles), np.sin(angles)), axis=1)
# if you want s[:,0] and s[:,1] to contain X and Y values instead.
if __name__ == '__main__':
fig, ax = plt.subplots()
# Let's plot three sunflowers with different values of alpha!
for alpha in (0, 1, 2):
s = sunflower(500, alpha)
# NOTE: the 'alpha=0.5' parameter is to control transparency, it does
# not have anything to do with the alpha used in 'sunflower' ;)
ax.scatter(s[0], s[1], alpha=0.5, label=f"alpha={alpha}")
# Display as square plot with equal axes and add a legend. Then show the result :)
ax.set_aspect('equal')
ax.legend()
plt.show()
Adding my Java implementation of previous answers with an example (Processing).
int n = 2000; // count of nodes
Float alpha = 2.; // constant that can be adjusted to vary the geometry of points at the boundary
ArrayList<PVector> vertices = new ArrayList<PVector>();
Float scaleFactor = 200.; // scale points beyond their 0.0-1.0 range for visualisation;
void setup() {
size(500, 500);
// Test
vertices = sunflower(n, alpha);
displayTest(vertices, scaleFactor);
}
ArrayList<PVector> sunflower(int n, Float alpha) {
Double phi = (1 + Math.sqrt(5)) / 2; // golden ratio
Double angle = 2 * PI / Math.pow(phi, 2); // value used to calculate theta for each point
ArrayList<PVector> points = new ArrayList<PVector>();
Long b = Math.round(alpha*Math.sqrt(n)); // number of boundary points
Float theta, r, x, y;
for (int i = 1; i < n + 1; i++) {
r = radius(i, n, b.floatValue());
theta = i * angle.floatValue();
x = r * cos(theta);
y = r * sin(theta);
PVector p = new PVector(x, y);
points.add(p);
}
return points;
}
Float radius(int k, int n, Float b) {
if (k > n - b) {
return 1.0;
} else {
Double r = Math.sqrt(k - 0.5) / Math.sqrt(n - (b+1) / 2);
return r.floatValue();
}
}
void displayTest(ArrayList<PVector> points, Float size) {
for (int i = 0; i < points.size(); i++) {
Float x = size * points.get(i).x;
Float y = size * points.get(i).y;
pushMatrix();
translate(width / 2, height / 2);
ellipse(x, y, 5, 5);
popMatrix();
}
}
Here's my Unity implementation.
Vector2[] Sunflower(int n, float alpha = 0, bool geodesic = false){
float phi = (1 + Mathf.Sqrt(5)) / 2;//golden ratio
float angle_stride = 360 * phi;
float radius(float k, float n, float b)
{
return k > n - b ? 1 : Mathf.Sqrt(k - 0.5f) / Mathf.Sqrt(n - (b + 1) / 2);
}
int b = (int)(alpha * Mathf.Sqrt(n)); //# number of boundary points
List<Vector2>points = new List<Vector2>();
for (int k = 0; k < n; k++)
{
float r = radius(k, n, b);
float theta = geodesic ? k * 360 * phi : k * angle_stride;
float x = !float.IsNaN(r * Mathf.Cos(theta)) ? r * Mathf.Cos(theta) : 0;
float y = !float.IsNaN(r * Mathf.Sin(theta)) ? r * Mathf.Sin(theta) : 0;
points.Add(new Vector2(x, y));
}
return points.ToArray();
}

How to calculate coordinates of third point in a triangle (2D) knowing 2 points coordinates, all lenghts and all angles [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I have a triangle and I know the coordinates of two vertices: A=(x1,y1),B=(x2,y2)
All the angles: ABC=90∘,CAB=30∘ and BCA=60∘ and all the edge lengths. How can I find the coordinates of the third vertex C=(x3,y3)?
I know there are two solutions (I want both).
You know p1 and p2. You know the internal angles.
Make a ray from p1 trough p2, and rotate it CW or CCW 30° around p1.
Make a line trough p1 and p2, and rotate it 90° around p2.
Calculate the intersections.
You get the points:
x3 = x2 + s*(y1 - y2)
y3 = y2 + s*(x2 - x1)
and
x3 = x2 + s*(y2 - y1)
y3 = y2 + s*(x1 - x2)
where s = 1/sqrt(3) ≈ 0.577350269
In a 30-60-90 right triangle, smallest leg (the smallest side adjacent the 90 degree angle) has length of 1/2 of the hypotenuse (the side opposite to 90 degree angle), so since you have the side lengths, you can determine which leg is the line segment AB.
From that you deduce where do the angles go.
Then to compute the coordinate you just need to pick the point on the circle of the radius with the correct radius length at the correct angle.
Two solutions come from measuring the angle clock-wise or counter-clockwise, and result in symmetrical triangles, with the edge AB being the line of symmetry.
Since you already have given the angles, compute the length of AB via quadratic formula
L(AB) = Sqrt[(x1-x2)^2 + (y1-y2)^2].
Now, let x = L(AC) = 2*L(BC) so since it is the right triangle,
L(AC)^2 = L(BC)^2 + L(AB)^2,
x^2 = (0.5x)^2 + L(AB)^2, so L(AB) = x*Sqrt[3]/2,
and since you already computed L(AB) you now have x.
The angle of the original AB is a = arctan([y2-y1]/[x2-x1]).
Now you can measure 30 degrees up or down (use a+30 or a-30 as desired)
and mark the point C on the circle (centered at A) of radius x (which we computed above) at the angle a +/- 30.
Then, C has coordinates
x3 = x1 + x*cos(a+30)
y3 = y1 + x*sin(a+30)
or you can use (a-30) to get the symmetrical triangle.
Here is the code to return points of full polygon if two points and number of sides are provided as input.
This is written for Android(Java) and the logic can be re-used for other languages
private static final float angleBetweenPoints(PointF a, PointF b) {
float deltaY = b.y - a.y;
float deltaX = b.x - a.x;
return (float) (Math.atan2(deltaY, deltaX));
}
private static PointF pullPointReferenceToLineWithAngle(PointF a, PointF b,
float angle) {
float angleBetween = angleBetweenPoints(b, a);
float distance = (float) Math.hypot(b.x - a.x, b.y - a.y);
float x = (float) (b.x + (distance * Math.cos((angleBetween + angle))));
float y = (float) (b.y + (distance * Math.sin((angleBetween + angle))));
return new PointF(x, y);
}
private static List<PointF> pullPolygonPointsFromBasePoints(PointF a,
PointF b, int noOfSides) {
List<PointF> points = new ArrayList<>();
points.add(a);
points.add(b);
if (noOfSides < 3) {
return points;
}
float angleBetweenTwoSides = (float) ((((noOfSides - 2) * 180) / noOfSides)
* Math.PI / 180);
for (int i = 3; i <= noOfSides; i++) {
PointF nextPoint = pullPointReferenceToLineWithAngle(
points.get(i - 3), points.get(i - 2), angleBetweenTwoSides);
points.add(nextPoint);
}
return points;
}
Usage is onDraw method:
PointF a = new PointF(100, 600);
PointF b = new PointF(300, 500);
int noOfSides = 3;
List<PointF> polygonPoints = pullPolygonPointsFromBasePoints(a, b,
noOfSides);
drawPolyPoints(canvas, noOfSides, polygonPoints);
This is a right angled triangle. The angle ABC is 90 degrees, so calculate the vector joining A to B and call this AA and normalise it:
AA = (x2-x1,y2-y1) / |(x2-x1,y2-y1)|
A unit vector perpendicular to AA is given by
BB = (-(y2-y1),x2-x1) / |(x2-x1,y2-y1)|
Because AC is perpendicular to AB all you can obtain your first point P1 as
P1 = (x2,y2) + K * BB
where K is the scalar value equal to the length of side AC (which you say you already know in the question). Your second solution point P2 is then simply given by going in the negative BB direction
P2 = (x2,y2) - K * BB

Computing the 3D coordinates on a unit sphere from a 2D point

I have a square bitmap of a circle and I want to compute the normals of all the pixels in that circle as if it were a sphere of radius 1:
The sphere/circle is centered in the bitmap.
What is the equation for this?
Don't know much about how people program 3D stuff, so I'll just give the pure math and hope it's useful.
Sphere of radius 1, centered on origin, is the set of points satisfying:
x2 + y2 + z2 = 1
We want the 3D coordinates of a point on the sphere where x and y are known. So, just solve for z:
z = ±sqrt(1 - x2 - y2).
Now, let us consider a unit vector pointing outward from the sphere. It's a unit sphere, so we can just use the vector from the origin to (x, y, z), which is, of course, <x, y, z>.
Now we want the equation of a plane tangent to the sphere at (x, y, z), but this will be using its own x, y, and z variables, so instead I'll make it tangent to the sphere at (x0, y0, z0). This is simply:
x0x + y0y + z0z = 1
Hope this helps.
(OP):
you mean something like:
const int R = 31, SZ = power_of_two(R*2);
std::vector<vec4_t> p;
for(int y=0; y<SZ; y++) {
for(int x=0; x<SZ; x++) {
const float rx = (float)(x-R)/R, ry = (float)(y-R)/R;
if(rx*rx+ry*ry > 1) { // outside sphere
p.push_back(vec4_t(0,0,0,0));
} else {
vec3_t normal(rx,sqrt(1.-rx*rx-ry*ry),ry);
p.push_back(vec4_t(normal,1));
}
}
}
It does make a nice spherical shading-like shading if I treat the normals as colours and blit it; is it right?
(TZ)
Sorry, I'm not familiar with those aspects of C++. Haven't used the language very much, nor recently.
This formula is often used for "fake-envmapping" effect.
double x = 2.0 * pixel_x / bitmap_size - 1.0;
double y = 2.0 * pixel_y / bitmap_size - 1.0;
double r2 = x*x + y*y;
if (r2 < 1)
{
// Inside the circle
double z = sqrt(1 - r2);
.. here the normal is (x, y, z) ...
}
Obviously you're limited to assuming all the points are on one half of the sphere or similar, because of the missing dimension. Past that, it's pretty simple.
The middle of the circle has a normal facing precisely in or out, perpendicular to the plane the circle is drawn on.
Each point on the edge of the circle is facing away from the middle, and thus you can calculate the normal for that.
For any point between the middle and the edge, you use the distance from the middle, and some simple trig (which eludes me at the moment). A lerp is roughly accurate at some points, but not quite what you need, since it's a curve. Simple curve though, and you know the beginning and end values, so figuring them out should only take a simple equation.
I think I get what you're trying to do: generate a grid of depth data for an image. Sort of like ray-tracing a sphere.
In that case, you want a Ray-Sphere Intersection test:
http://www.siggraph.org/education/materials/HyperGraph/raytrace/rtinter1.htm
Your rays will be simple perpendicular rays, based off your U/V coordinates (times two, since your sphere has a diameter of 2). This will give you the front-facing points on the sphere.
From there, calculate normals as below (point - origin, the radius is already 1 unit).
Ripped off from the link above:
You have to combine two equations:
Ray: R(t) = R0 + t * Rd , t > 0 with R0 = [X0, Y0, Z0] and Rd = [Xd, Yd, Zd]
Sphere: S = the set of points[xs, ys, zs], where (xs - xc)2 + (ys - yc)2 + (zs - zc)2 = Sr2
To do this, calculate your ray (x * pixel / width, y * pixel / width, z: 1), then:
A = Xd^2 + Yd^2 + Zd^2
B = 2 * (Xd * (X0 - Xc) + Yd * (Y0 - Yc) + Zd * (Z0 - Zc))
C = (X0 - Xc)^2 + (Y0 - Yc)^2 + (Z0 - Zc)^2 - Sr^2
Plug into quadratic equation:
t0, t1 = (- B + (B^2 - 4*C)^1/2) / 2
Check discriminant (B^2 - 4*C), and if real root, the intersection is:
Ri = [xi, yi, zi] = [x0 + xd * ti , y0 + yd * ti, z0 + zd * ti]
And the surface normal is:
SN = [(xi - xc)/Sr, (yi - yc)/Sr, (zi - zc)/Sr]
Boiling it all down:
So, since we're talking unit values, and rays that point straight at Z (no x or y component), we can boil down these equations greatly:
Ray:
X0 = 2 * pixelX / width
Y0 = 2 * pixelY / height
Z0 = 0
Xd = 0
Yd = 0
Zd = 1
Sphere:
Xc = 1
Yc = 1
Zc = 1
Factors:
A = 1 (unit ray)
B
= 2 * (0 + 0 + (0 - 1))
= -2 (no x/y component)
C
= (X0 - 1) ^ 2 + (Y0 - 1) ^ 2 + (0 - 1) ^ 2 - 1
= (X0 - 1) ^ 2 + (Y0 - 1) ^ 2
Discriminant
= (-2) ^ 2 - 4 * 1 * C
= 4 - 4 * C
From here:
If discriminant < 0:
Z = ?, Normal = ?
Else:
t = (2 + (discriminant) ^ 1 / 2) / 2
If t < 0 (hopefully never or always the case)
t = -t
Then:
Z: t
Nx: Xi - 1
Ny: Yi - 1
Nz: t - 1
Boiled farther still:
Intuitively it looks like C (X^2 + Y^2) and the square-root are the most prominent figures here. If I had a better recollection of my math (in particular, transformations on exponents of sums), then I'd bet I could derive this down to what Tom Zych gave you. Since I can't, I'll just leave it as above.

Resources