Exemple #1
0
void
TestScene5::runOgre()
{
	// initialize framework & open window
	Ogre::Root* root = new Ogre::Root();
	root->restoreConfig();
	root->initialise(false);
	auto window = root->createRenderWindow("Ogre RenderWindow", 800, 600, false);
	auto sceneMgr = root->createSceneManager(Ogre::ST_GENERIC);
	// adjust camera
	auto cam1 = sceneMgr->createCamera("cam1");
	auto camNode1 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode1");
	cam1->setNearClipDistance(5);
	camNode1->attachObject(cam1);
	camNode1->setPosition(100, 100, 100);
	camNode1->lookAt(Ogre::Vector3(-1, -1, -1), Ogre::Node::TS_LOCAL);
	window->addViewport(cam1);
	// load & integrate model
	root->addResourceLocation("./resources/Ogre", "FileSystem");
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	auto model = sceneMgr->createEntity("model", "alexandria.mesh");
	auto modelNode = sceneMgr->getRootSceneNode()->createChildSceneNode();
	modelNode->attachObject(model);
	// position model
	modelNode->setPosition(-100, -100, -100);
	// loop
	runOgreLoop(root);
}
Exemple #2
0
void WebAPI::setWebView( WebView *view )
{
    WebPage *page = view->page();
    frame = page->mainFrame();
    attachObject();
    connect( frame, SIGNAL(javaScriptWindowObjectCleared()),
             this,  SLOT(attachObject()) );
}
Exemple #3
0
void BrowserApi::setWebView(QWebView *view)
{
    QWebPage *page = view->page();
    m_frame = page->mainFrame();

    attachObject();
    connect(m_frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(attachObject()));
}
void CellDrawActor< C >::gridDraw(
    const GridDrawMessage& m
) {
    // Левый нижний угол - центр координат (порт - матрица).
    // Нумерация строк / столбцов матрицы совпадает с напраслением
    // осей OX / OZ.

    // Не рисуем сетку, если она уже есть
    const std::string sceneName = "CellDrawActor::gridDraw::Scene";
    const bool virgin = m.sm->hasSceneNode( sceneName );
    if ( !virgin ) {

        // Каждому образу - свой холст (общая сцена)
        auto scene = m.sm->getRootSceneNode()->createChildSceneNode( sceneName );

        // Ячейки смещаем на полмасштаба влево-вниз
        const auto halfCell = m.scale / 2.0f;

        auto mo = m.sm->createManualObject();
        mo->begin( "smokeport2d/grid", Ogre::RenderOperation::OT_LINE_LIST );

        const float side = (float)m.size * m.scale;
        for (size_t i = 0; i <= m.size; ++i) {
            // OX
            const float z  = (float)i * m.scale - halfCell;
            mo->position( Ogre::Vector3( -halfCell, 0.0f, z ) );
            mo->position( Ogre::Vector3( side - halfCell, 0.0f, z ) );
            // OZ
            const float x  = (float)i * m.scale - halfCell;
            mo->position( Ogre::Vector3( x, 0.0f, -halfCell  ) );
            mo->position( Ogre::Vector3( x, 0.0f, side - halfCell ) );
        }

        mo->end();

        // Каждому образу - свой холст
        auto moScene = scene->createChildSceneNode( "CellDrawActor::gridDraw::MOScene::Scene" );
        moScene->attachObject( mo );
        //childScene->setPosition( Ogre::Vector3::ZERO );

        // Отмечаем первую ячейку (центр координат)
        auto centerScene = scene->createChildSceneNode( "CellDrawActor::gridDraw::CenterScene::Scene" );
        auto point = m.sm->createEntity( "sphere.mesh" );
        //centerScene->setPosition( Ogre::Vector3::ZERO );
        centerScene->attachObject( point );
        //centerScene->setScale( Ogre::Vector3( 1.0f / 20.0f ) );

    } // if ( !virgin )

}
Exemple #5
0
void fakeHaskell()
{
    DemoApp* da = initDemo();
    
    Ogre::SceneManager* sm = getSceneManager();
    Ogre::SceneNode* rnode = getRootSceneNode(sm);
    
    /*	OgreFramework::getSingletonPtr()->m_pSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox");
     
     m_pCubeEntity = OgreFramework::getSingletonPtr()->m_pSceneMgr->createEntity("Cube", "ogrehead.mesh");
     m_pCubeNode = OgreFramework::getSingletonPtr()->m_pSceneMgr->getRootSceneNode()->createChildSceneNode("CubeNode");
     m_pCubeNode->attachObject(m_pCubeEntity);
     
     m_pCube2E = OgreFramework::getSingletonPtr()->m_pSceneMgr->createEntity("Steve", Ogre::SceneManager::PT_CUBE);
     m_pCube2N = OgreFramework::getSingletonPtr()->m_pSceneMgr->getRootSceneNode()->createChildSceneNode("SteveN");
     m_pCube2N->attachObject(m_pCube2E);*/
    
    setSkybox(sm, true, "Examples/SpaceSkyBox");
    
    Ogre::Entity* cubeEntity = createEntity(sm, "Cube", "ogrehead.mesh");
    Ogre::SceneNode* cubeNode = createChildSceneNode(rnode, "CubeNode");
    attachObject(cubeNode, cubeEntity);
    
    finishSetupAndRun(da);
}
Exemple #6
0
void ScriptApi::setWebView( View *view )
{
    m_view = view;
    attachObject();
    connect( m_view->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(attachObject()) );
    installGlobals();
}
bool xSceneHelperDrawableNode::attachDrawElement(IDrawElement* pDrawElement)
{
	if(pDrawElement == NULL)
		return false;
     xSceneHelperDrawable* pObject = new xSceneHelperDrawable(m_pScene , 0);
	 pObject->setDrawElement(pDrawElement,0);
	 return attachObject(pObject);
}
Exemple #8
0
void
TestScene12::runOgre()
{
	// initialize framework & open window
	Ogre::Root* root = new Ogre::Root();
	root->restoreConfig();
	root->initialise(false);
	auto window = root->createRenderWindow("Ogre RenderWindow", 800, 600, false);
	auto sceneMgr = root->createSceneManager(Ogre::ST_GENERIC);
	// adjust camera
	auto cam1 = sceneMgr->createCamera("cam1");
	auto camNode1 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode1");
	cam1->setNearClipDistance(5);
	camNode1->attachObject(cam1);
	camNode1->setPosition(Ogre::Vector3(100, 100, 100));
	camNode1->lookAt(Ogre::Vector3(-1, -1, -1), Ogre::Node::TS_LOCAL);
	window->addViewport(cam1);
	// load & integrate model
	root->addResourceLocation("./resources/Ogre", "FileSystem");
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	Mesh_Cube M(1);
	M.createMesh("cube");
	Ogre::SceneNode* groups[ROWS];
	std::list<Ogre::SceneNode*> nodes;
	for (int i = 0; i < ROWS; i++)
	{
		groups[i] = sceneMgr->getRootSceneNode()->createChildSceneNode();
		nodes.push_back(groups[i]);
	}
	for (int i = 0; i < ROWS * COLS; i++)
	{
		auto node = groups[i % ROWS]->createChildSceneNode();
		node->attachObject(sceneMgr->createEntity(std::string("model") + boost::lexical_cast<std::string>(i), "cube"));
		node->setPosition(
			camNode1->getOrientation() * -Ogre::Vector3::UNIT_X * LEFT(i)
			+ camNode1->getOrientation() * Ogre::Vector3::UNIT_Y * UP(i)
		);
	}
	root->addFrameListener(new MoveObjectTask_Ogre12(nodes));
	// loop
	runOgreLoop(root);
}
/*===========================================================================*/
void StochasticUniformGridRenderer::Engine::create( kvs::ObjectBase* object, kvs::Camera* camera, kvs::Light* light )
{
    kvs::StructuredVolumeObject* volume = kvs::StructuredVolumeObject::DownCast( object );

    attachObject( object );
    createRandomTexture();
    this->create_shader_program( volume );
    this->create_volume_texture( volume );
    this->create_transfer_function_texture();
    this->create_bounding_cube_buffer( volume );
    this->create_framebuffer( camera->windowWidth(), camera->windowHeight() );
}
Exemple #10
0
  void CameraWrapper::createCamera(const std::string& name)
  {
    if(mObjectId == name && mObject) {
      return;
    }

    mObjectId = name;
    LOG(TRACE) << "Create camera with id " << name;
    // toss camera object to the movable wrapper
    mObject = mSceneManager->createCamera(name);
    mObject->setListener(this);
    attachObject(mObject);
  }
