Exemplo n.º 1
0
    //----------------------------------------------------------------------------------
    bool GameObject::removeFlag(Ogre::String flag)
    {
	    std::string::size_type pos1 = mFlags.find("|" + flag + "|");

	    if (pos1 == Ogre::String::npos)
	    {
		    return false;
	    }

	    ++pos1;
	    std::string::size_type pos2 = flag.length() + 1;

	    mFlags.erase(pos1, pos2);

	    return true;
    }
Exemplo n.º 2
0
void SoundEditDialog::SaveSoundInfoFromFile(const Ogre::String& filename)
{
    if (mSoundInfoFileChanged)
    {
        char buf[1024];
        FILE* pFile = NULL;
        pFile = ::fopen(filename.c_str(), "w");
        if(NULL == pFile)
        {
            wxMessageBox("Can't open the file, Maybe the file is missing or it is read only!");
            return;
        }

        memset(buf, 0, sizeof(buf));
        sprintf(buf, "INT\tINT\tINT\tINT\tINT\tINT\tINT\tINT\n");
        ::fwrite(buf, strlen(buf), 1, pFile);

        memset(buf, 0, sizeof(buf));
        sprintf(buf, "ID\t声音ID\t声源位置X\t声源位置Z\t有效距离\t连播次数\t间隔时间(ms)\t下一次连播间隔时间(ms)\n");
        ::fwrite(buf, strlen(buf), 1, pFile);
        
        memset(buf, 0, sizeof(buf));

        for(size_t i=0; i<mSoundItems.size(); ++i)
        {
            SoundItem* soundItem = mSoundItems[i];

            if (soundItem->mRepeatTime == 0)
            {
                sprintf(buf, "%d\t%d\t%d\t%d\t%d\n",
                    i, soundItem->mSoundID, soundItem->mXPos, soundItem->mZPos, soundItem->mRadius);
            }
            else
            {
                sprintf(buf, "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n",
                    i, soundItem->mSoundID, soundItem->mXPos, soundItem->mZPos, soundItem->mRadius,
                    soundItem->mRepeatTime, soundItem->mRepeatIntervalTime, soundItem->mNextRepeatTime);
            }

            ::fwrite(buf, strlen(buf), 1, pFile);
        }

        ::fclose(pFile);

        mSoundInfoFileChanged = false;
    }
}
Exemplo n.º 3
0
Ogre::ResourcePtr
loadCorrelativeResource(const Ogre::String& resourceName, const Ogre::String& groupName,
                        const Ogre::String& baseResourceName, const Ogre::String& baseGroupName,
                        Ogre::ResourceManager& resourceManager)
{
    Ogre::ResourcePtr res;

   Ogre::String name, path;
    Ogre::StringUtil::splitFilename(resourceName, name, path);
    bool existsPath = !path.empty();

    // First, load in correlatived group and path if resource name doesn't exists path
    if (!existsPath)
    {
        Ogre::StringUtil::splitFilename(baseResourceName, name, path);
        if (!path.empty())
        {
            name = path + resourceName;
            res = tryLoadResource(resourceManager, name, baseGroupName);
            if (!res.isNull())
                return res;
        }
    }

    // Second, load in correlatived group
    res = tryLoadResource(resourceManager, resourceName, baseGroupName);
    if (!res.isNull())
        return res;

    // Three, load in user given group
    if (!groupName.empty())
    {
        res = tryLoadResource(resourceManager, resourceName, groupName);
        if (!res.isNull())
            return res;
    }

    // Four, load in global default group
    if (groupName != DEFAULT_RESOURCE_GROUP_NAME)
    {
        res = tryLoadResource(resourceManager, resourceName, groupName);
        if (!res.isNull())
            return res;
    }

    return res;
}
Exemplo n.º 4
0
//-----------------------------------------------------------------------------
int COFSSceneSerializer::_writeFile(Ogre::String exportfile, const bool forceSave)
{
    if (exportfile.empty())
        return SCF_ERRUNKNOWN;

    OgitorsRoot *ogRoot = OgitorsRoot::getSingletonPtr();
    // Open a stream to output our XML Content and write the general headercopyFile
    std::stringstream outfile;

    outfile << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    outfile << "<OGITORSCENE version=\"" << Globals::OGSCENE_FORMAT_VERSION << "\">\n";

    PROJECTOPTIONS *pOpt = ogRoot->GetProjectOptions();
    pOpt->CameraSpeed = ogRoot->GetViewport()->GetCameraSpeed();

    ogRoot->WriteProjectOptions(outfile, pOpt);

    ObjectVector ObjectList;
    OgitorsPropertyValueMap theList;
    OgitorsPropertyValueMap::iterator ni;

    // Start from 1, since 0 means all objects
    for(unsigned int i = 1; i < LAST_EDITOR; i++)
    {
        ogRoot->GetObjectList(i, ObjectList);
        for(unsigned int ob = 0; ob < ObjectList.size(); ob++)
        {
            /// If Object does not have a parent, then it is not part of the scene
            if(ObjectList[ob]->getParent())
            {
                ObjectList[ob]->onSave(forceSave);
                if(ObjectList[ob]->isSerializable())
                {
                    outfile << OgitorsUtils::GetObjectSaveStringV2(ObjectList[ob], 2, true, true).c_str();
                    outfile << "\n";
                }
            }
        }
    }
    outfile << "</OGITORSCENE>\n";

    if (OgitorsUtils::SaveStreamOfs(outfile, exportfile)) {
        return SCF_OK;
    }

    return SCF_ERRFILE;
}
//-----------------------------------------------------------------------------------------
void OgitorsRoot::GetObjectListByCustomProperty(unsigned int type, const Ogre::String& nameregexp, bool inverse, ObjectVector& list)
{
    list.clear();

    try
    {
        const boost::regex e(nameregexp.c_str());

        NameObjectPairList::iterator list_st, list_ed;

        if(type == 0)
        {
            list_st = mNameList.begin();
            list_ed = mNameList.end();
        }
        else
        {
            list_st = mNamesByType[type].begin();
            list_ed = mNamesByType[type].end();
        }

        OgitorsPropertyVector pvec;

        while(list_st != list_ed)
        {
            pvec = list_st->second->getCustomProperties()->getPropertyVector();
            bool add_list = false;
            for(unsigned int k = 0;k < pvec.size();k++)
            {
                if(regex_match(pvec[k]->getName().c_str(), e))
                {
                    add_list = true;
                    break;
                }
            }
            
            if(add_list != inverse)
                list.push_back(list_st->second);
            
            list_st++;
        }
    }
    catch(...)
    {
        list.clear();
    }
}
Exemplo n.º 6
0
void Cube::save(Ogre::String file)
{
  if (rndCounter == 0)
  {
    std::ofstream output(file.c_str());

    // Write cube size
    output << size << std::endl;

    for (int i = 0; i < size; ++i)
      for (int j = 0; j < size; ++j)
        for (int k = 0; k < size; ++k)
        {
          CubeElement *e = data[i][j][k];
          Ogre::Entity *ent = static_cast<Ogre::Entity*>(e->node->getAttachedObject(0));
          Ogre::SceneNode *node = e->node;
          // Write name, indexes and position
          output << node->getName() << "\n"
                 << "\t" << i << " " << j << " " << k << "\n" // index in data array
                 << "\t" << node->getPosition().x << " " << node->getPosition().y << " " << node->getPosition().z << "\n"; // position
          // Write orientation
          Ogre::Vector3 orient_axis;
          Ogre::Degree orient_angle;
          node->getOrientation().ToAngleAxis(orient_angle, orient_axis);
          output << "\t" << orient_axis.x << " " << orient_axis.y << " " << orient_axis.z << " " // orientation axis
                 << orient_angle.valueDegrees() << "\n"; // orientation angle
          output << "\t" << ent->getSubEntity(0)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(1)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(2)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(3)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(4)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(5)->getMaterialName() << "\n";
          // Write pivot info
          output << "\t" << e->isPivot << "\n";
          if (e->isPivot)
          {
            // pivot indexes
            output << "\t" << e->pivotArrays[0] << " " << e->pivotArrayIndexes[0] << "\n"
                   << "\t" << e->pivotArrays[1] << " " << e->pivotArrayIndexes[1] << "\n";
          }
          // flush
          output << std::endl;
        }

    output.close();
  }
}
bool NetworkManager::doConnect( Ogre::String serverIP, Ogre::ushort serverPort )
{
	mConnectAtemp = true;

	switch(mRakPeer->Connect(serverIP.c_str(), serverPort, 0, 0, 0))
	{
	case RakNet::CONNECTION_ATTEMPT_STARTED:
		{
			Ogre::LogManager::getSingletonPtr()
				->logMessage(RealToys::logMessagePrefix + "CONNECTION_ATTEMPT_STARTED");
			return true;
			break;
		}
	case RakNet::INVALID_PARAMETER:
		{
			Ogre::LogManager::getSingletonPtr()
				->logMessage(RealToys::logMessagePrefix + "INVALID_PARAMETER");
			break;
		}
	case RakNet::CANNOT_RESOLVE_DOMAIN_NAME:
		{
			Ogre::LogManager::getSingletonPtr()
				->logMessage(RealToys::logMessagePrefix + "CANNOT_RESOLVE_DOMAIN_NAME");
			break;
		}
	case RakNet::ALREADY_CONNECTED_TO_ENDPOINT:
		{
			Ogre::LogManager::getSingletonPtr()
				->logMessage(RealToys::logMessagePrefix + "ALREADY_CONNECTED_TO_ENDPOINT");
			break;
		}
	case RakNet::CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS:
		{
			Ogre::LogManager::getSingletonPtr()
				->logMessage(RealToys::logMessagePrefix + "CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS");
			break;
		}
	case RakNet::SECURITY_INITIALIZATION_FAILED:
		{
			Ogre::LogManager::getSingletonPtr()
				->logMessage(RealToys::logMessagePrefix + "SECURITY_INITIALIZATION_FAILED");
			break;
		}
	}

	return false;	
}
bool fnmatch (Ogre::String pattern, Ogre::String name, int dummy)
{
	if (pattern == "*")
	{
		return true;
	}
	if (pattern.substr(0,2) == "*.")
	{
		Ogre::StringUtil::toLowerCase(pattern);
		Ogre::StringUtil::toLowerCase(name);
		Ogre::String extToFind = pattern.substr(2, pattern.size() - 2);
		if ((name.size() > extToFind.size()) &&(extToFind == name.substr(name.size() - extToFind.size(), extToFind.size())))
		{
			return 0; // match
		}
		else
		{
			return 1; // don't match
		}
	}
	return false;
}
MovableTextOverlayAttributes::MovableTextOverlayAttributes(const Ogre::String & name, const Ogre::Camera *cam,
						 const Ogre::String & fontName, int charHeight, const Ogre::ColourValue & color, const Ogre::String & materialName)
