Hello!

I'm trying to alter a raytracer program which is supposed to create a picture of 25 spheres. It's an exercise in optimization so I'm basically trying to make the program run without any unnecessary code, making the program specific for the intended output. I'm using a C++ array to add the spheres.

I've done a couple of changes but now I've come across some problems, which is why I need help. So, I've got a couple of questions regarding this:

``````//std::vector<CSphere> spheres; implementation of vector previously used, replaced with array
CSphere* spheres = new CSphere;
srand(10);
int c = 0;
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
float sx = -5.0f + 10.0f * ((float)i / 5.0f);
float sy = -5.0f + 10.0f * ((float)j / 5.0f);

float x = sx + 1.0f * ((float)rand() / (float)RAND_MAX);
float y = sy + 1.0f * ((float)rand() / (float)RAND_MAX);
float z = 0.0f;
float r = 0.5f + 0.5f * (float)rand() / (float)RAND_MAX;

spheres[c++].m_C = CVector3f(x, y, z);
spheres[c].m_R = r;
///CSphere c(CVector3f(x, y, z ), r);
///spheres.push_back(c); push back replaced.. but is it right?
}
}``````

My intention is to replace the vector with an array containing the spheres and replacing the push_back accordingly. The program works fine but I'm not sure if this is completely right. m_C returns the center of a sphere and m_R the radius.

This code might be relevant for you to help me:

``````class CSphere
{
public:
CVector3f m_C;
float m_R;
CSphere(const CVector3f& c, float r) : m_C(c), m_R(r) {}
CSphere() {}

bool Intersect(float& t, const CRay& ray)
{
CVector3f oc = m_C - ray.m_O;
float l2oc = oc.x * oc.x + oc.y * oc.y + oc.z * oc.z;
float r2 = m_R * m_R;
if (l2oc < r2)
{
float tca = oc.x * ray.m_D.x + oc.y * ray.m_D.y + oc.z * ray.m_D.z;
float l2hc = (r2 - l2oc) / 1.0f + (tca * tca);
t = tca + (float)sqrt(l2hc);
return true;
}
else
{
float tca = oc.x * ray.m_D.x + oc.y * ray.m_D.y + oc.z * ray.m_D.z;
if (tca < 0.0f) // points away from the sphere
return false;
float l2hc = (r2 - l2oc) / 1.0f + (tca * tca);
if (l2hc > 0)
{
t = tca - (float)sqrt(l2hc);
return true;
}
return false;
}
}

};``````

Also, how and where do I delete the array? I figure it's at the end of the program, like this: delete [] spheres;

Looks fine to me. And yes, you would just delete the array at the end of the program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.