コード例 #1
0
ファイル: Renderer.cpp プロジェクト: kikko/ofxEmbree
Handle <Device::RTShape> Renderer::addShape(Device::RTMaterial material, Device::RTShape shape, const AffineSpace3f & transform) {
    Handle<Device::RTPrimitive> prim = g_device->rtNewShapePrimitive(shape, material, copyToArray(transform));
    prims.push_back(prim);
    primsMap[shape] = prim;
    buildScene();
    return shape;
}
コード例 #2
0
ファイル: world.cpp プロジェクト: RichardSlade/Flocky-Sheep
World::World(GameState& gameState
             , const Controller& controller
             , sf::RenderWindow& window
             , std::string username
             , int worldDim
             , int numSheep
             , sf::Time levelTime)
: mWorldX(worldDim)
, mWorldY(worldDim)
, mExitRadius(controller.getParams().ExitRadius)
, mLevelBlockSize(controller.getParams().LevelBlockSize)
, mNumSheep(numSheep)
, mWaypointRadius(controller.getParams().WaypointRadius)
, mScrollSpeed(controller.getParams().ScrollSpeed)
, mGameState(gameState)
, mWindow(window)
, mWorldView(mWindow.getDefaultView())
, mWorldBounds(sf::Vector2i(0, 0), sf::Vector2i(mWorldX, mWorldY))
, mFocusPoint(mWorldBounds.width / 2.f, mWorldBounds.height / 2.f)
, mSheepHerded(0)
, mTimeLeft(levelTime)
, mTimeTaken(sf::Time::Zero)
, mLevel(mLevelBlockSize
         , controller.getParams().ExitWidth
         , mWorldBounds)
, mHUD(this
       , controller.getFont(Controller::Fonts::Sansation)
       , getViewBounds()
       , username)