: mpCam(cam)
, mpFont(NULL)
, mName(name)
, mFontName("")
, mMaterialName("")
, mCharHeight(charHeight)
, mColor(ColourValue::ZERO)
{
	if (fontName.length() == 0)
        Ogre::Exception(Ogre::Exception::ERR_INVALIDPARAMS, "Invalid font name", "MovableTextOverlayAttributes::MovableTextOverlayAttributes");

	setFontName(fontName);
	setMaterialName(materialName);
	setColor(color);
}
Exemplo n.º 10
0
    //-----------------------------------------------------------------------
    void XercesWriter::writeXMLFile(const XMLNode* root, const Ogre::String& filename)
    {
        XERCES_CPP_NAMESPACE_USE;

        DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(L"Core");
        DOMDocumentType* docType = NULL;
        DOMDocument* doc = impl->createDocument(NULL, transcode(root->getName()).c_str(), docType);

        populateDOMElement(root, doc->getDocumentElement());

        LocalFileFormatTarget destination(filename.c_str());
        DOMWriter* writer = impl->createDOMWriter();
        writer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
        writer->writeNode(&destination, *doc);
        writer->release();
        doc->release();
    }
Exemplo n.º 11
0
bool OgreDetourTileCache::saveAll(Ogre::String filename)
{
    if (!m_tileCache) {
        Ogre::LogManager::getSingletonPtr()->logMessage("Error: OgreDetourTileCache::saveAll("+filename+"). Could not save tilecache, no tilecache to save.");
        return false;
    }

       FILE* fp = fopen(filename.data(), "wb");
       if (!fp) {
           Ogre::LogManager::getSingletonPtr()->logMessage("Error: OgreDetourTileCache::saveAll("+filename+"). Could not save file.");
           return false;
       }

// Store header.
       TileCacheSetHeader header;
       header.magic = TILECACHESET_MAGIC;
       header.version = TILECACHESET_VERSION;
       header.numTiles = 0;
       for (int i = 0; i < m_tileCache->getTileCount(); ++i)
       {
               const dtCompressedTile* tile = m_tileCache->getTile(i);
               if (!tile || !tile->header || !tile->dataSize) continue;
               header.numTiles++;
       }
       memcpy(&header.cacheParams, m_tileCache->getParams(), sizeof(dtTileCacheParams));
       memcpy(&header.meshParams, m_recast->m_navMesh->getParams(), sizeof(dtNavMeshParams));
       memcpy(&header.recastConfig, &m_cfg, sizeof(rcConfig));
       fwrite(&header, sizeof(TileCacheSetHeader), 1, fp);

       // Store tiles.
       for (int i = 0; i < m_tileCache->getTileCount(); ++i)
       {
               const dtCompressedTile* tile = m_tileCache->getTile(i);
               if (!tile || !tile->header || !tile->dataSize) continue;

               TileCacheTileHeader tileHeader;
               tileHeader.tileRef = m_tileCache->getTileRef(tile);
               tileHeader.dataSize = tile->dataSize;
               fwrite(&tileHeader, sizeof(tileHeader), 1, fp);

               fwrite(tile->data, tile->dataSize, 1, fp);
       }

       fclose(fp);
       return true;
}
Exemplo n.º 12
0
bool LuaScriptUtilities::HasAttribute(
    lua_State* const luaVM,
    const int tableIndex,
    const Ogre::String& attributeName)
{
    if (!lua_istable(luaVM, tableIndex))
        return false;

    lua_pushstring(luaVM, attributeName.c_str());
    lua_gettable(luaVM, tableIndex);

    const bool result = lua_isnil(luaVM, -1);

    lua_pop(luaVM, 1);

    return !result;
}
Exemplo n.º 13
0
  void CollisionSerializer::exportCollision(const CollisionPtr& collision, const Ogre::String& filename)
  {
    if( !collision )
        OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, "Argument collision is NULL","CollisionSerializer::exportCollision");

    mpfFile=fopen(filename.c_str(),"wb");
    
    if (!mpfFile)
    {
        OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, "Unable to open file " + filename + " for writing","CollisionSerializer::exportCollision");
    }

    NewtonCollisionSerialize(collision->getWorld()->getNewtonWorld(), collision->m_col, &CollisionSerializer::_newtonSerializeCallback, this);


    fclose(mpfFile);
  }
Exemplo n.º 14
0
Ogre::Real LuaScriptUtilities::GetRealAttribute(
    lua_State* const luaVM,
    const Ogre::String attributeName,
    const int tableIndex)
{
    if (!lua_istable(luaVM, tableIndex))
        return Ogre::Real();

    lua_pushstring(luaVM, attributeName.c_str());
    lua_gettable(luaVM, tableIndex);

    Ogre::Real value = lua_tonumber(luaVM, -1);

    lua_pop(luaVM, 1);

    return value;
}
Exemplo n.º 15
0
void
AudioManager::Player::Play( const Ogre::String &file )
{
    boost::recursive_mutex::scoped_lock lock( *m_UpdateMutex );

    // open vorbis file
    if( ov_fopen( const_cast< char* >( file.c_str() ), &m_VorbisFile ) )
    {
        LOG_ERROR( "Can't play file \"" + file + "\"." );
        return;
    }

    // get file info
    m_VorbisInfo = ov_info( &m_VorbisFile, -1.0f );

    // create sound source
    alGenSources( 1, &m_Source );

    // create buffers
    ALuint buffers[ m_ChannelBufferNumber ];
    alGenBuffers( m_ChannelBufferNumber, buffers );

    // set source parameters
    alSourcei( m_Source, AL_LOOPING, AL_FALSE );

    // fill buffers
    for( int i = 0; i < m_ChannelBufferNumber; ++i )
    {
        ALsizei buffer_size = FillBuffer();

        if( buffer_size )
        {
            alBufferData( buffers[ i ], m_VorbisInfo->channels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16, ( const ALvoid* )AudioManager::getSingleton().m_Buffer, ( ALsizei )buffer_size, ( ALsizei )m_VorbisInfo->rate );
            alSourceQueueBuffers( m_Source, 1, &buffers[ i ] );
        }
        else
        {
            m_StreamFinished = true;
            alDeleteBuffers( 1, &buffers[ i ] );
        }
    }

    // start playback
    alSourcePlay( m_Source );
}
Exemplo n.º 16
0
//-----------------------------------------------------------------------
void AtlasImageTool::initialise (const Ogre::String& configFileName)
{
	if (!configFileName.empty())
	{
		mConfigFile.load(configFileName);
	}
	else
	{
		mConfigFile.load("atlas.cfg");
	}

	mInputFileNames = Ogre::StringUtil::split(mConfigFile.getSetting("InputImage"), ";, ");
	mInputFrames = Ogre::StringUtil::split(mConfigFile.getSetting("Frame"), ";, ");
	mAlpha = Ogre::StringUtil::split(mConfigFile.getSetting("Alpha"), ";, ");
	mOutputImage = mConfigFile.getSetting("OutputImage");
	mImagePath = mConfigFile.getSetting("ImagePath");
	mAtlasImage.setAlwaysUpdate(false); // Manual compilation to speed things up.
}
Exemplo n.º 17
0
	MainSkin::MainSkin(const SubWidgetInfo& _info, const Ogre::String& _material, CroppedRectanglePtr _parent, size_t _id) : 
		CroppedRectangleInterface(_info.coord, _info.align, _parent)
	{

		Ogre::OverlayManager& overlayManager = Ogre::OverlayManager::getSingleton();

		mOverlayContainer = static_cast<SharedPanelAlphaOverlayElement*>( overlayManager.createOverlayElement(
			"SharedPanelAlpha", utility::toString("MainSkin_", this)) );

		// устанавливаем колличество саб оверлеев
		mOverlayContainer->setCountSharedOverlay(1);

		//mOverlayContainer->setMetricsMode(Ogre::GMM_PIXELS);
		mOverlayContainer->setPositionInfo(mParent->getLeft() + mCoord.left, mParent->getTop() + mCoord.top, mCoord.width, mCoord.height, 0);
		if (false == _material.empty() && (_info.coord.width != 0)) mOverlayContainer->setMaterialName(_material);

		mParent->_attachChild(this, false);
	}
Exemplo n.º 18
0
bool TracksXml::LoadXml(Ogre::String file)
{
	TiXmlDocument doc;
	if (!doc.LoadFile(file.c_str()))  return false;
		
	TiXmlElement* root = doc.RootElement();
	if (!root)  return false;

	//  clear
	//Default();
	trks.clear();  trkmap.clear();

	///  tracks
	const char* a;  int i=1;  //0 = none
	TiXmlElement* eTrk = root->FirstChildElement("track");
	while (eTrk)
	{
		TrackInfo t;
		a = eTrk->Attribute("n");			if (a)  t.n = s2i(a);
		a = eTrk->Attribute("name");		if (a)  t.name = std::string(a);
		a = eTrk->Attribute("created");		if (a)  t.created = s2dt(a);
		a = eTrk->Attribute("crtver");		if (a)  t.crtver = s2r(a);
		a = eTrk->Attribute("modified");	if (a)  t.modified = s2dt(a);
		a = eTrk->Attribute("scenery");		if (a)  t.scenery = std::string(a);
		a = eTrk->Attribute("author");		if (a)  t.author = std::string(a);

		a = eTrk->Attribute("fluids");		if (a)  t.fluids = s2i(a);
		a = eTrk->Attribute("bumps");		if (a)  t.bumps = s2i(a);	a = eTrk->Attribute("jumps");		if (a)  t.jumps = s2i(a);
		a = eTrk->Attribute("loops");		if (a)  t.loops = s2i(a);	a = eTrk->Attribute("pipes");		if (a)  t.pipes = s2i(a);
		a = eTrk->Attribute("banked");		if (a)  t.banked = s2i(a);	a = eTrk->Attribute("frenzy");		if (a)  t.frenzy = s2i(a);
		a = eTrk->Attribute("long");		if (a)  t.longn = s2i(a);

		a = eTrk->Attribute("diff");		if (a)  t.diff = s2i(a);
		a = eTrk->Attribute("rating");		if (a)  t.rating = s2i(a);
		a = eTrk->Attribute("rateuser");	if (a)  t.rateuser = s2i(a);
		a = eTrk->Attribute("drivenlaps");	if (a)  t.drivenlaps = s2i(a);

		trks.push_back(t);
		//trkmap[t.name] = &trks.back();
		trkmap[t.name] = i++;
		eTrk = eTrk->NextSiblingElement("track");
	}
	return true;
}
Exemplo n.º 19
0
NativeWindowPair ApplicationContextSDL::createWindow(const Ogre::String& name, Ogre::uint32 w, Ogre::uint32 h, Ogre::NameValuePairList miscParams)
{
    NativeWindowPair ret = {NULL, NULL};
    parseWindowOptions(w, h, miscParams);

    Ogre::ConfigOptionMap& ropts = mRoot->getRenderSystem()->getConfigOptions();

    if(!SDL_WasInit(SDL_INIT_VIDEO)) {
        SDL_InitSubSystem(SDL_INIT_VIDEO);
    }

    Uint32 flags = SDL_WINDOW_RESIZABLE;

    if(ropts["Full Screen"].currentValue == "Yes"){
       flags = SDL_WINDOW_FULLSCREEN;
    } else {
       flags = SDL_WINDOW_RESIZABLE;
    }

    ret.native = SDL_CreateWindow(name.c_str(),
                                SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, flags);

#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
    SDL_GL_CreateContext(ret.native);
    miscParams["currentGLContext"] = "true";
#else
    SDL_SysWMinfo wmInfo;
    SDL_VERSION(&wmInfo.version);
    SDL_GetWindowWMInfo(ret.native, &wmInfo);
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
    miscParams["parentWindowHandle"] = Ogre::StringConverter::toString(size_t(wmInfo.info.x11.window));
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32
    miscParams["externalWindowHandle"] = Ogre::StringConverter::toString(size_t(wmInfo.info.win.window));
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
    assert(wmInfo.subsystem == SDL_SYSWM_COCOA);
    miscParams["externalWindowHandle"] = Ogre::StringConverter::toString(size_t(wmInfo.info.cocoa.window));
#endif

    ret.render = mRoot->createRenderWindow(name, w, h, false, &miscParams);
    mWindows.push_back(ret);
    return ret;
}
Exemplo n.º 20
0
void BoneCollisionManager::CreateBoneData(Ogre::Bone *q, Ogre::String Type, Ogre::Vector3 D, Ogre::String MeshName)
{
	Ogre::String Line;

	if (mFile == NULL)
	{
		mFile = fopen((MeshName.c_str()), "w");
	}

	//Write Top Compoment
	Line = "[" + q->getName() + "]"  + "\n";
	fwrite(Line.c_str(), 1, strlen(Line.c_str()), mFile);

	//Write Bone Name
	Line = "boneName=" + q->getName() + "\n";
	//fputs(Line.c_str(),mFile);
	fwrite(Line.c_str(), 1, strlen(Line.c_str()), mFile);

	//Write Type
	Line = "actorShape="+Type+"\n";
	//fputs(Line.c_str(),mFile);
	fwrite(Line.c_str(), 1, strlen(Line.c_str()), mFile);

	//Write Dimensions
	std::stringstream s;
	std::stringstream ss;
	std::stringstream sss;
	s << D.x;
	ss << D.y;
	sss << D.z;
	Line = "dimensions=";
	Line += s.str()+" "+ss.str()+" "+sss.str()+"\n"+"\n";
	fputs(Line.c_str(),mFile);
	
	fflush(mFile);
}
Exemplo n.º 21
0
CChest::CChest(Ogre::SceneNode *pNode, CObjectManager &objectManager, btCollisionObject *pCollisionObject, EChestType eChestType, const Ogre::String &id)
	: CObject(objectManager, CHEST_OBJECT, pCollisionObject, id), m_eChestType(eChestType) {

	m_eChestState = CS_CLOSED;
	//setInnerObject(&innerObject);
	m_pInnerObject = NULL;

	m_pLidSceneNode = objectManager.getMap().getRootSceneNode()->createChildSceneNode();
	m_pLidSceneNode->setPosition(pNode->getPosition());
	m_pLidSceneNode->setOrientation(pNode->getOrientation());
	m_pLidSceneNode->setScale(pNode->getScale());
	m_vInnerObjectPos = m_pLidSceneNode->getPosition();
	btCollisionShape *pColShape(0);
	switch (m_eChestType) {
	case CT_SMALL:
		m_pLidSceneNode->attachObject(pNode->getCreator()->createEntity("Chest.Small.Upper.mesh"));
		m_pLidSceneNode->translate(0, 0.37465f, -0.30862f, Ogre::Node::TS_LOCAL);
		m_vInnerObjectPos += m_pLidSceneNode->getOrientation() * Ogre::Vector3(0, 0.15f, 0);
		pColShape = new btBoxShape(btVector3(0.3f, 0.08f, 0.2f));
		m_vPhysicsOffset = Ogre::Vector3(0, 0.15f, 0.25f);
		break;
	default:
		throw Ogre::Exception(0, "Unknown chest type", __FILE__);
		break;
	}
	m_pLidPhysics = new btRigidBody(0, new btDefaultMotionState(), pColShape);
	m_pLidPhysics->getWorldTransform().setOrigin(BtOgre::Convert::toBullet(m_pLidSceneNode->getPosition() + m_pLidSceneNode->getOrientation() * m_vPhysicsOffset));
	m_pLidPhysics->getWorldTransform().setRotation(BtOgre::Convert::toBullet(m_pLidSceneNode->getOrientation()));

	m_ObjectManager.getMap().getPhysicsManager()->getWorld()->addRigidBody(m_pLidPhysics, COL_STATIC, MASK_STATIC_COLLIDES_WITH);

	// check for safe state
	if (id.length() > 0) {
        EItemSaveState iss = CPlayerData::getSingleton().getMapItemState(m_ObjectManager.getMap().getName(), id, ISS_CLOSED);
        if (iss == ISS_OPENED) {
            // open chest as initial state
            m_eChestState = CS_OPENED;
            m_pLidSceneNode->pitch(Ogre::Radian(-CHEST_MAX_ANGLE));
            m_pLidPhysics->getWorldTransform().setOrigin(BtOgre::Convert::toBullet(m_pLidSceneNode->getPosition() + m_pLidSceneNode->getOrientation() * m_vPhysicsOffset));
            m_pLidPhysics->getWorldTransform().setRotation(BtOgre::Convert::toBullet(m_pLidSceneNode->getOrientation()));
        }
    }
}
Exemplo n.º 22
0
bool LuaScriptUtilities::IsUserdataType(
    lua_State* const luaVM, const int stackIndex, const Ogre::String type)
{
    void* pointer = lua_touserdata(luaVM, stackIndex);
    if (pointer != NULL)
    {
        if (lua_getmetatable(luaVM, stackIndex))
        {
            lua_getfield(luaVM, LUA_REGISTRYINDEX, type.c_str());
            if (lua_rawequal(luaVM, -1, -2))
            {
                lua_pop(luaVM, 2);
                return true;
            }
            lua_pop(luaVM, 2);
        }
    }
    return false;
}
Exemplo n.º 23
0
Ogre::MaterialPtr AssetLoader::createMaterial(Ogre::String name, int index, aiMaterial* mat)
{
	Ogre::MaterialManager* omatMgr = Ogre::MaterialManager::getSingletonPtr();

	std::ostringstream matname;
	matname << name.data() << "_mat";
	matname.widen(4);
	matname.fill('0');
	matname << index;
	Ogre::String matName = matname.str();

	Ogre::ResourceManager::ResourceCreateOrRetrieveResult status = omatMgr->createOrRetrieve(matName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
	Ogre::MaterialPtr omat = status.first;

	aiColor4D clr(1.0, 1.0, 1.0, 1.0);
	aiGetMaterialColor(mat, AI_MATKEY_COLOR_DIFFUSE, &clr);
	omat->getTechnique(0)->getPass(0)->setDiffuse(clr.r, clr.g, clr.b, clr.a);
	
	aiGetMaterialColor(mat, AI_MATKEY_COLOR_SPECULAR, &clr);
	omat->getTechnique(0)->getPass(0)->setSpecular(clr.r, clr.g, clr.b, clr.a);
	
	aiGetMaterialColor(mat, AI_MATKEY_COLOR_AMBIENT, &clr);
	omat->getTechnique(0)->getPass(0)->setAmbient(clr.r, clr.g, clr.b);
	
	aiGetMaterialColor(mat, AI_MATKEY_COLOR_EMISSIVE, &clr);
	omat->getTechnique(0)->getPass(0)->setSelfIllumination(clr.r, clr.g, clr.b);

	omat->getTechnique(0)->getPass(0)->setShadingMode(Ogre::SO_GOURAUD);
	omat->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
	omat->getTechnique(0)->getPass(0)->setLightingEnabled(true);
	omat->getTechnique(0)->getPass(0)->setDepthCheckEnabled(true);
	//omat->getTechnique(0)->getPass(0)->setVertexColourTracking(Ogre::TVC_DIFFUSE);
	
	aiString path;
	aiReturn res = mat->GetTexture(aiTextureType_DIFFUSE, 0, &path);
	if (res == AI_SUCCESS) {
		Ogre::TextureUnitState* stateBase = omat->getTechnique(0)->getPass(0)->createTextureUnitState();
		stateBase->setColourOperation(Ogre::LBO_MODULATE);
		stateBase->setTextureName(path.data);
	}
	
	return omat;
}
Exemplo n.º 24
0
//-----------------------------------------------------------------------------------------
TiXmlElement* CPGInstanceManager::exportDotScene(TiXmlElement *pParent)
{
    Ogre::String name = mName->get();
    std::replace(name.begin(), name.end(), '<', ' ');
    std::replace(name.begin(), name.end(), '>', ' ');
    std::replace(name.begin(), name.end(), '#', ' ');

    name = Ogre::StringConverter::toString(mObjectID->get()) + "_" + name;

    Ogre::String filename = "PGInstances/" + name + ".instance";

    TiXmlElement *pNode = pParent->InsertEndChild(TiXmlElement("node"))->ToElement();

    // node properties
    pNode->SetAttribute("name", mName->get().c_str());
    pNode->SetAttribute("id", Ogre::StringConverter::toString(mObjectID->get()).c_str());
    // position
    TiXmlElement *pPosition = pNode->InsertEndChild(TiXmlElement("position"))->ToElement();
    pPosition->SetAttribute("x", "0");
    pPosition->SetAttribute("y", "0");
    pPosition->SetAttribute("z", "0");
    // rotation
    TiXmlElement *pRotation = pNode->InsertEndChild(TiXmlElement("rotation"))->ToElement();
    pRotation->SetAttribute("qw", "1");
    pRotation->SetAttribute("qx", "0");
    pRotation->SetAttribute("qy", "0");
    pRotation->SetAttribute("qz", "0");
    // scale
    TiXmlElement *pScale = pNode->InsertEndChild(TiXmlElement("scale"))->ToElement();
    pScale->SetAttribute("x", "1");
    pScale->SetAttribute("y", "1");
    pScale->SetAttribute("z", "1");
    
    
    TiXmlElement *pPG = pNode->InsertEndChild(TiXmlElement("pagedgeometry"))->ToElement();
    pPG->SetAttribute("fileName", filename.c_str());
    pPG->SetAttribute("model", mModel->get().c_str());
    pPG->SetAttribute("pageSize", Ogre::StringConverter::toString(mPageSize->get()).c_str());
    pPG->SetAttribute("batchDistance", Ogre::StringConverter::toString(mBatchDistance->get()).c_str());
    pPG->SetAttribute("impostorDistance", Ogre::StringConverter::toString(mImpostorDistance->get()).c_str());
    pPG->SetAttribute("bounds", Ogre::StringConverter::toString(mBounds->get()).c_str());
    pPG->SetAttribute("castShadows", Ogre::StringConverter::toString(mCastShadows->get()).c_str());

    return pPG;
}
void NavigationMesh::loadCellsFromXML(const Ogre::String& fileName) {
    pugi::xml_document doc;
    std::vector<int> a, b, c;
    std::vector<Ogre::Vector3> vertex;
    
    if (!doc.load_file(fileName.c_str())) {
        cerr << "NavigationMesh::loadCellsFromXML(): error al leer el fichero " << fileName << endl;
        exit(1);
    }

    pugi::xml_node meshNode = doc.child("mesh");
    pugi::xml_node subMeshesNode = meshNode.child("submeshes");
    pugi::xml_node subMeshNode = subMeshesNode.child("submesh");
    pugi::xml_node facesNode = subMeshNode.child("faces");
    
    for (pugi::xml_node faceNode = facesNode.child("face"); faceNode; faceNode = faceNode.next_sibling()) {
        int v1 = faceNode.attribute("v1").as_int();
        int v2 = faceNode.attribute("v2").as_int();
        int v3 = faceNode.attribute("v3").as_int();
        
        a.push_back(v1);
        b.push_back(v2);
        c.push_back(v3);
    }
    
    pugi::xml_node geometryNode = subMeshNode.child("geometry");
    pugi::xml_node vertexBufferNode = geometryNode.child("vertexbuffer");

    for (pugi::xml_node vertexNode = vertexBufferNode.child("vertex"); vertexNode; vertexNode = vertexNode.next_sibling()) {
        pugi::xml_node positionNode = vertexNode.child("position");
        Ogre::Vector3 v = Ogre::Vector3(positionNode.attribute("x").as_float(),
                                       positionNode.attribute("y").as_float(),
                                       positionNode.attribute("z").as_float());
        
        vertex.push_back(v);
    }
    
    int faceCount = a.size();

    for (int i = 0; i < faceCount; ++i)
        addCell(i, vertex[a[i]], vertex[b[i]], vertex[c[i]]);
}
Exemplo n.º 26
0
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::_save(Ogre::String filename)
{
    std::ofstream stream(filename.c_str());

    PGInstanceList::iterator it = mInstanceList.begin();

    while(it != mInstanceList.end())
    {
        stream << Ogre::StringConverter::toString(it->first).c_str();
        stream << ";";
        stream << Ogre::StringConverter::toString(it->second.pos).c_str();
        stream << ";";
        stream << Ogre::StringConverter::toString(it->second.scale).c_str();
        stream << ";";
        stream << Ogre::StringConverter::toString(it->second.yaw).c_str();
        stream << "\n";

        it++;
    }
}
Exemplo n.º 27
0
//----------------------------------------------------------------------------------
bool  UILayout::ConvertCEGUIRectToOgre(const Ogre::String& CEGUICoord,Ogre::Vector4& rect)
{
	using namespace std;
	Ogre::Vector4 temVect;


	int n= sscanf(
		CEGUICoord.c_str(),
		" {{%g,%g},{%g,%g},{%g,%g},{%g,%g}}",
		&rect.x, &temVect.x,
		&rect.y, &temVect.y,
		&rect.z, &temVect.z,
		&rect.w, &temVect.w
		);

	if(n==8)
		return true;
	return false;

}
Exemplo n.º 28
0
//-------------------------------------------------------------------------------------
void SpaceLogin::createScene(void)
{
	g_accountName = kbe_getLastAccountName();
	if(g_accountName.size() == 0)
		g_accountName = KBEngine::StringConv::val2str(KBEngine::genUUID64());

	mTrayMgr->createButton(OgreBites::TL_CENTER, "login", "fast login", 120);

	Ogre::StringVector values;
	values.push_back(g_accountName);
	mTrayMgr->createParamsPanel(OgreBites::TL_CENTER, "accountName", 300, values);

	mTrayMgr->showCursor();
	
	mTrayMgr->hideFrameStats();
	mTrayMgr->hideLogo();
	mTrayMgr->hideBackdrop();

	mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);

    // Create the camera
    mActiveCamera = mSceneMgr->createCamera("PlayerCam");

    // Position it at 500 in Z direction
    mActiveCamera->setPosition(Ogre::Vector3(0,0,80));
    // Look back along -Z
    mActiveCamera->lookAt(Ogre::Vector3(0,0,-300));
    mActiveCamera->setNearClipDistance(5);

    mCameraMan = new OgreBites::SdkCameraMan(mActiveCamera);   // create a default camera controller
    mCameraMan->setTopSpeed(7.0f);
	OgreApplication::getSingleton().setCurrCameraMan(mCameraMan);

    // Create one viewport, entire window
    Ogre::Viewport* vp = mWindow->addViewport(mActiveCamera);
    vp->setBackgroundColour(Ogre::ColourValue(0,0,0));

    // Alter the camera aspect ratio to match the viewport
    mActiveCamera->setAspectRatio(
        Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
}
Exemplo n.º 29
0
void TerrainManager::LoadTerrainGeometry(const Ogre::String& name, float* data, Ogre::uint16 size, Ogre::Real worldSize, Ogre::Real minHeight, Ogre::Real maxHeight, const Ogre::Vector3& position)
{
    // Create the manual heightfield
    NxOgre::ManualHeightField mhf;
    mhf.begin(size, size);
    Ogre::Real normMin = -32768.0f;
    Ogre::Real normMax = 32767.0f;
    // Sample the data to the manual heightfield
    for(int x = 0; x < size; ++x)
    {
        NxOgre::Enums::HeightFieldTesselation tess = NxOgre::Enums::HeightFieldTesselation_NW_SE;
        for(int z = size-1; z >= 0; --z)
        {
            Ogre::Real height = data[(size * z) + x];
            short sample = (short)(((height - minHeight) / (maxHeight - minHeight)) * (normMax - normMin) + normMin);
            mhf.sample(sample, 0, 0, tess);
            if(tess == NxOgre::Enums::HeightFieldTesselation_NE_SW)
                tess = NxOgre::Enums::HeightFieldTesselation_NW_SE;
            else
                tess = NxOgre::Enums::HeightFieldTesselation_NE_SW;
        }
    }
    // Create the actual heightfield
    NxOgre::HeightField *hf = mhf.end(name.c_str());
    Ogre::Real hf_size = worldSize + (worldSize / size);
    Ogre::Real hf_height = (maxHeight - minHeight) / 2.0f;
    Ogre::Real hf_pose_x = position.x - (worldSize / 2.0f);
    Ogre::Real hf_pose_y = position.y + ((maxHeight + minHeight) / 2.0f);
    Ogre::Real hf_pose_z = position.z - (worldSize / 2.0f);
#if NxOgreVersionMajor <= 1 && NxOgreVersionMinor <= 5
    NxOgre::HeightFieldGeometry* hfg = new NxOgre::HeightFieldGeometry(hf, NxOgre::Vec3(hf_size, hf_height, hf_size));
    hfg->setLocalPose(NxOgre::Matrix44(NxOgre::Vec3(hf_pose_x, hf_pose_y, hf_pose_z)));
    mSceneGeometry = GameManager::GetInstance()->GetRenderSystem()->getScene()->createSceneGeometry(hfg);
#else
    NxOgre::HeightFieldGeometryDescription desc(hf, NxOgre::Vec3(hf_size, hf_height, hf_size));

    mSceneGeometry = GameManager::GetInstance()->GetRenderSystem()->getScene()->createSceneGeometry(
                         desc, NxOgre::Matrix44(NxOgre::Vec3(hf_pose_x, hf_pose_y, hf_pose_z)));
    mSceneGeometry->setGroup(1);
#endif
}
Exemplo n.º 30
0
        void setIndicatorModel( const Ogre::String &lightType )
        {
            assert( !lightType.empty() );

            assert ( mIndicatorSceneNode );
            assert ( mPointLightEntity );
            assert ( mDirectionalLightEntity );
            assert ( mSpotLightEntity );

            mIndicatorSceneNode->detachAllObjects();

            if ( lightType == "point" )
            {
              //  mIndicatorSceneNode->attachObject(mPointLightEntity);
                mCurrentLightEntity = mPointLightEntity;
				if ( mOldPos != Ogre::Vector3::ZERO )
					mIndicatorSceneNode->setPosition(mOldPos);
            }	
            else if ( lightType == "directional")
            {
             //   mIndicatorSceneNode->attachObject(mDirectionalLightEntity);
				// 因为方向光本身没有位置属性,不过指示器会出现在地形中心,会改变scene node的位置
				// 所以这里先把旧位置保存下来
                mOldPos = mIndicatorSceneNode->getPosition();
                mCurrentLightEntity = mDirectionalLightEntity;
            //    mIndicatorSceneNode->setPosition(0, 0 ,0);

                // 获取到地形中心点的高度
                float height = mSceneManipulator->getTerrainData()->getHeightAt(0,0);
                mIndicatorSceneNode->setPosition(0, height ,0);
            }
            else if ( lightType == "spotlight" )
            {
             //   mIndicatorSceneNode->attachObject(mSpotLightEntity);
                mCurrentLightEntity = mSpotLightEntity;
				if ( mOldPos != Ogre::Vector3::ZERO )
					mIndicatorSceneNode->setPosition(mOldPos);
            }

            mIndicatorSceneNode->attachObject(mCurrentLightEntity);
        }