void SurveyMapEntity::updateIcon() { // check if static only icon String imageFile = "icon_" + mType + "_" + entityStates[mState] + ".dds"; if (mIsStatic) { imageFile = "icon_" + mType + ".dds"; } // set image texture to load it into memory, so TextureManager::getByName will have it loaded if files exist mIcon->setImageTexture(imageFile); TexturePtr texture = (TexturePtr)(TextureManager::getSingleton().getByName(imageFile)); if (texture.isNull()) { imageFile = "icon_missing.dds"; texture = (TexturePtr)(TextureManager::getSingleton().getByName(imageFile)); } if (!texture.isNull()) { mIconSize.width = (int)texture->getWidth(); mIconSize.height = (int)texture->getHeight(); mIcon->setSize(mIconSize); } if (mIconRotating) { mIconRotating->setCenter(MyGUI::IntPoint(mIcon->getWidth()/2, mIcon->getHeight()/2)); mIconRotating->setAngle(mRotation); } }
void TextureToolWindow::saveTexture(String texName, bool usePNG) { try { TexturePtr tex = TextureManager::getSingleton().getByName(texName); if (tex.isNull()) return; Image img; tex->convertToImage(img); // Save to disk! String outname = std::string(App::sys_user_dir.GetActive()) + RoR::PATH_SLASH + texName; if (usePNG) outname += ".png"; img.save(outname); UTFString msg = _L("saved texture as ") + outname; RoR::App::GetConsole()->putMessage(Console::CONSOLE_MSGTYPE_INFO, Console::CONSOLE_MSGTYPE_INFO, msg, "information.png"); } catch (Exception& e) { UTFString str = "Exception while saving image: " + e.getFullDescription(); RoR::App::GetConsole()->putMessage(Console::CONSOLE_MSGTYPE_INFO, Console::CONSOLE_MSGTYPE_INFO, str, "error.png"); } }
bool SurveyMapTextureCreator::init() { TexturePtr texture = TextureManager::getSingleton().createManual(getTextureName(), ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 2048, 2048, TU_RENDERTARGET, PF_R8G8B8, TU_RENDERTARGET, new ResourceBuffer()); if ( texture.isNull() ) return false;; mRttTex = texture->getBuffer()->getRenderTarget(); if ( !mRttTex ) return false; mRttTex->setAutoUpdated(false); mCamera = gEnv->sceneManager->createCamera(getCameraName()); mViewport = mRttTex->addViewport(mCamera); mViewport->setBackgroundColour(ColourValue::Black); mViewport->setOverlaysEnabled(false); mViewport->setShadowsEnabled(false); mViewport->setSkiesEnabled(false); mMaterial = MaterialManager::getSingleton().create(getMaterialName(), ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if ( mMaterial.isNull() ) return false; mTextureUnitState = mMaterial->getTechnique(0)->getPass(0)->createTextureUnitState(getTextureName()); mRttTex->addListener(this); mCamera->setFixedYawAxis(false); mCamera->setProjectionType(PT_ORTHOGRAPHIC); mCamera->setNearClipDistance(1.0f); return true; }
TexturePtr ResourceStorage::getTexture(const std::wstring& path) { TexturePtr texture = getResource<Texture>(path); if (texture.isNull()) { texture = loadTexture(path); } return texture; }
//----------------------------------------------------------------------------------- void PbsMaterial::setTexture(SamplerType samplerType, TexturePtr tex, TextureAddressing textureAddr, float blendFactor1, float blendFactor2, BlendFunction blendFunc, float intensityFactor) { SamplerContainer& s = _samplers[samplerType]; if (s.status == SS_ACTIVE && tex == s.tex && s.blendFunc == blendFunc && s.blendFactor1 == blendFactor1 && s.blendFactor2 == blendFactor2 && s.intensity == intensityFactor && s.textureAddressing == textureAddr) return; if (s.status == SS_NOT_ACTIVE && tex.isNull()) return; if (!tex.isNull()) { // Ensure that the texture in the shader is in linear space tex->setHardwareGammaEnabled(mCanHardwareGamma && s.needsGammaCorrection); if (s.status == SS_NOT_ACTIVE) s.status = SS_ADDED; else if (s.status == SS_ACTIVE) s.status = SS_UPDATED; else if (s.status == SS_UPDATED) s.status = SS_UPDATED; else if (s.status == SS_ADDED) s.status = SS_ADDED; else if (s.status == SS_REMOVED) s.status = SS_UPDATED; } else { if (s.status == SS_NOT_ACTIVE) s.status = SS_NOT_ACTIVE; else if (s.status == SS_ACTIVE) s.status = SS_REMOVED; else if (s.status == SS_UPDATED) s.status = SS_REMOVED; else if (s.status == SS_ADDED) s.status = SS_NOT_ACTIVE; else if (s.status == SS_REMOVED) s.status = SS_REMOVED; } s.tex = tex; s.textureAddressing = textureAddr; s.blendFunc = blendFunc; s.blendFactor1 = blendFactor1; s.blendFactor2 = blendFactor2; s.intensity = intensityFactor; s.mipmapCount = tex.isNull() ? 0.0f : tex->getNumMipmaps(); _hasSamplerChanged = true; _hasSamplerListChanged = s.status == SS_ADDED || s.status == SS_REMOVED; }
//----------------------------------------------------------------------- std::pair< size_t, size_t > TextureUnitState::getTextureDimensions( unsigned int frame ) const { TexturePtr tex = _getTexturePtr(frame); if (tex.isNull()) OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Could not find texture " + mFrames[ frame ], "TextureUnitState::getTextureDimensions" ); return std::pair< size_t, size_t >( tex->getWidth(), tex->getHeight() ); }
void GrassLayer::setDensityMap(TexturePtr map, MapChannel channel) { if (densityMap) { densityMap->unload(); densityMap = NULL; } if (map.isNull() == false) { densityMap = DensityMap::load(map, channel); densityMap->setFilter(densityMapFilter); } }
void GrassLayer::setColorMap(TexturePtr map, MapChannel channel) { if (colorMap) { colorMap->unload(); colorMap = NULL; } if (map.isNull() == false) { colorMap = ColorMap::load(map, channel); colorMap->setFilter(colorMapFilter); } }
void DashBoard::windowResized() { if (!mainWidget) return; mainWidget->setPosition(0, 0); if (textureLayer) { // texture layers are independent from the screen size, but rather from the layer texture size TexturePtr tex = TextureManager::getSingleton().getByName("RTTTexture1"); if (!tex.isNull()) mainWidget->setSize(tex->getWidth(), tex->getHeight()); } else { MyGUI::IntSize screenSize = MyGUI::RenderManager::getInstance().getViewSize(); mainWidget->setSize(screenSize); } }
//----------------------------------------------------------------------- void PagingLandScapeTexture_Splatting7::LoadAlphaMap(const String &filename) const { TexturePtr tex = TextureManager::getSingleton().getByName (filename); if (tex.isNull()) { Image Imageloader; const String group = PagingLandScapeOptions::getSingleton().groupName; Imageloader.load (filename, group); const size_t psize = PagingLandScapeOptions::getSingleton().PageSize - 1; Image ImageConvertertoAlphaFormat; ImageConvertertoAlphaFormat.loadDynamicImage(Imageloader.getData(), psize, psize, 1, PF_A8, false); TextureManager::getSingleton().loadImage (filename, group, ImageConvertertoAlphaFormat); } }
//--------------------------------------------------------------------- bool CompositorManager::isInputPreviousTarget(CompositorInstance* inst, TexturePtr tex) { CompositionTechnique::TargetPassIterator tpit = inst->getTechnique()->getTargetPassIterator(); while(tpit.hasMoreElements()) { CompositionTargetPass* tp = tpit.getNext(); if (tp->getInputMode() == CompositionTargetPass::IM_PREVIOUS) { // Don't have to worry about an MRT, because no MRT can be input previous TexturePtr t = inst->getTextureInstance(tp->getOutputName(), 0); if (!t.isNull() && t.get() == tex.get()) return true; } } return false; }
//---------------------------------------------------------------------() bool CompositorManager::isInputToOutputTarget(CompositorInstance* inst, TexturePtr tex) { CompositionTargetPass* tp = inst->getTechnique()->getOutputTargetPass(); CompositionTargetPass::PassIterator pit = tp->getPassIterator(); while(pit.hasMoreElements()) { CompositionPass* p = pit.getNext(); for (size_t i = 0; i < p->getNumInputs(); ++i) { TexturePtr t = inst->getTextureInstance(p->getInput(i).name, 0); if (!t.isNull() && t.get() == tex.get()) return true; } } return false; }
//----------------------------------------------------------------------- void TextureUnitState::setTexture( const TexturePtr& texPtr) { if (texPtr.isNull()) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texture Pointer is empty.", "TextureUnitState::setTexture"); } setContentType(CONTENT_NAMED); mTextureLoadFailed = false; if (texPtr->getTextureType() == TEX_TYPE_CUBE_MAP) { // delegate to cubic texture implementation setCubicTexture(&texPtr, true); } else { mFrames.resize(1); mFramePtrs.resize(1); mFrames[0] = texPtr->getName(); mFramePtrs[0] = texPtr; // defer load until used, so don't grab pointer yet mCurrentFrame = 0; mCubic = false; mTextureType = texPtr->getTextureType(); // Load immediately ? if (isLoaded()) { _load(); // reload } // Tell parent to recalculate hash if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) ) { mParent->_dirtyHash(); } } }
void App::LoadTrackEv() { Ogre::Timer ti; NewCommon(false); // full destroy iObjCur = -1; scn->DestroyRoad(); scn->DestroyPace(); // load scene scn->sc->LoadXml(gcom->TrkDir()+"scene.xml"); scn->sc->vdr = IsVdrTrack(); if (scn->sc->vdr) scn->sc->ter = false; // water RTT recreate scn->UpdateWaterRTT(mCamera); BltWorldInit(); UpdWndTitle(); scn->CreateFluids(); scn->CreateWeather(); // set sky tex name for water sh::MaterialInstance* m = mFactory->getMaterialInstance(scn->sc->skyMtr); std::string skyTex = sh::retrieveValue<sh::StringValue>(m->getProperty("texture"), 0).get(); sh::Factory::getInstance().setTextureAlias("SkyReflection", skyTex); sh::Factory::getInstance().setTextureAlias("CubeReflection", "ReflectionCube"); bNewHmap = false;/**/ scn->CreateTerrain(bNewHmap, scn->sc->ter); if (track) if (scn->sc->vdr) // vdrift track { if (!LoadTrackVdr(pSet->gui.track)) LogO("Error during track loading: " + pSet->gui.track); CreateVdrTrack(pSet->gui.track, track); CreateVdrTrackBlt(); } // road ~ scn->road = new SplineRoad(this); scn->road->Setup("sphere.mesh", pSet->road_sphr, scn->terrain, mSceneMgr, mCamera); scn->road->LoadFile(gcom->TrkDir()+"road.xml"); scn->UpdPSSMMaterials(); // pace ~ ~ scn->pace = new PaceNotes(pSet); scn->pace->Setup(mSceneMgr, mCamera, scn->terrain, gui->mGui, mWindow); /// HW_Inst Test * * * //inst = new Instanced(); //inst->Create(mSceneMgr,"sphere_inst.mesh"); CreateObjects(); if (pSet->bTrees && scn->sc->ter) scn->CreateTrees(); // trees after objects so they aren't inside them // updates after load //-------------------------- gcom->ReadTrkStats(); gui->SetGuiFromXmls(); /// Rnd2TexSetup(); //UpdVisGui(); //UpdStartPos(); UpdEditWnds(); // try { TexturePtr tex = TextureManager::getSingleton().getByName("waterDepth.png"); if (!tex.isNull()) tex->reload(); } catch(...) { } gui->Status("#{Loaded}", 0.5,0.7,1.0); if (pSet->check_load) gui->WarningsCheck(scn->sc, scn->road); LogO(String("::: Time Load Track: ") + fToStr(ti.getMilliseconds(),0,3) + " ms"); }
/// save water depth map //----------------------------------------------------------------------------------------------------------- void App::SaveWaterDepth() { if (scn->sc->fluids.empty()) { gui->Delete(gcom->TrkDir()+"objects/waterDepth.png"); // no tex if no fluids return; } Ogre::Timer ti; // 2048 for bigger terrains ? int w = 1024, h = w; float fh = h-1, fw = w-1; using Ogre::uint; uint *wd = new uint[w*h]; // water depth register int x,y,a,i,ia,id; register float fa,fd; /// write to img ----------- // get ter height to fluid height difference for below for (y = 0; y < h; ++y) { a = y*w; for (x = 0; x < w; ++x, ++a) { // pos 0..1 float fx = float(y)/fh, fz = float(x)/fw; // pos on ter -terSize..terSize float w = scn->sc->td.fTerWorldSize; float wx = (fx-0.5f) * w, wz = -(fz-0.5f) * w; fa = 0.f; // fluid y pos for (i=0; i < scn->sc->fluids.size(); ++i) { const FluidBox& fb = scn->sc->fluids[i]; const float sizex = fb.size.x*0.5f, sizez = fb.size.z*0.5f; // check rect 2d - no rot ! todo: make 2nd type circle.. if (wx > fb.pos.x - sizex && wx < fb.pos.x + sizex && wz > fb.pos.z - sizez && wz < fb.pos.z + sizez) { float f = fb.pos.y - scn->terrain->getHeightAtTerrainPosition(fx,fz); if (f > fa) fa = f; } } //par fd = fa * 0.4f * 255.f; // depth far full at 2.5 m fa = fa * 8.f * 255.f; // alpha near full at 1/8 m ia = std::max(0, std::min(255, (int)fa )); // clamp id = std::max(0, std::min(255, (int)fd )); wd[a] = 0xFF000000 + /*0x01 */ ia + 0x0100 * id; // write } } Image im; // save img im.loadDynamicImage((uchar*)wd, w,h,1, PF_BYTE_RGBA); im.save(gcom->TrkDir()+"objects/waterDepth.png"); delete[] wd; try { TexturePtr tex = TextureManager::getSingleton().getByName("waterDepth.png"); if (!tex.isNull()) tex->reload(); else // 1st fluid after start, refresh matdef ?.. TextureManager::getSingleton().load("waterDepth.png", rgDef); } catch(...) { } LogO(String("::: Time WaterDepth: ") + fToStr(ti.getMilliseconds(),0,3) + " ms"); }
void App::LoadTrackEv() { QTimer ti; ti.update(); /// time NewCommon(false); // full destroy if (road) { road->Destroy(); delete road; road = 0; } // load scene sc->LoadXml(gcom->TrkDir()+"scene.xml"); sc->vdr = IsVdrTrack(); if (sc->vdr) sc->ter = false; // water RTT recreate UpdateWaterRTT(mCamera); BltWorldInit(); UpdWndTitle(); CreateFluids(); CreateWeather(); // set sky tex name for water sh::MaterialInstance* m = mFactory->getMaterialInstance(sc->skyMtr); std::string skyTex = sh::retrieveValue<sh::StringValue>(m->getProperty("texture"), 0).get(); sh::Factory::getInstance().setTextureAlias("SkyReflection", skyTex); sh::Factory::getInstance().setTextureAlias("CubeReflection", "ReflectionCube"); bNewHmap = false;/**/ CreateTerrain(bNewHmap,sc->ter); if (sc->vdr) // vdrift track { if (!LoadTrackVdr(pSet->gui.track)) LogO("Error during track loading: " + pSet->gui.track); CreateVdrTrack(pSet->gui.track, track); CreateVdrTrackBlt(); } // road ~ road = new SplineRoad(this); road->Setup("sphere.mesh", 1.4f*pSet->road_sphr, terrain, mSceneMgr, mCamera); road->LoadFile(gcom->TrkDir()+"road.xml"); UpdPSSMMaterials(); CreateObjects(); if (pSet->bTrees && sc->ter) CreateTrees(); // trees after objects so they aren't inside them // updates after load //-------------------------- gcom->ReadTrkStats(); gui->SetGuiFromXmls(); /// Rnd2TexSetup(); UpdVisGui(); LoadStartPos(gcom->TrkDir()); try { TexturePtr tex = TextureManager::getSingleton().getByName("waterDepth.png"); if (!tex.isNull()) tex->reload(); } catch(...) { } gui->Status("Loaded", 0.5,0.7,1.0); if (pSet->check_load) gui->WarningsCheck(sc,road); ti.update(); /// time float dt = ti.dt * 1000.f; LogO(String("::: Time Load Track: ") + fToStr(dt,0,3) + " ms"); }
void TextureToolWindow::updateControls(String texName) { try { bool exists = TextureManager::getSingleton().resourceExists(texName); if (!exists) { mTxt->setCaption(convertToMyGUIString("Texture not found:\n" + texName)); mBtnSavePNG->setEnabled(false); return; } TexturePtr tex = TextureManager::getSingleton().getByName(texName); if (tex.isNull()) { mTxt->setCaption(convertToMyGUIString("Error loading texture:\n" + texName)); mBtnSavePNG->setEnabled(false); return; } String str = "#aa0000" + texName + "#000000\n"; str += "#00aa00res: #000000" + TOSTRING(tex->getWidth()) + " x " + TOSTRING(tex->getHeight()) + " pixels\n"; str += "#00aa00size: #000000" + formatBytes(tex->getSize()) + "\n"; str += "#00aa00format: #000000" + PixelUtil::getFormatName(tex->getFormat()) + "\n"; if (tex->getNumFaces() > 1) str += "#00aa00faces: #000000" + TOSTRING(tex->getNumFaces()) + "\n"; if (tex->getFSAA() > 0) str += "#00aa00FSAA: #000000" + TOSTRING(tex->getFSAA()) + "\n"; if (tex->getNumMipmaps() > 0) str += "#00aa00mipmaps: #000000" + TOSTRING(tex->getNumMipmaps()) + "\n"; String typeStr = ""; switch (tex->getTextureType()) { case TEX_TYPE_1D: typeStr = "1D"; break; case TEX_TYPE_2D: typeStr = "2D"; break; case TEX_TYPE_3D: typeStr = "3D"; break; case TEX_TYPE_CUBE_MAP: typeStr = "Cube Map"; break; } str += "#00aa00type: #000000" + typeStr + "\n"; String usageStr = ""; if (tex->getUsage() & TU_STATIC) usageStr += "static,\n"; if (tex->getUsage() & TU_DYNAMIC) usageStr += "dynamic,\n"; if (tex->getUsage() & TU_WRITE_ONLY) usageStr += "write only,\n"; if (tex->getUsage() & TU_STATIC_WRITE_ONLY) usageStr += "static write only,\n"; if (tex->getUsage() & TU_DYNAMIC_WRITE_ONLY) usageStr += "dynamic write only,\n"; if (tex->getUsage() & TU_DYNAMIC_WRITE_ONLY_DISCARDABLE) usageStr += "dynamic write only discardable,\n"; if (tex->getUsage() & TU_AUTOMIPMAP) usageStr += "automipmap,\n"; if (tex->getUsage() & TU_RENDERTARGET) usageStr += "rendertarget,\n"; if (tex->getUsage() & TU_DEFAULT) usageStr += "default\n"; str += "#00aa00usage: #000000" + usageStr + "\n"; if (tex->getDepth() > 1) str += "#00aa00depth: #000000" + TOSTRING(tex->getDepth()) + "\n"; mTxt->setCaption(convertToMyGUIString(str)); mImage->setImageTexture(texName); mBtnSavePNG->setEnabled(true); } catch (Exception& e) { UTFString str = "Exception while opening texture:" + e.getFullDescription(); RoR::App::GetConsole()->putMessage(Console::CONSOLE_MSGTYPE_INFO, Console::CONSOLE_MSGTYPE_INFO, str, "error.png"); } }
//--------------------------------------------------------------------- TexturePtr CompositorManager::getPooledTexture(const String& name, const String& localName, size_t w, size_t h, PixelFormat f, uint aa, const String& aaHint, bool srgb, CompositorManager::UniqueTextureSet& texturesAssigned, CompositorInstance* inst, CompositionTechnique::TextureScope scope) { if (scope == CompositionTechnique::TS_GLOBAL) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Global scope texture can not be pooled.", "CompositorManager::getPooledTexture"); } TextureDef def(w, h, f, aa, aaHint, srgb); if (scope == CompositionTechnique::TS_CHAIN) { StringPair pair = std::make_pair(inst->getCompositor()->getName(), localName); TextureDefMap& defMap = mChainTexturesByDef[pair]; TextureDefMap::iterator it = defMap.find(def); if (it != defMap.end()) { return it->second; } // ok, we need to create a new one TexturePtr newTex = TextureManager::getSingleton().createManual( name, ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, (uint)w, (uint)h, 0, f, TU_RENDERTARGET, 0, srgb, aa, aaHint); defMap.insert(TextureDefMap::value_type(def, newTex)); return newTex; } TexturesByDef::iterator i = mTexturesByDef.find(def); if (i == mTexturesByDef.end()) { TextureList* texList = OGRE_NEW_T(TextureList, MEMCATEGORY_GENERAL); i = mTexturesByDef.insert(TexturesByDef::value_type(def, texList)).first; } CompositorInstance* previous = inst->getChain()->getPreviousInstance(inst); CompositorInstance* next = inst->getChain()->getNextInstance(inst); TexturePtr ret; TextureList* texList = i->second; // iterate over the existing textures and check if we can re-use for (TextureList::iterator t = texList->begin(); t != texList->end(); ++t) { TexturePtr& tex = *t; // check not already used if (texturesAssigned.find(tex.get()) == texturesAssigned.end()) { bool allowReuse = true; // ok, we didn't use this one already // however, there is an edge case where if we re-use a texture // which has an 'input previous' pass, and it is chained from another // compositor, we can end up trying to use the same texture for both // so, never allow a texture with an input previous pass to be // shared with its immediate predecessor in the chain if (isInputPreviousTarget(inst, localName)) { // Check whether this is also an input to the output target of previous // can't use CompositorInstance::mPreviousInstance, only set up // during compile if (previous && isInputToOutputTarget(previous, tex)) allowReuse = false; } // now check the other way around since we don't know what order they're bound in if (isInputToOutputTarget(inst, localName)) { if (next && isInputPreviousTarget(next, tex)) allowReuse = false; } if (allowReuse) { ret = tex; break; } } } if (ret.isNull()) { // ok, we need to create a new one ret = TextureManager::getSingleton().createManual( name, ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, (uint)w, (uint)h, 0, f, TU_RENDERTARGET, 0, srgb, aa, aaHint); texList->push_back(ret); } // record that we used this one in the requester's list texturesAssigned.insert(ret.get()); return ret; }
void App::CreateVdrTrack(std::string strack, TRACK* pTrack) { // materials ------------- std::vector<OGRE_MESH>& meshes = pTrack->ogre_meshes; std::string sMatCache = strack + ".matdef", sMatOrig = "_" + sMatCache, sPathCache = PATHMANAGER::ShaderDir() + "/" + sMatCache, sPathOrig = gcom->TrkDir() +"objects/"+ sMatOrig; bool hasMatOrig = boost::filesystem::exists(sPathOrig), hasMatCache = boost::filesystem::exists(sPathCache); bool bGenerate = 0, gen = !hasMatOrig && !hasMatCache || bGenerate; // set 1 to force generate for new vdrift tracks //TODO .mat ..rewrite this code for new system #if 0 if (gen) { String sMtrs; for (int i=0; i < meshes.size(); i++) { OGRE_MESH& msh = meshes[i]; if (msh.sky /*&& ownSky*/) continue; if (!msh.newMtr) continue; // create material if new bool found = true; TexturePtr tex = TextureManager::getSingleton().getByName(msh.material); if (tex.isNull()) try{ tex = TextureManager::getSingleton().load(msh.material, rgDef); } catch(...){ found = false; } msh.found = found; // dont create meshes for not found textures, test if (!found) continue; #if 0 // use 0 for some tracks (eg.zandvoort) - have alpha textures for all! if (!tex.isNull() && tex->hasAlpha()) msh.alpha = true; // for textures that have alpha #endif if (msh.alpha) sMtrs += "["+msh.material+"]\n"+ " parent = 0vdrAlpha\n"+ " diffuseMap_512 = "+msh.material+"\n"; else sMtrs += "["+msh.material+"]\n"+ " parent = 0vdrTrk\n"+ " diffuseMap_512 = "+msh.material+"\n"; } std::ofstream fileout(sPathCache.c_str()); if (!fileout) LogO("Error: Can't save vdrift track matdef!"); fileout.write(sMtrs.c_str(), sMtrs.size()); fileout.close(); hasMatCache = true; } #endif // meshes ------------- std::vector<Entity*> ents; static int ii = 0; int i; for (i=0; i < meshes.size(); ++i) { OGRE_MESH& msh = meshes[i]; if (msh.sky /*&& ownSky*/) continue; if (!msh.found) continue; //if (strstr(msh.material.c_str(), "tree")!=0) continue; //LogO( String("--- model: ") + msh.name + " mtr:" + msh.material + //" v:" + toStr(msh.mesh->vertices.size()) + " f:" + toStr(msh.mesh->faces.size()) ); //if (ownSky && msh.sky) if (!msh.sky) { ManualObject* m = CreateModel(mSceneMgr, msh.material, msh.mesh, Vector3(0,0,0), false, true); //if (!m) continue; if (msh.sky) m->setCastShadows(false); MeshPtr mp = m->convertToMesh("m"+toStr(ii+i)); Entity* e = mSceneMgr->createEntity(mp); ents.push_back(e); } } ii += i; // static geom ------------- scn->vdrTrack = mSceneMgr->createStaticGeometry("track"); scn->vdrTrack->setRegionDimensions(Vector3::UNIT_SCALE * 1000); // 1000 scn->vdrTrack->setOrigin(Vector3::ZERO); scn->vdrTrack->setCastShadows(true); for (std::vector<Entity*>::iterator it = ents.begin(); it != ents.end(); ++it) scn->vdrTrack->addEntity(*it, Vector3::ZERO); scn->vdrTrack->build(); //mStaticGeom->dump("_track-sg.txt"); }
void ImpostorTexture::renderTextures(bool force) { #ifdef IMPOSTOR_FILE_SAVE TexturePtr renderTexture; #else TexturePtr renderTexture(texture); //if we're not using a file image we need to set up a resource loader, so that the texture is regenerated if it's ever unloaded (such as switching between fullscreen and the desktop in win32) loader = std::auto_ptr<ImpostorTextureResourceLoader>(new ImpostorTextureResourceLoader(*this)); #endif RenderTexture *renderTarget; Camera *renderCamera; Viewport *renderViewport; SceneNode *camNode; //Set up RTT texture uint32 textureSize = ImpostorPage::impostorResolution; if (renderTexture.isNull()) { renderTexture = TextureManager::getSingleton().createManual(getUniqueID("ImpostorTexture"), "Impostors", TEX_TYPE_2D, textureSize * IMPOSTOR_YAW_ANGLES, textureSize * IMPOSTOR_PITCH_ANGLES, 0, PF_A8R8G8B8, TU_RENDERTARGET, loader.get()); } renderTexture->setNumMipmaps(MIP_UNLIMITED); //Set up render target renderTarget = renderTexture->getBuffer()->getRenderTarget(); renderTarget->setAutoUpdated(false); //Set up camera camNode = sceneMgr->getSceneNode("ImpostorPage::cameraNode"); renderCamera = sceneMgr->createCamera(getUniqueID("ImpostorCam")); camNode->attachObject(renderCamera); renderCamera->setLodBias(1000.0f); renderViewport = renderTarget->addViewport(renderCamera); renderViewport->setOverlaysEnabled(false); renderViewport->setClearEveryFrame(true); renderViewport->setShadowsEnabled(false); renderViewport->setBackgroundColour(ImpostorPage::impostorBackgroundColor); //Set up scene node SceneNode* node = sceneMgr->getSceneNode("ImpostorPage::renderNode"); Ogre::SceneNode* oldSceneNode = entity->getParentSceneNode(); if (oldSceneNode) { oldSceneNode->detachObject(entity); } node->attachObject(entity); node->setPosition(-entityCenter); //Set up camera FOV const Real objDist = entityRadius * 100; const Real nearDist = objDist - (entityRadius + 1); const Real farDist = objDist + (entityRadius + 1); renderCamera->setAspectRatio(1.0f); renderCamera->setFOVy(Math::ATan(entityDiameter / objDist)); renderCamera->setNearClipDistance(nearDist); renderCamera->setFarClipDistance(farDist); //Disable mipmapping (without this, masked textures look bad) MaterialManager *mm = MaterialManager::getSingletonPtr(); FilterOptions oldMinFilter = mm->getDefaultTextureFiltering(FT_MIN); FilterOptions oldMagFilter = mm->getDefaultTextureFiltering(FT_MAG); FilterOptions oldMipFilter = mm->getDefaultTextureFiltering(FT_MIP); mm->setDefaultTextureFiltering(FO_POINT, FO_LINEAR, FO_NONE); //Disable fog FogMode oldFogMode = sceneMgr->getFogMode(); ColourValue oldFogColor = sceneMgr->getFogColour(); Real oldFogDensity = sceneMgr->getFogDensity(); Real oldFogStart = sceneMgr->getFogStart(); Real oldFogEnd = sceneMgr->getFogEnd(); sceneMgr->setFog(Ogre::FOG_EXP2, Ogre::ColourValue(0,0,0,0), 0.0f, 0.0f, 0.0f); //Ember change //We need to disable all lightning and render it full bright Ogre::ColourValue oldAmbientColour = sceneMgr->getAmbientLight(); sceneMgr->setAmbientLight(ColourValue::White); std::vector<Ogre::MovableObject*> lightStore; Ogre::SceneManager::MovableObjectIterator lightIterator = sceneMgr->getMovableObjectIterator(Ogre::LightFactory::FACTORY_TYPE_NAME); while (lightIterator.hasMoreElements()) { Ogre::MovableObject* light = lightIterator.getNext(); if (light) { if (light->getVisible()) { lightStore.push_back(light); light->setVisible(false); } } } // Get current status of the queue mode Ogre::SceneManager::SpecialCaseRenderQueueMode OldSpecialCaseRenderQueueMode = sceneMgr->getSpecialCaseRenderQueueMode(); //Only render the entity sceneMgr->setSpecialCaseRenderQueueMode(Ogre::SceneManager::SCRQM_INCLUDE); sceneMgr->addSpecialCaseRenderQueue(group->geom->getRenderQueue() + 1); uint8 oldRenderQueueGroup = entity->getRenderQueueGroup(); entity->setRenderQueueGroup(group->geom->getRenderQueue() + 1); bool oldVisible = entity->getVisible(); entity->setVisible(true); float oldMaxDistance = entity->getRenderingDistance(); entity->setRenderingDistance(0); bool needsRegen = true; #ifdef IMPOSTOR_FILE_SAVE //Calculate the filename hash used to uniquely identity this render String strKey = entityKey; char key[32] = {0}; uint32 i = 0; for (String::const_iterator it = entityKey.begin(); it != entityKey.end(); ++it) { key[i] ^= *it; i = (i+1) % sizeof(key); } for (i = 0; i < sizeof(key); ++i) key[i] = (key[i] % 26) + 'A'; String tempdir = this->group->geom->getTempdir(); ResourceGroupManager::getSingleton().addResourceLocation(tempdir, "FileSystem", "BinFolder"); String fileNamePNG = "Impostor." + String(key, sizeof(key)) + '.' + StringConverter::toString(textureSize) + ".png"; String fileNameDDS = "Impostor." + String(key, sizeof(key)) + '.' + StringConverter::toString(textureSize) + ".dds"; //Attempt to load the pre-render file if allowed needsRegen = force; if (!needsRegen){ try{ texture = TextureManager::getSingleton().load(fileNameDDS, "BinFolder", TEX_TYPE_2D, MIP_UNLIMITED); } catch (...){ try{ texture = TextureManager::getSingleton().load(fileNamePNG, "BinFolder", TEX_TYPE_2D, MIP_UNLIMITED); } catch (...){ needsRegen = true; } } } #endif if (needsRegen){ //If this has not been pre-rendered, do so now const float xDivFactor = 1.0f / IMPOSTOR_YAW_ANGLES; const float yDivFactor = 1.0f / IMPOSTOR_PITCH_ANGLES; for (int o = 0; o < IMPOSTOR_PITCH_ANGLES; ++o){ //4 pitch angle renders #ifdef IMPOSTOR_RENDER_ABOVE_ONLY Radian pitch = Degree((90.0f * o) * yDivFactor); //0, 22.5, 45, 67.5 #else Radian pitch = Degree((180.0f * o) * yDivFactor - 90.0f); #endif for (int i = 0; i < IMPOSTOR_YAW_ANGLES; ++i){ //8 yaw angle renders Radian yaw = Degree((360.0f * i) * xDivFactor); //0, 45, 90, 135, 180, 225, 270, 315 //Position camera camNode->setPosition(0, 0, 0); camNode->setOrientation(Quaternion(yaw, Vector3::UNIT_Y) * Quaternion(-pitch, Vector3::UNIT_X)); camNode->translate(Vector3(0, 0, objDist), Node::TS_LOCAL); //Render the impostor renderViewport->setDimensions((float)(i) * xDivFactor, (float)(o) * yDivFactor, xDivFactor, yDivFactor); renderTarget->update(); } } #ifdef IMPOSTOR_FILE_SAVE //Save RTT to file with respecting the temp dir renderTarget->writeContentsToFile(tempdir + fileNamePNG); //Load the render into the appropriate texture view texture = TextureManager::getSingleton().load(fileNamePNG, "BinFolder", TEX_TYPE_2D, MIP_UNLIMITED); #else texture = renderTexture; #endif } entity->setVisible(oldVisible); entity->setRenderQueueGroup(oldRenderQueueGroup); entity->setRenderingDistance(oldMaxDistance); sceneMgr->removeSpecialCaseRenderQueue(group->geom->getRenderQueue() + 1); // Restore original state sceneMgr->setSpecialCaseRenderQueueMode(OldSpecialCaseRenderQueueMode); //Re-enable mipmapping mm->setDefaultTextureFiltering(oldMinFilter, oldMagFilter, oldMipFilter); //Re-enable fog sceneMgr->setFog(oldFogMode, oldFogColor, oldFogDensity, oldFogStart, oldFogEnd); //Re-enable both scene lightning and disabled individual lights sceneMgr->setAmbientLight(oldAmbientColour); for (std::vector<Ogre::MovableObject*>::const_iterator I = lightStore.begin(); I != lightStore.end(); ++I) { (*I)->setVisible(true); } //Delete camera renderTarget->removeViewport(0); renderCamera->getSceneManager()->destroyCamera(renderCamera); //Delete scene node node->detachAllObjects(); if (oldSceneNode) { oldSceneNode->attachObject(entity); } #ifdef IMPOSTOR_FILE_SAVE //Delete RTT texture assert(!renderTexture.isNull()); String texName2(renderTexture->getName()); renderTexture.setNull(); if (TextureManager::getSingletonPtr()) TextureManager::getSingleton().remove(texName2); #endif }
TexturePtr TerrainManager::getVertexColours(ESM::Land* land, int cellX, int cellY, int fromX, int fromY, int size) { TextureManager* const texMgr = TextureManager::getSingletonPtr(); const std::string colourTextureName = "VtexColours_" + boost::lexical_cast<std::string>(cellX) + "_" + boost::lexical_cast<std::string>(cellY) + "_" + boost::lexical_cast<std::string>(fromX) + "_" + boost::lexical_cast<std::string>(fromY); TexturePtr tex = texMgr->getByName(colourTextureName); if ( !tex.isNull() ) { return tex; } tex = texMgr->createManual(colourTextureName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, size, size, 0, PF_BYTE_BGR); HardwarePixelBufferSharedPtr pixelBuffer = tex->getBuffer(); pixelBuffer->lock(HardwareBuffer::HBL_DISCARD); const PixelBox& pixelBox = pixelBuffer->getCurrentLock(); uint8* pDest = static_cast<uint8*>(pixelBox.data); if ( land != NULL ) { const char* const colours = land->mLandData->mColours; for ( int y = 0; y < size; y++ ) { for ( int x = 0; x < size; x++ ) { const size_t colourOffset = (y+fromY)*3*65 + (x+fromX)*3; assert( colourOffset < 65*65*3 && "Colour offset is out of the expected bounds of record" ); const unsigned char r = colours[colourOffset + 0]; const unsigned char g = colours[colourOffset + 1]; const unsigned char b = colours[colourOffset + 2]; //as is the case elsewhere we need to flip the y const size_t imageOffset = (size - 1 - y)*size*4 + x*4; pDest[imageOffset + 0] = b; pDest[imageOffset + 1] = g; pDest[imageOffset + 2] = r; } } } else { for ( int y = 0; y < size; y++ ) { for ( int x = 0; x < size; x++ ) { for ( int k = 0; k < 3; k++ ) { *pDest++ = 0; } } } } pixelBuffer->unlock(); return tex; }