void DeferredSkyboxRenderPass::SkyboxPass (const Scene* scene, const Camera* camera)
{
	GL::Enable (GL_STENCIL_TEST);
	GL::StencilFunc (GL_EQUAL, 0, 0xFF);
	GL::StencilOp (GL_KEEP, GL_KEEP, GL_KEEP);

	Pipeline::CreateProjection (camera->GetProjectionMatrix ());
	Pipeline::SendCamera (camera);

	/*
	 * Get scene's skybox
	*/

	Skybox* sceneSkybox = scene->GetSkybox ();

	/*
	 * Check if there is an actual skybox attached
	*/

	if (sceneSkybox != nullptr) {
		sceneSkybox->GetRenderer ()->Draw ();
	}

	GL::Disable (GL_STENCIL_TEST);
}
Beispiel #2
0
    void GameNode3DReader::setPropsWithFlatBuffers(cocos2d::Node *node,
                                                   const flatbuffers::Table* node3DOptions)
    {
        auto options = (GameNode3DOption*)node3DOptions;
        
        std::string name = options->name()->c_str();
        node->setName(name);

        bool skyBoxEnabled = options->skyBoxEnabled() != 0;
        if (skyBoxEnabled)
        {
            auto leftFileData = options->leftFileData()->path()->c_str();
            auto rightFileData = options->rightFileData()->path()->c_str();
            auto upFileData = options->upFileData()->path()->c_str();
            auto downFileData = options->downFileData()->path()->c_str();
            auto forwardFileData = options->forwardFileData()->path()->c_str();
            auto backFileData = options->backFileData()->path()->c_str();

            Skybox* childBox = Skybox::create(leftFileData,rightFileData,upFileData,downFileData,forwardFileData,backFileData);
            unsigned short cameraFlag = 1 << 10;
            childBox->setCameraMask(cameraFlag, false);
            node->addChild(childBox,0,"_innerSkyBox");
        }

        std::string customProperty = options->customProperty()->c_str();
        ComExtensionData* extensionData = ComExtensionData::create();
        extensionData->setCustomProperty(customProperty);\
        if (node->getComponent("ComExtensionData"))
        {
            node->removeComponent("ComExtensionData");
        }
        node->addComponent(extensionData);
    }
void ZombieForce::DrawScene()
{
	md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::Blue));
	md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0);

	md3dImmediateContext->IASetInputLayout(InputLayouts::Basic32);
    md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
 
	UINT stride = sizeof(Vertex::Basic32);
    UINT offset = 0;
	
	mCam.UpdateViewMatrix();

	XMMATRIX view  = mCam.View();
	XMMATRIX proj  = mCam.Proj();
	XMMATRIX viewProj = mCam.ViewProj();

	// Set per frame constants.
	Effects::BillboardFX->SetDirLights(mDirLights);
	Effects::BillboardFX->SetEyePosW(mCam.GetPosition());
	Effects::BillboardFX->SetCubeMap(mSky->CubeMapSRV());

	//ID3DX11EffectTechnique* activeTech = Effects::BasicFX->Light2TexTech;
	ID3DX11EffectTechnique* activeTech = Effects::BillboardFX->Light2TexTech;

    D3DX11_TECHNIQUE_DESC techDesc;
	activeTech->GetDesc( &techDesc );
    for(UINT p = 0; p < techDesc.Passes; ++p)
    {
		pyramid->DrawPyramid(md3dImmediateContext,activeTech, mCam);
		//myFirstSphere->DrawSphere(md3dImmediateContext,activeTech, mCam);
		myFirstPlane->DrawPlane(md3dImmediateContext,activeTech, mCam);
		//myFirstGeoSphere->DrawGeoSphere(md3dImmediateContext,activeTech, mCam);
		//myFirstCylinder->DrawCylinder(md3dImmediateContext,activeTech, mCam);
		for(unsigned int i = 0; i < spheres.size(); ++i)
		{
			spheres[i]->DrawSphere(md3dImmediateContext,activeTech, mCam);
		}
		for(unsigned int i = 0; i < boxes.size(); ++i)
		{
			boxes[i]->DrawBox(md3dImmediateContext,activeTech, mCam);
		}
		CMESHMANAGER->Render(md3dImmediateContext, activeTech, mCam);
    }

	mSky->Draw(md3dImmediateContext, mCam);

	// restore default states, as the SkyFX changes them in the effect file.
	md3dImmediateContext->RSSetState(0);
	md3dImmediateContext->OMSetDepthStencilState(0, 0);

	HR(mSwapChain->Present(0, 0));
}
	void RenderingGame::Update()
	{
		Skybox* skybox = (Skybox*)mServices.GetService(Skybox::TypeIdClass());
		GamePadComponent* gamePadComponent = (GamePadComponent *)mServices.GetService(GamePadComponent::TypeIdClass());

		if (skybox && gamePadComponent)
		{
			if (gamePadComponent->WasButtonUp(GamePadButton::LeftStick) && gamePadComponent->IsButtonDown(GamePadButton::LeftStick))
			{
				skybox->SetEnabled(!skybox->IsEnabled());
			}
		}

		Game::Update();
	}
	void transform (Skybox sky)
	{
		// Ease keyRot
		static vec3f porbit;
		orbit.x += (keyRot.x - porbit.x) * 0.05f;
		orbit.y += (keyRot.y - porbit.y) * 0.05f;
		porbit = orbit;

		// Skybox is not affected by camera translation
		glPushMatrix();
		glRotatef(viewRot.x, -1.0, 0.0, 0.0);
		glRotatef(viewRot.y, 0.0, 1.0, 0.0);
		glRotatef(orbit.x, 1.0, 0.0, 0.0);
		glRotatef(orbit.y, 0.0, 1.0, 0.0);
		glRotatef(orbit.z, 0.0, 0.0, 1.0);
		sky.draw();
		glPopMatrix();

		// Rotate entire coordinate system (view rotation)
		glRotatef(viewRot.x, -1.0, 0.0, 0.0);
		glRotatef(viewRot.y, 0.0, 1.0, 0.0);

		// Move viewer into distance, starting from origin
		glTranslatef(0, 0, -distance);
		glTranslatef(origin.x, origin.y, origin.z);

		// Orbit about keyboard rotation angle
		glRotatef(orbit.x, 1.0, 0.0, 0.0);
		glRotatef(orbit.y, 0.0, 1.0, 0.0);
		glRotatef(orbit.z, 0.0, 0.0, 1.0);
		glRotatef(90, 0.0, 1.0, 0.0);
	}
Beispiel #6
0
void display(void) {

//----------------------------------------------------------------------------//
// Snippet-5-3                                                                //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-7 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	float currentTimeStamp;
	Matrix osgCamMatrix;
	float dt; // time difference between currentTimestamp and lastTimestamp

	currentTimeStamp = timer.getTime(); //get current time
	dt = currentTimeStamp - lastTimeStamp;

	controller->update();    // poll/update associated devices
	navigation->update(dt);	 // update navigation

	// process transformations which belong to the pipes with priority 0x0E000000
	TransformationManager::step(dt, 0x0E000000);

	camera->getCameraTransformation(camMatrix); // get camera transformation
//----------------------------------------------------------------------------//
// Snippet-2-7 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-17 - BEGIN                                                       //
//----------------------------------------------------------------------------//
	skybox.setupRender(camera->getPosition()); // attach the SkyBox to the camera
//----------------------------------------------------------------------------//
// Snippet-2-17 - END                                                         //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-4-2                                                                //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-8 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	set(osgCamMatrix, camMatrix);      // convert gmtl matrix into OpenSG matrix

	Navigator* nav = mgr->getNavigator();
	nav->set(osgCamMatrix);            // plug new camera matrix into navigator

	TransformationManager::step(dt);   // process the remaining pipes

	lastTimeStamp = currentTimeStamp;
//----------------------------------------------------------------------------//
// Snippet-2-8 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-6-1                                                                //
//----------------------------------------------------------------------------//

	mgr->redraw(); // redraw the window
} // display
void drawCity()
{
	for(size_t i = 0; i < city.size(); i++)
	{
		city[i].draw();
	}
	glCallList(PAVEMENT);
	if(cam.eye.z < 75 && cam.eye.z > 0)
		glCallList(STREETS);

	sky.draw();
}
Beispiel #8
0
void render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    cam.orient_before();
    box.render(Vector3f(5.0, 5.0, 5.0));
    cam.orient();
    textureManager.bind(grass);
    /*glBegin(GL_QUADS);
    glTexCoord2f(0.0, 0.0);
    glVertex3f(-1000.0, -1.0, -1000.0);
    glTexCoord2f(0.0, 200.0);
    glVertex3f(-1000.0, -1.0, 1000.0);
    glTexCoord2f(200.0, 200.0);
    glVertex3f(1000.0, -1.0, 1000.0);
    glTexCoord2f(200.0, 0.0);
    glVertex3f(1000.0, -1.0, -1000.0);
    glEnd();*/
    glPushMatrix();
	glPushMatrix();
    glTranslatef(0.0, -1.0, -5.0);
    //plant.render();
	glPushAttrib(GL_ENABLE_BIT);
	glDisable(GL_TEXTURE_2D);
	//glTranslatef(-3.0, 0.0, 0.0);
	//fireworks.render();
	//glTranslatef(6.0, 0.0, 0.0);
	//fountain.render();
	//glTranslatef(4.0, 0.0, 0.0);
	glColor3f(1.0, 0.6, 0.3);
	glDisable(GL_TEXTURE_2D);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
#ifdef ANIMATION
 animation.render();
#else
mesh.render();
#endif
  glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

	glPopAttrib();
	glPopMatrix();

	if (snow_falling)
	{
		glScalef(50.0, 50.0, 50.0);
		textureManager.bind(snow_tex);
		snow.render();
	}

	glPopMatrix();
    glFlush();
	SDL_GL_SwapBuffers();
}
Beispiel #9
0
void drawGameMeshes(void)
{
    skybox.render();
    glmaze.render();

    for (unsigned int i=0; i<Player_List.size(); ++i) {
        Player_List[i]->draw();
    }

    cone1.render();
    cone2.render();
}
void LegacyOpenGLRenderer::DrawSkybox(const Skybox & InSkybox)
{
    // Turn Depth off
    glDisable(GL_DEPTH_TEST);
    const VertexObject* vo = InSkybox.GetCube();
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    const Texture& tex = vo->GetTexture();
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, vo->GetTexture().GetTexture());
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glMatrixMode(GL_TEXTURE);
    glPushMatrix(); // Texture matrix manipulation
    const Vector3 &offset = tex.GetOffset(), &scale = tex.GetScale();
    const Rotation &rot = tex.GetRotation();
    glTranslatef(offset.x, offset.y, offset.z);
    glRotatef(rot.deg, rot.axis.x, rot.axis.y, rot.axis.z);
    glScalef(scale.x, scale.y, scale.z);
    glMatrixMode(GL_MODELVIEW);

    // Translate to the camera position
    glPushMatrix();
    Translate(cam->GetPosition());

    // Setup Arrays
    glVertexPointer(3, GL_FLOAT, 0, &(vo->GetVertices()[0]));
    glNormalPointer(GL_FLOAT, 0, &(vo->GetNormals()[0]));
    glTexCoordPointer(2, GL_FLOAT, 0, &(vo->GetTexCoords()[0]));

    // Draw!
    glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(vo->GetIndicies().size()), GL_UNSIGNED_INT, &(vo->GetIndicies()[0]));

    glPopMatrix(); 

    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

    glBindTexture(GL_TEXTURE_2D, NULL);
    glDisable(GL_TEXTURE_2D);
    glMatrixMode(GL_TEXTURE);
    glPopMatrix(); // Undo Texture matrix manipulation
    glMatrixMode(GL_MODELVIEW);
    // Turn Depth test on again
    glEnable(GL_DEPTH_TEST);
}
Beispiel #11
0
void loadResources(Resources *resources)
{
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    glEnable(GL_TEXTURE_2D);

    initAL(resources);

    std::string font_path;
    search_path("FreeMonoBold.ttf", font_path);
    font = new FTGLBitmapFont(font_path.c_str());
    Fontbig = new FTGLBitmapFont(font_path.c_str());

    if (font->Error()) {
        DEBUG_ERROR("error on font");
    }
    font->FaceSize(18);
    if (Fontbig->Error()) {
        DEBUG_ERROR("error on font");
    }
    Fontbig->FaceSize(110);

    restartButton = new Button(10, 10, 100, 50, Resources_Manager.texture("restart_button.tga"), restartMatch);
    newMazeButton = new Button(10, 10, 100, 50, Resources_Manager.texture("newmaze_button.tga"), newMatch);
    toggleCameraButton = new Button(10, 10, 100, 50, Resources_Manager.texture("togglecamera_button.tga"), toggleCameraMode);

    Widget_List.push_back(restartButton);
    Widget_List.push_back(newMazeButton);
    Widget_List.push_back(toggleCameraButton);

    skybox.setTexture(Resources_Manager.texture("checkerboard.tga"));
    skybox.build(Config_Info.matrixDimensions.x*Tilesize*20.0f);
}
Beispiel #12
0
//----------------------------------------------------------------------------
// Callback method called by GLUT when window readraw is necessary or when glutPostRedisplay() was called.
void Window::displayCallback()
{
    //Clear color and depth buffers
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    //Set the OpenGL matrix mode to ModelView
    glMatrixMode(GL_MODELVIEW);
    
    //Push a matrix save point
    //This will save a copy of the current matrix so that we can
    //make changes to it and 'pop' those changes off later.
    glPushMatrix();
    
    //Replace the current top of the matrix stack with the inverse camera matrix
    //This will convert all world coordiantes into camera coordiantes
    glLoadMatrixf(Globals::camera.getInverseMatrix().ptr());
    
    //Bind the light to slot 0.  We do this after the camera matrix is loaded so that
    //the light position will be treated as world coordiantes
    //(if we didn't the light would move with the camera, why is that?)
	//Globals::light.bind(0);
	Globals::point.bind(0);

	//Draw skybox
	if (!draw_sky)
	{
		// Draw skybox faces
		skybox.draw_ft(Globals::drawData);
		skybox.draw_bk(Globals::drawData);
		skybox.draw_lf(Globals::drawData);
		skybox.draw_rt(Globals::drawData);
		skybox.draw_up(Globals::drawData);
		skybox.draw_dn(Globals::drawData);
	}

	//Draw terrain / sun
	drawScene();

	//Calculate next position for sun. Travels on a parabolic path. Also determines sun color
	calculateSunPath();

    //Pop off the changes we made to the matrix stack this frame
    glPopMatrix();
    
    //Tell OpenGL to clear any outstanding commands in its command buffer
    //This will make sure that all of our commands are fully executed before
    //we swap buffers and show the user the freshly drawn frame
    glFlush();
    
    //Swap the off-screen buffer (the one we just drew to) with the on-screen buffer
    glutSwapBuffers();
}
static void setup (void)
{
	glClearColor( 0.8,0.8,0.8,1.0 );

	// Load textures
	init_texture("Textures\\cylinderWall.bmp",	CYLINDER_WALL, textures);
	init_texture("Textures\\cylinderCap.bmp",	CYLINDER_CAP, textures);
	init_texture("Textures\\Front.bmp",			BUILD_FRONT, textures);
	init_texture("Textures\\BuildRight.bmp",	BUILD_RIGHT, textures);
	init_texture("Textures\\Concrete.bmp",		CONCRETE, textures);
	init_texture("Textures\\Skybox.bmp",		SKYBOX, textures);

	// Cylinder building
	cylinder.initialize(CYLINDER_WALL, CYLINDER_CAP);
	step1.initialize(CONCRETE, CYLINDER_CAP);
	step2.initialize(CONCRETE, CYLINDER_CAP);

	// Rectangle buildings
	build_front.initialize(BUILD_FRONT, BUILD_FRONT);
	build_right.initialize(BUILD_RIGHT, CONCRETE);
	foundation.initialize(CONCRETE, CONCRETE);

	// Water
	water.build();

	// Sky
	sky.initialize(SKYBOX);

	// Directional light
	sun.init();

	// Spot light
	spLight.init();

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CCW);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}
Beispiel #14
0
void drawScene(void) {
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);

    glEnable(GL_LIGHTING);
    // set up the scene
    pool.render();
    basin.render();
    ground.render();
    // sky
    glDisable(GL_LIGHTING);
    skybox.render();

    // water in the air
    glDisable(GL_TEXTURE_2D);
    glColor4fv(WATER_COLOR);
    fountain.render();
    glEnable(GL_LIGHTING);

    glDisable(GL_BLEND);
}
Beispiel #15
0
void Water::CreateScene()
{
    ResourceCache* cache = GetContext()->m_ResourceCache.get();

    scene_ = new Scene(GetContext());

    // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
    scene_->CreateComponent<Octree>();

    // Create a Zone component for ambient lighting & fog control
    Node* zoneNode = scene_->CreateChild("Zone");
    Zone* zone = zoneNode->CreateComponent<Zone>();
    zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
    zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
    zone->SetFogColor(Color(1.0f, 1.0f, 1.0f));
    zone->SetFogStart(500.0f);
    zone->SetFogEnd(750.0f);

    // Create a directional light to the world. Enable cascaded shadows on it
    Node* lightNode = scene_->CreateChild("DirectionalLight");
    lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
    Light* light = lightNode->CreateComponent<Light>();
    light->SetLightType(LIGHT_DIRECTIONAL);
    light->SetCastShadows(true);
    light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
    light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
    light->SetSpecularIntensity(0.5f);
    // Apply slightly overbright lighting to match the skybox
    light->SetColor(Color(1.2f, 1.2f, 1.2f));

    // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
    // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
    // generate the necessary 3D texture coordinates for cube mapping
    Node* skyNode = scene_->CreateChild("Sky");
    skyNode->SetScale(500.0f); // The scale actually does not matter
    Skybox* skybox = skyNode->CreateComponent<Skybox>();
    skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
    skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));

    // Create heightmap terrain
    Node* terrainNode = scene_->CreateChild("Terrain");
    terrainNode->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
    Terrain* terrain = terrainNode->CreateComponent<Terrain>();
    terrain->SetPatchSize(64);
    terrain->SetSpacing(Vector3(2.0f, 0.5f, 2.0f)); // Spacing between vertices and vertical resolution of the height map
    terrain->SetSmoothing(true);
    terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png"));
    terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
    // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
    // terrain patches and other objects behind it
    terrain->SetOccluder(true);

    // Create 1000 boxes in the terrain. Always face outward along the terrain normal
    unsigned NUM_OBJECTS = 1000;
    for (unsigned i = 0; i < NUM_OBJECTS; ++i)
    {
        Node* objectNode = scene_->CreateChild("Box");
        Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
        position.y_ = terrain->GetHeight(position) + 2.25f;
        objectNode->SetPosition(position);
        // Create a rotation quaternion from up vector to terrain normal
        objectNode->SetRotation(Quaternion(Vector3(0.0f, 1.0f, 0.0f), terrain->GetNormal(position)));
        objectNode->SetScale(5.0f);
        StaticModel* object = objectNode->CreateComponent<StaticModel>();
        object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
        object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
        object->SetCastShadows(true);
    }
    Node* shipNode = scene_->CreateChild("Ship");
    shipNode->SetPosition(Vector3(0.0f, 4.6f, 0.0f));
    //shipNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
    shipNode->SetScale(0.5f + Random(2.0f));
    StaticModel* shipObject = shipNode->CreateComponent<StaticModel>();
    shipObject->SetModel(cache->GetResource<Model>("Models/ship04.mdl"));
    shipObject->SetMaterial(0,cache->GetResource<Material>("Materials/ship04_Material0.xml"));
    shipObject->SetMaterial(1,cache->GetResource<Material>("Materials/ship04_Material1.xml"));
    shipObject->SetMaterial(2,cache->GetResource<Material>("Materials/ship04_Material2.xml"));
    shipObject->SetCastShadows(true);

    // Create a water plane object that is as large as the terrain
    waterNode_ = scene_->CreateChild("Water");
    waterNode_->SetScale(Vector3(2048.0f, 1.0f, 2048.0f));
    waterNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
    StaticModel* water = waterNode_->CreateComponent<StaticModel>();
    water->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
    water->SetMaterial(cache->GetResource<Material>("Materials/Water.xml"));
    // Set a different viewmask on the water plane to be able to hide it from the reflection camera
    water->SetViewMask(0x80000000);

    // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
    // the scene, because we want it to be unaffected by scene load / save
    cameraNode_ = new Node(GetContext());
    Camera* camera = cameraNode_->CreateComponent<Camera>();
    camera->setFarClipDistance(750.0f);

    // Set an initial position for the camera scene node above the ground
    cameraNode_->SetPosition(Vector3(0.0f, 7.0f, -20.0f));
}
Beispiel #16
0
void Physics::CreateScene()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    scene_ = new Scene(context_);

    // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
    // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
    // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
    // Finally, create a DebugRenderer component so that we can draw physics debug geometry
    scene_->CreateComponent<Octree>();
    scene_->CreateComponent<PhysicsWorld>();
    scene_->CreateComponent<DebugRenderer>();

    // Create a Zone component for ambient lighting & fog control
    Node* zoneNode = scene_->CreateChild("Zone");
    Zone* zone = zoneNode->CreateComponent<Zone>();
    zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
    zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
    zone->SetFogColor(Color(1.0f, 1.0f, 1.0f));
    zone->SetFogStart(300.0f);
    zone->SetFogEnd(500.0f);

    // Create a directional light to the world. Enable cascaded shadows on it
    Node* lightNode = scene_->CreateChild("DirectionalLight");
    lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
    Light* light = lightNode->CreateComponent<Light>();
    light->SetLightType(LIGHT_DIRECTIONAL);
    light->SetCastShadows(true);
    light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
    // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
    light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));

    // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
    // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
    // generate the necessary 3D texture coordinates for cube mapping
    Node* skyNode = scene_->CreateChild("Sky");
    skyNode->SetScale(500.0f); // The scale actually does not matter
    Skybox* skybox = skyNode->CreateComponent<Skybox>();
    skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
    skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));

    {
        // Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y
        Node* floorNode = scene_->CreateChild("Floor");
        floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
        floorNode->SetScale(Vector3(1000.0f, 1.0f, 1000.0f));
        StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
        floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
        floorObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));

        // Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default
        // parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate
        // in the physics simulation
        /*RigidBody* body = */floorNode->CreateComponent<RigidBody>();
        CollisionShape* shape = floorNode->CreateComponent<CollisionShape>();
        // Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
        // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
        shape->SetBox(Vector3::ONE);
    }

    {
        // Create a pyramid of movable physics objects
        for (int y = 0; y < 8; ++y)
        {
            for (int x = -y; x <= y; ++x)
            {
                Node* boxNode = scene_->CreateChild("Box");
                boxNode->SetPosition(Vector3((float)x, -(float)y + 8.0f, 0.0f));
                StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
                boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
                boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneEnvMapSmall.xml"));
                boxObject->SetCastShadows(true);

                // Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable
                // and also adjust friction. The actual mass is not important; only the mass ratios between colliding
                // objects are significant
                RigidBody* body = boxNode->CreateComponent<RigidBody>();
                body->SetMass(1.0f);
                body->SetFriction(0.75f);
                CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
                shape->SetBox(Vector3::ONE);
            }
        }
    }

    // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside the scene, because
    // we want it to be unaffected by scene load / save
    cameraNode_ = new Node(context_);
    Camera* camera = cameraNode_->CreateComponent<Camera>();
    camera->SetFarClip(500.0f);

    // Set an initial position for the camera scene node above the floor
    cameraNode_->SetPosition(Vector3(0.0f, 5.0f, -20.0f));
}
Beispiel #17
0
int main(int argc, char ** argv[])
{

	Display display(800, 600, "TSBK07 Level of Detail on Terrain");
	Basic_Shader base_shader("./shaders/space");
	Phong_Shader phong("./shaders/phong");
	Texture texture("./textures/dirt.tga");
	Camera camera(glm::vec3(0, 1, 0), 70.0f, display.GetAspectRation(), 0.01f, 1000.0f);

	Terrain terr("./textures/terrain2.jpg", "./textures/terrain2.jpg");
	
	Skybox sky;
	sky.SkyboxInit("./textures/skybox/", "back.jpg", "front.jpg", "left.jpg", "right.jpg", "top.jpg", "bottom.jpg");
	Transform transform;
	Keyboard keyboard;
	Mouse mouse;

	float counter = 0.0f;
	Mesh monkey("./models/monkey3.obj");
	Mesh box("./models/box.obj");

	std::cout << "init complete" << std::endl;

	bool wireframe = true;
	bool lock = false;

	while (!display.IsClosed())
	{
		display.Clear(1, 0, 1, 1);

		SDL_Event e;

		while (SDL_PollEvent(&e))
		{
			if (e.type == SDL_QUIT)
			{
				display.HandleEvent(e);
			}
			if (e.type == SDL_MOUSEMOTION || e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP)
			{
				mouse.HandleEvent(e, camera);
			}
		}

		const Uint8* currentKeyStates = SDL_GetKeyboardState(NULL);

		keyboard.HandleEvent(currentKeyStates, camera);
		
		sky.Draw(transform, camera);

		if (currentKeyStates[SDL_SCANCODE_B])
		{
			lock = !lock;
		}
		if (currentKeyStates[SDL_SCANCODE_F])
		{
			wireframe = !wireframe;
		}
	
		terr.Draw(transform, camera, lock, wireframe);

		display.Update();

		counter += 0.001f;
	}
	return 0;
}
Beispiel #18
0
void init()
{
    new Logger;
	new Settings;
	ERR_CODE ret = settings.load(CONFIG);

    if (ret != NONE)
    {
		logger.logln(LOG_USER | LOG_FILE, "An error occurred while loading the default settings file (" + CONFIG + "): " + errString(ret));
		delete loggerPtr;
		delete settingsPtr;
		exit(0);
	}

    new TextureManager;
	new SkeletonManager;
	atexit(cleanUp);
    srand(time(0));
    //plant.parse();
	Skeleton *skel = new Skeleton;
	ret = skel->load("HumanSkel");

	if (ret != NONE)
	{
		delete skel;
		die("An error occurred while loading skeleton file: " + errString(ret));
	}

	ret = skel->add_animation("idle");

	if (ret != NONE)
	{
		delete skel;
		die("An error occurred while loading idle animation file: " + errString(ret));
	}

	skeletonManager.add_skeleton(skel);
#ifdef ANIMATION
	ret = animation.link_skeleton("HumanSkel");

	if (ret != NONE)
		die("An error occurred while linking skeleton to animation: " + errString(ret));

	ret = animation.animate("idle", true);

	if (ret != NONE)
	die("An error occurred in starting idle animation: " + errString(ret));
#else
	ret = mesh.load("human.mesh");

	if (ret != NONE)
		die("An error occurred while loading mesh file: " + errString(ret));

	ret = mesh.animate("idle", true);

	if (ret != NONE)
		die("An error occurred while animating mesh: " + errString(ret));
#endif

    cam.advance(-15.0);
    setPerspective();
    glViewport(0, 0, WIDTH, HEIGHT);
	glClearColor(0.0, 0.0, 0.0, 1.0);
	glFogi(GL_FOG_MODE, GL_LINEAR);
	glFogfv(GL_FOG_COLOR, fog_color);
	glFogf(GL_FOG_DENSITY, 0.25f);
	glHint(GL_FOG_HINT, GL_DONT_CARE);
	glFogf(GL_FOG_START, 1.0f);
	glFogf(GL_FOG_END, 5.0f);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glColor3f(1.0, 1.0, 1.0);
    Image front, back, right, left, up, down;
#define CHECK_RET_NAME(x, name) if ((ret = x.load(name ".tga")) != NONE) die("Error while loading " name ".tga: " + errString(ret));
#define CHECK_RET(x) CHECK_RET_NAME(x, #x)
    CHECK_RET(front);
    CHECK_RET(back);
    CHECK_RET(right);
    CHECK_RET(left);
    CHECK_RET(up);
    CHECK_RET(down);

    Image img_grass, img_snow;
    CHECK_RET_NAME(img_grass, "grass");
	CHECK_RET_NAME(img_snow, "snow");
    grass = textureManager.load(img_grass);
	snow_tex = textureManager.load(img_snow);
    box.init(front, left, back, right, up, down);
}
Beispiel #19
0
void Skybox::render(gpu::Batch& batch, const ViewFrustum& viewFrustum, const Skybox& skybox) {

    if (skybox.getCubemap() && skybox.getCubemap()->isDefined()) {
        static gpu::PipelinePointer thePipeline;
        static gpu::BufferPointer theBuffer;
        static gpu::Stream::FormatPointer theFormat;
        static gpu::BufferPointer theConstants;
        int SKYBOX_CONSTANTS_SLOT = 0; // need to be defined by the compilation of the shader
        if (!thePipeline) {
            auto skyVS = gpu::ShaderPointer(gpu::Shader::createVertex(std::string(Skybox_vert)));
            auto skyFS = gpu::ShaderPointer(gpu::Shader::createPixel(std::string(Skybox_frag)));
            auto skyShader = gpu::ShaderPointer(gpu::Shader::createProgram(skyVS, skyFS));

            gpu::Shader::BindingSet bindings;
            bindings.insert(gpu::Shader::Binding(std::string("cubeMap"), 0));
            if (!gpu::Shader::makeProgram(*skyShader, bindings)) {

            }

            SKYBOX_CONSTANTS_SLOT = skyShader->getBuffers().findLocation("skyboxBuffer");
            if (SKYBOX_CONSTANTS_SLOT == gpu::Shader::INVALID_LOCATION) {
                SKYBOX_CONSTANTS_SLOT = skyShader->getUniforms().findLocation("skyboxBuffer");
            }
            
            auto skyState = gpu::StatePointer(new gpu::State());

            thePipeline = gpu::PipelinePointer(gpu::Pipeline::create(skyShader, skyState));
        
            const float CLIP = 1.0;
            const glm::vec2 vertices[4] = { {-CLIP, -CLIP}, {CLIP, -CLIP}, {-CLIP, CLIP}, {CLIP, CLIP}};
            theBuffer.reset(new gpu::Buffer(sizeof(vertices), (const gpu::Byte*) vertices));
        
            theFormat.reset(new gpu::Stream::Format());
            theFormat->setAttribute(gpu::Stream::POSITION, gpu::Stream::POSITION, gpu::Element(gpu::VEC2, gpu::FLOAT, gpu::XYZ));
        
            auto color = glm::vec4(1.0f);
            theConstants.reset(new gpu::Buffer(sizeof(color), (const gpu::Byte*) &color));
        }

        glm::mat4 projMat;
        viewFrustum.evalProjectionMatrix(projMat);

        Transform viewTransform;
        viewFrustum.evalViewTransform(viewTransform);

        if (glm::all(glm::equal(skybox.getColor(), glm::vec3(0.0f)))) { 
            auto color = glm::vec4(1.0f);
            theConstants->setSubData(0, sizeof(color), (const gpu::Byte*) &color);
        } else {
            theConstants->setSubData(0, sizeof(Color), (const gpu::Byte*) &skybox.getColor());
        }

        batch.setProjectionTransform(projMat);
        batch.setViewTransform(viewTransform);
        batch.setModelTransform(Transform()); // only for Mac
        batch.setPipeline(thePipeline);
        batch.setInputBuffer(gpu::Stream::POSITION, theBuffer, 0, 8);
        batch.setUniformBuffer(SKYBOX_CONSTANTS_SLOT, theConstants, 0, theConstants->getSize());
        batch.setInputFormat(theFormat);
        batch.setUniformTexture(0, skybox.getCubemap());
        batch.draw(gpu::TRIANGLE_STRIP, 4);
    } else {
        // skybox has no cubemap, just clear the color buffer
        auto color = skybox.getColor();
        batch.clearFramebuffer(gpu::Framebuffer::BUFFER_COLOR0, glm::vec4(skybox.getColor(),1.0f), 0.f, 0); 
    }
}
void MasterControl::CreateScene()
{
  world_.scene = new Scene(context_);

  //Create octree, use default volume (-1000, -1000, -1000) to (1000,1000,1000)
  {
    world_.scene->CreateComponent<Octree>();
  }
  //Create the physics
  {
    PhysicsWorld * const physicsWorld = world_.scene->CreateComponent<PhysicsWorld>();
    physicsWorld->SetGravity(Vector3::ZERO);
  }

  world_.scene->CreateComponent<DebugRenderer>();

  //Create an invisible plane for mouse raycasting
  world_.voidNode = world_.scene->CreateChild("Void");
  //Location is set in update since the plane moves with the camera.
  world_.voidNode->SetScale(Vector3(1000.0f, 1.0f, 1000.0f));
  StaticModel* planeModel = world_.voidNode->CreateComponent<StaticModel>();
  planeModel->SetModel(cache_->GetResource<Model>("Models/Plane.mdl"));
  planeModel->SetMaterial(cache_->GetResource<Material>("Materials/Terrain.xml"));

  CreateBackground();

  {
    // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
    // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
    // generate the necessary 3D texture coordinates for cube mapping
    Node* skyNode = world_.scene->CreateChild("Sky");
    skyNode->SetScale(500.0f); // The scale actually does not matter
    Skybox* skybox = skyNode->CreateComponent<Skybox>();
    skybox->SetModel(cache_->GetResource<Model>("Models/Box.mdl"));
    skybox->SetMaterial(cache_->GetResource<Material>("Materials/Skybox.xml"));
  }

  //Create a directional light to the world. Enable cascaded shadows on it
  {
    Node* lightNode = world_.scene->CreateChild("DirectionalLight");
    lightNode->SetDirection(Vector3(0.0f, -1.0f, 0.0f));
    Light* light = lightNode->CreateComponent<Light>();
    light->SetLightType(LIGHT_DIRECTIONAL);
    light->SetBrightness(1.0f);
    light->SetColor(Color(1.0f, 0.8f, 0.7f));
    light->SetCastShadows(true);
    light->SetShadowBias(BiasParameters(0.00025f, 0.5f));

    //Set cascade splits at 10, 50, 200 world unitys, fade shadows at 80% of maximum shadow distance
    light->SetShadowCascade(CascadeParameters(7.0f, 23.0f, 42.0f, 500.0f, 0.8f));
  }

  //Create a second directional light without shadows
  {
    Node * const lightNode = world_.scene->CreateChild("DirectionalLight");
    lightNode->SetDirection(Vector3(0.0, 1.0, 0.0));
    Light * const light = lightNode->CreateComponent<Light>();
    light->SetLightType(LIGHT_DIRECTIONAL);
    light->SetBrightness(0.25);
    light->SetColor(Color(1.0, 1.0, 1.0));
    light->SetCastShadows(true);
    light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  }

  //Create camera
  world_.camera = new CameraMaster(context_, this);
}
int main(int argc, char **argv)
{
	//srand(time(0));
	Engine* engine = new Engine();
	engine->Init();

	engine->GetShader_Manager()->CreateProgram("baseShader",
		"Shaders\\Base_Vertex_Shader.glsl",
		"Shaders\\Base_Fragment_Shader.glsl");

	engine->GetShader_Manager()->CreateProgram("skyboxShader",
		"Shaders\\SkyboxVertexShader.glsl",
		"Shaders\\SkyboxFragmentShader.glsl");

	engine->GetShader_Manager()->CreateProgram("importedModelShader",
		"Shaders\\ImportedVertexShader.glsl",
		"Shaders\\ImportedFragmentShader.glsl");

	engine->GetShader_Manager()->CreateProgram("terrainShader",
		"Shaders\\TerrainVertexShader.glsl",
		"Shaders\\TerrainFragmentShader.glsl");

	engine->GetShader_Manager()->CreateProgram("bulletShader",
		"Shaders\\BulletVertexShader.glsl",
		"Shaders\\BulletFragmentShader.glsl");

	Skybox* skybox = new Skybox();
	skybox->SetProgram(engine->GetShader_Manager()->GetShader("skyboxShader"));
	skybox->Create(engine->GetScene_Manager());

	engine->GetModels_Manager()->SetModel("skybox", skybox);

	Terrain* terrain = new Terrain();
	terrain->SetProgram(engine->GetShader_Manager()->GetShader("terrainShader"));
	terrain->Create("maps\\map.bmp");

	engine->GetModels_Manager()->SetModel("map", terrain);

	for (int i = 0; i < 50; i++)
	{
		Tree1* tree = new Tree1();
		tree->SetProgram(engine->GetShader_Manager()->GetShader("importedModelShader"));
		int signX = rand() % 2 ? 1 : -1;
		int signZ = rand() % 2 ? 1 : -1;
		tree->Create("models\\Tree1\\tree.obj", ((((float)rand()) / (float)RAND_MAX) * (signX * 65 - signX * 3)) + signX * 3, ((((float)rand()) / (float)RAND_MAX) * (signZ * 65 - signZ * 3)) + signZ * 3);

		std::string tmp = "";
		sprintf((char*)tmp.c_str(), "tree_%d", i);
		engine->GetModels_Manager()->SetModel(tmp, tree);
	}

	for (int i = 0; i < 8; i++)
	{
		int XorZ = rand() % 2;
		int signX = rand() % 2 ? 1 : -1;
		int signZ = rand() % 2 ? 1 : -1;
		GLfloat Xoffset = ((((float)rand()) / (float)RAND_MAX) * (signX * 60 - signX * 3)) + signX * 3;
		GLfloat Zoffset = ((((float)rand()) / (float)RAND_MAX) * (signZ * 60 - signZ * 3)) + signZ * 3;
		for (int j = 0; j < 4; j++)
		{
			CubeIndex* box = new CubeIndex();
			box->SetProgram(engine->GetShader_Manager()->GetShader("importedModelShader"));
			XorZ == 0 ? box->Create(Xoffset + j*2, 0, Zoffset) : box->Create(Xoffset, 0, Zoffset + j*2);

			std::string tmp = "";
			sprintf((char*)tmp.c_str(), "bunch_%d_#box_%d", i, j);
			engine->GetModels_Manager()->SetModel(tmp, box);
		}
		for (int j = 0; j < 3; j++)
		{
			CubeIndex* box = new CubeIndex();
			box->SetProgram(engine->GetShader_Manager()->GetShader("importedModelShader"));
			XorZ == 0 ? box->Create(Xoffset + 1 + j * 2, 2, Zoffset) : box->Create(Xoffset, 2, Zoffset + 1 + j * 2);

			std::string tmp = "";
			sprintf((char*)tmp.c_str(), "bunch_%d_#box_%d", i, j+4);
			engine->GetModels_Manager()->SetModel(tmp, box);
		}
		for (int j = 0; j < 2; j++)
		{
			CubeIndex* box = new CubeIndex();
			box->SetProgram(engine->GetShader_Manager()->GetShader("importedModelShader"));
			XorZ == 0 ? box->Create(Xoffset + 2 + j * 2, 4, Zoffset) : box->Create(Xoffset, 4, Zoffset + 2 + j * 2);

			std::string tmp = "";
			sprintf((char*)tmp.c_str(), "bunch_%d_#box_%d", i, j + 7);
			engine->GetModels_Manager()->SetModel(tmp, box);
		}
		CubeIndex* box = new CubeIndex();
		box->SetProgram(engine->GetShader_Manager()->GetShader("importedModelShader"));
		XorZ == 0 ? box->Create(Xoffset + 3, 6, Zoffset) : box->Create(Xoffset, 6, Zoffset + 3);

		std::string tmp = "";
		sprintf((char*)tmp.c_str(), "bunch_%d_#box_9", i);
		engine->GetModels_Manager()->SetModel(tmp, box);
	}


	Tank* tank = new Tank();
	tank->SetProgram(engine->GetShader_Manager()->GetShader("importedModelShader"));
	tank->Create("models\\Tiger\\Tiger_I.obj");

	Bullets* bullets = new Bullets();
	bullets->SetProgram(engine->GetShader_Manager()->GetShader("bulletShader"));
	bullets->Create();

	engine->GetModels_Manager()->SetModel("bullets", bullets);


	engine->GetModels_Manager()->SetModel("tank", tank);

	engine->GetScene_Manager()->BindTank("tank");
	engine->GetScene_Manager()->BindBullets("bullets");

	engine->Run();

	delete engine;
	return 0;
}
Beispiel #22
0
void TestScene::initScene() {
	scene_State* currentState = &scene_states[SimState::currentUpdateState];

	extern std::string ROME_PATH;

	std::string location = ROME_PATH + "/Assets/Meshes/test_sphere_hires.msh";
	std::string cubeLocation = ROME_PATH + "/Assets/Meshes/test_cube.msh";
	std::string quadLocation = ROME_PATH + "/Assets/Meshes/test_quad.msh";

	std::string testTextureLocation = ROME_PATH + "/Assets/Textures/stone.png";
	std::string testNormalLocation = ROME_PATH + "/Assets/Textures/stone_normal.png";
	std::string transTextureLocation = ROME_PATH + "/Assets/Textures/stone_transparent.png";

	std::string skyboxLocation = ROME_PATH + "/Assets/Meshes/test_cube_skybox.msh";
	std::string skyboxTexLocation = ROME_PATH + "/Assets/Textures/skybox.png";
	std::string cubeMapLocation = ROME_PATH + "/Assets/Textures/debug";

	//make two offset objects
	MeshNode* childNode = new MeshNode(location, MaterialList::BLINNPHONG);
	childNode->setMaterialColor(1.0, 1.0, 1.0);
	childNode->setMaterialAlpha(0.4);
	childNode->setMaterialProperties(40.0, 0.2, 4.0);
	//childNode->setMaterialTexture(transTextureLocation);
	//childNode->setMaterialNormalMap(testNormalLocation);
	childNode->setTranslation(0, 0, 0);
	currentState->sceneRoot->addChild(childNode);

	////float randRot = rand() % 90;
	VitalEntity * secondChild = new VitalEntity(location, 1, 0, 0);
	secondChild->setTranslation(2, 2, 0);
	//secondChild->setRotation(20, randRot, 0);
	childNode->addChild(secondChild);

	//add a floor
	MeshNode* floor = new MeshNode(quadLocation, MaterialList::BLINNPHONG);
	floor->setMaterialColor(1.0, 1.0, 1.0, 1.0, 0.0, 0.0);
	floor->setMaterialProperties(40.0, 1.0, 1.0);
	floor->setMaterialTexture(testTextureLocation);
	floor->setMaterialNormalMap(testNormalLocation);
	floor->setScaling(5, 5, 1.0);
	floor->setTranslation(0, 0, -1.1);
	currentState->sceneRoot->addChild(floor);

	//make a ring of spheres
	for(double i = 0; i < 6; ++i) {
		MeshNode* newNode = new MeshNode(location, MaterialList::SOLIDTRANSPARENT);
		newNode->setMaterialColor(0.0, 1.0, 1.0);
		newNode->setMaterialAlpha(0.4);
		//newNode->setMaterialProperties(40.0, 1.0, 1.0);
		newNode->setMaterialTexture(transTextureLocation);
		//newNode->setMaterialNormalMap(testNormalLocation);
		newNode->setTranslation(3*sin(i*6.28/6), 3*cos(i*6.28/6), 0);
		currentState->sceneRoot->addChild(newNode);
	}

	Skybox* sky = new Skybox(this, skyboxLocation);
	sky->setMaterialColor(1.0, 1.0, 1.0, 0.0, 0.0, 0.0);
	sky->setMaterialTexture(skyboxTexLocation);
	sky->setScaling(100.0, 100.0, 100.0);
	setSkybox(sky);

	//add a light
	LightNode* light = new LightNode();
	light->setTranslation(16.0, 16.0, 6.0);
	currentState->sceneRoot->addChild(light);

	//cube mapping
	setCubeMap(cubeMapLocation);
};
Beispiel #23
0
int main(int argc, char **argv) {
    static_assert(std::is_pod<FVector3>::value, "FVector must be a POD!");
    static_assert(std::is_pod<Oscillator>::value, "Oscillator must be a POD!");

    // initialize GLUT
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    glutCreateWindow("Fountain");

    // textures
    std::unique_ptr<Texture> pebbleTexture(new Texture);
    std::unique_ptr<Texture> basinTexture(new Texture);
    std::unique_ptr<Texture> groundTexture(new Texture);
    std::unique_ptr<Texture[]> skyTextures(new Texture[SKY_BOX_FACES]);

    pebbleTexture->load("resource/pebbles.bmp");
    basinTexture->load("resource/wall.bmp");
    groundTexture->load("resource/grass.bmp");

    skyTextures[SKY_FRONT].load("resource/skybox/front.bmp", GL_CLAMP_TO_EDGE);
    skyTextures[SKY_RIGHT].load("resource/skybox/right.bmp", GL_CLAMP_TO_EDGE);
    skyTextures[SKY_LEFT].load("resource/skybox/left.bmp", GL_CLAMP_TO_EDGE);
    skyTextures[SKY_BACK].load("resource/skybox/back.bmp", GL_CLAMP_TO_EDGE);
    skyTextures[SKY_UP].load("resource/skybox/up.bmp", GL_CLAMP_TO_EDGE);
    skyTextures[SKY_DOWN].load("resource/skybox/down.bmp", GL_CLAMP_TO_EDGE);

    // initialize the scene
    skybox.initialize(-SKY_BOX_SIZE, SKY_BOX_SIZE,
                      -SKY_BOX_SIZE, SKY_BOX_SIZE,
                      -SKY_BOX_SIZE, SKY_BOX_SIZE, std::move(skyTextures));

    pool.initialize(OSCILLATORS_NUM_X, OSCILLATORS_NUM_Z, POOL_HEIGHT,
                    OSCILLATOR_DISTANCE, OSCILLATOR_WEIGHT,
                    OSCILLATOR_DAMPING, OSCILLATOR_SPLASH,
                    POOL_TEX_REPEAT_X, POOL_TEX_REPEAT_Z,
                    std::move(pebbleTexture));

    fountain.initialize(initializers[0]);

    basin.initialize(BASIN_BORDER_HEIGHT + POOL_HEIGHT, BASIN_BORDER_WIDTH,
                     BASIN_INNER_X, BASIN_INNER_Z, std::move(basinTexture));

    ground.initialize(-GROUND_SIZE, GROUND_SIZE,
                      -GROUND_SIZE, GROUND_SIZE,
                      std::move(groundTexture), GROUND_TEX_REPEAT);

    // place the fountain in the center of the pool
    fountain.center.set(BASIN_INNER_X / 2.0f, POOL_HEIGHT, BASIN_INNER_Z / 2.0f);

    // initialize camera:
    FVector3 cposition, crotation;
    cposition.set(CAMERA_POSITION[0], CAMERA_POSITION[1], CAMERA_POSITION[2]);
    camera.move(cposition);
    crotation.set(CAMERA_ROTATION[0], CAMERA_ROTATION[1], CAMERA_ROTATION[2]);
    camera.rotate(crotation);

    // enable vertex array
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);

    // solid rendering
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    glEnable(GL_DEPTH_TEST);

    // lighting
    glLightfv(GL_LIGHT1, GL_AMBIENT, LIGHT_AMBIENT_1);
    glLightfv(GL_LIGHT1, GL_DIFFUSE, LIGHT_DIFFUSE_1);
    glLightfv(GL_LIGHT1, GL_POSITION, LIGHT_POSITION_1);
    glEnable(GL_LIGHT1);

    glLightfv(GL_LIGHT2, GL_AMBIENT, LIGHT_AMBIENT_2);
    glLightfv(GL_LIGHT2, GL_DIFFUSE, LIGHT_DIFFUSE_2);
    glLightfv(GL_LIGHT2, GL_POSITION, LIGHT_POSITION_2);
    glEnable(GL_LIGHT2);

    glEnable(GL_LIGHTING);

    glEnable(GL_COLOR_MATERIAL);

    // settings
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glFrontFace(GL_CCW);   // orientation should be the front face
    glShadeModel(GL_SMOOTH);

    // blending
    glEnable(GL_BLEND);
    glEnable(GL_POINT_SMOOTH);
    glEnable(GL_POLYGON_SMOOTH);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // seed
    srand((unsigned)time(NULL));

    printf("1 - 8:\tChange the shape of the fountain\n");
    printf("f:\tToggle fullscreen\n");
    printf("c:\tSwitch between mouse mode / keyboard mode\n");

    printf("----------- Keyboard Mode -----------------\n");
    printf("up, down:\tMove camera forward / backword\n");
    printf("left, right:\tTurn camera right / left\n");
    printf("r, v:\tTurn camera up / down\n");
    printf("w, s:\tMove camera up / down\n");
    printf("a, d:\tMove camera left / right\n");

    printf("----------- Mouse Mode -----------------\n");
    printf("Mouse move:\tRotate camera\n");
    printf("Mouse scroll:\tMove forward / backward\n");

    printf("ESC:\tExit\n");

    // register callbacks
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutKeyboardFunc(keyDown);
    glutPassiveMotionFunc(mouseMove);
    glutSpecialFunc(spKeyDown);
    glutMouseFunc(mouseButton);
    glutIdleFunc(idle);

    // hide cursor
    glutSetCursor(GLUT_CURSOR_NONE);

    // start
    glutMainLoop();

    return 0;
}
int main() 
{
	// Init GLFW and GLEW
	glfwInit();
	CVK::useOpenGL33CoreProfile();
	window = glfwCreateWindow(width, height, "AnSim Exercise 3", 0, 0);
	glfwSetWindowPos(window, 100, 50);
	glfwMakeContextCurrent(window);
	glfwSetWindowSizeCallback(window, resizeCallback);
	glfwSetKeyCallback(window, keyCallback);
	glewInit();

	CVK::State::getInstance()->setBackgroundColor( white);
	glm::vec3 BgCol = CVK::State::getInstance()->getBackgroundColor();
	glClearColor( BgCol.r, BgCol.g, BgCol.b, 0.0);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);         
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);  

	//load, compile and link Shader
	const char *shadernames[2] = { SHADERS_PATH "/Toon.vert", SHADERS_PATH "/Toon.frag" };
	CVK::ShaderSpace spaceShader(VERTEX_SHADER_BIT | FRAGMENT_SHADER_BIT, shadernames);

    const char *skyboxShadernames[2] = {SHADERS_PATH "/Minimal.vert", SHADERS_PATH "/SimpleTexture.frag"};
    ShaderSkybox skyboxShader(VERTEX_SHADER_BIT | FRAGMENT_SHADER_BIT, skyboxShadernames);
    

	//Camera
	glm::vec3 center(0.0f, 0.0f, 0.0f);
	camera.setCenter(&center);
	camera.setRadius(6.0f);
	CVK::State::getInstance()->setCamera( &camera);

	//Light Sources
	CVK::Light light = CVK::Light(glm::vec4(0.0, 10.0, 0.0, 1.0), grey, glm::vec3(0, 0, 0), 1.0f, 0.0f);
	CVK::State::getInstance()->addLight(&light);
	CVK::State::getInstance()->updateSceneSettings(darkgrey, 0, white, 1, 10, 1);

	// Create skybox
    Skybox* skybox = new Skybox(15.0f);

	//Init scene nodes and mass points
	CVK::Node spaceship("Spaceship", RESOURCES_PATH "/spaceship.obj");
	CVK::Node fish("Fish", RESOURCES_PATH "/fish.obj");
	CVK::Node pig("Pig", RESOURCES_PATH "/piggy.obj");
	//First mass point for the spaceship
	spaceShipMassPoint = CVK::MassPoint(glm::vec3(0.0f, 2.3f, 0.0f),  glm::vec3(0.0f, 0.0f, 0.0f), 1.0); 
	//Next ones for the pigs
	pigsMassPoints.push_back(CVK::MassPoint(glm::vec3(-2.0f, 2.3f, 2.0f),  glm::vec3(-0.3f, 0.0f, -0.23f), 1.0));
	pigsMassPoints.push_back(CVK::MassPoint(glm::vec3(2.0f, 2.3f, -2.0f), glm::vec3(0.0f, 0.0f, 0.4f), 2.0));
	pigsMassPoints.push_back(CVK::MassPoint(glm::vec3(4.0f, 2.3f, 3.0f),  glm::vec3(-0.23f, 0.0f, -0.1f), 3.0));
	pigsMassPoints.push_back(CVK::MassPoint(glm::vec3(-5.0f, 0.0f, 6.0f),  glm::vec3(-0.3f, 0.0f, -0.4f), 1.0));
	pigsMassPoints.push_back(CVK::MassPoint(glm::vec3(5.0f, 2.3f, -3.0f), glm::vec3(0.2f, 0.0f, 0.2f), 2.0));
	pigsMassPoints.push_back(CVK::MassPoint(glm::vec3(4.0f, 4.3f, 2.5f),  glm::vec3(-0.4f, 0.0f, -0.2f), 3.0));

	// TODO 4 (b)
	// Fuellen Sie den global definierten Vektor (quaternions) mit den gewünschten Orientierungen.

	float deltaTime = 0.0f;
	float oldTime = glfwGetTime();
	float t = 0.0f;

	while(!glfwWindowShouldClose( window))
	{	
		float currentTime = glfwGetTime();
		deltaTime = currentTime - oldTime;
		oldTime = currentTime;

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
		//Update Camera
		camera.update(window);
		glm::vec3 spaceShipPos=spaceShipMassPoint.getPosition();
		camera.setCenter(&spaceShipPos);

		//Use the skybox shader program
        CVK::State::getInstance()->setShader(&skyboxShader);
        CVK::State::getInstance()->getShader()->update();
        skybox->render();

		//Use phong shader to render the scene
		CVK::State::getInstance()->setShader(&spaceShader);
		CVK::State::getInstance()->setLight(0, &light);
		spaceShader.update();

		//Update and render spaceship
		spaceShipMassPoint.numericIntegration(deltaTime);
		glm::mat4 modelmatrix = glm::rotate(glm::mat4(1.0f), spaceShipRotAngle, glm::vec3(0.0f,1.0f,0.0f));
		modelmatrix = glm::translate(modelmatrix, spaceShipMassPoint.getPosition());
		modelmatrix = glm::scale(modelmatrix, glm::vec3(1.5,1.5,1.5));
		spaceship.setModelMatrix(modelmatrix);
		spaceship.render();

		//Update and render pigs
		for(CVK::MassPoint& mp : pigsMassPoints)
		{
			mp.numericIntegration(deltaTime);
			modelmatrix = glm::translate(glm::mat4(1.0f), mp.getPosition());
			modelmatrix = glm::scale(modelmatrix, glm::vec3(0.5,0.5,0.5));
			pig.setModelMatrix(modelmatrix);
			pig.render();
		}
		
		t += deltaTime * 0.01f; //speed = 0.01
		if(t >= 1.0)
			t = 0.0f;

		// TODO 4 (b) 
		// Erweitern Sie die Modelmatrix um Translation und Rotation.
		// Anmerkung: Verwenden Sie die Variable t.
		modelmatrix = glm::scale(glm::mat4(1.0f), glm::vec3(0.1f, 0.1f, 0.1f));
		fish.setModelMatrix(modelmatrix);
		fish.render();

		glfwSwapBuffers( window);
		glfwPollEvents();
	}

	glfwDestroyWindow( window);
	glfwTerminate();


	return 0;
}
Beispiel #25
0
int main(int argc, char** argv) {
    Engine* engine = new Engine();
    if(!engine->init()) {
        std::cout << "Engine initialization failed\n";
        return 1;
    }

    engine->getShaderManager()->createProgram("mainShader", "Shaders/VertexShader.glsl", "Shaders/FragmentShader.glsl");
    GLuint program = engine->getShaderManager()->getProgram("mainShader");
    if(program == 0) {
        std::cout << "Program initialization failed\n";
        return 2;
    }
    engine->getSceneManager()->setProgram(program);

    Skybox* skybox = new Skybox();
    skybox->create(40.0f);
    skybox->setRotation(glm::vec3(0.0f, 180.0f, 0.0f));
    skybox->addMaterial(0, "Resources/Copyrighted/skybox1.png", 1.0f, 0.0f, 0.0f, 0.0f, engine->getTextureLoader());
    engine->getModelManager()->setModel("skybox", skybox);

    Cuboid* floorBox = new Cuboid();
    floorBox->create(40.0f, 1.0f, 40.0f, glm::vec4(0.24f, 0.267f, 0.337f, 1.0f));
    floorBox->setPosition(glm::vec3(0.0f, -8.0f, 0.0f));
    engine->getModelManager()->setModel("floorBox", floorBox);

    glm::vec3 sunPosition(-8.7f, 20.0f, 11.1f);
    engine->getSceneManager()->addLight(0, sunPosition, glm::vec3(1.0), 1.0f, 0.0, 0.0);
    Sphere* sun = new Sphere();
    sun->create(1.2f, 16, 16, glm::vec4(1.0f, 1.0f, 0.9f, 1.0f));
    sun->setBaseMaterial(1.0f, 0.0f, 0.0f, 0.0f);
    sun->setPosition(sunPosition);
    engine->getModelManager()->setModel("sun", sun);

    glm::vec3 lampPosition(8.0f, -1.0f, 5.0f);
    engine->getSceneManager()->addLight(1, lampPosition, glm::vec3(4.0f, 1.0f, 1.0f), 1.0f, 0.003f, 0.0005f);
    Sphere* lamp = new Sphere();
    lamp->create(0.3f, 16, 16, glm::vec4(1.0f, 0.2f, 0.2f, 1.0f));
    lamp->setBaseMaterial(1.0f, 0.0f, 0.0f, 0.0f);
    lamp->setPosition(lampPosition);
    engine->getModelManager()->setModel("lamp", lamp);

    Eel* eel = new Eel();
    eel->create(10.0f, 0.5f, 16);
    eel->setPosition(glm::vec3(0.0f, 0.0f, 0.0f));
    eel->addMaterial(0, "Resources/Copyrighted/scales1_2.png", 0.05f, 0.6f, 3.5f, 12.0f, engine->getTextureLoader());
    eel->addMaterial(1, "Resources/Textures/sphere_dots.png", 0.25f, 0.4f, 0.7f, 1.0f, engine->getTextureLoader());
    eel->addNormalMap("Resources/Copyrighted/scales1-normal3.png", engine->getTextureLoader());
    engine->getModelManager()->setModel("eel", eel);

    Sphere* sphere = new Sphere();
    sphere->create(1.0f, 24, 48);
    sphere->setPosition(glm::vec3(0.0f, -2.0f, 14.0f));
    sphere->setRotation(glm::vec3(30.0f, 0.0f, 0.0f));
    sphere->setRotationSpeed(glm::vec3(0.0f, 20.0f, 0.0f));
    sphere->addMaterial(0, "Resources/Textures/sphere1.bmp", 0.02f, 0.3f, 2.5f, 15.0f, engine->getTextureLoader());
    sphere->addMaterial(1, "Resources/Textures/sphere_dots.png", 0.02f, 0.8f, 1.0f, 1.0f, engine->getTextureLoader());
    sphere->addNormalMap("Resources/Copyrighted/fish-normal.bmp", engine->getTextureLoader());
    engine->getModelManager()->setModel("sphere", sphere);

    engine->run();

    delete engine;
    return 0;
}
Beispiel #26
0
//------------------------------------------------------------------------------
// The main method
//------------------------------------------------------------------------------
int main(int argc, char **argv) {
	osgInit(argc, argv);                 // initialize OpenSG
	int winid = setupGLUT(&argc, argv);  // initialize GLUT

	// the connection between GLUT and OpenSG is established
	GLUTWindowPtr gwin = GLUTWindow::create();
	gwin->setId(winid);
	gwin->init();

//----------------------------------------------------------------------------//
// Snippet-1-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// very first step: load the configuration of the file structures, basically
	// paths are set. The Configuration always has to be loaded first since each
	// module uses the paths set in the configuration-file
	if (!Configuration::loadConfig("config/general.xml")) {
		printf("Error: could not load config-file!\n");
		return -1;
	}
//----------------------------------------------------------------------------//
// Snippet-1-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-4 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// register callbacks
	InputInterface::registerModuleInitCallback(initInputInterface);
	SystemCore::registerModuleInitCallback(initModules);
//----------------------------------------------------------------------------//
// Snippet-2-4 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-3-3 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	SystemCore::registerCoreComponentInitCallback(initCoreComponents);
//----------------------------------------------------------------------------//
// Snippet-3-3 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-1-2 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	std::string systemCoreConfigFile = Configuration::getString(
			"SystemCore.systemCoreConfiguration");
	std::string outputInterfaceConfigFile = Configuration::getString(
			"Interfaces.outputInterfaceConfiguration");

