back to home

Tutorial 3: Basic Texturing with OpenSceneGraph

Lighting Example

We know how to create geometric objects and light already. Not let's combine this, add some textures to a couple of spheres, make them rotate a bit and voila: We have a Solar System Simulation!

Add a texture onto a geometric object

The following code will create a sphere and assign a simple material and texture to it.

	// create a sphere
	Geode *sphere = new Geode();
	sphere->addDrawable(new ShapeDrawable(new Sphere(Vec3(), 1)));

	// create a simple material
	Material *material = new Material();
	material->setEmission(Material::FRONT, Vec4(0.8, 0.8, 0.8, 1.0));

	// create a texture
	// load image for texture
	Image *image = osgDB::readImageFile("texture.png");
	if (!image) {
		std::cout << "Couldn't load texture." << std::endl;
		return NULL;
	osg::Texture2D *texture = new Texture2D;
	texture->setFilter(Texture::MIN_FILTER, Texture::LINEAR_MIPMAP_LINEAR);
	texture->setFilter(Texture::MAG_FILTER, Texture::LINEAR);
	texture->setWrap(Texture::WRAP_S, Texture::CLAMP);
	texture->setWrap(Texture::WRAP_T, Texture::CLAMP);

	// assign the material and texture to the sphere
	StateSet *sphereStateSet = sphere->getOrCreateStateSet();
	sphereStateSet->setTextureAttributeAndModes(0, texture, StateAttribute::ON);

As you can see it doesn't take much to add a texture to our scene. Combined with the other things we know already we can create some good looking Solar System Simulation. Download the complete source code to see how!

Complete Source Code

Since we use classes and textures here, we can't just drop the whole source code. Instead, you can download all needed files in a zip-archive: