Skip to content

Instantly share code, notes, and snippets.

@rfdickerson
Created September 24, 2017 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rfdickerson/2f4d7db88e6e38e7620a1b8a1a9ff417 to your computer and use it in GitHub Desktop.
Save rfdickerson/2f4d7db88e6e38e7620a1b8a1a9ff417 to your computer and use it in GitHub Desktop.
Sphere Matlab
width = 1024;
height = 1024;
numpixels = width * height;
x = linspace(-1, 1, width);
y = linspace(-1, 1, height);
[X,Y] = meshgrid(x,y);
view_direction = [reshape(X, numpixels, 1) reshape(Y, numpixels, 1) ones(numpixels,1)];
%view_direction = bsxfun(@rdivide, coords, sqrt(sum(coords.^2,2)));
view_direction = view_direction ./ sqrt(sum(view_direction.^2,2));
view_origin = [0, 0, -2];
s_center = [0, 0, 0];
s_radius = 0.7;
light_origin = [-1, -1, -3];
specularity = 40;
ks = 0.4
kd = 0.7
diffuse_color = [0, 0.3, 0.8];
spec_color = [0.8, 0.8, 0.95];
a = ones(numpixels,1); % sum(view_direction.^2, 2);
b = 2 * view_direction * (view_origin - s_center)';
c = sum((view_origin - s_center).^2,2) - s_radius^2;
discriminant = b.^2 - 4 .* a .* c;
hits = discriminant > 0;
distancea = (-b - sqrt(discriminant))./(2*a);
distanceb = (-b + sqrt(discriminant))./(2*a);
distance = min(distancea, distanceb);
distance(hits==0) = NaN;
intersection = view_origin + view_direction .* distance;
normals = intersection - s_center;
normals = normals ./ sqrt(sum(normals.^2,2));
light_direction = light_origin - intersection ;
light_direction = light_direction ./ sqrt(sum(light_direction.^2,2));
view_direction = view_origin - intersection;
view_direction = view_direction ./ sqrt(sum(view_direction.^2,2));
r = (2*(light_direction .* normals) .* normals) - light_direction;
r = r ./ sqrt(sum(r.^2,2));
specular_intensity = max(0, dot(r, view_direction, 2)) .^ specularity ;
diffuse_intensity = max(0, dot(normals, light_direction, 2));
light_color = specular_intensity * spec_color + diffuse_intensity * diffuse_color;
image2 = reshape(light_color, width, height, 3);
imagesc(image2);
pbaspect([1 1 1])
saveas(1,"sphere.png");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment