void ForwardPositonalLightShader::update_properties(
                                                            const Mat4& trans,
                                                            const RenderEngine& engine) const
        {
            //TODO remove global camera.
            //                auto mvp =
            
            set_uniform_matrix4("transformation_mat", trans);
//            set_uniform_matrix4("camera_mat", engine.get_global_camera()->get_camera_mat());
//            set_uniform_matrix4("projection_mat", engine.get_global_camera()->get_projection_mat());
            set_uniform_matrix4("camera_mat", Locator::get_game().get_camera()->get_camera_mat());
            set_uniform_matrix4("projection_mat", Locator::get_game().get_camera()->get_projection_mat());

            set_uniform_matrix3("normal_mat",  trans.get_mat3().inverse().transpose());
            
            
            
            set_light("positional_light.light", engine.get_active_light());
            
            set_pos_light("positional_light",static_cast<const PositionalLight*>(engine.get_active_light()),trans);
            

//            
            //TODO 
            set_uniform3f("camera_pos", Locator::get_game().get_camera()->get_world_pos());
            set_uniform3f("camera_pos", Locator::get_game().get_camera()->get_world_pos());
            
            set_uniform3f("camera_pos", Locator::get_game().get_camera()->get_world_pos());
            set_uniform3f("camera_pos", Locator::get_game().get_camera()->get_world_pos());
//            //use the new texture
//            material.get_texture("diffuse").bind_texture(m_program_id, m_uniform_map["texture_sampler"]);
        }
Beispiel #2
0
void
Gui::onTimelineTimeAboutToChange()
{
    assert( QThread::currentThread() == qApp->thread() );
    const std::list<ViewerTab*>& viewers = getViewersList();
    for (std::list<ViewerTab*>::const_iterator it = viewers.begin(); it != viewers.end(); ++it) {
        RenderEngine* engine = (*it)->getInternalNode()->getRenderEngine();
        engine->abortRendering(true, false);
    }
}
Beispiel #3
0
void TextureFX::bindImage(RenderEngine renderengine) 
{
        if(tileImage == 0)
        {
            GL11.glBindTexture(3553 /*GL_TEXTURE_2*/, renderengine.getTexture("/terrain.png"));
        } else
        if(tileImage == 1)
        {
            GL11.glBindTexture(3553 /*GL_TEXTURE_2*/, renderengine.getTexture("/gui/items.png"));
        }
}
Beispiel #4
0
	void ImageProcessor::operator()(RenderEngine& render_engine)
	{
		if (initialized_)
		{
			render_engine.draw(*quadrilateral_);
		}
	}
Beispiel #5
0
	void handleEvents()
	{
		const sf::Input& Input = App->GetInput();
		bool shiftDown = Input.IsKeyDown(sf::Key::LShift) || Input.IsKeyDown(sf::Key::RShift);
		sf::Event Event;
		while (App->GetEvent(Event))
		{
			if (Event.Type == sf::Event::Closed)
				App->Close();
			if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
				App->Close();
			
			// This is for grading your code. DO NOT REMOVE
			if(Event.Type == sf::Event::KeyPressed && Event.Key.Code == sf::Key::Space) {
				firing = 6;
			} 
			if(Event.Type == sf::Event::KeyReleased && Event.Key.Code == sf::Key::Space) {
				firing = 0;
			}

			if(Event.Type == sf::Event::KeyPressed && Event.Key.Code == sf::Key::F12){
				render = RenderEngine();
				render.init();
			}

			
			if (Event.Type == sf::Event::Resized)
			{ glViewport(0, 0, Event.Size.Width, Event.Size.Height); }
		}
	}
Beispiel #6
0
void AppGUI::UpdateTexture(RenderEngine& engine)
{
    const int selectedTexture = m_cache->TextureSelected.Get();
    if(selectedTexture != m_selectedTexture)
    {
        m_selectedTexture = selectedTexture;
        const int ID = m_data.proceduralTextures[m_selectedTexture];
        m_data.textures[ID]->Write(*m_cache);
        m_data.textures[ID]->Save();
        m_cache->TexturePath.SetUpdated(m_data.textures[ID]->Path());
    }
    else if(m_selectedTexture >= 0 && 
            m_selectedTexture < static_cast<int>(m_data.proceduralTextures.size()))
    {
        const int ID = m_data.proceduralTextures[m_selectedTexture];
        m_data.textures[ID]->Read(*m_cache);
    }

    if (m_cache->ReloadTexture.Get())
    {
        const int ID = m_data.proceduralTextures[m_selectedTexture];
        m_scene.ReloadTexture(ID);
        engine.ReloadTexture(ID);
        m_data.textures[ID]->Save();
        m_cache->TexturePath.SetUpdated(m_data.textures[ID]->Path());
        m_cache->ReloadTexture.Set(false);
    }
}
Beispiel #7
0
void AppGUI::UpdateShader(RenderEngine& engine)
{   
    const int selectedShader = m_cache->ShaderSelected.Get();
    bool changedShader = selectedShader != m_selectedShader;
    bool recompiledShader = false;

    const std::string updatedText = m_cache->CompileShader.Get();
    if(!updatedText.empty() && m_selectedShader != NO_INDEX)
    {
        recompiledShader = ReCompileShader(updatedText, engine);
    }

    if(changedShader || recompiledShader)
    {
        m_selectedShader = selectedShader;
        m_cache->ShaderText.SetUpdated(engine.GetShaderText(m_selectedShader));
        m_cache->ShaderAsm.SetUpdated(engine.GetShaderAssembly(m_selectedShader));
    }
}
Beispiel #8
0
bool AppGUI::ReCompileShader(const std::string& text, RenderEngine& engine)
{
    const auto& shader = *m_data.shaders[m_selectedShader];
    m_cache->CompileShader.Clear();
    engine.WriteToShader(shader, text);

    std::string errors = engine.CompileShader(m_selectedShader);
    if(errors.empty())
    {
        Logger::LogInfo(shader.Name() + ": Recompiled successfully");
        return true;
    }
    else
    {
        Logger::LogInfo(shader.Name() + ": Failed Recompilation");
        MessageBox(nullptr, (shader.Name() + ":" + errors).c_str(), "Compilation Errors", MB_OK);
        return false;
    }
}
Beispiel #9
0
	void HudWriter::draw(RenderEngine& render_engine)
	{
		if (!vertex_buffer_.empty() && ((drawMode() == DynamicDraw) || (drawMode() == StaticDraw) || (drawMode() == StreamDraw)) )
		{
			if (needsDataRefresh())
			{
				prepareDrawing(render_engine);
				needs_data_refresh = false;
			}

			render_engine.drawVertexArrayObject(vertex_vao_, vertex_buffer_);
		}
	}
Beispiel #10
0
void AppGUI::UpdateScene(RenderEngine& engine)
{
    UpdateCamera();

    m_cache->FramesPerSec.Set(m_timer.GetFPS());
    m_cache->DeltaTime.Set(m_timer.GetDeltaTime());
    m_cache->Timer.Set(m_timer.GetTotalTime());

    if (m_cache->ReloadScene.Get())
    {
        m_cache->ReloadScene.Set(false);
        m_scene.Reload();

        const auto maxTextures = m_cache->Textures.Get().size();
        for (unsigned int i = 0; i < maxTextures; ++i)
        {
            engine.ReloadTexture(m_data.proceduralTextures[i]);
        }

        const auto maxTerrain = m_cache->Terrains.Get().size();
        for (unsigned int i = 0; i < maxTerrain; ++i)
        {
            engine.ReloadTerrain(i);
        }
    }

    if (m_cache->ReloadEngine.Get())
    {
        m_reloadEngine();
        m_cache->ReloadEngine.Set(false);
    }

    if (m_cache->ReloadPlacement.Get())
    {
        m_scene.ReloadPlacement();
        m_cache->ReloadPlacement.Set(false);
    }
}
        void ForwardDirectionalShader::update_properties(
                                                         const Mat4& trans,
                                                         const RenderEngine& engine) const
        {
            //TOOD use dir
            //TODO remove global camera.
            //                auto mvp =
            
            set_uniform_matrix4("transformation_mat", trans);
//            set_uniform_matrix4("camera_mat", engine.get_global_camera()->get_camera_mat());
//            set_uniform_matrix4("projection_mat", engine.get_global_camera()->get_projection_mat());
            set_uniform_matrix4("camera_mat", Locator::get_game().get_camera()->get_camera_mat());
            set_uniform_matrix4("projection_mat", Locator::get_game().get_camera()->get_projection_mat());

            set_uniform_matrix3("normal_mat", trans.get_mat3().inverse().transpose());
            
            auto dir_light = static_cast<const DirectionalLight*>(engine.get_active_light());
            set_light("directional_light.light", engine.get_active_light());
            set_uniform3f("directional_light.direction", dir_light->get_dir());
            
            
            auto& rim_light = dir_light->get_rim_light();
            if (rim_light) {
                set_uniformi("directional_light.rim_light.enable", rim_light->get_status());
                set_uniform3f("directional_light.rim_light.color", rim_light->get_rim_color());
                set_uniformf("directional_light.rim_light.power", rim_light->get_rim_power());
            }else{
                set_uniformi("directional_light.rim_light.enable", false);
            }
            
            
            //TODO
//            set_uniform3f("camera_pos", engine.get_global_camera()->get_world_pos()    );
            set_uniform3f("camera_pos", Locator::get_game().get_camera()->get_world_pos()    );
            
//            //use the new texture
//            material.get_texture("diffuse").bind_texture(m_program_id, m_uniform_map["texture_sampler"]);
        }
Beispiel #12
0
	void renderLoop(sf::Window & window)
	{
		sf::Clock time;
		WorldState state;
		
		while (state.isRunning())
		{
			this->handleEvents(window, state);
			state.timeStep( time.getElapsedTime().asSeconds() );
			engine.display(state);
			window.display();
		}
		window.close();
	}
        void ForwardAmbientShader::update_properties(
                                                     const Mat4& trans,
                                                     const RenderEngine& engine) const
        {
            set_uniform_matrix4("transformation_mat", trans);
            set_uniform_matrix4("camera_mat", Locator::get_game().get_camera()->get_camera_mat());
            set_uniform_matrix4("projection_mat", Locator::get_game().get_camera()->get_projection_mat());

            
            
            set_uniform3f("ambient", engine.get_ambient_light());
            
//            material.get_texture("diffuse").bind_texture(m_program_id, m_uniform_map["texture_sampler"]);

        }
Beispiel #14
0
void AppGUI::UpdatePost(RenderEngine& engine)
{
    const int selectedMap = m_cache->PostMapSelected.Get();
    if (selectedMap != m_selectedMap)
    {
        m_selectedMap = selectedMap;
        m_scene.SetPostMap(selectedMap);
    }

    m_data.post->Read(*m_cache);

    m_data.caustics->SetSpeed(
        m_cache->Post[POST_CAUSTIC_SPEED].Get());

    if (m_cache->ToggleWireframe.Get())
    {
        engine.ToggleWireframe();
        m_cache->ToggleWireframe.Set(false);
    }
}
Beispiel #15
0
void AppGUI::UpdateTerrain(RenderEngine& engine)
{
    const int selectedTerrain = m_cache->TerrainSelected.Get();
    if(selectedTerrain != m_selectedTerrain)
    {
        m_selectedTerrain = selectedTerrain;
        m_data.terrain[m_selectedTerrain]->Write(*m_cache);
    }
    else if(m_selectedTerrain >= 0 && 
            m_selectedTerrain < static_cast<int>(m_scene.Terrains().size()))
    {
        auto& terrain = *m_data.terrain[m_selectedTerrain];
        terrain.Read(*m_cache);
        m_cache->TerrainInstances.SetUpdated(terrain.GetRenderedInstances());
    }

    if (m_cache->ReloadTerrain.Get())
    {
        m_cache->ReloadTerrain.Set(false);
        m_scene.ReloadTerrain(m_selectedTerrain);
        engine.ReloadTerrain(m_selectedTerrain);
    }
}
void RenderEngine::display()
{
  if(render_engine.is_done())
  {
    render_engine.set_gl_ortho_proj();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    render_engine.draw_texture();
  }
  else
  {
    glEnable(GL_DEPTH_TEST);
    render_engine.set_gl_perspective();
    render_engine.set_gl_clearcolor();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
	  render_engine.set_gl_camera();
    render_engine.draw();
    glDisable(GL_DEPTH_TEST);
  }
  glutSwapBuffers();  
}
Beispiel #17
0
int main()
{
    init();
    map = mapLoader.FileMapper();
    int x = mapLoader.GetX();
    int y = mapLoader.GetY();
    char** mapArr = mapLoader.GetMap(map, x, y);
    char** safetyCopy = mapLoader.GetMap(map, x, y);
    ostringstream os;

    Image title = Image("title.txt");
    renderEngine.Render(title);
    getch();
    system("cls");
    mapArr[playerX][playerY] = '0';
    renderEngine.DrawMap(mapArr, x, y);

    while(true) {
        mapArr[playerX][playerY] = safetyCopy[playerX][playerY];
        switch(getch()) {
        case 'w':
            if(playerCanMove('w', safetyCopy[playerX][playerY-1])) {
                playerY--;
            }
            break;
        case 's':
            if(playerCanMove('s', safetyCopy[playerX][playerY+1])) {
                playerY++;
            }
            break;
        case 'a':
            if(playerCanMove('a', safetyCopy[playerX-1][playerY])) {
                playerX--;
            }
            break;
        case 'd':
            if(playerCanMove('d', safetyCopy[playerX+1][playerY])) {
                playerX++;
            }
            break;
        case '0':
            return EXIT_SUCCESS;
            break;
        default:
            break;
        }

        switch(command.Interact(safetyCopy[playerX][playerY])) {
        case 'a':
            pos++;
            os.str("");
            os << "next" << pos << ".txt";
            mapLoader.SetPath(os.str());
            renderEngine.SetEnvironment("fields");
            map = mapLoader.FileMapper();
            x = mapLoader.GetX();
            y = mapLoader.GetY();
            playerX = 20;
            playerY = 2;
            mapArr = mapLoader.GetMap(map, x, y);
            safetyCopy = mapLoader.GetMap(map, x, y);
            break;
        case 'p':
            pos--;
            os.str("");
            os << "next" << pos << ".txt";
            mapLoader.SetPath(os.str());
            renderEngine.SetEnvironment("house");
            map = mapLoader.FileMapper();
            x = mapLoader.GetX();
            y = mapLoader.GetY();
            playerX = 8;
            playerY = 12;
            mapArr = mapLoader.GetMap(map, x, y);
            safetyCopy = mapLoader.GetMap(map, x, y);
            break;
        case 'n':
            break;
        }
        system("cls");
        mapArr[playerX][playerY] = '0';
        renderEngine.DrawMap(mapArr, x, y);
    }

    return EXIT_SUCCESS;

}
static int BatchSimpleMode(const double haltTime, const unsigned int haltSpp, const float haltThreshold) {
	RenderConfig *config = session->renderConfig;
	RenderEngine *engine = session->renderEngine;

	// Force the film update at 2.5secs (mostly used by PathOCL)
	config->SetScreenRefreshInterval(2500);

	// Start the rendering
	session->Start();

	// Nothing to do if it is the FileSaverRenderEngine
	if (!dynamic_cast<FileSaverRenderEngine *>(engine)) {
		const double startTime = WallClockTime();

		double lastFilmUpdate = WallClockTime();
		char buf[512];
		for (;;) {
			boost::this_thread::sleep(boost::posix_time::millisec(1000));

			// Check if periodic save is enabled
			if (session->NeedPeriodicSave()) {
				// Time to save the image and film
				session->SaveFilmImage();
				lastFilmUpdate =  WallClockTime();
			} else {
				// Film update may be required by some render engine to
				// update statistics, convergence test and more
				if (WallClockTime() - lastFilmUpdate > 5.0) {
					session->renderEngine->UpdateFilm();
					lastFilmUpdate =  WallClockTime();
				}
			}

			const double now = WallClockTime();
			const double elapsedTime = now - startTime;
			if ((haltTime > 0) && (elapsedTime >= haltTime))
				break;

			const unsigned int pass = engine->GetPass();
			if ((haltSpp > 0) && (pass >= haltSpp))
				break;

			// Convergence test is update inside UpdateFilm()
			const float convergence = engine->GetConvergence();
			if ((haltThreshold >= 0.f) && (1.f - convergence <= haltThreshold))
				break;

			// Print some information about the rendering progress
			sprintf(buf, "[Elapsed time: %3d/%dsec][Samples %4d/%d][Convergence %f%%][Avg. samples/sec % 3.2fM on %.1fK tris]",
					int(elapsedTime), int(haltTime), pass, haltSpp, 100.f * convergence, engine->GetTotalSamplesSec() / 1000000.0,
					config->scene->dataSet->GetTotalTriangleCount() / 1000.0);

			SLG_LOG(buf);
		}
	}

	// Stop the rendering
	session->Stop();

	// Save the rendered image
	session->SaveFilmImage();

	delete session;
	SLG_LOG("Done.");

	return EXIT_SUCCESS;
}
static int BatchTileMode(const unsigned int haltSpp, const float haltThreshold) {
	RenderConfig *config = session->renderConfig;
	RenderEngine *engine = session->renderEngine;

	// batch.halttime condition doesn't make sense in the context
	// of tile rendering
	if (config->cfg.IsDefined("batch.halttime") && (config->cfg.GetInt("batch.halttime", 0) > 0))
		throw runtime_error("batch.halttime parameter can not be used with batch.tile");
	// image.subregion condition doesn't make sense in the context
	// of tile rendering
	if (config->cfg.IsDefined("image.subregion"))
		throw runtime_error("image.subregion parameter can not be used with batch.tile");

	// Force the film update at 2.5secs (mostly used by PathOCL)
	config->SetScreenRefreshInterval(2500);

	const u_int filterBorder = 2;

	// Original film size
	const u_int originalFilmWidth = session->film->GetWidth();
	const u_int originalFilmHeight = session->film->GetHeight();

	// Allocate a film where to merge all tiles
	Film mergeTileFilm(originalFilmWidth, originalFilmWidth,
			session->film->HasPerPixelNormalizedBuffer(), session->film->HasPerScreenNormalizedBuffer(),
			true);
	mergeTileFilm.CopyDynamicSettings(*(session->film));
	mergeTileFilm.EnableOverlappedScreenBufferUpdate(false);
	mergeTileFilm.Init(originalFilmWidth, originalFilmWidth);

	// Get the tile size
	vector<int> tileSize = config->cfg.GetIntVector("batch.tile", "256 256");
	if (tileSize.size() != 2)
		throw runtime_error("Syntax error in batch.tile (required 2 parameters)");
	tileSize[0] = Max<int>(64, Min<int>(tileSize[0], originalFilmWidth));
	tileSize[1] = Max<int>(64, Min<int>(tileSize[1], originalFilmHeight));
	SLG_LOG("Tile size: " << tileSize[0] << " x " << tileSize[1]);

	// Get the loop count
	int loopCount = config->cfg.GetInt("batch.tile.loops", 1);

	bool sessionStarted = false;
	for (int loopIndex = 0; loopIndex < loopCount; ++loopIndex) {
		u_int tileX = 0;
		u_int tileY = 0;
		const double startTime = WallClockTime();

		// To setup new rendering parameters
		if (loopIndex > 0) {
			// I can begin an edit only after the start
			session->BeginEdit();

			// I have to use a new seed or I will render exactly the same images
			session->renderEngine->GenerateNewSeed();
		}

		for (;;) {
			SLG_LOG("Rendering tile offset: (" << tileX << "/" << originalFilmWidth  + 2 * filterBorder << ", " <<
					tileY << "/" << originalFilmHeight + 2 * filterBorder << ")");

			// Set the film subregion to render
			u_int filmSubRegion[4];
			filmSubRegion[0] = tileX;
			filmSubRegion[1] = Min(tileX + tileSize[0] - 1, originalFilmWidth - 1) + 2 * filterBorder;
			filmSubRegion[2] = tileY;
			filmSubRegion[3] = Min(tileY + tileSize[1] - 1, originalFilmHeight - 1) + 2 * filterBorder;
			SLG_LOG("Tile subregion: " << 
					boost::lexical_cast<string>(filmSubRegion[0]) << " " << 
					boost::lexical_cast<string>(filmSubRegion[1]) << " " <<
					boost::lexical_cast<string>(filmSubRegion[2]) << " " <<
					boost::lexical_cast<string>(filmSubRegion[3]));

			// Update the camera and resize the film
			session->renderConfig->scene->camera->Update(
					originalFilmWidth + 2 * filterBorder,
					originalFilmHeight + 2 * filterBorder,
					filmSubRegion);
			
			session->film->Init(session->renderConfig->scene->camera->GetFilmWeight(),
					session->renderConfig->scene->camera->GetFilmHeight());

			if (sessionStarted) {
				session->editActions.AddAction(CAMERA_EDIT);
				session->editActions.AddAction(FILM_EDIT);
				session->EndEdit();
			} else {
				session->Start();
				sessionStarted = true;
			}

			double lastFilmUpdate = WallClockTime();
			char buf[512];
			for (;;) {
				boost::this_thread::sleep(boost::posix_time::millisec(1000));

				// Film update may be required by some render engine to
				// update statistics, convergence test and more
				if (WallClockTime() - lastFilmUpdate > 5.0) {
					session->renderEngine->UpdateFilm();
					lastFilmUpdate =  WallClockTime();
				}

				const unsigned int pass = engine->GetPass();
				if ((haltSpp > 0) && (pass >= haltSpp))
					break;

				// Convergence test is update inside UpdateFilm()
				const float convergence = engine->GetConvergence();
				if ((haltThreshold >= 0.f) && (1.f - convergence <= haltThreshold))
					break;

				// Print some information about the rendering progress
				const double now = WallClockTime();
				const double elapsedTime = now - startTime;
				sprintf(buf, "[Loop step: %d/%d][Elapsed time: %3d][Samples %4d/%d][Convergence %f%%][Avg. samples/sec % 3.2fM on %.1fK tris]",
						loopIndex + 1, loopCount,
						int(elapsedTime), pass, haltSpp, 100.f * convergence, engine->GetTotalSamplesSec() / 1000000.0,
						config->scene->dataSet->GetTotalTriangleCount() / 1000.0);

				SLG_LOG(buf);
			}

			// Splat the current tile on the merge film
			session->renderEngine->UpdateFilm();

			{
				boost::unique_lock<boost::mutex> lock(session->filmMutex);
				mergeTileFilm.AddFilm(*(session->film), filterBorder, filterBorder,
						filmSubRegion[1] - filmSubRegion[0] - 2 * filterBorder + 1,
						filmSubRegion[3] - filmSubRegion[2] - 2 * filterBorder + 1,
						tileX, tileY);
			}

			// Save the merge film
			const string fileName = config->cfg.GetString("image.filename", "image.png");
			SLG_LOG("Saving merged tiles to: " << fileName);
			mergeTileFilm.UpdateScreenBuffer();
			mergeTileFilm.SaveScreenBuffer(fileName);

			// Advance to the next tile
			tileX += tileSize[0];
			if (tileX >= originalFilmWidth) {
				tileX = 0;
				tileY += tileSize[1];

				if (tileY >= originalFilmHeight) {
					// Rendering done
					break;
				}
			}

			// To setup new rendering parameters
			session->BeginEdit();
		}
	}

	// Stop the rendering
	session->Stop();

	delete session;
	SLG_LOG("Done.");

	return EXIT_SUCCESS;
}
void RenderEngine::keyboard(unsigned char key, int x, int y)
{
  // The shader to be used when rendering a material is chosen 
  // by setting the "illum" property of the material. This
  // property is part of the MTL file format ("illum" is short
  // for "illumination model"). The shader to be used with
  // each illumination model is specified in the init_tracer 
  // function above.
  //
  // Number keys switch the shader used for illumination
  // models 0 and 1 to the shader at the corresponding index
  // in the array "shaders" at the top of this file.
  //
  // When you switch shaders all previous rendering results
  // will be erased!
  if(key >= 48 && key < 48 + static_cast<unsigned char>(render_engine.no_of_shaders()))
  {
    unsigned int shader_no = key - 48;
    if(shader_no != render_engine.get_current_shader())
    {
      render_engine.set_current_shader(shader_no);
      render_engine.clear_image();
      render_engine.redo_display_list();
      cout << "Switched to shader number " << shader_no << endl;
      glutPostRedisplay();
    }
  }
  switch(key)
  { 
  // Use '+' and '-' to increase or decrease the number of
  // jitter samples per pixel in a simple ray tracing
  case '+':
    render_engine.increment_pixel_subdivs();
    break;
  case '-':
    render_engine.decrement_pixel_subdivs();
    break;
  // Press '*' to apply tone mapping
  case '*':
    render_engine.apply_tone_map();
    break;
  // Press '/' to unapply tone mapping
  case '/':
    render_engine.unapply_tone_map();
    break;
  // Press 'b' to save a bitmap called the same as the last loaded .obj file.
  case 'b':
    render_engine.save_as_bitmap();
    break;
  // Press 'r' to start a simple ray tracing (one pass -> done).
  // To switch back to preview mode after the ray tracing is done
  // press 'r' again.
  case 'r':
    if(render_engine.is_done())
      render_engine.undo();
    else 
      render_engine.render();
    glutPostRedisplay();
    break;
  // Press 's' to toggle shadows on/off
  case 's':
    {
      bool shadows_on = render_engine.toggle_shadows();
      render_engine.clear_image();
      render_engine.redo_display_list();
      cout << "Toggled shadows " << (shadows_on ? "on" : "off") << endl;
      glutPostRedisplay();
    }
    break;
  // Press 'x' to switch on material textures.
  case 'x':
    render_engine.add_textures();
    cout << "Toggled textures on." << endl;
    break;
  // Press 'z' to zoom in.
  case 'z':
    {
      render_engine.set_focal_dist(render_engine.get_focal_dist()*1.05f);
      glutPostRedisplay();
    }
    break;
  // Press 'Z' to zoom out.
  case 'Z':
    {
      render_engine.set_focal_dist(render_engine.get_focal_dist()/1.05f);
      glutPostRedisplay();
    }
    break;
  // Press 'SPACE' to switch between pre-view and your last tracing result.
  case 32:
    render_engine.undo();
    glutPostRedisplay();
    break;
  // Press 'ESC' to exit the program.
  case 27:
    exit(0);
  }
}
void RenderEngine::reshape(int width, int height)
{
  render_engine.set_window_size(width, height);
  glViewport(0, 0, width, height);
}
Beispiel #22
0
	void ProcessingChain::operator()(RenderEngine& render_engine)
	{
		if (initialize())
		{
			Uint viewport_x = render_engine.getViewportX();
			Uint viewport_y = render_engine.getViewportY();
			Uint viewport_width = render_engine.getViewportWidth();
			Uint viewport_height = render_engine.getViewportHeight();

			render_engine.pushDrawStates();
			render_engine.apply(states);

			render_engine.setViewport(0, 0, ping_->width(), ping_->height());

			if (stages_.size() == 1)
			{
				render_engine.bind(*ping_);
				render_engine.clearBuffers();

				(*stages_[0])(render_engine);

				render_engine.unbind(*ping_);

			}
			else
			{
				for (ProcessingStages::size_type stage = 0; stage != stages_.size(); ++ stage)
				{
					Bool use_ping = usePing(false, stage, stages_.size());

					render_engine.bind(use_ping ? *ping_ : *pong_);
					render_engine.clearBuffers();

					(*stages_[stage])(render_engine);

					render_engine.unbind(use_ping ? *ping_ : *pong_);
				}
			}


			render_engine.popDrawStates();

			render_engine.setViewport(viewport_x, viewport_y, viewport_width, viewport_height);
		}
	}
Beispiel #23
0
	void handleEvents(WorldState & state, RenderEngine & render)
	{
		bool shiftDown = sf::Keyboard::isKeyPressed(sf::Keyboard::LShift) ||sf::Keyboard::isKeyPressed(sf::Keyboard::RShift);
		sf::Event Event;
		
		while (App->pollEvent(Event))
		{
			if (Event.type == sf::Event::Closed)
				state.setRunning(false);
			if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Escape))
				state.setRunning(false);
			
			if (Event.type == sf::Event::MouseButtonPressed)
			{
				previousPos = glm::vec2(Event.mouseButton.x, Event.mouseButton.y);
				
				if(Event.mouseButton.button == sf::Mouse::Left && !shiftDown)
					buttonDown[0] = 1;
				if(Event.mouseButton.button == sf::Mouse::Right)
					buttonDown[1] = true;
				if(Event.mouseButton.button == sf::Mouse::Middle)
					buttonDown[2] = true;
				if(Event.mouseButton.button == sf::Mouse::Left && shiftDown)
					buttonDown[2] = true;
			}
			
			if (Event.type == sf::Event::MouseButtonReleased)
			{
				if(Event.mouseButton.button == sf::Mouse::Left && !shiftDown)
					buttonDown[0] = false;
				if(Event.mouseButton.button == sf::Mouse::Right)
					buttonDown[1] = false;
				if(Event.mouseButton.button == sf::Mouse::Middle)
					buttonDown[2] = false;
				if(Event.mouseButton.button == sf::Mouse::Left && shiftDown)
					buttonDown[2] = false;
				
				lastUpdate = timer.getElapsedTime().asSeconds();
			}
			
			if (Event.type == sf::Event::Resized) {
				render.reshape( Event.size.width, Event.size.height );
				state.setSize( Event.size.width, Event.size.height );
			}
		}
		
		
		lastUpdate = timer.getElapsedTime().asSeconds();
		bool needsUpdate = lastUpdate > TIME_BETWEEN_UPDATES;
		if (needsUpdate)
		{
			glm::ivec2 newPos = glm::ivec2(sf::Mouse::getPosition(*App).x, sf::Mouse::getPosition(*App).y);
			
			if(buttonDown[0])
				state.updateRotate(previousPos, newPos);
			if(buttonDown[1])
				state.updateXYTranslate(previousPos, newPos);
			if(buttonDown[2])
				state.updateZTranslate(previousPos, newPos);
			
			lastUpdate = timer.restart().asSeconds();
			previousPos = newPos;
		}
	}
