virtual void initialize(const ObjectAdapterPtr&, const Identity&, const string&, const ObjectPtr& servant) { Test::ServantI* servantI = dynamic_cast<Test::ServantI*>(servant.get()); if(servantI != 0) { servantI->init(_remoteEvictor, _evictor); } else { Test::AccountI* account = dynamic_cast<Test::AccountI*>(servant.get()); test(account != 0); account->init(Freeze::TransactionalEvictorPtr::dynamicCast(_evictor)); } }
ObjectPtr<> deserialize_object(const ArchiveNode& node, IUniverse& universe) { if (!node.is_map()) { std::cerr << "Expected object, got non-map.\n"; return nullptr; } std::string error; const DerivedType* type = get_type_from_map(node, error); if (type == nullptr) { std::cerr << "ERROR: " << error << '\n'; return nullptr; } std::string id; if (!node["id"].get(id)) { std::cerr << "WARNING: Object without id.\n"; } ObjectPtr<> ptr = universe.create_object(type, id); if (ptr->object_id() != id) { std::cerr << "WARNING: Object '" << id << "' was renamed to '" << ptr->object_id() << "' because of a collision.\n"; } type->deserialize(reinterpret_cast<byte*>(ptr.get()), node, universe); return ptr; }
ConstObjectPtr LiveScene::readObject( double time ) const { tbb::mutex::scoped_lock l( s_mutex ); if( m_dagPath.length() == 0 && !m_isRoot ) { throw Exception( "IECoreMaya::LiveScene::readObject: Dag path no longer exists!" ); } if( fabs( MAnimControl::currentTime().as( MTime::kSeconds ) - time ) > 1.e-4 ) { throw Exception( "IECoreMaya::LiveScene::readObject: time must be the same as on the maya timeline!" ); } for ( std::vector< CustomReader >::const_reverse_iterator it = customObjectReaders().rbegin(); it != customObjectReaders().rend(); it++ ) { if ( it->m_has( m_dagPath ) ) { return it->m_read( m_dagPath ); } } // if no custom object was detected, we try the general cortex converter unsigned int childCount = 0; m_dagPath.numberOfShapesDirectlyBelow(childCount); for ( unsigned int c = 0; c < childCount; c++ ) { MDagPath childDag = m_dagPath; if( childDag.extendToShapeDirectlyBelow( c ) ) { MFnDagNode fnChildDag(childDag); if ( fnChildDag.isIntermediateObject() ) { continue; } FromMayaShapeConverterPtr shapeConverter = FromMayaShapeConverter::create( childDag ); if( shapeConverter ) { return shapeConverter->convert(); } FromMayaDagNodeConverterPtr dagConverter = FromMayaDagNodeConverter::create( childDag ); if( dagConverter ) { ObjectPtr result = dagConverter->convert(); Camera *cam = runTimeCast< Camera >( result.get() ); if( cam ) { // Cameras still carry the transform when converted from maya, // so we have to remove them after conversion. cam->setTransform( new MatrixTransform( Imath::M44f() ) ); } return result; } } } return IECore::NullObject::defaultNullObject(); }
ObjectPtr ModifyOp::doOperation( const CompoundObject *operands ) { ObjectPtr object = m_inputParameter->getValue(); if( m_copyParameter->getTypedValue() ) { object = object->copy(); } if( m_enableParameter->getTypedValue() ) { modify( object.get(), operands ); } return object; }
void AddLightObjectPlugin::onAddObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { LightObject *lightObject = static_cast<LightObject *> (object.get()); Indicator *indicator = new Indicator(object,mSceneManipulator->getSceneManager(), mSceneManipulator ); std::pair<Indicators::iterator, bool> inserted = mIndicators.insert(Indicators::value_type(object, indicator)); assert(inserted.second); } }
void Scene::addObject(ObjectPtr pObject) { SIACheckRet(!pObject.get()); SIAAssert(m_pGameLayer); auto pEntity = pObject->entity(); SIAAssert(pEntity); m_modelController.addCommand(std::make_shared<Commands::AddEntity>(pEntity), [pObject, this] () { auto pView = pObject->view(); SIAAssert(pView); m_pGameLayer->addGameView(pView); m_pObjects.push_back(pObject); SIADebug("Added object on scene."); }, nullptr); }
void SceneBrowser::OnContextMenu( ObjectPtr &object, wxTreeEvent& event ) { const Ogre::String &type = object->getType(); if ( type == "Actor" ) { ActorAnimationSettingDialog *dlg = new ActorAnimationSettingDialog(this, wxID_ANY, _("ActorAnimationSetting Dialog"), object, mSceneManipulator, event.GetPoint()); int result = dlg->Show(true); //if (result == wxID_CANCEL) //{ // // 如果异常列表中仍有内容,就给出提示 // if (dlg->mListBox->GetCount() > 0) // { // wxMessageBox(_("Thera are still some wrongs in scene,remember to fix them!")); // } // else // { // wxMessageBox(_("All wrongs in scene have been fixed,remember to save the scene!")); // } //} } else if ( type == "Effect" ) { Fairy::Effect *effect = static_cast<Fairy::EffectObject *>(object.get())->getEffect(); if ( effect ) { if ( NULL == mEffectDialog ) { mEffectDialog = new WXEffectEditDialog(this, wxID_ANY, _("Effect Setting")); } if ( false == mEffectDialog->IsShown() ) mEffectDialog->Show(); mEffectDialog->InitEffectDialog(effect, mSceneManipulator); } } mSceneManipulator->setActiveAction(NULL); }
void throwUOE(const string& expectedType, const ObjectPtr& v) { // // If the object is an unknown sliced object, we didn't find an // object factory, in this case raise a NoObjectFactoryException // instead. // UnknownSlicedObject* uso = dynamic_cast<UnknownSlicedObject*>(v.get()); if(uso) { throw NoObjectFactoryException(__FILE__, __LINE__, "", uso->getUnknownTypeId()); } string type = v->ice_id(); throw Ice::UnexpectedObjectException(__FILE__, __LINE__, "expected element of type `" + expectedType + "' but received '" + type, type, expectedType); }
void Scene::eraseObject(ObjectPtr pObject) { SIACheckRet(!pObject); SIAAssert(m_pGameLayer); auto pEntity = pObject->entity(); SIAAssert(pEntity); m_modelController.addCommand(std::make_shared<Commands::EraseEntity>(pEntity), [pObject, this] () { auto pView = pObject->view(); SIAAssert(pView); m_pGameLayer->eraseGameView(pView); m_pObjects.erase(std::remove_if(m_pObjects.begin(), m_pObjects.end(), [&pObject] (ObjectPtr& pObj) { return pObject.get() == pObj.get(); }), m_pObjects.end()); SIADebug("Removed object from scene."); }, nullptr); }
Bool Object::tequals(ObjectPtr other) const { return this->tequals(other.get()); }
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool AmpTool::run() { if ( !_originID.empty() ) { OriginPtr org = Origin::Cast(query()->getObject(Origin::TypeInfo(), _originID)); if ( !org ) { cerr << "Origin not found!" << endl; return false; } _fetchMissingAmplitudes = false; query()->loadArrivals(org.get()); process(org.get()); return true; } if ( !_strTimeWindowStartTime.empty() || !_strTimeWindowEndTime.empty() ) { if ( database() == NULL ) { cerr << "No database currently active for time window reprocessing" << endl; return false; } Core::Time startTime, endTime; if ( !_strTimeWindowStartTime.empty() && !startTime.fromString(_strTimeWindowStartTime.c_str(), "%F %T") ) { cerr << "Invalid start time: " << _strTimeWindowStartTime << endl; return false; } if ( !_strTimeWindowEndTime.empty() && !endTime.fromString(_strTimeWindowEndTime.c_str(), "%F %T") ) { cerr << "Invalid end time: " << _strTimeWindowEndTime << endl; return false; } std::string dbQuery; dbQuery += "select PPick." + _T("publicID") + ", Pick.* from Pick,PublicObject as PPick,Amplitude " "where Pick._oid=PPick._oid and Amplitude." + _T("pickID") + "=PPick." + _T("publicID"); if ( startTime.valid() ) dbQuery += " and Pick." + _T("time_value") + ">='" + startTime.toString("%F %T") + "'"; if ( endTime.valid() ) dbQuery += " and Pick." + _T("time_value") + "<'" + endTime.toString("%F %T") + "'"; dbQuery += " group by Amplitude." + _T("pickID"); if ( !commandline().hasOption("commit") ) _testMode = true; EventParametersPtr ep; if ( _testMode ) ep = new EventParameters; typedef list<PickPtr> PickList; PickList picks; cerr << "Collecting picks ... " << flush; DatabaseIterator db_it = query()->getObjectIterator(dbQuery, Pick::TypeInfo()); ObjectPtr obj; while ( obj = db_it.get() ) { Pick *pick = static_cast<Pick*>(obj.get()); try { pick->waveformID().networkCode(); pick->waveformID().stationCode(); pick->waveformID().locationCode(); pick->waveformID().channelCode(); pick->time().value(); } catch ( ... ) { continue; } ++db_it; picks.push_back(pick); if ( ep ) ep->add(pick); } db_it.close(); cerr << picks.size() << endl; _report << std::endl; _report << "Reprocessing report" << std::endl; _report << "-------------------" << std::endl; _report << " + Picks" << std::endl; int errors = 0; int ampsRecomputed = 0; int messagesSent = 0; int idx = 1; for ( PickList::iterator it = picks.begin(); it != picks.end(); ++it, ++idx ) { PickPtr pick = *it; SingleAmplitudeMap dbAmps; if ( isExitRequested() ) break; // Clear all processors _processors.clear(); // Clear all station time windows _stationRequests.clear(); _report << " + " << pick->publicID() << std::endl; cerr << "[" << idx << "]" << " " << (*it)->publicID() << endl; db_it = query()->getAmplitudesForPick((*it)->publicID()); while ( obj = db_it.get() ) { Amplitude *amp = static_cast<Amplitude*>(obj.get()); cerr << " [" << setw(10) << left << amp->type() << "] "; AmplitudeProcessorPtr proc = AmplitudeProcessorFactory::Create(amp->type().c_str()); if ( !proc ) { if ( _amplitudeTypes.find(amp->type()) == _amplitudeTypes.end() ) cerr << "No processor"; else { cerr << "No processor but enabled"; ++errors; } } else { cerr << "Fetch data"; dbAmps[amp->type()] = amp; proc->setTrigger(pick->time().value()); proc->setReferencingPickID(pick->publicID()); proc->setPublishFunction(boost::bind(&AmpTool::storeLocalAmplitude, this, _1, _2)); _report << " + Data" << std::endl; addProcessor(proc.get(), pick.get(), None, None); } cerr << endl; ++db_it; } db_it.close(); cerr << " --------------------------------" << endl; if ( _stationRequests.empty() ) continue; for ( RequestMap::iterator it = _stationRequests.begin(); it != _stationRequests.end(); ++it ) { StationRequest &req = it->second; for ( WaveformIDSet::iterator wit = req.streams.begin(); wit != req.streams.end(); ++wit ) { const WaveformStreamID &wsid = *wit; recordStream()->addStream(wsid.networkCode(), wsid.stationCode(), wsid.locationCode(), wsid.channelCode(), req.timeWindow.startTime(), req.timeWindow.endTime()); } _report << " + TimeWindow (" << it->first << "): " << req.timeWindow.startTime().toString("%F %T") << ", " << req.timeWindow.endTime().toString("%F %T") << std::endl; } _reprocessMap.clear(); readRecords(false); list<AmplitudePtr> updates; for ( AmplitudeMap::iterator it = dbAmps.begin(); it != dbAmps.end(); ++it ) { AmplitudePtr oldAmp = it->second; AmplitudePtr newAmp = _reprocessMap[oldAmp->type()]; cerr << " [" << setw(10) << left << oldAmp->type() << "] " << oldAmp->amplitude().value() << " "; if ( newAmp ) { if ( newAmp->amplitude().value() != oldAmp->amplitude().value() ) { *oldAmp = *newAmp; if ( ep ) ep->add(oldAmp.get()); else updates.push_back(oldAmp); cerr << "-> " << newAmp->amplitude().value(); } else cerr << " no changes"; ++ampsRecomputed; } else { cerr << "-"; ++errors; } cerr << endl; } if ( !updates.empty() ) { if ( !_testMode ) { NotifierMessagePtr nmsg = new NotifierMessage; for ( list<AmplitudePtr>::iterator it = updates.begin(); it != updates.end(); ++it ) { nmsg->attach(new Notifier("EventParameters", OP_UPDATE, it->get())); } connection()->send(nmsg.get()); ++messagesSent; if ( messagesSent % 100 == 0 ) sync(); } else { cerr << " --------------------------------" << endl; cerr << " Test mode, nothing sent" << endl; } } } if ( ep ) { IO::XMLArchive ar; ar.create("-"); ar.setFormattedOutput(true); ar << ep; ar.close(); } cerr << "----------------------------------" << endl; cerr << "Recomputed " << ampsRecomputed << " amplitudes" << endl; cerr << "Sent " << messagesSent << " messages" << endl; if ( errors ) cerr << errors << " errors occurred, check the processing log" << endl; return true; } if ( !_epFile.empty() ) { _fetchMissingAmplitudes = false; // Disable database setDatabase(NULL); _cache.setDatabaseArchive(NULL); IO::XMLArchive ar; if ( !ar.open(_epFile.c_str()) ) { SEISCOMP_ERROR("Failed to open %s", _epFile.c_str()); return false; } ar >> _ep; ar.close(); if ( !_ep ) { SEISCOMP_ERROR("No event parameters found in %s", _epFile.c_str()); return false; } if ( commandline().hasOption("reprocess") ) { for ( size_t i = 0; i < _ep->amplitudeCount(); ++i ) { AmplitudePtr amp = _ep->amplitude(i); feed(amp.get()); } } for ( size_t i = 0; i < _ep->originCount(); ++i ) { OriginPtr org = _ep->origin(i); SEISCOMP_INFO("Processing origin %s", org->publicID().c_str()); process(org.get()); } ar.create("-"); ar.setFormattedOutput(true); ar << _ep; ar.close(); _ep = NULL; return true; }
void Parameter::setValidatedValue( ObjectPtr value ) { validate( value.get() ); setValue( value ); }
qlib::LScrSp<qlib::LScrObjBase> SceneXMLReader::fromByteArray(const qlib::LScrSp<qlib::LByteArray> &pbuf) { qlib::uid_t nSceneID = m_pClient->getUID(); // Enter the context AutoStyleCtxt style_ctxt(nSceneID); MB_DPRINTLN("fromXML\n%s<<<", pbuf->data()); MB_DPRINTLN("Length: %d", pbuf->size()); // // Setup streams // qlib::StrInStream fis(pbuf); qlib::LDom2InStream ois(fis); qlib::LDom2Tree tree; ois.read(tree); qlib::LDom2Node *pNode = tree.top(); //pNode->dump(); qlib::LScrSp<qlib::LScrObjBase> pSObj; LString tag = pNode->getTagName(); LString type_name = pNode->getTypeName(); if (tag.equals("renderer") && !type_name.isEmpty()) { // pbuf contains Renderer RendererFactory *pRF = RendererFactory::getInstance(); RendererPtr pRend = pRF->create(type_name); pRend->resetAllProps(); pRend->readFrom2(pNode); pSObj = pRend; } else if (tag.equals("object") && !type_name.isEmpty()) { ObjectPtr pObj = pNode->createObjByTypeNameT<Object>(); pObj->readFrom2(pNode); LString src = pObj->getSource(); LString altsrc = pObj->getAltSource(); LString srctype = pObj->getSourceType(); pNode->requestDataLoad(src, altsrc, srctype, pObj.get()); pSObj = pObj; // clearChunkMap(); procDataSrcLoad(ois, pNode); procDataChunks(ois, pNode); // clearChunkMap(); } else if (tag.equals("camera")) { // pbuf contains Camera CameraPtr pCam(MB_NEW Camera); pCam->readFrom2(pNode); pSObj = pCam; } else { MB_DPRINTLN("readRendFromXML> ERROR, Invalid QSC XML"); return pSObj; } return pSObj; }
void Freeze::BackgroundSaveEvictorI::run() { try { for(;;) { deque<BackgroundSaveEvictorElementPtr> allObjects; deque<BackgroundSaveEvictorElementPtr> deadObjects; size_t saveNowThreadsSize = 0; { Lock sync(*this); while(!_savingThreadDone && (_saveNowThreads.size() == 0) && (_saveSizeTrigger < 0 || static_cast<Int>(_modifiedQueue.size()) < _saveSizeTrigger)) { if(_savePeriod == IceUtil::Time::milliSeconds(0)) { wait(); } else if(timedWait(_savePeriod) == false) { // // Timeout, so let's save // break; // while } } saveNowThreadsSize = _saveNowThreads.size(); if(_savingThreadDone) { assert(_modifiedQueue.size() == 0); assert(saveNowThreadsSize == 0); break; // for(;;) } // // Check first if there is something to do! // if(_modifiedQueue.size() == 0) { if(saveNowThreadsSize > 0) { _saveNowThreads.clear(); notifyAll(); } continue; // for(;;) } _modifiedQueue.swap(allObjects); } const size_t size = allObjects.size(); deque<StreamedObjectPtr> streamedObjectQueue; Long streamStart = IceUtil::Time::now(IceUtil::Time::Monotonic).toMilliSeconds(); // // Stream each element // for(size_t i = 0; i < size; i++) { BackgroundSaveEvictorElementPtr& element = allObjects[i]; bool tryAgain; do { tryAgain = false; ObjectPtr servant = 0; // // These elements can't be stale as only elements with // usageCount == 0 can become stale, and the modifiedQueue // (us now) owns one count. // IceUtil::Mutex::Lock lockElement(element->mutex); Byte status = element->status; switch(status) { case created: case modified: { servant = element->rec.servant; break; } case destroyed: { size_t index = streamedObjectQueue.size(); streamedObjectQueue.resize(index + 1); streamedObjectQueue[index] = new StreamedObject; stream(element, streamStart, streamedObjectQueue[index]); element->status = dead; deadObjects.push_back(element); break; } case dead: { deadObjects.push_back(element); break; } default: { // // Nothing to do (could be a duplicate) // break; } } if(servant == 0) { lockElement.release(); } else { IceUtil::AbstractMutex* mutex = dynamic_cast<IceUtil::AbstractMutex*>(servant.get()); if(mutex != 0) { // // Lock servant and then element so that user can safely lock // servant and call various Evictor operations // IceUtil::AbstractMutex::TryLock lockServant(*mutex); if(!lockServant.acquired()) { lockElement.release(); IceUtil::TimerTaskPtr watchDogTask; if(_timer) { watchDogTask = new WatchDogTask(*this); _timer->schedule(watchDogTask, IceUtil::Time::milliSeconds(_streamTimeout)); } lockServant.acquire(); if(watchDogTask) { _timer->cancel(watchDogTask); watchDogTask = 0; } lockElement.acquire(); status = element->status; } switch(status) { case created: case modified: { if(servant == element->rec.servant) { size_t index = streamedObjectQueue.size(); streamedObjectQueue.resize(index + 1); streamedObjectQueue[index] = new StreamedObject; stream(element, streamStart, streamedObjectQueue[index]); element->status = clean; } else { tryAgain = true; } break; } case destroyed: { lockServant.release(); size_t index = streamedObjectQueue.size(); streamedObjectQueue.resize(index + 1); streamedObjectQueue[index] = new StreamedObject; stream(element, streamStart, streamedObjectQueue[index]); element->status = dead; deadObjects.push_back(element); break; } case dead: { deadObjects.push_back(element); break; } default: { // // Nothing to do (could be a duplicate) // break; } } } else { DatabaseException ex(__FILE__, __LINE__); Ice::Object& servant = *element->rec.servant; ex.message = string(typeid(servant).name()) + " does not implement IceUtil::AbstractMutex"; throw ex; } } } while(tryAgain); } if(_trace >= 1) { Long now = IceUtil::Time::now(IceUtil::Time::Monotonic).toMilliSeconds(); Trace out(_communicator->getLogger(), "Freeze.Evictor"); out << "streamed " << streamedObjectQueue.size() << " objects in " << static_cast<Int>(now - streamStart) << " ms"; } // // Now let's save all these streamed objects to disk using a transaction // // // Each time we get a deadlock, we reduce the number of objects to save // per transaction // size_t txSize = streamedObjectQueue.size(); if(txSize > static_cast<size_t>(_maxTxSize)) { txSize = static_cast<size_t>(_maxTxSize); } bool tryAgain; do { tryAgain = false; while(streamedObjectQueue.size() > 0) { if(txSize > streamedObjectQueue.size()) { txSize = streamedObjectQueue.size(); } Long saveStart = IceUtil::Time::now(IceUtil::Time::Monotonic).toMilliSeconds(); try { DbTxn* tx = 0; _dbEnv->getEnv()->txn_begin(0, &tx, 0); long txnId = 0; if(_txTrace >= 1) { txnId = (tx->id() & 0x7FFFFFFF) + 0x80000000L; Trace out(_communicator->getLogger(), "Freeze.Evictor"); out << "started transaction " << hex << txnId << dec << " in saving thread"; } try { for(size_t i = 0; i < txSize; i++) { StreamedObjectPtr obj = streamedObjectQueue[i]; Dbt key, value; obj->key->getDbt(key); if(obj->value) { obj->value->getDbt(value); } obj->store->save(key, value, obj->status, tx); } } catch(...) { tx->abort(); if(_txTrace >= 1) { Trace out(_communicator->getLogger(), "Freeze.Evictor"); out << "rolled back transaction " << hex << txnId << dec; } throw; } tx->commit(0); if(_txTrace >= 1) { Trace out(_communicator->getLogger(), "Freeze.Evictor"); out << "committed transaction " << hex << txnId << dec; } streamedObjectQueue.erase(streamedObjectQueue.begin(), streamedObjectQueue.begin() + txSize); if(_trace >= 1) { Long now = IceUtil::Time::now(IceUtil::Time::Monotonic).toMilliSeconds(); Trace out(_communicator->getLogger(), "Freeze.Evictor"); out << "saved " << txSize << " objects in " << static_cast<Int>(now - saveStart) << " ms"; } } catch(const DbDeadlockException&) { if(_deadlockWarning) { Warning out(_communicator->getLogger()); out << "Deadlock in Freeze::BackgroundSaveEvictorI::run while writing into Db \"" + _filename + "\"; retrying ..."; } tryAgain = true; txSize = (txSize + 1)/2; } catch(const DbException& dx) { DatabaseException ex(__FILE__, __LINE__); ex.message = dx.what(); throw ex; } } } while(tryAgain); { Lock sync(*this); // // Release usage count // for(deque<BackgroundSaveEvictorElementPtr>::iterator p = allObjects.begin(); p != allObjects.end(); p++) { BackgroundSaveEvictorElementPtr& element = *p; element->usageCount--; } allObjects.clear(); for(deque<BackgroundSaveEvictorElementPtr>::iterator q = deadObjects.begin(); q != deadObjects.end(); q++) { BackgroundSaveEvictorElementPtr& element = *q; if(!element->stale) { // // Can be stale when there are duplicate elements on the // deadObjecst queue // if(!element->stale && element->usageCount == 0 && element->keepCount == 0) { // // Get rid of unused dead elements // IceUtil::Mutex::Lock lockElement(element->mutex); if(element->status == dead) { evict(element); } } } } deadObjects.clear(); evict(); if(saveNowThreadsSize > 0) { _saveNowThreads.erase(_saveNowThreads.begin(), _saveNowThreads.begin() + saveNowThreadsSize); notifyAll(); } } } } catch(const std::exception& ex) { Error out(_communicator->getLogger()); out << "Saving thread killed by exception: " << ex; out.flush(); handleFatalError(this, _communicator); } catch(...) { Error out(_communicator->getLogger()); out << "Saving thread killed by unknown exception"; out.flush(); handleFatalError(this, _communicator); } }
void AddParticleSystemObjectPlugin::onAddObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(ParticleSystemObject),就处理 if ( type == "ParticleSystem" ) { ParticleSystemObject *particleSystemObject = static_cast<ParticleSystemObject *> (object.get()); Indicator *indicator = new Indicator(object, mSceneManipulator); std::pair<Indicators::iterator, bool> inserted = mIndicators.insert(Indicators::value_type(object, indicator)); assert(inserted.second); } }
Indicator(const ObjectPtr &object, SceneManipulator *sceneManipulator) : mProxy(NULL) { assert(sceneManipulator); mUserAny = Ogre::Any(); mProxy = new ObjectProxy(object); // 根据光源位置来定节点位置 Ogre::Vector3 pos = VariantCast<Ogre::Vector3>(object->getProperty("position")); mIndicatorSceneNode = sceneManipulator->getIndicatorRootSceneNode()->createChildSceneNode(pos); Real radius = 5; int rings = 16; int segments = 16; Ogre::MeshPtr sphereMesh = createCommonSphere(radius, rings, segments); Ogre::MaterialPtr material = createPureColourMaterial( Ogre::ColourValue(1, 0, 0, 0.75) ); mIndicatorEntity = sceneManipulator->getSceneManager()->createEntity(mIndicatorSceneNode->getName(), sphereMesh->getName()); //david-<< //mIndicatorEntity->setNormaliseNormals(true); //david->> mIndicatorEntity->setMaterialName(material->getName()); setUserObject(mProxy); mIndicatorSceneNode->attachObject(mIndicatorEntity); // 选择时不考虑粒子系统的包围盒,用的是指示器的包围盒 ParticleSystemObject *particleSystemObject = static_cast<ParticleSystemObject *> (object.get()); Ogre::ParticleSystem *system = particleSystemObject->getParticleSystem(); if (system) system->setQueryFlags(0); // 根据光源类型来挂接模型 showIndicator(false); }
ObjectPtr copyObject(ObjectPtr other) { Object& obj = *other.get(); return std::make_shared<Object>(obj); }
ObjectPtr<> aspect_cast(ObjectPtr<From> ptr, const DerivedType* type) { return ObjectPtr<>(aspect_cast(ptr.get(), type)); }
typename std::enable_if<HasReflection<From>::Value && !HasReflection<To>::Value, To*>::type aspect_cast(ObjectPtr<From> ptr) { return aspect_cast<To>(ptr.get()); }
static void validate( Parameter &that, ObjectPtr value ) { that.validate( value.get() ); }
int main(int argc, char** argv) { typedef std::unique_ptr<Object> ObjectPtr; std::vector<ObjectPtr> objects; World theWorld; std::shared_ptr<RenderSystem> render; render.reset(new RenderSystem()); theWorld.AddSystem(render); std::shared_ptr<System> input; input.reset(new InputSystem()); theWorld.AddSystem(std::static_pointer_cast<System>(input)); render->LoadDataFile("data/data.txt"); //create an object { ObjectPtr myObject; myObject.reset(new Object(&theWorld)); std::unique_ptr<Component> component; component.reset(new LivingComponent(myObject.get())); myObject->AddComponent(component); std::unique_ptr<Component> component2; component2.reset(new HealingEffect(myObject.get())); Event buffness("set_property"); buffness.SetValueString("property", "duration"); buffness.SetValueString("value", "5"); component2->HandleEvent(buffness); buffness.SetValueString("property", "quantity"); buffness.SetValueString("value", "20"); component2->HandleEvent(buffness); myObject->AddComponent(component2); std::unique_ptr<Component> component3; component3.reset(new RenderComponent(myObject.get())); myObject->AddComponent(component3); objects.emplace_back(std::move(myObject)); } //create an object 2 { ObjectPtr myObject; myObject.reset(new Object(&theWorld)); std::unique_ptr<Component> component; component.reset(new LivingComponent(myObject.get())); myObject->AddComponent(component); std::unique_ptr<Component> component2; component2.reset(new DamageReductionEffect(myObject.get())); Event buffness("set_property"); buffness.SetValueString("property", "max_health"); buffness.SetValueString("value", "150"); component2->HandleEvent(buffness); buffness.SetValueString("property", "health"); buffness.SetValueString("value", "150"); component2->HandleEvent(buffness); myObject->AddComponent(component2); objects.emplace_back(std::move(myObject)); } Event debug("debug"); for(auto &obj : objects) { obj->HandleEvent(debug); } Event startFrame("event_start_frame"); for(uint32_t ii=0; ii<2000; ++ii) { printf("==========[ %5d ]==========\n", ii); for(auto& object : objects) { Event damage("take_damage"); damage.SetValueInteger("damage", 20); object->HandleEvent(startFrame); object->HandleEvent(damage); //object->HandleEvent(debug); } theWorld.Update(ii, 1.0/60.0); } return 0; }