Archived

This topic is now archived and is closed to further replies.

Texturing a Sphere

This topic is 6359 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Here''s some code to build a sphere with texture coordinates in the verticies. (It''s stolen directly from the DX8 bumpearth sample code, so I take no blame or credit for it.)

    
// Get the World-View(WV) matrix set
D3DXMATRIX matWorld, matView, matWorldView;
m_pd3dDevice->GetTransform( D3DTS_WORLD, &matWorld );
m_pd3dDevice->GetTransform( D3DTS_VIEW, &matView );
D3DXMatrixMultiply( &matWorldView, &matWorld, &matView );

// Lock the vertex buffer

BUMPVERTEX* vtx;
m_pEarthVB->Lock( 0, 0, (BYTE**)&vtx, 0 );

// Establish constants used in sphere generation

DWORD dwNumSphereRings = m_bHighTesselation ? 15 : 5;
DWORD dwNumSphereSegments = m_bHighTesselation ? 30 : 10;
FLOAT fDeltaRingAngle = ( D3DX_PI / dwNumSphereRings );
FLOAT fDeltaSegAngle = ( 2.0f * D3DX_PI / dwNumSphereSegments );

D3DXVECTOR4 vT;
FLOAT fScale;

// Generate the group of rings for the sphere

for( DWORD ring = 0; ring < dwNumSphereRings; ring++ )
{
FLOAT r0 = sinf( (ring+0) * fDeltaRingAngle );
FLOAT r1 = sinf( (ring+1) * fDeltaRingAngle );
FLOAT y0 = cosf( (ring+0) * fDeltaRingAngle );
FLOAT y1 = cosf( (ring+1) * fDeltaRingAngle );

// Generate the group of segments for the current ring

for( DWORD seg = 0; seg < (dwNumSphereSegments+1); seg++ )
{
FLOAT x0 = r0 * sinf( seg * fDeltaSegAngle );
FLOAT z0 = r0 * cosf( seg * fDeltaSegAngle );
FLOAT x1 = r1 * sinf( seg * fDeltaSegAngle );
FLOAT z1 = r1 * cosf( seg * fDeltaSegAngle );

// Add two vertices to the strip which makes up the sphere

(*vtx).p = (*vtx).n = D3DXVECTOR3(x0,y0,z0);
(*vtx).tu1 = (*vtx).tu2 = -((FLOAT)seg)/dwNumSphereSegments;
(*vtx).tv1 = (*vtx).tv2 = (ring+0)/(FLOAT)dwNumSphereRings;

// Use the transformed normal to generate texture coords

D3DXVec3Transform( &vT, &(*vtx).n, &matWorldView );
fScale = 1.37f / D3DXVec4Length( &vT );
(*vtx).tu1 = 0.5f + fScale*vT.x;
(*vtx).tv1 = 0.5f - fScale*vT.y;
vtx++;

(*vtx).p = (*vtx).n = D3DXVECTOR3(x1,y1,z1);
(*vtx).tu1 = (*vtx).tu2 = -((FLOAT)seg)/dwNumSphereSegments;
(*vtx).tv1 = (*vtx).tv2 = (ring+1)/(FLOAT)dwNumSphereRings;

// Use the transformed normal to generate texture coords

D3DXVec3Transform( &vT, &(*vtx).n, &matWorldView );
fScale = 1.37f / D3DXVec4Length( &vT );
(*vtx).tu1 = 0.5f + fScale*vT.x;
(*vtx).tv1 = 0.5f - fScale*vT.y;
vtx++;
}
}

m_pEarthVB->Unlock();

Share this post


Link to post
Share on other sites