Exemple #11
0
void Ogrenoid::createScene(void)
{
	m_theBall = new TheBall(m_sceneManager);
	m_playerPaddle = new Paddle(m_sceneManager);

	//Left wall
	auto leftWallEntity = m_sceneManager->createEntity("leftWall", "cube.mesh");
	auto leftWallNode = m_sceneManager->getRootSceneNode()->createChildSceneNode("leftWall");
	leftWallNode->attachObject(leftWallEntity);
	leftWallNode->setPosition(-110, 0, 0);
	leftWallNode->setScale(2.0, 100.00, 1.0);

	//Right wall
	auto rightWallEntity = m_sceneManager->createEntity("rightWall", "cube.mesh");
	auto rightWallNode = m_sceneManager->getRootSceneNode()->createChildSceneNode("rightWall");
	rightWallNode->attachObject(rightWallEntity);
	rightWallNode->setPosition(110, 0, 0);
	rightWallNode->setScale(2.0, 100.00, 1.0);

	//Upper wall
	auto upperWallEntity = m_sceneManager->createEntity("upperWall", "cube.mesh");
	auto upperWallNode = m_sceneManager->getRootSceneNode()->createChildSceneNode("upperWall");
	upperWallNode->attachObject(upperWallEntity);
	upperWallNode->setPosition(0, 82, 0);
	upperWallNode->setScale(190.0, 2.0, 1.0);

	//Bottom wall
	auto bottomWallEntity = m_sceneManager->createEntity("bottomWall", "cube.mesh");
	auto bottomWallNode = m_sceneManager->getRootSceneNode()->createChildSceneNode("bottomWall");
	bottomWallNode->attachObject(bottomWallEntity);
	bottomWallNode->setPosition(0, -82, 0);
	bottomWallNode->setScale(190.0, 2.0, 1.0);

	//Ambient light
	m_sceneManager->setAmbientLight(Ogre::ColourValue(0.75, 0.75, 0.75));
	Ogre::Light* lightPtr = m_sceneManager->createLight("ambientLight");
	lightPtr->setPosition(0, 0, 50);
}
Exemple #12
0
//-------------------------------------------------------
void Ground::LoadFromHeightMap(std::shared_ptr<Ogre::Image> hmap, Ogre::SceneNode* parentNode)
{
    mImage = hmap;
    Ogre::Box box = Ogre::Box(0, 0, mImage->getWidth(), mImage->getHeight());

    mRootNode = parentNode->createChildSceneNode();
    
    mGlobalBoundingBox.setNull();

    Ogre::Material* groundMaterial = CreateGroundMaterialTextured("Material/" + CLASS_NAME + "/Textured", mImage.get());
    
    static const float VERTEX_STEP = 1.0f;
    static const float HEIGHT_STEP = 8.0f;

    float offsetX = GROUND_SIZE * VERTEX_STEP / 2.0f;
    float offsetY = GROUND_SIZE * VERTEX_STEP / 2.0f;

    size_t width  = mImage->getWidth();
    size_t height = mImage->getHeight();

    float texStep = 1.0f / REGIONS_NUMBER;

    size_t texRegionWidth  = static_cast<size_t>(std::ceil(static_cast<float>(width) / REGIONS_NUMBER));
    size_t texRegionHeight = static_cast<size_t>(std::ceil(static_cast<float>(height) / REGIONS_NUMBER));
    for (size_t y = 0; y < REGIONS_NUMBER; ++y)
    {
        size_t top = y * texRegionHeight;
        for (size_t x = 0; x < REGIONS_NUMBER; ++x)
        {
            size_t left = x * texRegionWidth;
            Ogre::Box roi = Ogre::Box(left, height - std::min(top + texRegionHeight + 1, height), std::min(left + texRegionWidth + 1, width), height - top);
                
            Ogre::MeshPtr mesh = CreateRegion(y * REGIONS_NUMBER + x, groundMaterial->getName(), roi,
                Ogre::Vector3(x * VERTEX_STEP * REGION_SIZE - offsetX, y * VERTEX_STEP * REGION_SIZE - offsetY, 0.0f),
                Ogre::Vector3(VERTEX_STEP, VERTEX_STEP, HEIGHT_STEP),
                Ogre::Vector2(x * texStep, 1.0f - (y + 1) * texStep));

            Ogre::Entity* entity = mSceneManager->createEntity(mesh);
            
            auto node = mRootNode->createChildSceneNode();
            node->attachObject(entity);
            node->showBoundingBox(true);

            mGlobalBoundingBox.merge(entity->getBoundingBox());

            mEntities.push_back(entity);
        }
    }
}
Exemple #13
0
	void GOAPapp::initCamera(float asp) {
		//camera
		m_pCamera.reset(new Camera("cam1"));
		auto cameraNode = new Node("cameraNode1");
		cameraNode->attachObject(m_pCamera.get());

		m_pCamera->setLocalRotation(vec3f(-PI / 2, 0, 0));
		m_pCamera->setPosition(vec3f(20, 40, 6));
		m_pCamera->updateViewMatrix();
		m_pCamera->setProjection(45.0f, asp, 0.1f, 10000.f);
		if (root)
			root->addAChindNode(cameraNode);

		m_pCamera->applyImpulse(vec3f());
	}