//	// !!!!!! Remove in tutorial part 2, Snippet-2-1 - BEGIN
//	if (!SystemCore::configure(systemCoreConfigFile, outputInterfaceConfigFile)) {
//		printf("Error: failed to setup SystemCore!\n");
//		return -1;
//	}
//	// !!!!!! Remove - END
//----------------------------------------------------------------------------//
// Snippet-1-2 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// !!!!!! Remove part of Snippet-1-2 (right above)
	// in addition to the SystemCore config file, modules and interfaces config
	// files have to be loaded.
	std::string modulesConfigFile = Configuration::getString(
				"Modules.modulesConfiguration");
	std::string inputInterfaceConfigFile = Configuration::getString(
			"Interfaces.inputInterfaceConfiguration");

	if (!SystemCore::configure(systemCoreConfigFile, outputInterfaceConfigFile, inputInterfaceConfigFile,
			modulesConfigFile)) {
		printf("Error: failed to setup SystemCore!\n");
		printf("Please check if the Plugins-path is correctly set to the inVRs-lib directory in the ");
		printf("'final/config/general.xml' config file, e.g.:\n");
		printf("<path name=\"Plugins\" path=\"/home/guest/inVRs/lib\"/>\n");
		return -1;
	}
//----------------------------------------------------------------------------//
// Snippet-2-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-3-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// generate or load and configure height maps of the used tiles
	HeightMapManager::generateTileHeightMaps();