, mExitPos(mWorldBounds.width / 2.f, 0.f)
, mDog(nullptr)
{
    initialiseStatesAndStats();
    buildScene(controller);
}
コード例 #3
0
ファイル: World.cpp プロジェクト: AlexDontsov2008/spacecrash
World::World(sf::RenderWindow& window)
: mWindow(window)
, mWorldView(window.getDefaultView())
, mTextures() 
, mFonts()
, mSceneGraph()
, mSceneLayers()
, mWorldBounds(0.f, 0.f, mWorldView.getSize().x, WorldLeght)
, mSpawnPosition(mWorldView.getSize().x / 2.f, mWorldBounds.height - mWorldView.getSize().y / 3.f)
, mScrollSpeed(-200.f)
, mPlayerSpaceship(nullptr)
, mPlanetSpawnPoints()
, mBackgroundSprite(nullptr)
, mHealthDisplay(nullptr)
, mPointsDisplay(nullptr)
, mPoints(0)
, mOldWorldCoordY(0.f)
, mDistanceForSpawnNewEnemies(WorldLeght)
{

	mFonts.load(Fonts::Main, "Media/Sansation.ttf");
	loadTextures();
	buildScene();	

	// Prepare the view
	mWorldView.setCenter(mSpawnPosition.x, mWorldBounds.height - mWorldView.getSize().y / 2.f);

}
コード例 #4
0
SceneLoader::SceneLoader(Scene &scene, string file) {
    err = &cout;
    scene._root = new SceneInstance();
    root = scene._root;
    root->_name = "toplevel";
    buildScene(file);
}
コード例 #5
0
ファイル: World.cpp プロジェクト: jimmybeer/TAGEngine
World::World(sf::RenderTarget& outputTarget, FontHolder& fonts, SoundPlayer& sounds)
 : mTarget(outputTarget)
 , mSceneTexture()
 , mWorldView(outputTarget.getDefaultView())
 , mFonts(fonts)
 , mSounds(sounds)
 , mTextures()
 , mSceneGraph()
 , mSceneLayers()
 , mWorldBounds(0.f, 0.f, mWorldView.getSize().x, 2000.0f)
 , mSpawnPosition(mWorldView.getSize().x / 2.f, mWorldBounds.height - mWorldView.getSize().y / 2.f)
 , mScrollSpeed(-50.f)
 , mPlayerAircraft(nullptr)
 , mEnemySpawnPoints()
 , mActiveEnemies()
 , mPostEffectsSupported(false)
{
    mPostEffectsSupported = PostEffect::isSupported();
	if(mPostEffectsSupported)
	{
        mSceneTexture.create(mTarget.getSize().x, mTarget.getSize().y);
	}
	
    loadTextures();
	buildScene();
	
	// Prepare the view.
	mWorldView.setCenter(mSpawnPosition);
}
コード例 #6
0
World::World(sf::RenderTarget& outputTarget, FontHolder& fonts, SoundPlayer& sounds, bool networked)
: mTarget(outputTarget)
, mSceneTexture()
, mWorldView(outputTarget.getDefaultView())
, mTextures() 
, mFonts(fonts)
, mSounds(sounds)
, mSceneGraph()
, mSceneLayers()
, mWorldBounds(0.f, 0.f, mWorldView.getSize().x, 5000.f)
, mSpawnPosition(mWorldView.getSize().x / 2.f, mWorldBounds.height - mWorldView.getSize().y / 2.f)
, mScrollSpeed(-50.f)
, mScrollSpeedCompensation(1.f)
, mPlayerAircrafts()
, mEnemySpawnPoints()
, mActiveEnemies()
, mNetworkedWorld(networked)
, mNetworkNode(nullptr)
, mFinishSprite(nullptr)
{
	mSceneTexture.create(mTarget.getSize().x, mTarget.getSize().y);

	loadTextures();
	buildScene();

	// Prepare the view
	mWorldView.setCenter(mSpawnPosition);
}
コード例 #7
0
ファイル: GameState.cpp プロジェクト: OtemPsych/Infestation
GameState::GameState(pyro::StateStack* stack, sf::RenderWindow* window)
	: State(stack, window)
	, camera_(nullptr)
	, blood_splatter_lifetime_(sf::seconds(30.f))
	, crosshair_(nullptr)
	, wave_(0)
	, infected_per_wave_(6)
	, world_bounds_(0.f, 0.f, 2500.f, 2500.f)
{
	window_->setMouseCursorVisible(false);
	
	setupResources();
	projectile_data_     = std::move(data::initializeProjectileData(projectile_textures_));
	survivor_data_       = std::move(data::initializeSurvivorData(survivor_textures_));
	infected_data_       = std::move(data::initializeInfectedData(infected_textures_));
	blood_spray_data_    = std::move(data::initializeBloodSprayData(blood_spray_textures_));
	blood_splatter_data_ = std::move(data::initializeBloodSplatterData(blood_splatter_textures_));

	buildScene();

	auto wave_text(std::make_unique<pyro::Text>());
	wave_text->loadFontFromFile("Assets/Fonts/Waves.ttf");
	wave_text->setOriginFlags(pyro::utils::OriginFlag::Right | pyro::utils::OriginFlag::Top);
	wave_text->setTextColor(sf::Color::White);
	wave_text->activateShadow(true);
	wave_text->setShadowColor(sf::Color::Black);
	wave_text->setShadowOffset(2.f, 2.f);
	wave_text->setPosition(window_->getSize().x - 5.f, 5.f);
	wave_text_ = wave_text.get();
	camera_->attachChild(std::move(wave_text));

	music_player_.setVolume(70.f);
}
コード例 #8
0
World::World(sf::RenderTarget&	target, FontHolder& fonts, SoundPlayer& sounds)
	: mTarget(target)
	, mFonts(fonts)
	, mSounds(sounds)
	, mWorldView(target.getDefaultView())
	, mImages()
	, mTextures()
	, mSceneGraph()
	, mSceneLayers()
	, mWorldBounds(mWorldView.getCenter() - mWorldView.getSize() / 2.f, mWorldView.getSize())
	, mSpawnPosition(mWorldView.getSize().x / 2.f, mWorldView.getSize().y / 2.f)
	, mBossFactory(mTextures, mWorldBounds)
	, mPlayerFactory(mTextures)
	, mPlayer(nullptr)
	, mBoss(nullptr)
	, mLife(nullptr)
	, mScore(nullptr)
	, mQuadTreePrimary(1, mWorldBounds)
	, mQuadTreeSecondary(1, mWorldBounds)
	, mPlayerBulletNodes()
	, mEnemyBulletNodes()
	, mInvaders()
	, mLivesCount(3)
	, mChangeSpeed(false)
	, mDeadLine(getBattlefieldBounds().height + getBattlefieldBounds().top - Padding / 2.f)
	, mIsGameEnded(false)
{
	loadTextures();
	buildScene();

	// Prepare the view
	mWorldView.setCenter(mSpawnPosition);
}
コード例 #9
0
ファイル: World.hpp プロジェクト: Casper-Olsen/snake-game
World::World(sf::RenderWindow &w)
: window(w)
, food(nullptr)
, snakeHead(nullptr)
, observers()
{
    buildScene();
}
コード例 #10
0
ファイル: Raytracer.cpp プロジェクト: ThermalPixel/osgdemos
Raytracer::Raytracer(osg::Node *scene, osg::Camera *camera)
    :_rootNode(scene), _camera(camera), TILE_SIZE_X(32),TILE_SIZE_Y(32), _backgroundColor(0.3f,0.4f,0.5f,1.0f)
{
    rtcInit();
    _scene = rtcNewScene(RTC_SCENE_STATIC, RTC_INTERSECT1);
    buildScene();
    setOutputResolution(512,512);
}
コード例 #11
0
World::World(sf::RenderWindow &window) : window(window), worldView(window.getDefaultView()), textures("img/textures/"),
                                         worldBounds(0.f, 0.f, worldView.getSize().x, 2000.f),
                                         spawnPosition(worldView.getSize().x / 2.f, worldBounds.height -
                                                 worldView.getSize().y / 2.f),
                                         scrollSpeed(-50.f), playerAircraft(nullptr) {
    loadTextures();
    buildScene();
    worldView.setCenter(spawnPosition);
}
コード例 #12
0
ファイル: World.cpp プロジェクト: calvinaquino/RacingSimGame
World::World(sf::RenderWindow& window)
: mWindow(window)
, mWorldView(window.getDefaultView())
{
	loadTextures();
	buildScene();

	// Prepare the view
	mWorldView.setCenter(mSpawnPosition);
}
コード例 #13
0
CWBOOL CubeMapDemoScene::init()
{
	if (!cwBaseScene::init()) return CWFALSE;

	buildSphereMaterial();
	buildLight();
	buildScene();

	return CWTRUE;
}
コード例 #14
0
ファイル: osgVRPNviewer.cpp プロジェクト: mew-cx/osgtoy
int main( int argc, char **argv )
{
    osg::ArgumentParser args( &argc, argv );
    args.getApplicationUsage()->setApplicationName( args.getApplicationName() );
    args.getApplicationUsage()->setDescription(args.getApplicationName()+" demonstrates osgVRPN trackers");
    args.getApplicationUsage()->setCommandLineUsage(args.getApplicationName()+" [options]");
    args.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    args.getApplicationUsage()->addKeyboardMouseBinding( "upArrow", "increase tracker scale" );
    args.getApplicationUsage()->addKeyboardMouseBinding( "downArrow", "decrease tracker scale" );

    osgProducer::Viewer viewer(args);
    viewer.setUpViewer( osgProducer::Viewer::STANDARD_SETTINGS );

    viewer.getUsage( *args.getApplicationUsage() );
    if (args.read("-h") || args.read("--help"))
    {
        args.getApplicationUsage()->write(std::cout);
        return 1;
    }

#if defined(CAMERA_TRACKER_NAME)
    osgVRPN::TrackerManipulator* trkManip = new osgVRPN::TrackerManipulator();
    unsigned int pos = viewer.addCameraManipulator( trkManip );
    viewer.selectCameraManipulator( pos );

    osg::ref_ptr<osgVRPN::Tracker> tracker = new osgVRPN::Tracker( CAMERA_TRACKER_NAME );
    trkManip->setTracker( tracker );
    trkManip->setAutoComputeHomePosition(false);
    trkManip->setHomeMatrix( osg::Matrix::translate(0,0,10) * osg::Matrixd::rotate(1.2,1,0,0) );

    viewer.getEventHandlerList().push_front( new EventHandler( tracker ) );
#endif

    viewer.setSceneData( buildScene( &viewer ) );
    viewer.realize();
    while( !viewer.done() )
    {
        viewer.sync();
        viewer.update();

        {   // handy diagnostic: set clearcolor based on view orientation
            osg::Vec3 eye, center, up;
            viewer.getViewMatrix().getLookAt( eye, center, up );
            osg::Vec3 dirColor( center - eye );
            dirColor.normalize();
            dirColor += osg::Vec3(1,1,1);
            dirColor *= 0.5f;
            viewer.setClearColor( osg::Vec4(dirColor,1) );
        }

        viewer.frame();
    }
    viewer.sync();
    return 0;
}
コード例 #15
0
ファイル: LSMS.c プロジェクト: imago/mfes
void init(void)
{
	clock_t t;

	t = clock();
	buildScene(grid);
	printf("Scene building time %f seconds\n",(clock()-t)/(float)CLOCKS_PER_SEC);
	t = clock();
	printf("Total Molecular Surface Generation Time : %f seconds\n",(clock()-ttime)/(float)CLOCKS_PER_SEC);

}
コード例 #16
0
World::World(Data* gameData): data(gameData),
							worldView(data->window.getDefaultView()), 
							worldBounds( 0.f, 0.f, // left X position, top Y position
										worldView.getSize().x * 2.f, worldView.getSize().y * 2.f ), // width, height
							spawnPosition( worldView.getSize().x / 2.f, worldView.getSize().y / 2.f ),
							playerCharacter(nullptr)
{
	loadTextures();
	buildScene();
	worldView.setCenter(spawnPosition);
	worldView.setSize(sf::Vector2f(data->window.getSize()));
}
コード例 #17
0
ファイル: Scene.cpp プロジェクト: Debarquer/RayCastLab
// This method should not be modified for the purpose of the assignment.
void Update(float deltaTime)
{
	buildScene();
	// randomise the scene.
	// we do this to verify that no matter in what order the primitives are tested,
	// they should always return the same intersection points
	std::random_shuffle(shapes.begin(), shapes.end()); 

	// THE CODE BELOW CANNOT BE CHANGED FOR THIS ASSIGNMENT
	//loop through every screen pixel from bottom to top
	for(unsigned int y = 0; y < g_ToScreen->mScreenHeight; y++)
	{
		for(unsigned int x = 0; x < g_ToScreen->mScreenWidth; x++)
		{
			// Black color by default
			Color c = { 0, 0, 0 };

			// hitData will be reset every pixel.
			// hitData is sent to intersection tests to return intersection info
			// and ALWAYS carries the closest intersection for each pixel
			HitData hitData;

			// Create ray for current pixel, in ORTHOGRAPHIC fashion
			// Ray from (x, y, -10) with direction (0, 0, 1)
			Ray r(Vec((float)x, (float)y, -10), Vec(0,0,1));
			
			for (auto& shapeIt : shapes)
				shapeIt->test(r, hitData);

			// if we hit anything, we shade it
			if (hitData.lastShape != nullptr)
			{
				Shape* s = dynamic_cast<Shape*>(hitData.lastShape);
				// light source position at the center of the screen, z=-1000
				// camera position at the center of the screen, z = -10, 
				// normal at surface is queried from the surface and hitData
				c = s->shade(Vec(g_ToScreen->mScreenWidth/2, g_ToScreen->mScreenHeight/2, -1000), Vec(g_ToScreen->mScreenWidth/2, g_ToScreen->mScreenHeight/2, -10), r, hitData);
			}
			// hitData should contain the closest intersection point, 
			// and of course the colour of the shape
			// If there was no intersection, the colour will be BLACK
			g_ToScreen->SetPixelColor( 
				x, 
				(g_ToScreen->mScreenHeight-1-y), 
				c.r, c.g, c.b );
		}
	}
	//update texture surface with new pixel data
	g_ToScreen->Update(deltaTime);
}
コード例 #18
0
World::World(sf::RenderWindow& window)
: mWindow(window)
, mWorldView(window.getDefaultView())
, mTextures() 
, mSceneGraph()
, mSceneLayers()
, mWorldBounds(0.f, 0.f, mWorldView.getSize().x, 2000.f)
, mSpawnPosition(mWorldView.getSize().x / 2.f, mWorldBounds.height - mWorldView.getSize().y / 2.f)
, mScrollSpeed(-50.f)
, mPlayerAircraft(nullptr)
{
	loadTextures();
	buildScene();

	// Prepare the view
	mWorldView.setCenter(mSpawnPosition);
}
コード例 #19
0
ファイル: TilemapDemoState.cpp プロジェクト: fallahn/xygine
TilemapDemoState::TilemapDemoState(xy::StateStack& stateStack, Context context)
    : State     (stateStack, context),
    m_messageBus(context.appInstance.getMessageBus()),
    m_scene     (m_messageBus),
    m_physWorld (m_messageBus)
{
    launchLoadingScreen();
    m_scene.setView(context.defaultView);
    m_shaderResource.preload(xy::Shader::Tilemap, xy::Shader::tmx::vertex, xy::Shader::tmx::fragment);
    m_physWorld.setGravity({ 0.f, 980.f });

    buildScene();

    REPORT("Q", "Show Debug");
    //xy::StatsReporter::show();

    quitLoadingScreen();
}
コード例 #20
0
void init(int argc, char *argv[])
{
    int winId = setupGLUT(&argc, argv);
    
    GLUTWindowUnrecPtr gwin = GLUTWindow::create();
    gwin->setGlutId(winId);
    gwin->init     (     );

    NodeUnrecPtr scene = buildScene();

    mgr = SimpleSceneManager::create();
    mgr->setWindow(gwin );
    mgr->setRoot  (scene);

    FrameHandler::the()->init();

    mgr->showAll();
}
コード例 #21
0
ファイル: scene.cpp プロジェクト: TTU-Graphics/FinalProject
Scene::Scene(const char* sceneFile) {
    //*
    Json::Value root;
    Json::Reader reader;
    filebuf fb;
    fb.open(sceneFile,ios::in);
    istream json(&fb);
    if(!reader.parse(json, root)) {
        printf("error parsing scene file!!! %s\n%s\n",sceneFile,
               reader.getFormatedErrorMessages().c_str());
        return;
    }
    fb.close();

    buildScene(root);

    /*Menger *m = new Menger(vec3(0,0,0), 1, 2);
      models.push_back(m);*/
}
コード例 #22
0
// TODO LEVEL
World::World(sf::RenderWindow& window, FontHolder& fonts, SoundPlayer& sounds, const std::string& level):
    m_window(window),
    m_fonts(fonts),
    m_sounds(sounds),
    m_worldView(window.getDefaultView()),
    m_physicWorld(b2Vec2(0, 0.0f)),
    m_worldBounds(0,0,0,0),
    m_player(nullptr),
    m_commandQueue(),
    m_contactListener(m_commandQueue),
    ml("maps/")
{
    loadTextures();

    m_worldView.setCenter(m_spawnPosition);

    m_physicWorld.SetContactListener(&m_contactListener);

    buildScene(level);
}
コード例 #23
0
ファイル: world.cpp プロジェクト: Lo-X/ludumdare31
World::World(sf::RenderWindow& window, TextureHolder &textures, FontHolder &fonts, MusicPlayer &music, SoundPlayer &sounds, ScriptPlayer &scripts, PlayerController &player) :
    mWindow(window),
    mWorldView(window.getDefaultView()),
    mTextures(textures),
    mFonts(fonts),
    mMusic(music),
    mSounds(sounds),
    mScripts(scripts),
    mPlayer(nullptr),
    mSceneGraph(),
    mSceneLayers()
{
    loadTextures();
    buildScene();

    // Other things here, like setting the view center on the player, scores, etc...
    mKidKilledCommand.category = Category::WaveGenerator;
    mKidKilledCommand.action = derivedAction<WaveGenerator>([&](WaveGenerator& gen, sf::Time dt) {
        gen.kidKilled();
    });
}
コード例 #24
0
ファイル: World.cpp プロジェクト: kevin5396/Hellfire
World::World(sf::RenderWindow& window, FontHolder& fonts)
: mWindow(window)
, mWorldView(window.getDefaultView())
, mFonts(fonts)
, mScore(0)
, mLevel(1)
, mWorldBounds (
    0.f,                                //left x position
    0.f,                                // top y position
    mWorldView.getSize().x,             //width
                2500.f)                 //height
, mScrollSpeed(-50.f)
, mSpawnPosition(mWorldView.getSize().x / 2.f,              //X
                 mWorldBounds.height - mWorldView.getSize().y / 2.f)  //Y
, mPlayerAircraft(nullptr)
{
    loadTextures();
    addEnemies();
    buildScene();
    mWorldView.setCenter(mSpawnPosition);
}
コード例 #25
0
ファイル: World.cpp プロジェクト: gabrieljt/learn-sfml
World::World(sf::RenderWindow& window)
: mWindow(window)
, mWorldView(window.getDefaultView())
, mTextures()
, mSceneGraph()
, mSceneLayers()
, mWorldBounds(
    0.f,                                                // left X position
    0.f,                                                // top y position
    mWorldView.getSize().x,                             // width
    20000.f)                                            // height
, mSpawnPosition(   
    mWorldView.getSize().x / 2.f,                       // X
    mWorldBounds.height - mWorldView.getSize().y / 2.f) // Y
, mScrollSpeed(-50.f)
, mPlayerAircraft(nullptr)
{
    loadTextures();
    buildScene();

    mWorldView.setCenter(mSpawnPosition);
}
コード例 #26
0
ファイル: ExampleScene2.cpp プロジェクト: iPruch/X-GS
ExampleScene2::ExampleScene2(sf::RenderWindow& window, xgs::SceneManager& sceneManager)
: Scene(window, sceneManager)
, mTransitionState(none)
, mTransitionTime(0)
, mTransitionDuration(ONE_SECOND*2)
, mFadingRectangle()
, mFontManager()
, mTextureManager()
{
	//std::cout << "ExampleScene2 constructor\n";
	
	// Load resources here (RAII)
	loadResources();
	
	// Build the scene graph
	buildScene();
	
	// Some configuration
	mText.setFont(mFontManager.get(Fonts::Sansation, FontManager::Global));
	mText.setPosition(mWindow.getView().getSize().x / 2.5f, 5.f);
	mText.setCharacterSize(20);
	mText.setColor(sf::Color::White);
	mText.setString("Example Scene 2 \n B - Back to previous scene \n Arrows/WASD - Move player");
	
	// Begin in transition
	mTransitionState = in;
	
	// Set the rectangle's size. This rectangle is used for the transition effect.
	mFadingRectangle.setSize(sf::Vector2f(mWindow.getView().getSize().x, mWindow.getView().getSize().y));
	mFadingRectangle.setFillColor(sf::Color(0, 0, 0, 255));
	
	// Set the background
	mTextureManager.get(Textures::ExampleBackground).setRepeated(true);
	mBackground.setTexture(&mTextureManager.get(Textures::ExampleBackground));
	mBackground.setTextureRect(sf::IntRect(0, 0, mWindow.getView().getSize().x, mWindow.getView().getSize().y));
	mBackground.setSize(sf::Vector2f(mWindow.getView().getSize().x, mWindow.getView().getSize().y));
}
コード例 #27
0
ファイル: World.cpp プロジェクト: MlLHoUzE/SFMLPlaneGame
World::World(sf::RenderTarget& outputTarget, FontHolder& fonts, SoundPlayer& sounds, int level)	//needs level passed in to change how the world creates
: mTarget(outputTarget)
, mSceneTexture()
, mWorldView(outputTarget.getDefaultView())
, mTextures() 
, mFonts(fonts)
, mSounds(sounds)
, mSceneGraph()
, mSceneLayers()
, mWorldBounds(0.f, 0.f, mWorldView.getSize().x, 5000.f)
, mSpawnPosition(mWorldView.getSize().x / 2.f, mWorldBounds.height - mWorldView.getSize().y / 2.f)
, mScrollSpeed(-50.f)
, mPlayerAircraft(nullptr)
, mEnemySpawnPoints()
, mActiveEnemies()
{
	mSceneTexture.create(mTarget.getSize().x, mTarget.getSize().y);

	loadTextures();
	buildScene(level);	//pass the level into the build scene to change number of enemies

	// Prepare the view
	mWorldView.setCenter(mSpawnPosition);
}
コード例 #28
0
ファイル: Example.cpp プロジェクト: YoutaVen/Vulkan
VkBool32 Example::buildResources(const vkts::IUpdateThreadContext& updateContext)
{
	VkResult result;

	//

	auto lastSwapchain = swapchain;

	VkSwapchainKHR oldSwapchain = lastSwapchain.get() ? lastSwapchain->getSwapchain() : VK_NULL_HANDLE;

	swapchain = vkts::wsiSwapchainCreate(initialResources->getPhysicalDevice()->getPhysicalDevice(), initialResources->getDevice()->getDevice(), 0, surface->getSurface(), VKTS_NUMBER_BUFFERS, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_SHARING_MODE_EXCLUSIVE, 0, nullptr, VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, VK_TRUE, oldSwapchain);

	if (!swapchain.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not create swap chain.");

		return VK_FALSE;
	}

    //

    swapchainImagesCount = (uint32_t)swapchain->getAllSwapchainImages().size();

    if (swapchainImagesCount == 0)
    {
        vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not get swap chain images count.");

        return VK_FALSE;
    }

    swapchainImageView = vkts::SmartPointerVector<vkts::IImageViewSP>(swapchainImagesCount);
    framebuffer = vkts::SmartPointerVector<vkts::IFramebufferSP>(swapchainImagesCount);
    cmdBuffer = vkts::SmartPointerVector<vkts::ICommandBuffersSP>(swapchainImagesCount);

    //

	if (lastSwapchain.get())
	{
		lastSwapchain->destroy();
	}

	//

	if (!buildRenderPass())
	{
		return VK_FALSE;
	}

	if (!buildPipeline())
	{
		return VK_FALSE;
	}

	//

	vkts::ICommandBuffersSP updateCmdBuffer = vkts::commandBuffersCreate(initialResources->getDevice()->getDevice(), commandPool->getCmdPool(), VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1);

	if (!updateCmdBuffer.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not create command buffer.");

		return VK_FALSE;
	}


	result = updateCmdBuffer->beginCommandBuffer(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, VK_NULL_HANDLE, 0, VK_NULL_HANDLE, VK_FALSE, 0, 0);

	if (result != VK_SUCCESS)
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not begin command buffer.");

		return VK_FALSE;
	}

    for (uint32_t index = 0; index < swapchain->getMinImageCount(); index++)
    {
        swapchain->cmdPipelineBarrier(updateCmdBuffer->getCommandBuffer(), 0, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, index);
    }

	if (!buildDepthTexture(updateCmdBuffer))
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not build texture.");

		return VK_FALSE;
	}

	VkBool32 doUpdateDescriptorSets = VK_FALSE;

	if (!scene.get())
	{
		if (!buildScene(updateCmdBuffer))
		{
			vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not build scene.");

			return VK_FALSE;
		}

		doUpdateDescriptorSets = VK_TRUE;
	}

	result = updateCmdBuffer->endCommandBuffer();

	if (result != VK_SUCCESS)
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not end command buffer.");

		return VK_FALSE;
	}


	VkSubmitInfo submitInfo;

	memset(&submitInfo, 0, sizeof(VkSubmitInfo));

	submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;

	submitInfo.waitSemaphoreCount = 0;
	submitInfo.pWaitSemaphores = nullptr;
	submitInfo.commandBufferCount = updateCmdBuffer->getCommandBufferCount();
	submitInfo.pCommandBuffers = updateCmdBuffer->getCommandBuffers();
	submitInfo.signalSemaphoreCount = 0;
	submitInfo.pSignalSemaphores = nullptr;

	result = initialResources->getQueue()->submit(1, &submitInfo, VK_NULL_HANDLE);

	if (result != VK_SUCCESS)
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not submit queue.");

		return VK_FALSE;
	}

	result = initialResources->getQueue()->waitIdle();

	if (result != VK_SUCCESS)
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not wait for idle queue.");

		return VK_FALSE;
	}

	updateCmdBuffer->destroy();

	//

	if (doUpdateDescriptorSets)
	{
		if (!updateDescriptorSets())
		{
			return VK_FALSE;
		}

		if (scene.get())
		{
			scene->updateDescriptorSetsRecursive(VKTS_BINDING_UNIFORM_BINDING_COUNT, writeDescriptorSets);
		}
	}

	if (!buildDepthStencilImageView())
	{
		return VK_FALSE;
	}

	//

	for (int32_t i = 0; i < (int32_t)swapchainImagesCount; i++)
	{
		if (!buildSwapchainImageView(i))
		{
			return VK_FALSE;
		}

		if (!buildFramebuffer(i))
		{
			return VK_FALSE;
		}

		if (!buildCmdBuffer(i))
		{
			return VK_FALSE;
		}
	}

	return VK_TRUE;
}
コード例 #29
0
ファイル: RayTracer.c プロジェクト: geoffkflee/D18
int main(int argc, char *argv[])
{
  // Main function for the raytracer. Parses input parameters,
  // sets up the initial blank image, and calls the functions
  // that set up the scene and do the raytracing.
  struct image *im; // Will hold the raytraced image
  struct view *cam; // Camera and view for this scene
  int sx;   // Size of the raytraced image
  int antialiasing; // Flag to determine whether antialiaing is enabled or disabled
  char output_name[1024]; // Name of the output file for the raytraced .ppm image
  struct point3D e;   // Camera view parameters 'e', 'g', and 'up'
  struct point3D g;
  struct point3D up;
  double du, dv;      // Increase along u and v directions for pixel coordinates
  struct point3D pc,d;    // Point structures to keep the coordinates of a pixel and
        // the direction or a ray
  struct ray3D *ray;    // Structure to keep the ray from e to a pixel
  // struct colourRGB col;    // Return colour for raytraced pixels
  struct colourRGB background;   // Background colour
  int i,j;      // Counters for pixel coordinates
  unsigned char *rgbIm;

  if (argc<5)
  {
    fprintf(stderr,"RayTracer: Can not parse input parameters\n");
    fprintf(stderr,"USAGE: RayTracer size rec_depth antialias output_name\n");
    fprintf(stderr,"   size = Image size (both along x and y)\n");
    fprintf(stderr,"   rec_depth = Recursion depth\n");
    fprintf(stderr,"   antialias = A single digit, 0 disables antialiasing. Anything else enables antialiasing\n");
    fprintf(stderr,"   output_name = Name of the output file, e.g. MyRender.ppm\n");
    exit(0);
  }
  sx=atoi(argv[1]);
  MAX_DEPTH=atoi(argv[2]);
  if (atoi(argv[3])==0) antialiasing=0; else antialiasing=1;
    strcpy(&output_name[0],argv[4]);

  fprintf(stderr,"Rendering image at %d x %d\n",sx,sx);
  fprintf(stderr,"Recursion depth = %d\n",MAX_DEPTH);
  if (!antialiasing) fprintf(stderr,"Antialising is off\n");
  else  fprintf(stderr,"Antialising is on\n");
  fprintf(stderr,"Output file name: %s\n",output_name);

  object_list=NULL;
  light_list=NULL;
  texture_list=NULL;

  // Allocate memory for the new image
  im=newImage(sx, sx);
  if (!im)
  {
    fprintf(stderr,"Unable to allocate memory for raytraced image\n");
    exit(0);
  }
  else rgbIm=(unsigned char *)im->rgbdata;

  ///////////////////////////////////////////////////
  // TO DO: You will need to implement several of the
  //        functions below. For Assignment 3, you can use
  //        the simple scene already provided. But
  //        for Assignment 4 you need to create your own
  //        *interesting* scene.
  ///////////////////////////////////////////////////
  buildScene();   // Create a scene. This defines all the
      // objects in the world of the raytracer

  //////////////////////////////////////////
  // TO DO: For Assignment 3 you can use the setup
  //        already provided here. For Assignment 4
  //        you may want to move the camera
  //        and change the view parameters
  //        to suit your scene.
  //////////////////////////////////////////

  // Mind the homogeneous coordinate w of all vectors below. DO NOT
  // forget to set it to 1, or you'll get junk out of the
  // geometric transformations later on.

  // Camera center is at (0,0,-1)
  e.px=0;
  e.py=0;
  e.pz=-1;
  e.pw=1;

  // To define the gaze vector, we choose a point 'pc' in the scene that
  // the camera is looking at, and do the vector subtraction pc-e.
  // Here we set up the camera to be looking at the origin.
  g.px=0-e.px;
  g.py=0-e.py;
  g.pz=0-e.pz;
  g.pw=1;
  // In this case, the camera is looking along the world Z axis, so
  // vector w should end up being [0, 0, -1]

  // Define the 'up' vector to be the Y axis
  up.px=0;
  up.py=1;
  up.pz=0;
  up.pw=1;

  // Set up view with given the above vectors, a 4x4 window,
  // and a focal length of -1 (why? where is the image plane?)
  // Note that the top-left corner of the window is at (-2, 2)
  // in camera coordinates.
  cam=setupView(&e, &g, &up, -1, -2, 2, 4);

  if (cam==NULL)
  {
    fprintf(stderr,"Unable to set up the view and camera parameters. Our of memory!\n");
    cleanup(object_list,light_list, texture_list);
    deleteImage(im);
    exit(0);
  }

  // Set up background colour here
  background.R=0;
  background.G=0;
  background.B=0;

  // Do the raytracing
  //////////////////////////////////////////////////////
  // TO DO: You will need code here to do the raytracing
  //        for each pixel in the image. Refer to the
  //        lecture notes, in particular, to the
  //        raytracing pseudocode, for details on what
  //        to do here. Make sure you undersand the
  //        overall procedure of raytracing for a single
  //        pixel.
  //////////////////////////////////////////////////////
  du=cam->wsize/(sx-1);   // du and dv. In the notes in terms of wl and wr, wt and wb,
  dv=-cam->wsize/(sx-1);    // here we use wl, wt, and wsize. du=dv since the image is
        // and dv is negative since y increases downward in pixel
        // coordinates and upward in camera coordinates.
  colourRGB col;
  point3D origin;
  point3D direction;
  ray3D initialRay;
  colourRGB total;
  int offset;
  int aaSamples;
  fprintf(stderr,"View parameters:\n");
  fprintf(stderr,"Left=%f, Top=%f, Width=%f, f=%f\n",cam->wl,cam->wt,cam->wsize,cam->f);
  fprintf(stderr,"Camera to world conversion matrix (make sure it makes sense!):\n");
  printmatrix(cam->C2W);
  fprintf(stderr,"World to camera conversion matrix:\n");
  printmatrix(cam->W2C);
  fprintf(stderr,"\n");
  fprintf(stderr,"Rendering row: ");
  #pragma omp parallel for schedule(dynamic,32) shared(rgbIm, object_list, light_list, texture_list) private(j)
  for (j=0;j<sx;j++)    // For each of the pixels in the image
  // for (j=2;j<3;j++)
  {
    fprintf(stderr,"%d/%d, ",j,sx);
    #pragma omp parallel for private(origin, direction, col, initialRay, i, aaSamples, offset, total)
    for (i=0;i<sx;i++)
    // for (i=2;i<3;i++)
    {
      if (!antialiasing){
        col.R = 0;
        col.G = 0;
        col.B = 0;
        // = newPoint(cam->wl+i*du,cam->wt+j*dv,cam->f);
        origin.px = cam->wl+i*du;
        origin.py = cam->wt+j*dv;
        origin.pz = cam->f;
        origin.pw = 1.0;
        matVecMult(cam->C2W, &origin);
        // Construct direction vector using Pij - e
        // point3D direction;// = newPoint(origin->px,origin->py, origin->pz);
        direction.px = origin.px;
        direction.py = origin.py;
        direction.pz = origin.pz;
        direction.pw = 1.0;
        subVectors(&e, &direction);
        normalize(&direction);
        // Construct ray using both origin and direction.
        // ray3D initialRay;// = newRay(origin, direction);
        initialRay.p0 = origin;
        initialRay.d = direction;
        // Setting up colors.
        // col = (struct colourRGB *)calloc(1,sizeof(struct colourRGB));

        // Tracing ray
        rayTrace(&initialRay, 1, &col, NULL);
        offset = (sx * j * 3) + (i * 3);
        *(rgbIm + offset + 0) = col.R*255;
        *(rgbIm + offset + 1) = col.G*255;
        *(rgbIm + offset + 2) = col.B*255;
        // Tear down col struct.
        // free(col);
      } else {
        total.R = 0;
        total.G = 0;
        total.B = 0;
        for (aaSamples = 0; aaSamples < 20; aaSamples ++){
          col.R = 0;
          col.G = 0;
          col.B = 0;
          // point3D origin;// = newPoint(cam->wl+i*du,cam->wt+j*dv,cam->f);
          origin.px = cam->wl+(i+drand48()-0.5)*du;
          origin.py = cam->wt+(j+drand48()-0.5)*dv;
          origin.pz = cam->f;
          origin.pw = 1.0;
          matVecMult(cam->C2W, &origin);
          // Construct direction vector using Pij - e
          // point3D direction;// = newPoint(origin->px,origin->py, origin->pz);
          direction.px = origin.px;
          direction.py = origin.py;
          direction.pz = origin.pz;
          direction.pw = 1.0;
          subVectors(&e, &direction);
          normalize(&direction);
          // Construct ray using both origin and direction.
          // ray3D initialRay;// = newRay(origin, direction);
          initialRay.p0 = origin;
          initialRay.d = direction;
          // Setting up colors.
          // col = (struct colourRGB *)calloc(1,sizeof(struct colourRGB));
          // Tracing ray
          rayTrace(&initialRay, 1, &col, NULL);
          total.R += col.R;
          total.G += col.G;
          total.B += col.B;
        }
        offset = (sx * j * 3) + (i * 3);
        total.R = total.R / 20 * 255.0;
        total.G = total.G / 20 * 255.0;
        total.B = total.B / 20 * 255.0;
        *(rgbIm + offset + 0) = total.R;
        *(rgbIm + offset + 1) = total.G;
        *(rgbIm + offset + 2) = total.B;
      }
    } // end for i
  } // end for j
  
  fprintf(stderr,"\nDone!\n");

  // Output rendered image
  imageOutput(im,output_name);

  // Exit section. Clean up and return.
  cleanup(object_list,light_list,texture_list);   // Object, light, and texture lists
  deleteImage(im);          // Rendered image
  free(cam);            // camera view
  exit(0);
}
コード例 #30
0
ファイル: Renderer.cpp プロジェクト: kikko/ofxEmbree
void Renderer::clearScene(bool bRebuild) {
    prims.erase(prims.begin(), prims.end());
    if(bRebuild) buildScene();
}