RenderEngine* RenderEngine::create(EGLDisplay display, EGLConfig config) {
    EGLint renderableType = 0;
    EGLint contextClientVersion = 0;

    // query the renderable type, setting the EGL_CONTEXT_CLIENT_VERSION accordingly
    if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
        LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
    }

    if (renderableType & EGL_OPENGL_ES2_BIT) {
        contextClientVersion = 2;
    } else if (renderableType & EGL_OPENGL_ES_BIT) {
        contextClientVersion = 1;
    } else {
        LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
    }

    // Also create our EGLContext
    EGLint contextAttributes[] = {
            EGL_CONTEXT_CLIENT_VERSION, contextClientVersion,      // MUST be first
#ifdef EGL_IMG_context_priority
#ifdef HAS_CONTEXT_PRIORITY
#warning "using EGL_IMG_context_priority"
            EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
#endif
#endif
            EGL_NONE, EGL_NONE
    };
    EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);

    // if can't create a GL context, we can only abort.
    LOG_ALWAYS_FATAL_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");


    // now figure out what version of GL did we actually get
    // NOTE: a dummy surface is not needed if KHR_create_context is supported

    EGLint attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE, EGL_NONE };
    EGLSurface dummy = eglCreatePbufferSurface(display, config, attribs);
    LOG_ALWAYS_FATAL_IF(dummy==EGL_NO_SURFACE, "can't create dummy pbuffer");
    EGLBoolean success = eglMakeCurrent(display, dummy, dummy, ctxt);
    LOG_ALWAYS_FATAL_IF(!success, "can't make dummy pbuffer current");

    GLExtensions& extensions(GLExtensions::getInstance());
    extensions.initWithGLStrings(
            glGetString(GL_VENDOR),
            glGetString(GL_RENDERER),
            glGetString(GL_VERSION),
            glGetString(GL_EXTENSIONS));

    GlesVersion version = parseGlesVersion( extensions.getVersion() );

    // initialize the renderer while GL is current

    RenderEngine* engine = NULL;
    switch (version) {
    case GLES_VERSION_1_0:
        engine = new GLES10RenderEngine();
        break;
    case GLES_VERSION_1_1:
        engine = new GLES11RenderEngine();
        break;
    case GLES_VERSION_2_0:
    case GLES_VERSION_3_0:
        engine = new GLES20RenderEngine();
        break;
    }
    engine->setEGLContext(ctxt);

    ALOGI("OpenGL ES informations:");
    ALOGI("vendor    : %s", extensions.getVendor());
    ALOGI("renderer  : %s", extensions.getRenderer());
    ALOGI("version   : %s", extensions.getVersion());
    ALOGI("extensions: %s", extensions.getExtension());
    ALOGI("GL_MAX_TEXTURE_SIZE = %d", engine->getMaxTextureSize());
    ALOGI("GL_MAX_VIEWPORT_DIMS = %d", engine->getMaxViewportDims());

    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    eglDestroySurface(display, dummy);

    return engine;
}