//----------------------------------------------------------------------------//
// Snippet-3-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-15 - BEGIN                                                       //
//----------------------------------------------------------------------------//
	// generate and configure the SkyBox
	std::string skyPath = Configuration::getPath("Skybox");
	skybox.init(5,5,5, 1000, (skyPath+"lostatseaday/lostatseaday_dn.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_up.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_ft.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_bk.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_rt.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_lf.jpg").c_str());
//----------------------------------------------------------------------------//
// Snippet-2-15 - END                                                         //
//----------------------------------------------------------------------------//

	NodePtr root = Node::create();
	beginEditCP(root);
		root->setCore(Group::create());

//----------------------------------------------------------------------------//
// Snippet-1-3 - BEGIN                                                        //
//----------------------------------------------------------------------------//
		OpenSGSceneGraphInterface* sgIF =
			dynamic_cast<OpenSGSceneGraphInterface*>(OutputInterface::getSceneGraphInterface());
		if (!sgIF) {
			printf("Error: Failed to get OpenSGSceneGraphInterface!\n");
			printf("Please check if the OutputInterface configuration is correct!\n");
			return -1;
		}
		// retrieve root node of the SceneGraphInterface (method is OpenSG specific)
		NodePtr scene = sgIF->getNodePtr();

		root->addChild(scene);
