Example #1
0
// Returns a random point on the surface of this shape
Point Sphere::GetRandomPointOnSurface(RNG& rng) const {
	// Keep generating random coordinates within cube around unit sphere
	// Reject any points outside the unit sphere
	float x = 1.f - 2.f * rng.Random();
	float y = 1.f - 2.f * rng.Random();
	float z = 1.f - 2.f * rng.Random();
	float lengthSquared = x*x + y*y + z*z;
	// Expected number of iterations < 2
	while (lengthSquared > 1.f) {
		x = 1.f - 2.f * rng.Random();
		y = 1.f - 2.f * rng.Random();
		z = 1.f - 2.f * rng.Random();
		lengthSquared = x*x + y*y + z*z;
	}

	// Point on surface of sphere
	float invLength = 1.f / sqrtf(lengthSquared);
	Point p(x, y, z);
	return p * r * invLength + c;
}