Exemple #14
0
WebView::WebView(QWidget *parent) :
    QWebView(parent)
    , m_page(new WebPage(this))
{
    setPage(m_page);
    page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    connect( m_page->mainFrame() , SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(attachObject()) );

    connect(this,SIGNAL(loadFinished(bool)),this,SLOT(loadFinished(bool)));
    connect(this,SIGNAL(selectionChanged()),this,SLOT(doNothing()));
    connect(this,SIGNAL(urlChanged(QUrl)),this,SLOT(urlChanged(QUrl)));
    enableSettings();
    attachObject();
    //setContextMenuPolicy(Qt::PreventContextMenu);
}
Exemple #15
0
Brush::Brush(Ogre::TerrainGroup* group, Ogre::SceneManager* sceneMgr, QUndoStack* stack)
: QObject(),
 m_mode(Brush::M_NONE),
 m_stack(stack),
 m_drawer(new BrushDrawer("Brush", group)),
 m_group(group),
 m_currentCommand(nullptr),
 m_enabled(true)
{
    auto rootNode = sceneMgr->getRootSceneNode();
    rootNode->attachObject(m_drawer);
    settings_t def { 2.0f, 5.0f, 0.0f };
    m_settings[M_HEIGHT_FLATTEN] = def;
    m_settings[M_HEIGHT_SMOOTH] = def;
    m_settings[M_HEIGHT_RAISE] = def;
    m_settings[M_LAYER_PAINT] = def;
}
Exemple #16
0
  void Player::spawn( const Vector3& position, const Quaternion& orientation )
  {
    Character::spawn( position, orientation );

    mMesh = Procedural::CapsuleGenerator().setHeight( mHeight ).setRadius( mRadius ).realizeMesh( "playerStandCapsule" );

    mItem = Locator::getGraphics().getScene()->createItem( mMesh );
    mItem->setQueryFlags( SceneQueryFlag_Character );
    mItem->setDatablock( "Developer/Placeholder/Player" );
    mItem->setCastShadows( true );
    mNode->attachObject( mItem );

    auto skull = Locator::getGraphics().getScene()->createEntity( "skull_02.mesh" );
    auto snode = mNode->createChildSceneNode( Ogre::SCENE_DYNAMIC, Vector3( 0, 1.5f, 0 ) );
    skull->setQueryFlags( SceneQueryFlag_Camera );
    snode->attachObject( skull );
  }
Exemple #17
0
void
TestScene3::runOgre()
{
	// initialize framework & open window
	Ogre::Root* root = new Ogre::Root();
	root->restoreConfig();
	root->initialise(false);
	auto window = root->createRenderWindow("Ogre RenderWindow", 800, 600, false);
	auto sceneMgr = root->createSceneManager(Ogre::ST_GENERIC);
	// adjust camera
	auto cam1 = sceneMgr->createCamera("cam1");
	auto camNode1 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode1");
	cam1->setNearClipDistance(5);
	camNode1->attachObject(cam1);
	camNode1->setPosition(100, 100, 100);
	camNode1->lookAt(Ogre::Vector3(-1, -1, -1), Ogre::Node::TS_LOCAL);
	window->addViewport(cam1);
	// loop
	runOgreLoop(root);
}
Exemple #18
0
void Layer::gradientPointDraw(
    Ogre::SceneManager* sm,
    Ogre::SceneNode* sn,
    const surface2d_t& gp
) const {

    assert( (gp.size() > 1) && "Точки перепада не получены." );
    assert( (gp.size() == feature.countGradient)
        && "Количество полученных точек перепада не соотв. ожидаемому." );

    // Создаём образ

    // Каждую точку представим в виде меша
    for (auto itr = gp.cbegin(); itr != gp.cend(); ++itr) {
        const coord2d_t coord = *itr;
        auto point = sm->createEntity( "sphere.mesh" );
        auto childScene = sn->createChildSceneNode();
        childScene->attachObject( point );
        childScene->setPosition( coord.get<0>(),  0.0f,  coord.get<1>() );
    }


    // Соединим точки
    auto image = sm->createManualObject();
    int i = 0;

    image->begin( "landscape25/red", Ogre::RenderOperation::OT_LINE_STRIP );
    for (auto itr = gp.cbegin(); itr != gp.cend(); ++itr) {
        const coord2d_t coord = *itr;
        image->position( coord.get<0>(),  0.0f,  coord.get<1>() );
        image->index( i ); ++i;
    }
    image->end();

    image->setCastShadows( false );

    sn->createChildSceneNode()->attachObject( image );

}
Exemple #19
0
TestMenuState::TestMenuState(XE::XEngine& engine, bool replace)
	: XE::XEState(engine, replace)
{
	LOG(plog::info) << "InitState - Initialization";

	auto ctrlSystem = engine.getScene().systems.add<XET::TestControllerSystem>(engine);
	
	engine.getScene().create(1);

	XE::FileResource fres;
	engine.getResourceMgr().getBufferFromFile("dbData/UI/TestAtlas.fbbin", fres);
	engine.getGraphicsManager().getGUIRenderer().loadAtlas(fres.buffer); // "dbData/UI/TestAtlas.fbbin"); // ("XEngine", "General"); //texturemanager initialized in createrenderwindow!!!

	/*if (!engine.getGraphicsManager().getGUIRenderer().loadAtlas("dbData/UI/TestAtlas.fbbin"))
		return;*/
	
	//create an empty entity for free style camera
	entityx::Entity entity = engine.getScene().entities.create();
	XE::BodyComponent* body = entity.assign<XE::BodyComponent>().get();
	XE::CameraRenderable* camRenderable = entity.assign<XE::CameraRenderable>(0, engine.getGraphicsManager(), engine.getScene()).get();
	XE::CameraFreeComponent* camera = entity.assign<XE::CameraFreeComponent>(*camRenderable, *body).get();
	
	body->setPosition(0,10,0);

	XET::TestControllerComponent* ctrl = entity.assign<XET::TestControllerComponent>(0,engine,  engine.getGraphicsManager().getWindow(), true).get();

	XE::ScreenComponent* screenComp = entity.assign<XE::ScreenComponent>(*camRenderable, engine.getGraphicsManager().getWindow()).get(); //createScreen(); //workspace needed for screen
	screenComp->mUIStateManager.get()->addUIState(screenComp->mUIStateManager.get()->build <XE::UIDebug>(NetMsg::UIStateId_Stats, entity, true));
//	screenComp->mUIStateManager.addUIState(screenComp->mUIStateManager.build <XE::UIConsole>(10, entity, true));//ctrl.createConsole();

	screenComp->mUIStateManager.get()->addUIState(screenComp->mUIStateManager.get()->build <UIState_1>(99, entity, true));//ctrl.createConsole();

	//XE::ScreenComponent* screenComp = entity.assign<XE::ScreenComponent>(*camRenderable, engine.getGraphicsManager().getWindowManager().getWindow(0)).get(); //createScreen(); //workspace needed for screen

	ctrlSystem->setBasicInputEvents(*ctrl);
	ctrl->setActionMap(*ctrl);

	m_engine.getGraphicsManager().getIntoRendererQueue().push([this, camRenderable]()
	{
		//XET::TestPostProcess pp(m_engine, *camRenderable);
		//	pp.createCustomTextures();

		m_engine.getResourceMgr()._t_initResourceGroup("TestGrp");

	//	pp.setupCompositor();
		//		pp.togglePostprocess("Bloom");

		//load gltf
		//	gltf::Asset asset;
		//	//gltf::load("F:/Projekte/coop/XGame/data/assets/Impact/impact_ground_1.gltf", asset);
		////gltf::load("F:/Projekte/coop/FrankE/data/assets/DamagedHelmet/DamagedHelmet.gltf", asset);
		//	gltf::load("F:/Projekte/coop/XGame/data/assets/Turricane/turicane_blendshapes.gltf", asset);
		//	//	gltf::load("F:/Projekte/coop/glTF-Sample-Models/2.0/AnimatedMorphCube/glTF/AnimatedMorphCube.gltf", asset);
		////gltf::load("F:/Projekte/coop/glTF-Sample-Models/2.0/DamagedHelmet/glTF/DamagedHelmet.gltf", asset);

		//	XE::XEMesh mesh;
		//	mesh.buildMesh(asset, m_engine.getGraphicsManager(), m_engine.getScene().getOgreSceneManager().__OgreSceneMgrPtr);

		gltf::Asset assetEmissive;
		gltf::load(m_engine.settings.resourceData.assetsFolder + "/DebugPack/material_ball/material_ball.gltf", assetEmissive);
		XE::XEMesh meshMaterialBall;
		meshMaterialBall.buildMesh(assetEmissive, "Ball 1", m_engine.getGraphicsManager(), m_engine.getScene().getOgreSceneManager().__OgreSceneMgrPtr);

		{
			Ogre::Item* item{ nullptr };
			item = m_engine.getScene().getOgreSceneManager().__OgreSceneMgrPtr->createItem(meshMaterialBall.m_ogreMesh, Ogre::SCENE_DYNAMIC);
			auto m_sceneNode = m_engine.getScene().getOgreSceneManager().__OgreSceneMgrPtr->getRootSceneNode(Ogre::SCENE_DYNAMIC)->createChildSceneNode(Ogre::SCENE_DYNAMIC);
			m_sceneNode->attachObject(item);
			item->setCastShadows(true);
			//do it at last! here the texture baking happens! needed for normal maps etc.
			if (meshMaterialBall.m_datablock)
				item->setDatablock(meshMaterialBall.m_datablock);

			m_sceneNode->setPosition(0, 10, 0);
			m_sceneNode->rotate(Ogre::Quaternion(Ogre::Degree(90), Ogre::Vector3(1, 0, 0))); // needed for blender exported meshes!
		}

		{
			Ogre::Item* item{ nullptr };
			item = m_engine.getScene().getOgreSceneManager().__OgreSceneMgrPtr->createItem(meshMaterialBall.m_ogreMesh, Ogre::SCENE_DYNAMIC);
			auto m_sceneNode = m_engine.getScene().getOgreSceneManager().__OgreSceneMgrPtr->getRootSceneNode(Ogre::SCENE_DYNAMIC)->createChildSceneNode(Ogre::SCENE_DYNAMIC);
			m_sceneNode->attachObject(item);
			item->setCastShadows(true);
			//do it at last! here the texture baking happens! needed for normal maps etc.

			Ogre::HlmsManager *hlmsManager = m_engine.getGraphicsManager().getRoot()->getHlmsManager();
			Ogre::HlmsUnlitDatablock* testdatablock = (Ogre::HlmsUnlitDatablock*)hlmsManager->getDatablock("BillBoardTest");
			testdatablock->setUseColour(true);
			testdatablock->setColour(Ogre::ColourValue(0, 1, 0, 1) * 1.5);

			item->setDatablock(testdatablock);

			m_sceneNode->setPosition(20, 10, 0);
			m_sceneNode->rotate(Ogre::Quaternion(Ogre::Degree(90), Ogre::Vector3(1, 0, 0))); // needed for blender exported meshes!
		}

	});

	LOG(XE::info) << "InitState - Initialized";
}
void CellDrawActor< C >::allDraw(
    const AllDrawMessage< C >& m
) {
    // Рисуем только если ещё не было нарисовано
    // или по просьбе "обновлять постоянно"
    const std::string sceneName = "CellDrawActor::allDraw::Scene";
    const std::string bsName = "CellDrawActor::allDraw::BillboardSet";

    // @test
    /*
    try {
        m.sm->getRootSceneNode()->removeAndDestroyChild( sceneName );
    } catch ( ... ) {
    }
    try {
        m.sm->destroyBillboardSet( bsName );
    } catch ( ... ) {
    }
    */

    if ( m.update || !m.sm->hasSceneNode( sceneName ) ) {

        // Каждому образу - свой холст (общая сцена)
        auto scene = m.sm->hasSceneNode( sceneName ) ?
            m.sm->getSceneNode( sceneName ) :
            m.sm->getRootSceneNode()->createChildSceneNode( sceneName );

        // Определяем общее кол-во элементов
        const size_t NM = m.N * m.M;

        // Готовим биллборды

        // Обращаются за отрисовкой первый раз?
        const bool virgin = m.sm->hasBillboardSet( bsName );
        Ogre::BillboardSet* bs = nullptr;
        if ( virgin ) {
            bs = m.sm->getBillboardSet( bsName );

        } else {
            // Один образ для всех ячеек
            // @todo Расширить кол-во образов.
            bs = m.sm->createBillboardSet( bsName, NM );
            bs->setAutoextend( true );
            const std::string nameMaterial = m.prefixMaterial + "0";
            bs->setMaterialName( nameMaterial );
            bs->setBillboardType( Ogre::BBT_PERPENDICULAR_COMMON );
            bs->setCommonUpVector( Ogre::Vector3::UNIT_Z );
            bs->setCommonDirection( -Ogre::Vector3::UNIT_Y );
            bs->setBillboardsInWorldSpace( true );
            bs->setBillboardOrigin( Ogre::BBO_CENTER );
            bs->setDefaultDimensions( m.scale, m.scale );
            bs->setUseAccurateFacing( false );
            scene->attachObject( bs );
        }

        // Визуализируем каждую ячейку

        /* - @todo Можно ускорить отрисовку > http://www.ogre3d.org/forums/viewtopic.php?f=2&t=11134&start=0
        Ogre::Billboard b = Ogre::Billboard( Ogre::Vector3::ZERO, bs );
        b.setColour( Ogre::ColourValue::White );
        b.setRotation( Ogre::Degree( (float)rand() ) );
        */

        //bs->beginBillboards();
        for (size_t z = 0; z < m.M; ++z) {
            for (size_t x = 0; x < m.N; ++x) {
                const coordInt2d_t coord( (int)x, (int)z );

                // Создадим образ ячейки с указанной координатой

                const int i = helper::ic( coord.get<0>(), coord.get<1>(), m.N, m.M );
                assert( (i != -1) && "Получена координата за пределами матрицы порта." );
                const C c = m.content[i];

                // Биллборд уже мог быть создан ранее
                const auto bi = helper::index( *bs, coord, m.scale );
                if (bi != -1) {
                    bs->removeBillboard( bi );
                }

                if (c.uid == 0) {
                    // Вакуум - отсутствие образа
                    continue;
                }
    
#if 0
                // - Медленно. Переписано через биллборды.
                /*
                const std::string name =
                    "smoke-pressure-"
                  + Ogre::StringConverter::toString( (int)c.pressure );
                */
                const std::string meshName = "sphere.mesh";
                /* - @todo Так ли каждый раз нужна новая сущность?
                const std::string entityName = meshName + ".entity";
                const bool has = sm->hasEntity( entityName );
                Ogre::Entity* image = has ?
                    sm->getEntity( entityName ) :
                    sm->createEntity( entityName, meshName );
                */
                Ogre::Entity* image = sm->createEntity( meshName );
                auto childScene = sn->createChildSceneNode();
                childScene->attachObject( image );
                // Координаты образа кратны масштабу
                childScene->setPosition(
                    (float)coord.get<0>() * scale,
                    0.0f,
                    (float)coord.get<1>() * scale
                );
                // Образ заполняет ячейку целиком
                //const Ogre::Vector3 fillScale( scale / image->getBoundingRadius() );
                //childScene->setScale( fillScale );
#endif

                // Работаем через биллборды
                // @source http://89.151.96.106/forums/viewtopic.php?f=10&t=60455

                // @todo Визаулизировать в зависимости от характеристики ячейки и соседей.

                // Позиционируем биллборд

                Ogre::Billboard* b = bs->createBillboard(
                    (float)coord.get<0>() * m.scale,
                    0.0f,
                    (float)coord.get<1>() * m.scale
                );
                b->setRotation( Ogre::Degree( (float)rand() ) );
                /*
                b.setPosition(
                    (float)coord.get<0>() * m.scale,
                    0.0f,
                    (float)coord.get<1>() * m.scale
                );
                bs->injectBillboard( b );
                */
                
                // @test
                //break;

            } // for (size_t x = 0; x < m.N; ++x)

        } // for (size_t z = 0; z < m.M; ++z)

        //bs->endBillboards();

    } // if ( m.update || !m.sm->hasSceneNode( sceneName ) )

}
Exemple #21
0
bool CLiftableObject::lift() {
	assert(m_eState == LOS_AT_DEFAULT_LOCATION);

	m_eState = LOS_LIFTED;
	sendCreateInnerObjectEvent(IOCE_LIFT);


    btRigidBody *pRB = btRigidBody::upcast(m_pCollisionObject);
    btRigidBody *pNewRB(NULL);
    assert(pRB);
    if (m_bRecreateOnLift) {

        Ogre::String meshFile;

        // create dynamic close of pRB -> pNewRB, and delete the other one in the next frame

        auto pSN = m_ObjectManager.getMap().getRootSceneNode()->createChildSceneNode();

        CPhysicsCollisionObject *pCO = m_ObjectManager.getMap().getPhysicsManager()->findCollisionShape(m_pCollisionObject->getCollisionShape());
        auto shape = pCO->getShape();
        meshFile = m_ObjectManager.getMap().getPhysicsManager()->getCollisionShapeKey(*pCO);

        float mass = 100.0f;
        btVector3 inertia;
        shape->calculateLocalInertia(mass, inertia);
        btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,
            new BtOgre::RigidBodyState(pSN, m_pCollisionObject->getWorldTransform(), btTransform(btQuaternion::getIdentity(), BtOgre::Convert::toBullet(-pCO->getOffset()))),
                shape,inertia);


        pNewRB = new btRigidBody(rbInfo);
        // object now belongs to player, so dont interact with each other


        // create the entity

        Ogre::Entity *pEnt = m_ObjectManager.getMap().getSceneManager()->createEntity(meshFile);
        pSN->attachObject(pEnt);

        //m_ObjectManager.getMap().destroyObjectsEntity(this, NULL, BtOgre::Convert::toOgre(pNewRB->getWorldTransform().getOrigin()));

        //m_ObjectManager.getMap().getPhysicsManager()->createLater(const_cast<btRigidBody*>(pNewRB));
        //m_ObjectManager.getMap().getPhysicsManager()->deleteLater(const_cast<btRigidBody*>(pRB));
        delete pRB->getMotionState();
        delete pRB;

        m_pCollisionObject = pNewRB;
        setAsUserPointer(pNewRB);
    }
    else {
        pNewRB = pRB;
    }
    assert(pNewRB);
    m_ObjectManager.getMap().getPhysicsManager()->getWorld()->removeCollisionObject(const_cast<btRigidBody*>(pRB));
    m_ObjectManager.getMap().getPhysicsManager()->getWorld()->addRigidBody(pNewRB, COL_DAMAGE_P, COL_STATIC | COL_WALL | COL_CHARACTER_N);

    // is there an linked object to delete on lift?
    Ogre::String sRemoveObjectOnLift(m_UserData.getStringUserData("removeObjectOnLift"));
    if (sRemoveObjectOnLift.length() > 0) {
        m_ObjectManager.getObjectBySafeStateId(sRemoveObjectOnLift)->suicide();
    }

	return true;
}
	// 当属性改变了,需要重构贴花的时候
	void GridDecal::updateDecal()
	{
#define WIDTH_POS_COUNT (m_widthGridCount + 1)
#define HEIGHT_POS_COUNT (m_heightGridCount + 1)
		// 显示整个节点
		m_node->setVisible(m_visible);
		// 不可视就不更新了
		if(!m_visible)
		{
			return;
		}
		// 错误数据检查
		if(m_heightGridCount == 0 || m_widthGridCount == 0)
			return;
		// 如果网格大小改变了,就重构
		if((m_dirty & (GRID_DECAL_DIRTY_WIDTH_GRID_COUNT
			| GRID_DECAL_DIRTY_HEIGHT_GRID_COUNT))
			|| m_gridPositions == 0
			)
		{
			OGRE_DELETE_ARRAY(m_gridPositions);
			m_gridPositions = new Vector3[WIDTH_POS_COUNT * HEIGHT_POS_COUNT];
			memset(m_gridPositions , 0 , sizeof(Vector3) * WIDTH_POS_COUNT * HEIGHT_POS_COUNT);
		}

		// 位置、深度、大小会导致平面重新定义
		if(m_dirty & (DIRTY_POSITION
			| DIRTY_DEPTH
			| DIRTY_SIZE
			| GRID_DECAL_DIRTY_WIDTH_GRID_COUNT
			| GRID_DECAL_DIRTY_HEIGHT_GRID_COUNT)
			)
		{
			for(uint y = 0 ; y < WIDTH_POS_COUNT ; y ++)
			{
				for(uint x = 0 ; x < HEIGHT_POS_COUNT ; x ++)
				{
					// 找到与地形相交的点
					if(!IDecalSystem::getSingleton().worldRayQuery(m_gridPositions[y * WIDTH_POS_COUNT + x]
						, m_position + Vector3(m_size.x * ((float)x / (float)WIDTH_POS_COUNT) - m_size.x / 2.0f , m_depth , m_size.y * ((float)y / (float)HEIGHT_POS_COUNT) - m_size.y / 2.0f)
						, m_position + Vector3(m_size.x * ((float)x / (float)WIDTH_POS_COUNT) - m_size.x / 2.0f , -m_depth , m_size.y * ((float)y / (float)HEIGHT_POS_COUNT) - m_size.y / 2.0f)
						)
						)
					{
						return;
					}
					// 移动到相对位置
					m_gridPositions[y * WIDTH_POS_COUNT + x] -= m_position;
				}
			}
			// 从三点定义贴花平面
			m_decalPlane.redefine(m_gridPositions[WIDTH_POS_COUNT / 2]
								, m_gridPositions[WIDTH_POS_COUNT * (HEIGHT_POS_COUNT - 1)]
								, m_gridPositions[WIDTH_POS_COUNT * HEIGHT_POS_COUNT - 1]
								);
		}

		// 改变节点位置
		if(m_dirty & DIRTY_POSITION)
		{
			m_node->setPosition(m_position);
		}

		// 材质名和大小会影响贴花对象的重构
		if(m_dirty & (DIRTY_POSITION
			| DIRTY_DEPTH
			| DIRTY_MATERIAL_NAME
			| DIRTY_SIZE
			| GRID_DECAL_DIRTY_WIDTH_GRID_COUNT
			| GRID_DECAL_DIRTY_HEIGHT_GRID_COUNT)
			)
		{
			// 材质贴花
			if(!m_materialName.empty())
			{
				// 创建贴花对象
				if(m_decal == 0)
				{
					m_decal = m_sceneMgr->createManualObject(m_name + "_GridDecal");
					m_decal->setDynamic(true);
					m_decal->begin(m_materialName);
					m_decal->position(Vector3::ZERO);
					m_decal->textureCoord(0,0);
					m_decal->index(0);
					m_decal->end();
					// 贴花在地形之后,物件之前
					m_decal->setRenderQueueGroup(RENDER_QUEUE_DECAL);
					attachObject(m_decal);
				}

				// 设置材质
				if(m_dirty & DIRTY_MATERIAL_NAME)
				{
					m_decal->getSection(0)->setMaterialName(m_materialName);
				}
				// 更新顶点
				if(m_dirty & (DIRTY_POSITION
					| DIRTY_DEPTH
					| DIRTY_SIZE
					| GRID_DECAL_DIRTY_WIDTH_GRID_COUNT
					| GRID_DECAL_DIRTY_HEIGHT_GRID_COUNT)
					)
				{
					m_decal->beginUpdate(0);
					// 生成所有顶点
					for(uint y = 0 ; y < HEIGHT_POS_COUNT ; y ++)
					{
						for(uint x = 0 ; x < WIDTH_POS_COUNT ; x ++)
						{
							m_decal->position(m_gridPositions[y * WIDTH_POS_COUNT + x]);
							m_decal->textureCoord((float)x / (float)WIDTH_POS_COUNT
								, (float)y / (float)HEIGHT_POS_COUNT);
						}
					}
					// 根据顶点生成索引缓冲区
					for(uint y = 0 ; y < m_heightGridCount ; y ++)
					{
						for(uint x = 0 ; x < m_widthGridCount ; x ++)
						{
							uint tl = y * WIDTH_POS_COUNT + x;
							uint tr = y * WIDTH_POS_COUNT + x + 1;
							uint bl = (y + 1) * WIDTH_POS_COUNT + x;
							uint br = (y + 1) * WIDTH_POS_COUNT + x + 1;
							m_decal->quad(tl
								, bl
								, br
								, tr
								);
						}
					}
					
					m_decal->end();
				}
			}
			else
			{
				if(m_decal)
				{
					m_sceneMgr->destroyManualObject(m_decal);
					m_decal = 0;
				}
			}
		}

		// 改变附加对象的节点旋转
		if(m_nodeAttachObject)
		{
			// 位置信息改变才需要重新设置
			if(m_dirty & (DIRTY_POSITION
				| DIRTY_DEPTH
				| DIRTY_SIZE
				| DIRTY_OFFSET)
				)
			{
				m_nodeAttachObject->setPosition(m_offsetPosition);
			}
		}
	}
void QmlWebViewWidget::setUrl(QUrl arg)
{

    connect(m_widget->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), SLOT(attachObject()));

    QWebSettings::globalSettings( )->setAttribute( QWebSettings::PrivateBrowsingEnabled, true );
    QWebSettings::setMaximumPagesInCache( 0 );
    QWebSettings::setObjectCacheCapacities( 0, 0, 0 );
    QWebSettings::clearMemoryCaches( );

    m_widget->setUrl(arg);
}
Exemple #24
0
 /// Hack to handle overloaded methods.
 inline
 void scriptAttachObject1(AttachableObject& _object)
 {
     attachObject(_object);
 }
void GasCellPort::cellDraw( const coordInt2d_t& coord ) const {

    // Создаём образ

    // Содержимое ячейки представим в виде меша

    const int i = helper::ic( coord.get<0>(), coord.get<1>(), N, M );
    assert( (i != -1) && "Получена координата за пределами матрицы порта." );
    const GasFD c = content[i];
    if (c.uid == 0) {
        // Вакуум не показываем
        return;
    }

    
#if 0
    // - Медленно. Переписано через биллборды.
    /*
    const std::string name =
        "smoke-pressure-"
      + Ogre::StringConverter::toString( (int)c.pressure );
    */
    const std::string meshName = "sphere.mesh";
    /* - @todo Так ли каждый раз нужна новая сущность?
    const std::string entityName = meshName + ".entity";
    const bool has = sm->hasEntity( entityName );
    Ogre::Entity* image = has ?
        sm->getEntity( entityName ) :
        sm->createEntity( entityName, meshName );
    */
    Ogre::Entity* image = sm->createEntity( meshName );
    auto childScene = sn->createChildSceneNode();
    childScene->attachObject( image );
    // Координаты образа кратны масштабу
    childScene->setPosition(
        (float)coord.get<0>() * scale,
        0.0f,
        (float)coord.get<1>() * scale
    );
    // Образ заполняет ячейку целиком
    //const Ogre::Vector3 fillScale( scale / image->getBoundingRadius() );
    //childScene->setScale( fillScale );
#endif

    // Работаем через биллборды
    // @source http://89.151.96.106/forums/viewtopic.php?f=10&t=60455

    const float S = scale * visualScale;

    // Готовим биллборды при первом обращении к ним
    // @todo Визаулизировать в зависимости от характеристики ячейки и соседей.
    std::string bsName = "GasCellPort-bs";
    Ogre::BillboardSet* bs = nullptr;
    if ( sm->hasBillboardSet( bsName ) ) {
        bs = sm->getBillboardSet( bsName );

    } else {
        // Дым - один образ на всю ячейку
        bs = sm->createBillboardSet( bsName, count() );
        bs->setAutoextend( false );
        const std::string prefixMaterial = "smokeport2d/smoke-";
        const std::string nameMaterial = prefixMaterial + "0";
        bs->setMaterialName( nameMaterial );
        bs->setBillboardType( Ogre::BBT_PERPENDICULAR_COMMON );
        bs->setCommonUpVector( Ogre::Vector3::UNIT_Z );
        bs->setCommonDirection( -Ogre::Vector3::UNIT_Y );
        bs->setBillboardsInWorldSpace( true );
        bs->setBillboardOrigin( Ogre::BBO_CENTER );
        bs->setDefaultDimensions( S, S );
        sn->attachObject( bs );
    }

    // Позиционируем биллборд
    Ogre::Billboard* b = bs->createBillboard(
        (float)coord.get<0>() * S,
        0.0f,
        (float)coord.get<1>() * S
    );
    //b->setRotation( Ogre::Degree( (float)rand() ) );

}
Exemple #26
0
void App::createScene()
{
#pragma region Plane
	// Define the mathematical plane
	Ogre::Plane plane(Vector3::UNIT_Y, 0);
	
	// Create the plane into memory
	Ogre::MeshManager::getSingleton().createPlane(
		"plane",
		ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		plane,
		500, 500, // size
		25, 25,   // how many quads are used to make the plane
		true,
		1, 5, 5, Vector3::UNIT_Z);

	// Create an instance of the plane
	auto planeEnt = mSceneMgr->createEntity("PlaneEntity", "plane");
	planeEnt->setMaterialName("Examples/BeachStones");

	// Create a node for the plane and attach he plane to it
	mSceneMgr->getRootSceneNode()->createChildSceneNode("planeNode")->attachObject(planeEnt);
#pragma endregion

#pragma region Lights
	// Directional
	auto sunlight = mSceneMgr->createLight("sun");
	sunlight->setType(Ogre::Light::LT_DIRECTIONAL);
	sunlight->setDirection(Ogre::Vector3(0, -1, -1));
	sunlight->setDiffuseColour(Ogre::ColourValue(.30, .30, 0));
	sunlight->setSpecularColour(Ogre::ColourValue(.30, .30, 0));

	// Spotlight
	auto spotlight = mSceneMgr->createLight("spotlight");
	spotlight->setType(Ogre::Light::LT_SPOTLIGHT);
	
	spotlight->setSpotlightRange(
		Ogre::Degree(5.0f),  // inner angle
		Ogre::Degree(15.0f), // outer angle
		0.0f);               // falloff
	
	spotlight->setDiffuseColour(Ogre::ColourValue(1.0f, 0.0f, 0.0f));

	// Sphere to visualize the spotlights source
	auto sphereEnt = mSceneMgr->createEntity("sphere", "sphere.mesh");
	sphereEnt->setMaterialName("Examples/checker");
	auto sphereNode = mSceneMgr->getSceneNode("planeNode")->createChildSceneNode("spotlightNode");
	sphereNode->attachObject(sphereEnt);
	sphereNode->attachObject(spotlight);
	sphereNode->scale(0.02f, 0.02f, 0.02f);
	sphereNode->translate(0.0f, 15.0f, 0.0f);
	sphereNode->lookAt(Ogre::Vector3(0, 0, 0), Ogre::Node::TS_PARENT);
#pragma endregion

#pragma region Entities
	std::array<Ogre::Entity*, 6> entities;
	auto entParentNode = mSceneMgr->getSceneNode("planeNode")->createChildSceneNode("entParentNode");

	float angleOffset = 360.0f / 6.0f;
	float radius = 30.0f;

	for (int i = 0; i < entities.size(); ++i)
	{
		auto e = mSceneMgr->createEntity("Sinbad.mesh");
		entParentNode->createChildSceneNode(Ogre::Vector3(
			radius * Math::Cos(Math::DegreesToRadians(angleOffset * i)),  // x = r cos(t)
			6.75f,                                                        // y = height
			radius * Math::Sin(Math::DegreesToRadians(angleOffset * i)))) // z = r sin(t)
		->attachObject(e);
	}

	// Barrel
	auto barrel = mSceneMgr->createEntity("barrel.mesh");
	mSceneMgr->getSceneNode("planeNode")->createChildSceneNode("barrel", Ogre::Vector3(0, 2.5f, 0))->attachObject(barrel);
#pragma endregion

	// Skybox
	mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 5000, false);
}