//----------------------------------------------------------------------------//
// Snippet-1-3 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-16 - BEGIN                                                       //
//----------------------------------------------------------------------------//
		// add the SkyBox to the scene
		root->addChild(skybox.getNodePtr());
//----------------------------------------------------------------------------//
// Snippet-2-16 - END                                                         //
//----------------------------------------------------------------------------//

	endEditCP(root);

//----------------------------------------------------------------------------//
// Snippet-2-5 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// fetch users camera, it is used to tell the Navigator where we are
	localUser = UserDatabase::getLocalUser();
	if (!localUser) {
		printd(ERROR, "Error: Could not find localUser!\n");
		return -1;
	}

	camera = localUser->getCamera();
	if (!camera) {
		printd(ERROR, "Error: Could not find camera!\n");
		return -1;
	}

	avatar = localUser->getAvatar();
	if (!avatar) {
		printd(ERROR, "Error: Could not find avatar!\n");
		return -1;
	}
	avatar->showAvatar(false);

  // set our transformation to the start transformation
	TransformationData startTrans =
		WorldDatabase::getEnvironmentWithId(1)->getStartTransformation(0);
	localUser->setNavigatedTransformation(startTrans);
//----------------------------------------------------------------------------//
// Snippet-2-5 - END                                                          //
//----------------------------------------------------------------------------//

	mgr = new SimpleSceneManager;  // create the SimpleSceneManager
	mgr->setWindow(gwin);          // tell the manager what to manage
	mgr->setRoot(root);            // attach the scenegraph to the  root node
	mgr->showAll();                // show the whole scene
	mgr->getCamera()->setNear(0.1);

//----------------------------------------------------------------------------//
// Snippet-2-6 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// Navigator is part of SimpleSceneManager and not of the inVRs framework
	Navigator *nav = mgr->getNavigator();
	nav->setMode(Navigator::NONE);     // turn off the navigator
	lastTimeStamp = timer.getTime();   // initialize timestamp;
	camMatrix = gmtl::MAT_IDENTITY44F; // initial setting of the camera matrix
//----------------------------------------------------------------------------//
// Snippet-2-6 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-5-2                                                                //
//----------------------------------------------------------------------------//

	glutMainLoop(); // GLUT main loop
	return 0;
}
Beispiel #27
0
//Render thread that controls all the rendering in OpenGL.
int render(void *data)
{
    //Create window with set resolution 1200x800 using a software surface on the SDL side and obtain Context using SDL_OPENGL.
    SDL_SetVideoMode(1200,800,32,SDL_SWSURFACE|SDL_OPENGL);
    SDL_WM_SetCaption("3D Desert Racer", NULL);
    std::cout << "Video Initiated." << std::endl;
    const char* vendor = (const char*)glGetString( GL_VENDOR );
    const char* renderer = (const char*)glGetString( GL_RENDERER );
    const char* version = (const char*)glGetString( GL_VERSION );
    //General info about the users Video card and current installed openGL.
    std::cout << "OPENGL Version:  " << version << std::endl;
    std::cout << "OPENGL Renderer:  " << renderer << std::endl;
    std::cout << "OPENGL Vendor:  " << vendor << std::endl;

    glClearColor(0.0,0.0,0.0,1.0);
    glShadeModel(GL_SMOOTH);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //Sets Perspectivefor the camera.
    gluPerspective(45,1200.0/800.0,1.0,3000.0);
    //Enable all the required GL drawing parameters.
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_BLEND);
    //Sets lighting properties.
    float dif[] = {1.0,1.0,1.0,1.0};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, dif);
    float amb[] = {0.2,0.2,0.2,1.0};
    glLightfv(GL_LIGHT0, GL_AMBIENT, amb);

    //Load car Objects and Textures.
    level.loadGround();
    objWheel = objloader::load("Texture/Wheel2.obj");
    objCar = objloader::load("Texture/Chassis.obj");

    list1 = level.BuildList();
    //sets the matrixmode to ModelView matrix.
    glMatrixMode(GL_MODELVIEW);

    std::cout << "Video Initiated." << std::endl;
    init_video=true;

    //Main render thread loop.
    while(isRunning)
    {
        //Lock Mutex
        SDL_LockMutex(console_mutex);
        //std::cout << "Render thread started." << std::endl;
        fps.start();
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        float pos[] = {200.0,300.0,200.0,1.0};

        //Resets Matrix to all 0's.
        glLoadIdentity();
        //Does all the translations and rotates for the drawings.
        car.UpdateCamera();
        //Draws the skybox.
        sky.draw();
        glPushMatrix();
            car.UpdateCar();
            glLightfv(GL_LIGHT0, GL_POSITION, pos);
            //Render call to the list that contains the terrain heightmap.
            glCallList(list1);
        glPopMatrix();
        car.rotCar();
        //Draw the chassis of the car with translations/rotations.
        glPushMatrix();
            glTranslatef(0.2,car.carY+2,0.0);
            glRotatef(car.carPitch,1.0,0.0,0.0);
            glRotatef(car.carRoll,0.0,0.0,1.0);

            glRotatef(77,0.0,1.0,0.0);
            glRotatef(25,1.0,0.0,0.0);
            glScalef(0.6,0.6,0.6);
            glCallList(objCar);
        glPopMatrix();
        //Draw and translate/rotate the wheels.
        glPushMatrix();
        glTranslatef(1.5,w1+1,-1.8);
        glRotatef(90,0.0,1.0,0.0);
        glRotatef(car.carRoll,0.0,0.0,1.0);
        glScalef(0.6,0.6,0.6);
        glCallList(objWheel);
        glPopMatrix();
        glPushMatrix();
        glTranslatef(-1.5,w2+1,1.5);
        glRotatef(90,0.0,1.0,0.0);
        glRotatef(car.carRoll,0.0,0.0,1.0);
        glScalef(0.6,0.6,0.6);
        glCallList(objWheel);
        glPopMatrix();
        glPushMatrix();
        glTranslatef(1.5,w3+1,1.5);
        glRotatef(90,0.0,1.0,0.0);
        glRotatef(car.carRoll,0.0,0.0,1.0);
        glScalef(0.6,0.6,0.6);
        glCallList(objWheel);
        glPopMatrix();
        glPushMatrix();
        glTranslatef(-1.5,w4+1,-1.8);
        glRotatef(90,0.0,1.0,0.0);
        glRotatef(car.carRoll,0.0,0.0,1.0);
        glScalef(0.6,0.6,0.6);
        glCallList(objWheel);
        glPopMatrix();

        //This bit gets the Position 1.5,1.8 and -1.5,1.5 after rotations for the exact x,z positions of the wheels.
        //matrix1 will contain the new (x,y,z) at rotation/translation in (matrix1[12],matrix1[13],matrix[14]);
        glPushMatrix();
            glLoadIdentity();
            car.rotCar();
            glTranslatef(1.5,0.0,1.8);
            glGetFloatv (GL_MODELVIEW_MATRIX, matrix1);
            glLoadIdentity();
            car.rotCar();
            glTranslatef(-1.5,0.0,1.5);
            glGetFloatv (GL_MODELVIEW_MATRIX, matrix2);
        glPopMatrix();
        //Swaps the drawing buffers.
        SDL_GL_SwapBuffers();
        //Counts the rendering frames for the fps count in the logic thread.
        frame2++;
        //Unlocks the mutex.
        SDL_UnlockMutex(console_mutex);
        //std::cout << "Render thread end loop." << std::endl;
        //Sets a delay so each run of the loops lasts 1/60 of a second, makes the max fps of the thread to be 60 per second.
        if( ( cap == true ) && ( fps.get_ticks() < 1000 / FRAMES_PER_SECOND ) )
        { //Sleep the remaining frame time
            SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
        }

    }
    return(0);
}
Beispiel #28
0
int main(int argc, char* args[])
{
    init_SDL();
    //Starts the menu screen, i==1 is Quit, else turn on the game.
    int i = objloader::showmenu(screen, font);
    if(i==1)
    {
        isRunning=false;
        SDL_Quit();
    }else
    {
        screen = NULL;
        isRunning=true;
    }
    //lets isRunning to true;
    update.start();
    //Creates the threads .
    thread1 = SDL_CreateThread(render, NULL);
    thread2 = SDL_CreateThread(logic, NULL);
    //Create a new Event call object.
    SDL_Event event;
    while(isRunning)
    {
        //Set certain keys to have events attached to them.
        if(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)
            {
                isRunning = false;
            }
            if(event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE)
            {
                isRunning = false;
            }
            if(event.type == SDL_KEYDOWN)
            {
                if(event.key.keysym.sym == SDLK_RETURN)
                {
                    cap = ( !cap );
                }
                else if(event.key.keysym.sym == SDLK_e)
                {
                    //Scrolls throught the skybox
                    sky.currentSkybox++;
                    if(sky.currentSkybox > 4)
                    {
                        sky.currentSkybox = 0;
                    }
                }
                if(event.key.keysym.sym == SDLK_w)
                {
                    car.up=true;
                }else if(event.key.keysym.sym == SDLK_s)
                {
                    car.down=true;
                }
                if(event.key.keysym.sym == SDLK_a)
                {
                    car.left=true;
                }else if(event.key.keysym.sym == SDLK_d)
                {
                    car.right=true;
                }
            }
            if(event.type == SDL_KEYUP)
            {
                if(event.key.keysym.sym == SDLK_w)
                {
                    car.up=false;
                }else if(event.key.keysym.sym == SDLK_s)
                {
                    car.down=false;
                }
                if(event.key.keysym.sym == SDLK_a)
                {
                    car.left=false;
                }else if(event.key.keysym.sym == SDLK_d)
                {
                    car.right=false;
                }
            }
        }

        SDL_Delay(1000/60);
    }
    //Waits til the threads site
    SDL_WaitThread(thread1, NULL);
    SDL_WaitThread(thread2, NULL);
    //Cleanup handler.
    glDeleteLists(list1, 1);
    glDeleteLists(objCar, 1);
    glDeleteLists(objWheel, 1);
    TTF_CloseFont(font);
    TTF_Quit();
    sky.killSkybox();
    //Exits SDL
    SDL_Quit();

    return(0);
}
Beispiel #29
0
// SDL wants main() to have this exact signature
extern "C" int main(int argc, char* argv[])
{
    // Initialize SDL
    if (SDL_Init(SDL_INIT_VIDEO))
    {
        fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
        return 1;
    }

    // Plain 32-bit RGBA8 pixel format
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

    // Don't need built-in depth buffer, we use our own.
    //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);

    // Select OpenGL version
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

#ifdef _DEBUG
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif

    // Create the window
	SDL_Window* window = SDL_CreateWindow("OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL);
    if (!window)
    {
        fprintf(stderr, "SDL_CreateWindow: %s\n", SDL_GetError());
        return 1;
    }

    // Create the OpenGL context
    SDL_GLContext context = SDL_GL_CreateContext(window);
    if (!context)
    {
        fprintf(stderr, "SDL_GL_CreateContext: %s\n", SDL_GetError());
        return 1;
    }

    // Initialize OpenGL (must be called before calling any OpenGL functions)
    OpenGL_Init();	

	// DEBUG: print OpenGL version
	const GLubyte* version = glGetString(GL_VERSION);
	fprintf(stdout, "OpenGL Version: %s\n", version);	

	//======================== VAO ===============================
	// Hook up the vertex and index buffers to a "vertex array object" (VAO)
	// VAOs are the closest thing OpenGL has to a "mesh" object.
	// VAOs are used to feed data from buffers to thgle inputs of a vertex shader.
	//============================================================	

	//===================== VBO/EBO ===============================
	Skybox skyBox = Skybox();
	skyBox.load();

	TerrainMesh terrainMesh = TerrainMesh(64, 64, 0.0);
	terrainMesh.load();

	
	//============================================================

	//===================== TEXTURES =============================
	
	//============================================================

	//======================= SHADERS ============================
	// init terrain shader
	ShaderSet terrainShaderSet;
	terrainShaderSet.SetVersion("330");

	// set uniforms (use preambles here or define them in the shader file, but NOT both)
	terrainShaderSet.SetPreamble(
		"uniform mat4 iModelViewProjection;\n"
		"uniform mat4 iModel;\n"
		"uniform mat4 iView;\n"
		"uniform vec3 iLightPosition_worldspace;\n"
		"uniform sampler2DArray iTextureArray;\n"
	);
	GLuint* terrainShaderId = terrainShaderSet.AddProgramFromExts({ "a3.vert", "a3.frag" });


	// init skybox shader
	ShaderSet skyboxShaderSet;
	skyboxShaderSet.SetVersion("330");

	// set uniforms (use preambles here or define them in the shader file, but NOT both)
	skyboxShaderSet.SetPreamble(
		"uniform mat4 iProjection;\n"
		"uniform mat4 iView;\n"
		"uniform samplerCube iSkyBoxCubeTexture;\n"
	);
	GLuint* skyboxShaderId = skyboxShaderSet.AddProgramFromExts({ "skybox.vert", "skybox.frag" });
	//============================================================

	//======================== LIGHTS ============================
	glm::vec3 light = glm::vec3(4, 40, 4);
	//============================================================

	//================== BEZIER CURVES ===========================
	glm::vec3 xzLength = glm::vec3(32.0, 0.0, 32.0);
	glm::vec3 yPull = glm::vec3(0.0, 20.0, 0.0);
	glm::vec3 xPull = glm::vec3(20.0, 0.0, 0.0);

	CubicBezierCurve bezierCurve1 = CubicBezierCurve(light, xzLength, yPull, yPull);
	CubicBezierCurve bezierCurve2 = CubicBezierCurve(bezierCurve1.p3, xzLength, -yPull, -yPull);
	CubicBezierCurve bezierCurve3 = CubicBezierCurve(bezierCurve2.p3, -xzLength, xPull, xPull);
	CubicBezierCurve bezierCurve4 = CubicBezierCurve(bezierCurve3.p3, -xzLength, -xPull, -xPull);
	
	BezierPath bezierPath = BezierPath(std::vector<CubicBezierCurve>{ bezierCurve1, bezierCurve2, bezierCurve3, bezierCurve4 });
	//============================================================
	
    // Begin main loop
	double lastTime = 0;
	InputHandler inputHandler = InputHandler(window);
	Camera camera = Camera(4, 40, 4);
	float bezierTime = 0.0;
	const float bezierSpeed = 0.001;
    while (1)
    {			
		//================= UPDATE USER INPUT ========================
		double currentTime = SDL_GetTicks() / 1000.0;		
		float deltaTime = float(currentTime - lastTime);
		
		if (inputHandler.updateInput(deltaTime) == -1)
		{
			goto quit;
		}
		camera.update(inputHandler.getInputData(), deltaTime);

		lastTime = currentTime;
		//============================================================

		//================= COMPUTE MATRICES =========================
		// move camera position along bezier curve		
		glm::vec3 bezPos = bezierPath.getPointAt(bezierTime);
		bezierTime += bezierSpeed;
		bezierTime = (bezierTime > 1.0) ? 0.0 : bezierTime;
		camera.position = bezPos;

		// Projection matrix
		glm::mat4 Projection = glm::perspective(
			camera.FoV,
			camera.aspectRatio,
			camera.nearClip,
			camera.farClip
		);

		// Or, for an ortho camera :
		//glm::mat4 Projection = glm::ortho(-10.0f,10.0f,-10.0f,10.0f,0.0f,100.0f); // In world coordinates

		// Camera matrix
		glm::mat4 View = glm::lookAt(
			camera.position,
			camera.position + camera.direction,
			camera.up
		);

		// Model matrix : an identity matrix (model will be at the origin)
		glm::mat4 Model = glm::mat4(1.0f);
		// Our ModelViewProjection : multiplication of our 3 matrices
		glm::mat4 ModelViewProjection = Projection * View * Model; // Remember, matrix multiplication is the other way around
		//glm::mat4 ModelViewProjection = MVP;
		//============================================================		

		//================== UPDATE SHADERS ==========================
		// Set the color to clear with
		//glClearColor(100.0f / 255.0f, 149.0f / 255.0f, 237.0f / 255.0f, 1.0f);
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

		// Clear the screen
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		//===================== Z-BUFFER =============================
		// Enable depth test
		glEnable(GL_DEPTH_TEST);
		// Accept fragment if it closer to the camera than the former one
		glDepthFunc(GL_LESS);


		// TERRAIN ======================================================
		// Recompile/relink any programs that changed (must be called)
		terrainShaderSet.UpdatePrograms();

		// set OpenGL's shader program (must be called in loop)
		glUseProgram(*terrainShaderId);

		// get uniform handles
		GLuint iModelViewProjectionLoc = glGetUniformLocation(*terrainShaderId, "iModelViewProjection");
		GLuint iModelLoc = glGetUniformLocation(*terrainShaderId, "iModel");
		GLuint iViewLoc = glGetUniformLocation(*terrainShaderId, "iView");
		GLuint iLightPosition_worldspaceLoc = glGetUniformLocation(*terrainShaderId, "iLightPosition_worldspace");

		// send matrix uniforms to shader
		if (iModelViewProjectionLoc != -1)
		{
			glUniformMatrix4fv(iModelViewProjectionLoc, 1, GL_FALSE, &ModelViewProjection[0][0]);
		}

		if (iModelLoc != -1)
		{
			glUniformMatrix4fv(iModelLoc, 1, GL_FALSE, &Model[0][0]);
		}
		if (iViewLoc != -1)
		{
			glUniformMatrix4fv(iViewLoc, 1, GL_FALSE, &View[0][0]);
		}						

		// pass light position uniform to shader
		if (iLightPosition_worldspaceLoc != -1) 
		{
			glUniform3f(iLightPosition_worldspaceLoc, light.x, light.y, light.z);
		}				

		terrainMesh.generateTextureUniform(terrainShaderId, "iTextureArray");

		terrainMesh.attachToVAO(0, 1, 2, 3);

		terrainMesh.draw();



		// SKYBOX ========================================================
		// Recompile/relink any programs that changed (must be called)
		skyboxShaderSet.UpdatePrograms();

		// set OpenGL's shader program (must be called in loop)
		glUseProgram(*skyboxShaderId);

		// get skybox shader uniform handles
		GLuint iSkyBoxViewLoc = glGetUniformLocation(*skyboxShaderId, "iView");
		GLuint iSkyBoxProjectionLoc = glGetUniformLocation(*skyboxShaderId, "iProjection");
		if (iSkyBoxViewLoc != -1)
		{
			// remove the translation component of the view matrix
			// to make sure the skybox's origin is always at the camera
			glm::mat4 newView = glm::mat4(glm::mat3(View));
			glUniformMatrix4fv(iSkyBoxViewLoc, 1, GL_FALSE, &newView[0][0]);
		}
		if (iSkyBoxProjectionLoc != -1)
		{
			glUniformMatrix4fv(iSkyBoxProjectionLoc, 1, GL_FALSE, &Projection[0][0]);
		}

		// generate uniforms for object textures		
		skyBox.generateTextureUniform(skyboxShaderId, "iSkyBoxCubeTexture");

		skyBox.attachToVAO(4);

		skyBox.draw();


		// draw wireframe of mesh
		//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);		
		

		// check for errors
		GLenum err2;
		while ((err2 = glGetError()) != GL_NO_ERROR) {
			std::cerr << "OpenGL error: " << err2 << std::endl;
		}

		// disable the depth buffer
		glDisable(GL_DEPTH_TEST);

        // SDL docs: "On Mac OS X make sure you bind 0 to the draw framebuffer before swapping the window, otherwise nothing will happen."
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
        
        // Display the frame of rendering to the window
        SDL_GL_SwapWindow(window);		
    }

quit:
    SDL_Quit();
    return 0;
}