Changeset 6412 for code/branches/pickup2/src/libraries
- Timestamp:
- Dec 25, 2009, 1:18:03 PM (15 years ago)
- Location:
- code/branches/pickup2
- Files:
-
- 6 deleted
- 178 edited
- 6 copied
Legend:
- Unmodified
- Added
- Removed
-
code/branches/pickup2
- Property svn:mergeinfo changed
-
code/branches/pickup2/src/libraries/core/ArgumentCompletionFunctions.cc
r5929 r6412 72 72 else 73 73 { 74 std::stringdir = startdirectory.string();74 const std::string& dir = startdirectory.string(); 75 75 if (dir.size() > 0 && dir[dir.size() - 1] == ':') 76 76 startdirectory = dir + '/'; … … 84 84 { 85 85 if (boost::filesystem::is_directory(*file)) 86 dirlist.push_back(ArgumentCompletionListElement( (*file).string() + '/', getLowercase((*file).string()) + '/', (*file).BOOST_LEAF_FUNCTION() + '/'));86 dirlist.push_back(ArgumentCompletionListElement(file->string() + '/', getLowercase(file->string()) + '/', file->BOOST_LEAF_FUNCTION() + '/')); 87 87 else 88 filelist.push_back(ArgumentCompletionListElement( (*file).string(), getLowercase((*file).string()), (*file).BOOST_LEAF_FUNCTION()));88 filelist.push_back(ArgumentCompletionListElement(file->string(), getLowercase(file->string()), file->BOOST_LEAF_FUNCTION())); 89 89 ++file; 90 90 } … … 101 101 102 102 for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin(); it != Identifier::getStringIdentifierMapEnd(); ++it) 103 if ( (*it).second->hasConfigValues())104 classlist.push_back(ArgumentCompletionListElement( (*it).second->getName(), getLowercase((*it).first)));103 if (it->second->hasConfigValues()) 104 classlist.push_back(ArgumentCompletionListElement(it->first, getLowercase(it->first))); 105 105 106 106 return classlist; … … 110 110 { 111 111 ArgumentCompletionList configvalues; 112 std::map<std::string, Identifier*>::const_iterator identifier = Identifier::get StringIdentifierMap().find(classname);112 std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname)); 113 113 114 if (identifier != Identifier::get StringIdentifierMapEnd() && (*identifier).second->hasConfigValues())114 if (identifier != Identifier::getLowercaseStringIdentifierMapEnd() && identifier->second->hasConfigValues()) 115 115 { 116 for (std::map<std::string, ConfigValueContainer*>::const_iterator it = (*identifier).second->getConfigValueMapBegin(); it != (*identifier).second->getConfigValueMapEnd(); ++it)117 configvalues.push_back(ArgumentCompletionListElement( (*it).second->getName(), getLowercase((*it).first)));116 for (std::map<std::string, ConfigValueContainer*>::const_iterator it = identifier->second->getConfigValueMapBegin(); it != identifier->second->getConfigValueMapEnd(); ++it) 117 configvalues.push_back(ArgumentCompletionListElement(it->first, getLowercase(it->first))); 118 118 } 119 119 … … 127 127 if (identifier != Identifier::getLowercaseStringIdentifierMapEnd()) 128 128 { 129 std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));130 if (variable != (*identifier).second->getLowercaseConfigValueMapEnd())129 std::map<std::string, ConfigValueContainer*>::const_iterator variable = identifier->second->getLowercaseConfigValueMap().find(getLowercase(varname)); 130 if (variable != identifier->second->getLowercaseConfigValueMapEnd()) 131 131 { 132 std::string valuestring = (*variable).second->toString();132 const std::string& valuestring = variable->second->toString(); 133 133 oldvalue.push_back(ArgumentCompletionListElement(valuestring, getLowercase(valuestring), "Old value: " + valuestring)); 134 134 } -
code/branches/pickup2/src/libraries/core/BaseObject.cc
r5929 r6412 36 36 #include <tinyxml/tinyxml.h> 37 37 38 #include "util/StringUtils.h"39 38 #include "CoreIncludes.h" 40 39 #include "Event.h" … … 119 118 XMLPortObjectTemplate(BaseObject, Template, "templates", addTemplate, getTemplate, xmlelement, mode, Template*); 120 119 XMLPortObject(BaseObject, BaseObject, "eventlisteners", addEventListener, getEventListener, xmlelement, mode); 121 120 122 121 Element* events = 0; 123 122 if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject) … … 139 138 XMLPortEventState(BaseObject, BaseObject, "visibility", setVisible, xmlelement, mode); 140 139 XMLPortEventState(BaseObject, BaseObject, "mainstate", setMainState, xmlelement, mode); 141 140 142 141 this->bRegisteredEventStates_ = true; 143 142 } … … 236 235 if (it->second != state) 237 236 continue; 238 237 239 238 if (i == index) 240 239 return it->first; … … 252 251 listener->addEventSource(this, "mainstate"); 253 252 } 254 253 255 254 /** 256 255 @brief Returns an event listener with a given index. … … 278 277 if (it != this->eventStates_.end()) 279 278 { 280 COUT(2) << "Warning: Overwriting EventState in class " << this->getIdentifier()->getName() << "."<< std::endl;279 COUT(2) << "Warning: Overwriting EventState in class " << this->getIdentifier()->getName() << '.' << std::endl; 281 280 delete (it->second); 282 281 } … … 292 291 std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name); 293 292 if (it != this->eventStates_.end()) 294 return ( (*it).second);293 return (it->second); 295 294 else 296 295 return 0; … … 344 343 { 345 344 this->registerEventStates(); 346 345 347 346 std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(event.statename_); 348 347 if (it != this->eventStates_.end()) 349 348 it->second->process(event, this); 350 else if ( event.statename_ != "")349 else if (!event.statename_.empty()) 351 350 COUT(2) << "Warning: \"" << event.statename_ << "\" is not a valid state in object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl; 352 351 else … … 356 355 /** 357 356 @brief Sets the main state of the object to a given boolean value. 358 357 359 358 Note: The main state of an object can be set with the @ref setMainStateName function. 360 359 It's part of the eventsystem and used for event forwarding (when the target object can't specify a specific state, … … 386 385 this->mainStateFunctor_ = 0; 387 386 388 if ( this->mainStateName_ != "")387 if (!this->mainStateName_.empty()) 389 388 { 390 389 this->registerEventStates(); 391 390 392 391 std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(this->mainStateName_); 393 392 if (it != this->eventStates_.end() && it->second->getFunctor()) … … 402 401 } 403 402 } 404 403 405 404 /** 406 405 @brief Calls XMLEventPort with an empty XML-element to register the event states if necessary. … … 414 413 } 415 414 } 416 415 417 416 /** 418 417 @brief Manually loads all event states, even if the class doesn't officially support them. This is needed by some classes like @ref EventDispatcher or @ref EventTarget. … … 437 436 for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it) 438 437 { 439 std::stringstatename = (*it);438 const std::string& statename = (*it); 440 439 441 440 // if the event state is already known, continue with the next state … … 447 446 if (!container) 448 447 { 449 ExecutorMember<BaseObject>* setfunctor = createExecutor(createFunctor(&BaseObject::addEventSource), std::string( "BaseObject" ) + "::" + "addEventSource" + "(" + statename + ")");450 ExecutorMember<BaseObject>* getfunctor = createExecutor(createFunctor(&BaseObject::getEventSource), std::string( "BaseObject" ) + "::" + "getEventSource" + "(" + statename + ")");448 ExecutorMember<BaseObject>* setfunctor = createExecutor(createFunctor(&BaseObject::addEventSource), std::string( "BaseObject" ) + "::" + "addEventSource" + '(' + statename + ')'); 449 ExecutorMember<BaseObject>* getfunctor = createExecutor(createFunctor(&BaseObject::getEventSource), std::string( "BaseObject" ) + "::" + "getEventSource" + '(' + statename + ')'); 451 450 setfunctor->setDefaultValue(1, statename); 452 451 getfunctor->setDefaultValue(1, statename); -
code/branches/pickup2/src/libraries/core/BaseObject.h
r5929 r6412 157 157 void removeEventSource(BaseObject* source); 158 158 BaseObject* getEventSource(unsigned int index, const std::string& state) const; 159 159 160 160 void addEventListener(BaseObject* listener); 161 161 BaseObject* getEventListener(unsigned int index) const; … … 172 172 /** @brief Returns the indentation of the debug output in the Loader. @return The indentation */ 173 173 inline const std::string& getLoaderIndentation() const { return this->loaderIndentation_; } 174 174 175 175 static void loadAllEventStates(Element& xmlelement, XMLPort::Mode mode, BaseObject* object, Identifier* identifier); 176 176 … … 210 210 Gametype* oldGametype_; 211 211 std::set<Template*> templates_; 212 212 213 213 std::map<BaseObject*, std::string> eventSources_; //!< List of objects which send events to this object, mapped to the state which they affect 214 214 std::set<BaseObject*> eventListeners_; //!< List of objects which listen to the events of this object -
code/branches/pickup2/src/libraries/core/CMakeLists.txt
r5929 r6412 29 29 GraphicsManager.cc 30 30 GUIManager.cc 31 IOConsole.cc 31 32 Language.cc 32 33 LuaState.cc … … 40 41 CommandEvaluation.cc 41 42 CommandExecutor.cc 42 CommandLine .cc43 CommandLineParser.cc 43 44 ConsoleCommand.cc 44 45 ConsoleCommandCompilation.cc … … 85 86 TOLUA_FILES 86 87 CommandExecutor.h 88 ConfigFileManager.h 89 Game.h 90 GameMode.h 91 GUIManager.h 87 92 Loader.h 88 93 LuaState.h 94 PathConfig.h 95 input/InputManager.h 96 input/KeyBinder.h 97 input/KeyBinderManager.h 89 98 DEFINE_SYMBOL 90 99 "CORE_SHARED_BUILD" -
code/branches/pickup2/src/libraries/core/ClassTreeMask.cc
r5929 r6412 291 291 void ClassTreeMask::add(const Identifier* subclass, bool bInclude, bool overwrite, bool clean) 292 292 { 293 if (!subclass) 294 return; 293 295 // Check if the given subclass is a child of our root-class 294 296 if (subclass->isA(this->root_->getClass())) … … 320 322 void ClassTreeMask::add(ClassTreeMaskNode* node, const Identifier* subclass, bool bInclude, bool overwrite) 321 323 { 324 if (!subclass) 325 return; 322 326 // Check if the current node contains exactly the subclass we want to add 323 327 if (subclass == node->getClass()) … … 395 399 void ClassTreeMask::addSingle(const Identifier* subclass, bool bInclude, bool clean) 396 400 { 401 if (!subclass) 402 return; 397 403 for (std::set<const Identifier*>::const_iterator it = subclass->getDirectChildrenBegin(); it != subclass->getDirectChildrenEnd(); ++it) 398 404 this->add(*it, this->isIncluded(*it), false, false); … … 428 434 bool ClassTreeMask::isIncluded(ClassTreeMaskNode* node, const Identifier* subclass) const 429 435 { 436 if (!subclass) 437 return false; 430 438 // Check if the searched subclass is of the same type as the class in the current node or a derivative 431 439 if (subclass->isA(node->getClass())) … … 816 824 // Calculate the prefix: + means included, - means excluded 817 825 if (it->isIncluded()) 818 out << "+";826 out << '+'; 819 827 else 820 out << "-";828 out << '-'; 821 829 822 830 // Put the name of the corresponding class on the stream 823 out << it->getClass()->getName() << " ";831 out << it->getClass()->getName() << ' '; 824 832 } 825 833 … … 850 858 // If there is a first subclass, move the object-iterator to the first object of this class. Else go to the end 851 859 if (this->subclassIterator_ != this->subclasses_.end()) 852 this->objectIterator_ = (*this->subclassIterator_).first->getObjects()->begin();860 this->objectIterator_ = this->subclassIterator_->first->getObjects()->begin(); 853 861 else 854 862 this->objectIterator_ = ObjectList<BaseObject>::end(); 855 863 856 864 // Check if the iterator points on a valid object. If not, go to the next object by calling ++ 857 if (!this->objectIterator_ || ( (*this->subclassIterator_).second && !this->objectIterator_->isExactlyA((*this->subclassIterator_).first)))865 if (!this->objectIterator_ || (this->subclassIterator_->second && !this->objectIterator_->isExactlyA(this->subclassIterator_->first))) 858 866 this->operator++(); 859 867 … … 882 890 // Check if there really is a next class. If yes, move the object-iterator to the first object 883 891 if (this->subclassIterator_ != this->subclasses_.end()) 884 this->objectIterator_ = (*this->subclassIterator_).first->getObjects()->begin();892 this->objectIterator_ = this->subclassIterator_->first->getObjects()->begin(); 885 893 else 886 894 return (*this); … … 888 896 889 897 // Repeat this until we reach a valid object or the end 890 } while ( (*this->subclassIterator_).second && !this->objectIterator_->isExactlyA((*this->subclassIterator_).first));898 } while (this->subclassIterator_->second && !this->objectIterator_->isExactlyA(this->subclassIterator_->first)); 891 899 } 892 900 return (*this); -
code/branches/pickup2/src/libraries/core/CommandEvaluation.cc
r5781 r6412 50 50 this->commandTokens_.split(command, " ", SubString::WhiteSpaces, false, '\\', false, '"', false, '(', ')', false, '\0'); 51 51 52 this->additionalParameter_ = "";52 this->additionalParameter_.clear(); 53 53 54 54 this->bEvaluatedParams_ = false; … … 60 60 this->functionclass_ = 0; 61 61 this->function_ = 0; 62 this->possibleArgument_ = "";63 this->argument_ = "";64 65 this->errorMessage_ = "";62 this->possibleArgument_.clear(); 63 this->argument_.clear(); 64 65 this->errorMessage_.clear(); 66 66 this->state_ = CommandState::Empty; 67 67 } … … 79 79 if (this->bEvaluatedParams_ && this->function_) 80 80 { 81 COUT(6) << "CE_execute (evaluation): " << this->function_->getName() << " " << this->param_[0] << " " << this->param_[1] << " " << this->param_[2] << " " << this->param_[3] << " "<< this->param_[4] << std::endl;81 COUT(6) << "CE_execute (evaluation): " << this->function_->getName() << ' ' << this->param_[0] << ' ' << this->param_[1] << ' ' << this->param_[2] << ' ' << this->param_[3] << ' ' << this->param_[4] << std::endl; 82 82 (*this->function_)(this->param_[0], this->param_[1], this->param_[2], this->param_[3], this->param_[4]); 83 83 return true; … … 98 98 } 99 99 100 std::stringCommandEvaluation::complete()100 const std::string& CommandEvaluation::complete() 101 101 { 102 102 if (!this->bNewCommand_) … … 114 114 return (this->command_ = this->function_->getName()); 115 115 else 116 return (this->command_ = this->function_->getName() + " ");116 return (this->command_ = this->function_->getName() + ' '); 117 117 } 118 118 else if (this->functionclass_) 119 return (this->command_ = this->functionclass_->getName() + " ");119 return (this->command_ = this->functionclass_->getName() + ' '); 120 120 break; 121 121 case CommandState::Function: … … 123 123 { 124 124 if (this->function_->getParamCount() == 0) 125 return (this->command_ = this->functionclass_->getName() + " "+ this->function_->getName());125 return (this->command_ = this->functionclass_->getName() + ' ' + this->function_->getName()); 126 126 else 127 return (this->command_ = this->functionclass_->getName() + " " + this->function_->getName() + " ");127 return (this->command_ = this->functionclass_->getName() + ' ' + this->function_->getName() + ' '); 128 128 } 129 129 break; … … 131 131 case CommandState::Params: 132 132 { 133 if (this->argument_ == "" && this->possibleArgument_ == "")133 if (this->argument_.empty() && this->possibleArgument_.empty()) 134 134 break; 135 135 … … 137 137 if (this->command_[this->command_.size() - 1] != ' ') 138 138 maxIndex -= 1; 139 std::string whitespace = "";140 141 if ( this->possibleArgument_ != "")139 std::string whitespace; 140 141 if (!this->possibleArgument_.empty()) 142 142 { 143 143 this->argument_ = this->possibleArgument_; … … 146 146 } 147 147 148 return (this->command_ = this->commandTokens_.subSet(0, maxIndex).join() + " "+ this->argument_ + whitespace);148 return (this->command_ = this->commandTokens_.subSet(0, maxIndex).join() + ' ' + this->argument_ + whitespace); 149 149 break; 150 150 } … … 262 262 std::string CommandEvaluation::dump(const std::list<std::pair<const std::string*, const std::string*> >& list) 263 263 { 264 std::string output = "";264 std::string output; 265 265 for (std::list<std::pair<const std::string*, const std::string*> >::const_iterator it = list.begin(); it != list.end(); ++it) 266 266 { 267 267 if (it != list.begin()) 268 output += " ";269 270 output += *( *it).second;268 output += ' '; 269 270 output += *(it->second); 271 271 } 272 272 return output; … … 275 275 std::string CommandEvaluation::dump(const ArgumentCompletionList& list) 276 276 { 277 std::string output = "";277 std::string output; 278 278 for (ArgumentCompletionList::const_iterator it = list.begin(); it != list.end(); ++it) 279 279 { 280 280 if (it != list.begin()) 281 output += " ";282 283 output += (*it).getDisplay();281 output += ' '; 282 283 output += it->getDisplay(); 284 284 } 285 285 return output; … … 295 295 { 296 296 if (i != 0) 297 output += " ";297 output += ' '; 298 298 299 299 if (command->defaultValueSet(i)) 300 output += "[";300 output += '['; 301 301 else 302 output += "{";302 output += '{'; 303 303 304 304 output += command->getTypenameParam(i); 305 305 306 306 if (command->defaultValueSet(i)) 307 output += "=" + command->getDefaultValue(i).getString() + "]";307 output += '=' + command->getDefaultValue(i).getString() + ']'; 308 308 else 309 output += "}";309 output += '}'; 310 310 } 311 311 return output; -
code/branches/pickup2/src/libraries/core/CommandEvaluation.h
r5781 r6412 66 66 67 67 bool execute() const; 68 std::stringcomplete();68 const std::string& complete(); 69 69 std::string hint() const; 70 70 void evaluateParams(); … … 82 82 { this->additionalParameter_ = param; this->bEvaluatedParams_ = false; } 83 83 inline std::string getAdditionalParameter() const 84 { return ( this->additionalParameter_ != "") ? (" "+ this->additionalParameter_) : ""; }84 { return (!this->additionalParameter_.empty()) ? (' ' + this->additionalParameter_) : ""; } 85 85 86 86 void setEvaluatedParameter(unsigned int index, MultiType param); -
code/branches/pickup2/src/libraries/core/CommandExecutor.cc
r5929 r6412 59 59 if (it != CommandExecutor::getInstance().consoleCommandShortcuts_.end()) 60 60 { 61 COUT(2) << "Warning: Overwriting console-command shortcut with name " << command->getName() << "."<< std::endl;61 COUT(2) << "Warning: Overwriting console-command shortcut with name " << command->getName() << '.' << std::endl; 62 62 } 63 63 … … 82 82 std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getInstance().consoleCommandShortcuts_.find(name); 83 83 if (it != CommandExecutor::getInstance().consoleCommandShortcuts_.end()) 84 return (*it).second;84 return it->second; 85 85 else 86 86 return 0; … … 96 96 std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getInstance().consoleCommandShortcuts_LC_.find(name); 97 97 if (it != CommandExecutor::getInstance().consoleCommandShortcuts_LC_.end()) 98 return (*it).second;98 return it->second; 99 99 else 100 100 return 0; … … 215 215 CommandExecutor::getEvaluation().state_ = CommandState::Error; 216 216 AddLanguageEntry("commandexecutorunknownfirstargument", "is not a shortcut nor a classname"); 217 CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getArgument(0) + " " + GetLocalisation("commandexecutorunknownfirstargument") + ".";217 CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getArgument(0) + ' ' + GetLocalisation("commandexecutorunknownfirstargument") + '.'; 218 218 return; 219 219 } … … 231 231 { 232 232 // It's a shortcut 233 std::string functionname = *(*CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin()).first;233 const std::string& functionname = *CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin()->first; 234 234 CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(functionname); 235 235 if (getLowercase(functionname) != getLowercase(CommandExecutor::getArgument(0))) … … 243 243 if (CommandExecutor::getEvaluation().function_->getParamCount() > 0) 244 244 { 245 CommandExecutor::getEvaluation().command_ += " ";245 CommandExecutor::getEvaluation().command_ += ' '; 246 246 CommandExecutor::getEvaluation().bCommandChanged_ = true; 247 247 } … … 251 251 { 252 252 // It's a classname 253 std::string classname = *(*CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.begin()).first;253 const std::string& classname = *CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.begin()->first; 254 254 CommandExecutor::getEvaluation().functionclass_ = CommandExecutor::getPossibleIdentifier(classname); 255 255 if (getLowercase(classname) != getLowercase(CommandExecutor::getArgument(0))) … … 260 260 CommandExecutor::getEvaluation().state_ = CommandState::Function; 261 261 CommandExecutor::getEvaluation().function_ = 0; 262 CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + " ";262 CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + ' '; 263 263 // Move on to next case 264 264 } … … 268 268 CommandExecutor::getEvaluation().state_ = CommandState::Error; 269 269 AddLanguageEntry("commandexecutorunknownfirstargumentstart", "There is no command or classname starting with"); 270 CommandExecutor::getEvaluation().errorMessage_ = "Error: " + GetLocalisation("commandexecutorunknownfirstargumentstart") + " " + CommandExecutor::getArgument(0) + ".";270 CommandExecutor::getEvaluation().errorMessage_ = "Error: " + GetLocalisation("commandexecutorunknownfirstargumentstart") + ' ' + CommandExecutor::getArgument(0) + '.'; 271 271 return; 272 272 } … … 319 319 { 320 320 // It's a function 321 std::string functionname = *(*CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin()).first;321 const std::string& functionname = *CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin()->first; 322 322 CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(functionname, CommandExecutor::getEvaluation().functionclass_); 323 323 if (getLowercase(functionname) != getLowercase(CommandExecutor::getArgument(1))) … … 327 327 } 328 328 CommandExecutor::getEvaluation().state_ = CommandState::ParamPreparation; 329 CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + " "+ CommandExecutor::getEvaluation().function_->getName();329 CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + ' ' + CommandExecutor::getEvaluation().function_->getName(); 330 330 if (CommandExecutor::getEvaluation().function_->getParamCount() > 0) 331 331 { 332 CommandExecutor::getEvaluation().command_ += " ";332 CommandExecutor::getEvaluation().command_ += ' '; 333 333 CommandExecutor::getEvaluation().bCommandChanged_ = true; 334 334 } … … 340 340 CommandExecutor::getEvaluation().state_ = CommandState::Error; 341 341 AddLanguageEntry("commandexecutorunknownsecondargumentstart", "has no function starting with"); 342 CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getEvaluation().functionclass_->getName() + " " + GetLocalisation("commandexecutorunknownsecondargumentstart") + " " + CommandExecutor::getArgument(1) + ".";342 CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getEvaluation().functionclass_->getName() + ' ' + GetLocalisation("commandexecutorunknownsecondargumentstart") + ' ' + CommandExecutor::getArgument(1) + '.'; 343 343 return; 344 344 } … … 346 346 { 347 347 // There are several possibilities 348 CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + " "+ CommandExecutor::getCommonBegin(CommandExecutor::getEvaluation().listOfPossibleFunctions_);348 CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + ' ' + CommandExecutor::getCommonBegin(CommandExecutor::getEvaluation().listOfPossibleFunctions_); 349 349 CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(CommandExecutor::getArgument(1), CommandExecutor::getEvaluation().functionclass_); 350 350 CommandExecutor::getEvaluation().bCommandChanged_ = true; … … 386 386 { 387 387 // There is exactly one possible argument 388 CommandExecutor::getEvaluation().argument_ = (*CommandExecutor::getEvaluation().listOfPossibleArguments_.begin()).getString();389 CommandExecutor::getEvaluation().possibleArgument_ = (*CommandExecutor::getEvaluation().listOfPossibleArguments_.begin()).getString();388 CommandExecutor::getEvaluation().argument_ = CommandExecutor::getEvaluation().listOfPossibleArguments_.begin()->getString(); 389 CommandExecutor::getEvaluation().possibleArgument_ = CommandExecutor::getEvaluation().listOfPossibleArguments_.begin()->getString(); 390 390 CommandExecutor::getEvaluation().state_ = CommandState::ParamPreparation; 391 391 return; … … 451 451 } 452 452 453 std::stringCommandExecutor::getArgument(unsigned int index)453 const std::string& CommandExecutor::getArgument(unsigned int index) 454 454 { 455 455 if (index < (CommandExecutor::getEvaluation().commandTokens_.size())) 456 456 return CommandExecutor::getEvaluation().commandTokens_[index]; 457 457 else 458 return "";459 } 460 461 std::stringCommandExecutor::getLastArgument()458 return BLANKSTRING; 459 } 460 461 const std::string& CommandExecutor::getLastArgument() 462 462 { 463 463 return CommandExecutor::getArgument(CommandExecutor::argumentsGiven() - 1); … … 467 467 { 468 468 CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.clear(); 469 std::stringlowercase = getLowercase(fragment);469 const std::string& lowercase = getLowercase(fragment); 470 470 for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMapBegin(); it != Identifier::getLowercaseStringIdentifierMapEnd(); ++it) 471 if ( (*it).second->hasConsoleCommands())472 if ( (*it).first.find(lowercase) == 0 || fragment == "")473 CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.push_back(std::pair<const std::string*, const std::string*>(& (*it).first, &(*it).second->getName()));471 if (it->second->hasConsoleCommands()) 472 if (it->first.find(lowercase) == 0 || fragment.empty()) 473 CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.push_back(std::pair<const std::string*, const std::string*>(&it->first, &it->second->getName())); 474 474 } 475 475 … … 477 477 { 478 478 CommandExecutor::getEvaluation().listOfPossibleFunctions_.clear(); 479 std::stringlowercase = getLowercase(fragment);479 const std::string& lowercase = getLowercase(fragment); 480 480 if (!identifier) 481 481 { 482 482 for (std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getLowercaseConsoleCommandShortcutMapBegin(); it != CommandExecutor::getLowercaseConsoleCommandShortcutMapEnd(); ++it) 483 if ( (*it).first.find(lowercase) == 0 || fragment == "")484 CommandExecutor::getEvaluation().listOfPossibleFunctions_.push_back(std::pair<const std::string*, const std::string*>(& (*it).first, &(*it).second->getName()));483 if (it->first.find(lowercase) == 0 || fragment.empty()) 484 CommandExecutor::getEvaluation().listOfPossibleFunctions_.push_back(std::pair<const std::string*, const std::string*>(&it->first, &it->second->getName())); 485 485 } 486 486 else 487 487 { 488 488 for (std::map<std::string, ConsoleCommand*>::const_iterator it = identifier->getLowercaseConsoleCommandMapBegin(); it != identifier->getLowercaseConsoleCommandMapEnd(); ++it) 489 if ( (*it).first.find(lowercase) == 0 || fragment == "")490 CommandExecutor::getEvaluation().listOfPossibleFunctions_.push_back(std::pair<const std::string*, const std::string*>(& (*it).first, &(*it).second->getName()));489 if (it->first.find(lowercase) == 0 || fragment.empty()) 490 CommandExecutor::getEvaluation().listOfPossibleFunctions_.push_back(std::pair<const std::string*, const std::string*>(&it->first, &it->second->getName())); 491 491 } 492 492 } … … 497 497 498 498 CommandExecutor::getEvaluation().listOfPossibleArguments_.clear(); 499 std::stringlowercase = getLowercase(fragment);499 const std::string& lowercase = getLowercase(fragment); 500 500 for (ArgumentCompletionList::const_iterator it = command->getArgumentCompletionListBegin(); it != command->getArgumentCompletionListEnd(); ++it) 501 501 { 502 if ( (*it).lowercaseComparison())503 { 504 if ( (*it).getComparable().find(lowercase) == 0 || fragment == "")502 if (it->lowercaseComparison()) 503 { 504 if (it->getComparable().find(lowercase) == 0 || fragment.empty()) 505 505 CommandExecutor::getEvaluation().listOfPossibleArguments_.push_back(*it); 506 506 } 507 507 else 508 508 { 509 if ( (*it).getComparable().find(fragment) == 0 || fragment == "")509 if (it->getComparable().find(fragment) == 0 || fragment.empty()) 510 510 CommandExecutor::getEvaluation().listOfPossibleArguments_.push_back(*it); 511 511 } … … 515 515 Identifier* CommandExecutor::getPossibleIdentifier(const std::string& name) 516 516 { 517 std::stringlowercase = getLowercase(name);517 const std::string& lowercase = getLowercase(name); 518 518 std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMap().find(lowercase); 519 if ((it != Identifier::getLowercaseStringIdentifierMapEnd()) && (*it).second->hasConsoleCommands())520 return (*it).second;519 if ((it != Identifier::getLowercaseStringIdentifierMapEnd()) && it->second->hasConsoleCommands()) 520 return it->second; 521 521 522 522 return 0; … … 525 525 ConsoleCommand* CommandExecutor::getPossibleCommand(const std::string& name, Identifier* identifier) 526 526 { 527 std::stringlowercase = getLowercase(name);527 const std::string& lowercase = getLowercase(name); 528 528 if (!identifier) 529 529 { 530 530 std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getLowercaseConsoleCommandShortcutMap().find(lowercase); 531 531 if (it != CommandExecutor::getLowercaseConsoleCommandShortcutMapEnd()) 532 return (*it).second;532 return it->second; 533 533 } 534 534 else … … 536 536 std::map<std::string, ConsoleCommand*>::const_iterator it = identifier->getLowercaseConsoleCommandMap().find(lowercase); 537 537 if (it != identifier->getLowercaseConsoleCommandMapEnd()) 538 return (*it).second;538 return it->second; 539 539 } 540 540 return 0; 541 541 } 542 542 543 std::stringCommandExecutor::getPossibleArgument(const std::string& name, ConsoleCommand* command, unsigned int param)543 const std::string& CommandExecutor::getPossibleArgument(const std::string& name, ConsoleCommand* command, unsigned int param) 544 544 { 545 545 CommandExecutor::createArgumentCompletionList(command, param); 546 546 547 std::stringlowercase = getLowercase(name);547 const std::string& lowercase = getLowercase(name); 548 548 for (ArgumentCompletionList::const_iterator it = command->getArgumentCompletionListBegin(); it != command->getArgumentCompletionListEnd(); ++it) 549 549 { 550 if ( (*it).lowercaseComparison())551 { 552 if ( (*it).getComparable() == lowercase)553 return (*it).getString();550 if (it->lowercaseComparison()) 551 { 552 if (it->getComparable() == lowercase) 553 return it->getString(); 554 554 } 555 555 else 556 556 { 557 if ( (*it).getComparable() == name)558 return (*it).getString();559 } 560 } 561 562 return "";557 if (it->getComparable() == name) 558 return it->getString(); 559 } 560 } 561 562 return BLANKSTRING; 563 563 } 564 564 … … 589 589 else if (list.size() == 1) 590 590 { 591 return ((* (*list.begin()).first) + " ");592 } 593 else 594 { 595 std::string output = "";591 return ((*list.begin()->first) + ' '); 592 } 593 else 594 { 595 std::string output; 596 596 for (unsigned int i = 0; true; i++) 597 597 { … … 599 599 for (std::list<std::pair<const std::string*, const std::string*> >::const_iterator it = list.begin(); it != list.end(); ++it) 600 600 { 601 if ( (*(*it).first).size() > i)601 if (it->first->size() > i) 602 602 { 603 603 if (it == list.begin()) 604 604 { 605 temp = (* (*it).first)[i];605 temp = (*it->first)[i]; 606 606 } 607 607 else 608 608 { 609 if (temp != (* (*it).first)[i])609 if (temp != (*it->first)[i]) 610 610 return output; 611 611 } … … 630 630 else if (list.size() == 1) 631 631 { 632 return ( (*list.begin()).getComparable() + " ");633 } 634 else 635 { 636 std::string output = "";632 return (list.begin()->getComparable() + ' '); 633 } 634 else 635 { 636 std::string output; 637 637 for (unsigned int i = 0; true; i++) 638 638 { 639 char tempComparable = 0; 639 640 char temp = 0; 640 641 for (ArgumentCompletionList::const_iterator it = list.begin(); it != list.end(); ++it) 641 642 { 642 std::string argument = (*it).getComparable(); 643 const std::string& argumentComparable = it->getComparable(); 644 const std::string& argument = it->getString(); 643 645 if (argument.size() > i) 644 646 { 645 647 if (it == list.begin()) 646 648 { 649 tempComparable = argumentComparable[i]; 647 650 temp = argument[i]; 648 651 } 649 652 else 650 653 { 651 if (temp != argument[i])654 if (tempComparable != argumentComparable[i]) 652 655 return output; 656 else if (temp != argument[i]) 657 temp = tempComparable; 653 658 } 654 659 } -
code/branches/pickup2/src/libraries/core/CommandExecutor.h
r5781 r6412 90 90 static unsigned int argumentsGiven(); 91 91 static bool enoughArgumentsGiven(ConsoleCommand* command); 92 static std::stringgetArgument(unsigned int index);93 static std::stringgetLastArgument();92 static const std::string& getArgument(unsigned int index); 93 static const std::string& getLastArgument(); 94 94 95 95 static void createListOfPossibleIdentifiers(const std::string& fragment); … … 99 99 static Identifier* getPossibleIdentifier(const std::string& name); 100 100 static ConsoleCommand* getPossibleCommand(const std::string& name, Identifier* identifier = 0); 101 static std::stringgetPossibleArgument(const std::string& name, ConsoleCommand* command, unsigned int param);101 static const std::string& getPossibleArgument(const std::string& name, ConsoleCommand* command, unsigned int param); 102 102 103 103 static void createArgumentCompletionList(ConsoleCommand* command, unsigned int param); -
code/branches/pickup2/src/libraries/core/CommandLineParser.cc
r6105 r6412 63 63 this->value_ = temp; 64 64 } 65 else if (value == "")65 else if (value.empty()) 66 66 { 67 67 this->bHasDefaultValue_ = false; … … 140 140 OrxAssert(cmdLineArgsShortcut_.find(it->second->getShortcut()) == cmdLineArgsShortcut_.end(), 141 141 "Cannot have two command line shortcut with the same name."); 142 if ( it->second->getShortcut() != "")142 if (!it->second->getShortcut().empty()) 143 143 cmdLineArgsShortcut_[it->second->getShortcut()] = it->second; 144 144 } … … 165 165 { 166 166 // negative number as a value 167 value += arguments[i] + " ";167 value += arguments[i] + ' '; 168 168 } 169 169 else … … 173 173 // save old data first 174 174 value = removeTrailingWhitespaces(value); 175 if ( name != "")175 if (!name.empty()) 176 176 { 177 177 checkFullArgument(name, value, bParsingFile); 178 name = "";179 assert(shortcut == "");178 name.clear(); 179 assert(shortcut.empty()); 180 180 } 181 else if ( shortcut != "")181 else if (!shortcut.empty()) 182 182 { 183 183 checkShortcut(shortcut, value, bParsingFile); 184 shortcut = "";185 assert(name == "");184 shortcut.clear(); 185 assert(name.empty()); 186 186 } 187 187 … … 198 198 199 199 // reset value string 200 value = "";200 value.clear(); 201 201 } 202 202 } … … 205 205 // value string 206 206 207 if (name == "" && shortcut == "")207 if (name.empty() && shortcut.empty()) 208 208 { 209 209 ThrowException(Argument, "Expected \"-\" or \"-\" in command line arguments.\n"); … … 218 218 // parse last argument 219 219 value = removeTrailingWhitespaces(value); 220 if ( name != "")220 if (!name.empty()) 221 221 { 222 222 checkFullArgument(name, value, bParsingFile); 223 assert(shortcut == "");224 } 225 else if ( shortcut != "")223 assert(shortcut.empty()); 224 } 225 else if (!shortcut.empty()) 226 226 { 227 227 checkShortcut(shortcut, value, bParsingFile); 228 assert(name == "");228 assert(name.empty()); 229 229 } 230 230 } … … 291 291 it != inst.cmdLineArgs_.end(); ++it) 292 292 { 293 if ( it->second->getShortcut() != "")293 if (!it->second->getShortcut().empty()) 294 294 infoStr << " [-" << it->second->getShortcut() << "] "; 295 295 else 296 296 infoStr << " "; 297 infoStr << "--" << it->second->getName() << " ";297 infoStr << "--" << it->second->getName() << ' '; 298 298 if (it->second->getValue().getType() != MT_Type::Bool) 299 299 infoStr << "ARG "; … … 347 347 void CommandLineParser::_parseFile() 348 348 { 349 std::stringfilename = CommandLineParser::getValue("optionsFile").getString();349 const std::string& filename = CommandLineParser::getValue("optionsFile").getString(); 350 350 351 351 // look for additional arguments in given file or start.ini as default -
code/branches/pickup2/src/libraries/core/ConfigFileManager.cc
r5929 r6412 51 51 if (identifier != Identifier::getLowercaseStringIdentifierMapEnd()) 52 52 { 53 std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));54 if (variable != (*identifier).second->getLowercaseConfigValueMapEnd())55 return (*variable).second->set(value);53 std::map<std::string, ConfigValueContainer*>::const_iterator variable = identifier->second->getLowercaseConfigValueMap().find(getLowercase(varname)); 54 if (variable != identifier->second->getLowercaseConfigValueMapEnd()) 55 return variable->second->set(value); 56 56 } 57 57 return false; 58 } 59 60 std::string getConfig(const std::string& classname, const std::string& varname) 61 { 62 return ConfigFileManager::getInstance().getValue(ConfigFileType::Settings, classname, varname, "", true); 58 63 } 59 64 … … 63 68 if (identifier != Identifier::getLowercaseStringIdentifierMapEnd()) 64 69 { 65 std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));66 if (variable != (*identifier).second->getLowercaseConfigValueMapEnd())67 return (*variable).second->tset(value);70 std::map<std::string, ConfigValueContainer*>::const_iterator variable = identifier->second->getLowercaseConfigValueMap().find(getLowercase(varname)); 71 if (variable != identifier->second->getLowercaseConfigValueMapEnd()) 72 return variable->second->tset(value); 68 73 } 69 74 return false; … … 94 99 this->value_ = value; 95 100 else 96 this->value_ = "\"" + addSlashes(stripEnclosingQuotes(value)) + "\"";101 this->value_ = '"' + addSlashes(stripEnclosingQuotes(value)) + '"'; 97 102 } 98 103 … … 107 112 std::string ConfigFileEntryValue::getFileEntry() const 108 113 { 109 if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)110 return (this->name_ + "="+ this->value_);111 else 112 return (this->name_ + "="+ this->value_ + " " + this->additionalComment_);114 if (this->additionalComment_.empty()) 115 return (this->name_ + '=' + this->value_); 116 else 117 return (this->name_ + '=' + this->value_ + " " + this->additionalComment_); 113 118 } 114 119 … … 119 124 std::string ConfigFileEntryVectorValue::getFileEntry() const 120 125 { 121 if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)122 return (this->name_ + "[" + multi_cast<std::string>(this->index_) + "]" + "="+ this->value_);123 else 124 return (this->name_ + "[" + multi_cast<std::string>(this->index_) + "]=" + this->value_ + " "+ this->additionalComment_);126 if (this->additionalComment_.empty()) 127 return (this->name_ + '[' + multi_cast<std::string>(this->index_) + ']' + '=' + this->value_); 128 else 129 return (this->name_ + '[' + multi_cast<std::string>(this->index_) + "]=" + this->value_ + ' ' + this->additionalComment_); 125 130 } 126 131 … … 166 171 std::string ConfigFileSection::getFileEntry() const 167 172 { 168 if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)169 return ( "[" + this->name_ + "]");170 else 171 return ( "["+ this->name_ + "] " + this->additionalComment_);173 if (this->additionalComment_.empty()) 174 return ('[' + this->name_ + ']'); 175 else 176 return ('[' + this->name_ + "] " + this->additionalComment_); 172 177 } 173 178 … … 246 251 std::getline(file, line); 247 252 248 std::stringtemp = getStripped(line);253 const std::string& temp = getStripped(line); 249 254 if (!isEmpty(temp) && !isComment(temp)) 250 255 { … … 256 261 { 257 262 // New section 258 std::stringcomment = line.substr(pos2 + 1);263 const std::string& comment = line.substr(pos2 + 1); 259 264 if (isComment(comment)) 260 265 newsection = new ConfigFileSection(line.substr(pos1 + 1, pos2 - pos1 - 1), comment); … … 288 293 commentposition = getNextCommentPosition(line, commentposition + 1); 289 294 } 290 std::string value = "", comment = "";295 std::string value, comment; 291 296 if (commentposition == std::string::npos) 292 297 { … … 377 382 { 378 383 std::map<std::string, Identifier*>::const_iterator it2 = Identifier::getStringIdentifierMap().find((*it1)->getName()); 379 if (it2 != Identifier::getStringIdentifierMapEnd() && (*it2).second->hasConfigValues())384 if (it2 != Identifier::getStringIdentifierMapEnd() && it2->second->hasConfigValues()) 380 385 { 381 386 // The section exists, delete comment … … 384 389 for (std::list<ConfigFileEntry*>::iterator it3 = (*it1)->entries_.begin(); it3 != (*it1)->entries_.end(); ) 385 390 { 386 std::map<std::string, ConfigValueContainer*>::const_iterator it4 = (*it2).second->getConfigValueMap().find((*it3)->getName());387 if (it4 != (*it2).second->getConfigValueMapEnd())391 std::map<std::string, ConfigValueContainer*>::const_iterator it4 = it2->second->getConfigValueMap().find((*it3)->getName()); 392 if (it4 != it2->second->getConfigValueMapEnd()) 388 393 { 389 394 // The config-value exists, delete comment … … 459 464 if (it->second->hasConfigValues()) 460 465 { 461 for (std::map<std::string, ConfigValueContainer*>::const_iterator it2 = (*it).second->getConfigValueMapBegin(); it2 != (*it).second->getConfigValueMapEnd(); ++it2)466 for (std::map<std::string, ConfigValueContainer*>::const_iterator it2 = it->second->getConfigValueMapBegin(); it2 != it->second->getConfigValueMapEnd(); ++it2) 462 467 it2->second->update(); 463 468 -
code/branches/pickup2/src/libraries/core/ConfigFileManager.h
r5738 r6412 40 40 #include "util/Singleton.h" 41 41 42 // tolua_begin 42 43 namespace orxonox 43 44 { 45 // tolua_end 44 46 // Use int as config file type to have an arbitrary number of files 45 47 struct ConfigFileType : OrxEnum<ConfigFileType> … … 50 52 static const int Settings = 1; 51 53 static const int JoyStickCalibration = 2; 54 static const int CommandHistory = 3; 52 55 53 56 static const int numberOfReservedTypes = 1024; 54 57 }; 55 58 56 bool config(const std::string& classname, const std::string& varname, const std::string& value); 57 bool tconfig(const std::string& classname, const std::string& varname, const std::string& value); 58 void reloadConfig(); 59 void saveConfig(); 60 void cleanConfig(); 61 void loadSettings(const std::string& filename); 59 _CoreExport bool config(const std::string& classname, const std::string& varname, const std::string& value); // tolua_export 60 _CoreExport std::string getConfig(const std::string& classname, const std::string& varname); // tolua_export 61 _CoreExport bool tconfig(const std::string& classname, const std::string& varname, const std::string& value); 62 _CoreExport void reloadConfig(); 63 _CoreExport void saveConfig(); 64 _CoreExport void cleanConfig(); 65 _CoreExport void loadSettings(const std::string& filename); 62 66 63 67 … … 85 89 { 86 90 public: 87 inline ConfigFileEntryValue(const std::string& name, const std::string& value = "", bool bString = false, const std::string& additionalComment = "") : name_(name), value_(value), bString_(bString), additionalComment_(additionalComment) {} 91 inline ConfigFileEntryValue(const std::string& name, const std::string& value = "", bool bString = false, const std::string& additionalComment = "") 92 : name_(name) 93 , value_(value) 94 , bString_(bString) 95 , additionalComment_(additionalComment) 96 {} 88 97 inline virtual ~ConfigFileEntryValue() {} 89 98 … … 169 178 170 179 public: 171 inline ConfigFileSection(const std::string& name, const std::string& additionalComment = "") : name_(name), additionalComment_(additionalComment), bUpdated_(false) {} 180 inline ConfigFileSection(const std::string& name, const std::string& additionalComment = "") 181 : name_(name) 182 , additionalComment_(additionalComment) 183 , bUpdated_(false) 184 {} 172 185 ~ConfigFileSection(); 173 186 … … 240 253 { this->getSection(section)->setValue(name, value, bString); this->save(); } 241 254 inline std::string getValue(const std::string& section, const std::string& name, const std::string& fallback, bool bString) 242 { std::stringoutput = this->getSection(section)->getValue(name, fallback, bString); this->saveIfUpdated(); return output; }255 { const std::string& output = this->getSection(section)->getValue(name, fallback, bString); this->saveIfUpdated(); return output; } 243 256 244 257 inline void setValue(const std::string& section, const std::string& name, unsigned int index, const std::string& value, bool bString) 245 258 { this->getSection(section)->setValue(name, index, value, bString); this->save(); } 246 259 inline std::string getValue(const std::string& section, const std::string& name, unsigned int index, const std::string& fallback, bool bString) 247 { std::stringoutput = this->getSection(section)->getValue(name, index, fallback, bString); this->saveIfUpdated(); return output; }260 { const std::string& output = this->getSection(section)->getValue(name, index, fallback, bString); this->saveIfUpdated(); return output; } 248 261 249 262 inline void deleteVectorEntries(const std::string& section, const std::string& name, unsigned int startindex = 0) … … 319 332 static ConfigFileManager* singletonPtr_s; 320 333 }; 321 } 334 } // tolua_export 322 335 323 336 #endif /* _ConfigFileManager_H__ */ -
code/branches/pickup2/src/libraries/core/ConfigValueContainer.h
r5738 r6412 121 121 @param defvalue The default-value 122 122 */ 123 template <class V>124 ConfigValueContainer(ConfigFileType type, Identifier* identifier, const std::string& sectionname, const std::string& varname, const std::vector< V>& defvalue)123 template <class D, class V> 124 ConfigValueContainer(ConfigFileType type, Identifier* identifier, const std::string& sectionname, const std::string& varname, const std::vector<D>& defvalue, const std::vector<V>& value) 125 125 { 126 126 this->init(type, identifier, sectionname, varname); … … 146 146 if ((this->callback_ && object) || this->bContainerIsNew_) 147 147 { 148 if (this->bContainerIsNew_)149 this->bContainerIsNew_ = false;150 151 148 T temp = *value; 152 149 this->value_.getValue(value); 153 if ((*value) != temp) 154 { 150 if (this->bContainerIsNew_ || (*value) != temp) 151 { 152 this->bContainerIsNew_ = false; 155 153 if (this->callback_ && object) 156 154 this->callback_->call(object); -
code/branches/pickup2/src/libraries/core/ConfigValueIncludes.h
r5738 r6412 23 23 * Fabian 'x3n' Landau 24 24 * Co-authors: 25 * ...25 * Reto Grieder (functions) 26 26 * 27 27 */ 28 28 29 29 /** 30 @file 31 @brief Definition of macros for config-values. 30 @file 31 @brief 32 Definition of macros and functions for config-values. 32 33 */ 33 34 … … 41 42 #include "ConfigFileManager.h" 42 43 44 namespace orxonox 45 { 46 /** Sets a runtime configurable value. 47 If the container for the value doesn't yet exist, a new one is created. 48 Also, the @a variable argument will be modified and set to the new value (default or from ini file). 49 @param object 50 Class instance that the config value should belong to (usually just 'this') 51 @param variable 52 Pointer to the variable where the value should be written to 53 @param type 54 Type of the config file, usually ConfigFileType::Settings 55 @param sectionName 56 Name of the section in the ini file (e.g. [MySection]) 57 @param entryName 58 Name of the entry in the ini file (e.g. [MySection] myValue) 59 @param defaultValue 60 Value to be used if it cannot be read from the ini file 61 */ 62 template <class T, class D, class V> 63 inline ConfigValueContainer& setConfigValueGeneric(T* object, V* variable, ConfigFileType type, const std::string& sectionName, const std::string& entryName, const D& defaultValue) 64 { 65 ConfigValueContainer* container = object->getIdentifier()->getConfigValueContainer(entryName); 66 if (!container) 67 { 68 container = new ConfigValueContainer(type, object->getIdentifier(), sectionName, entryName, defaultValue, *variable); 69 object->getIdentifier()->addConfigValueContainer(entryName, container); 70 } 71 return container->getValue(variable, object); 72 } 73 } 43 74 44 /** 45 @brief Assigns the value, defined in the config-file, to the variable (or the default-value, if there is no entry in the file). 46 @param varname The name of the variable 47 @param defvalue The default-value of the variable 75 /** Sets a runtime configurable value (simplified macro version of setConfigValueGeneric) 76 If the container for the value doesn't yet exist, a new one is created. 77 Also, the @a varname argument will be modified and set to the new value (default or from ini file). 78 @param varname 79 Variable name as C++ identifier. It will be used as entry name and as variable pointer 80 @param defaultValue 81 Value to be used if it cannot be read from the ini file 48 82 */ 49 #define SetConfigValueGeneric(type, varname, defvalue) \ 50 static orxonox::Identifier* identifier##varname = this->getIdentifier(); \ 51 orxonox::ConfigValueContainer* container##varname = identifier##varname->getConfigValueContainer(#varname); \ 52 if (!container##varname) \ 53 { \ 54 container##varname = new orxonox::ConfigValueContainer(type, identifier##varname, identifier##varname->getName(), #varname, defvalue, varname); \ 55 identifier##varname->addConfigValueContainer(#varname, container##varname); \ 56 } \ 57 container##varname->getValue(&varname, this) 83 #define SetConfigValue(varname, defaultValue) \ 84 orxonox::setConfigValueGeneric(this, &varname, ConfigFileType::Settings, this->getIdentifier()->getName(), #varname, defaultValue) 58 85 59 #define SetConfigValue(varname, defvalue) SetConfigValueGeneric(ConfigFileType::Settings, varname, defvalue) 86 /** Sets a runtime configurable value (simplified macro version of setConfigValueGeneric) 87 If the container for the value doesn't yet exist, a new one is created. 88 Also, the @a varname argument will be modified and set to the new value (default or from ini file). 89 @param variable 90 Variable name as C++ identifier. 91 @param entryName 92 Name of the entry in the ini file (e.g. [MySection] myValue) 93 @param defaultValue 94 Value to be used if it cannot be read from the ini file 95 */ 96 #define SetConfigValueAlias(variable, entryName, defaultValue) \ 97 orxonox::setConfigValueGeneric(this, &variable, ConfigFileType::Settings, this->getIdentifier()->getName(), entryName, defaultValue) 60 98 61 99 62 /** 63 @brief Assigns the vector-values, defined in the config-file, to the vector (or the default-value, if there are no entries in the file). 64 @param varname The name of the std::vector 65 @param defvalue The default-value 100 namespace orxonox 101 { 102 /** Resets a runtime configurable value to its default. 103 If the container for the value doesn't yet exist, a warning is displayed. 104 Also, the @a variable argument will be modified and set to the default value. 105 @param object 106 Class instance that the config value should belong to (usually just 'this') 107 @param variable 108 Pointer to the variable where the value should be written to 109 @param entryName 110 Name of the entry in the ini file (e.g. [MySection] myValue) 111 */ 112 template <class T, class V> 113 inline void resetConfigValueGeneric(T* object, V* variable, const std::string& entryName) 114 { 115 ConfigValueContainer* container = object->getIdentifier()->getConfigValueContainer(entryName); 116 if (container) 117 { 118 container->reset(); 119 container->getValue(variable, object); 120 } 121 else 122 { 123 COUT(2) << "Warning: Couldn't reset config-value '" << entryName << "' in class '" 124 << object->getIdentifier()->getName() << "', corresponding container doesn't exist." << std::endl; 125 } 126 } 127 } 128 129 /** Resets a runtime configurable value to its default (simplified macro version of modifyConfigValueGeneric) 130 If the container for the value doesn't yet exist, a warning is displayed. 131 Also, the @a varname argument will be modified and set to the default value. 132 @param varname 133 Variable name as C++ identifier. It will be used as entry name and as variable pointer 66 134 */ 67 #define SetConfigValueVectorGeneric(type, varname, defvalue) \ 68 static orxonox::Identifier* identifier##varname = this->getIdentifier(); \ 69 orxonox::ConfigValueContainer* container##varname = identifier##varname->getConfigValueContainer(#varname); \ 70 if (!container##varname) \ 71 { \ 72 container##varname = new orxonox::ConfigValueContainer(type, identifier##varname, identifier##varname->getName(), #varname, defvalue); \ 73 identifier##varname->addConfigValueContainer(#varname, container##varname); \ 74 } \ 75 container##varname->getValue(&varname, this) 76 77 #define SetConfigValueVector(varname, defvalue) SetConfigValueVectorGeneric(ConfigFileType::Settings, varname, defvalue) 135 #define ResetConfigValue(varname) \ 136 orxonox::resetConfigValueGeneric(this, &varname, #varname) 78 137 79 138 80 /** 81 @brief Sets the variable and the config-file entry back to the previously defined default-value. 82 @param varname The name of the variable 139 /** Modifies a runtime configurable value by using a modifier and some arguments. 140 If the container for the value doesn't yet exist, a warning is displayed. 141 Also, the @a variable argument will be modified and set to the current value. 142 @param object 143 Class instance that the config value should belong to (usually just 'this') 144 @param variable 145 Pointer to the variable where the value should be written to 146 @param entryName 147 Name of the entry in the ini file (e.g. [MySection] myValue) 148 @param modifier 149 On of these functions: set, tset, add, remove, reset, update 150 @param ... 151 Arguments for the modifier function 83 152 */ 84 #define ResetConfigValue(varname) \ 85 orxonox::ConfigValueContainer* container##varname##reset = this->getIdentifier()->getConfigValueContainer(#varname); \ 86 if (container##varname##reset) \ 153 #define ModifyConfigValueGeneric(object, variable, entryName, modifier, ...) \ 154 if (orxonox::ConfigValueContainer* container = object->getIdentifier()->getConfigValueContainer(entryName)) \ 87 155 { \ 88 container ##varname##reset->reset(); \89 container ##varname##reset->getValue(&varname, this); \156 container->modifier(__VA_ARGS__); \ 157 container->getValue(variable, object); \ 90 158 } \ 91 159 else \ 92 160 { \ 93 COUT(2) << "Warning: Couldn't reset config-value '" << #varname << "', corresponding container doesn't exist." << std::endl; \ 161 COUT(2) << "Warning: Couln't modify config-value '" << entryName << "' in class '" \ 162 << object->getIdentifier()->getName() << "', corresponding container doesn't exist." << std::endl; \ 94 163 } 95 164 96 97 /** 98 @brief Modifies a config-value by using a modifier and some arguments. 99 @param varname The name of the config-value 100 @param modifier The name of the modifier: set, tset, add, remove, reset, update 165 /** Modifies a runtime configurable value by using a modifier and some arguments. 166 If the container for the value doesn't yet exist, a warning is displayed. 167 Also, the @a varname argument will be modified and set to the current value. 168 @param varname 169 Variable name as C++ identifier. It will be used as entry name and as variable pointer 170 @param modifier 171 On of these functions: set, tset, add, remove, reset, update 172 @param ... 173 Arguments for the modifier function 101 174 */ 102 175 #define ModifyConfigValue(varname, modifier, ...) \ 103 orxonox::ConfigValueContainer* container##varname##modify##modifier = this->getIdentifier()->getConfigValueContainer(#varname); \ 104 if (container##varname##modify##modifier) \ 105 { \ 106 container##varname##modify##modifier->modifier(__VA_ARGS__); \ 107 container##varname##modify##modifier->getValue(&varname, this); \ 108 } \ 109 else \ 110 { \ 111 COUT(2) << "Warning: Couln't modify config-value '" << #varname << "', corresponding container doesn't exist." << std::endl; \ 112 } 176 ModifyConfigValueGeneric(this, &varname, #varname, modifier, __VA_ARGS__) 113 177 114 178 #endif /* _ConfigValueIncludes_H__ */ -
code/branches/pickup2/src/libraries/core/ConsoleCommandCompilation.cc
r5781 r6412 35 35 #include "util/Debug.h" 36 36 #include "util/ExprParser.h" 37 #include "util/StringUtils.h" 37 38 #include "ConsoleCommand.h" 38 39 … … 86 87 std::string echo(const std::string& text) 87 88 { 88 std::cout << text << std::endl;89 89 return text; 90 90 } … … 143 143 } 144 144 145 std::string output = "";145 std::string output; 146 146 while (file.good() && !file.eof()) 147 147 { … … 159 159 float calculate(const std::string& calculation) 160 160 { 161 ExprParser expr(calculation); 161 ExprParser expr; 162 expr.parse(calculation); 162 163 if (expr.getSuccess()) 163 164 { … … 166 167 COUT(3) << "Greetings from the restaurant at the end of the universe." << std::endl; 167 168 } 168 if ( expr.getRemains() != "")169 if (!expr.getRemains().empty()) 169 170 { 170 COUT(2) << "Warning: Expression could not be parsed to the end! Remains: '" << expr.getRemains() << "'"<< std::endl;171 COUT(2) << "Warning: Expression could not be parsed to the end! Remains: '" << expr.getRemains() << '\'' << std::endl; 171 172 } 172 173 return static_cast<float>(expr.getResult()); -
code/branches/pickup2/src/libraries/core/Core.cc
r5929 r6412 51 51 #include "util/Debug.h" 52 52 #include "util/Exception.h" 53 #include "util/Scope.h" 53 54 #include "util/SignalHandler.h" 54 55 #include "PathConfig.h" 55 56 #include "CommandExecutor.h" 56 #include "CommandLine .h"57 #include "CommandLineParser.h" 57 58 #include "ConfigFileManager.h" 58 59 #include "ConfigValueIncludes.h" … … 64 65 #include "Identifier.h" 65 66 #include "Language.h" 67 #include "IOConsole.h" 66 68 #include "LuaState.h" 67 69 #include "ScopedSingletonManager.h" 68 #include "Shell.h"69 70 #include "TclBind.h" 70 71 #include "TclThreadManager.h" … … 78 79 SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file"); 79 80 #ifdef ORXONOX_PLATFORM_WINDOWS 80 SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one cpu/core (1, 2, 3, etc.). 0 turns it off (default)"); 81 #endif 82 83 /** 84 @brief 85 Helper class for the Core singleton: we cannot derive 86 Core from OrxonoxClass because we need to handle the Identifier 87 destruction in the Core destructor. 88 */ 89 class CoreConfiguration : public OrxonoxClass 90 { 91 public: 92 CoreConfiguration() 93 { 94 } 95 96 void initialise() 97 { 98 RegisterRootObject(CoreConfiguration); 99 this->setConfigValues(); 100 } 101 102 /** 103 @brief Function to collect the SetConfigValue-macro calls. 104 */ 105 void setConfigValues() 106 { 107 #ifdef NDEBUG 108 const unsigned int defaultLevelConsole = 1; 109 const unsigned int defaultLevelLogfile = 3; 110 const unsigned int defaultLevelShell = 1; 111 #else 112 const unsigned int defaultLevelConsole = 3; 113 const unsigned int defaultLevelLogfile = 4; 114 const unsigned int defaultLevelShell = 3; 115 #endif 116 SetConfigValue(softDebugLevelConsole_, defaultLevelConsole) 117 .description("The maximal level of debug output shown in the console") 118 .callback(this, &CoreConfiguration::debugLevelChanged); 119 SetConfigValue(softDebugLevelLogfile_, defaultLevelLogfile) 120 .description("The maximal level of debug output shown in the logfile") 121 .callback(this, &CoreConfiguration::debugLevelChanged); 122 SetConfigValue(softDebugLevelShell_, defaultLevelShell) 123 .description("The maximal level of debug output shown in the ingame shell") 124 .callback(this, &CoreConfiguration::debugLevelChanged); 125 126 SetConfigValue(language_, Language::getInstance().defaultLanguage_) 127 .description("The language of the ingame text") 128 .callback(this, &CoreConfiguration::languageChanged); 129 SetConfigValue(bInitializeRandomNumberGenerator_, true) 130 .description("If true, all random actions are different each time you start the game") 131 .callback(this, &CoreConfiguration::initializeRandomNumberGenerator); 132 } 133 134 /** 135 @brief Callback function if the debug level has changed. 136 */ 137 void debugLevelChanged() 138 { 139 // softDebugLevel_ is the maximum of the 3 variables 140 this->softDebugLevel_ = this->softDebugLevelConsole_; 141 if (this->softDebugLevelLogfile_ > this->softDebugLevel_) 142 this->softDebugLevel_ = this->softDebugLevelLogfile_; 143 if (this->softDebugLevelShell_ > this->softDebugLevel_) 144 this->softDebugLevel_ = this->softDebugLevelShell_; 145 146 OutputHandler::setSoftDebugLevel(OutputHandler::LD_All, this->softDebugLevel_); 147 OutputHandler::setSoftDebugLevel(OutputHandler::LD_Console, this->softDebugLevelConsole_); 148 OutputHandler::setSoftDebugLevel(OutputHandler::LD_Logfile, this->softDebugLevelLogfile_); 149 OutputHandler::setSoftDebugLevel(OutputHandler::LD_Shell, this->softDebugLevelShell_); 150 } 151 152 /** 153 @brief Callback function if the language has changed. 154 */ 155 void languageChanged() 156 { 157 // Read the translation file after the language was configured 158 Language::getInstance().readTranslatedLanguageFile(); 159 } 160 161 /** 162 @brief Sets the language in the config-file back to the default. 163 */ 164 void resetLanguage() 165 { 166 ResetConfigValue(language_); 167 } 168 169 void initializeRandomNumberGenerator() 170 { 171 static bool bInitialized = false; 172 if (!bInitialized && this->bInitializeRandomNumberGenerator_) 173 { 174 srand(static_cast<unsigned int>(time(0))); 175 rand(); 176 bInitialized = true; 177 } 178 } 179 180 int softDebugLevel_; //!< The debug level 181 int softDebugLevelConsole_; //!< The debug level for the console 182 int softDebugLevelLogfile_; //!< The debug level for the logfile 183 int softDebugLevelShell_; //!< The debug level for the ingame shell 184 std::string language_; //!< The language 185 bool bInitializeRandomNumberGenerator_; //!< If true, srand(time(0)) is called 186 }; 187 81 SetCommandLineArgument(limitToCPU, 1).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is the first core (faster than off)"); 82 #endif 188 83 189 84 Core::Core(const std::string& cmdLine) … … 192 87 // Cleanup guard for external console commands that don't belong to an Identifier 193 88 , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands) 194 , configuration_(new CoreConfiguration()) // Don't yet create config values!195 89 , bGraphicsLoaded_(false) 196 90 { … … 216 110 217 111 // Parse command line arguments AFTER the modules have been loaded (static code!) 218 CommandLine ::parseCommandLine(cmdLine);112 CommandLineParser::parseCommandLine(cmdLine); 219 113 220 114 // Set configurable paths like log, config and media 221 115 this->pathConfig_->setConfigurablePaths(); 222 116 223 // create a signal handler (only active for linux)117 // create a signal handler (only active for Linux) 224 118 // This call is placed as soon as possible, but after the directories are set 225 119 this->signalHandler_.reset(new SignalHandler()); 226 120 this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log"); 227 121 228 // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used229 OutputHandler::get OutStream().setLogPath(PathConfig::getLogPathString());122 // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% (Windows) was used 123 OutputHandler::getInstance().setLogPath(PathConfig::getLogPathString()); 230 124 231 125 // Parse additional options file now that we know its path 232 CommandLine ::parseFile();126 CommandLineParser::parseFile(); 233 127 234 128 #ifdef ORXONOX_PLATFORM_WINDOWS … … 236 130 // do this after ogre has initialised. Somehow Ogre changes the settings again (not through 237 131 // the timer though). 238 int limitToCPU = CommandLine ::getValue("limitToCPU");132 int limitToCPU = CommandLineParser::getValue("limitToCPU"); 239 133 if (limitToCPU > 0) 240 134 setThreadAffinity(static_cast<unsigned int>(limitToCPU)); … … 244 138 this->configFileManager_.reset(new ConfigFileManager()); 245 139 this->configFileManager_->setFilename(ConfigFileType::Settings, 246 CommandLine ::getValue("settingsFile").getString());140 CommandLineParser::getValue("settingsFile").getString()); 247 141 248 142 // Required as well for the config values 249 143 this->languageInstance_.reset(new Language()); 250 144 145 // Do this soon after the ConfigFileManager has been created to open up the 146 // possibility to configure everything below here 147 ClassIdentifier<Core>::getIdentifier("Core")->initialiseObject(this, "Core", true); 148 this->setConfigValues(); 149 150 // create persistent io console 151 this->ioConsole_.reset(new IOConsole()); 152 251 153 // creates the class hierarchy for all classes with factories 252 154 Identifier::createClassHierarchy(); 253 254 // Do this soon after the ConfigFileManager has been created to open up the255 // possibility to configure everything below here256 this->configuration_->initialise();257 155 258 156 // Load OGRE excluding the renderer and the render window … … 262 160 this->tclBind_.reset(new TclBind(PathConfig::getDataPathString())); 263 161 this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter())); 264 265 // create a shell266 this->shell_.reset(new Shell());267 162 268 163 // Create singletons that always exist (in other libraries) … … 276 171 Core::~Core() 277 172 { 173 // Remove us from the object lists again to avoid problems when destroying them 174 this->unregisterObject(); 175 } 176 177 //! Function to collect the SetConfigValue-macro calls. 178 void Core::setConfigValues() 179 { 180 #ifdef ORXONOX_RELEASE 181 const unsigned int defaultLevelLogFile = 3; 182 #else 183 const unsigned int defaultLevelLogFile = 4; 184 #endif 185 setConfigValueGeneric(this, &this->softDebugLevelLogFile_, ConfigFileType::Settings, "OutputHandler", "softDebugLevelLogFile", defaultLevelLogFile) 186 .description("The maximum level of debug output shown in the log file"); 187 OutputHandler::getInstance().setSoftDebugLevel(OutputHandler::logFileOutputListenerName_s, this->softDebugLevelLogFile_); 188 189 SetConfigValue(language_, Language::getInstance().defaultLanguage_) 190 .description("The language of the in game text") 191 .callback(this, &Core::languageChanged); 192 SetConfigValue(bInitRandomNumberGenerator_, true) 193 .description("If true, all random actions are different each time you start the game") 194 .callback(this, &Core::initRandomNumberGenerator); 195 } 196 197 //! Callback function if the language has changed. 198 void Core::languageChanged() 199 { 200 // Read the translation file after the language was configured 201 Language::getInstance().readTranslatedLanguageFile(); 202 } 203 204 void Core::initRandomNumberGenerator() 205 { 206 static bool bInitialized = false; 207 if (!bInitialized && this->bInitRandomNumberGenerator_) 208 { 209 srand(static_cast<unsigned int>(time(0))); 210 rand(); 211 bInitialized = true; 212 } 278 213 } 279 214 … … 327 262 } 328 263 329 /** 330 @brief Returns the softDebugLevel for the given device (returns a default-value if the class is right about to be created). 331 @param device The device 332 @return The softDebugLevel 333 */ 334 /*static*/ int Core::getSoftDebugLevel(OutputHandler::OutputDevice device) 335 { 336 switch (device) 337 { 338 case OutputHandler::LD_All: 339 return Core::getInstance().configuration_->softDebugLevel_; 340 case OutputHandler::LD_Console: 341 return Core::getInstance().configuration_->softDebugLevelConsole_; 342 case OutputHandler::LD_Logfile: 343 return Core::getInstance().configuration_->softDebugLevelLogfile_; 344 case OutputHandler::LD_Shell: 345 return Core::getInstance().configuration_->softDebugLevelShell_; 346 default: 347 assert(0); 348 return 2; 349 } 350 } 351 352 /** 353 @brief Sets the softDebugLevel for the given device. Please use this only temporary and restore the value afterwards, as it overrides the configured value. 354 @param device The device 355 @param level The level 356 */ 357 /*static*/ void Core::setSoftDebugLevel(OutputHandler::OutputDevice device, int level) 358 { 359 if (device == OutputHandler::LD_All) 360 Core::getInstance().configuration_->softDebugLevel_ = level; 361 else if (device == OutputHandler::LD_Console) 362 Core::getInstance().configuration_->softDebugLevelConsole_ = level; 363 else if (device == OutputHandler::LD_Logfile) 364 Core::getInstance().configuration_->softDebugLevelLogfile_ = level; 365 else if (device == OutputHandler::LD_Shell) 366 Core::getInstance().configuration_->softDebugLevelShell_ = level; 367 368 OutputHandler::setSoftDebugLevel(device, level); 369 } 370 371 /** 372 @brief Returns the configured language. 373 */ 374 /*static*/ const std::string& Core::getLanguage() 375 { 376 return Core::getInstance().configuration_->language_; 377 } 378 379 /** 380 @brief Sets the language in the config-file back to the default. 381 */ 382 /*static*/ void Core::resetLanguage() 383 { 384 Core::getInstance().configuration_->resetLanguage(); 264 //! Sets the language in the config-file back to the default. 265 void Core::resetLanguage() 266 { 267 ResetConfigValue(language_); 385 268 } 386 269 … … 433 316 void Core::preUpdate(const Clock& time) 434 317 { 435 // singletons from other libraries436 ScopedSingletonManager:: update<ScopeID::Root>(time);318 // Update singletons before general ticking 319 ScopedSingletonManager::preUpdate<ScopeID::Root>(time); 437 320 if (this->bGraphicsLoaded_) 438 321 { 439 // process input events 440 this->inputManager_->update(time); 441 // process gui events 442 this->guiManager_->update(time); 443 // graphics singletons from other libraries 444 ScopedSingletonManager::update<ScopeID::Graphics>(time); 445 } 446 // process thread commands 447 this->tclThreadManager_->update(time); 322 // Process input events 323 this->inputManager_->preUpdate(time); 324 // Update GUI 325 this->guiManager_->preUpdate(time); 326 // Update singletons before general ticking 327 ScopedSingletonManager::preUpdate<ScopeID::Graphics>(time); 328 } 329 // Process console events and status line 330 this->ioConsole_->preUpdate(time); 331 // Process thread commands 332 this->tclThreadManager_->preUpdate(time); 448 333 } 449 334 450 335 void Core::postUpdate(const Clock& time) 451 336 { 337 // Update singletons just before rendering 338 ScopedSingletonManager::postUpdate<ScopeID::Root>(time); 452 339 if (this->bGraphicsLoaded_) 453 340 { 341 // Update singletons just before rendering 342 ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time); 454 343 // Render (doesn't throw) 455 this->graphicsManager_-> update(time);344 this->graphicsManager_->postUpdate(time); 456 345 } 457 346 } -
code/branches/pickup2/src/libraries/core/Core.h
r5929 r6412 35 35 #include <cassert> 36 36 #include <boost/scoped_ptr.hpp> 37 #include "util/OutputHandler.h"38 #include "util/Scope.h"39 37 #include "util/ScopeGuard.h" 40 38 #include "util/Singleton.h" 39 #include "core/OrxonoxClass.h" 41 40 42 41 namespace orxonox 43 42 { 44 class CoreConfiguration;45 46 43 /** 47 44 @brief … … 50 47 You should only create this singleton once because it destroys the identifiers! 51 48 */ 52 class _CoreExport Core : public Singleton<Core> 49 class _CoreExport Core : public Singleton<Core>, public OrxonoxClass 53 50 { 54 51 typedef Loki::ScopeGuardImpl0<void (*)()> SimpleScopeGuard; … … 69 66 void setConfigValues(); 70 67 71 static int getSoftDebugLevel(OutputHandler::OutputDevice device = OutputHandler::LD_All);72 static void setSoftDebugLevel(OutputHandler::OutputDevice device, int level);73 static const std::string& getLanguage();74 static voidresetLanguage();68 //! Returns the configured language. 69 const std::string& getLanguage() 70 { return this->language_; } 71 void resetLanguage(); 75 72 76 73 private: 77 74 Core(const Core&); //!< Don't use (undefined symbol) 75 76 void languageChanged(); 77 void initRandomNumberGenerator(); 78 78 79 79 void preUpdate(const Clock& time); … … 84 84 85 85 void setThreadAffinity(int limitToCPU); 86 86 // MANAGED SINGLETONS/OBJECTS 87 87 // Mind the order for the destruction! 88 88 scoped_ptr<PathConfig> pathConfig_; … … 93 93 scoped_ptr<ConfigFileManager> configFileManager_; 94 94 scoped_ptr<Language> languageInstance_; 95 scoped_ptr< CoreConfiguration> configuration_;95 scoped_ptr<IOConsole> ioConsole_; 96 96 scoped_ptr<TclBind> tclBind_; 97 97 scoped_ptr<TclThreadManager> tclThreadManager_; 98 scoped_ptr<S hell> shell_;98 scoped_ptr<Scope<ScopeID::Root> > rootScope_; 99 99 // graphical 100 100 scoped_ptr<GraphicsManager> graphicsManager_; //!< Interface to OGRE 101 101 scoped_ptr<InputManager> inputManager_; //!< Interface to OIS 102 102 scoped_ptr<GUIManager> guiManager_; //!< Interface to GUI 103 scoped_ptr<Scope<ScopeID::Root> > rootScope_;104 103 scoped_ptr<Scope<ScopeID::Graphics> > graphicsScope_; 105 104 106 105 bool bGraphicsLoaded_; 107 static Core* singletonPtr_s; 106 int softDebugLevelLogFile_; //!< The debug level for the log file (belongs to OutputHandler) 107 std::string language_; //!< The language 108 bool bInitRandomNumberGenerator_; //!< If true, srand(time(0)) is called 109 110 static Core* singletonPtr_s; 108 111 }; 109 112 } -
code/branches/pickup2/src/libraries/core/CorePrereqs.h
r5929 r6412 116 116 class ClassTreeMaskObjectIterator; 117 117 class CommandEvaluation; 118 class CommandLine ;118 class CommandLineParser; 119 119 class CommandLineArgument; 120 120 class ConfigFile; … … 148 148 class GUIManager; 149 149 class Identifier; 150 class IOConsole; 150 151 class IRC; 151 152 template <class T> -
code/branches/pickup2/src/libraries/core/DynLib.cc
r5750 r6412 70 70 COUT(2) << "Loading module " << mName << std::endl; 71 71 72 std::stringname = mName;72 const std::string& name = mName; 73 73 #ifdef ORXONOX_PLATFORM_LINUX 74 74 // dlopen() does not add .so to the filename, like windows does for .dll … … 93 93 94 94 if( DYNLIB_UNLOAD( m_hInst ) ) 95 95 { 96 96 ThrowException( 97 97 General, 98 98 "Could not unload dynamic library " + mName + 99 99 ". System Error: " + dynlibError()); 100 100 } 101 101 102 102 } … … 132 132 return std::string(mac_errorBundle()); 133 133 #else 134 return std::string("");134 return ""; 135 135 #endif 136 136 } -
code/branches/pickup2/src/libraries/core/DynLib.h
r5738 r6412 72 72 Resource 73 73 */ 74 74 class _CoreExport DynLib 75 75 { 76 77 76 protected: 77 std::string mName; 78 78 /// Gets the last loading error 79 79 std::string dynlibError(void); … … 95 95 */ 96 96 void unload(); 97 98 97 /// Get the name of the library 98 const std::string& getName(void) const { return mName; } 99 99 100 100 /** -
code/branches/pickup2/src/libraries/core/DynLibManager.cc
r5738 r6412 41 41 42 42 //----------------------------------------------------------------------- 43 44 45 46 43 DynLibManager::DynLibManager() 44 { 45 } 46 //----------------------------------------------------------------------- 47 47 DynLib* DynLibManager::load( const std::string& filename) 48 48 { 49 50 51 52 53 54 55 56 57 58 59 60 49 DynLibList::iterator i = mLibList.find(filename); 50 if (i != mLibList.end()) 51 { 52 return i->second; 53 } 54 else 55 { 56 DynLib* pLib = new DynLib(filename); 57 pLib->load(); 58 mLibList[filename] = pLib; 59 return pLib; 60 } 61 61 } 62 63 64 65 66 67 68 69 70 71 72 73 62 //----------------------------------------------------------------------- 63 void DynLibManager::unload(DynLib* lib) 64 { 65 DynLibList::iterator i = mLibList.find(lib->getName()); 66 if (i != mLibList.end()) 67 { 68 mLibList.erase(i); 69 } 70 lib->unload(); 71 delete lib; 72 } 73 //----------------------------------------------------------------------- 74 74 DynLibManager::~DynLibManager() 75 75 { -
code/branches/pickup2/src/libraries/core/Event.cc
r5929 r6412 45 45 /** 46 46 @brief Processes an event (calls the set-function if the necessary conditions are met). 47 47 48 48 @param event The fired event 49 49 @param object The object whose state is affected by the event (only needed for debug output) … … 53 53 if (this->bProcessingEvent_) 54 54 { 55 COUT(2) << "Warning: Detected Event loop in section \"" << event.statename_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << "\""<< std::endl;55 COUT(2) << "Warning: Detected Event loop in section \"" << event.statename_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << '"' << std::endl; 56 56 return; 57 57 } -
code/branches/pickup2/src/libraries/core/Event.h
r5929 r6412 50 50 /** 51 51 @brief The EventState contains information about an event state. 52 52 53 53 An event state is a state of an object, which can be changed by events. 54 54 Event states are changed through functions. Possible functions headers for set event states are: … … 56 56 - boolean state: function(bool state) 57 57 - individual state: function(bool state, SomeClass originator) 58 58 59 59 Note that SomeClass may be any class deriving from BaseObject. You will not receive events from originators of other classes. 60 60 The actual class for SomeClass must be specified as the second argument of the XMLPortEventState macro. 61 61 62 62 The this pointer of the affected object is hidden in the functors, because the events are processed in the BaseObject, but some 63 63 statefunctions may be from child-classes. … … 70 70 71 71 void process(const Event& event, BaseObject* object); 72 72 73 73 Functor* getFunctor() const 74 74 { return this->statefunction_; } -
code/branches/pickup2/src/libraries/core/EventIncludes.h
r5929 r6412 36 36 /** 37 37 @brief Defines a new event state (a state of the object which can be changed by events). 38 38 39 39 @param classname The name of this class 40 40 @param subclassname Usually BaseObject - if different, only instances of this class can send events to this object … … 66 66 67 67 #define XMLPortEventStateIntern(name, classname, statename, xmlelement, mode) \ 68 static orxonox::ExecutorMember<classname>* xmlsetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::addEventSource), std::string( #classname ) + "::" + "addEventSource" + "(" + statename + ")")->setDefaultValue(1, statename); \69 static orxonox::ExecutorMember<classname>* xmlgetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::getEventSource), std::string( #classname ) + "::" + "getEventSource" + "(" + statename + ")")->setDefaultValue(1, statename); \68 static orxonox::ExecutorMember<classname>* xmlsetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::addEventSource), std::string( #classname ) + "::" + "addEventSource" + '(' + statename + ')')->setDefaultValue(1, statename); \ 69 static orxonox::ExecutorMember<classname>* xmlgetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::getEventSource), std::string( #classname ) + "::" + "getEventSource" + '(' + statename + ')')->setDefaultValue(1, statename); \ 70 70 XMLPortObjectGeneric(xmlport##name, classname, orxonox::BaseObject, statename, xmlsetfunctor##name, xmlgetfunctor##name, xmlelement, mode, false, true) 71 71 72 72 73 73 /** 74 74 @brief Defines a new event name for a class. Named events can only have names which were defined with this macro. 75 75 76 76 @param classname The name of the class 77 77 @param name The name of the event … … 82 82 /** 83 83 @brief This macro is needed to fire an event with this name. The event name must previously be declared with @ref CreateEventName. 84 */ 84 */ 85 85 #define FireEventName(classname, name) \ 86 86 eventname##classname##name 87 87 88 88 #endif /* _EventIncludes_H__ */ -
code/branches/pickup2/src/libraries/core/Executor.cc
r5738 r6412 73 73 { 74 74 // only one param: check if there are params given, otherwise try to use default values 75 std::string temp = getStripped(params); 76 if ((temp != "") && (temp.size() != 0)) 75 if (!getStripped(params).empty()) 77 76 { 78 77 param[0] = params; -
code/branches/pickup2/src/libraries/core/Executor.h
r5738 r6412 63 63 else if (paramCount == 1) \ 64 64 { \ 65 std::stringtemp = getStripped(params); \66 if ( (temp != "") && (temp.size() != 0)) \65 const std::string& temp = getStripped(params); \ 66 if (!temp.empty()) \ 67 67 { \ 68 68 COUT(5) << "Calling Executor " << this->name_ << " through parser with one parameter, using whole string: " << params << std::endl; \ … … 187 187 { return this->functor_->getTypenameReturnvalue(); } 188 188 189 inline void setName(const std::string name)189 inline void setName(const std::string& name) 190 190 { this->name_ = name; } 191 191 inline const std::string& getName() const -
code/branches/pickup2/src/libraries/core/Functor.h
r5929 r6412 35 35 #include "util/Debug.h" 36 36 #include "util/MultiType.h" 37 #include "util/StringUtils.h"38 37 39 38 namespace orxonox -
code/branches/pickup2/src/libraries/core/GUIManager.cc
r5929 r6412 40 40 #include <CEGUIResourceProvider.h> 41 41 #include <CEGUISystem.h> 42 #include <CEGUIWindow.h> 42 43 #include <ogreceguirenderer/OgreCEGUIRenderer.h> 43 44 … … 50 51 51 52 #include "util/Clock.h" 53 #include "util/Convert.h" 52 54 #include "util/Debug.h" 53 55 #include "util/Exception.h" 54 56 #include "util/OrxAssert.h" 57 #include "ConsoleCommand.h" 55 58 #include "Core.h" 56 59 #include "LuaState.h" … … 60 63 namespace orxonox 61 64 { 65 static void key_esc() 66 { GUIManager::getInstance().keyESC(); } 67 SetConsoleCommandShortcutExternAlias(key_esc, "keyESC"); 68 62 69 class CEGUILogger : public CEGUI::DefaultLogger 63 70 { … … 75 82 default: OrxAssert(false, "CEGUI log level out of range, inpect immediately!"); 76 83 } 77 OutputHandler::getOutStream( ).setOutputLevel(orxonoxLevel)84 OutputHandler::getOutStream(orxonoxLevel) 78 85 << "CEGUI: " << message << std::endl; 79 86 … … 85 92 86 93 GUIManager* GUIManager::singletonPtr_s = 0; 94 95 SetConsoleCommandShortcut(GUIManager, showGUI).accessLevel(AccessLevel::User).defaultValue(1, false).defaultValue(2, true); 96 SetConsoleCommandShortcut(GUIManager, hideGUI).accessLevel(AccessLevel::User); 87 97 88 98 /** … … 102 112 , resourceProvider_(0) 103 113 , camera_(NULL) 114 , bShowIngameGUI_(false) 104 115 { 105 116 using namespace CEGUI; … … 114 125 // setup scripting 115 126 luaState_.reset(new LuaState()); 127 rootFileInfo_ = Resource::getInfo("InitialiseGUI.lua"); 128 // This is necessary to ensure that input events also use the right resource info when triggering lua functions 129 luaState_->setDefaultResourceInfo(this->rootFileInfo_); 116 130 scriptModule_.reset(new LuaScriptModule(luaState_->getInternalLuaState())); 117 131 … … 121 135 // set the log level according to ours (translate by subtracting 1) 122 136 ceguiLogger->setLoggingLevel( 123 static_cast<LoggingLevel>( Core::getSoftDebugLevel(OutputHandler::LD_Logfile) - 1));137 static_cast<LoggingLevel>(OutputHandler::getInstance().getSoftDebugLevel("logFile") - 1)); 124 138 this->ceguiLogger_ = ceguiLogger.release(); 125 139 … … 127 141 guiSystem_.reset(new System(guiRenderer_.get(), resourceProvider_, 0, scriptModule_.get())); 128 142 129 // Initialise the basic lua code 130 rootFileInfo_ = Resource::getInfo("InitialiseGUI.lua", "GUI"); 131 this->luaState_->doFile("InitialiseGUI.lua", "GUI", false); 143 // Initialise the basic Lua code 144 this->luaState_->doFile("InitialiseGUI.lua"); 132 145 133 146 // Align CEGUI mouse with OIS mouse 134 147 guiSystem_->injectMousePosition(mousePosition.first, mousePosition.second); 135 148 136 // Hide the mouse cursor unless playing in full screen mode149 // Hide the mouse cursor unless playing in full screen mode 137 150 if (!bFullScreen) 138 151 CEGUI::MouseCursor::getSingleton().hide(); … … 157 170 This time value is then used to provide a fluent animation of the GUI. 158 171 */ 159 void GUIManager:: update(const Clock& time)172 void GUIManager::preUpdate(const Clock& time) 160 173 { 161 174 assert(guiSystem_); … … 204 217 For more details check out loadGUI_2.lua where the function presides. 205 218 */ 206 void GUIManager::showGUI(const std::string& name) 207 { 208 this->luaState_->doString("showGUI(\"" + name + "\")", rootFileInfo_); 219 /*static*/ void GUIManager::showGUI(const std::string& name, bool hidePrevious, bool showCursor) 220 { 221 GUIManager::getInstance().executeCode("showGUI(\"" + name + "\", " + multi_cast<std::string>(hidePrevious) + ", " + multi_cast<std::string>(showCursor) + ")"); 222 } 223 224 /** 225 @brief 226 Hack-ish. Needed for GUIOverlay. 227 */ 228 void GUIManager::showGUIExtra(const std::string& name, const std::string& ptr, bool hidePrevious, bool showCursor) 229 { 230 this->executeCode("showGUI(\"" + name + "\", " + multi_cast<std::string>(hidePrevious) + ", " + multi_cast<std::string>(showCursor) + ", " + ptr + ")"); 231 } 232 233 /** 234 @brief 235 Hides specified GUI. 236 @param name 237 The name of the GUI. 238 */ 239 /*static*/ void GUIManager::hideGUI(const std::string& name) 240 { 241 GUIManager::getInstance().executeCode("hideGUI(\"" + name + "\")"); 242 } 243 244 void GUIManager::keyESC() 245 { 246 this->executeCode("keyESC()"); 247 } 248 249 void GUIManager::setBackground(const std::string& name) 250 { 251 this->executeCode("setBackground(\"" + name + "\")"); 209 252 } 210 253 … … 280 323 code of the mouse button as it is used by CEGUI 281 324 282 Simple conver tion from mouse event code in Orxonox to the one used in CEGUI.325 Simple conversion from mouse event code in Orxonox to the one used in CEGUI. 283 326 */ 284 327 static inline CEGUI::MouseButton convertButton(MouseButtonCode::ByEnum button) … … 305 348 } 306 349 } 350 351 void GUIManager::subscribeEventHelper(CEGUI::Window* window, const std::string& event, const std::string& function) 352 { 353 window->subscribeScriptedEvent(event, function); 354 } 307 355 } -
code/branches/pickup2/src/libraries/core/GUIManager.h
r5929 r6412 34 34 35 35 #include <map> 36 #include <set> 36 37 #include <string> 37 38 #include <CEGUIForwardRefs.h> … … 43 44 #include "input/InputHandler.h" 44 45 45 namespace orxonox 46 { 46 namespace orxonox // tolua_export 47 { // tolua_export 47 48 class PlayerInfo; // Forward declaration 48 49 … … 58 59 Those input events are then injected into CEGUI in Lua. 59 60 */ 60 class _CoreExport GUIManager : public Singleton<GUIManager>, public InputHandler 61 { 61 class _CoreExport GUIManager // tolua_export 62 : public Singleton<GUIManager>, public InputHandler 63 { // tolua_export 62 64 friend class Singleton<GUIManager>; 63 65 public: … … 65 67 ~GUIManager(); 66 68 67 void update(const Clock& time);69 void preUpdate(const Clock& time); 68 70 69 void showGUI(const std::string& name); 70 void executeCode(const std::string& str); 71 static void showGUI(const std::string& name, bool hidePrevious=false, bool showCursor=true); 72 void showGUIExtra(const std::string& name, const std::string& ptr, bool hidePrevious=false, bool showCursor=true); 73 static void hideGUI(const std::string& name); 74 void keyESC(); 75 void setBackground(const std::string& name); 71 76 72 77 void setCamera(Ogre::Camera* camera); … … 80 85 { std::map<std::string, PlayerInfo*>::const_iterator it = this->players_.find(guiname); return (it != this->players_.end()) ? it->second : 0; } 81 86 87 // TODO: Temporary hack because the tolua exported CEGUI method does not seem to work 88 static void subscribeEventHelper(CEGUI::Window* window, const std::string& event, const std::string& function); //tolua_export 89 82 90 private: 83 91 GUIManager(const GUIManager& instance); //!< private and undefined copy c'tor (this is a singleton class) 92 93 void executeCode(const std::string& str); 84 94 85 95 // keyHandler functions … … 105 115 106 116 static GUIManager* singletonPtr_s; //!< Singleton reference to GUIManager 117 bool bShowIngameGUI_; 107 118 108 }; 109 } 119 }; // tolua_export 120 } // tolua_export 110 121 111 122 #endif /* _GUIManager_H__ */ -
code/branches/pickup2/src/libraries/core/Game.cc
r5929 r6412 44 44 #include "util/Sleep.h" 45 45 #include "util/SubString.h" 46 #include "CommandLine .h"46 #include "CommandLineParser.h" 47 47 #include "ConsoleCommand.h" 48 48 #include "Core.h" … … 51 51 #include "GameMode.h" 52 52 #include "GameState.h" 53 #include "GUIManager.h" 53 54 54 55 namespace orxonox … … 67 68 Game* Game::singletonPtr_s = 0; 68 69 69 70 /** 71 @brief 72 Represents one node of the game state tree. 73 */ 70 //! Represents one node of the game state tree. 74 71 struct GameStateTreeNode 75 72 { … … 79 76 }; 80 77 81 82 /**83 @brief84 Another helper class for the Game singleton: we cannot derive85 Game from OrxonoxClass because we need to handle the Identifier86 destruction in the Core destructor.87 */88 class GameConfiguration : public OrxonoxClass89 {90 public:91 GameConfiguration()92 {93 RegisterRootObject(GameConfiguration);94 this->setConfigValues();95 }96 97 void setConfigValues()98 {99 SetConfigValue(statisticsRefreshCycle_, 250000)100 .description("Sets the time in microseconds interval at which average fps, etc. get updated.");101 SetConfigValue(statisticsAvgLength_, 1000000)102 .description("Sets the time in microseconds interval at which average fps, etc. gets calculated.");103 SetConfigValue(fpsLimit_, 50)104 .description("Sets the desired framerate (0 for no limit).");105 }106 107 unsigned int statisticsRefreshCycle_;108 unsigned int statisticsAvgLength_;109 unsigned int fpsLimit_;110 };111 112 113 /**114 @brief115 Non-initialising constructor.116 */117 78 Game::Game(const std::string& cmdLine) 118 79 // Destroy factories before the Core! … … 128 89 #endif 129 90 91 // reset statistics 92 this->statisticsStartTime_ = 0; 93 this->statisticsTickTimes_.clear(); 94 this->periodTickTime_ = 0; 95 this->periodTime_ = 0; 96 this->avgFPS_ = 0.0f; 97 this->avgTickTime_ = 0.0f; 98 this->excessSleepTime_ = 0; 99 130 100 // Create an empty root state 131 101 this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false); … … 136 106 // Create the Core 137 107 this->core_.reset(new Core(cmdLine)); 108 109 // Do this after the Core creation! 110 ClassIdentifier<Game>::getIdentifier("Game")->initialiseObject(this, "Game", true); 111 this->setConfigValues(); 138 112 139 113 // After the core has been created, we can safely instantiate the GameStates that don't require graphics … … 150 124 this->loadedTopStateNode_ = this->rootStateNode_; 151 125 this->loadedStates_.push_back(this->getState(rootStateNode_->name_)); 152 153 // Do this after the Core creation!154 this->configuration_.reset(new GameConfiguration());155 126 } 156 127 … … 161 132 Game::~Game() 162 133 { 134 // Remove us from the object lists again to avoid problems when destroying them 135 this->unregisterObject(); 136 } 137 138 void Game::setConfigValues() 139 { 140 SetConfigValue(statisticsRefreshCycle_, 250000) 141 .description("Sets the time in microseconds interval at which average fps, etc. get updated."); 142 SetConfigValue(statisticsAvgLength_, 1000000) 143 .description("Sets the time in microseconds interval at which average fps, etc. gets calculated."); 144 SetConfigValue(fpsLimit_, 50) 145 .description("Sets the desired frame rate (0 for no limit)."); 163 146 } 164 147 … … 176 159 COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl; 177 160 178 // reset statistics179 this->statisticsStartTime_ = 0;180 this->statisticsTickTimes_.clear();181 this->periodTickTime_ = 0;182 this->periodTime_ = 0;183 this->avgFPS_ = 0.0f;184 this->avgTickTime_ = 0.0f;185 this->excessSleepTime_ = 0;186 187 161 // START GAME 188 162 // first delta time should be about 0 seconds … … 204 178 this->updateGameStateStack(); 205 179 206 // Core preUpdate (doesn't throw)180 // Core preUpdate 207 181 try 208 182 { this->core_->preUpdate(*this->gameClock_); } … … 218 192 this->updateGameStates(); 219 193 220 // Core postUpdate (doesn't throw)194 // Core postUpdate 221 195 try 222 196 { this->core_->postUpdate(*this->gameClock_); } … … 232 206 this->updateStatistics(); 233 207 234 // Limit frame rate208 // Limit frame rate 235 209 this->updateFPSLimiter(); 236 210 } … … 312 286 this->statisticsTickTimes_.back().tickLength += currentRealTime - currentTime; 313 287 this->periodTickTime_ += currentRealTime - currentTime; 314 if (this->periodTime_ > this-> configuration_->statisticsRefreshCycle_)288 if (this->periodTime_ > this->statisticsRefreshCycle_) 315 289 { 316 290 std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin(); 317 291 assert(it != this->statisticsTickTimes_.end()); 318 int64_t lastTime = currentTime - this-> configuration_->statisticsAvgLength_;292 int64_t lastTime = currentTime - this->statisticsAvgLength_; 319 293 if (static_cast<int64_t>(it->tickTime) < lastTime) 320 294 { … … 330 304 331 305 uint32_t framesPerPeriod = this->statisticsTickTimes_.size(); 332 this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f; 306 // Why minus 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too low 307 this->avgFPS_ = -1 + static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f; 333 308 this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f; 334 309 335 this->periodTime_ -= this-> configuration_->statisticsRefreshCycle_;310 this->periodTime_ -= this->statisticsRefreshCycle_; 336 311 } 337 312 } … … 339 314 void Game::updateFPSLimiter() 340 315 { 341 // Why configuration_->fpsLimit_ - 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too high 342 uint32_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / (configuration_->fpsLimit_ - 1)); 316 uint64_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / fpsLimit_); 343 317 uint64_t currentRealTime = gameClock_->getRealMicroseconds(); 344 318 while (currentRealTime < nextTime - minimumSleepTime_) … … 584 558 585 559 shared_ptr<GameState> state = this->getState(name); 586 state->activate ();560 state->activateInternal(); 587 561 if (!this->loadedStates_.empty()) 588 562 this->loadedStates_.back()->activity_.topState = false; … … 603 577 if (!this->loadedStates_.empty()) 604 578 this->loadedStates_.back()->activity_.topState = true; 605 state->deactivate ();579 state->deactivateInternal(); 606 580 } 607 581 catch (...) -
code/branches/pickup2/src/libraries/core/Game.h
r5929 r6412 50 50 #include "util/ScopeGuard.h" 51 51 #include "util/Singleton.h" 52 #include "core/OrxonoxClass.h" 52 53 53 54 /** … … 58 59 #define DeclareGameState(className, stateName, bIgnoreTickTime, bGraphicsMode) \ 59 60 static bool BOOST_PP_CAT(bGameStateDummy_##className, __LINE__) = orxonox::Game::declareGameState<className>(#className, stateName, bIgnoreTickTime, bGraphicsMode) 60 61 // tolua_begin 61 62 namespace orxonox 62 63 { 63 class GameConfiguration; 64 // tolua_end 64 65 65 66 //! Helper object required before GameStates are being constructed … … 78 79 You should only create this singleton once because it owns the Core class! (see remark there) 79 80 */ 80 class _CoreExport Game : public Singleton<Game> 81 { 81 // tolua_begin 82 class _CoreExport Game 83 // tolua_end 84 : public Singleton<Game>, public OrxonoxClass 85 { // tolua_export 82 86 friend class Singleton<Game>; 83 87 typedef std::vector<shared_ptr<GameState> > GameStateVector; … … 89 93 ~Game(); 90 94 95 void setConfigValues(); 96 91 97 void setStateHierarchy(const std::string& str); 92 98 shared_ptr<GameState> getState(const std::string& name); … … 95 101 void stop(); 96 102 97 void requestState(const std::string& name); 98 void requestStates(const std::string& names); 99 void popState(); 103 static Game& getInstance(){ return Singleton<Game>::getInstance(); } // tolua_export 104 105 void requestState(const std::string& name); //tolua_export 106 void requestStates(const std::string& names); //tolua_export 107 void popState(); //tolua_export 100 108 101 109 const Clock& getGameClock() { return *this->gameClock_; } … … 160 168 scoped_ptr<Core> core_; 161 169 ObjScopeGuard gsFactoryDestroyer_; 162 scoped_ptr<GameConfiguration> configuration_;163 170 164 171 GameStateMap constructedStates_; … … 181 188 unsigned int minimumSleepTime_; 182 189 190 // config values 191 unsigned int statisticsRefreshCycle_; 192 unsigned int statisticsAvgLength_; 193 unsigned int fpsLimit_; 194 183 195 static std::map<std::string, GameStateInfo> gameStateDeclarations_s; 184 196 static Game* singletonPtr_s; //!< Pointer to the Singleton 185 }; 197 }; //tolua_export 186 198 187 199 template <class T> … … 209 221 return true; 210 222 } 211 } 223 } //tolua_export 212 224 213 225 #endif /* _Game_H__ */ -
code/branches/pickup2/src/libraries/core/GameMode.h
r5929 r6412 37 37 #include "CorePrereqs.h" 38 38 39 // tolua_begin 39 40 namespace orxonox 40 41 { 41 42 class _CoreExport GameMode 42 43 { 44 // tolua_end 43 45 friend class Core; 44 46 45 47 public: 48 // tolua_begin 46 49 static bool showsGraphics() { return bShowsGraphics_s; } 47 50 static bool playsSound() { return bPlaysSound_s; } … … 50 53 static bool isStandalone() { return bIsStandalone_s; } 51 54 static bool isMaster() { return bIsMaster_s; } 55 // tolua_end 52 56 53 57 static void setPlaysSound (bool val) { bPlaysSound_s = val; } … … 72 76 static bool bIsStandalone_s; 73 77 static bool bIsMaster_s; 74 }; 75 } 78 }; // tolua_export 79 } // tolua_export 76 80 77 81 #endif /* _GameMode_H__ */ -
code/branches/pickup2/src/libraries/core/GameState.cc
r5738 r6412 83 83 this->activity_.active = false; 84 84 this->activity_.deactivating = true; 85 this-> activate();85 this->deactivate(); 86 86 this->activity_.deactivating = false; 87 87 this->activity_.suspended = false; -
code/branches/pickup2/src/libraries/core/GraphicsManager.cc
r5929 r6412 98 98 // Ogre setup procedure (creating Ogre::Root) 99 99 this->loadOgreRoot(); 100 // load all the required plugins for Ogre101 this->loadOgrePlugins();102 100 103 101 // At first, add the root paths of the data directories as resource locations 104 Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem" , "dataRoot", false);102 Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem"); 105 103 // Load resources 106 resources_.reset(new XMLFile(" resources.oxr", "dataRoot"));104 resources_.reset(new XMLFile("DefaultResources.oxr")); 107 105 resources_->setLuaSupport(false); 108 106 Loader::open(resources_.get()); … … 111 109 if (PathConfig::isDevelopmentRun()) 112 110 { 113 Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem" , "externalDataRoot", false);114 extResources_.reset(new XMLFile("resources.oxr" , "externalDataRoot"));111 Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem"); 112 extResources_.reset(new XMLFile("resources.oxr")); 115 113 extResources_->setLuaSupport(false); 116 114 Loader::open(extResources_.get()); … … 171 169 if (renderWindow_ != NULL) 172 170 return; 171 172 // load all the required plugins for Ogre 173 this->loadOgrePlugins(); 173 174 174 175 this->loadRenderer(); … … 207 208 shared_array<char> data(new char[output.str().size()]); 208 209 // Debug optimisations 209 const std::string outputStr = output.str();210 const std::string& outputStr = output.str(); 210 211 char* rawData = data.get(); 211 212 for (unsigned i = 0; i < outputStr.size(); ++i) … … 237 238 COUT(3) << "Setting up Ogre..." << std::endl; 238 239 239 if (ogreConfigFile_ == "")240 if (ogreConfigFile_.empty()) 240 241 { 241 242 COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl; 242 243 ModifyConfigValue(ogreConfigFile_, tset, "config.cfg"); 243 244 } 244 if (ogreLogFile_ == "")245 if (ogreLogFile_.empty()) 245 246 { 246 247 COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl; … … 284 285 { 285 286 // just to make sure the next statement doesn't segfault 286 if (ogrePluginsDirectory_ == "")287 ogrePluginsDirectory_ = ".";287 if (ogrePluginsDirectory_.empty()) 288 ogrePluginsDirectory_ = '.'; 288 289 289 290 boost::filesystem::path folder(ogrePluginsDirectory_); … … 340 341 need the time. So we shouldn't run into problems. 341 342 */ 342 void GraphicsManager:: update(const Clock& time)343 void GraphicsManager::postUpdate(const Clock& time) 343 344 { 344 345 Ogre::FrameEvent evt; … … 394 395 { 395 396 int orxonoxLevel; 396 switch (lml) 397 { 398 case Ogre::LML_TRIVIAL: 399 orxonoxLevel = this->ogreLogLevelTrivial_; 400 break; 401 case Ogre::LML_NORMAL: 402 orxonoxLevel = this->ogreLogLevelNormal_; 403 break; 404 case Ogre::LML_CRITICAL: 405 orxonoxLevel = this->ogreLogLevelCritical_; 406 break; 407 default: 408 orxonoxLevel = 0; 409 } 410 OutputHandler::getOutStream().setOutputLevel(orxonoxLevel) 411 << "Ogre: " << message << std::endl; 397 std::string introduction; 398 // Do not show caught OGRE exceptions in front 399 if (message.find("EXCEPTION") != std::string::npos) 400 { 401 orxonoxLevel = OutputLevel::Debug; 402 introduction = "Ogre, caught exception: "; 403 } 404 else 405 { 406 switch (lml) 407 { 408 case Ogre::LML_TRIVIAL: 409 orxonoxLevel = this->ogreLogLevelTrivial_; 410 break; 411 case Ogre::LML_NORMAL: 412 orxonoxLevel = this->ogreLogLevelNormal_; 413 break; 414 case Ogre::LML_CRITICAL: 415 orxonoxLevel = this->ogreLogLevelCritical_; 416 break; 417 default: 418 orxonoxLevel = 0; 419 } 420 introduction = "Ogre: "; 421 } 422 OutputHandler::getOutStream(orxonoxLevel) 423 << introduction << message << std::endl; 412 424 } 413 425 … … 439 451 { 440 452 assert(this->renderWindow_); 441 442 this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".jpg"); 453 this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png"); 443 454 } 444 455 } -
code/branches/pickup2/src/libraries/core/GraphicsManager.h
r5929 r6412 63 63 void setConfigValues(); 64 64 65 void update(const Clock& time);65 void postUpdate(const Clock& time); 66 66 67 67 Ogre::Viewport* getViewport() { return this->viewport_; } … … 106 106 107 107 // config values 108 std::string ogreConfigFile_; //!< ogre config file 108 std::string ogreConfigFile_; //!< ogre config filename 109 109 std::string ogrePluginsDirectory_; //!< Directory where the Ogre plugins are located 110 110 std::string ogrePlugins_; //!< Comma separated list of all plugins to load 111 std::string ogreLogFile_; //!< log file 112 int ogreLogLevelTrivial_; //!< Corresponding Orxon x debug level for LL_TRIVIAL113 int ogreLogLevelNormal_; //!< Corresponding Orxon x debug level for LL_NORMAL114 int ogreLogLevelCritical_; //!< Corresponding Orxon x debug level for LL_CRITICAL111 std::string ogreLogFile_; //!< log filename for Ogre log messages 112 int ogreLogLevelTrivial_; //!< Corresponding Orxonox debug level for LL_TRIVIAL 113 int ogreLogLevelNormal_; //!< Corresponding Orxonox debug level for LL_NORMAL 114 int ogreLogLevelCritical_; //!< Corresponding Orxonox debug level for LL_CRITICAL 115 115 116 116 // console commands -
code/branches/pickup2/src/libraries/core/IOConsole.cc
r6105 r6412 32 32 #include <iomanip> 33 33 #include <iostream> 34 35 #include "util/Clock.h" 36 #include "util/Math.h" 34 37 #include "core/Game.h" 35 38 #include "core/input/InputBuffer.h" … … 42 45 IOConsole* IOConsole::singletonPtr_s = NULL; 43 46 44 int IOConsole::extractLogLevel(std::string* text)45 {46 // Handle line colouring by inspecting the first letter47 char level = 0;48 if (!text->empty())49 {50 level = (*text)[0];51 if (level == -1 || level >= 1 && level <= 6)52 {53 *text = text->substr(1);54 if (level != -1)55 return level;56 }57 }58 return 0;59 }60 61 inline bool IOConsole::willPrintStatusLines()62 {63 return !this->statusLineWidths_.empty()64 && this->terminalWidth_ >= this->statusLineMaxWidth_65 && this->terminalHeight_ >= (this->minOutputLines_ + this->statusLineWidths_.size());66 }67 68 47 // ############################### 69 48 // ### ShellListener methods ### … … 78 57 } 79 58 80 //! Called if the text in the input-line has changed81 void IOConsole::inputChanged()82 {83 this->printInputLine();84 this->cout_.flush();85 }86 87 //! Called if the position of the cursor in the input-line has changed88 void IOConsole::cursorChanged()89 {90 this->printInputLine();91 this->cout_.flush();92 }93 94 59 //! Called if a command is about to be executed 95 60 void IOConsole::executed() 96 61 { 97 this->shell_->addOutput Line(this->promptString_ + this->shell_->getInput());62 this->shell_->addOutput(this->promptString_ + this->shell_->getInput() + '\n', Shell::Command); 98 63 } 99 64 … … 126 91 127 92 IOConsole::IOConsole() 128 : shell_(new Shell("IOConsole", false , true))93 : shell_(new Shell("IOConsole", false)) 129 94 , buffer_(shell_->getInputBuffer()) 130 95 , cout_(std::cout.rdbuf()) 96 , promptString_("orxonox # ") 131 97 , bStatusPrinted_(false) 132 , promptString_("orxonox # ") 133 , originalTerminalSettings_(new termios()) 98 , originalTerminalSettings_(0) 134 99 { 135 100 this->setTerminalMode(); … … 151 116 152 117 // Make sure we make way for the status lines 153 this-> update(Game::getInstance().getGameClock());118 this->preUpdate(Game::getInstance().getGameClock()); 154 119 } 155 120 156 121 IOConsole::~IOConsole() 157 122 { 158 // Empty all buffers 159 this->update(Game::getInstance().getGameClock()); 123 // Process output written to std::cout in the meantime 124 std::cout.flush(); 125 if (!this->origCout_.str().empty()) 126 this->shell_->addOutput(this->origCout_.str(), Shell::None); 160 127 // Erase input and status lines 161 128 this->cout_ << "\033[1G\033[J"; … … 166 133 167 134 resetTerminalMode(); 168 delete this->originalTerminalSettings_;169 135 this->shell_->destroy(); 170 136 … … 175 141 } 176 142 177 void IOConsole:: update(const Clock& time)143 void IOConsole::preUpdate(const Clock& time) 178 144 { 179 145 unsigned char c; … … 284 250 } 285 251 286 // We always assume that the cursor is on the input line.252 // We always assume that the cursor is on the input line. 287 253 // But we cannot always be sure about that, esp. if we scroll the console 288 254 this->cout_ << "\033[" << this->statusLineWidths_.size() << 'B'; … … 296 262 297 263 // Process output written to std::cout 264 std::cout.flush(); 298 265 if (!this->origCout_.str().empty()) 299 266 { 300 this->shell_->addOutput Line(this->origCout_.str());267 this->shell_->addOutput(this->origCout_.str(), Shell::None); 301 268 this->origCout_.str(""); 302 269 } 303 270 } 304 271 305 void IOConsole::printLogText(const std::string& text) 306 { 307 std::string output = text; 308 /*int level =*/ this->extractLogLevel(&output); 309 272 void IOConsole::printOutputLine(const std::string& text, Shell::LineType type) 273 { 310 274 /* 311 275 // Colour line 312 switch ( level)313 { 314 case -1:this->cout_ << "\033[37m"; break;315 case 1:this->cout_ << "\033[91m"; break;316 case 2: this->cout_ << "\033[31m"; break;317 case 3:this->cout_ << "\033[34m"; break;318 case 4:this->cout_ << "\033[36m"; break;319 case 5: this->cout_ << "\033[35m"; break;320 case 6:this->cout_ << "\033[37m"; break;276 switch (type) 277 { 278 case Shell::None: this->cout_ << "\033[37m"; break; 279 case Shell::Error: this->cout_ << "\033[91m"; break; 280 case Shell::Warning: this->cout_ << "\033[31m"; break; 281 case Shell::Info: this->cout_ << "\033[34m"; break; 282 case Shell::Debug: this->cout_ << "\033[36m"; break; 283 case Shell::Verbose: this->cout_ << "\033[35m"; break; 284 case Shell::Ultra: this->cout_ << "\033[37m"; break; 321 285 default: break; 322 286 } … … 324 288 325 289 // Print output line 326 this->cout_ << output;290 this->cout_ << text; 327 291 328 292 // Reset colour to white … … 343 307 this->cout_ << "\033[u"; 344 308 if (this->buffer_->getCursorPosition() > 0) 345 this->cout_ << "\033[" << this->buffer_->getCursorPosition() << "C";309 this->cout_ << "\033[" << this->buffer_->getCursorPosition() << 'C'; 346 310 } 347 311 … … 367 331 { 368 332 termios new_settings; 333 this->originalTerminalSettings_ = new termios(); 369 334 370 335 tcgetattr(0, this->originalTerminalSettings_); … … 375 340 new_settings.c_cc[VMIN] = 0; 376 341 tcsetattr(0, TCSANOW, &new_settings); 377 } 378 379 void IOConsole::resetTerminalMode() 380 { 381 tcsetattr(0, TCSANOW, IOConsole::originalTerminalSettings_); 342 atexit(&IOConsole::resetTerminalMode); 343 } 344 345 /*static*/ void IOConsole::resetTerminalMode() 346 { 347 if(IOConsole::singletonPtr_s && IOConsole::singletonPtr_s->originalTerminalSettings_) 348 { 349 tcsetattr(0, TCSANOW, IOConsole::singletonPtr_s->originalTerminalSettings_); 350 delete IOConsole::singletonPtr_s->originalTerminalSettings_; 351 IOConsole::singletonPtr_s->originalTerminalSettings_ = 0; 352 } 382 353 } 383 354 … … 411 382 } 412 383 384 inline bool IOConsole::willPrintStatusLines() 385 { 386 return !this->statusLineWidths_.empty() 387 && this->terminalWidth_ >= this->statusLineMaxWidth_ 388 && this->terminalHeight_ >= this->minOutputLines_ + (int)this->statusLineWidths_.size(); 389 } 390 413 391 // ############################### 414 392 // ### ShellListener methods ### … … 423 401 this->cout_ << "\033[K"; 424 402 // Reprint the last output line 425 this->print LogText(*(this->shell_->getNewestLineIterator()));403 this->printOutputLine(this->shell_->getNewestLineIterator()->first, this->shell_->getNewestLineIterator()->second); 426 404 // Restore cursor 427 405 this->cout_ << "\033[u"; … … 432 410 void IOConsole::lineAdded() 433 411 { 434 int newLines = this->shell_->getNewestLineIterator()-> size() / this->terminalWidth_ + 1;412 int newLines = this->shell_->getNewestLineIterator()->first.size() / this->terminalWidth_ + 1; 435 413 // Create new lines by scrolling the screen 436 414 this->cout_ << "\033[" << newLines << 'S'; … … 441 419 // Print the new output lines 442 420 for (int i = 0; i < newLines; ++i) 443 this->printLogText(this->shell_->getNewestLineIterator()->substr(i*this->terminalWidth_, this->terminalWidth_)); 421 { 422 Shell::LineList::const_iterator it = this->shell_->getNewestLineIterator(); 423 this->printOutputLine(it->first.substr(i*this->terminalWidth_, this->terminalWidth_), it->second); 424 } 444 425 // Move cursor down 445 426 this->cout_ << "\033[1B\033[1G"; … … 449 430 this->cout_.flush(); 450 431 } 432 433 //! Called if the text in the input-line has changed 434 void IOConsole::inputChanged() 435 { 436 this->printInputLine(); 437 this->cout_.flush(); 438 } 439 440 //! Called if the position of the cursor in the input-line has changed 441 void IOConsole::cursorChanged() 442 { 443 this->printInputLine(); 444 this->cout_.flush(); 445 } 451 446 } 452 447 … … 456 451 // ################################## 457 452 453 #include <windows.h> 454 458 455 namespace orxonox 459 456 { 457 //! Redirects std::cout, creates the corresponding Shell and changes the terminal mode 460 458 IOConsole::IOConsole() 461 : shell_(new Shell("IOConsole", false , true))459 : shell_(new Shell("IOConsole", false)) 462 460 , buffer_(shell_->getInputBuffer()) 463 461 , cout_(std::cout.rdbuf()) 464 , bStatusPrinted_(false)465 462 , promptString_("orxonox # ") 466 { 463 , inputLineHeight_(1) 464 , statusLines_(1) 465 , lastOutputLineHeight_(0) 466 { 467 // Disable standard this->cout_ logging 468 OutputHandler::getInstance().disableCout(); 469 // Redirect std::cout to an ostringstream 470 // (Other part is in the initialiser list) 471 std::cout.rdbuf(this->origCout_.rdbuf()); 472 473 this->setTerminalMode(); 474 CONSOLE_SCREEN_BUFFER_INFO screenBufferInfo; 475 GetConsoleScreenBufferInfo(this->stdOutHandle_, &screenBufferInfo); 476 this->terminalWidth_ = screenBufferInfo.dwSize.X; 477 this->terminalHeight_ = screenBufferInfo.dwSize.Y; 478 // Determines where we are in respect to output already written with std::cout 479 this->inputLineRow_ = screenBufferInfo.dwCursorPosition.Y; 467 480 /* 468 this->setTerminalMode(); 481 this->lastTerminalWidth_ = this->terminalWidth_; 482 this->lastTerminalHeight_ = this->terminalHeight_; 483 */ 484 485 // Cursor already at the end of the screen buffer? 486 // (assuming the current input line height is 1) 487 if (this->inputLineRow_ >= this->terminalHeight_ - this->statusLines_) 488 SetConsoleCursorPosition(this->stdOutHandle_, makeCOORD(0, this->terminalHeight_ - this->statusLines_)); 489 490 // Prevent input line from overflowing 491 int maxInputLength = (this->terminalHeight_ - this->statusLines_) * this->terminalWidth_ - 1 - this->promptString_.size(); 492 // Consider that the echo of a command might include the command plus some other characters (assumed max 80) 493 // Also put a minimum so the config file parser is not overwhelmed with the command history 494 this->buffer_->setMaxLength(std::min(8192, (maxInputLength - 80) / 2)); 495 496 // Print input and status line and position cursor 497 this->inputChanged(); 498 this->cursorChanged(); 499 this->lastRefreshTime_ = Game::getInstance().getGameClock().getRealMicroseconds(); 500 this->preUpdate(Game::getInstance().getGameClock()); 501 469 502 this->shell_->registerListener(this); 470 471 // Manually set the widths of the individual status lines 472 this->statusLineWidths_.push_back(29); 473 this->statusLineMaxWidth_ = 29; 474 475 this->getTerminalSize(); 503 } 504 505 //! Resets std::cout redirection and restores the terminal mode 506 IOConsole::~IOConsole() 507 { 508 // Process output written to std::cout in the meantime 509 std::cout.flush(); 510 if (!this->origCout_.str().empty()) 511 this->shell_->addOutput(this->origCout_.str(), Shell::None); 512 513 this->shell_->unregisterListener(this); 514 515 // Erase input and status lines 516 COORD pos = {0, this->inputLineRow_}; 517 this->writeText(std::string((this->inputLineHeight_ + this->statusLines_) * this->terminalWidth_, ' '), pos); 518 // Move cursor to the beginning of the line 519 SetConsoleCursorPosition(stdOutHandle_, pos); 520 521 // Restore this->cout_ redirection 522 std::cout.rdbuf(this->cout_.rdbuf()); 523 // Enable standard this->cout_ logging again 524 OutputHandler::getInstance().enableCout(); 525 526 resetTerminalMode(); 527 this->shell_->destroy(); 528 } 529 530 //! Processes the pending input key strokes, refreshes the status lines and handles std::cout (redirected) 531 void IOConsole::preUpdate(const Clock& time) 532 { 533 // Process input 534 while (true) 535 { 536 DWORD count; 537 INPUT_RECORD inrec; 538 PeekConsoleInput(this->stdInHandle_, &inrec, 1, &count); 539 if (count == 0) 540 break; 541 ReadConsoleInput(this->stdInHandle_, &inrec, 1, &count); 542 if (inrec.EventType == KEY_EVENT && inrec.Event.KeyEvent.bKeyDown) 543 { 544 // Process keyboard modifiers (Ctrl, Alt and Shift) 545 DWORD modifiersIn = inrec.Event.KeyEvent.dwControlKeyState; 546 int modifiersOut = 0; 547 if ((modifiersIn & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0) 548 modifiersOut |= KeyboardModifier::Alt; 549 if ((modifiersIn & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0) 550 modifiersOut |= KeyboardModifier::Ctrl; 551 if ((modifiersIn & SHIFT_PRESSED) != 0) 552 modifiersOut |= KeyboardModifier::Shift; 553 554 // ASCII character (0 for special keys) 555 char asciiChar = inrec.Event.KeyEvent.uChar.AsciiChar; 556 557 // Process special keys and if not found, use Key::A as dummy (InputBuffer uses the ASCII text anyway) 558 switch (inrec.Event.KeyEvent.wVirtualKeyCode) 559 { 560 case VK_BACK: this->buffer_->buttonPressed(KeyEvent(KeyCode::Back, asciiChar, modifiersOut)); break; 561 case VK_TAB: this->buffer_->buttonPressed(KeyEvent(KeyCode::Tab, asciiChar, modifiersOut)); break; 562 case VK_RETURN: this->buffer_->buttonPressed(KeyEvent(KeyCode::Return, asciiChar, modifiersOut)); break; 563 case VK_PAUSE: this->buffer_->buttonPressed(KeyEvent(KeyCode::Pause, asciiChar, modifiersOut)); break; 564 case VK_ESCAPE: this->buffer_->buttonPressed(KeyEvent(KeyCode::Escape, asciiChar, modifiersOut)); break; 565 case VK_SPACE: this->buffer_->buttonPressed(KeyEvent(KeyCode::Space, asciiChar, modifiersOut)); break; 566 case VK_PRIOR: this->buffer_->buttonPressed(KeyEvent(KeyCode::PageUp, asciiChar, modifiersOut)); break; 567 case VK_NEXT: this->buffer_->buttonPressed(KeyEvent(KeyCode::PageDown, asciiChar, modifiersOut)); break; 568 case VK_END: this->buffer_->buttonPressed(KeyEvent(KeyCode::End, asciiChar, modifiersOut)); break; 569 case VK_HOME: this->buffer_->buttonPressed(KeyEvent(KeyCode::Home, asciiChar, modifiersOut)); break; 570 case VK_LEFT: this->buffer_->buttonPressed(KeyEvent(KeyCode::Left, asciiChar, modifiersOut)); break; 571 case VK_UP: this->buffer_->buttonPressed(KeyEvent(KeyCode::Up, asciiChar, modifiersOut)); break; 572 case VK_RIGHT: this->buffer_->buttonPressed(KeyEvent(KeyCode::Right, asciiChar, modifiersOut)); break; 573 case VK_DOWN: this->buffer_->buttonPressed(KeyEvent(KeyCode::Down, asciiChar, modifiersOut)); break; 574 case VK_INSERT: this->buffer_->buttonPressed(KeyEvent(KeyCode::Insert, asciiChar, modifiersOut)); break; 575 case VK_DELETE: this->buffer_->buttonPressed(KeyEvent(KeyCode::Delete, asciiChar, modifiersOut)); break; 576 default: this->buffer_->buttonPressed(KeyEvent(KeyCode::A, asciiChar, modifiersOut)); 577 } 578 } 579 } 580 581 // TODO: Respect screen buffer size changes 582 /* 583 // The user can manually adjust the screen buffer size on Windows 584 // And we don't want to screw the console because of that 476 585 this->lastTerminalWidth_ = this->terminalWidth_; 477 586 this->lastTerminalHeight_ = this->terminalHeight_; 478 479 // Disable standard this->cout_ logging 480 OutputHandler::getInstance().disableCout(); 587 this->getTerminalSize(); // Also sets this->inputLineRow_ according to the cursor position 588 // Is there still enough space below the cursor for the status line(s)? 589 if (this->inputLineRow_ >= this->terminalHeight_ - this->statusLines_) 590 this->moveCursor(0, -this->inputLineRow_ + this->terminalHeight_ - this->statusLines_ - 1); 481 591 */ 482 } 483 484 IOConsole::~IOConsole() 485 { 486 /* 487 resetTerminalMode(); 488 this->shell_->destroy(); 489 490 // Enable standard this->cout_ logging again 491 OutputHandler::getInstance().enableCout(); 492 */ 493 } 494 495 void IOConsole::update(const Clock& time) 496 { 497 /* 498 unsigned char c = 0; 499 while (std::cin.good()) 500 { 501 c = std::cin.get(); 502 if (std::cin.bad()) 503 break; 504 } 505 // Reset error flags in std::cin 506 std::cin.clear(); 507 508 // Determine terminal width and height 509 this->lastTerminalWidth_ = this->terminalWidth_; 510 this->lastTerminalHeight_ = this->terminalHeight_; 511 this->getTerminalSize(); 512 */ 513 } 514 515 void IOConsole::printLogText(const std::string& text) 516 { 517 } 518 519 void IOConsole::printInputLine() 520 { 521 } 522 592 593 // Refresh status line 5 times per second 594 if (time.getMicroseconds() > this->lastRefreshTime_ + 1000000) 595 { 596 this->printStatusLines(); 597 this->lastRefreshTime_ = time.getMicroseconds(); 598 } 599 600 // Process output written to std::cout 601 std::cout.flush(); 602 if (!this->origCout_.str().empty()) 603 { 604 this->shell_->addOutput(this->origCout_.str(), Shell::None); 605 this->origCout_.str(""); 606 } 607 } 608 609 //! Prints output text. Similar to writeText, but sets the colour according to the output level 610 void IOConsole::printOutputLine(const std::string& text, Shell::LineType type, const COORD& pos) 611 { 612 // Colour line 613 WORD colour = 0; 614 switch (type) 615 { 616 case Shell::Error: colour = FOREGROUND_INTENSITY | FOREGROUND_RED; break; 617 case Shell::Warning: colour = FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED; break; 618 case Shell::Info: 619 case Shell::Debug: 620 case Shell::Verbose: 621 case Shell::Ultra: colour = FOREGROUND_INTENSITY ; break; 622 case Shell::Command: colour = FOREGROUND_GREEN | FOREGROUND_BLUE; break; 623 case Shell::Hint: colour = FOREGROUND_GREEN | FOREGROUND_RED ; break; 624 default: colour = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE; break; 625 } 626 627 // Print output line 628 this->writeText(text, pos, colour); 629 } 630 631 //! Prints all status lines with current content 523 632 void IOConsole::printStatusLines() 524 633 { 525 /* 526 if (this->willPrintStatusLines())527 {528 this->bStatusPrinted_ = true;529 }530 else531 this->bStatusPrinted_ = false;532 */ 533 } 534 634 // Prepare text to be written 635 std::ostringstream oss; 636 oss << std::fixed << std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgFPS() << " fps, "; 637 oss << std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgTickTime() << " ms tick time"; 638 // Clear rest of the line by inserting spaces 639 oss << std::string(this->terminalWidth_ - oss.str().size(), ' '); 640 this->writeText(oss.str(), makeCOORD(0, this->inputLineRow_ + this->inputLineHeight_), FOREGROUND_GREEN); 641 } 642 643 //! Changes the console parameters for unbuffered input 535 644 void IOConsole::setTerminalMode() 536 645 { 537 } 538 646 // Set the console mode to no-echo, raw input, and no window or mouse events 647 this->stdOutHandle_ = GetStdHandle(STD_OUTPUT_HANDLE); 648 this->stdInHandle_ = GetStdHandle(STD_INPUT_HANDLE); 649 if (this->stdInHandle_ == INVALID_HANDLE_VALUE 650 || !GetConsoleMode(this->stdInHandle_, &this->originalTerminalSettings_) 651 || !SetConsoleMode(this->stdInHandle_, 0)) 652 { 653 COUT(1) << "Error: Could not set Windows console settings" << std::endl; 654 return; 655 } 656 FlushConsoleInputBuffer(this->stdInHandle_); 657 } 658 659 //! Restores the console parameters 539 660 void IOConsole::resetTerminalMode() 540 661 { 541 } 542 662 SetConsoleMode(this->stdInHandle_, this->originalTerminalSettings_); 663 } 664 665 //! Sets this->terminalWidth_ and this->terminalHeight_ 543 666 void IOConsole::getTerminalSize() 544 667 { 668 CONSOLE_SCREEN_BUFFER_INFO screenBufferInfo; 669 GetConsoleScreenBufferInfo(this->stdOutHandle_, &screenBufferInfo); 670 this->terminalWidth_ = screenBufferInfo.dwSize.X; 671 this->terminalHeight_ = screenBufferInfo.dwSize.Y; 672 } 673 674 //! Writes arbitrary text to the console with a certain colour and screen buffer position 675 void IOConsole::writeText(const std::string& text, const COORD& coord, WORD attributes) 676 { 677 DWORD count; 678 WriteConsoleOutputCharacter(stdOutHandle_, text.c_str(), text.size(), coord, &count); 679 FillConsoleOutputAttribute(stdOutHandle_, attributes, text.size(), coord, &count); 680 } 681 682 /** Scrolls the console screen buffer to create empty lines above the input line. 683 @details 684 If the input and status lines are already at the bottom of the screen buffer 685 the whole output gets scrolled up. In the other case the input and status 686 lines get scrolled down. 687 In any case the status and input lines get scrolled down as far as possible. 688 @param lines 689 Number of lines to be inserted. Behavior for negative values is undefined. 690 */ 691 void IOConsole::createNewOutputLines(int lines) 692 { 693 CHAR_INFO fillChar = {{' '}, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED}; 694 // Lines to scroll input/status down (if possible) 695 int linesDown = clamp(terminalHeight_ - inputLineRow_ - inputLineHeight_ - statusLines_, 0, lines); 696 if (linesDown > 0) 697 { 698 // Scroll input and status lines down 699 SMALL_RECT oldRect = {0, this->inputLineRow_, 700 this->terminalWidth_ - 1, this->inputLineRow_ + this->inputLineHeight_ + this->statusLines_ - 1}; 701 this->inputLineRow_ += linesDown; 702 ScrollConsoleScreenBuffer(stdOutHandle_, &oldRect, NULL, makeCOORD(0, this->inputLineRow_), &fillChar); 703 // Move cursor down to the new bottom so the user can see the status lines 704 COORD pos = {0, this->inputLineRow_ + this->inputLineHeight_ - 1 + this->statusLines_}; 705 SetConsoleCursorPosition(stdOutHandle_, pos); 706 // Get cursor back to the right position 707 this->cursorChanged(); 708 } 709 // Check how many lines we still have to scroll up the output 710 if (lines - linesDown > 0) 711 { 712 // Scroll output up 713 SMALL_RECT oldRect = {0, lines - linesDown, this->terminalWidth_ - 1, this->inputLineRow_ - 1}; 714 ScrollConsoleScreenBuffer(stdOutHandle_, &oldRect, NULL, makeCOORD(0, 0), &fillChar); 715 } 545 716 } 546 717 … … 549 720 // ############################### 550 721 722 //! Called if the text in the input line has changed 723 void IOConsole::inputChanged() 724 { 725 int newInputLineLength = this->promptString_.size() + this->shell_->getInput().size(); 726 int newInputLineHeight = 1 + newInputLineLength / this->terminalWidth_; 727 int newLines = newInputLineHeight - this->inputLineHeight_; 728 if (newLines > 0) 729 { 730 // Abuse this function to scroll the console 731 this->createNewOutputLines(newLines); 732 // Either Compensate for side effects (input/status lines scrolled down) 733 // or we have to do this anyway (output scrolled up) 734 this->inputLineRow_ -= newLines; 735 } 736 else if (newLines < 0) 737 { 738 // Scroll status lines up 739 int statusLineRow = this->inputLineRow_ + this->inputLineHeight_; 740 SMALL_RECT oldRect = {0, statusLineRow, this->terminalWidth_ - 1, statusLineRow + this->statusLines_}; 741 CHAR_INFO fillChar = {{' '}, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED}; 742 ScrollConsoleScreenBuffer(stdOutHandle_, &oldRect, NULL, makeCOORD(0, statusLineRow + newLines), &fillChar); 743 // Clear potential leftovers 744 if (-newLines - this->statusLines_ > 0) 745 { 746 COORD pos = {0, this->inputLineRow_ + newInputLineHeight + this->statusLines_}; 747 this->writeText(std::string((-newLines - this->statusLines_) * this->terminalWidth_, ' '), pos); 748 } 749 } 750 this->inputLineHeight_ = newInputLineHeight; 751 752 // Print the whole line, including spaces that erase leftovers 753 std::string inputLine = this->promptString_ + this->shell_->getInput(); 754 inputLine += std::string(this->terminalWidth_ - newInputLineLength % this->terminalWidth_, ' '); 755 this->writeText(inputLine, makeCOORD(0, this->inputLineRow_), FOREGROUND_GREEN | FOREGROUND_INTENSITY); 756 // If necessary, move cursor 757 if (newLines != 0) 758 this->cursorChanged(); 759 } 760 761 //! Called if the position of the cursor in the input-line has changed 762 void IOConsole::cursorChanged() 763 { 764 int rawCursorPos = this->promptString_.size() + this->buffer_->getCursorPosition(); 765 // Compensate for cursor further to the right than the terminal width 766 COORD pos; 767 pos.X = rawCursorPos % this->terminalWidth_; 768 pos.Y = this->inputLineRow_ + rawCursorPos / this->terminalWidth_; 769 SetConsoleCursorPosition(stdOutHandle_, pos); 770 } 771 551 772 //! Called if only the last output-line has changed 552 773 void IOConsole::onlyLastLineChanged() 553 774 { 554 } 555 556 //! Called if a new output-line was added 775 int newLineHeight = 1 + this->shell_->getNewestLineIterator()->first.size() / this->terminalWidth_; 776 // Compute the number of new lines needed 777 int newLines = newLineHeight - this->lastOutputLineHeight_; 778 this->lastOutputLineHeight_ = newLineHeight; 779 // Scroll console if necessary 780 if (newLines > 0) // newLines < 0 is assumed impossible 781 this->createNewOutputLines(newLines); 782 Shell::LineList::const_iterator it = this->shell_->getNewestLineIterator(); 783 this->printOutputLine(it->first, it->second, makeCOORD(0, this->inputLineRow_ - newLineHeight)); 784 } 785 786 //! Called if a new output line was added 557 787 void IOConsole::lineAdded() 558 788 { 789 Shell::LineList::const_iterator it = this->shell_->getNewestLineIterator(); 790 // Scroll console 791 this->lastOutputLineHeight_ = 1 + it->first.size() / this->terminalWidth_; 792 this->createNewOutputLines(this->lastOutputLineHeight_); 793 // Write the text 794 COORD pos = {0, this->inputLineRow_ - this->lastOutputLineHeight_}; 795 this->printOutputLine(it->first, it->second, pos); 559 796 } 560 797 } -
code/branches/pickup2/src/libraries/core/IOConsole.h
r6105 r6412 41 41 #ifdef ORXONOX_PLATFORM_UNIX 42 42 struct termios; 43 #elif defined(ORXONOX_PLATFORM_WINDOWS) 44 #define WIN32_LEAN_AND_MEAN 45 #ifndef NOMINMAX 46 #define NOMINMAX 47 #endif 48 #include <windows.h> 43 49 #endif 44 50 … … 53 59 ~IOConsole(); 54 60 55 void update(const Clock& time);61 void preUpdate(const Clock& time); 56 62 57 63 private: 58 64 void setTerminalMode(); 59 void resetTerminalMode();60 65 void getTerminalSize(); 61 bool willPrintStatusLines();62 int extractLogLevel(std::string* text);63 64 void printLogText(const std::string& line);65 void printInputLine();66 66 void printStatusLines(); 67 static int extractLogLevel(std::string* text); 67 68 68 69 // Methods from ShellListener … … 74 75 void executed(); 75 76 void exit(); 77 76 78 Shell* shell_; 77 79 InputBuffer* buffer_; 78 80 std::ostream cout_; 79 81 std::ostringstream origCout_; 80 unsigned int terminalWidth_; 81 unsigned int terminalHeight_; 82 unsigned int lastTerminalWidth_; 83 unsigned int lastTerminalHeight_; 82 int terminalWidth_; 83 int terminalHeight_; 84 int lastTerminalWidth_; 85 int lastTerminalHeight_; 86 const std::string promptString_; 87 88 #ifdef ORXONOX_PLATFORM_UNIX 89 bool willPrintStatusLines(); 90 void printInputLine(); 91 void printOutputLine(const std::string& line, Shell::LineType type); 92 static void resetTerminalMode(); 93 84 94 bool bPrintStatusLine_; 85 95 bool bStatusPrinted_; 86 std::vector< unsigned>statusLineWidths_;87 unsigned intstatusLineMaxWidth_;88 const std::string promptString_;89 static const unsigned minOutputLines_ = 3;96 std::vector<int> statusLineWidths_; 97 int statusLineMaxWidth_; 98 static const int minOutputLines_ = 3; 99 termios* originalTerminalSettings_; 90 100 91 #ifdef ORXONOX_PLATFORM_UNIX 92 termios* originalTerminalSettings_; 101 #elif defined(ORXONOX_PLATFORM_WINDOWS) 102 void resetTerminalMode(); 103 void moveCursor(int dx, int dy); 104 void writeText(const std::string& text, const COORD& pos, WORD attributes = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); 105 void createNewOutputLines(int lines); 106 void printOutputLine(const std::string& line, Shell::LineType type, const COORD& pos); 107 108 static inline COORD makeCOORD(int x, int y) 109 { 110 COORD val = {x, y}; 111 return val; 112 } 113 114 DWORD originalTerminalSettings_; 115 HANDLE stdInHandle_; 116 HANDLE stdOutHandle_; 117 int inputLineRow_; 118 int inputLineHeight_; 119 const int statusLines_; 120 int lastOutputLineHeight_; 121 uint64_t lastRefreshTime_; 93 122 #endif 94 123 -
code/branches/pickup2/src/libraries/core/IRC.cc
r5781 r6412 33 33 #include "util/Convert.h" 34 34 #include "util/Exception.h" 35 #include "util/StringUtils.h" 35 36 #include "ConsoleCommand.h" 36 37 #include "CoreIncludes.h" … … 103 104 void IRC::say(const std::string& message) 104 105 { 105 if (IRC::eval("irk::say $conn #orxonox {" + message + "}"))106 if (IRC::eval("irk::say $conn #orxonox {" + message + '}')) 106 107 IRC::tcl_say(Tcl::object(), Tcl::object(IRC::getInstance().nickname_), Tcl::object(message)); 107 108 } … … 109 110 void IRC::msg(const std::string& channel, const std::string& message) 110 111 { 111 if (IRC::eval("irk::say $conn " + channel + " {" + message + "}"))112 if (IRC::eval("irk::say $conn " + channel + " {" + message + '}')) 112 113 IRC::tcl_privmsg(Tcl::object(channel), Tcl::object(IRC::getInstance().nickname_), Tcl::object(message)); 113 114 } … … 131 132 void IRC::tcl_action(Tcl::object const &channel, Tcl::object const &nick, Tcl::object const &args) 132 133 { 133 COUT(0) << "IRC> * " << nick.get() << " "<< stripEnclosingBraces(args.get()) << std::endl;134 COUT(0) << "IRC> * " << nick.get() << ' ' << stripEnclosingBraces(args.get()) << std::endl; 134 135 } 135 136 -
code/branches/pickup2/src/libraries/core/Identifier.cc
r5929 r6412 410 410 if (it != this->configValues_.end()) 411 411 { 412 COUT(2) << "Warning: Overwriting config-value with name " << varname << " in class " << this->getName() << "."<< std::endl;412 COUT(2) << "Warning: Overwriting config-value with name " << varname << " in class " << this->getName() << '.' << std::endl; 413 413 delete (it->second); 414 414 } … … 458 458 if (it != this->consoleCommands_.end()) 459 459 { 460 COUT(2) << "Warning: Overwriting console-command with name " << command->getName() << " in class " << this->getName() << "."<< std::endl;460 COUT(2) << "Warning: Overwriting console-command with name " << command->getName() << " in class " << this->getName() << '.' << std::endl; 461 461 delete (it->second); 462 462 } … … 524 524 if (it != this->xmlportParamContainers_.end()) 525 525 { 526 COUT(2) << "Warning: Overwriting XMLPortParamContainer in class " << this->getName() << "."<< std::endl;526 COUT(2) << "Warning: Overwriting XMLPortParamContainer in class " << this->getName() << '.' << std::endl; 527 527 delete (it->second); 528 528 } … … 555 555 if (it != this->xmlportObjectContainers_.end()) 556 556 { 557 COUT(2) << "Warning: Overwriting XMLPortObjectContainer in class " << this->getName() << "."<< std::endl;557 COUT(2) << "Warning: Overwriting XMLPortObjectContainer in class " << this->getName() << '.' << std::endl; 558 558 delete (it->second); 559 559 } … … 573 573 { 574 574 if (it != list.begin()) 575 out << " ";575 out << ' '; 576 576 out << (*it)->getName(); 577 577 } -
code/branches/pickup2/src/libraries/core/Identifier.h
r5929 r6412 411 411 { 412 412 // Get the name of the class 413 std::stringname = typeid(T).name();413 const std::string& name = typeid(T).name(); 414 414 415 415 // create a new identifier anyway. Will be deleted in Identifier::getIdentifier if not used. -
code/branches/pickup2/src/libraries/core/Language.cc
r5929 r6412 62 62 { 63 63 // Check if the translation is more than just an empty string 64 if ( (localisation != "") && (localisation.size() > 0))64 if (!localisation.empty()) 65 65 { 66 66 this->localisedEntry_ = localisation; … … 130 130 } 131 131 132 COUT(2) << "Warning: Language entry " << label << " is duplicate in " << getFilename(this->defaultLanguage_) << "!"<< std::endl;132 COUT(2) << "Warning: Language entry " << label << " is duplicate in " << getFilename(this->defaultLanguage_) << '!' << std::endl; 133 133 return it->second; 134 134 } … … 199 199 COUT(4) << "Read default language file." << std::endl; 200 200 201 std::stringfilepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);201 const std::string& filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_); 202 202 203 203 // This creates the file if it's not existing … … 224 224 225 225 // Check if the line is empty 226 if ( (lineString != "") && (lineString.size() > 0))226 if (!lineString.empty()) 227 227 { 228 228 size_t pos = lineString.find('='); … … 246 246 void Language::readTranslatedLanguageFile() 247 247 { 248 COUT(4) << "Read translated language file (" << Core::get Language() << ")." << std::endl;249 250 std::string filepath = PathConfig::getConfigPathString() + getFilename(Core::getLanguage());248 COUT(4) << "Read translated language file (" << Core::getInstance().getLanguage() << ")." << std::endl; 249 250 const std::string& filepath = PathConfig::getConfigPathString() + getFilename(Core::getInstance().getLanguage()); 251 251 252 252 // Open the file … … 257 257 { 258 258 COUT(1) << "An error occurred in Language.cc:" << std::endl; 259 COUT(1) << "Error: Couldn't open file " << getFilename(Core::get Language()) << " to read the translated language entries!" << std::endl;260 Core:: resetLanguage();261 COUT(3) << "Info: Reset language to " << this->defaultLanguage_ << "."<< std::endl;259 COUT(1) << "Error: Couldn't open file " << getFilename(Core::getInstance().getLanguage()) << " to read the translated language entries!" << std::endl; 260 Core::getInstance().resetLanguage(); 261 COUT(3) << "Info: Reset language to " << this->defaultLanguage_ << '.' << std::endl; 262 262 return; 263 263 } … … 270 270 271 271 // Check if the line is empty 272 if ( (lineString != "") && (lineString.size() > 0))272 if (!lineString.empty()) 273 273 { 274 274 size_t pos = lineString.find('='); … … 287 287 else 288 288 { 289 COUT(2) << "Warning: Invalid language entry \"" << lineString << "\" in " << getFilename(Core::get Language()) << std::endl;289 COUT(2) << "Warning: Invalid language entry \"" << lineString << "\" in " << getFilename(Core::getInstance().getLanguage()) << std::endl; 290 290 } 291 291 } … … 302 302 COUT(4) << "Language: Write default language file." << std::endl; 303 303 304 std::stringfilepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);304 const std::string& filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_); 305 305 306 306 // Open the file … … 318 318 for (std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.begin(); it != this->languageEntries_.end(); ++it) 319 319 { 320 file << (*it).second->getLabel() << "=" << (*it).second->getDefault() << std::endl;320 file << it->second->getLabel() << '=' << it->second->getDefault() << std::endl; 321 321 } 322 322 -
code/branches/pickup2/src/libraries/core/Language.h
r5738 r6412 116 116 { 117 117 friend class Singleton<Language>; 118 friend class Core Configuration;118 friend class Core; 119 119 120 120 public: -
code/branches/pickup2/src/libraries/core/Loader.cc
r5929 r6412 80 80 for (std::vector<std::pair<const XMLFile*, ClassTreeMask> >::iterator it = Loader::files_s.begin(); it != Loader::files_s.end(); ++it) 81 81 { 82 if ( (*it).first == file)82 if (it->first == file) 83 83 { 84 84 Loader::files_s.erase(it); … … 92 92 bool success = true; 93 93 for (std::vector<std::pair<const XMLFile*, ClassTreeMask> >::iterator it = Loader::files_s.begin(); it != Loader::files_s.end(); ++it) 94 if (!Loader::load( (*it).first, (*it).second * mask))94 if (!Loader::load(it->first, it->second * mask)) 95 95 success = false; 96 96 … … 128 128 scoped_ptr<LuaState> luaState(new LuaState()); 129 129 luaState->setIncludeParser(&Loader::replaceLuaTags); 130 luaState->includeFile(file->getFilename() , file->getResourceGroup(), false);130 luaState->includeFile(file->getFilename()); 131 131 xmlInput = luaState->getOutput().str(); 132 132 } 133 133 else 134 134 { 135 shared_ptr<ResourceInfo> info = Resource::getInfo(file->getFilename() , file->getResourceGroup());135 shared_ptr<ResourceInfo> info = Resource::getInfo(file->getFilename()); 136 136 if (info == NULL) 137 137 { … … 139 139 return false; 140 140 } 141 xmlInput = Resource::open(file->getFilename() , file->getResourceGroup())->getAsString();141 xmlInput = Resource::open(file->getFilename())->getAsString(); 142 142 } 143 143 … … 165 165 rootNamespace->XMLPort(rootElement, XMLPort::LoadObject); 166 166 167 COUT(0) << "Finished loading " << file->getFilename() << "."<< std::endl;167 COUT(0) << "Finished loading " << file->getFilename() << '.' << std::endl; 168 168 169 169 COUT(4) << "Namespace-tree:" << std::endl << rootNamespace->toString(" ") << std::endl; … … 174 174 { 175 175 COUT(1) << std::endl; 176 COUT(1) << "An XML-error occurred in Loader.cc while loading " << file->getFilename() << ":"<< std::endl;176 COUT(1) << "An XML-error occurred in Loader.cc while loading " << file->getFilename() << ':' << std::endl; 177 177 COUT(1) << ex.what() << std::endl; 178 178 COUT(1) << "Loading aborted." << std::endl; … … 182 182 { 183 183 COUT(1) << std::endl; 184 COUT(1) << "A loading-error occurred in Loader.cc while loading " << file->getFilename() << ":"<< std::endl;184 COUT(1) << "A loading-error occurred in Loader.cc while loading " << file->getFilename() << ':' << std::endl; 185 185 COUT(1) << ex.what() << std::endl; 186 186 COUT(1) << "Loading aborted." << std::endl; … … 190 190 { 191 191 COUT(1) << std::endl; 192 COUT(1) << "An error occurred in Loader.cc while loading " << file->getFilename() << ":"<< std::endl;192 COUT(1) << "An error occurred in Loader.cc while loading " << file->getFilename() << ':' << std::endl; 193 193 COUT(1) << Exception::handleMessage() << std::endl; 194 194 COUT(1) << "Loading aborted." << std::endl; … … 218 218 std::string Loader::replaceLuaTags(const std::string& text) 219 219 { 220 // c hreate map with all Lua tags220 // create map with all Lua tags 221 221 std::map<size_t, bool> luaTags; 222 222 { … … 291 291 { 292 292 if (it != luaTags.end()) 293 end = ( *(it++)).first;293 end = (it++)->first; 294 294 else 295 295 end = std::string::npos; … … 300 300 { 301 301 // count ['='[ and ]'='] and replace tags with print([[ and ]]) 302 std::stringtemp = text.substr(start, end - start);302 const std::string& temp = text.substr(start, end - start); 303 303 { 304 304 size_t pos = 0; … … 345 345 } 346 346 } 347 std::string equalSigns = "";347 std::string equalSigns; 348 348 for(unsigned int i = 0; i < equalSignCounter; i++) 349 349 { 350 equalSigns += "=";350 equalSigns += '='; 351 351 } 352 output << "print([" + equalSigns + "[" + temp + "]"+ equalSigns +"])";352 output << "print([" + equalSigns + '[' + temp + ']' + equalSigns +"])"; 353 353 start = end + 5; 354 354 } -
code/branches/pickup2/src/libraries/core/LuaState.cc
r5929 r6412 86 86 } 87 87 88 shared_ptr<ResourceInfo> LuaState::getFileInfo(const std::string& filename, const std::string& resourceGroup, bool bSearchOtherPaths) 89 { 90 shared_ptr<ResourceInfo> sourceInfo; 91 if (resourceGroup != "NoResourceGroupProvided") 92 sourceInfo = Resource::getInfo(filename, resourceGroup); 93 94 // Continue search if not explicitely forbidden 95 if (bSearchOtherPaths && sourceInfo == NULL) 96 { 97 // Call might be relative to the file currently being processed 98 sourceInfo = Resource::getInfo(sourceFileInfo_->path + filename, sourceFileInfo_->group); 99 if (sourceInfo == NULL) 100 { 101 // Maybe find something in the same group but in the root path 102 sourceInfo = Resource::getInfo(filename, sourceFileInfo_->group); 103 } 104 } 88 shared_ptr<ResourceInfo> LuaState::getFileInfo(const std::string& filename) 89 { 90 // Look in the current directory first 91 shared_ptr<ResourceInfo> sourceInfo = Resource::getInfo(sourceFileInfo_->path + filename); 92 // Continue search in root directories 93 if (sourceInfo == NULL && !sourceFileInfo_->path.empty()) 94 sourceInfo = Resource::getInfo(filename); 105 95 return sourceInfo; 106 96 } 107 97 108 void LuaState::includeFile(const std::string& filename , const std::string& resourceGroup, bool bSearchOtherPaths)109 { 110 shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename , resourceGroup, bSearchOtherPaths);98 void LuaState::includeFile(const std::string& filename) 99 { 100 shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename); 111 101 if (sourceInfo != NULL) 112 this->includeString(Resource::open(sourceInfo->filename, sourceInfo->group)->getAsString(), sourceInfo); 113 else 114 COUT(2) << "LuaState: Cannot include file '" << filename << "' in resource group '" 115 << (resourceGroup == "NoResourceGroupProvided" ? sourceFileInfo_->group : resourceGroup) << "': group not found." << std::endl; 116 } 117 118 void LuaState::includeString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo) 102 this->includeString(Resource::open(sourceInfo)->getAsString(), sourceInfo); 103 else 104 COUT(2) << "LuaState: Cannot include file '" << filename << "'." << std::endl; 105 } 106 107 void LuaState::includeString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo) 119 108 { 120 109 // Parse string with provided include parser (otherwise don't preparse at all) … … 128 117 } 129 118 130 void LuaState::doFile(const std::string& filename , const std::string& resourceGroup, bool bSearchOtherPaths)131 { 132 shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename , resourceGroup, bSearchOtherPaths);119 void LuaState::doFile(const std::string& filename) 120 { 121 shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename); 133 122 if (sourceInfo != NULL) 134 this->doString(Resource::open(sourceInfo->filename, sourceInfo->group)->getAsString(), sourceInfo); 135 else 136 COUT(2) << "LuaState: Cannot do file '" << filename << "' in resource group '" 137 << (resourceGroup == "NoResourceGroupProvided" ? sourceFileInfo_->group : resourceGroup) << "': group not found." << std::endl; 138 } 139 140 void LuaState::doString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo) 141 { 142 // Save the oold source file info 123 this->doString(Resource::open(sourceInfo)->getAsString(), sourceInfo); 124 else 125 COUT(2) << "LuaState: Cannot do file '" << filename << "'." << std::endl; 126 } 127 128 void LuaState::doString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo) 129 { 130 // Save the old source file info 143 131 shared_ptr<ResourceInfo> oldSourceFileInfo = sourceFileInfo_; 144 132 // Only override if sourceFileInfo provides useful information … … 164 152 if (sourceFileInfo != NULL) 165 153 origin = " originating from " + sourceFileInfo_->filename; 166 COUT( 2) << "Error in Lua-script" << origin << ": " << lua_tostring(luaState_, -1) << std::endl;154 COUT(1) << "Error in Lua-script" << origin << ": " << lua_tostring(luaState_, -1) << std::endl; 167 155 // return value is nil 168 156 lua_pushnil(luaState_); … … 182 170 void LuaState::luaLog(unsigned int level, const std::string& message) 183 171 { 184 OutputHandler::getOutStream( ).setOutputLevel(level) << message << std::endl;185 } 186 187 bool LuaState::fileExists(const std::string& filename , const std::string& resourceGroup, bool bSearchOtherPaths)188 { 189 shared_ptr<ResourceInfo> info = this->getFileInfo(filename, resourceGroup, bSearchOtherPaths);172 OutputHandler::getOutStream(level) << message << std::endl; 173 } 174 175 bool LuaState::fileExists(const std::string& filename) 176 { 177 shared_ptr<ResourceInfo> info = this->getFileInfo(filename); 190 178 if (info == NULL) 191 179 return false; … … 263 251 } 264 252 } 253 254 255 LuaFunctor::LuaFunctor(const std::string& code, LuaState* luaState) 256 { 257 this->code_ = code; 258 this->lua_ = luaState; 259 } 260 261 void LuaFunctor::operator()(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5) 262 { 263 lua_->doString(this->code_); 264 } 265 265 } -
code/branches/pickup2/src/libraries/core/LuaState.h
r5781 r6412 40 40 41 41 #include "util/ScopeGuard.h" 42 #include "core/Functor.h" 42 43 #include "ToluaInterface.h" 43 44 44 // tolua_begin 45 namespace orxonox 46 { 45 namespace orxonox // tolua_export 46 { // tolua_export 47 class Functor; // tolua_export 48 49 //! Functor subclass that simply executes code with 0 arguments. 50 class _CoreExport LuaFunctor : public Functor 51 { 52 public: 53 LuaFunctor(const std::string& code, LuaState* luaState); 54 void operator()(const MultiType& param1 = MT_Type::Null, const MultiType& param2 = MT_Type::Null, const MultiType& param3 = MT_Type::Null, const MultiType& param4 = MT_Type::Null, const MultiType& param5 = MT_Type::Null); 55 void evaluateParam(unsigned int index, MultiType& param) const {} 56 57 private: 58 std::string code_; 59 LuaState* lua_; 60 }; 61 62 47 63 /** 48 64 @brief 49 65 Representation of an interface to lua 50 66 */ 51 class _CoreExport LuaState 52 { 53 // tolua_end 67 class _CoreExport LuaState // tolua_export 68 { // tolua_export 54 69 public: 55 70 LuaState(); 56 71 ~LuaState(); 57 72 58 void doFile(const std::string& filename , const std::string& resourceGroup = "General", bool bSearchOtherPaths = true); // tolua_export59 void doString(const std::string& code, shared_ptr<ResourceInfo>sourceFileInfo = shared_ptr<ResourceInfo>());73 void doFile(const std::string& filename); // tolua_export 74 void doString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo = shared_ptr<ResourceInfo>()); 60 75 61 void includeFile(const std::string& filename , const std::string& resourceGroup = "General", bool bSearchOtherPaths = true); // tolua_export62 void includeString(const std::string& code, shared_ptr<ResourceInfo>sourceFileInfo = shared_ptr<ResourceInfo>());76 void includeFile(const std::string& filename); // tolua_export 77 void includeString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo = shared_ptr<ResourceInfo>()); 63 78 64 79 void luaPrint(const std::string& str); // tolua_export 65 80 void luaLog(unsigned int level, const std::string& message); // tolua_export 66 bool fileExists(const std::string& filename , const std::string& resourceGroup = "General", bool bSearchOtherPaths = true); // tolua_export81 bool fileExists(const std::string& filename); // tolua_export 67 82 68 83 const std::stringstream& getOutput() const { return output_; } … … 72 87 lua_State* getInternalLuaState() { return luaState_; } 73 88 89 void setDefaultResourceInfo(const shared_ptr<ResourceInfo>& sourceFileInfo) { this->sourceFileInfo_ = sourceFileInfo; } 90 const shared_ptr<ResourceInfo>& getDefaultResourceInfo() { return this->sourceFileInfo_; } 91 92 Functor* createLuaFunctor(const std::string& code) { return new LuaFunctor(code, this); } // tolua_export 93 74 94 static bool addToluaInterface(int (*function)(lua_State*), const std::string& name); 75 95 static bool removeToluaInterface(const std::string& name); … … 78 98 79 99 private: 80 shared_ptr<ResourceInfo> getFileInfo(const std::string& filename , const std::string& resourceGroup, bool bSearchOtherPaths);100 shared_ptr<ResourceInfo> getFileInfo(const std::string& filename); 81 101 82 102 #if LUA_VERSION_NUM != 501 -
code/branches/pickup2/src/libraries/core/MemoryArchive.cc
r5940 r6412 64 64 } 65 65 66 void MemoryArchive::findFiles(const String& pattern, bool bRecursive, 66 void MemoryArchive::findFiles(const String& pattern, bool bRecursive, 67 67 bool bDirs, StringVector* simpleList, FileInfoList* detailList) 68 68 { … … 118 118 } 119 119 120 FileInfoListPtr MemoryArchive::findFileInfo(const String& pattern, 120 FileInfoListPtr MemoryArchive::findFileInfo(const String& pattern, 121 121 bool recursive, bool dirs) 122 122 { -
code/branches/pickup2/src/libraries/core/MemoryArchive.h
r5781 r6412 79 79 80 80 private: 81 void findFiles(const Ogre::String& pattern, bool bRecursive, 81 void findFiles(const Ogre::String& pattern, bool bRecursive, 82 82 bool bDirs, Ogre::StringVector* simpleList, Ogre::FileInfoList* detailList); 83 83 -
code/branches/pickup2/src/libraries/core/Namespace.cc
r5781 r6412 173 173 { 174 174 if (i > 0) 175 output += "\n";175 output += '\n'; 176 176 177 177 output += (*it)->toString(indentation); -
code/branches/pickup2/src/libraries/core/NamespaceNode.cc
r5781 r6412 43 43 { 44 44 for (std::map<std::string, NamespaceNode*>::iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ) 45 delete ( (*(it++)).second);45 delete (it++)->second; 46 46 } 47 47 … … 50 50 std::set<NamespaceNode*> nodes; 51 51 52 if ( (name.size() == 0) || (name == ""))52 if (name.empty()) 53 53 { 54 54 nodes.insert(this); … … 89 89 it = this->subnodes_.insert(this->subnodes_.begin(), std::pair<std::string, NamespaceNode*>(firstPart, new NamespaceNode(firstPart, this))); 90 90 91 if ( (*it).second->isHidden())91 if (it->second->isHidden()) 92 92 { 93 93 COUT(2) << "Warning: Subnamespace '" << firstPart << "' in namespace '" << this->name_ << "' is hidden and can't be accessed." << std::endl; … … 96 96 else 97 97 { 98 nodes = (*it).second->getNodeRelative(secondPart);98 nodes = it->second->getNodeRelative(secondPart); 99 99 } 100 100 } … … 105 105 for (std::map<std::string, NamespaceNode*>::iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ++it) 106 106 { 107 if ( (*it).first.find(firstPart) == ((*it).first.size() - firstPart.size()))107 if (it->first.find(firstPart) == (it->first.size() - firstPart.size())) 108 108 { 109 std::set<NamespaceNode*> temp2 = (*it).second->getNodeRelative(secondPart);109 std::set<NamespaceNode*> temp2 = it->second->getNodeRelative(secondPart); 110 110 nodes.insert(temp2.begin(), temp2.end()); 111 111 bFoundMatchingNamespace = true; … … 133 133 { 134 134 for (std::map<std::string, NamespaceNode*>::const_iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ++it) 135 if ( (*it).second->includes(ns))135 if (it->second->includes(ns)) 136 136 return true; 137 137 } … … 154 154 output += ", "; 155 155 156 output += (*it).second->toString();156 output += it->second->toString(); 157 157 } 158 158 159 output += ")";159 output += ')'; 160 160 } 161 161 … … 165 165 std::string NamespaceNode::toString(const std::string& indentation) const 166 166 { 167 std::string output = (indentation + this->name_ + "\n");167 std::string output = (indentation + this->name_ + '\n'); 168 168 169 169 for (std::map<std::string, NamespaceNode*>::const_iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ++it) 170 output += (*it).second->toString(indentation + " ");170 output += it->second->toString(indentation + " "); 171 171 172 172 return output; -
code/branches/pickup2/src/libraries/core/OrxonoxClass.cc
r5929 r6412 34 34 #include "OrxonoxClass.h" 35 35 36 #include <cassert> 36 37 #include "MetaObjectList.h" 37 38 #include "Identifier.h" … … 48 49 this->referenceCount_ = 0; 49 50 this->requestedDestruction_ = false; 51 // Optimisation 52 this->objectPointers_.reserve(6); 50 53 } 51 54 … … 54 57 { 55 58 // if (!this->requestedDestruction_) 56 // COUT(2) << "Warning: Destroyed object without destroy() (" << this->getIdentifier()->getName() << ")"<< std::endl;59 // COUT(2) << "Warning: Destroyed object without destroy() (" << this->getIdentifier()->getName() << ')' << std::endl; 57 60 58 61 assert(this->referenceCount_ <= 0); 59 62 60 delete this->metaList_;63 this->unregisterObject(); 61 64 62 65 // parents_ exists only if isCreatingHierarchy() of the associated Identifier returned true while creating the class 63 66 if (this->parents_) 64 67 delete this->parents_; 65 68 66 69 // reset all weak pointers pointing to this object 67 70 for (std::set<WeakPtr<OrxonoxClass>*>::iterator it = this->weakPointers_.begin(); it != this->weakPointers_.end(); ) … … 72 75 void OrxonoxClass::destroy() 73 76 { 77 assert(this); // Just in case someone tries to delete a NULL pointer 74 78 this->requestedDestruction_ = true; 75 79 if (this->referenceCount_ == 0) 76 delete this; 80 { 81 this->preDestroy(); 82 if (this->referenceCount_ == 0) 83 delete this; 84 } 85 } 86 87 void OrxonoxClass::unregisterObject() 88 { 89 if (this->metaList_) 90 delete this->metaList_; 91 this->metaList_ = 0; 77 92 } 78 93 -
code/branches/pickup2/src/libraries/core/OrxonoxClass.h
r5929 r6412 43 43 #include <vector> 44 44 45 /** 46 @def CCOUT 47 Acts almost exactly like COUT(x), but prepends "ClassName: " 48 */ 49 #define CCOUT(level) \ 50 COUT(level) << this->getIdentifier()->getName() << ": " 51 45 52 namespace orxonox 46 53 { … … 66 73 67 74 void destroy(); 75 void unregisterObject(); 68 76 69 77 /** @brief Function to collect the SetConfigValue-macro calls. */ … … 127 135 { return const_cast<OrxonoxClass*>(this)->getDerivedPointer<T>(classID); } 128 136 137 protected: 138 virtual void preDestroy() {} 139 129 140 private: 130 141 /** @brief Increments the reference counter (for smart pointers). */ … … 133 144 /** @brief Decrements the reference counter (for smart pointers). */ 134 145 inline void decrementReferenceCount() 135 { --this->referenceCount_; if (this->referenceCount_ == 0 && this->requestedDestruction_) { delete this; } } 136 146 { 147 --this->referenceCount_; 148 if (this->referenceCount_ == 0 && this->requestedDestruction_) 149 this->destroy(); 150 } 151 137 152 /** @brief Register a weak pointer which points to this object. */ 138 153 template <class T> -
code/branches/pickup2/src/libraries/core/PathConfig.cc
r5929 r6412 54 54 #include "util/Debug.h" 55 55 #include "util/Exception.h" 56 #include "CommandLine .h"56 #include "CommandLineParser.h" 57 57 58 58 // Boost 1.36 has some issues with deprecated functions that have been omitted … … 186 186 187 187 // Check for data path override by the command line 188 if (!CommandLine ::getArgument("externalDataPath")->hasDefaultValue())189 externalDataPath_ = CommandLine ::getValue("externalDataPath").getString();188 if (!CommandLineParser::getArgument("externalDataPath")->hasDefaultValue()) 189 externalDataPath_ = CommandLineParser::getValue("externalDataPath").getString(); 190 190 else 191 191 externalDataPath_ = specialConfig::externalDataDevDirectory; … … 224 224 225 225 // Option to put all the config and log files in a separate folder 226 if (!CommandLine ::getArgument("writingPathSuffix")->hasDefaultValue())227 { 228 std::string directory(CommandLine::getValue("writingPathSuffix").getString());226 if (!CommandLineParser::getArgument("writingPathSuffix")->hasDefaultValue()) 227 { 228 const std::string& directory(CommandLineParser::getValue("writingPathSuffix").getString()); 229 229 configPath_ = configPath_ / directory; 230 230 logPath_ = logPath_ / directory; … … 256 256 257 257 // We search for helper files with the following extension 258 std::stringmoduleextension = specialConfig::moduleExtension;258 const std::string& moduleextension = specialConfig::moduleExtension; 259 259 size_t moduleextensionlength = moduleextension.size(); 260 260 261 261 // Add that path to the PATH variable in case a module depends on another one 262 std::string pathVariable = getenv("PATH"); 263 putenv(const_cast<char*>(("PATH=" + pathVariable + ";" + modulePath_.string()).c_str())); 262 std::string pathVariable(getenv("PATH")); 263 putenv(const_cast<char*>(("PATH=" + pathVariable + ';' + modulePath_.string()).c_str())); 264 265 // Make sure the path exists, otherwise don't load modules 266 if (!boost::filesystem::exists(modulePath_)) 267 return modulePaths; 264 268 265 269 boost::filesystem::directory_iterator file(modulePath_); … … 269 273 while (file != end) 270 274 { 271 std::stringfilename = file->BOOST_LEAF_FUNCTION();275 const std::string& filename = file->BOOST_LEAF_FUNCTION(); 272 276 273 277 // Check if the file ends with the exension in question … … 277 281 { 278 282 // We've found a helper file 279 std::stringlibrary = filename.substr(0, filename.size() - moduleextensionlength);283 const std::string& library = filename.substr(0, filename.size() - moduleextensionlength); 280 284 modulePaths.push_back((modulePath_ / library).file_string()); 281 285 } -
code/branches/pickup2/src/libraries/core/PathConfig.h
r5929 r6412 36 36 #include "util/Singleton.h" 37 37 38 //tolua_begin 38 39 namespace orxonox 39 40 { 41 //tolua_end 40 42 /** 41 43 @brief … … 50 52 - externalData only for development builds in the build tree 51 53 */ 52 class _CoreExport PathConfig : public Singleton<PathConfig> 53 { 54 class _CoreExport PathConfig //tolua_export 55 : public Singleton<PathConfig> 56 { //tolua_export 54 57 friend class Singleton<PathConfig>; 55 58 friend class Core; … … 99 102 static std::string getExternalDataPathString(); 100 103 //! Returns the path to the config files as std::string 101 static std::string getConfigPathString(); 104 static std::string getConfigPathString(); //tolua_export 102 105 //! Returns the path to the log files as std::string 103 106 static std::string getLogPathString(); … … 132 135 bool bDevRun_; //!< True for runs in the build directory (not installed) 133 136 static PathConfig* singletonPtr_s; 134 }; 135 } 137 }; //tolua_export 138 } //tolua_export 136 139 137 140 #endif /* _PathConfig_H__ */ -
code/branches/pickup2/src/libraries/core/Resource.cc
r5781 r6412 34 34 std::string Resource::DEFAULT_GROUP(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); 35 35 36 DataStreamPtr Resource::open(const std::string& name , const std::string& group, bool bSearchGroupsIfNotFound)36 DataStreamPtr Resource::open(const std::string& name) 37 37 { 38 return Ogre::ResourceGroupManager::getSingleton().openResource(name, group, bSearchGroupsIfNotFound); 38 return Ogre::ResourceGroupManager::getSingleton().openResource(name, 39 Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true); 39 40 } 40 41 41 DataStreamListPtr Resource::openMulti(const std::string& pattern , const std::string& group)42 DataStreamListPtr Resource::openMulti(const std::string& pattern) 42 43 { 43 return Ogre::ResourceGroupManager::getSingleton().openResources(pattern, group); 44 DataStreamListPtr resources(new Ogre::DataStreamList()); 45 const Ogre::StringVector& groups = Ogre::ResourceGroupManager::getSingleton().getResourceGroups(); 46 for (Ogre::StringVector::const_iterator it = groups.begin(); it != groups.end(); ++it) 47 { 48 DataStreamListPtr temp = Ogre::ResourceGroupManager::getSingleton().openResources(pattern, *it); 49 resources->insert(resources->end(), temp->begin(), temp->end()); 50 } 51 return resources; 44 52 } 45 53 46 bool Resource::exists(const std::string& name , const std::string& group)54 bool Resource::exists(const std::string& name) 47 55 { 48 return Ogre::ResourceGroupManager::getSingleton().resourceExists(group, name); 56 try 57 { 58 Ogre::ResourceGroupManager::getSingleton().findGroupContainingResource(name); 59 return true; 60 } 61 catch (const Ogre::Exception&) 62 { 63 return false; 64 } 49 65 } 50 66 51 shared_ptr<ResourceInfo> Resource::getInfo(const std::string& name , const std::string& group)67 shared_ptr<ResourceInfo> Resource::getInfo(const std::string& name) 52 68 { 69 std::string group; 70 try 71 { 72 group = Ogre::ResourceGroupManager::getSingleton().findGroupContainingResource(name); 73 } 74 catch (const Ogre::Exception&) 75 { 76 return shared_ptr<ResourceInfo>(); 77 } 53 78 Ogre::FileInfoListPtr infos = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(group, name); 54 79 for (std::vector<Ogre::FileInfo>::const_iterator it = infos->begin(); it != infos->end(); ++it) … … 67 92 return shared_ptr<ResourceInfo>(); 68 93 } 94 95 StringVectorPtr Resource::findResourceNames(const std::string& pattern) 96 { 97 StringVectorPtr resourceNames(new Ogre::StringVector()); 98 const Ogre::StringVector& groups = Ogre::ResourceGroupManager::getSingleton().getResourceGroups(); 99 for (Ogre::StringVector::const_iterator it = groups.begin(); it != groups.end(); ++it) 100 { 101 StringVectorPtr temp = Ogre::ResourceGroupManager::getSingleton().findResourceNames(*it, pattern); 102 resourceNames->insert(resourceNames->end(), temp->begin(), temp->end()); 103 } 104 return resourceNames; 105 } 69 106 } -
code/branches/pickup2/src/libraries/core/Resource.h
r5929 r6412 34 34 #include <boost/shared_ptr.hpp> 35 35 #include <OgreDataStream.h> 36 #include <OgreStringVector.h> 36 37 37 38 namespace orxonox … … 40 41 using Ogre::DataStreamList; 41 42 using Ogre::DataStreamListPtr; 43 using Ogre::StringVector; 44 using Ogre::StringVectorPtr; 42 45 43 46 //! Stores basic information about a Resource from Ogre … … 56 59 }; 57 60 58 /** 59 @brief 60 Provides simple functions to easily access the Ogre::ResourceGroupManager 61 /** Provides simple functions to easily access the Ogre::ResourceGroupManager. 62 The wrapper functions also avoid having to deal with resource groups. 61 63 */ 62 64 class _CoreExport Resource … … 72 74 Even if resource locations are added recursively, you 73 75 must provide a fully qualified name to this method. 74 @param groupName75 The name of the resource group; this determines which76 locations are searched.77 @param searchGroupsIfNotFound78 If true, if the resource is not found in79 the group specified, other groups will be searched.80 76 @return 81 77 Shared pointer to data stream containing the data. Will be 82 78 destroyed automatically when no longer referenced. 83 79 */ 84 static DataStreamPtr open(const std::string& name, 85 const std::string& group = Resource::DEFAULT_GROUP, 86 bool bSearchGroupsIfNotFound = false); 80 static DataStreamPtr open(const std::string& name); 81 82 //! Similar to open(string, string, bool), but with a fileInfo struct 83 static DataStreamPtr open(shared_ptr<ResourceInfo> fileInfo) 84 { 85 return open(fileInfo->filename); 86 } 87 87 88 88 /** 89 89 @brief 90 90 Open all resources matching a given pattern (which can contain 91 the character '*' as a wildcard), and return a collection of 91 the character '*' as a wildcard), and return a collection of 92 92 DataStream objects on them. 93 93 @param pattern … … 95 95 added recursively, subdirectories will be searched too so this 96 96 does not need to be fully qualified. 97 @param groupName98 The resource group; this determines which locations99 are searched.100 97 @return 101 98 Shared pointer to a data stream list , will be 102 99 destroyed automatically when no longer referenced 103 100 */ 104 static DataStreamListPtr openMulti(const std::string& pattern , const std::string& group = Resource::DEFAULT_GROUP);101 static DataStreamListPtr openMulti(const std::string& pattern); 105 102 106 103 /** 107 Find out if the named file exists in a group.104 Find out if the named file exists. 108 105 @param filename 109 106 Fully qualified name of the file to test for 110 @param group111 The name of the resource group112 107 */ 113 static bool exists(const std::string& name , const std::string& group = Resource::DEFAULT_GROUP);108 static bool exists(const std::string& name); 114 109 115 110 /** 116 Get struct with information about group,path and size.111 Get struct with information about path and size. 117 112 @param filename 118 113 Fully qualified name of the file to test for 119 @param group120 The name of the resource group121 114 */ 122 static shared_ptr<ResourceInfo> getInfo(const std::string& name, const std::string& group = Resource::DEFAULT_GROUP); 115 static shared_ptr<ResourceInfo> getInfo(const std::string& name); 116 117 /** 118 Retrieves a list with all resources matching a certain pattern. 119 @param pattern 120 The pattern to look for. If resource locations have been 121 added recursively, subdirectories will be searched too so this 122 does not need to be fully qualified. 123 */ 124 static StringVectorPtr findResourceNames(const std::string& pattern); 123 125 124 126 //! Name of the default resource group (usually "General") -
code/branches/pickup2/src/libraries/core/ScopedSingletonManager.cc
r5929 r6412 47 47 getManagersByScope().insert(std::make_pair(manager->scope_, manager)); 48 48 } 49 50 /*static*/ void ScopedSingletonManager::removeManager(ScopedSingletonManager* manager)51 {52 getManagers().erase(getManagers().find(manager->className_));53 for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(manager->scope_); it != getManagersByScope().upper_bound(manager->scope_);)54 if (it->second == manager)55 getManagersByScope().erase(it++);56 else57 ++it;58 }59 49 } -
code/branches/pickup2/src/libraries/core/ScopedSingletonManager.h
r5929 r6412 39 39 40 40 #define ManageScopedSingleton(className, scope, allowedToFail) \ 41 className* className::singletonPtr_s = NULL; \ 41 42 static ClassScopedSingletonManager<className, scope, allowedToFail> className##ScopedSingletonManager(#className) 42 43 … … 52 53 virtual ~ScopedSingletonManager() { } 53 54 static void addManager(ScopedSingletonManager* manager); 54 static void removeManager(ScopedSingletonManager* manager);55 55 56 56 template<ScopeID::Value scope> 57 static void update(const Clock& time)57 static void preUpdate(const Clock& time) 58 58 { 59 59 assert(Scope<scope>::isActive()); 60 60 for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(scope); it != getManagersByScope().upper_bound(scope); ++it) 61 it->second-> update(time);61 it->second->preUpdate(time); 62 62 } 63 virtual void update(const Clock& time) = 0; 63 virtual void preUpdate(const Clock& time) = 0; 64 template<ScopeID::Value scope> 65 static void postUpdate(const Clock& time) 66 { 67 assert(Scope<scope>::isActive()); 68 for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(scope); it != getManagersByScope().upper_bound(scope); ++it) 69 it->second->postUpdate(time); 70 } 71 virtual void postUpdate(const Clock& time) = 0; 64 72 65 73 static std::map<std::string, ScopedSingletonManager*>& getManagers(); … … 86 94 ~ClassScopedSingletonManager() 87 95 { 88 //assert(singletonPtr_ == NULL); // Might get triggered in the SignalHandler89 ScopedSingletonManager::removeManager(this);90 96 } 91 97 … … 115 121 116 122 //! Called every frame by the ScopedSingletonManager 117 void update(const Clock& time) 118 { 119 assert(Scope<scope>::isActive()); 120 // assuming T inherits Singleton<T> 121 singletonPtr_->updateSingleton(time); 123 void preUpdate(const Clock& time) 124 { 125 assert(Scope<scope>::isActive()); 126 // assuming T inherits Singleton<T> 127 singletonPtr_->preUpdateSingleton(time); 128 } 129 130 //! Called every frame by the ScopedSingletonManager 131 void postUpdate(const Clock& time) 132 { 133 assert(Scope<scope>::isActive()); 134 // assuming T inherits Singleton<T> 135 singletonPtr_->postUpdateSingleton(time); 122 136 } 123 137 … … 140 154 ~ClassScopedSingletonManager() 141 155 { 142 assert(singletonPtr_ == NULL);143 ScopedSingletonManager::removeManager(this);144 156 } 145 157 … … 150 162 try 151 163 { singletonPtr_ = new T(); } 164 catch (const InitialisationAbortedException& ex) 165 { COUT(3) << ex.getDescription() << std::endl; } 152 166 catch (...) 153 167 { COUT(1) << "Singleton creation failed: " << Exception::handleMessage() << std::endl; } … … 174 188 175 189 //! Called every frame by the ScopedSingletonManager 176 void update(const Clock& time)190 void preUpdate(const Clock& time) 177 191 { 178 192 assert(Scope<scope>::isActive()); 179 193 // assuming T inherits Singleton<T> 180 194 if (singletonPtr_ != NULL) 181 singletonPtr_->updateSingleton(time); 195 singletonPtr_->preUpdateSingleton(time); 196 } 197 198 //! Called every frame by the ScopedSingletonManager 199 void postUpdate(const Clock& time) 200 { 201 assert(Scope<scope>::isActive()); 202 // assuming T inherits Singleton<T> 203 if (singletonPtr_ != NULL) 204 singletonPtr_->postUpdateSingleton(time); 182 205 } 183 206 -
code/branches/pickup2/src/libraries/core/Shell.cc
r5929 r6412 23 23 * Fabian 'x3n' Landau 24 24 * Co-authors: 25 * ...25 * Reto Grieder 26 26 * 27 27 */ … … 30 30 31 31 #include "util/OutputHandler.h" 32 #include "util/StringUtils.h" 33 #include "util/SubString.h" 32 34 #include "CommandExecutor.h" 33 35 #include "CoreIncludes.h" 34 36 #include "ConfigValueIncludes.h" 35 #include "Core.h"36 37 #include "ConsoleCommand.h" 37 38 #define SHELL_UPDATE_LISTENERS(function) \39 for (std::list<ShellListener*>::iterator it = this->listeners_.begin(); it != this->listeners_.end(); ) \40 (*(it++))->function()41 38 42 39 namespace orxonox 43 40 { 44 SetConsoleCommand(Shell, clearShell, true);45 SetConsoleCommand(Shell, history, true);46 47 41 SetConsoleCommandShortcut(OutputHandler, log); 48 42 SetConsoleCommandShortcut(OutputHandler, error); … … 51 45 SetConsoleCommandShortcut(OutputHandler, debug); 52 46 53 Shell* Shell::singletonPtr_s = 0; 54 55 Shell::Shell() 56 { 57 int level = Core::getSoftDebugLevel(OutputHandler::LD_Shell); 58 Core::setSoftDebugLevel(OutputHandler::LD_Shell, -1); 59 47 Shell::Shell(const std::string& consoleName, bool bScrollable) 48 : OutputListener(consoleName) 49 , inputBuffer_(new InputBuffer()) 50 , consoleName_(consoleName) 51 , bScrollable_(bScrollable) 52 { 60 53 RegisterRootObject(Shell); 61 54 … … 64 57 this->historyPosition_ = 0; 65 58 this->historyOffset_ = 0; 66 this->finishedLastLine_ = true; 67 this->bAddOutputLevel_ = false; 68 69 this->clearLines(); 70 71 this->inputBuffer_ = new InputBuffer(); 59 this->bFinishedLastLine_ = true; 60 61 this->clearOutput(); 72 62 this->configureInputBuffer(); 73 63 74 this->outputBuffer_.registerListener(this); 75 OutputHandler::getOutStream().setOutputBuffer(&this->outputBuffer_); 76 77 // Get a config file for the command history 78 this->commandHistoryConfigFileType_ = ConfigFileManager::getInstance().getNewConfigFileType(); 79 ConfigFileManager::getInstance().setFilename(this->commandHistoryConfigFileType_, "commandHistory.ini"); 64 // Specify file for the command history 65 ConfigFileManager::getInstance().setFilename(ConfigFileType::CommandHistory, "commandHistory.ini"); 66 67 // Use a stringstream object to buffer the output 68 this->outputStream_ = &this->outputBuffer_; 80 69 81 70 this->setConfigValues(); 82 71 83 Core::setSoftDebugLevel(OutputHandler::LD_Shell, level); 72 // Get the previous output and add it to the Shell 73 for (OutputHandler::OutputVectorIterator it = OutputHandler::getInstance().getOutputVectorBegin(); 74 it != OutputHandler::getInstance().getOutputVectorEnd(); ++it) 75 { 76 if (it->first <= this->getSoftDebugLevel()) 77 { 78 this->outputBuffer_ << it->second; 79 this->outputChanged(it->first); 80 } 81 } 82 83 // Register the shell as output listener 84 OutputHandler::getInstance().registerOutputListener(this); 84 85 } 85 86 86 87 Shell::~Shell() 87 88 { 88 OutputHandler::getOutStream().setOutputBuffer(0); 89 if (this->inputBuffer_) 90 this->inputBuffer_->destroy(); 89 OutputHandler::getInstance().unregisterOutputListener(this); 90 this->inputBuffer_->destroy(); 91 91 } 92 92 93 93 void Shell::setConfigValues() 94 94 { 95 SetConfigValue Generic(commandHistoryConfigFileType_,maxHistoryLength_, 100)95 SetConfigValue(maxHistoryLength_, 100) 96 96 .callback(this, &Shell::commandHistoryLengthChanged); 97 SetConfigValue Generic(commandHistoryConfigFileType_,historyOffset_, 0)97 SetConfigValue(historyOffset_, 0) 98 98 .callback(this, &Shell::commandHistoryOffsetChanged); 99 SetConfigValueVectorGeneric(commandHistoryConfigFileType_, commandHistory_, std::vector<std::string>()); 99 setConfigValueGeneric(this, &commandHistory_, ConfigFileType::CommandHistory, "Shell", "commandHistory_", std::vector<std::string>()); 100 101 #ifdef ORXONOX_RELEASE 102 const unsigned int defaultLevel = 1; 103 #else 104 const unsigned int defaultLevel = 3; 105 #endif 106 setConfigValueGeneric(this, &softDebugLevel_, ConfigFileType::Settings, "OutputHandler", "softDebugLevel" + this->consoleName_, defaultLevel) 107 .description("The maximal level of debug output shown in the Shell"); 108 this->setSoftDebugLevel(this->softDebugLevel_); 100 109 } 101 110 … … 121 130 { 122 131 this->inputBuffer_->registerListener(this, &Shell::inputChanged, true); 123 this->inputBuffer_->registerListener(this, &Shell::execute, '\r', false); 124 this->inputBuffer_->registerListener(this, &Shell::hintandcomplete, '\t', true); 125 this->inputBuffer_->registerListener(this, &Shell::backspace, '\b', true); 126 this->inputBuffer_->registerListener(this, &Shell::deletechar, KeyCode::Delete); 127 this->inputBuffer_->registerListener(this, &Shell::exit, static_cast<char>(27), true); 128 this->inputBuffer_->registerListener(this, &Shell::cursor_right, KeyCode::Right); 129 this->inputBuffer_->registerListener(this, &Shell::cursor_left, KeyCode::Left); 130 this->inputBuffer_->registerListener(this, &Shell::cursor_end, KeyCode::End); 131 this->inputBuffer_->registerListener(this, &Shell::cursor_home, KeyCode::Home); 132 this->inputBuffer_->registerListener(this, &Shell::history_up, KeyCode::Up); 133 this->inputBuffer_->registerListener(this, &Shell::history_down, KeyCode::Down); 134 this->inputBuffer_->registerListener(this, &Shell::scroll_up, KeyCode::PageUp); 135 this->inputBuffer_->registerListener(this, &Shell::scroll_down, KeyCode::PageDown); 136 } 137 138 void Shell::clearShell() 139 { 140 Shell::getInstance().clearLines(); 141 } 142 132 this->inputBuffer_->registerListener(this, &Shell::execute, '\r', false); 133 this->inputBuffer_->registerListener(this, &Shell::execute, '\n', false); 134 this->inputBuffer_->registerListener(this, &Shell::hintAndComplete, '\t', true); 135 this->inputBuffer_->registerListener(this, &Shell::backspace, '\b', true); 136 this->inputBuffer_->registerListener(this, &Shell::backspace, '\177', true); 137 this->inputBuffer_->registerListener(this, &Shell::exit, '\033', true); // escape 138 this->inputBuffer_->registerListener(this, &Shell::deleteChar, KeyCode::Delete); 139 this->inputBuffer_->registerListener(this, &Shell::cursorRight, KeyCode::Right); 140 this->inputBuffer_->registerListener(this, &Shell::cursorLeft, KeyCode::Left); 141 this->inputBuffer_->registerListener(this, &Shell::cursorEnd, KeyCode::End); 142 this->inputBuffer_->registerListener(this, &Shell::cursorHome, KeyCode::Home); 143 this->inputBuffer_->registerListener(this, &Shell::historyUp, KeyCode::Up); 144 this->inputBuffer_->registerListener(this, &Shell::historyDown, KeyCode::Down); 145 if (this->bScrollable_) 146 { 147 this->inputBuffer_->registerListener(this, &Shell::scrollUp, KeyCode::PageUp); 148 this->inputBuffer_->registerListener(this, &Shell::scrollDown, KeyCode::PageDown); 149 } 150 else 151 { 152 this->inputBuffer_->registerListener(this, &Shell::historySearchUp, KeyCode::PageUp); 153 this->inputBuffer_->registerListener(this, &Shell::historySearchDown, KeyCode::PageDown); 154 } 155 } 156 157 /* 143 158 void Shell::history() 144 159 { … … 146 161 147 162 for (unsigned int i = instance.historyOffset_; i < instance.commandHistory_.size(); ++i) 148 instance.add Line(instance.commandHistory_[i], -1);163 instance.addOutput(instance.commandHistory_[i] + '\n', -1); 149 164 for (unsigned int i = 0; i < instance.historyOffset_; ++i) 150 instance.addLine(instance.commandHistory_[i], -1); 151 } 165 instance.addOutput(instance.commandHistory_[i] + '\n', -1); 166 } 167 */ 152 168 153 169 void Shell::registerListener(ShellListener* listener) 154 170 { 155 this->listeners_. insert(this->listeners_.end(),listener);171 this->listeners_.push_back(listener); 156 172 } 157 173 … … 161 177 { 162 178 if ((*it) == listener) 163 this->listeners_.erase(it++);179 it = this->listeners_.erase(it); 164 180 else 165 181 ++it; … … 170 186 { 171 187 this->inputBuffer_->setCursorPosition(cursor); 172 SHELL_UPDATE_LISTENERS(cursorChanged); 173 } 174 175 void Shell::setInput(const std::string& input) 176 { 177 this->inputBuffer_->set(input); 178 this->inputChanged(); 179 } 180 181 void Shell::addLine(const std::string& line, int level) 182 { 183 int original_level = OutputHandler::getOutStream().getOutputLevel(); 184 OutputHandler::getOutStream().setOutputLevel(level); 185 186 if (!this->finishedLastLine_) 187 this->outputBuffer_ << std::endl; 188 189 this->outputBuffer_ << line << std::endl; 190 OutputHandler::getOutStream().setOutputLevel(original_level); 191 } 192 193 void Shell::clearLines() 194 { 195 this->lines_.clear(); 196 this->scrollIterator_ = this->lines_.begin(); 188 this->updateListeners<&ShellListener::cursorChanged>(); 189 } 190 191 void Shell::addOutput(const std::string& text, LineType type) 192 { 193 this->outputBuffer_ << text; 194 this->outputChanged(type); 195 } 196 197 void Shell::clearOutput() 198 { 199 this->outputLines_.clear(); 200 this->scrollIterator_ = this->outputLines_.begin(); 197 201 198 202 this->scrollPosition_ = 0; 199 this-> finishedLastLine_ = true;200 201 SHELL_UPDATE_LISTENERS(linesChanged);202 } 203 204 std::list<std::string>::const_iterator Shell::getNewestLineIterator() const203 this->bFinishedLastLine_ = true; 204 205 this->updateListeners<&ShellListener::linesChanged>(); 206 } 207 208 Shell::LineList::const_iterator Shell::getNewestLineIterator() const 205 209 { 206 210 if (this->scrollPosition_) 207 211 return this->scrollIterator_; 208 212 else 209 return this-> lines_.begin();210 } 211 212 std::list<std::string>::const_iterator Shell::getEndIterator() const213 { 214 return this-> lines_.end();213 return this->outputLines_.begin(); 214 } 215 216 Shell::LineList::const_iterator Shell::getEndIterator() const 217 { 218 return this->outputLines_.end(); 215 219 } 216 220 … … 222 226 } 223 227 224 std::stringShell::getFromHistory() const228 const std::string& Shell::getFromHistory() const 225 229 { 226 230 unsigned int index = mod(static_cast<int>(this->historyOffset_) - static_cast<int>(this->historyPosition_), this->maxHistoryLength_); … … 228 232 return this->commandHistory_[index]; 229 233 else 230 return ""; 231 } 232 233 void Shell::outputChanged() 234 { 235 std::string output; 236 bool newline; 234 return BLANKSTRING; 235 } 236 237 void Shell::outputChanged(int lineType) 238 { 239 bool newline = false; 237 240 do 238 241 { 239 newline = this->outputBuffer_.getLine(&output); 240 241 if (!newline && output == "") 242 std::string output; 243 std::getline(this->outputBuffer_, output); 244 245 bool eof = this->outputBuffer_.eof(); 246 bool fail = this->outputBuffer_.fail(); 247 if (eof) 248 this->outputBuffer_.flush(); 249 if (eof || fail) 250 this->outputBuffer_.clear(); 251 newline = (!eof && !fail); 252 253 if (!newline && output.empty()) 242 254 break; 243 255 244 if (this-> finishedLastLine_)256 if (this->bFinishedLastLine_) 245 257 { 246 if (this->bAddOutputLevel_) 247 output.insert(0, 1, static_cast<char>(OutputHandler::getOutStream().getOutputLevel())); 248 249 this->lines_.insert(this->lines_.begin(), output); 258 this->outputLines_.push_front(std::make_pair(output, static_cast<LineType>(lineType))); 250 259 251 260 if (this->scrollPosition_) 252 261 this->scrollPosition_++; 253 262 else 254 this->scrollIterator_ = this-> lines_.begin();255 256 this-> finishedLastLine_ = newline;263 this->scrollIterator_ = this->outputLines_.begin(); 264 265 this->bFinishedLastLine_ = newline; 257 266 258 267 if (!this->scrollPosition_) 259 { 260 SHELL_UPDATE_LISTENERS(lineAdded); 261 } 268 this->updateListeners<&ShellListener::lineAdded>(); 262 269 } 263 270 else 264 271 { 265 (*this->lines_.begin())+= output;266 this-> finishedLastLine_ = newline;267 SHELL_UPDATE_LISTENERS(onlyLastLineChanged);272 this->outputLines_.front().first += output; 273 this->bFinishedLastLine_ = newline; 274 this->updateListeners<&ShellListener::onlyLastLineChanged>(); 268 275 } 276 this->bFinishedLastLine_ = newline; 269 277 270 278 } while (newline); 271 279 } 272 280 273 void Shell::inputChanged() 274 { 275 SHELL_UPDATE_LISTENERS(inputChanged); 276 SHELL_UPDATE_LISTENERS(cursorChanged); 277 } 278 279 void Shell::execute() 280 { 281 this->addToHistory(this->inputBuffer_->get()); 282 this->addLine(this->inputBuffer_->get(), 0); 283 284 if (!CommandExecutor::execute(this->inputBuffer_->get())) 285 this->addLine("Error: Can't execute \"" + this->inputBuffer_->get() + "\".", 1); 286 287 this->clear(); 288 } 289 290 void Shell::hintandcomplete() 291 { 292 this->inputBuffer_->set(CommandExecutor::complete(this->inputBuffer_->get())); 293 this->addLine(CommandExecutor::hint(this->inputBuffer_->get()), -1); 294 295 this->inputChanged(); 296 } 297 298 void Shell::backspace() 299 { 300 this->inputBuffer_->removeBehindCursor(); 301 SHELL_UPDATE_LISTENERS(inputChanged); 302 SHELL_UPDATE_LISTENERS(cursorChanged); 303 } 304 305 void Shell::deletechar() 306 { 307 this->inputBuffer_->removeAtCursor(); 308 SHELL_UPDATE_LISTENERS(inputChanged); 309 } 310 311 void Shell::clear() 281 void Shell::clearInput() 312 282 { 313 283 this->inputBuffer_->clear(); 314 284 this->historyPosition_ = 0; 315 SHELL_UPDATE_LISTENERS(inputChanged); 316 SHELL_UPDATE_LISTENERS(cursorChanged); 317 } 318 319 void Shell::cursor_right() 285 this->updateListeners<&ShellListener::inputChanged>(); 286 this->updateListeners<&ShellListener::cursorChanged>(); 287 } 288 289 void Shell::setPromptPrefix(const std::string& str) 290 { 291 } 292 293 294 // ########################################## 295 // ### InputBuffer callback functions ### 296 // ########################################## 297 298 void Shell::inputChanged() 299 { 300 this->updateListeners<&ShellListener::inputChanged>(); 301 this->updateListeners<&ShellListener::cursorChanged>(); 302 } 303 304 void Shell::execute() 305 { 306 this->addToHistory(this->inputBuffer_->get()); 307 this->updateListeners<&ShellListener::executed>(); 308 309 if (!CommandExecutor::execute(this->inputBuffer_->get())) 310 { 311 this->outputBuffer_ << "Error: Can't execute \"" << this->inputBuffer_->get() << "\"." << std::endl; 312 this->outputChanged(Error); 313 } 314 315 this->clearInput(); 316 } 317 318 void Shell::hintAndComplete() 319 { 320 this->inputBuffer_->set(CommandExecutor::complete(this->inputBuffer_->get())); 321 this->outputBuffer_ << CommandExecutor::hint(this->inputBuffer_->get()) << std::endl; 322 this->outputChanged(Hint); 323 324 this->inputChanged(); 325 } 326 327 void Shell::backspace() 328 { 329 this->inputBuffer_->removeBehindCursor(); 330 this->updateListeners<&ShellListener::inputChanged>(); 331 this->updateListeners<&ShellListener::cursorChanged>(); 332 } 333 334 void Shell::exit() 335 { 336 if (this->inputBuffer_->getSize() > 0) 337 { 338 this->clearInput(); 339 return; 340 } 341 342 this->clearInput(); 343 this->scrollPosition_ = 0; 344 this->scrollIterator_ = this->outputLines_.begin(); 345 346 this->updateListeners<&ShellListener::exit>(); 347 } 348 349 void Shell::deleteChar() 350 { 351 this->inputBuffer_->removeAtCursor(); 352 this->updateListeners<&ShellListener::inputChanged>(); 353 } 354 355 void Shell::cursorRight() 320 356 { 321 357 this->inputBuffer_->increaseCursor(); 322 SHELL_UPDATE_LISTENERS(cursorChanged);323 } 324 325 void Shell::cursor _left()358 this->updateListeners<&ShellListener::cursorChanged>(); 359 } 360 361 void Shell::cursorLeft() 326 362 { 327 363 this->inputBuffer_->decreaseCursor(); 328 SHELL_UPDATE_LISTENERS(cursorChanged);329 } 330 331 void Shell::cursor _end()364 this->updateListeners<&ShellListener::cursorChanged>(); 365 } 366 367 void Shell::cursorEnd() 332 368 { 333 369 this->inputBuffer_->setCursorToEnd(); 334 SHELL_UPDATE_LISTENERS(cursorChanged);335 } 336 337 void Shell::cursor _home()370 this->updateListeners<&ShellListener::cursorChanged>(); 371 } 372 373 void Shell::cursorHome() 338 374 { 339 375 this->inputBuffer_->setCursorToBegin(); 340 SHELL_UPDATE_LISTENERS(cursorChanged);341 } 342 343 void Shell::history _up()376 this->updateListeners<&ShellListener::cursorChanged>(); 377 } 378 379 void Shell::historyUp() 344 380 { 345 381 if (this->historyPosition_ < this->commandHistory_.size()) … … 350 386 } 351 387 352 void Shell::history _down()388 void Shell::historyDown() 353 389 { 354 390 if (this->historyPosition_ > 0) … … 359 395 } 360 396 361 void Shell::scroll_up() 362 { 363 if (this->scrollIterator_ != this->lines_.end()) 397 void Shell::historySearchUp() 398 { 399 if (this->historyPosition_ == this->historyOffset_) 400 return; 401 unsigned int cursorPosition = this->getCursorPosition(); 402 const std::string& input_str(this->getInput().substr(0, cursorPosition)); // only search for the expression from the beginning of the inputline until the cursor position 403 for (unsigned int newPos = this->historyPosition_ + 1; newPos <= this->historyOffset_; newPos++) 404 { 405 if (getLowercase(this->commandHistory_[this->historyOffset_ - newPos]).find(getLowercase(input_str)) == 0) // search case insensitive 406 { 407 this->historyPosition_ = newPos; 408 this->inputBuffer_->set(this->getFromHistory()); 409 this->setCursorPosition(cursorPosition); 410 return; 411 } 412 } 413 } 414 415 void Shell::historySearchDown() 416 { 417 if (this->historyPosition_ == 0) 418 return; 419 unsigned int cursorPosition = this->getCursorPosition(); 420 const std::string& input_str(this->getInput().substr(0, cursorPosition)); // only search for the expression from the beginning 421 for (unsigned int newPos = this->historyPosition_ - 1; newPos > 0; newPos--) 422 { 423 if (getLowercase(this->commandHistory_[this->historyOffset_ - newPos]).find(getLowercase(input_str)) == 0) // sear$ 424 { 425 this->historyPosition_ = newPos; 426 this->inputBuffer_->set(this->getFromHistory()); 427 this->setCursorPosition(cursorPosition); 428 return; 429 } 430 } 431 } 432 433 void Shell::scrollUp() 434 { 435 if (this->scrollIterator_ != this->outputLines_.end()) 364 436 { 365 437 ++this->scrollIterator_; 366 438 ++this->scrollPosition_; 367 439 368 SHELL_UPDATE_LISTENERS(linesChanged);369 } 370 } 371 372 void Shell::scroll _down()373 { 374 if (this->scrollIterator_ != this-> lines_.begin())440 this->updateListeners<&ShellListener::linesChanged>(); 441 } 442 } 443 444 void Shell::scrollDown() 445 { 446 if (this->scrollIterator_ != this->outputLines_.begin()) 375 447 { 376 448 --this->scrollIterator_; 377 449 --this->scrollPosition_; 378 450 379 SHELL_UPDATE_LISTENERS(linesChanged); 380 } 381 } 382 383 void Shell::exit() 384 { 385 if (this->inputBuffer_->getSize() > 0) 386 { 387 this->clear(); 388 return; 389 } 390 391 this->clear(); 392 this->scrollPosition_ = 0; 393 this->scrollIterator_ = this->lines_.begin(); 394 395 SHELL_UPDATE_LISTENERS(exit); 451 this->updateListeners<&ShellListener::linesChanged>(); 452 } 396 453 } 397 454 } -
code/branches/pickup2/src/libraries/core/Shell.h
r5781 r6412 23 23 * Fabian 'x3n' Landau 24 24 * Co-authors: 25 * ...25 * Reto Grieder 26 26 * 27 27 */ … … 32 32 #include "CorePrereqs.h" 33 33 34 #include <cassert>35 34 #include <list> 35 #include <sstream> 36 36 #include <string> 37 37 #include <vector> 38 38 39 #include "util/OutputBuffer.h" 40 #include "input/InputBuffer.h" 39 #include "util/OutputHandler.h" 41 40 #include "OrxonoxClass.h" 42 41 #include "ConfigFileManager.h" 42 #include "input/InputBuffer.h" 43 43 44 44 namespace orxonox … … 57 57 virtual void inputChanged() {} 58 58 virtual void cursorChanged() {} 59 virtual void executed() {} 59 60 virtual void exit() {} 60 61 }; 61 62 62 class _CoreExport Shell : public Singleton<Shell>, virtual public OrxonoxClass, public OutputBufferListener 63 64 class _CoreExport Shell : virtual public OrxonoxClass, public OutputListener 63 65 { 64 friend class Singleton<Shell>;65 66 public: 66 Shell(); 67 virtual ~Shell(); 67 enum LineType 68 { 69 None = OutputLevel::None, 70 Warning = OutputLevel::Warning, 71 Error = OutputLevel::Error, 72 Info = OutputLevel::Info, 73 Debug = OutputLevel::Debug, 74 Verbose = OutputLevel::Verbose, 75 Ultra = OutputLevel::Ultra, 76 Input, 77 Command, 78 Hint 79 }; 68 80 69 static void clearShell();70 static void history();81 Shell(const std::string& consoleName, bool bScrollable); 82 ~Shell(); 71 83 72 v irtual void setConfigValues();84 void setConfigValues(); 73 85 void commandHistoryOffsetChanged(); 74 86 void commandHistoryLengthChanged(); … … 79 91 inline InputBuffer* getInputBuffer() 80 92 { return this->inputBuffer_; } 81 inline OutputBuffer& getOutputBuffer()82 { return this->outputBuffer_; }83 93 84 94 void setCursorPosition(unsigned int cursor); … … 86 96 { return this->inputBuffer_->getCursorPosition(); } 87 97 88 void setInput(const std::string& input); 89 90 inline void clearInput() 91 { this->setInput(""); } 92 inline std::string getInput() const 98 inline const std::string& getInput() const 93 99 { return this->inputBuffer_->get(); } 94 100 95 std::list<std::string>::const_iterator getNewestLineIterator() const; 96 std::list<std::string>::const_iterator getEndIterator() const; 101 typedef std::list<std::pair<std::string, LineType> > LineList; 102 LineList::const_iterator getNewestLineIterator() const; 103 LineList::const_iterator getEndIterator() const; 97 104 98 void add Line(const std::string& line, int level = 0);99 void clear Lines();105 void addOutput(const std::string& text, LineType type = None); 106 void clearOutput(); 100 107 101 108 inline unsigned int getNumLines() const 102 { return this-> lines_.size(); }109 { return this->outputLines_.size(); } 103 110 inline unsigned int getScrollPosition() const 104 111 { return this->scrollPosition_; } 105 112 106 inline void addOutputLevel(bool bAddOutputLevel)107 { this->bAddOutputLevel_ = bAddOutputLevel; }113 inline const std::string& getPromptPrefix() const { return this->promptPrefix_; } 114 void setPromptPrefix(const std::string& str); 108 115 109 116 private: 110 117 Shell(const Shell& other); 111 118 119 void addToHistory(const std::string& command); 120 const std::string& getFromHistory() const; 121 void clearInput(); 122 // OutputListener 123 void outputChanged(int level); 124 112 125 void configureInputBuffer(); 113 126 114 void addToHistory(const std::string& command); 115 std::string getFromHistory() const; 116 117 virtual void outputChanged(); 127 // InputBuffer callbacks 118 128 void inputChanged(); 119 129 void execute(); 120 void hint andcomplete();130 void hintAndComplete(); 121 131 void backspace(); 122 void deletechar(); 123 void clear(); 124 void cursor_right(); 125 void cursor_left(); 126 void cursor_end(); 127 void cursor_home(); 128 void history_up(); 129 void history_down(); 130 void scroll_up(); 131 void scroll_down(); 132 void deleteChar(); 133 void cursorRight(); 134 void cursorLeft(); 135 void cursorEnd(); 136 void cursorHome(); 137 void historyUp(); 138 void historyDown(); 139 void historySearchUp(); 140 void historySearchDown(); 141 void scrollUp(); 142 void scrollDown(); 132 143 void exit(); 133 144 145 template <void (ShellListener::*F)()> 146 void updateListeners() 147 { 148 for (std::list<ShellListener*>::const_iterator it = this->listeners_.begin(); it != this->listeners_.end(); ) 149 ((*(it++))->*F)(); 150 } 151 134 152 std::list<ShellListener*> listeners_; 135 InputBuffer* inputBuffer_; 136 OutputBuffer outputBuffer_; 137 bool finishedLastLine_; 138 std::list<std::string> lines_; 139 std::list<std::string>::const_iterator scrollIterator_; 140 unsigned int scrollPosition_; 141 std::vector<std::string> commandHistory_; 142 unsigned int maxHistoryLength_; 143 unsigned int historyPosition_; 144 unsigned int historyOffset_; 145 bool bAddOutputLevel_; 153 InputBuffer* inputBuffer_; 154 std::stringstream outputBuffer_; 155 bool bFinishedLastLine_; 156 LineList outputLines_; 157 LineList::const_iterator scrollIterator_; 158 unsigned int scrollPosition_; 159 unsigned int historyPosition_; 146 160 147 ConfigFileType commandHistoryConfigFileType_; 161 std::string promptPrefix_; 162 const std::string consoleName_; 163 const bool bScrollable_; 148 164 149 static Shell* singletonPtr_s; 165 // Config values 166 unsigned int maxHistoryLength_; 167 unsigned int historyOffset_; 168 std::vector<std::string> commandHistory_; 169 int softDebugLevel_; 150 170 }; 151 171 } -
code/branches/pickup2/src/libraries/core/SmartPtr.h
r5929 r6412 84 84 this->base_->decrementReferenceCount(); 85 85 } 86 86 87 87 inline const SmartPtr& operator=(int) 88 88 { -
code/branches/pickup2/src/libraries/core/SubclassIdentifier.h
r5929 r6412 98 98 if (identifier) 99 99 { 100 COUT(1) << "Error: Class " << identifier->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!"<< std::endl;100 COUT(1) << "Error: Class " << identifier->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << '!' << std::endl; 101 101 COUT(1) << "Error: SubclassIdentifier<" << ClassIdentifier<T>::getIdentifier()->getName() << "> = Class(" << identifier->getName() << ") is forbidden." << std::endl; 102 102 } … … 166 166 { 167 167 COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl; 168 COUT(1) << "Error: Class " << this->identifier_->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!"<< std::endl;168 COUT(1) << "Error: Class " << this->identifier_->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << '!' << std::endl; 169 169 COUT(1) << "Error: Couldn't fabricate a new Object." << std::endl; 170 170 } -
code/branches/pickup2/src/libraries/core/TclBind.cc
r5929 r6412 101 101 { 102 102 Tcl::interpreter* interpreter = new Tcl::interpreter(); 103 std::stringlibpath = TclBind::getTclLibraryPath();103 const std::string& libpath = TclBind::getTclLibraryPath(); 104 104 105 105 try 106 106 { 107 if ( libpath != "")108 interpreter->eval("set tcl_library \"" + libpath + "\"");107 if (!libpath.empty()) 108 interpreter->eval("set tcl_library \"" + libpath + '"'); 109 109 110 110 Tcl_Init(interpreter->get()); … … 136 136 COUT(4) << "Tcl_query: " << args.get() << std::endl; 137 137 138 std::stringcommand = stripEnclosingBraces(args.get());138 const std::string& command = stripEnclosingBraces(args.get()); 139 139 140 140 if (!CommandExecutor::execute(command, false)) … … 152 152 { 153 153 COUT(4) << "Tcl_execute: " << args.get() << std::endl; 154 std::stringcommand = stripEnclosingBraces(args.get());154 const std::string& command = stripEnclosingBraces(args.get()); 155 155 156 156 if (!CommandExecutor::execute(command, false)) … … 166 166 try 167 167 { 168 std::stringoutput = TclBind::getInstance().interpreter_->eval("uplevel #0 " + tclcode);169 if ( output != "")168 const std::string& output = TclBind::getInstance().interpreter_->eval("uplevel #0 " + tclcode); 169 if (!output.empty()) 170 170 { 171 171 COUT(0) << "tcl> " << output << std::endl; … … 182 182 } 183 183 184 void TclBind::bgerror( std::stringerror)184 void TclBind::bgerror(const std::string& error) 185 185 { 186 186 COUT(1) << "Tcl background error: " << stripEnclosingBraces(error) << std::endl; -
code/branches/pickup2/src/libraries/core/TclBind.h
r5781 r6412 46 46 47 47 static std::string tcl(const std::string& tclcode); 48 static void bgerror( std::stringerror);48 static void bgerror(const std::string& error); 49 49 50 50 void setDataPath(const std::string& datapath); -
code/branches/pickup2/src/libraries/core/TclThreadManager.cc
r5929 r6412 39 39 #include "util/Convert.h" 40 40 #include "util/Exception.h" 41 #include "util/StringUtils.h" 41 42 #include "CommandExecutor.h" 42 43 #include "ConsoleCommand.h" … … 122 123 @brief The "main loop" of the TclThreadManager. Creates new threads if needed and handles queries and queued commands for the main interpreter. 123 124 */ 124 void TclThreadManager:: update(const Clock& time)125 void TclThreadManager::preUpdate(const Clock& time) 125 126 { 126 127 // Get the bundle of the main interpreter (0) … … 252 253 void TclThreadManager::initialize(TclInterpreterBundle* bundle) 253 254 { 254 std::stringid_string = getConvertedValue<unsigned int, std::string>(bundle->id_);255 const std::string& id_string = getConvertedValue<unsigned int, std::string>(bundle->id_); 255 256 256 257 // Initialize the new interpreter … … 403 404 { 404 405 // This query would lead to a deadlock - return with an error 405 TclThreadManager::error("Error: Circular query (" + this->dumpList(source_bundle->queriers_.getList()) + " "+ getConvertedValue<unsigned int, std::string>(source_bundle->id_) \406 TclThreadManager::error("Error: Circular query (" + this->dumpList(source_bundle->queriers_.getList()) + ' ' + getConvertedValue<unsigned int, std::string>(source_bundle->id_) \ 406 407 + " -> " + getConvertedValue<unsigned int, std::string>(target_bundle->id_) \ 407 408 + "), couldn't query Tcl-interpreter with ID " + getConvertedValue<unsigned int, std::string>(target_bundle->id_) \ 408 + " from other interpreter with ID " + getConvertedValue<unsigned int, std::string>(source_bundle->id_) + ".");409 + " from other interpreter with ID " + getConvertedValue<unsigned int, std::string>(source_bundle->id_) + '.'); 409 410 } 410 411 else … … 524 525 std::string TclThreadManager::dumpList(const std::list<unsigned int>& list) 525 526 { 526 std::string output = "";527 std::string output; 527 528 for (std::list<unsigned int>::const_iterator it = list.begin(); it != list.end(); ++it) 528 529 { 529 530 if (it != list.begin()) 530 output += " ";531 output += ' '; 531 532 532 533 output += getConvertedValue<unsigned int, std::string>(*it); … … 600 601 @param command the Command to execute 601 602 */ 602 void tclThread(TclInterpreterBundle* bundle, std::stringcommand)603 void tclThread(TclInterpreterBundle* bundle, const std::string& command) 603 604 { 604 605 TclThreadManager::debug("TclThread_execute: " + command); … … 613 614 @param file The name of the file that should be executed by the non-interactive interpreter. 614 615 */ 615 void sourceThread( std::stringfile)616 void sourceThread(const std::string& file) 616 617 { 617 618 TclThreadManager::debug("TclThread_source: " + file); … … 651 652 652 653 // Initialize the non-interactive interpreter (like in @ref TclBind::createTclInterpreter but exception safe) 653 std::stringlibpath = TclBind::getTclLibraryPath();654 if ( libpath != "")655 TclThreadManager::eval(bundle, "set tcl_library \"" + libpath + "\"", "source");654 const std::string& libpath = TclBind::getTclLibraryPath(); 655 if (!libpath.empty()) 656 TclThreadManager::eval(bundle, "set tcl_library \"" + libpath + '"', "source"); 656 657 int cc = Tcl_Init(interp); 657 658 TclThreadManager::eval(bundle, "source \"" + TclBind::getInstance().getTclDataPath() + "/init.tcl\"", "source"); -
code/branches/pickup2/src/libraries/core/TclThreadManager.h
r5781 r6412 48 48 friend class Singleton<TclThreadManager>; 49 49 friend class TclBind; 50 friend _CoreExport void tclThread(TclInterpreterBundle* bundle, std::stringcommand);51 friend _CoreExport void sourceThread( std::stringfile);50 friend _CoreExport void tclThread(TclInterpreterBundle* bundle, const std::string& command); 51 friend _CoreExport void sourceThread(const std::string& file); 52 52 friend _CoreExport int Tcl_OrxonoxAppInit(Tcl_Interp* interp); 53 53 … … 66 66 static void debug(const std::string& error); 67 67 68 void update(const Clock& time);68 void preUpdate(const Clock& time); 69 69 70 70 std::list<unsigned int> getThreadList() const; … … 95 95 }; 96 96 97 _CoreExport void tclThread(TclInterpreterBundle* bundle, std::stringcommand);98 _CoreExport void sourceThread( std::stringfile);97 _CoreExport void tclThread(TclInterpreterBundle* bundle, const std::string& command); 98 _CoreExport void sourceThread(const std::string& file); 99 99 _CoreExport int Tcl_OrxonoxAppInit(Tcl_Interp* interp); 100 100 } -
code/branches/pickup2/src/libraries/core/Template.cc
r5781 r6412 79 79 SUPER(Template, changedName); 80 80 81 if ( this->getName() != "")81 if (!this->getName().empty()) 82 82 { 83 83 std::map<std::string, Template*>::iterator it; -
code/branches/pickup2/src/libraries/core/Template.h
r5781 r6412 48 48 49 49 inline void setLink(const std::string& link) 50 { this->link_ = link; this->bIsLink_ = (link != ""); }50 { this->link_ = link; this->bIsLink_ = !link.empty(); } 51 51 inline const std::string& getLink() const 52 52 { return this->link_; } -
code/branches/pickup2/src/libraries/core/Thread.cc
r5738 r6412 41 41 { 42 42 boost::posix_time::millisec THREAD_WAIT_BEFORE_DETACH(1000); 43 44 43 44 45 45 Thread::Thread(): 46 46 executor_(0), … … 53 53 this->workerThread_ = new boost::thread( boost::bind(&Thread::threadLoop, this) ); 54 54 } 55 55 56 56 Thread::~Thread() 57 57 { … … 66 66 delete this->isWorkingMutex_; 67 67 } 68 68 69 69 bool Thread::isWorking() 70 70 { … … 74 74 return isWorking; 75 75 } 76 76 77 77 bool Thread::evaluateExecutor( Executor* executor ) 78 78 { … … 85 85 return true; 86 86 } 87 87 88 88 void Thread::threadLoop() 89 89 { … … 114 114 } 115 115 } 116 116 117 117 void Thread::waitUntilFinished() 118 118 { -
code/branches/pickup2/src/libraries/core/Thread.h
r5738 r6412 50 50 private: 51 51 void threadLoop(); 52 52 53 53 Executor* executor_; 54 54 bool isWorking_; -
code/branches/pickup2/src/libraries/core/ThreadPool.cc
r5738 r6412 37 37 { 38 38 } 39 39 40 40 ThreadPool::~ThreadPool() 41 41 { … … 43 43 assert(a == 0); 44 44 } 45 45 46 46 void ThreadPool::addThreads( unsigned int nr ) 47 47 { … … 80 80 } 81 81 } 82 82 83 83 bool ThreadPool::passFunction( Executor* executor, bool addThread ) 84 84 { … … 103 103 return false; 104 104 } 105 105 106 106 void ThreadPool::synchronise() 107 107 { -
code/branches/pickup2/src/libraries/core/ThreadPool.h
r5738 r6412 41 41 ThreadPool(); 42 42 virtual ~ThreadPool(); 43 43 44 44 void addThreads( unsigned int nr ); 45 45 unsigned int removeThreads( unsigned int nr ); 46 46 unsigned int setNrOfThreads( unsigned int nr ); 47 47 48 48 bool passFunction( Executor* executor, bool addThread=false ); 49 49 void synchronise(); 50 50 51 51 private: 52 52 std::vector<Thread*> threadPool_; 53 53 54 54 }; 55 55 } -
code/branches/pickup2/src/libraries/core/WeakPtr.h
r5929 r6412 44 44 { 45 45 friend class OrxonoxClass; 46 46 47 47 public: 48 48 inline WeakPtr() : pointer_(0), base_(0), callback_(0) … … 79 79 if (this->callback_) 80 80 delete this->callback_; 81 82 } 83 81 82 } 83 84 84 inline const WeakPtr& operator=(int) 85 85 { … … 145 145 if (other.base_) 146 146 other.base_->unregisterWeakPtr(&other); 147 147 148 148 { 149 149 T* temp = this->pointer_; … … 167 167 WeakPtr().swap(*this); 168 168 } 169 169 170 170 inline void setCallback(Functor* callback) 171 171 { 172 172 this->callback_ = callback; 173 173 } 174 174 175 175 inline Functor* getFunctor() const 176 176 { … … 186 186 (*this->callback_)(); 187 187 } 188 188 189 189 T* pointer_; 190 190 OrxonoxClass* base_; -
code/branches/pickup2/src/libraries/core/XMLFile.h
r5781 r6412 40 40 { 41 41 public: 42 XMLFile(const std::string& filename , const std::string& resourceGroup = "General")42 XMLFile(const std::string& filename) 43 43 : filename_(filename) 44 , group_(resourceGroup)45 44 , bLuaSupport_(true) 46 45 { } 47 XMLFile(const ClassTreeMask& mask, const std::string& filename , const std::string& resourceGroup = "General")46 XMLFile(const ClassTreeMask& mask, const std::string& filename) 48 47 : filename_(filename) 49 , group_(resourceGroup)50 48 , mask_(mask) 51 49 , bLuaSupport_(true) … … 55 53 56 54 const std::string& getFilename() const { return this->filename_; } 57 const std::string& getResourceGroup() const { return this->group_; }58 55 const ClassTreeMask& getMask() const { return this->mask_; } 59 56 bool getLuaSupport() const { return this->bLuaSupport_; } … … 61 58 private: 62 59 std::string filename_; 63 std::string group_;64 60 ClassTreeMask mask_; 65 61 bool bLuaSupport_; // Default is true -
code/branches/pickup2/src/libraries/core/XMLPort.h
r5929 r6412 51 51 #include "util/MultiType.h" 52 52 #include "util/OrxAssert.h" 53 #include "util/StringUtils.h" 53 54 #include "Identifier.h" 54 55 #include "Executor.h" … … 184 185 ClassIdentifier<classname>::getIdentifier()->addXMLPortParamContainer(paramname, containername); \ 185 186 } \ 186 containername->port( static_cast<BaseObject*>(this), object, xmlelement, mode)187 containername->port(dynamic_cast<BaseObject*>(this), object, xmlelement, mode) 187 188 188 189 // -------------------- … … 316 317 { return this->paramname_; } 317 318 318 virtual XMLPortParamContainer& description(const std::string description) = 0;319 virtual XMLPortParamContainer& description(const std::string& description) = 0; 319 320 virtual const std::string& getDescription() = 0; 320 321 … … 344 345 345 346 public: 346 XMLPortClassParamContainer(const std::string paramname, Identifier* identifier, ExecutorMember<T>* loadexecutor, ExecutorMember<T>* saveexecutor)347 XMLPortClassParamContainer(const std::string& paramname, Identifier* identifier, ExecutorMember<T>* loadexecutor, ExecutorMember<T>* saveexecutor) 347 348 { 348 349 this->paramname_ = paramname; … … 385 386 } 386 387 std::map<std::string, std::string>::const_iterator it = this->owner_->xmlAttributes_.find(getLowercase(this->paramname_)); 387 std::string attributeValue ("");388 std::string attributeValue; 388 389 if (it != this->owner_->xmlAttributes_.end()) 389 390 attributeValue = it->second; … … 407 408 { 408 409 COUT(1) << std::endl; 409 COUT(1) << "An error occurred in XMLPort.h while loading attribute '" << this->paramname_ << "' of '" << this->identifier_->getName() << "' (objectname: " << this->owner_->getName() << ") in " << this->owner_->getFilename() << ":"<< std::endl;410 COUT(1) << "An error occurred in XMLPort.h while loading attribute '" << this->paramname_ << "' of '" << this->identifier_->getName() << "' (objectname: " << this->owner_->getName() << ") in " << this->owner_->getFilename() << ':' << std::endl; 410 411 COUT(1) << ex.what() << std::endl; 411 412 } … … 435 436 } 436 437 437 virtual XMLPortParamContainer& description(const std::string description)438 virtual XMLPortParamContainer& description(const std::string& description) 438 439 { this->loadexecutor_->setDescription(description); return (*this); } 439 440 virtual const std::string& getDescription() … … 497 498 { return this->sectionname_; } 498 499 499 virtual XMLPortObjectContainer& description(const std::string description) = 0;500 virtual XMLPortObjectContainer& description(const std::string& description) = 0; 500 501 virtual const std::string& getDescription() = 0; 501 502 … … 513 514 { 514 515 public: 515 XMLPortClassObjectContainer(const std::string sectionname, Identifier* identifier, ExecutorMember<T>* loadexecutor, ExecutorMember<T>* saveexecutor, bool bApplyLoaderMask, bool bLoadBefore)516 XMLPortClassObjectContainer(const std::string& sectionname, Identifier* identifier, ExecutorMember<T>* loadexecutor, ExecutorMember<T>* saveexecutor, bool bApplyLoaderMask, bool bLoadBefore) 516 517 { 517 518 this->sectionname_ = sectionname; … … 538 539 { 539 540 Element* xmlsubelement; 540 if ( (this->sectionname_ != "") && (this->sectionname_.size() > 0))541 if (!this->sectionname_.empty()) 541 542 xmlsubelement = xmlelement.FirstChildElement(this->sectionname_, false); 542 543 else … … 570 571 { 571 572 newObject->XMLPort(*child, XMLPort::LoadObject); 572 COUT(4) << object->getLoaderIndentation() << "assigning " << child->Value() << " (objectname " << newObject->getName() << ") to " << this->identifier_->getName() << " (objectname " << static_cast<BaseObject*>(object)->getName() << ")"<< std::endl;573 COUT(4) << object->getLoaderIndentation() << "assigning " << child->Value() << " (objectname " << newObject->getName() << ") to " << this->identifier_->getName() << " (objectname " << static_cast<BaseObject*>(object)->getName() << ')' << std::endl; 573 574 } 574 575 else 575 576 { 576 COUT(4) << object->getLoaderIndentation() << "assigning " << child->Value() << " (object not yet loaded) to " << this->identifier_->getName() << " (objectname " << static_cast<BaseObject*>(object)->getName() << ")"<< std::endl;577 COUT(4) << object->getLoaderIndentation() << "assigning " << child->Value() << " (object not yet loaded) to " << this->identifier_->getName() << " (objectname " << static_cast<BaseObject*>(object)->getName() << ')' << std::endl; 577 578 } 578 579 … … 609 610 else 610 611 { 611 if ( this->sectionname_ != "")612 if (!this->sectionname_.empty()) 612 613 { 613 614 COUT(2) << object->getLoaderIndentation() << "Warning: '" << child->Value() << "' is not a valid classname." << std::endl; … … 624 625 { 625 626 COUT(1) << std::endl; 626 COUT(1) << "An error occurred in XMLPort.h while loading a '" << ClassIdentifier<O>::getIdentifier()->getName() << "' in '" << this->sectionname_ << "' of '" << this->identifier_->getName() << "' (objectname: " << object->getName() << ") in " << object->getFilename() << ":"<< std::endl;627 COUT(1) << "An error occurred in XMLPort.h while loading a '" << ClassIdentifier<O>::getIdentifier()->getName() << "' in '" << this->sectionname_ << "' of '" << this->identifier_->getName() << "' (objectname: " << object->getName() << ") in " << object->getFilename() << ':' << std::endl; 627 628 COUT(1) << ex.what() << std::endl; 628 629 } … … 635 636 } 636 637 637 virtual XMLPortObjectContainer& description(const std::string description)638 virtual XMLPortObjectContainer& description(const std::string& description) 638 639 { this->loadexecutor_->setDescription(description); return (*this); } 639 640 virtual const std::string& getDescription() -
code/branches/pickup2/src/libraries/core/input/Button.cc
r5929 r6412 116 116 for (unsigned int iCommand = 0; iCommand < commandStrings.size(); iCommand++) 117 117 { 118 if ( commandStrings[iCommand] != "")118 if (!commandStrings[iCommand].empty()) 119 119 { 120 120 SubString tokens(commandStrings[iCommand], " ", SubString::WhiteSpaces, false, … … 123 123 KeybindMode::Value mode = KeybindMode::None; 124 124 float paramModifier = 1.0f; 125 std::string commandStr = "";125 std::string commandStr; 126 126 127 127 for (unsigned int iToken = 0; iToken < tokens.size(); ++iToken) 128 128 { 129 std::stringtoken = getLowercase(tokens[iToken]);129 const std::string& token = getLowercase(tokens[iToken]); 130 130 131 131 if (token == "onpress") … … 159 159 // we interpret everything from here as a command string 160 160 while (iToken != tokens.size()) 161 commandStr += tokens[iToken++] + " ";162 } 163 } 164 165 if (commandStr == "")161 commandStr += tokens[iToken++] + ' '; 162 } 163 } 164 165 if (commandStr.empty()) 166 166 { 167 167 parseError("No command string given.", false); … … 242 242 } 243 243 244 inline void Button::parseError( std::stringmessage, bool serious)244 inline void Button::parseError(const std::string& message, bool serious) 245 245 { 246 246 if (serious) -
code/branches/pickup2/src/libraries/core/input/Button.h
r5781 r6412 76 76 77 77 private: 78 void parseError( std::stringmessage, bool serious);78 void parseError(const std::string& message, bool serious); 79 79 }; 80 80 -
code/branches/pickup2/src/libraries/core/input/InputBuffer.cc
r5781 r6412 39 39 RegisterRootObject(InputBuffer); 40 40 41 this->buffer_ = "";42 41 this->cursor_ = 0; 42 this->maxLength_ = 1024; 43 43 this->allowedChars_ = "abcdefghijklmnopqrstuvwxyz \ 44 44 ABCDEFGHIJKLMNOPQRSTUVWXYZ \ … … 59 59 RegisterRootObject(InputBuffer); 60 60 61 this->maxLength_ = 1024; 61 62 this->allowedChars_ = allowedChars; 62 this->buffer_ = "";63 63 this->cursor_ = 0; 64 64 … … 80 80 void InputBuffer::setConfigValues() 81 81 { 82 SetConfigValue(keyRepeatDeleay_, 0.4).description("Key repeat del eay of the input buffer");82 SetConfigValue(keyRepeatDeleay_, 0.4).description("Key repeat delay of the input buffer"); 83 83 SetConfigValue(keyRepeatTime_, 0.022).description("Key repeat time of the input buffer"); 84 84 … … 91 91 ResetConfigValue(keyRepeatTime_); 92 92 } 93 } 94 95 void InputBuffer::setMaxLength(unsigned int length) 96 { 97 this->maxLength_ = length; 98 if (this->buffer_.size() > length) 99 this->buffer_.resize(length); 93 100 } 94 101 … … 117 124 if (this->charIsAllowed(input)) 118 125 { 126 if (this->buffer_.size() >= this->maxLength_) 127 return; 119 128 this->buffer_.insert(this->cursor_, 1, input); 120 129 ++this->cursor_; … … 127 136 void InputBuffer::clear(bool update) 128 137 { 129 this->buffer_ = "";138 this->buffer_.clear(); 130 139 this->cursor_ = 0; 131 140 … … 177 186 bool InputBuffer::charIsAllowed(const char& input) 178 187 { 179 if (this->allowedChars_ == "")188 if (this->allowedChars_.empty()) 180 189 return true; 181 190 else … … 186 195 void InputBuffer::processKey(const KeyEvent& evt) 187 196 { 197 // Prevent disaster when switching applications 188 198 if (evt.isModifierDown(KeyboardModifier::Alt) && evt.getKeyCode() == KeyCode::Tab) 189 199 return; … … 222 232 223 233 /** 224 @brief This update() function is called by the Input Managerif the InputBuffer is active.234 @brief This update() function is called by the InputState if the InputBuffer is active. 225 235 @param dt Delta time 226 236 */ -
code/branches/pickup2/src/libraries/core/input/InputBuffer.h
r5781 r6412 83 83 void setConfigValues(); 84 84 85 unsigned int getMaxLength() const { return this->maxLength_; } 86 void setMaxLength(unsigned int length); 87 85 88 template <class T> 86 89 void registerListener(T* listener, void (T::*function)(), bool bOnlySingleInput) … … 162 165 { if (this->cursor_ > 0) { --this->cursor_; } } 163 166 167 void buttonPressed(const KeyEvent& evt); 168 164 169 private: 165 170 bool charIsAllowed(const char& input); 166 171 167 void buttonPressed(const KeyEvent& evt);168 172 void buttonHeld (const KeyEvent& evt); 169 173 void processKey (const KeyEvent& evt); … … 174 178 std::list<BaseInputBufferListenerTuple*> listeners_; 175 179 std::string allowedChars_; 180 unsigned int maxLength_; 176 181 unsigned int cursor_; 177 182 -
code/branches/pickup2/src/libraries/core/input/InputCommands.h
r5781 r6412 71 71 @brief 72 72 Executes a simple command with no additional paramters. 73 @return 73 @return 74 74 True if command execution was successful, false otherwise. 75 75 */ -
code/branches/pickup2/src/libraries/core/input/InputDevice.h
r5929 r6412 203 203 { 204 204 // remove the button from the pressedButtons_ list 205 bool found = false; 205 206 for (unsigned int iButton = 0; iButton < pressedButtons_.size(); iButton++) 206 207 { … … 208 209 { 209 210 pressedButtons_.erase(pressedButtons_.begin() + iButton); 211 found = true; 210 212 break; 211 213 } 212 214 } 215 if (!found) 216 return; // We ignore release strokes when the press was not captured 213 217 214 218 // Call states -
code/branches/pickup2/src/libraries/core/input/InputHandler.h
r5781 r6412 73 73 , modifiers_(0) 74 74 { } 75 KeyEvent(KeyCode::ByEnum key, unsigned int text, int modifiers) 76 : key_(key) 77 , text_(text) 78 , modifiers_(modifiers) 79 { } 75 80 bool operator==(const KeyEvent& rhs) const 76 81 { return rhs.key_ == key_; } … … 97 102 98 103 Derive from this class if you wish to receive input events. 99 But keep in mind that this is pointless wi htout first having an InputState.104 But keep in mind that this is pointless without first having an InputState. 100 105 @note 101 106 The definitions for the button events with the weird arguments are simply 102 to avoid redun ant code in the input devices.107 to avoid redundant code in the input devices. 103 108 */ 104 109 class _CoreExport InputHandler -
code/branches/pickup2/src/libraries/core/input/InputManager.cc
r5929 r6412 48 48 #include "core/ConfigValueIncludes.h" 49 49 #include "core/ConsoleCommand.h" 50 #include "core/CommandLine .h"50 #include "core/CommandLineParser.h" 51 51 #include "core/Functor.h" 52 52 #include "core/GraphicsManager.h" … … 170 170 if (mouseMode_ == MouseMode::Exclusive || GraphicsManager::getInstance().isFullScreen()) 171 171 { 172 if (CommandLine ::getValue("keyboard_no_grab").getBool())172 if (CommandLineParser::getValue("keyboard_no_grab").getBool()) 173 173 paramList.insert(std::make_pair("x11_keyboard_grab", "false")); 174 174 else … … 190 190 // Exception-safety 191 191 Loki::ScopeGuard guard = Loki::MakeGuard(OIS::InputManager::destroyInputSystem, oisInputManager_); 192 CCOUT( ORX_DEBUG) << "Created OIS input manager." << std::endl;192 CCOUT(4) << "Created OIS input manager." << std::endl; 193 193 194 194 if (oisInputManager_->getNumberOfDevices(OIS::OISKeyboard) > 0) … … 232 232 } 233 233 else 234 CCOUT( ORX_WARNING) << "Warning: No mouse found! Proceeding without mouse support." << std::endl;234 CCOUT(2) << "Warning: No mouse found! Proceeding without mouse support." << std::endl; 235 235 } 236 236 … … 275 275 // destroy all user InputStates 276 276 while (statesByName_.size() > 0) 277 this->destroyStateInternal( (*statesByName_.rbegin()).second);277 this->destroyStateInternal(statesByName_.rbegin()->second); 278 278 279 279 if (!(internalState_ & Bad)) … … 297 297 if (device == NULL) 298 298 continue; 299 std::stringclassName = device->getClassName();299 const std::string& className = device->getClassName(); 300 300 try 301 301 { … … 366 366 // ############################################################ 367 367 368 void InputManager:: update(const Clock& time)368 void InputManager::preUpdate(const Clock& time) 369 369 { 370 370 if (internalState_ & Bad) … … 466 466 @brief 467 467 Updates the currently active states (according to activeStates_) for each device. 468 Also, a list of all active states (no duplicates!) is compiled for the general update().468 Also, a list of all active states (no duplicates!) is compiled for the general preUpdate(). 469 469 */ 470 470 void InputManager::updateActiveStates() … … 508 508 if (mouseStates.empty()) 509 509 requestedMode = MouseMode::Nonexclusive; 510 else 510 else 511 511 requestedMode = mouseStates.front()->getMouseMode(); 512 512 if (requestedMode != MouseMode::Dontcare && mouseMode_ != requestedMode) … … 554 554 } 555 555 556 //! Gets called by WindowEventListener upon focus change --> clear buffers 556 //! Gets called by WindowEventListener upon focus change --> clear buffers 557 557 void InputManager::windowFocusChanged() 558 558 { … … 579 579 InputState* InputManager::createInputState(const std::string& name, bool bAlwaysGetsInput, bool bTransparent, InputStatePriority priority) 580 580 { 581 if (name == "")581 if (name.empty()) 582 582 return 0; 583 583 if (statesByName_.find(name) == statesByName_.end()) … … 631 631 { 632 632 // not scheduled for destruction 633 // prevents a state being added multiple times633 // prevents a state from being added multiple times 634 634 stateEnterRequests_.insert(it->second); 635 635 return true; 636 636 } 637 637 } 638 else if (this->stateLeaveRequests_.find(it->second) != this->stateLeaveRequests_.end()) 639 { 640 // State already scheduled for leaving --> cancel 641 this->stateLeaveRequests_.erase(this->stateLeaveRequests_.find(it->second)); 642 } 638 643 } 639 644 return false; … … 658 663 return true; 659 664 } 665 else if (this->stateEnterRequests_.find(it->second) != this->stateEnterRequests_.end()) 666 { 667 // State already scheduled for entering --> cancel 668 this->stateEnterRequests_.erase(this->stateEnterRequests_.find(it->second)); 669 } 660 670 } 661 671 return false; -
code/branches/pickup2/src/libraries/core/input/InputManager.h
r5929 r6412 41 41 #include "InputState.h" 42 42 43 // tolua_begin 43 44 namespace orxonox 44 45 { … … 47 48 Manages the input devices (mouse, keyboard, joy sticks) and the input states. 48 49 49 Every input device has its own wrapper class which does the actual y input event50 Every input device has its own wrapper class which does the actually input event 50 51 distribution. The InputManager only creates reloads (on request) those devices. 51 52 … … 58 59 in the InputDevices themselves. 59 60 - The devices_ vector always has at least two elements: Keyboard (first) and mouse. 60 You best access them inte nally with InputDeviceEnumerator::Keyboard/Mouse61 You best access them internally with InputDeviceEnumerator::Keyboard/Mouse 61 62 The first joy stick is accessed with InputDeviceEnumerator::FirstJoyStick. 62 63 - Keyboard construction is mandatory , mouse and joy sticks are not. 63 64 If the OIS::InputManager or the Keyboard fail, an exception is thrown. 64 65 */ 65 class _CoreExport InputManager : public Singleton<InputManager>, public WindowEventListener 66 { 66 class _CoreExport InputManager 67 // tolua_end 68 : public Singleton<InputManager>, public WindowEventListener 69 { // tolua_export 67 70 friend class Singleton<InputManager>; 68 71 public: … … 80 83 @brief 81 84 Loads the devices and initialises the KeyDetector and the Calibrator. 82 85 83 86 If either the OIS input system and/or the keyboard could not be created, 84 87 the constructor fails with an std::exception. … … 94 97 95 98 Any InpuStates changes (destroy, enter, leave) and happens here. If a reload request 96 was submitted while updating, the request wil be postponed until the next update call.97 */ 98 void update(const Clock& time);99 was submitted while updating, the request will be postponed until the next update call. 100 */ 101 void preUpdate(const Clock& time); 99 102 //! Clears all input device buffers. This usually only includes the pressed button list. 100 103 void clearBuffers(); … … 105 108 Reloads all the input devices. Use this method to initialise new joy sticks. 106 109 @note 107 Only reloads immediately if the call stack doesn't include the update() method.110 Only reloads immediately if the call stack doesn't include the preUpdate() method. 108 111 */ 109 112 void reload(); … … 135 138 @brief 136 139 Activates a specific input state. 137 It might not be actuallyactivated if the priority is too low!140 It might not actually be activated if the priority is too low! 138 141 @return 139 142 False if name was not found, true otherwise. 140 143 */ 141 bool enterState(const std::string& name); 144 bool enterState(const std::string& name); // tolua_export 142 145 /** 143 146 @brief … … 146 149 False if name was not found, true otherwise. 147 150 */ 148 bool leaveState(const std::string& name); 151 bool leaveState(const std::string& name); // tolua_export 149 152 /** 150 153 @brief … … 154 157 @remarks 155 158 - You can't remove the internal states "empty", "calibrator" and "detector". 156 - The removal process is being postponed if InputManager:: update() is currently running.159 - The removal process is being postponed if InputManager::preUpdate() is currently running. 157 160 */ 158 161 bool destroyState(const std::string& name); … … 168 171 std::pair<int, int> getMousePosition() const; 169 172 173 static InputManager& getInstance() { return Singleton<InputManager>::getInstance(); } // tolua_export 174 170 175 private: // functions 171 176 // don't mess with a Singleton 172 177 InputManager(const InputManager&); 173 178 174 // Inte nal methods179 // Internal methods 175 180 void loadDevices(); 176 181 void loadMouse(); … … 207 212 208 213 static InputManager* singletonPtr_s; //!< Pointer reference to the singleton 209 }; 210 } 214 }; // tolua_export 215 } // tolua_export 211 216 212 217 #endif /* _InputManager_H__ */ -
code/branches/pickup2/src/libraries/core/input/InputPrereqs.h
r5781 r6412 202 202 MediaSelect = OIS::KC_MEDIASELECT // Media Select 203 203 }; 204 204 205 205 //! Key codes as strings 206 206 const char* const ByString[] = -
code/branches/pickup2/src/libraries/core/input/InputState.cc
r5929 r6412 102 102 if (enterFunctor_) 103 103 (*enterFunctor_)(); 104 104 105 105 } 106 106 -
code/branches/pickup2/src/libraries/core/input/JoyStick.cc
r5781 r6412 33 33 #include <boost/foreach.hpp> 34 34 35 #include "util/StringUtils.h" 35 36 #include "core/ConfigFileManager.h" 36 37 #include "core/ConfigValueIncludes.h" … … 61 62 std::string name = oisDevice_->vendor(); 62 63 replaceCharacters(name, ' ', '_'); 63 deviceName_ = name + "_";64 } 65 deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Button)) + "_";66 deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Axis)) + "_";67 deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Slider)) + "_";64 deviceName_ = name + '_'; 65 } 66 deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Button)) + '_'; 67 deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Axis)) + '_'; 68 deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Slider)) + '_'; 68 69 deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_POV)); 69 70 //deviceName_ += multi_cast<std::string>(oisDevice_->getNumberOfComponents(OIS::OIS_Vector3)); … … 74 75 { 75 76 // Make the ID unique for this execution time. 76 deviceName_ += "_"+ multi_cast<std::string>(this->getDeviceName());77 deviceName_ += '_' + multi_cast<std::string>(this->getDeviceName()); 77 78 break; 78 79 } -
code/branches/pickup2/src/libraries/core/input/JoyStickQuantityListener.h
r5781 r6412 29 29 /** 30 30 @file 31 @brief 31 @brief 32 32 */ 33 33 -
code/branches/pickup2/src/libraries/core/input/KeyBinder.cc
r5929 r6412 29 29 #include "KeyBinder.h" 30 30 31 #include <algorithm> 32 #include <sstream> 31 33 #include "util/Convert.h" 32 34 #include "util/Debug.h" … … 50 52 mouseRelative_[0] = 0; 51 53 mouseRelative_[1] = 0; 52 mousePosition_[0] = 0 ;53 mousePosition_[1] = 0 ;54 mousePosition_[0] = 0.0; 55 mousePosition_[1] = 0.0; 54 56 55 57 RegisterRootObject(KeyBinder); … … 59 61 for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++) 60 62 { 61 std::stringkeyname = KeyCode::ByString[i];63 const std::string& keyname = KeyCode::ByString[i]; 62 64 if (!keyname.empty()) 63 65 keys_[i].name_ = std::string("Key") + keyname; 64 66 else 65 keys_[i].name_ = "";67 keys_[i].name_.clear(); 66 68 keys_[i].paramCommandBuffer_ = ¶mCommandBuffer_; 67 69 keys_[i].groupName_ = "Keys"; … … 126 128 SetConfigValue(bFilterAnalogNoise_, false) 127 129 .description("Specifies whether to filter small analog values like joy stick fluctuations."); 128 SetConfigValue(mouseSensitivity_, 1.0f)130 SetConfigValue(mouseSensitivity_, 3.0f) 129 131 .description("Mouse sensitivity."); 132 this->totalMouseSensitivity_ = this->mouseSensitivity_ / this->mouseClippingSize_; 130 133 SetConfigValue(bDeriveMouseInput_, false) 131 134 .description("Whether or not to derive moues movement for the absolute value."); … … 185 188 this->joyStickButtons_.resize(joySticks_.size()); 186 189 187 // reinitialise all joy stick bin ings (doesn't overwrite the old ones)190 // reinitialise all joy stick bindings (doesn't overwrite the old ones) 188 191 for (unsigned int iDev = 0; iDev < joySticks_.size(); iDev++) 189 192 { 190 std::stringdeviceName = joySticks_[iDev]->getDeviceName();193 const std::string& deviceName = joySticks_[iDev]->getDeviceName(); 191 194 // joy stick buttons 192 195 for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++) … … 218 221 for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++) 219 222 if (!keys_[i].name_.empty()) 220 allButtons_[keys_[i].groupName_ + "."+ keys_[i].name_] = keys_ + i;223 allButtons_[keys_[i].groupName_ + '.' + keys_[i].name_] = keys_ + i; 221 224 for (unsigned int i = 0; i < numberOfMouseButtons_; i++) 222 allButtons_[mouseButtons_[i].groupName_ + "."+ mouseButtons_[i].name_] = mouseButtons_ + i;225 allButtons_[mouseButtons_[i].groupName_ + '.' + mouseButtons_[i].name_] = mouseButtons_ + i; 223 226 for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++) 224 227 { 225 allButtons_[mouseAxes_[i].groupName_ + "."+ mouseAxes_[i].name_] = mouseAxes_ + i;228 allButtons_[mouseAxes_[i].groupName_ + '.' + mouseAxes_[i].name_] = mouseAxes_ + i; 226 229 allHalfAxes_.push_back(mouseAxes_ + i); 227 230 } … … 229 232 { 230 233 for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++) 231 allButtons_[(*joyStickButtons_[iDev])[i].groupName_ + "."+ (*joyStickButtons_[iDev])[i].name_] = &((*joyStickButtons_[iDev])[i]);234 allButtons_[(*joyStickButtons_[iDev])[i].groupName_ + '.' + (*joyStickButtons_[iDev])[i].name_] = &((*joyStickButtons_[iDev])[i]); 232 235 for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++) 233 236 { 234 allButtons_[(*joyStickAxes_[iDev])[i].groupName_ + "."+ (*joyStickAxes_[iDev])[i].name_] = &((*joyStickAxes_[iDev])[i]);237 allButtons_[(*joyStickAxes_[iDev])[i].groupName_ + '.' + (*joyStickAxes_[iDev])[i].name_] = &((*joyStickAxes_[iDev])[i]); 235 238 allHalfAxes_.push_back(&((*joyStickAxes_[iDev])[i])); 236 239 } … … 253 256 // Parse bindings and create the ConfigValueContainers if necessary 254 257 for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it) 258 { 255 259 it->second->readConfigValue(this->configFile_); 260 addButtonToCommand(it->second->bindingString_, it->second); 261 } 256 262 257 263 COUT(3) << "KeyBinder: Loading key bindings done." << std::endl; … … 263 269 if (it != allButtons_.end()) 264 270 { 271 addButtonToCommand(binding, it->second); 265 272 if (bTemporary) 266 273 it->second->configContainer_->tset(binding); … … 275 282 return false; 276 283 } 284 } 285 286 void KeyBinder::addButtonToCommand(const std::string& command, Button* button) 287 { 288 std::ostringstream stream; 289 stream << button->groupName_ << '.' << button->name_; 290 291 std::vector<std::string>& oldKeynames = this->allCommands_[button->bindingString_]; 292 std::vector<std::string>::iterator it = std::find(oldKeynames.begin(), oldKeynames.end(), stream.str()); 293 if(it != oldKeynames.end()) 294 { 295 oldKeynames.erase(it); 296 } 297 298 if (!command.empty()) 299 { 300 std::vector<std::string>& keynames = this->allCommands_[command]; 301 if( std::find(keynames.begin(), keynames.end(), stream.str()) == keynames.end()) 302 { 303 this->allCommands_[command].push_back(stream.str()); 304 } 305 } 306 } 307 308 /** 309 @brief 310 Return the first key name for a specific command 311 */ 312 const std::string& KeyBinder::getBinding(const std::string& commandName) 313 { 314 if( this->allCommands_.find(commandName) != this->allCommands_.end()) 315 { 316 std::vector<std::string>& keynames = this->allCommands_[commandName]; 317 return keynames.front(); 318 } 319 320 return BLANKSTRING; 321 } 322 323 /** 324 @brief 325 Return the key name for a specific command at a given index. 326 @param commandName 327 The command name the key name is returned for. 328 @param index 329 The index at which the key name is returned for. 330 */ 331 const std::string& KeyBinder::getBinding(const std::string& commandName, unsigned int index) 332 { 333 if( this->allCommands_.find(commandName) != this->allCommands_.end()) 334 { 335 std::vector<std::string>& keynames = this->allCommands_[commandName]; 336 if(index < keynames.size()) 337 { 338 return keynames[index]; 339 } 340 341 return BLANKSTRING; 342 } 343 344 return BLANKSTRING; 345 } 346 347 /** 348 @brief 349 Get the number of different key bindings of a specific command. 350 @param commandName 351 The command. 352 */ 353 unsigned int KeyBinder::getNumberOfBindings(const std::string& commandName) 354 { 355 if( this->allCommands_.find(commandName) != this->allCommands_.end()) 356 { 357 std::vector<std::string>& keynames = this->allCommands_[commandName]; 358 return keynames.size(); 359 } 360 361 return 0; 277 362 } 278 363 … … 395 480 396 481 // these are the actually useful axis bindings for analog input 397 if (!bFilterAnalogNoise_ || halfAxis.relVal_ > analogThreshold_ || halfAxis.absVal_ > analogThreshold_) 398 { 399 halfAxis.execute(); 400 } 482 halfAxis.execute(); 401 483 } 402 484 … … 426 508 mouseAxes_[2*i + 0].hasChanged_ = true; 427 509 mouseAxes_[2*i + 1].hasChanged_ = true; 428 mousePosition_[i] += rel[i] ;510 mousePosition_[i] += rel[i] * totalMouseSensitivity_; 429 511 430 512 // clip absolute position 431 if (mousePosition_[i] > mouseClippingSize_)432 mousePosition_[i] = mouseClippingSize_;433 if (mousePosition_[i] < - mouseClippingSize_)434 mousePosition_[i] = - mouseClippingSize_;435 436 if (mousePosition_[i] < 0 )513 if (mousePosition_[i] > 1.0) 514 mousePosition_[i] = 1.0; 515 if (mousePosition_[i] < -1.0) 516 mousePosition_[i] = -1.0; 517 518 if (mousePosition_[i] < 0.0) 437 519 { 438 mouseAxes_[2*i + 0].absVal_ = -mouse Sensitivity_ * mousePosition_[i] / mouseClippingSize_;520 mouseAxes_[2*i + 0].absVal_ = -mousePosition_[i]; 439 521 mouseAxes_[2*i + 1].absVal_ = 0.0f; 440 522 } … … 442 524 { 443 525 mouseAxes_[2*i + 0].absVal_ = 0.0f; 444 mouseAxes_[2*i + 1].absVal_ = mouse Sensitivity_ * mousePosition_[i] / mouseClippingSize_;526 mouseAxes_[2*i + 1].absVal_ = mousePosition_[i]; 445 527 } 446 528 } … … 452 534 { 453 535 if (rel[i] < 0) 454 mouseAxes_[0 + 2*i].relVal_ = - mouseSensitivity_ * rel[i] / mouseClippingSize_;536 mouseAxes_[0 + 2*i].relVal_ = -rel[i] * totalMouseSensitivity_; 455 537 else 456 mouseAxes_[1 + 2*i].relVal_ = mouseSensitivity_ * rel[i] / mouseClippingSize_;538 mouseAxes_[1 + 2*i].relVal_ = rel[i] * totalMouseSensitivity_; 457 539 } 458 540 } … … 474 556 void KeyBinder::axisMoved(unsigned int device, unsigned int axisID, float value) 475 557 { 558 // Filter analog noise 559 if (this->bFilterAnalogNoise_ && std::abs(value) < this->analogThreshold_) 560 value = 0.0; 476 561 int i = axisID * 2; 477 562 JoyStickAxisVector& axis = *joyStickAxes_[device]; -
code/branches/pickup2/src/libraries/core/input/KeyBinder.h
r5929 r6412 35 35 #include <string> 36 36 #include <vector> 37 #include <map> 37 38 #include <boost/shared_ptr.hpp> 38 39 … … 43 44 #include "JoyStickQuantityListener.h" 44 45 46 // tolua_begin 45 47 namespace orxonox 46 48 { 49 // tolua_end 47 50 /** 48 51 @brief … … 54 57 KeyBinders. If you need to load other bindings, just create a new one. 55 58 */ 56 class _CoreExport KeyBinder : public InputHandler, public JoyStickQuantityListener 57 { 59 class _CoreExport KeyBinder // tolua_export 60 : public InputHandler, public JoyStickQuantityListener 61 { // tolua_export 58 62 public: 59 63 KeyBinder (const std::string& filename); … … 62 66 void clearBindings(); 63 67 bool setBinding(const std::string& binding, const std::string& name, bool bTemporary = false); 68 const std::string& getBinding(const std::string& commandName); //tolua_export 69 const std::string& getBinding(const std::string& commandName, unsigned int index); //tolua_export 70 unsigned int getNumberOfBindings(const std::string& commandName); //tolua_export 71 64 72 const std::string& getBindingsFilename() 65 73 { return this->filename_; } … … 130 138 //! Pointer list with all half axes 131 139 std::vector<HalfAxis*> allHalfAxes_; 140 //! Maps input commands to all Button names, including half axes 141 std::map< std::string, std::vector<std::string> > allCommands_; 132 142 133 143 /** … … 138 148 std::vector<BufferedParamCommand*> paramCommandBuffer_; 139 149 140 //! Keeps track of the absolute mouse value (incl. scroll wheel)141 int mousePosition_[2];150 //! Keeps track of the absolute mouse value 151 float mousePosition_[2]; 142 152 //! Used to derive mouse input if requested 143 153 int mouseRelative_[2]; … … 150 160 151 161 private: 162 void addButtonToCommand(const std::string& command, Button* button); 163 152 164 //##### ConfigValues ##### 153 165 //! Whether to filter small value analog input … … 165 177 //! mouse sensitivity if mouse input is derived 166 178 float mouseSensitivityDerived_; 167 //! Equals one step of the mouse wheel179 //! Equals one step of the mouse wheel 168 180 int mouseWheelStepSize_; 181 182 //! Multiplication of mouse sensitivity and clipping size 183 float totalMouseSensitivity_; 169 184 170 185 //##### Constant config variables ##### 171 186 // Use some value at about 1000. This can be configured with mouseSensitivity_ anyway. 172 187 static const int mouseClippingSize_ = 1024; 173 }; 188 };// tolua_export 174 189 175 190 … … 216 231 mouseAxes_[i].relVal_ = 0.0f; 217 232 } 218 } 233 }// tolua_export 219 234 220 235 #endif /* _KeyBinder_H__ */ -
code/branches/pickup2/src/libraries/core/input/KeyBinderManager.cc
r5929 r6412 40 40 namespace orxonox 41 41 { 42 KeyBinderManager* KeyBinderManager::singletonPtr_s = 0;43 42 ManageScopedSingleton(KeyBinderManager, ScopeID::Graphics, false); 44 43 … … 48 47 , bBinding_(false) 49 48 { 50 this->callbackFunction_ = createFunctor(&KeyBinderManager::callback, this);51 52 49 RegisterObject(KeyBinderManager); 53 50 this->setConfigValues(); … … 57 54 .defaultValues(""); 58 55 CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyBinderManager::tkeybind, this), "tkeybind")) 56 .defaultValues(""); 57 CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyBinderManager::unbind, this), "unbind")) 58 .defaultValues(""); 59 CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyBinderManager::tunbind, this), "tunbind")) 59 60 .defaultValues(""); 60 61 … … 68 69 for (std::map<std::string, KeyBinder*>::const_iterator it = this->binders_.begin(); it != this->binders_.end(); ++it) 69 70 delete it->second; 70 delete this->callbackFunction_;71 71 } 72 72 … … 91 91 else 92 92 this->bDefaultFileLoaded_ = false; 93 } 94 95 inline void KeyBinderManager::unbind(const std::string& binding) 96 { 97 this->currentBinder_->setBinding("", binding, false); 98 } 99 100 inline void KeyBinderManager::tunbind(const std::string& binding) 101 { 102 this->currentBinder_->setBinding("", binding, true); 93 103 } 94 104 … … 146 156 { 147 157 COUT(0) << "Press any button/key or move a mouse/joystick axis" << std::endl; 148 KeyDetector::getInstance().setCallback( callbackFunction_);158 KeyDetector::getInstance().setCallback(shared_ptr<Functor>(createFunctor(&KeyBinderManager::keybindKeyPressed, this))); 149 159 InputManager::getInstance().enterState("detector"); 150 160 this->command_ = command; … … 156 166 157 167 // Gets called by the KeyDetector (registered with a Functor) 158 void KeyBinderManager:: callback(const std::string& keyName)168 void KeyBinderManager::keybindKeyPressed(const std::string& keyName) 159 169 { 160 170 if (this->bBinding_) 161 171 { 162 COUT(0) << "Binding string \"" << command_ << "\" on key '" << keyName << "'" << std::endl; 163 this->currentBinder_->setBinding(command_, keyName, bTemporary_); 172 if (keyName == "Keys.KeyEscape") 173 { 174 COUT(0) << "Keybinding aborted." << std::endl; 175 } 176 else 177 { 178 COUT(0) << "Binding string \"" << command_ << "\" on key '" << keyName << "'" << std::endl; 179 this->currentBinder_->setBinding(command_, keyName, bTemporary_); 180 } 164 181 InputManager::getInstance().leaveState("detector"); 182 // inform whatever was calling the command 183 if (this->callbackFunction_) 184 (*this->callbackFunction_)(); 165 185 this->bBinding_ = false; 166 186 } -
code/branches/pickup2/src/libraries/core/input/KeyBinderManager.h
r5929 r6412 34 34 #include <map> 35 35 #include <string> 36 #include <boost/shared_ptr.hpp> 37 36 38 #include "util/Singleton.h" 37 39 #include "core/OrxonoxClass.h" 38 40 39 namespace orxonox 40 { 41 namespace orxonox //tolua_export 42 { //tolua_export 41 43 /** 42 44 @brief … … 46 48 maps to the currently active KeyBinder. You can set that with setCurrent(). 47 49 There is also a default one, retrieved with getDefault(). The idea is that 48 mostly the default KeyBinder is active except for special situ tations (mini-game for inst).50 mostly the default KeyBinder is active except for special situations (mini-game for inst). 49 51 @remarks 50 52 You are not forced to use the KeyBinder imposed by getCurrent(). But be aware that "keybind" 51 53 will not work as expected! 52 54 */ 53 class _CoreExport KeyBinderManager : public Singleton<KeyBinderManager>, public OrxonoxClass 54 { 55 class _CoreExport KeyBinderManager //tolua_export 56 : public Singleton<KeyBinderManager>, public OrxonoxClass 57 { //tolua_export 55 58 friend class Singleton<KeyBinderManager>; 56 59 public: … … 59 62 void setConfigValues(); 60 63 64 static KeyBinderManager& getInstance() { return Singleton<KeyBinderManager>::getInstance(); } //tolua_export 61 65 //! Returns the currently selected KeyBinder 62 KeyBinder* getCurrent() 63 { return this->currentBinder_; } 66 KeyBinder* getCurrent() { return this->currentBinder_; } //tolua_export 64 67 //! Like getCurrent(), but returns it as InputHandler* (so you don't have to include KeyBinder.h) 65 68 InputHandler* getCurrentAsHandler(); … … 68 71 69 72 //! Returns the default KeyBinder 70 KeyBinder* 73 KeyBinder* getDefault() 71 74 { return binders_[this->defaultFilename_]; } 72 75 //! Returns the default KeyBinder as InputHandler* (so you don't have to include KeyBinder.h) … … 80 83 81 84 //! Returns a pointer to a KeyBinder (creates it if not yet loaded) 82 KeyBinder* 85 KeyBinder* get(const std::string& name); 83 86 //! Like get() but return value is of type InputHandler* (so you don't have to include KeyBinder.h) 84 87 InputHandler* getAsHandler(const std::string& name); 85 88 86 89 //! Loads a KeyBinder by creating it (no different from get() except for the return value) 87 void load 90 void load(const std::string& filename); 88 91 //! Destroys a KeyBinder completely (does nothing if not yet loaded) 89 92 void unload(const std::string& filename); 90 93 91 94 //! Bind 'command' to any key pressed after this call (use with care!) 92 inline void keybind(const std::string& command) 93 { this->keybindInternal(command, false); } 95 inline void keybind(const std::string& command) { this->keybindInternal(command, false); } //tolua_export 94 96 //! Bind 'command' to any key pressed after this call (use with care!), but temporarily (no file save) 95 97 inline void tkeybind(const std::string& command) 96 98 { this->keybindInternal(command, true); } 99 void unbind(const std::string& binding); //tolua_export 100 void tunbind(const std::string& binding); 101 inline void registerKeybindCallback(Functor* function) { this->callbackFunction_.reset(function); } // tolua_export 97 102 98 103 private: 99 104 KeyBinderManager(const KeyBinderManager&); 100 105 void keybindInternal(const std::string& command, bool bTemporary); 101 void callback(const std::string& keyName);106 void keybindKeyPressed(const std::string& keyName); 102 107 void defaultFilenameChanged(); 103 108 … … 109 114 110 115 // keybind command related 111 Functor* callbackFunction_;//! Function to be called when key was pressed after "keybind" command116 shared_ptr<Functor> callbackFunction_; //! Function to be called when key was pressed after "keybind" command 112 117 bool bBinding_; //! Tells whether a key binding process is active 113 118 bool bTemporary_; //! Stores tkeybind/keybind value … … 115 120 116 121 static KeyBinderManager* singletonPtr_s; 117 }; 118 } 122 }; //tolua_export 123 } //tolua_export 119 124 120 125 #endif /* _KeyBinderManager_H__ */ -
code/branches/pickup2/src/libraries/core/input/KeyDetector.cc
r5929 r6412 39 39 { 40 40 std::string KeyDetector::callbackCommand_s = "KeyDetectorKeyPressed"; 41 KeyDetector* KeyDetector::singletonPtr_s = 0;42 41 ManageScopedSingleton(KeyDetector, ScopeID::Graphics, false); 43 42 … … 68 67 for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it) 69 68 { 70 it->second->bindingString_ = callbackCommand_s + " "+ it->second->groupName_ + "." + it->second->name_;69 it->second->bindingString_ = callbackCommand_s + ' ' + it->second->groupName_ + "." + it->second->name_; 71 70 it->second->parse(); 72 71 } -
code/branches/pickup2/src/libraries/core/input/KeyDetector.h
r5929 r6412 32 32 #include "InputPrereqs.h" 33 33 34 #include <boost/shared_ptr.hpp> 34 35 #include "util/Singleton.h" 35 36 #include "KeyBinder.h" … … 45 46 ~KeyDetector(); 46 47 47 void setCallback( Functor*function) { this->callbackFunction_ = function; }48 void setCallback(const shared_ptr<Functor>& function) { this->callbackFunction_ = function; } 48 49 49 50 private: … … 54 55 void assignCommands(); 55 56 56 Functor*callbackFunction_;57 shared_ptr<Functor> callbackFunction_; 57 58 InputState* inputState_; 58 59 static std::string callbackCommand_s; -
code/branches/pickup2/src/libraries/core/input/Keyboard.cc
r5781 r6412 43 43 modifiers_ |= KeyboardModifier::Shift; // shift key 44 44 45 // Do not distribute the alt+tab event (messes with the operating system) 46 if ((modifiers_ & KeyboardModifier::Alt) != 0 && arg.key == OIS::KC_TAB) 47 return true; 48 45 49 KeyEvent evt(arg); 46 50 super::buttonPressed(evt); -
code/branches/pickup2/src/libraries/network/Client.cc
r5929 r6412 62 62 Client::Client(): 63 63 isSynched_(false), 64 gameStateFailure_(false) 64 gameStateFailure_(false), 65 timeSinceLastUpdate_(0) 65 66 { 66 67 } … … 73 74 Client::Client(const std::string& address, int port): 74 75 isSynched_(false), 75 gameStateFailure_(false) 76 gameStateFailure_(false), 77 timeSinceLastUpdate_(0) 76 78 { 77 79 setPort( port ); … … 112 114 } 113 115 116 void Client::printRTT(){ 117 COUT(0) << "Round trip time to server is " << ClientConnection::getRTT() << " ms" << endl; 118 } 119 114 120 /** 115 121 * This function implements the method of sending a chat message to the server … … 133 139 { 134 140 timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD; 135 // COUT(3) << ".";141 // COUT(3) << '.'; 136 142 if ( isConnected() && isSynched_ ) 137 143 { … … 149 155 } 150 156 sendPackets(); // flush the enet queue 151 157 152 158 Connection::processQueue(); 153 159 if(gamestate.processGamestates()) … … 157 163 } 158 164 gamestate.cleanup(); 165 Connection::sendPackets(); 159 166 160 167 return; 161 168 } 162 169 163 170 void Client::connectionClosed() 164 171 { -
code/branches/pickup2/src/libraries/network/Client.h
r5929 r6412 72 72 virtual bool chat(const std::string& message); 73 73 virtual bool broadcast(const std::string& message) { return false; } 74 virtual void printRTT(); 74 75 75 76 void update(const Clock& time); -
code/branches/pickup2/src/libraries/network/ClientConnection.cc
r5929 r6412 38 38 const unsigned int NETWORK_CLIENT_WAIT_TIME = 1; 39 39 const unsigned int NETWORK_CLIENT_CONNECTION_TIMEOUT = 3000; //millisecs 40 const unsigned int NETWORK_CLIENT_MAX_CONNECTIONS = 5;41 const unsigned int NETWORK_CLIENT_CHANNELS = 2;40 const unsigned int NETWORK_CLIENT_MAX_CONNECTIONS = 1; 41 const unsigned int NETWORK_CLIENT_CHANNELS = 1; 42 42 43 43 … … 69 69 { 70 70 ENetEvent event; 71 71 72 72 this->host_ = enet_host_create(NULL, NETWORK_CLIENT_MAX_CONNECTIONS, 0, 0); 73 73 if ( this->host_ == NULL ) … … 99 99 bool ClientConnection::closeConnection() { 100 100 ENetEvent event; 101 101 102 102 if ( !this->established_ ) 103 103 return true; … … 147 147 } 148 148 149 uint32_t ClientConnection::getRTT() 150 { 151 assert(server_); 152 return server_->roundTripTime; 153 } 154 149 155 } -
code/branches/pickup2/src/libraries/network/ClientConnection.h
r5929 r6412 26 26 * 27 27 */ 28 28 29 29 #ifndef _ClientConnection_H__ 30 30 #define _ClientConnection_H__ … … 40 40 ClientConnection(); 41 41 virtual ~ClientConnection(); 42 42 43 43 void setServerAddress( const std::string& serverAddress ); 44 44 void setPort( unsigned int port ); 45 45 46 46 ENetEvent *getEvent(); 47 47 // check wheter the packet queue is empty … … 55 55 protected: 56 56 virtual void connectionClosed()=0; 57 uint32_t getRTT(); 57 58 private: 58 59 virtual void addPeer(ENetEvent* event); 59 60 virtual void removePeer(ENetEvent* event); 60 61 61 62 bool disconnectConnection(); 62 63 // enet stuff -
code/branches/pickup2/src/libraries/network/ClientConnectionListener.cc
r5929 r6412 36 36 { 37 37 ClientConnectionListener::ClientConnectionListener() 38 { 39 RegisterRootObject(ClientConnectionListener); 38 { 39 RegisterRootObject(ClientConnectionListener); 40 40 } 41 41 … … 45 45 it->clientConnected(clientID); 46 46 } 47 47 48 48 void ClientConnectionListener::broadcastClientDisconnected(unsigned int clientID) 49 49 { -
code/branches/pickup2/src/libraries/network/ClientConnectionListener.h
r5929 r6412 40 40 ClientConnectionListener(); 41 41 virtual ~ClientConnectionListener() {} 42 42 43 43 static void broadcastClientConnected(unsigned int clientID); 44 44 static void broadcastClientDisconnected(unsigned int clientID); -
code/branches/pickup2/src/libraries/network/ClientInformation.cc
r5781 r6412 42 42 #define WIN32_LEAN_AND_MEAN 43 43 #include <enet/enet.h> 44 #include "ClientConnectionListener.h" 44 45 45 46 namespace orxonox 46 47 { 47 48 48 49 49 50 ClientInformation *ClientInformation::head_=0; … … 66 67 if(this==head_) 67 68 head_=next(); 69 ClientConnectionListener::broadcastClientDisconnected( this->getID() ); 68 70 } 69 71 -
code/branches/pickup2/src/libraries/network/Connection.cc
r5929 r6412 75 75 void Connection::processQueue() { 76 76 ENetEvent event; 77 77 78 78 assert(this->host_); 79 79 -
code/branches/pickup2/src/libraries/network/Connection.h
r5929 r6412 54 54 public: 55 55 virtual ~Connection(); 56 56 57 57 static bool addPacket(ENetPacket *packet, ENetPeer *peer); 58 58 bool sendPackets(); … … 62 62 Connection(); 63 63 static Connection* getInstance(){ return Connection::instance_; } 64 64 65 65 int service(ENetEvent* event); 66 66 virtual void disconnectPeer(ENetPeer *peer); 67 67 68 68 void processQueue(); 69 69 virtual void addPeer(ENetEvent* event)=0; 70 70 virtual void removePeer(ENetEvent* event)=0; 71 71 virtual bool processPacket(ENetEvent* event); 72 72 73 73 ENetHost *host_; 74 74 private: -
code/branches/pickup2/src/libraries/network/FunctionCallManager.cc
r5781 r6412 31 31 32 32 namespace orxonox { 33 33 34 34 std::map<uint32_t, packet::FunctionCalls*> FunctionCallManager::clientMap_; 35 35 … … 37 37 38 38 void FunctionCallManager::addCallStatic(uint32_t functionID, uint32_t clientID) 39 { 40 if(clientMap_.find(clientID)==clientMap_.end()) 39 { 40 if(clientMap_.find(clientID)==clientMap_.end()) 41 41 { 42 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 43 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 44 } 45 FunctionCallManager:: 42 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 43 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 44 } 45 FunctionCallManager::clientMap_[clientID]->addCallStatic(functionID); 46 46 } 47 47 void FunctionCallManager::addCallStatic(uint32_t functionID, uint32_t clientID, const MultiType& mt1) 48 { 49 if(clientMap_.find(clientID)==clientMap_.end()) 48 { 49 if(clientMap_.find(clientID)==clientMap_.end()) 50 50 { 51 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 52 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 53 } 51 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 52 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 53 } 54 54 FunctionCallManager:: clientMap_[clientID]->addCallStatic(functionID, &mt1); 55 55 } 56 56 void FunctionCallManager::addCallStatic(uint32_t functionID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2) 57 { 58 if(clientMap_.find(clientID)==clientMap_.end()) 57 { 58 if(clientMap_.find(clientID)==clientMap_.end()) 59 59 { 60 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 61 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 62 } 60 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 61 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 62 } 63 63 FunctionCallManager:: clientMap_[clientID]->addCallStatic(functionID, &mt1, &mt2); 64 64 } 65 65 void FunctionCallManager::addCallStatic(uint32_t functionID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3) 66 { 67 if(clientMap_.find(clientID)==clientMap_.end()) 66 { 67 if(clientMap_.find(clientID)==clientMap_.end()) 68 68 { 69 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 70 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 71 } 69 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 70 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 71 } 72 72 FunctionCallManager:: clientMap_[clientID]->addCallStatic(functionID, &mt1, &mt2, &mt3); 73 73 } 74 74 void FunctionCallManager::addCallStatic(uint32_t functionID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4) 75 { 76 if(clientMap_.find(clientID)==clientMap_.end()) 75 { 76 if(clientMap_.find(clientID)==clientMap_.end()) 77 77 { 78 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 79 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 80 } 78 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 79 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 80 } 81 81 FunctionCallManager:: clientMap_[clientID]->addCallStatic(functionID, &mt1, &mt2, &mt3, &mt4); 82 82 } 83 83 void FunctionCallManager::addCallStatic(uint32_t functionID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4, const MultiType& mt5) 84 { 85 if(clientMap_.find(clientID)==clientMap_.end()) 84 { 85 if(clientMap_.find(clientID)==clientMap_.end()) 86 86 { 87 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 88 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 89 } 87 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 88 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 89 } 90 90 FunctionCallManager:: clientMap_[clientID]->addCallStatic(functionID, &mt1, &mt2, &mt3, &mt4, &mt5); 91 91 } … … 95 95 96 96 void FunctionCallManager::addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID) 97 { 98 if(clientMap_.find(clientID)==clientMap_.end()) 97 { 98 if(clientMap_.find(clientID)==clientMap_.end()) 99 99 { 100 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 101 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 102 } 100 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 101 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 102 } 103 103 FunctionCallManager::clientMap_[clientID]->addCallMember(functionID, objectID); 104 104 } 105 105 void FunctionCallManager::addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID, const MultiType& mt1) 106 { 107 if(clientMap_.find(clientID)==clientMap_.end()) 106 { 107 if(clientMap_.find(clientID)==clientMap_.end()) 108 108 { 109 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 110 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 111 } 109 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 110 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 111 } 112 112 FunctionCallManager::clientMap_[clientID]->addCallMember(functionID, objectID, &mt1); 113 113 } 114 114 void FunctionCallManager::addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2) 115 { 116 if(clientMap_.find(clientID)==clientMap_.end()) 115 { 116 if(clientMap_.find(clientID)==clientMap_.end()) 117 117 { 118 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 119 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 120 } 118 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 119 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 120 } 121 121 FunctionCallManager::clientMap_[clientID]->addCallMember(functionID, objectID, &mt1, &mt2); 122 122 } 123 123 void FunctionCallManager::addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3) 124 { 125 if(clientMap_.find(clientID)==clientMap_.end()) 124 { 125 if(clientMap_.find(clientID)==clientMap_.end()) 126 126 { 127 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 128 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 129 } 127 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 128 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 129 } 130 130 FunctionCallManager::clientMap_[clientID]->addCallMember(functionID, objectID, &mt1, &mt2, &mt3); 131 131 } 132 132 void FunctionCallManager::addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4) 133 { 134 if(clientMap_.find(clientID)==clientMap_.end()) 133 { 134 if(clientMap_.find(clientID)==clientMap_.end()) 135 135 { 136 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 137 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 138 } 136 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 137 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 138 } 139 139 FunctionCallManager::clientMap_[clientID]->addCallMember(functionID, objectID, &mt1, &mt2, &mt3, &mt4); 140 140 } 141 141 void FunctionCallManager::addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4, const MultiType& mt5) 142 { 143 if(clientMap_.find(clientID)==clientMap_.end()) 142 { 143 if(clientMap_.find(clientID)==clientMap_.end()) 144 144 { 145 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 146 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 147 } 145 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 146 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 147 } 148 148 FunctionCallManager::clientMap_[clientID]->addCallMember(functionID, objectID, &mt1, &mt2, &mt3, &mt4, &mt5); 149 149 } -
code/branches/pickup2/src/libraries/network/FunctionCallManager.h
r5781 r6412 37 37 namespace orxonox { 38 38 /** 39 39 @author 40 40 */ 41 41 … … 49 49 static void addCallStatic(uint32_t functionID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4); 50 50 static void addCallStatic(uint32_t functionID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4, const MultiType& mt5); 51 51 52 52 static void addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID); 53 53 static void addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID, const MultiType& mt1); … … 56 56 static void addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4); 57 57 static void addCallMember(uint32_t functionID, uint32_t objectID, uint32_t clientID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4, const MultiType& mt5); 58 58 59 59 static void sendCalls(); 60 60 61 61 static std::map<uint32_t, packet::FunctionCalls*> clientMap_; 62 62 protected: -
code/branches/pickup2/src/libraries/network/GamestateClient.cc
r5929 r6412 54 54 std::map<unsigned int, packet::Gamestate *>::iterator it; 55 55 for ( it = this->gamestateMap_.begin(); it != this->gamestateMap_.end(); ++it ) 56 delete (*it).second;56 delete it->second; 57 57 if( this->tempGamestate_ ) 58 58 delete this->tempGamestate_; … … 81 81 packet::Gamestate *processed = processGamestate(tempGamestate_); 82 82 assert(processed); 83 83 84 84 //now call the queued callbacks 85 85 NetworkCallbackManager::callCallbacks(); 86 86 87 87 if (!processed){ 88 88 sendAck(0); … … 126 126 break; 127 127 // otherwise delete that stuff 128 delete (*it).second;128 delete it->second; 129 129 temp=it++; 130 130 gamestateMap_.erase(temp); … … 137 137 COUT(4) << "gamestates: "; 138 138 for(it=gamestateMap_.begin(); it!=gamestateMap_.end(); it++){ 139 COUT(4) << it->first << ":" << it->second << "|";139 COUT(4) << it->first << ':' << it->second << '|'; 140 140 } 141 141 COUT(4) << std::endl; -
code/branches/pickup2/src/libraries/network/GamestateHandler.cc
r5781 r6412 33 33 34 34 GamestateHandler *GamestateHandler::instance_=0; 35 35 36 36 GamestateHandler::GamestateHandler() 37 37 { -
code/branches/pickup2/src/libraries/network/GamestateHandler.h
r5781 r6412 35 35 36 36 /** 37 37 @author Oliver Scheuss 38 38 */ 39 39 class _NetworkExport GamestateHandler{ -
code/branches/pickup2/src/libraries/network/GamestateManager.cc
r5929 r6412 69 69 delete this->reference;std::map<unsigned int, packet::Gamestate*>::iterator it; 70 70 for( it = gamestateQueue.begin(); it != gamestateQueue.end(); ++it ) 71 delete (*it).second;71 delete it->second; 72 72 std::map<unsigned int, std::map<unsigned int, packet::Gamestate*> >::iterator it1; 73 73 std::map<unsigned int, packet::Gamestate*>::iterator it2; … … 75 75 { 76 76 for( it2 = it1->second.begin(); it2 != it1->second.end(); ++it2 ) 77 delete (*it2).second;77 delete it2->second; 78 78 } 79 79 this->trafficControl_->destroy(); … … 126 126 return true; 127 127 } 128 128 129 129 void GamestateManager::sendGamestates() 130 130 { … … 142 142 COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl; 143 143 int cid = temp->getID(); //get client id 144 144 145 145 unsigned int gID = temp->getGamestateID(); 146 146 if(!reference) 147 147 return; 148 148 149 149 packet::Gamestate *client=0; 150 150 if(gID != GAMESTATEID_INITIAL){ … … 156 156 } 157 157 } 158 158 159 159 clientGamestates.push(0); 160 160 finishGamestate( cid, &clientGamestates.back(), client, reference ); 161 //FunctorMember<GamestateManager>* functor = 161 //FunctorMember<GamestateManager>* functor = 162 162 // ExecutorMember<GamestateManager>* executor = createExecutor( createFunctor(&GamestateManager::finishGamestate, this) ); 163 163 // executor->setDefaultValues( cid, &clientGamestates.back(), client, reference ); … … 165 165 // this->threadPool_->passFunction( executor, true ); 166 166 // (*functor)( cid, &(clientGamestates.back()), client, reference ); 167 167 168 168 temp = temp->next(); 169 169 } 170 170 171 171 // threadPool_->synchronise(); 172 172 173 173 while( !clientGamestates.empty() ) 174 174 { … … 185 185 // save the (undiffed) gamestate in the clients gamestate map 186 186 //chose wheather the next gamestate is the first or not 187 187 188 188 packet::Gamestate *gs = gamestate->doSelection(clientID, 20000); 189 189 // packet::Gamestate *gs = new packet::Gamestate(*gamestate); … … 193 193 gamestateMap_[clientID][gamestate->getID()]=gs; 194 194 // this->threadMutex_->unlock(); 195 195 196 196 if(base) 197 197 { 198 198 199 199 // COUT(3) << "diffing" << std::endl; 200 200 // packet::Gamestate* gs1 = gs; … … 210 210 gs = new packet::Gamestate(*gs); 211 211 } 212 213 212 213 214 214 bool b = gs->compressData(); 215 215 assert(b); -
code/branches/pickup2/src/libraries/network/Host.cc
r5781 r6412 50 50 assert(instance_==0); 51 51 instance_=this; 52 this->printRTTCC_ = createConsoleCommand( createFunctor(&Host::printRTT, this), "printRTT" ); 53 CommandExecutor::addConsoleCommandShortcut( this->printRTTCC_ ); 52 54 } 53 55 … … 59 61 { 60 62 instance_=0; 63 if( this->printRTTCC_ ) 64 delete this->printRTTCC_; 61 65 } 62 66 -
code/branches/pickup2/src/libraries/network/Host.h
r5781 r6412 31 31 32 32 #include "NetworkPrereqs.h" 33 #include "core/CorePrereqs.h" 33 34 34 35 namespace orxonox { … … 44 45 * - defines static functions available on both server and client 45 46 * - is the interface to be used when communicating with the network 46 * 47 * @author Oliver Scheuss 47 48 */ 48 49 class _NetworkExport Host{ … … 79 80 static bool Broadcast(const std::string& message); 80 81 static bool incomingChat(const std::string& message, unsigned int playerID); 82 virtual void printRTT()=0; 81 83 private: 84 ConsoleCommand* printRTTCC_; 82 85 }; 83 86 -
code/branches/pickup2/src/libraries/network/NetworkFunction.cc
r5929 r6412 32 32 namespace orxonox 33 33 { 34 std::map<std::string, NetworkFunctionBase*> NetworkFunctionBase::nameMap_;35 34 std::map<uint32_t, bool> NetworkFunctionBase::isStaticMap_; 36 37 std::map<NetworkFunctionPointer, NetworkFunctionStatic*> NetworkFunctionStatic::functorMap_; 38 std::map<uint32_t, NetworkFunctionStatic*> NetworkFunctionStatic::idMap_; 39 35 40 36 std::map<NetworkFunctionPointer, NetworkMemberFunctionBase*> NetworkMemberFunctionBase::functorMap_; 41 37 std::map<uint32_t, NetworkMemberFunctionBase*> NetworkMemberFunctionBase::idMap_; … … 44 40 { 45 41 RegisterRootObject(NetworkFunctionBase); 46 42 47 43 static uint32_t networkID = 0; 48 44 this->networkID_ = networkID++; 49 45 50 46 this->name_ = name; 51 nameMap_[name] = this;47 NetworkFunctionBase::getNameMap()[name] = this; 52 48 } 53 49 NetworkFunctionBase::~NetworkFunctionBase() 54 50 { 55 51 } 56 57 52 53 58 54 void NetworkFunctionBase::destroyAllNetworkFunctions() 59 55 { 56 std::map<std::string, NetworkFunctionBase*>& map = NetworkFunctionBase::getNameMap(); 60 57 std::map<std::string, NetworkFunctionBase*>::iterator it; 61 for( it= NetworkFunctionBase::nameMap_.begin(); it!=NetworkFunctionBase::nameMap_.end(); ++it )58 for( it=map.begin(); it!=map.end(); ++it ) 62 59 it->second->destroy(); 63 60 } 64 65 61 62 63 /*static*/ std::map<std::string, NetworkFunctionBase*>& NetworkFunctionBase::getNameMap() 64 { 65 static std::map<std::string, NetworkFunctionBase*> nameMap_; 66 return nameMap_; 67 } 68 69 66 70 NetworkFunctionStatic::NetworkFunctionStatic(FunctorStatic* functor, const std::string& name, const NetworkFunctionPointer& p): 67 71 NetworkFunctionBase(name) 68 72 { 69 73 RegisterObject(NetworkFunctionStatic); 70 74 71 75 this->functor_ = functor; 72 functorMap_[p] = this;73 idMap_[ this->getNetworkID() ] = this;76 NetworkFunctionStatic::getFunctorMap()[p] = this; 77 NetworkFunctionStatic::getIdMap()[ this->getNetworkID() ] = this; 74 78 } 75 79 76 80 NetworkFunctionStatic::~NetworkFunctionStatic() 77 81 { 78 82 delete this->functor_; 79 83 } 80 81 82 84 85 /*static*/ std::map<NetworkFunctionPointer, NetworkFunctionStatic*>& NetworkFunctionStatic::getFunctorMap() 86 { 87 static std::map<NetworkFunctionPointer, NetworkFunctionStatic*> functorMap_; 88 return functorMap_; 89 } 90 91 /*static*/ std::map<uint32_t, NetworkFunctionStatic*>& NetworkFunctionStatic::getIdMap() 92 { 93 static std::map<uint32_t, NetworkFunctionStatic*> idMap_; 94 return idMap_; 95 } 96 97 83 98 NetworkMemberFunctionBase::NetworkMemberFunctionBase(const std::string& name, const NetworkFunctionPointer& p): 84 99 NetworkFunctionBase(name) 85 100 { 86 101 RegisterObject(NetworkMemberFunctionBase); 87 88 functorMap_[p] = this;89 idMap_[ this->getNetworkID() ] = this;102 103 this->functorMap_[p] = this; 104 this->idMap_[ this->getNetworkID() ] = this; 90 105 } 91 106 92 107 NetworkMemberFunctionBase::~NetworkMemberFunctionBase() 93 108 { 94 109 } 95 110 96 111 97 112 } -
code/branches/pickup2/src/libraries/network/NetworkFunction.h
r5781 r6412 74 74 NetworkFunctionBase(const std::string& name); 75 75 ~NetworkFunctionBase(); 76 76 77 77 virtual void setNetworkID(uint32_t id) { this->networkID_ = id; } 78 78 inline uint32_t getNetworkID() const { return this->networkID_; } 79 79 inline const std::string& getName() const { return name_; } 80 80 static inline bool isStatic( uint32_t networkID ) { return isStaticMap_[networkID]; } 81 82 static inline void setNetworkID(const std::string& name, uint32_t id){ assert( nameMap_.find(name)!=nameMap_.end() ); nameMap_[name]->setNetworkID(id); } 83 81 82 static inline void setNetworkID(const std::string& name, uint32_t id) 83 { 84 std::map<std::string, NetworkFunctionBase*>& map = NetworkFunctionBase::getNameMap(); 85 assert( map.find(name)!=map.end() ); 86 map[name]->setNetworkID(id); 87 } 88 84 89 static void destroyAllNetworkFunctions(); 85 90 86 91 protected: 87 92 static std::map<uint32_t, bool> isStaticMap_; 88 89 private: 90 static std::map<std::string, NetworkFunctionBase*> nameMap_;93 94 private: 95 static std::map<std::string, NetworkFunctionBase*>& getNameMap(); 91 96 uint32_t networkID_; 92 97 std::string name_; 93 98 94 99 }; 95 100 … … 99 104 NetworkFunctionStatic(FunctorStatic* functor, const std::string& name, const NetworkFunctionPointer& p); 100 105 ~NetworkFunctionStatic(); 101 106 102 107 inline void call(){ (*this->functor_)(); } 103 108 inline void call(const MultiType& mt1){ (*this->functor_)(mt1); } … … 106 111 inline void call(const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4){ (*this->functor_)(mt1, mt2, mt3, mt4); } 107 112 inline void call(const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4, const MultiType& mt5){ (*this->functor_)(mt1, mt2, mt3, mt4, mt5); } 108 109 virtual void setNetworkID( uint32_t id ){ NetworkFunctionBase::setNetworkID( id ); idMap_[id] = this; } 110 static inline NetworkFunctionStatic* getNetworkFunction( uint32_t id){ assert( idMap_.find(id)!=idMap_.end() ); return idMap_[id]; } 111 static NetworkFunctionStatic* getFunction( uint32_t id ){ assert( idMap_.find(id) != idMap_.end() ); return idMap_[id]; } 112 static NetworkFunctionStatic* getFunction( const NetworkFunctionPointer& p ){ assert( functorMap_.find(p) != functorMap_.end() ); return functorMap_[p]; } 113 114 private: 115 static std::map<NetworkFunctionPointer, NetworkFunctionStatic*> functorMap_; 116 static std::map<uint32_t, NetworkFunctionStatic*> idMap_; 117 113 114 virtual void setNetworkID( uint32_t id ) 115 { NetworkFunctionBase::setNetworkID( id ); NetworkFunctionStatic::getIdMap()[id] = this; } 116 static inline NetworkFunctionStatic* getNetworkFunction( uint32_t id) 117 { assert( NetworkFunctionStatic::getIdMap().find(id)!=NetworkFunctionStatic::getIdMap().end() ); return NetworkFunctionStatic::getIdMap()[id]; } 118 static NetworkFunctionStatic* getFunction( uint32_t id ) 119 { assert( NetworkFunctionStatic::getIdMap().find(id) != NetworkFunctionStatic::getIdMap().end() ); return NetworkFunctionStatic::getIdMap()[id]; } 120 static NetworkFunctionStatic* getFunction( const NetworkFunctionPointer& p ) 121 { assert( NetworkFunctionStatic::getFunctorMap().find(p) != NetworkFunctionStatic::getFunctorMap().end() ); return NetworkFunctionStatic::getFunctorMap()[p]; } 122 123 private: 124 static std::map<NetworkFunctionPointer, NetworkFunctionStatic*>& getFunctorMap(); 125 static std::map<uint32_t, NetworkFunctionStatic*>& getIdMap(); 118 126 FunctorStatic* functor_; 119 127 120 128 }; 121 129 … … 125 133 NetworkMemberFunctionBase(const std::string& name, const NetworkFunctionPointer& p); 126 134 ~NetworkMemberFunctionBase(); 127 135 128 136 virtual void setNetworkID( uint32_t id ){ NetworkFunctionBase::setNetworkID( id ); idMap_[id] = this; } 129 137 static inline NetworkMemberFunctionBase* getNetworkFunction( uint32_t id){ assert( idMap_.find(id)!=idMap_.end() ); return idMap_[id]; } 130 138 static NetworkMemberFunctionBase* getFunction( uint32_t id ){ assert( idMap_.find(id) != idMap_.end() ); return idMap_[id]; } 131 139 static NetworkMemberFunctionBase* getFunction( const NetworkFunctionPointer& p ){ assert( functorMap_.find(p) != functorMap_.end() ); return functorMap_[p]; } 132 133 // 140 141 // 134 142 virtual void call(uint32_t objectID)=0; 135 143 virtual void call(uint32_t objectID, const MultiType& mt1)=0; … … 138 146 virtual void call(uint32_t objectID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4)=0; 139 147 virtual void call(uint32_t objectID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4, const MultiType& mt5)=0; 140 148 141 149 private: 142 150 static std::map<NetworkFunctionPointer, NetworkMemberFunctionBase*> functorMap_; … … 149 157 NetworkMemberFunction(FunctorMember<T>* functor, const std::string& name, const NetworkFunctionPointer& p); 150 158 ~NetworkMemberFunction(); 151 159 152 160 inline void call(uint32_t objectID) 153 { 161 { 154 162 if ( Synchronisable::getSynchronisable(objectID)!=0 ) 155 163 (*this->functor_)(orxonox_cast<T*>(Synchronisable::getSynchronisable(objectID))); 156 164 } 157 165 inline void call(uint32_t objectID, const MultiType& mt1) 158 { 166 { 159 167 if ( Synchronisable::getSynchronisable(objectID)!=0 ) 160 168 (*this->functor_)(orxonox_cast<T*>(Synchronisable::getSynchronisable(objectID)), mt1); 161 169 } 162 170 inline void call(uint32_t objectID, const MultiType& mt1, const MultiType& mt2) 163 { 171 { 164 172 if ( Synchronisable::getSynchronisable(objectID)!=0 ) 165 173 (*this->functor_)(orxonox_cast<T*>(Synchronisable::getSynchronisable(objectID)), mt1, mt2); 166 174 } 167 175 inline void call(uint32_t objectID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3) 168 { 176 { 169 177 if ( Synchronisable::getSynchronisable(objectID)!=0 ) 170 178 (*this->functor_)(orxonox_cast<T*>(Synchronisable::getSynchronisable(objectID)), mt1, mt2, mt3); 171 179 } 172 180 inline void call(uint32_t objectID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4) 173 { 181 { 174 182 if ( Synchronisable::getSynchronisable(objectID)!=0 ) 175 183 (*this->functor_)(orxonox_cast<T*>(Synchronisable::getSynchronisable(objectID)), mt1, mt2, mt3, mt4); 176 184 } 177 185 inline void call(uint32_t objectID, const MultiType& mt1, const MultiType& mt2, const MultiType& mt3, const MultiType& mt4, const MultiType& mt5) 178 { 186 { 179 187 if ( Synchronisable::getSynchronisable(objectID)!=0 ) 180 188 (*this->functor_)(orxonox_cast<T*>(Synchronisable::getSynchronisable(objectID)), mt1, mt2, mt3, mt4, mt5); 181 189 } 182 190 183 191 private: 184 192 FunctorMember<T>* functor_; -
code/branches/pickup2/src/libraries/network/NetworkPrereqs.h
r5929 r6412 144 144 template <class T> 145 145 class NetworkCallback; 146 template <class T, class U> 147 class NetworkCallbackNotify; 146 148 class NetworkCallbackBase; 147 149 class NetworkCallbackManager; -
code/branches/pickup2/src/libraries/network/Server.cc
r5929 r6412 137 137 // receive incoming packets 138 138 Connection::processQueue(); 139 139 140 140 if ( ClientInformation::hasClients() ) 141 141 { 142 142 // process incoming gamestates 143 143 GamestateManager::processGamestates(); 144 144 145 145 // send function calls to clients 146 146 FunctionCallManager::sendCalls(); 147 147 148 148 //this steers our network frequency 149 149 timeSinceLastUpdate_+=time.getDeltaTime(); … … 160 160 return ServerConnection::addPacket(packet, clientID); 161 161 } 162 163 /** 164 * @brief: returns ping time to client in milliseconds 162 163 /** 164 * @brief: returns ping time to client in milliseconds 165 165 */ 166 unsigned int Server::get Ping(unsigned int clientID){166 unsigned int Server::getRTT(unsigned int clientID){ 167 167 assert(ClientInformation::findClient(clientID)); 168 168 return ClientInformation::findClient(clientID)->getRTT(); 169 } 170 171 void Server::printRTT() 172 { 173 for( ClientInformation* temp=ClientInformation::getBegin(); temp!=0; temp=temp->next() ) 174 COUT(0) << "Round trip time to client with ID: " << temp->getID() << " is " << temp->getRTT() << " ms" << endl; 169 175 } 170 176 … … 299 305 { 300 306 //ServerConnection::disconnectClient( client ); 301 ClientConnectionListener::broadcastClientDisconnected( client->getID() );307 //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now 302 308 delete client; 303 309 } … … 311 317 } 312 318 COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl; 313 319 314 320 // synchronise class ids 315 321 syncClassid(temp->getID()); 316 322 317 323 // now synchronise functionIDs 318 324 packet::FunctionIDs *fIDs = new packet::FunctionIDs(); … … 320 326 bool b = fIDs->send(); 321 327 assert(b); 322 328 323 329 temp->setSynched(true); 324 330 COUT(4) << "sending welcome" << std::endl; … … 338 344 return true; 339 345 } 340 346 341 347 void Server::disconnectClient( ClientInformation *client ){ 342 348 ServerConnection::disconnectClient( client ); 343 349 GamestateManager::removeClient(client); 344 350 // inform all the listeners 345 ClientConnectionListener::broadcastClientDisconnected(client->getID());351 // ClientConnectionListener::broadcastClientDisconnected(client->getID()); // this is done in ClientInformation now 346 352 } 347 353 -
code/branches/pickup2/src/libraries/network/Server.h
r5929 r6412 57 57 bool queuePacket(ENetPacket *packet, int clientID); 58 58 void update(const Clock& time); 59 unsigned int getPing(unsigned int clientID); 59 unsigned int getRTT(unsigned int clientID); 60 virtual void printRTT(); 60 61 double getPacketLoss(unsigned int clientID); 61 62 protected: … … 65 66 unsigned int shipID(){return 0;} 66 67 unsigned int playerID(){return 0;} 67 68 68 69 void addPeer(ENetEvent *event); 69 70 void removePeer(ENetEvent *event); 70 71 71 72 bool createClient(int clientID); 72 73 void disconnectClient( ClientInformation *client); -
code/branches/pickup2/src/libraries/network/ServerConnection.cc
r5929 r6412 99 99 return true; 100 100 } 101 101 102 102 void ServerConnection::disconnectClient(ClientInformation *client) 103 103 { 104 104 Connection::disconnectPeer( client->getPeer() ); 105 105 } 106 106 107 107 void ServerConnection::disconnectClient(int clientID){ 108 108 ClientInformation *client = ClientInformation::findClient(clientID); -
code/branches/pickup2/src/libraries/network/ServerConnection.h
r5929 r6412 50 50 public: 51 51 ~ServerConnection(); 52 52 53 53 void setBindAddress( const std::string& bindAddress ); 54 54 void setPort( unsigned int port ); 55 55 56 56 bool openListener(); 57 57 bool closeListener(); -
code/branches/pickup2/src/libraries/network/TrafficControl.cc
r5781 r6412 64 64 *Initializing protected members 65 65 */ 66 67 68 69 70 71 72 66 TrafficControl *TrafficControl::instance_=0; 67 68 /** 69 * @brief Constructor: assures that only one reference will be created and sets the pointer 70 */ 71 TrafficControl::TrafficControl() 72 { 73 73 RegisterObject(TrafficControl); 74 75 74 assert(instance_==0); 75 instance_=this; 76 76 this->setConfigValues(); 77 78 79 80 81 82 83 84 85 77 } 78 79 /** 80 * @brief Destructor: resets the instance pointer to 0 81 */ 82 TrafficControl::~TrafficControl() 83 { 84 instance_=0; 85 } 86 86 87 87 /** … … 121 121 122 122 123 124 125 126 127 128 129 123 void TrafficControl::processObjectList(unsigned int clientID, unsigned int gamestateID, std::list<obj>& list) 124 { 125 currentClientID=clientID; 126 currentGamestateID=gamestateID; 127 evaluateList(clientID, list); 128 return; 129 } 130 130 131 131 TrafficControl *TrafficControl::getInstance() … … 135 135 } 136 136 137 138 137 void TrafficControl::ack(unsigned int clientID, unsigned int gamestateID) 138 { 139 139 if ( !this->bActive_ ) 140 140 return; 141 141 std::list<obj>::iterator itvec; // iterator to iterate through the acked objects 142 142 143 143 //assertions to make sure the maps already exist … … 145 145 assert(clientListPerm_.find(clientID) != clientListPerm_.end() ); 146 146 assert( clientListTemp_[clientID].find(gamestateID) != clientListTemp_[clientID].end() ); 147 147 148 148 // shortcut for maps 149 149 std::map<unsigned int, objInfo >& objectListPerm = clientListPerm_[clientID]; … … 151 151 152 152 for(itvec = objectListTemp[gamestateID].begin(); itvec != objectListTemp[gamestateID].end(); itvec++) 153 154 if(objectListPerm.find( (*itvec).objID) != objectListPerm.end()) // check whether the obj already exists in our lists155 { 156 objectListPerm[ (*itvec).objID].objCurGS = gamestateID;157 objectListPerm[ (*itvec).objID].objValueSched = 0; //set scheduling value back153 { 154 if(objectListPerm.find(itvec->objID) != objectListPerm.end()) // check whether the obj already exists in our lists 155 { 156 objectListPerm[itvec->objID].objCurGS = gamestateID; 157 objectListPerm[itvec->objID].objValueSched = 0; //set scheduling value back 158 158 } 159 159 else 160 160 { 161 161 assert(0); 162 objectListPerm[ (*itvec).objID].objCurGS = gamestateID;163 objectListPerm[ (*itvec).objID].objID = (*itvec).objID;164 objectListPerm[ (*itvec).objID].objCreatorID = (*itvec).objCreatorID;165 objectListPerm[ (*itvec).objID].objSize = (*itvec).objSize;166 } 167 168 162 objectListPerm[itvec->objID].objCurGS = gamestateID; 163 objectListPerm[itvec->objID].objID = itvec->objID; 164 objectListPerm[itvec->objID].objCreatorID = itvec->objCreatorID; 165 objectListPerm[itvec->objID].objSize = itvec->objSize; 166 } 167 } 168 // remove temporary list (with acked objects) from the map 169 169 objectListTemp.erase( objectListTemp.find(gamestateID) ); 170 170 } 171 171 172 172 /** … … 174 174 */ 175 175 176 177 178 179 180 181 182 176 /** 177 *updateClientListPerm 178 *returns void 179 */ 180 void TrafficControl::insertinClientListPerm(unsigned int clientID, obj objinf) 181 { 182 std::map<unsigned int,std::map<unsigned int, objInfo> >::iterator itperm;//iterator clientListPerm over clientIDs 183 183 unsigned int gsid=GAMESTATEID_INITIAL, gsdiff=currentGamestateID, prioperm=Synchronisable::getSynchronisable(objinf.objID)->getPriority(), priomom=0; 184 184 clientListPerm_[clientID][objinf.objID] = objInfo(objinf.objID, objinf.objCreatorID,gsid,gsdiff, objinf.objSize,prioperm,priomom); 185 185 } 186 186 187 187 /** … … 205 205 for(itvec = list.begin(); itvec != list.end();) 206 206 { 207 assert( (*itvec).objSize < 1000);208 if ( ( size + (*itvec).objSize ) < targetsize )209 { 210 size += (*itvec).objSize;//objSize is given in bytes207 assert( itvec->objSize < 1000); 208 if ( ( size + itvec->objSize ) < targetsize ) 209 { 210 size += itvec->objSize;//objSize is given in bytes 211 211 ++itvec; 212 212 } 213 213 else 214 214 { 215 clientListPerm_[currentClientID][ (*itvec).objID].objValueSched += SCHED_PRIORITY_OFFSET; // NOTE: SCHED_PRIORITY_OFFSET is negative215 clientListPerm_[currentClientID][itvec->objID].objValueSched += SCHED_PRIORITY_OFFSET; // NOTE: SCHED_PRIORITY_OFFSET is negative 216 216 list.erase(itvec, list.end()); 217 217 break; … … 223 223 224 224 225 226 227 228 229 225 /** 226 *evaluateList evaluates whether new obj are there, whether there are things to be updatet and manipulates all this. 227 */ 228 void TrafficControl::evaluateList(unsigned int clientID, std::list<obj>& list) 229 { 230 230 231 231 if( bActive_ ) … … 236 236 //if listToProcess contains new Objects, add them to clientListPerm 237 237 std::list<obj>::iterator itvec; 238 238 239 239 std::map<unsigned int, objInfo >& objectListPerm = clientListPerm_[clientID]; 240 240 241 241 for( itvec=list.begin(); itvec != list.end(); itvec++) 242 242 { 243 if ( objectListPerm.find( (*itvec).objID) != objectListPerm.end() )243 if ( objectListPerm.find( itvec->objID) != objectListPerm.end() ) 244 244 { 245 245 // we already have the object in our map 246 246 //obj bleibt in liste und permanente prio wird berechnet 247 objectListPerm[ (*itvec).objID].objDiffGS = currentGamestateID - objectListPerm[(*itvec).objID].objCurGS;247 objectListPerm[itvec->objID].objDiffGS = currentGamestateID - objectListPerm[itvec->objID].objCurGS; 248 248 continue;//check next objId 249 249 } … … 256 256 } 257 257 //end compare listToProcess vs clientListPerm 258 258 259 259 //sort copied list according to priorities 260 260 // use boost bind here because we need to pass a memberfunction to stl sort 261 261 // sort( list.begin(), list.end(), boost::bind(&TrafficControl::prioritySort, this, clientID, _1, _2) ); 262 262 list.sort( boost::bind(&TrafficControl::prioritySort, this, clientID, _1, _2) ); 263 263 264 264 // list.sort(boost::bind(&TrafficControl::prioritySort, this, clientID, _1, _2) ); 265 265 … … 277 277 // sort(list.begin(), list.end(), boost::bind(&TrafficControl::dataSort, this, _1, _2) ); 278 278 list.sort( boost::bind(&TrafficControl::dataSort, this, _1, _2) ); 279 279 280 280 //diese Funktion updateClientList muss noch gemacht werden 281 281 updateClientListTemp(list); … … 289 289 COUT(0) << "=========== Objectlist ===========" << endl; 290 290 for( it=list.begin(); it!=list.end(); it++) 291 COUT(0) << "ObjectID: " << (*it).objID << " creatorID: " << (*it).objCreatorID << " Priority: " << clientListPerm_[clientID][(*it).objID].objValuePerm + clientListPerm_[clientID][(*it).objID].objValueSched << " size: " << (*it).objSize << endl;291 COUT(0) << "ObjectID: " << it->objID << " creatorID: " << it->objCreatorID << " Priority: " << clientListPerm_[clientID][it->objID].objValuePerm + clientListPerm_[clientID][it->objID].objValueSched << " size: " << it->objSize << endl; 292 292 } 293 293 294 294 void TrafficControl::fixCreatorDependencies(std::list<obj>::iterator it1, std::list<obj>& list, unsigned int clientID) 295 295 { 296 if ( (*it1).objCreatorID == OBJECTID_UNKNOWN )297 return; 298 if( clientListPerm_[clientID][ (*it1).objCreatorID].objCurGS != GAMESTATEID_INITIAL )296 if ( it1->objCreatorID == OBJECTID_UNKNOWN ) 297 return; 298 if( clientListPerm_[clientID][it1->objCreatorID].objCurGS != GAMESTATEID_INITIAL ) 299 299 return; 300 300 std::list<obj>::iterator it2, it3=it1; 301 301 for( it2 = ++it3; it2 != list.end(); it2++ ) 302 302 { 303 if( (*it2).objID == (*it1).objCreatorID )303 if( it2->objID == it1->objCreatorID ) 304 304 { 305 305 it3 = list.insert(it1, *it2); //insert creator before it1 -
code/branches/pickup2/src/libraries/network/TrafficControl.h
r5781 r6412 69 69 obj( uint32_t ID, uint32_t creatorID, uint32_t size, uint32_t offset ); 70 70 }; 71 71 72 72 73 73 … … 97 97 unsigned int targetSize; 98 98 bool bActive_; 99 99 100 100 void insertinClientListPerm(unsigned int clientID, obj objinf); 101 101 102 102 void cut(std::list<obj>& list, unsigned int targetsize); 103 103 void updateClientListTemp(std::list<obj>& list);//done … … 105 105 *evaluates Data given (list) and produces result(->Data to be updated) 106 106 */ 107 void evaluateList(unsigned int clientID, std::list<obj>& list);//done 107 void evaluateList(unsigned int clientID, std::list<obj>& list);//done 108 108 void ack(unsigned int clientID, unsigned int gamestateID); // this function gets called when the server receives an ack from the client 109 109 110 110 //ClientConnectionListener functions 111 111 virtual void clientConnected(unsigned int clientID){}; 112 112 virtual void clientDisconnected(unsigned int clientID); 113 113 114 114 115 115 protected: 116 116 static TrafficControl *instance_; … … 121 121 /** 122 122 *is being used by GSManager from Server: 123 *list contains: ObjIds, CreatorIds, Size (in this order) from Client XY 123 *list contains: ObjIds, CreatorIds, Size (in this order) from Client XY 124 124 *Elements of list are accessed by *list[i] 125 125 *Elements of struct i are therefore: *list[i].objID … … 130 130 static void processAck(unsigned int clientID, unsigned int gamestateID) 131 131 { return instance_->ack(clientID, gamestateID); } 132 void deleteObject(unsigned int objectID); 133 132 void deleteObject(unsigned int objectID); // this function gets called when an object has been deleted (in order to clean up lists and maps) 133 134 134 bool prioritySort(uint32_t clientID, obj i, obj j); 135 135 bool dataSort(obj i, obj j); -
code/branches/pickup2/src/libraries/network/packet/Acknowledgement.cc
r5781 r6412 38 38 #define _PACKETID 0 39 39 #define _ACKID _PACKETID + sizeof(packet::Type::Value) 40 40 41 41 Acknowledgement::Acknowledgement( unsigned int id, unsigned int clientID ) 42 42 : Packet() -
code/branches/pickup2/src/libraries/network/packet/Acknowledgement.h
r5781 r6412 37 37 namespace packet { 38 38 /** 39 39 @author 40 40 */ 41 41 class _NetworkExport Acknowledgement : public Packet -
code/branches/pickup2/src/libraries/network/packet/Chat.cc
r5781 r6412 35 35 namespace orxonox { 36 36 namespace packet { 37 37 38 38 #define PACKET_FLAGS_CHAT PacketFlag::Reliable 39 39 #define _PACKETID 0 -
code/branches/pickup2/src/libraries/network/packet/Chat.h
r5781 r6412 36 36 namespace packet { 37 37 /** 38 38 @author 39 39 */ 40 40 class _NetworkExport Chat : public Packet -
code/branches/pickup2/src/libraries/network/packet/ClassID.cc
r5929 r6412 48 48 ClassID::ClassID( ) : Packet(){ 49 49 Identifier *id; 50 std::string classname;51 50 unsigned int nrOfClasses=0; 52 51 unsigned int packetSize=2*sizeof(uint32_t); //space for the packetID and for the nrofclasses … … 58 57 std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin(); 59 58 for(;it != Identifier::getStringIdentifierMapEnd();++it){ 60 id = (*it).second;59 id = it->second; 61 60 if(id == NULL || !id->hasFactory()) 62 61 continue; 63 c lassname = id->getName();62 const std::string& classname = id->getName(); 64 63 network_id = id->getNetworkID(); 65 64 // now push the network id and the classname to the stack -
code/branches/pickup2/src/libraries/network/packet/ClassID.h
r5781 r6412 36 36 namespace packet { 37 37 38 38 39 39 /** 40 40 @author 41 41 */ 42 42 class _NetworkExport ClassID : public Packet -
code/branches/pickup2/src/libraries/network/packet/DeleteObjects.cc
r5781 r6412 41 41 #define _QUANTITY _PACKETID + sizeof(Type::Value) 42 42 #define _OBJECTIDS _QUANTITY + sizeof(uint32_t) 43 43 44 44 DeleteObjects::DeleteObjects() 45 45 : Packet() … … 71 71 for(unsigned int i=0; i<number; i++){ 72 72 unsigned int temp = Synchronisable::popDeletedObject(); 73 // assert(temp<10000); //ugly hack74 73 *reinterpret_cast<uint32_t*>(tdata) = temp; 75 COUT(4) << temp << " ";74 COUT(4) << temp << ' '; 76 75 tdata += sizeof(uint32_t); 77 76 } -
code/branches/pickup2/src/libraries/network/packet/DeleteObjects.h
r5781 r6412 35 35 namespace packet { 36 36 /** 37 37 @author 38 38 */ 39 39 class _NetworkExport DeleteObjects : public Packet -
code/branches/pickup2/src/libraries/network/packet/FunctionCalls.cc
r5781 r6412 36 36 namespace orxonox { 37 37 namespace packet { 38 38 39 39 #define PACKET_FLAGS_FUNCTIONCALLS PacketFlag::Reliable 40 40 #define _PACKETID 0 41 41 const unsigned int FUNCTIONCALLS_MEM_ALLOCATION = 1000; 42 42 43 43 FunctionCalls::FunctionCalls() 44 44 : Packet() … … 171 171 void FunctionCalls::addCallStatic( uint32_t networkID, const MultiType* mt1, const MultiType* mt2, const MultiType* mt3, const MultiType* mt4, const MultiType* mt5){ 172 172 assert(!isDataENetAllocated()); 173 173 174 174 // first determine the size that has to be reserved for this call 175 175 uint32_t callsize = 2*sizeof(uint32_t)+sizeof(uint8_t); //size for network-function-id and nrOfArguments and for bool isStatic … … 200 200 } 201 201 } 202 202 203 203 // now allocated mem if neccessary 204 204 if( currentSize_ + callsize > currentMemBlocks_*FUNCTIONCALLS_MEM_ALLOCATION ) … … 210 210 data_ = temp; 211 211 } 212 212 213 213 // now serialise the mt values and copy the function id and isStatic 214 214 uint8_t* temp = data_+currentSize_; … … 240 240 //currentSize_ += callsize; 241 241 currentSize_ = temp-data_; 242 242 243 243 } 244 244 245 245 void FunctionCalls::addCallMember( uint32_t networkID, uint32_t objectID, const MultiType* mt1, const MultiType* mt2, const MultiType* mt3, const MultiType* mt4, const MultiType* mt5){ 246 246 assert(!isDataENetAllocated()); 247 247 248 248 // first determine the size that has to be reserved for this call 249 249 uint32_t callsize = 3*sizeof(uint32_t)+sizeof(uint8_t); //size for network-function-id and nrOfArguments and the objectID … … 274 274 } 275 275 } 276 276 277 277 // now allocated mem if neccessary 278 278 if( currentSize_ + callsize > currentMemBlocks_*FUNCTIONCALLS_MEM_ALLOCATION ) … … 284 284 data_ = temp; 285 285 } 286 286 287 287 // now serialise the mt values and copy the function id 288 288 uint8_t* temp = data_+currentSize_; … … 314 314 } 315 315 currentSize_ += callsize; 316 316 317 317 } 318 318 -
code/branches/pickup2/src/libraries/network/packet/FunctionCalls.h
r5781 r6412 40 40 namespace packet { 41 41 /** 42 42 @author 43 43 */ 44 44 -
code/branches/pickup2/src/libraries/network/packet/FunctionIDs.cc
r5781 r6412 47 47 48 48 FunctionIDs::FunctionIDs( ) : Packet(){ 49 std::string functionname; 50 unsigned int nrOfFunctions=0; 49 unsigned int nrOfFunctions=0; 51 50 unsigned int packetSize=2*sizeof(uint32_t); //space for the packetID and for the nroffunctions 52 51 uint32_t networkID; 53 52 flags_ = flags_ | PACKET_FLAGS_FUNCTIONIDS; 54 53 std::queue<std::pair<uint32_t, std::string> > tempQueue; 55 54 56 55 //calculate total needed size (for all strings and integers) 57 56 ObjectList<NetworkFunctionBase>::iterator it; 58 57 for(it = ObjectList<NetworkFunctionBase>::begin(); it; ++it){ 59 functionname = it->getName();58 const std::string& functionname = it->getName(); 60 59 networkID = it->getNetworkID(); 61 60 // now push the network id and the classname to the stack … … 64 63 packetSize += (functionname.size()+1)+sizeof(uint32_t)+sizeof(uint32_t); // reserver size for the functionname string, the functionname length and the networkID 65 64 } 66 65 67 66 this->data_=new uint8_t[ packetSize ]; 68 67 //set the appropriate packet id 69 68 assert(this->data_); 70 69 *(Type::Value *)(this->data_ + _PACKETID ) = Type::FunctionIDs; 71 70 72 71 uint8_t *temp=data_+sizeof(uint32_t); 73 72 // save the number of all classes 74 73 *(uint32_t*)temp = nrOfFunctions; 75 74 temp += sizeof(uint32_t); 76 75 77 76 // now save all classids and classnames 78 77 std::pair<uint32_t, std::string> tempPair; … … 85 84 temp+=2*sizeof(uint32_t)+tempPair.second.size()+1; 86 85 } 87 86 88 87 COUT(5) << "FunctionIDs packetSize is " << packetSize << endl; 89 88 90 89 } 91 90 … … 106 105 temp += sizeof(uint32_t); 107 106 totalsize += sizeof(uint32_t); // storage size for nr of all classes 108 107 109 108 for(unsigned int i=0; i<nrOfFunctions; i++){ 110 109 totalsize += 2*sizeof(uint32_t) + *(uint32_t*)(temp + sizeof(uint32_t)); // for each network function add size for id, sizeof(string) and length of string itself to totalsize … … 121 120 uint32_t stringsize; 122 121 unsigned char *functionname; 123 122 124 123 COUT(4) << "=== processing functionids: " << endl; 125 124 std::pair<uint32_t, std::string> tempPair; … … 127 126 nrOfFunctions = *(uint32_t*)temp; 128 127 temp += sizeof(uint32_t); 129 128 130 129 for( int i=0; i<nrOfFunctions; i++){ 131 130 networkID = *(uint32_t*)temp; -
code/branches/pickup2/src/libraries/network/packet/FunctionIDs.h
r5781 r6412 36 36 namespace packet { 37 37 38 38 39 39 /** 40 40 @author 41 41 */ 42 42 class _NetworkExport FunctionIDs : public Packet -
code/branches/pickup2/src/libraries/network/packet/Gamestate.cc
r5929 r6412 95 95 return false; 96 96 } 97 97 98 98 // create the header object 99 99 assert( header_ == 0 ); … … 105 105 ObjectList<Synchronisable>::iterator it; 106 106 for(it = ObjectList<Synchronisable>::begin(); it; ++it){ 107 107 108 108 // tempsize=it->getSize(id, mode); 109 109 … … 111 111 if ( tempsize != 0 ) 112 112 dataVector_.push_back( obj(it->getObjectID(), it->getCreatorID(), tempsize, mem-data_) ); 113 113 114 114 #ifndef NDEBUG 115 115 if(currentsize+tempsize > size){ … … 362 362 assert(!header_->isCompressed() && !base->header_->isCompressed()); 363 363 assert(!header_->isDiffed()); 364 364 365 365 uint8_t *basep = GAMESTATE_START(base->data_); 366 366 uint8_t *gs = GAMESTATE_START(this->data_); 367 367 uint32_t dest_length = header_->getDataSize(); 368 368 369 369 if(dest_length==0) 370 370 return NULL; 371 371 372 372 uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()]; 373 373 uint8_t *dest = GAMESTATE_START(ndata); 374 374 375 375 rawDiff( dest, gs, basep, header_->getDataSize(), base->header_->getDataSize() ); 376 376 #ifndef NDEBUG … … 398 398 assert(!header_->isCompressed() && !base->header_->isCompressed()); 399 399 assert(header_->isDiffed()); 400 400 401 401 uint8_t *basep = GAMESTATE_START(base->data_); 402 402 uint8_t *gs = GAMESTATE_START(this->data_); 403 403 uint32_t dest_length = header_->getDataSize(); 404 404 405 405 if(dest_length==0) 406 406 return NULL; 407 407 408 408 uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()]; 409 409 uint8_t *dest = ndata + GamestateHeader::getSize(); 410 410 411 411 rawDiff( dest, gs, basep, header_->getDataSize(), base->header_->getDataSize() ); 412 412 413 413 Gamestate *g = new Gamestate(ndata, getClientID()); 414 414 assert(g->header_); … … 437 437 // uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()]; 438 438 // uint8_t *dest = ndata + GamestateHeader::getSize(); 439 // 440 // 439 // 440 // 441 441 // // LOOP-UNROLLED DIFFING 442 442 // uint32_t *dest32 = (uint32_t*)dest, *base32 = (uint32_t*)basep, *gs32 = (uint32_t*)gs; … … 465 465 // } 466 466 // } 467 // 467 // 468 468 // Gamestate *g = new Gamestate(ndata, getClientID()); 469 469 // *(g->header_) = *header_; … … 481 481 uint64_t* bd = (uint64_t*)basedata; 482 482 uint64_t* nd = (uint64_t*)newdata; 483 483 484 484 unsigned int i; 485 485 for( i=0; i<datalength/8; i++ ) … … 529 529 // COUT(0) << "myvector contains:"; 530 530 // for ( itt=dataVector_.begin() ; itt!=dataVector_.end(); itt++ ) 531 // COUT(0) << " "<< (*itt).objID;531 // COUT(0) << ' ' << (*itt).objID; 532 532 // COUT(0) << endl; 533 533 for(it=dataVector_.begin(); it!=dataVector_.end();){ 534 534 SynchronisableHeader oldobjectheader(origdata); 535 535 SynchronisableHeader newobjectheader(newdata); 536 if ( (*it).objSize == 0 )536 if ( it->objSize == 0 ) 537 537 { 538 538 ++it; … … 541 541 objectsize = oldobjectheader.getDataSize(); 542 542 objectOffset=SynchronisableHeader::getSize(); //skip the size and the availableData variables in the objectheader 543 if ( (*it).objID == oldobjectheader.getObjectID() ){543 if ( it->objID == oldobjectheader.getObjectID() ){ 544 544 memcpy(newdata, origdata, objectsize); 545 545 assert(newobjectheader.isDataAvailable()==true); -
code/branches/pickup2/src/libraries/network/packet/Gamestate.h
r5781 r6412 96 96 97 97 /** 98 98 @author Oliver Scheuss 99 99 */ 100 100 class _NetworkExport Gamestate: public Packet{ -
code/branches/pickup2/src/libraries/network/packet/Packet.cc
r5781 r6412 101 101 @brief 102 102 Destroys a packet completely. 103 104 That also means destroying the ENetPacket if one exists. There 103 104 That also means destroying the ENetPacket if one exists. There 105 105 */ 106 106 Packet::~Packet(){ … … 230 230 */ 231 231 void Packet::deletePacket(ENetPacket *enetPacket){ 232 // Get our Packet from a glo abal map with all Packets created in the send() method of Packet.232 // Get our Packet from a global map with all Packets created in the send() method of Packet. 233 233 std::map<size_t, Packet*>::iterator it = packetMap_.find(reinterpret_cast<size_t>(enetPacket)); 234 234 assert(it != packetMap_.end()); -
code/branches/pickup2/src/libraries/network/packet/Packet.h
r5781 r6412 57 57 58 58 /** 59 59 @author Oliver Scheuss <scheusso [at] ee.ethz.ch> 60 60 */ 61 61 class _NetworkExport Packet{ -
code/branches/pickup2/src/libraries/network/packet/Welcome.h
r5781 r6412 36 36 37 37 /** 38 38 @author 39 39 */ 40 40 class _NetworkExport Welcome : public Packet -
code/branches/pickup2/src/libraries/network/synchronisable/CMakeLists.txt
r5781 r6412 2 2 NetworkCallbackManager.cc 3 3 Synchronisable.cc 4 SynchronisableSpecialisations.cc5 4 SynchronisableVariable.cc 6 5 ) -
code/branches/pickup2/src/libraries/network/synchronisable/NetworkCallback.h
r5781 r6412 33 33 #include "network/NetworkPrereqs.h" 34 34 #include "NetworkCallbackManager.h" 35 // #include "util/MultiType.h" 35 36 36 37 namespace orxonox{ 37 38 39 struct EmptyType{}; 40 38 41 class _NetworkExport NetworkCallbackBase 39 42 { … … 49 52 public: 50 53 NetworkCallback(T* object, void (T::*function) (void)) : object_(object), function_(function) {} 51 54 virtual ~NetworkCallback() {} 52 55 virtual void call() 53 56 { (this->object_->*function_)(); } … … 58 61 }; 59 62 63 template <class T, class U> 64 class NetworkCallbackNotify: public NetworkCallbackBase 65 { 66 public: 67 NetworkCallbackNotify(T* object, void (T::*function) (const U&)) : object_(object), function_(function) {} 68 NetworkCallbackNotify() {} 69 virtual ~NetworkCallbackNotify() {} 70 virtual void call() 71 { (this->object_->*function_)( this->oldValue_ ); } 72 void setOldValue(const U& value){ this->oldValue_ = value; } 73 private: 74 T* object_; 75 U oldValue_; 76 void (T::*function_) (const U&); 77 }; 78 60 79 } 61 80 -
code/branches/pickup2/src/libraries/network/synchronisable/NetworkCallbackManager.cc
r5781 r6412 26 26 * 27 27 */ 28 28 29 29 #include "NetworkCallbackManager.h" 30 30 #include "NetworkCallback.h" 31 31 32 32 namespace orxonox{ 33 33 34 34 std::set<NetworkCallbackBase*> NetworkCallbackManager::callbackSet_; 35 35 std::queue<NetworkCallbackBase*> NetworkCallbackManager::triggeredCallbacks_; 36 36 37 37 void NetworkCallbackManager::registerCallback(NetworkCallbackBase *cb) 38 { 39 callbackSet_.insert(cb); 38 { 39 callbackSet_.insert(cb); 40 40 } 41 41 void NetworkCallbackManager::deleteCallback(NetworkCallbackBase *cb) … … 48 48 } 49 49 } 50 50 51 51 void NetworkCallbackManager::triggerCallback(NetworkCallbackBase *cb) 52 52 { -
code/branches/pickup2/src/libraries/network/synchronisable/NetworkCallbackManager.h
r5781 r6412 37 37 38 38 namespace orxonox{ 39 39 40 40 class _NetworkExport NetworkCallbackManager{ 41 41 public: … … 48 48 static std::queue<NetworkCallbackBase*> triggeredCallbacks_; 49 49 }; 50 50 51 51 52 52 } -
code/branches/pickup2/src/libraries/network/synchronisable/Synchronisable.cc
r5929 r6412 62 62 } 63 63 classID_ = static_cast<uint32_t>(-1); 64 64 65 65 // set dataSize to 0 66 66 this->dataSize_ = 0; … … 277 277 //tempsize += (*i)->getSize( mode ); 278 278 } 279 279 280 280 tempsize += SynchronisableHeader::getSize(); 281 281 header.setObjectID( this->objectID_ ); … … 284 284 header.setDataAvailable( true ); 285 285 header.setDataSize( tempsize ); 286 286 287 287 #ifndef NDEBUG 288 288 uint32_t size; … … 390 390 } 391 391 392 template <> void Synchronisable::registerVariable( std::string& variable, uint8_t mode, NetworkCallbackBase *cb, bool bidirectional) 393 { 394 SynchronisableVariableBase* sv; 395 if (bidirectional) 396 sv = new SynchronisableVariableBidirectional<std::string>(variable, mode, cb); 397 else 398 sv = new SynchronisableVariable<std::string>(variable, mode, cb); 399 syncList.push_back(sv); 400 stringList.push_back(sv); 401 } 402 392 403 393 404 } -
code/branches/pickup2/src/libraries/network/synchronisable/Synchronisable.h
r5929 r6412 66 66 67 67 /** 68 * @brief: stores information about a Synchronisable 69 * 68 * @brief: stores information about a Synchronisable 69 * 70 70 * This class stores the information about a Synchronisable (objectID_, classID_, creatorID_, dataSize) 71 71 * in an emulated bitset. … … 132 132 inline unsigned int getPriority() const { return this->objectFrequency_;} 133 133 inline uint8_t getSyncMode() const { return this->objectMode_; } 134 134 135 135 void setSyncMode(uint8_t mode); 136 136 … … 138 138 Synchronisable(BaseObject* creator); 139 139 template <class T> void registerVariable(T& variable, uint8_t mode=0x1, NetworkCallbackBase *cb=0, bool bidirectional=false); 140 //template <class T> void unregisterVariable(T& var); 140 141 141 void setPriority(unsigned int freq){ objectFrequency_ = freq; } 142 142 … … 148 148 bool isMyData(uint8_t* mem); 149 149 bool doSync(int32_t id, uint8_t mode=0x0); 150 150 151 151 inline void setObjectID(uint32_t id){ this->objectID_ = id; objectMap_[this->objectID_] = this; } 152 152 inline void setClassID(uint32_t id){ this->classID_ = id; } … … 167 167 }; 168 168 169 // ================= Specialisation declarations170 171 // template <> _NetworkExport void Synchronisable::registerVariable( const std::string& variable, uint8_t mode, NetworkCallbackBase *cb, bool bidirectional);172 template <> _NetworkExport void Synchronisable::registerVariable( std::string& variable, uint8_t mode, NetworkCallbackBase *cb, bool bidirectional);173 template <> _NetworkExport void Synchronisable::registerVariable( const ColourValue& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);174 template <> _NetworkExport void Synchronisable::registerVariable( ColourValue& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);175 template <> _NetworkExport void Synchronisable::registerVariable( const Vector2& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);176 template <> _NetworkExport void Synchronisable::registerVariable( Vector2& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);177 template <> _NetworkExport void Synchronisable::registerVariable( const Vector3& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);178 template <> _NetworkExport void Synchronisable::registerVariable( Vector3& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);179 template <> _NetworkExport void Synchronisable::registerVariable( const Vector4& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);180 template <> _NetworkExport void Synchronisable::registerVariable( Vector4& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);181 template <> _NetworkExport void Synchronisable::registerVariable( mbool& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);182 template <> _NetworkExport void Synchronisable::registerVariable( const Quaternion& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);183 template <> _NetworkExport void Synchronisable::registerVariable( Quaternion& variable, uint8_t mode, NetworkCallbackBase* cb, bool bidirectional);184 185 169 template <class T> void Synchronisable::registerVariable(T& variable, uint8_t mode, NetworkCallbackBase *cb, bool bidirectional) 186 170 { 187 171 if (bidirectional) 188 172 { 189 syncList.push_back(new SynchronisableVariableBidirectional< constT>(variable, mode, cb));173 syncList.push_back(new SynchronisableVariableBidirectional<T>(variable, mode, cb)); 190 174 this->dataSize_ += syncList.back()->getSize(state_); 191 175 } 192 176 else 193 177 { 194 syncList.push_back(new SynchronisableVariable< constT>(variable, mode, cb));178 syncList.push_back(new SynchronisableVariable<T>(variable, mode, cb)); 195 179 if ( this->state_ == mode ) 196 180 this->dataSize_ += syncList.back()->getSize(state_); 197 181 } 198 182 } 199 183 184 template <> _NetworkExport void Synchronisable::registerVariable( std::string& variable, uint8_t mode, NetworkCallbackBase *cb, bool bidirectional); 200 185 201 186 202 // template <class T> void Synchronisable::unregisterVariable(T& var){203 // std::vector<SynchronisableVariableBase*>::iterator it = syncList.begin();204 // while(it!=syncList.end()){205 // if( ((*it)->getReference()) == &var ){206 // delete (*it);207 // syncList.erase(it);208 // return;209 // }210 // else211 // it++;212 // }213 // bool unregistered_nonexistent_variable = false;214 // assert(unregistered_nonexistent_variable); //if we reach this point something went wrong:215 // // the variable has not been registered before216 // }217 218 219 187 } 220 188 -
code/branches/pickup2/src/libraries/network/synchronisable/SynchronisableVariable.h
r5781 r6412 35 35 #include <cassert> 36 36 #include <cstring> 37 #include " util/Serialise.h"37 #include "Serialise.h" 38 38 #include "util/TypeTraits.h" 39 39 #include "core/GameMode.h" … … 41 41 42 42 namespace orxonox{ 43 43 44 44 namespace VariableDirection{ 45 45 enum Value{ … … 54 54 }; 55 55 } 56 56 57 57 class _NetworkExport SynchronisableVariableBase 58 58 { … … 81 81 virtual inline void* getReference(){ return static_cast<void*>(const_cast<typename Loki::TypeTraits<T>::UnqualifiedType*>(&this->variable_)); } 82 82 protected: 83 84 T& variable_; 85 uint8_t mode_; 86 NetworkCallbackBase *callback_; 83 T& variable_; 84 uint8_t mode_; 85 NetworkCallbackBase *callback_; 87 86 }; 88 87 89 88 template <class T> 90 89 class SynchronisableVariableBidirectional: public SynchronisableVariable<T> … … 93 92 SynchronisableVariableBidirectional(T& variable, uint8_t master=Bidirectionality::ServerMaster, NetworkCallbackBase *cb=0); 94 93 virtual ~SynchronisableVariableBidirectional(); 95 94 96 95 virtual inline uint8_t getMode(){ return 0x3; } //this basically is a hack ^^ 97 96 virtual inline uint32_t getData(uint8_t*& mem, uint8_t mode); … … 113 112 } 114 113 } 115 114 116 115 template <class T> SynchronisableVariable<T>::~SynchronisableVariable() 117 116 { 118 if (this->callback_ != 0)117 if (this->callback_) 119 118 { 120 119 NetworkCallbackManager::deleteCallback(this->callback_); //safe call for deletion … … 141 140 return; 142 141 // check whether we need to consider a callback 143 if ( this->callback_ != 0 ) 144 { 145 if( forceCallback || !checkEquality( this->variable_, mem ) ) 146 callback = true; 142 if ( this->callback_ ) 143 { 144 callback = forceCallback || !checkEquality( this->variable_, mem ); 145 } 146 // now do a callback if neccessary 147 if ( callback ) 148 { 149 NetworkCallbackManager::triggerCallback( this->callback_ ); 147 150 } 148 151 // write the data 149 152 loadAndIncrease( this->variable_, mem ); 150 // now do a callback if neccessary151 if ( callback )152 NetworkCallbackManager::triggerCallback( this->callback_ );153 153 } 154 154 … … 216 216 mem += sizeof(varReference_); 217 217 memcpy(static_cast<void*>(const_cast<typename Loki::TypeTraits<T>::UnqualifiedType*>(&this->varBuffer_)), &this->variable_, sizeof(T)); 218 if ( this->callback_ != 0)218 if ( this->callback_ ) 219 219 callback = true; 220 220 } … … 235 235 { 236 236 // value changed so remark for callback 237 if ( this->callback_ != 0)237 if ( this->callback_ ) 238 238 callback = true; 239 239 } 240 240 } 241 241 } 242 // now do a callback if neccessary 243 if ( callback ) 244 { 245 NetworkCallbackManager::triggerCallback( this->callback_ ); 246 } 242 247 // now write the data 243 248 loadAndIncrease(this->variable_, mem); 244 // now do a callback if neccessary245 if ( callback )246 NetworkCallbackManager::triggerCallback( this->callback_ );247 249 } 248 250 … … 251 253 return returnSize( this->variable_ ) + sizeof(varReference_); 252 254 } 253 255 254 256 255 257 } -
code/branches/pickup2/src/libraries/tools/BillboardSet.cc
r5781 r6412 38 38 #include "util/Convert.h" 39 39 #include "util/Math.h" 40 #include "util/StringUtils.h"41 40 #include "core/GameMode.h" 42 41 … … 81 80 catch (...) 82 81 { 83 COUT(1) << "Error: Couln't load billboard \"" << file << "\""<< std::endl;82 COUT(1) << "Error: Couln't load billboard \"" << file << '"' << std::endl; 84 83 this->billboardSet_ = 0; 85 84 } … … 104 103 catch (...) 105 104 { 106 COUT(1) << "Error: Couln't load billboard \"" << file << "\""<< std::endl;105 COUT(1) << "Error: Couln't load billboard \"" << file << '"' << std::endl; 107 106 this->billboardSet_ = 0; 108 107 } -
code/branches/pickup2/src/libraries/tools/CMakeLists.txt
r5929 r6412 23 23 LINK_LIBRARIES 24 24 core 25 network 25 26 SOURCE_FILES ${TOOLS_SRC_FILES} 26 27 ) -
code/branches/pickup2/src/libraries/tools/Mesh.cc
r5781 r6412 36 36 37 37 #include "util/Convert.h" 38 #include "util/StringUtils.h"39 38 #include "core/GameMode.h" 40 39 … … 84 83 catch (...) 85 84 { 86 COUT(1) << "Error: Couln't load mesh \"" << meshsource << "\""<< std::endl;85 COUT(1) << "Error: Couln't load mesh \"" << meshsource << '"' << std::endl; 87 86 this->entity_ = 0; 88 87 } -
code/branches/pickup2/src/libraries/tools/ParticleInterface.cc
r5781 r6412 64 64 this->bAllowedByLOD_ = true; 65 65 this->speedFactor_ = 1.0f; 66 67 this->setDetailLevel(static_cast<unsigned int>(detaillevel)); 68 69 this->setConfigValues(); 66 70 67 71 if (GameMode::showsGraphics()) … … 74 78 catch (...) 75 79 { 76 COUT(1) << "Error: Couln't load particle system \"" << templateName << "\""<< std::endl;80 COUT(1) << "Error: Couln't load particle system \"" << templateName << '"' << std::endl; 77 81 this->particleSystem_ = 0; 78 82 } 79 83 } 80 81 this->setDetailLevel(static_cast<unsigned int>(detaillevel));82 84 } 83 85 -
code/branches/pickup2/src/libraries/tools/ResourceCollection.h
r5781 r6412 38 38 namespace orxonox 39 39 { 40 class ResourceLocation;41 42 40 class _ToolsExport ResourceCollection : public BaseObject 43 41 { -
code/branches/pickup2/src/libraries/tools/ResourceLocation.cc
r5929 r6412 92 92 { 93 93 // Remove from Ogre paths 94 resourceGroup_. erase();94 resourceGroup_.clear(); 95 95 try 96 96 { -
code/branches/pickup2/src/libraries/tools/Shader.cc
r5781 r6412 57 57 this->bLoadCompositor_ = GameMode::showsGraphics(); 58 58 this->bViewportInitialized_ = false; 59 this->compositor_ = "";60 this->oldcompositor_ = "";61 59 62 60 if (this->bLoadCompositor_ && Ogre::Root::getSingletonPtr()) … … 79 77 Shader::~Shader() 80 78 { 81 82 if (this->bLoadCompositor_ && this->compositorInstance_) 79 if (this->compositorInstance_ && this->bLoadCompositor_) 83 80 { 84 81 Ogre::Viewport* viewport = GraphicsManager::getInstance().getViewport(); … … 112 109 Ogre::Viewport* viewport = GraphicsManager::getInstance().getViewport(); 113 110 assert(viewport); 114 if ( this->oldcompositor_ != "")111 if (!this->oldcompositor_.empty()) 115 112 { 116 113 Ogre::CompositorManager::getSingleton().removeCompositor(viewport, this->oldcompositor_); 117 114 this->compositorInstance_ = 0; 118 115 } 119 if ( this->compositor_ != "")116 if (!this->compositor_.empty()) 120 117 { 121 118 this->compositorInstance_ = Ogre::CompositorManager::getSingleton().addCompositor(viewport, this->compositor_); … … 299 296 continue; 300 297 301 if ( pass_pointer->getFragmentProgramName() != "")298 if (!pass_pointer->getFragmentProgramName().empty()) 302 299 { 303 300 Ogre::GpuProgramParameters* parameter_pointer = pass_pointer->getFragmentProgramParameters().get(); -
code/branches/pickup2/src/libraries/tools/TextureGenerator.cc
r5781 r6412 72 72 if (it == colourMap.end()) 73 73 { 74 std::stringmaterialName = textureName + "_Material_" + multi_cast<std::string>(materialCount_s++);74 const std::string& materialName = textureName + "_Material_" + multi_cast<std::string>(materialCount_s++); 75 75 Ogre::MaterialPtr material = static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().create(materialName, "General")); 76 76 material->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA); … … 82 82 else 83 83 { 84 return (*it).second;84 return it->second; 85 85 } 86 86 } -
code/branches/pickup2/src/libraries/tools/Timer.cc
r5929 r6412 112 112 this->deleteExecutor(); 113 113 } 114 114 115 115 /** 116 116 @brief Initializes the Timer -
code/branches/pickup2/src/libraries/tools/Timer.h
r5929 r6412 140 140 private: 141 141 void init(); 142 142 143 143 Executor* executor_; //!< The executor of the function that should be called when the time expires 144 144 -
code/branches/pickup2/src/libraries/tools/interfaces/TimeFactorListener.h
r5781 r6412 37 37 class _ToolsExport TimeFactorListener : virtual public OrxonoxClass 38 38 { 39 friend class GSRoot;40 41 39 public: 42 40 TimeFactorListener(); 43 41 virtual ~TimeFactorListener() {} 44 42 43 static void setTimeFactor( float factor ); 44 static void setTimeFactorInternal( float factor ); 45 static inline float getTimeFactor(){ return TimeFactorListener::timefactor_s; } 46 45 47 protected: 46 48 virtual void changedTimeFactor(float factor_new, float factor_old) {} 47 inline float getTimeFactor() const48 { return TimeFactorListener::timefactor_s; }49 49 50 50 private: -
code/branches/pickup2/src/libraries/tools/interfaces/ToolsInterfaceCompilation.cc
r5781 r6412 37 37 38 38 #include "core/CoreIncludes.h" 39 #include "core/GameMode.h" 40 #include "network/NetworkFunction.h" 39 41 40 42 namespace orxonox … … 43 45 // TimeFactorListener 44 46 //---------------------------- 47 registerStaticNetworkFunction( &TimeFactorListener::setTimeFactorInternal ); 48 45 49 float TimeFactorListener::timefactor_s = 1.0f; 46 50 … … 48 52 { 49 53 RegisterRootObject(TimeFactorListener); 54 } 55 56 /*static*/ void TimeFactorListener::setTimeFactor( float factor ) 57 { 58 if ( !GameMode::isStandalone() ) 59 callStaticNetworkFunction( &TimeFactorListener::setTimeFactorInternal, CLIENTID_UNKNOWN, factor ); 60 TimeFactorListener::setTimeFactorInternal(factor); 61 } 62 63 /*static*/ void TimeFactorListener::setTimeFactorInternal( float factor ) 64 { 65 float oldFactor = TimeFactorListener::timefactor_s; 66 TimeFactorListener::timefactor_s = factor; 67 for (ObjectList<TimeFactorListener>::iterator it = ObjectList<TimeFactorListener>::begin(); it != ObjectList<TimeFactorListener>::end(); ++it) 68 it->changedTimeFactor(factor, oldFactor); 50 69 } 51 70 -
code/branches/pickup2/src/libraries/util/CMakeLists.txt
r5929 r6412 29 29 CRC32.cc 30 30 ExprParser.cc 31 OutputBuffer.cc32 31 OutputHandler.cc 33 32 SignalHandler.cc -
code/branches/pickup2/src/libraries/util/Clipboard.cc
r5781 r6412 78 78 { 79 79 COUT(1) << "Error: Unable to copy the following text to the clipboard:" << std::endl; 80 COUT(1) << " \"" << text << "\""<< std::endl;80 COUT(1) << " \"" << text << '"' << std::endl; 81 81 } 82 82 return false; … … 94 94 { 95 95 HANDLE hData = GetClipboardData(CF_TEXT); 96 std::string output = static_cast<char*>(GlobalLock(hData)); 96 if (hData == NULL) 97 return ""; 98 std::string output(static_cast<char*>(GlobalLock(hData))); 97 99 GlobalUnlock(hData); 98 100 CloseClipboard(); … … 117 119 namespace orxonox 118 120 { 119 static std::string clipboard = ""; //!< Keeps the text of our internal clipboard121 static std::string clipboard; //!< Keeps the text of our internal clipboard 120 122 121 123 /** -
code/branches/pickup2/src/libraries/util/Clock.cc
r5929 r6412 34 34 Clock::Clock() 35 35 : timer_(new Ogre::Timer()) 36 , storedTime_(0)37 36 , tickTime_(0) 38 37 , tickDt_(0) 39 38 , tickDtFloat_(0.0f) 40 , lastTimersTime_(0)41 39 { 42 40 } … … 46 44 delete timer_; 47 45 } 48 46 47 /** 48 @remarks 49 Mind the types! Ogre::Timer::getMicroseconds() will return an unsigned 50 long, which will eventually overflow. But if you use the subtraction of 51 the current time minus the last time the timer gave us and sum these up to 52 a 64 bit integer, we get the desired result. 53 Also mind that we don't have to store the last timer's time as unsigned long 54 as well because (unsigned long)tickTime_ will do exactly that. 55 */ 49 56 void Clock::capture() 50 57 { 51 unsigned long timersTime = timer_->getMicroseconds(); 52 tickTime_ = storedTime_ + timersTime; 53 tickDt_ = timersTime - lastTimersTime_; 58 tickDt_ = timer_->getMicroseconds() - (unsigned long)tickTime_; 59 tickTime_ += tickDt_; 54 60 tickDtFloat_ = static_cast<float>(tickDt_) / 1000000.0f; 55 56 if (timersTime > 0xFFFFFFFF/4)57 {58 // Ogre timer will overflow at 2^32 microseconds if unsigned long is 32 bit59 storedTime_ += timersTime;60 lastTimersTime_ = 0;61 timer_->reset();62 }63 else64 {65 lastTimersTime_ = timersTime;66 }67 61 } 68 62 69 63 unsigned long long Clock::getRealMicroseconds() const 70 64 { 71 return t his->timer_->getMicroseconds() + this->storedTime_;65 return tickTime_ + (timer_->getMicroseconds() - (unsigned long)tickTime_); 72 66 } 73 67 } -
code/branches/pickup2/src/libraries/util/Clock.h
r5929 r6412 57 57 58 58 Ogre::Timer* timer_; 59 unsigned long long storedTime_;60 59 unsigned long long tickTime_; 61 60 long tickDt_; 62 61 float tickDtFloat_; 63 unsigned long lastTimersTime_;64 62 }; 65 63 } -
code/branches/pickup2/src/libraries/util/Convert.h
r5738 r6412 43 43 44 44 #include "Debug.h" 45 #include "StringUtils.h"46 45 #include "TemplateUtils.h" 47 46 … … 336 335 FORCEINLINE static bool convert(std::string* output, const char input) 337 336 { 338 *output = std::string(1, input);337 *output = input; 339 338 return true; 340 339 } … … 345 344 FORCEINLINE static bool convert(std::string* output, const unsigned char input) 346 345 { 347 *output = std::string(1, input);346 *output = input; 348 347 return true; 349 348 } … … 352 351 struct ConverterExplicit<std::string, char> 353 352 { 354 FORCEINLINE static bool convert(char* output, const std::string input)355 { 356 if ( input != "")353 FORCEINLINE static bool convert(char* output, const std::string& input) 354 { 355 if (!input.empty()) 357 356 *output = input[0]; 358 357 else … … 364 363 struct ConverterExplicit<std::string, unsigned char> 365 364 { 366 FORCEINLINE static bool convert(unsigned char* output, const std::string input)367 { 368 if ( input != "")365 FORCEINLINE static bool convert(unsigned char* output, const std::string& input) 366 { 367 if (!input.empty()) 369 368 *output = input[0]; 370 369 else … … 389 388 }; 390 389 390 // Declarations to avoid StringUtils.h include 391 _UtilExport std::string removeTrailingWhitespaces(const std::string& str); 392 _UtilExport std::string getLowercase(const std::string& str); 393 391 394 // std::string to bool 392 395 template <> … … 395 398 static bool convert(bool* output, const std::string& input) 396 399 { 397 std::stringstripped = getLowercase(removeTrailingWhitespaces(input));400 const std::string& stripped = getLowercase(removeTrailingWhitespaces(input)); 398 401 if (stripped == "true" || stripped == "on" || stripped == "yes") 399 402 { 400 *output = true;401 return true;403 *output = true; 404 return true; 402 405 } 403 406 else if (stripped == "false" || stripped == "off" || stripped == "no") 404 407 { 405 *output = false;406 return true;408 *output = false; 409 return true; 407 410 } 408 411 -
code/branches/pickup2/src/libraries/util/Debug.h
r5738 r6412 21 21 * 22 22 * Author: 23 * Benjamin Grauer 23 * Fabian 'x3n' Landau 24 * Reto Grieder 24 25 * Co-authors: 25 * Fabian 'x3n' Landau26 * ... 26 27 * 27 28 */ 28 29 29 30 /** 30 @file 31 @brief Handles different output-levels of errors, warnings, infos and debug information. 31 @file 32 @brief 33 Handles different output-levels of errors, warnings, infos and debug information. 32 34 33 35 The COUT(level) macro acts like std::cout, but the output is only performed if the given … … 35 37 36 38 There are two used values in this file: 37 - The hard debug level is used during compile time. It describes the highest allowed output level.39 - The hard debug level is used during compile time. It describes the highest allowed output level. 38 40 - The soft debug level is used during runtime and is the maximum of the three configurable 39 output-levels for console, log file and ingame shell.41 output-levels for console, log file and in game shell. 40 42 41 43 The separation between the three devices is done by the OutputHandler. … … 50 52 6: Crazy debug information 51 53 52 54 @example 53 55 COUT(0) << "Very important output" << std::endl; 54 56 COUT(1) << "Error: Something went wrong!" << std::endl; 55 57 COUT(2) << "Warning: There might be a problem." << std::endl; 56 COUT(3) << "Info: It's monday" << std::endl;58 COUT(3) << "Info: It's Monday" << std::endl; 57 59 COUT(4) << "Debug: x is 1.23456" << std::endl; 58 60 */ 59 61 60 #ifndef _ Debug_H__61 #define _ Debug_H__62 #ifndef _Util_Debug_H__ 63 #define _Util_Debug_H__ 62 64 63 65 #include "UtilPrereqs.h" 64 65 66 #include "OutputHandler.h" 66 67 67 68 namespace orxonox 68 69 { 69 /** 70 @brief Returns the soft debug level, stored in the only existing instance of the OutputHandler class, configured in the config-file. 71 @return The soft debug level 72 */ 73 inline int getSoftDebugLevel() 70 // Just for convenience 71 using std::endl; 72 73 // Adjust this to discard certain output with level > hardDebugLevel at compile time already 74 #ifdef ORXONOX_RELEASE 75 const int hardDebugLevel = OutputLevel::Verbose 76 #elif defined(NDEBUG) 77 const int hardDebugLevel = OutputLevel::Verbose; 78 #else 79 //! Maximum level for debug output that should be even processed at run time 80 const int hardDebugLevel = OutputLevel::Ultra; 81 #endif 82 83 //! This function simply returns 0 and helps to suppress the "statement has no effect" compiler warning 84 inline int debugDummyFunction() 74 85 { 75 return OutputHandler::getSoftDebugLevel();86 return 0; 76 87 } 77 78 using std::endl;79 88 } 80 89 81 // DEFINE ERROR MODES 82 #define ORX_NONE 0 83 #define ORX_ERROR 1 84 #define ORX_WARNING 2 85 #define ORX_INFO 3 86 #define ORX_DEBUG 4 87 #define ORX_VERBOSE 5 88 #define ORX_ULTRA 6 90 /** 91 @brief 92 Logs text output: use exactly like std::cout, but specify an output 93 level as argument. 94 @details 95 (a > b ? 0 : c << "text") is equivalent to (a > b ? 0 : (c << "text")) 96 where (a > b ? 0 : ) stands for COUT(x). This should explain how 97 this macro magic can possibly even work ;) 98 @example 99 COUT(3) << "Some info" << std::endl; 100 @note 101 The ? : operator requires both possible results to have the type of 102 the first. This is achieved by the int conversion operator dummy 103 in the OutputHandler. 104 */ 105 #define COUT(level) \ 106 /*if*/ (level > orxonox::hardDebugLevel) ? \ 107 orxonox::debugDummyFunction() \ 108 /*else*/ : \ 109 /*if*/ (level > orxonox::OutputHandler::getSoftDebugLevel()) ? \ 110 orxonox::debugDummyFunction() \ 111 /*else*/ : \ 112 orxonox::OutputHandler::getOutStream(level) 89 113 90 //definitions 91 #define ORX_PRINT_DEBUG_OUTPUT 1 92 #define ORX_HARD_DEBUG_LEVEL ORX_VERBOSE 93 94 #define COUT_EXEC(x) orxonox::OutputHandler::getOutStream().setOutputLevel(x) 95 96 //////////////////////////////////////////////////////// 97 /// COUT: just prints output as is with std::cout /// 98 //////////////////////////////////////////////////////// 99 #define COUTORX_NONE COUT0 100 #define COUTORX_ERROR COUT1 101 #define COUTORX_WARNING COUT2 102 #define COUTORX_INFO COUT3 103 #define COUTORX_DEBUG COUT4 104 #define COUTORX_VERBOSE COUT5 105 #define COUTORX_ULTRA COUT6 106 107 #ifndef COUT 108 #if ORX_PRINT_DEBUG_OUTPUT 109 #define COUT(x) \ 110 COUT ## x 111 112 #if ORX_HARD_DEBUG_LEVEL >= ORX_NONE 113 #define COUT0 \ 114 (orxonox::getSoftDebugLevel() < ORX_NONE) ? COUT_EXEC(0) : COUT_EXEC(0) 115 #else 116 #define COUT0 \ 117 false ? COUT_EXEC(0) : COUT_EXEC(0) 118 #endif 119 120 #if ORX_HARD_DEBUG_LEVEL >= ORX_ERROR 121 #define COUT1 \ 122 (orxonox::getSoftDebugLevel() < ORX_ERROR) ? COUT_EXEC(1) : COUT_EXEC(1) 123 #else 124 #define COUT1 \ 125 false ? COUT_EXEC(1) : COUT_EXEC(1) 126 #endif 127 128 #if ORX_HARD_DEBUG_LEVEL >= ORX_WARNING 129 #define COUT2 \ 130 (orxonox::getSoftDebugLevel() < ORX_WARNING) ? COUT_EXEC(2) : COUT_EXEC(2) 131 #else 132 #define COUT2 \ 133 false ? COUT_EXEC(2) : COUT_EXEC(2) 134 #endif 135 136 #if ORX_HARD_DEBUG_LEVEL >= ORX_INFO 137 #define COUT3 \ 138 (orxonox::getSoftDebugLevel() < ORX_INFO) ? COUT_EXEC(3) : COUT_EXEC(3) 139 #else 140 #define COUT3 \ 141 false ? COUT_EXEC(3) : COUT_EXEC(3) 142 #endif 143 144 #if ORX_HARD_DEBUG_LEVEL >= ORX_DEBUG 145 #define COUT4 \ 146 (orxonox::getSoftDebugLevel() < ORX_DEBUG) ? COUT_EXEC(4) : COUT_EXEC(4) 147 #else 148 #define COUT4 \ 149 false ? COUT_EXEC(4) : COUT_EXEC(4) 150 #endif 151 152 #if ORX_HARD_DEBUG_LEVEL >= ORX_VERBOSE 153 #define COUT5 \ 154 (orxonox::getSoftDebugLevel() < ORX_VERBOSE) ? COUT_EXEC(5) : COUT_EXEC(5) 155 #else 156 #define COUT5 \ 157 false ? COUT_EXEC(5) : COUT_EXEC(5) 158 #endif 159 160 #if ORX_HARD_DEBUG_LEVEL >= ORX_ULTRA 161 #define COUT6 \ 162 (orxonox::getSoftDebugLevel() < ORX_ULTRA) ? COUT_EXEC(6) : COUT_EXEC(6) 163 #else 164 #define COUT6 \ 165 false ? COUT_EXEC(6) : COUT_EXEC(6) 166 #endif 167 168 #else /* if ORX_PRINT_DEBUG_OUTPUT */ 169 #define COUT(x) \ 170 false ? COUT_EXEC(6) : COUT_EXEC(6) 171 #endif /* if ORX_PRINT_DEBUG_OUTPUT */ 172 173 #endif /* ifndef COUT */ 174 175 176 ///////////////////////////////////////////////////////////////////// 177 /// CCOUT: Prints output with std::cout and adds the classname /// 178 ///////////////////////////////////////////////////////////////////// 179 #define CCOUTORX_NONE CCOUT0 180 #define CCOUTORX_ERROR CCOUT1 181 #define CCOUTORX_WARNING CCOUT2 182 #define CCOUTORX_INFO CCOUT3 183 #define CCOUTORX_DEBUG CCOUT4 184 #define CCOUTORX_VERBOSE CCOUT5 185 #define CCOUTORX_ULTRA CCOUT6 186 187 #define CCOUT_EXEC(x) \ 188 orxonox::OutputHandler::getOutStream().setOutputLevel(x) \ 189 << this->getIdentifier()->getName() << ": " 190 191 #ifndef CCOUT 192 #if ORX_PRINT_DEBUG_OUTPUT 193 #define CCOUT(x) \ 194 CCOUT ## x 195 196 #if ORX_HARD_DEBUG_LEVEL >= ORX_NONE 197 #define CCOUT0 \ 198 (orxonox::getSoftDebugLevel() < ORX_NONE) ? COUT_EXEC(0) : CCOUT_EXEC(0) 199 #else 200 #define CCOUT0 \ 201 false ? COUT_EXEC(0) : CCOUT_EXEC(0) 202 #endif 203 204 #if ORX_HARD_DEBUG_LEVEL >= ORX_ERROR 205 #define CCOUT1 \ 206 (orxonox::getSoftDebugLevel() < ORX_ERROR) ? COUT_EXEC(1) : CCOUT_EXEC(1) 207 #else 208 #define CCOUT1 \ 209 false ? COUT_EXEC(1) : CCOUT_EXEC(1) 210 #endif 211 212 #if ORX_HARD_DEBUG_LEVEL >= ORX_WARNING 213 #define CCOUT2 \ 214 (orxonox::getSoftDebugLevel() < ORX_WARNING) ? COUT_EXEC(2) : CCOUT_EXEC(2) 215 #else 216 #define CCOUT2 \ 217 false ? COUT_EXEC(2) : CCOUT_EXEC(2) 218 #endif 219 220 #if ORX_HARD_DEBUG_LEVEL >= ORX_INFO 221 #define CCOUT3 \ 222 (orxonox::getSoftDebugLevel() < ORX_INFO) ? COUT_EXEC(3) : CCOUT_EXEC(3) 223 #else 224 #define CCOUT3 \ 225 false ? COUT_EXEC(3) : CCOUT_EXEC(3) 226 #endif 227 228 #if ORX_HARD_DEBUG_LEVEL >= ORX_DEBUG 229 #define CCOUT4 \ 230 (orxonox::getSoftDebugLevel() < ORX_DEBUG) ? COUT_EXEC(4) : CCOUT_EXEC(4) 231 #else 232 #define CCOUT4 \ 233 false ? COUT_EXEC(4) : CCOUT_EXEC(4) 234 #endif 235 236 #if ORX_HARD_DEBUG_LEVEL >= ORX_VERBOSE 237 #define CCOUT5 \ 238 (orxonox::getSoftDebugLevel() < ORX_VERBOSE) ? COUT_EXEC(5) : CCOUT_EXEC(5) 239 #else 240 #define CCOUT5 \ 241 false ? COUT_EXEC(5) : CCOUT_EXEC(5) 242 #endif 243 244 #if ORX_HARD_DEBUG_LEVEL >= ORX_ULTRA 245 #define CCOUT6 \ 246 (orxonox::getSoftDebugLevel() < ORX_ULTRA) ? COUT_EXEC(6) : CCOUT_EXEC(6) 247 #else 248 #define CCOUT6 \ 249 false ? COUT_EXEC(6) : CCOUT_EXEC(6) 250 #endif 251 252 #else /* if ORX_PRINT_DEBUG_OUTPUT */ 253 #define CCOUT(x) \ 254 false ? CCOUT_EXEC(6) : CCOUT_EXEC(6) 255 #endif /* if ORX_PRINT_DEBUG_OUTPUT */ 256 257 #endif /* ifndef CCOUT */ 258 259 #endif /* _Debug_H__ */ 114 #endif /* _Util_Debug_H__ */ -
code/branches/pickup2/src/libraries/util/Exception.cc
r5781 r6412 49 49 : description_(description) 50 50 , lineNumber_(0) 51 , functionName_("")52 , filename_("")53 51 { } 54 52 … … 61 59 const std::string& Exception::getFullDescription() const 62 60 { 63 if (fullDescription_ == "")61 if (fullDescription_.empty()) 64 62 { 65 63 std::ostringstream fullDesc; … … 67 65 fullDesc << this->getTypeName() << "Exception"; 68 66 69 if ( this->filename_ != "")67 if (!this->filename_.empty()) 70 68 { 71 69 fullDesc << " in " << this->filename_; 72 70 if (this->lineNumber_) 73 fullDesc << "(" << this->lineNumber_ << ")";71 fullDesc << '(' << this->lineNumber_ << ')'; 74 72 } 75 73 76 if ( this->functionName_ != "")77 fullDesc << " in function '" << this->functionName_ << "'";74 if (!this->functionName_.empty()) 75 fullDesc << " in function '" << this->functionName_ << '\''; 78 76 79 77 fullDesc << ": "; 80 if ( this->description_ != "")78 if (!this->description_.empty()) 81 79 fullDesc << this->description_; 82 80 else 83 81 fullDesc << "No description available."; 84 82 85 this->fullDescription_ = std::string(fullDesc.str());83 this->fullDescription_ = fullDesc.str(); 86 84 } 87 85 -
code/branches/pickup2/src/libraries/util/Exception.h
r5747 r6412 131 131 CREATE_ORXONOX_EXCEPTION(PluginsNotFound); 132 132 CREATE_ORXONOX_EXCEPTION(InitialisationFailed); 133 CREATE_ORXONOX_EXCEPTION(InitialisationAborted); 133 134 CREATE_ORXONOX_EXCEPTION(NotImplemented); 134 135 CREATE_ORXONOX_EXCEPTION(GameState); -
code/branches/pickup2/src/libraries/util/ExprParser.cc
r5738 r6412 47 47 namespace orxonox 48 48 { 49 ExprParser::ExprParser( const std::string& str)49 ExprParser::ExprParser() 50 50 { 51 51 this->failed_ = false; 52 this->variables_["pi"] = 3.1415926535897932; 53 this->variables_["e"] = 2.7182818284590452; 54 } 55 56 void ExprParser::setVariable(const std::string& varname, double value) 57 { 58 this->variables_[varname] = value; 59 } 60 61 void ExprParser::parse(const std::string& str) 62 { 52 63 this->reading_stream = str.c_str(); 53 64 if (str.size() == 0 || *reading_stream == '\0') … … 343 354 else 344 355 { 345 #define SWITCH word 346 CASE_1("pi") 347 value = 3.1415926535897932; 348 CASE("e") 349 value = 2.7182818284590452; 350 CASE_ELSE 356 std::map<std::string, double>::const_iterator it = this->variables_.find(word); 357 if (it != this->variables_.end()) 358 value = it->second; 359 else 351 360 { 352 361 this->failed_ = true; … … 358 367 } 359 368 else if (*reading_stream == 40) 360 { // expres ion in paranthesis369 { // expression in parenthesis 361 370 ++reading_stream; 362 371 value = parse_last_argument(); -
code/branches/pickup2/src/libraries/util/ExprParser.h
r5738 r6412 36 36 37 37 #include "UtilPrereqs.h" 38 39 #include <map> 38 40 #include <string> 39 41 … … 71 73 72 74 73 ExprParser(const std::string& str); 75 ExprParser(); 76 void parse(const std::string& str); 74 77 const std::string& getRemains() { return this->remains_; } 75 78 double getResult() { return this->result_; } 76 79 bool getSuccess() { return !this->failed_; } 80 81 void setVariable(const std::string& varname, double value); 77 82 78 83 private: … … 97 102 double result_; 98 103 std::string remains_; 99 104 std::map<std::string, double> variables_; 100 105 }; 101 106 -
code/branches/pickup2/src/libraries/util/Math.cc
r5738 r6412 43 43 namespace orxonox 44 44 { 45 #if OGRE_VERSION < 0x010603 45 46 /** 46 47 @brief Function for writing a Radian to a stream. … … 51 52 return out; 52 53 } 54 55 /** 56 @brief Function for writing a Degree to a stream. 57 */ 58 std::ostream& operator<<(std::ostream& out, const orxonox::Degree& degree) 59 { 60 out << degree.valueDegrees(); 61 return out; 62 } 63 #endif 53 64 54 65 /** … … 61 72 radian = temp; 62 73 return in; 63 }64 65 /**66 @brief Function for writing a Degree to a stream.67 */68 std::ostream& operator<<(std::ostream& out, const orxonox::Degree& degree)69 {70 out << degree.valueDegrees();71 return out;72 74 } 73 75 … … 136 138 return orxonox::Vector2(0, 1); 137 139 } 138 140 139 141 float cos_value = clamp<float>(myorthonormal.dotProduct(projection) / projectionlength, -1, 1); 140 142 float sin_value = sqrt( 1 - cos_value*cos_value ); 141 143 142 144 if ((mydirection.crossProduct(myorthonormal)).dotProduct(distance) > 0) 143 145 return orxonox::Vector2( sin_value, cos_value ); … … 177 179 } 178 180 //float angle = acos(clamp<float>(myorthonormal.dotProduct(projection) / projectionlength, -1, 1)); 179 181 180 182 float cos_value = clamp<float>(myorthonormal.dotProduct(projection) / projectionlength, -1, 1); 181 183 float sin_value = sqrt( 1 - cos_value*cos_value ); -
code/branches/pickup2/src/libraries/util/Math.h
r5738 r6412 59 59 namespace orxonox 60 60 { 61 #if OGRE_VERSION < 0x010603 61 62 _UtilExport std::ostream& operator<<(std::ostream& out, const orxonox::Radian& radian); 63 _UtilExport std::ostream& operator<<(std::ostream& out, const orxonox::Degree& degree); 64 #endif 62 65 _UtilExport std::istream& operator>>(std::istream& in, orxonox::Radian& radian); 63 _UtilExport std::ostream& operator<<(std::ostream& out, const orxonox::Degree& degree);64 66 _UtilExport std::istream& operator>>(std::istream& in, orxonox::Degree& degree); 65 67 … … 163 165 template <> inline bool zeroise<bool>() { return 0; } 164 166 template <> inline void* zeroise<void*>() { return 0; } 165 template <> inline std::string zeroise<std::string>() { return ""; }167 template <> inline std::string zeroise<std::string>() { return std::string(); } 166 168 template <> inline orxonox::Radian zeroise<orxonox::Radian>() { return orxonox::Radian(0.0f); } 167 169 template <> inline orxonox::Degree zeroise<orxonox::Degree>() { return orxonox::Degree(0.0f); } -
code/branches/pickup2/src/libraries/util/MathConvert.h
r5738 r6412 53 53 { 54 54 std::ostringstream ostream; 55 if (ostream << input.x << ","<< input.y)55 if (ostream << input.x << ',' << input.y) 56 56 { 57 57 (*output) = ostream.str(); … … 69 69 { 70 70 std::ostringstream ostream; 71 if (ostream << input.x << "," << input.y << ","<< input.z)71 if (ostream << input.x << ',' << input.y << ',' << input.z) 72 72 { 73 73 (*output) = ostream.str(); … … 85 85 { 86 86 std::ostringstream ostream; 87 if (ostream << input.x << "," << input.y << "," << input.z << ","<< input.w)87 if (ostream << input.x << ',' << input.y << ',' << input.z << ',' << input.w) 88 88 { 89 89 (*output) = ostream.str(); … … 101 101 { 102 102 std::ostringstream ostream; 103 if (ostream << input.w << "," << input.x << "," << input.y << ","<< input.z)103 if (ostream << input.w << ',' << input.x << ',' << input.y << ',' << input.z) 104 104 { 105 105 (*output) = ostream.str(); … … 117 117 { 118 118 std::ostringstream ostream; 119 if (ostream << input.r << "," << input.g << "," << input.b << ","<< input.a)119 if (ostream << input.r << ',' << input.g << ',' << input.b << ',' << input.a) 120 120 { 121 121 (*output) = ostream.str(); -
code/branches/pickup2/src/libraries/util/MultiType.h
r5738 r6412 232 232 233 233 virtual void toString(std::ostream& outstream) const = 0; 234 234 235 235 virtual void importData( uint8_t*& mem )=0; 236 236 virtual void exportData( uint8_t*& mem ) const=0; … … 339 339 template <typename T> inline bool isType() const { return false; } // Only works for specialized values - see below 340 340 std::string getTypename() const; 341 341 342 342 /** @brief Saves the value of the MT to a bytestream (pointed at by mem) and increases mem pointer by size of MT */ 343 343 inline void exportData(uint8_t*& mem) const { assert(sizeof(MT_Type::Value)<=8); *static_cast<uint8_t*>(mem) = this->getType(); mem+=sizeof(uint8_t); this->value_->exportData(mem); } -
code/branches/pickup2/src/libraries/util/MultiTypeValue.h
r5738 r6412 150 150 /** @brief Puts the current value on the stream */ 151 151 inline void toString(std::ostream& outstream) const { outstream << this->value_; } 152 152 153 153 /** @brief loads data from the bytestream (mem) into the MT and increases the bytestream pointer by the size of the data */ 154 154 inline void importData( uint8_t*& mem ) { loadAndIncrease( /*(const T&)*/this->value_, mem ); } … … 160 160 T value_; //!< The stored value 161 161 }; 162 162 163 163 // Import / Export specialisation 164 164 // ColourValue -
code/branches/pickup2/src/libraries/util/OrxAssert.h
r5738 r6412 44 44 #ifndef NDEBUG 45 45 #define OrxAssert(Assertion, ErrorMessage) \ 46 Assertion ? ((void)0) : (void)(orxonox::OutputHandler::getOutStream( ).setOutputLevel(1) << ErrorMessage << std::endl); \46 Assertion ? ((void)0) : (void)(orxonox::OutputHandler::getOutStream(1) << ErrorMessage << std::endl); \ 47 47 assert(Assertion) 48 48 #else -
code/branches/pickup2/src/libraries/util/OutputHandler.cc
r5738 r6412 23 23 * Fabian 'x3n' Landau 24 24 * Co-authors: 25 * ...25 * Reto Grieder 26 26 * 27 27 */ 28 28 29 29 /** 30 @file 31 @brief Implementation of the OutputHandler class. 30 @file 31 @brief 32 Definition of classes related to output (logging). 32 33 */ 33 34 34 35 #include "OutputHandler.h" 35 36 37 #include <algorithm> 36 38 #include <ctime> 37 39 #include <cstdlib> 40 #include <fstream> 41 #include <iostream> 42 #include <sstream> 43 44 #include "Debug.h" 38 45 39 46 namespace orxonox 40 47 { 48 //! How the log file shall be named on the filesystem 49 const std::string logFileBaseName_g = "orxonox.log"; 50 51 ///////////////////////// 52 ///// LogFileWriter ///// 53 ///////////////////////// 41 54 /** 42 @brief Constructor: Opens the logfile and writes the first line. 43 @param logfilename The name of the logfile 55 @brief 56 Writes the output to the log file. 57 @note 58 As long as the correct log path is not yet known (for pre main code), the 59 LogFileWriter will write to a temporary file in /temp (Unix) or %TEMP% (Windows). 60 As soon as you set the correct path setLogPath the content of the temporary file 61 is read and put into the new file as well. 44 62 */ 63 class LogFileWriter : public OutputListener 64 { 65 public: 66 /** 67 @brief 68 Gets temporary log path and starts the log file 69 @param outputHandler 70 This is only required to avoid another call to getInstance (this c'tor was 71 called from getInstance!) 72 */ 73 LogFileWriter() 74 : OutputListener(OutputHandler::logFileOutputListenerName_s) 75 { 76 // Get path for a temporary file 77 #ifdef ORXONOX_PLATFORM_WINDOWS 78 char* pTempDir = getenv("TEMP"); 79 this->logFilename_ = std::string(pTempDir) + '/' + logFileBaseName_g; 80 #else 81 this->logFilename_ = std::string("/tmp/") + logFileBaseName_g; 82 #endif 83 84 // Get current time 85 time_t rawtime; 86 struct tm* timeinfo; 87 time(&rawtime); 88 timeinfo = localtime(&rawtime); 89 90 this->logFile_.open(this->logFilename_.c_str(), std::fstream::out); 91 this->logFile_ << "Started log on " << asctime(timeinfo) << std::endl; 92 this->logFile_.flush(); 93 94 this->outputStream_ = &this->logFile_; 95 } 96 97 //! Closes the log file 98 ~LogFileWriter() 99 { 100 this->logFile_ << "Closed log" << std::endl; 101 this->logFile_.close(); 102 } 103 104 //! Changes the log path 105 void setLogPath(const std::string& path) 106 { 107 this->logFile_.close(); 108 // Read old file into a buffer 109 std::ifstream old(this->logFilename_.c_str()); 110 this->logFilename_ = path + logFileBaseName_g; 111 // Open the new file and feed it the content of the old one 112 this->logFile_.open(this->logFilename_.c_str(), std::fstream::out); 113 this->logFile_ << old.rdbuf(); 114 this->logFile_.flush(); 115 old.close(); 116 } 117 118 private: 119 std::ofstream logFile_; //! File handle for the log file 120 std::string logFilename_; //! Filename of the log file 121 }; 122 123 124 ///////////////////////// 125 ///// ConsoleWriter ///// 126 ///////////////////////// 127 /** 128 @brief 129 Writes the output to std::cout. 130 @note 131 This listener will usually be disable once an actual shell with console is instantiated. 132 */ 133 class ConsoleWriter : public OutputListener 134 { 135 public: 136 //! Only assigns the output stream with std::cout 137 ConsoleWriter() 138 : OutputListener("consoleLog") 139 { 140 this->outputStream_ = &std::cout; 141 } 142 }; 143 144 145 /////////////////////////// 146 ///// MemoryLogWriter ///// 147 /////////////////////////// 148 /** 149 @brief 150 OutputListener that writes all the output piece by piece to an array 151 associated with the corresponding output level. 152 @note 153 Only output below or equal to the current soft debug level is written 154 to minimise huge arrays for the normal run. 155 */ 156 class MemoryLogWriter : public OutputListener 157 { 158 public: 159 friend class OutputHandler; 160 161 /** 162 @brief 163 Sets the right soft debug level and registers itself 164 @param outputHandler 165 This is only required to avoid another call to getInstance (this c'tor was 166 called from getInstance!) 167 */ 168 MemoryLogWriter() 169 : OutputListener("memoryLog") 170 { 171 this->outputStream_ = &this->buffer_; 172 } 173 174 //! Pushed the just written output to the internal array 175 void outputChanged(int level) 176 { 177 if (!this->buffer_.str().empty()) 178 { 179 // Read ostringstream and store it 180 this->output_.push_back(std::make_pair(level, this->buffer_.str())); 181 // Clear content and flags 182 this->buffer_.str(std::string()); 183 } 184 this->buffer_.clear(); 185 } 186 187 private: 188 std::ostringstream buffer_; //! Stream object used to process the output 189 std::vector<std::pair<int, std::string> > output_; //! Vector containing ALL output 190 }; 191 192 193 ///////////////////////// 194 ///// OutputHandler ///// 195 ///////////////////////// 196 const std::string OutputHandler::logFileOutputListenerName_s = "logFile"; 197 int OutputHandler::softDebugLevel_s = hardDebugLevel; 198 199 //! Creates the LogFileWriter and the MemoryLogWriter 45 200 OutputHandler::OutputHandler() 46 { 47 #ifdef ORXONOX_PLATFORM_WINDOWS 48 char* pTempDir = getenv("TEMP"); 49 this->logfilename_ = std::string(pTempDir) + "/orxonox.log"; 201 : outputLevel_(OutputLevel::Verbose) 202 { 203 #ifdef ORXONOX_RELEASE 204 const OutputLevel::Value defaultLevelConsole = OutputLevel::Error; 205 const OutputLevel::Value defaultLevelLogFile = OutputLevel::Info; 50 206 #else 51 this->logfilename_ = "/tmp/orxonox.log"; 207 const OutputLevel::Value defaultLevelConsole = OutputLevel::Info; 208 const OutputLevel::Value defaultLevelLogFile = OutputLevel::Debug; 52 209 #endif 53 #ifdef NDEBUG 54 this->softDebugLevel_[LD_All] = this->softDebugLevel_[LD_Logfile] = 2; 55 this->softDebugLevel_[LD_Console] = this->softDebugLevel_[LD_Shell] = 1; 56 #else 57 this->softDebugLevel_[LD_All] = this->softDebugLevel_[LD_Logfile] = 3; 58 this->softDebugLevel_[LD_Console] = this->softDebugLevel_[LD_Shell] = 2; 59 #endif 60 61 this->outputBuffer_ = &this->fallbackBuffer_; 62 this->logfile_.open(this->logfilename_.c_str(), std::fstream::out); 63 64 time_t rawtime; 65 struct tm* timeinfo; 66 time(&rawtime); 67 timeinfo = localtime(&rawtime); 68 69 this->logfile_ << "Started log on " << asctime(timeinfo) << std::endl; 70 this->logfile_.flush(); 71 } 72 73 /** 74 @brief Destructor: Writes the last line to the logfile and closes it. 75 */ 210 211 this->logFile_ = new LogFileWriter(); 212 // Use default level until we get the configValue from the Core 213 this->logFile_->softDebugLevel_ = defaultLevelLogFile; 214 this->registerOutputListener(this->logFile_); 215 216 this->consoleWriter_ = new ConsoleWriter(); 217 this->consoleWriter_->softDebugLevel_ = defaultLevelConsole; 218 this->registerOutputListener(this->consoleWriter_); 219 220 this->output_ = new MemoryLogWriter(); 221 // We capture as much input as the listener with the highest level 222 this->output_->softDebugLevel_ = getSoftDebugLevel(); 223 this->registerOutputListener(this->output_); 224 } 225 226 //! Destroys the LogFileWriter and the MemoryLogWriter 76 227 OutputHandler::~OutputHandler() 77 228 { 78 this->logfile_ << "Closed log" << std::endl; 79 this->logfile_.close(); 80 } 81 82 /** 83 @brief Returns a reference to the only existing instance of the OutputHandler class. 84 @return The instance 85 */ 86 OutputHandler& OutputHandler::getOutStream() 229 delete this->logFile_; 230 delete this->consoleWriter_; 231 delete this->output_; 232 } 233 234 OutputHandler& OutputHandler::getInstance() 87 235 { 88 236 static OutputHandler orxout; … … 90 238 } 91 239 92 /** 93 @brief Sets the soft debug level for a given output device. 94 @param device The output device 95 @param level The debug level 96 */ 97 void OutputHandler::setSoftDebugLevel(OutputHandler::OutputDevice device, int level) 98 { 99 OutputHandler::getOutStream().softDebugLevel_[static_cast<unsigned int>(device)] = level; 100 } 101 102 /** 103 @brief Returns the soft debug level for a given output device. 104 @param device The output device 105 @return The debug level 106 */ 107 int OutputHandler::getSoftDebugLevel(OutputHandler::OutputDevice device) 108 { 109 return OutputHandler::getOutStream().softDebugLevel_[static_cast<unsigned int>(device)]; 110 } 111 112 /** 113 @brief Sets the OutputBuffer, representing the third output stream. 114 @param buffer The OutputBuffer 115 */ 116 void OutputHandler::setOutputBuffer(OutputBuffer* buffer) 117 { 118 if (buffer == NULL) 119 this->outputBuffer_ = &this->fallbackBuffer_; 120 else 121 { 122 buffer->getStream() >> this->outputBuffer_->getStream().rdbuf(); 123 this->outputBuffer_ = buffer; 124 } 125 } 126 127 /** 128 @brief Sets the path where to create orxonox.log 129 @param Path string with trailing slash 130 */ 240 void OutputHandler::registerOutputListener(OutputListener* listener) 241 { 242 for (std::list<OutputListener*>::const_iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it) 243 { 244 if ((*it)->name_ == listener->name_) 245 { 246 COUT(2) << "OutputHandler, Warning: Trying to register two listeners with the same name!" << std::endl; 247 return; 248 } 249 } 250 this->listeners_.push_back(listener); 251 // Update global soft debug level 252 this->setSoftDebugLevel(listener->getOutputListenerName(), listener->getSoftDebugLevel()); 253 } 254 255 void OutputHandler::unregisterOutputListener(OutputListener* listener) 256 { 257 this->listeners_.remove(listener); 258 } 259 131 260 void OutputHandler::setLogPath(const std::string& path) 132 261 { 133 OutputHandler::getOutStream().logfile_.close(); 134 // store old content 135 std::ifstream old; 136 old.open(OutputHandler::getOutStream().logfilename_.c_str()); 137 OutputHandler::getOutStream().logfilename_ = path + "orxonox.log"; 138 OutputHandler::getOutStream().logfile_.open(OutputHandler::getOutStream().logfilename_.c_str(), std::fstream::out); 139 OutputHandler::getOutStream().logfile_ << old.rdbuf(); 140 old.close(); 141 OutputHandler::getOutStream().logfile_.flush(); 142 } 143 144 /** 145 @brief Overloaded << operator, redirects the output to the console and the logfile. 146 @param sb The streambuffer that should be shown in the console 147 @return A reference to the OutputHandler itself 148 */ 149 OutputHandler& OutputHandler::operator<<(std::streambuf* sb) 150 { 151 if (getSoftDebugLevel(OutputHandler::LD_Console) >= this->outputLevel_) 152 std::cout << sb; 153 154 if (getSoftDebugLevel(OutputHandler::LD_Logfile) >= this->outputLevel_) 155 { 156 this->logfile_ << sb; 157 this->logfile_.flush(); 158 } 159 160 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Shell) >= this->outputLevel_) 161 (*this->outputBuffer_) << sb; 162 163 return *this; 164 } 165 166 /** 167 @brief Overloaded << operator, redirects the output to the console, the logfile and the ingame shell. 168 @param manipulator A function, manipulating the outstream. 169 @return A reference to the OutputHandler itself 170 */ 171 OutputHandler& OutputHandler::operator<<(std::ostream& (*manipulator)(std::ostream&)) 172 { 173 if (getSoftDebugLevel(OutputHandler::LD_Console) >= this->outputLevel_) 174 manipulator(std::cout); 175 176 if (getSoftDebugLevel(OutputHandler::LD_Logfile) >= this->outputLevel_) 177 { 178 manipulator(this->logfile_); 179 this->logfile_.flush(); 180 } 181 182 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Shell) >= this->outputLevel_) 183 (*this->outputBuffer_) << manipulator; 184 185 return *this; 186 } 187 188 /** 189 @brief Overloaded << operator, redirects the output to the console, the logfile and the ingame shell. 190 @param manipulator A function, manipulating the outstream. 191 @return A reference to the OutputHandler itself 192 */ 193 OutputHandler& OutputHandler::operator<<(std::ios& (*manipulator)(std::ios&)) 194 { 195 if (getSoftDebugLevel(OutputHandler::LD_Console) >= this->outputLevel_) 196 manipulator(std::cout); 197 198 if (getSoftDebugLevel(OutputHandler::LD_Logfile) >= this->outputLevel_) 199 { 200 manipulator(this->logfile_); 201 this->logfile_.flush(); 202 } 203 204 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Shell) >= this->outputLevel_) 205 (*this->outputBuffer_) << manipulator; 206 207 return *this; 208 } 209 210 /** 211 @brief Overloaded << operator, redirects the output to the console, the logfile and the ingame shell. 212 @param manipulator A function, manipulating the outstream. 213 @return A reference to the OutputHandler itself 214 */ 215 OutputHandler& OutputHandler::operator<<(std::ios_base& (*manipulator)(std::ios_base&)) 216 { 217 if (getSoftDebugLevel(OutputHandler::LD_Console) >= this->outputLevel_) 218 manipulator(std::cout); 219 220 if (getSoftDebugLevel(OutputHandler::LD_Logfile) >= this->outputLevel_) 221 { 222 manipulator(this->logfile_); 223 this->logfile_.flush(); 224 } 225 226 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Shell) >= this->outputLevel_) 227 (*this->outputBuffer_) << manipulator; 228 229 return *this; 262 this->logFile_->setLogPath(path); 263 } 264 265 void OutputHandler::disableCout() 266 { 267 this->unregisterOutputListener(this->consoleWriter_); 268 } 269 270 void OutputHandler::enableCout() 271 { 272 this->registerOutputListener(this->consoleWriter_); 273 } 274 275 OutputHandler::OutputVectorIterator OutputHandler::getOutputVectorBegin() const 276 { 277 return this->output_->output_.begin(); 278 } 279 280 OutputHandler::OutputVectorIterator OutputHandler::getOutputVectorEnd() const 281 { 282 return this->output_->output_.end(); 283 } 284 285 int OutputHandler::getSoftDebugLevel(const std::string& name) const 286 { 287 for (std::list<OutputListener*>::const_iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it) 288 { 289 if ((*it)->name_ == name) 290 return (*it)->softDebugLevel_; 291 } 292 return -1; 293 } 294 295 void OutputHandler::setSoftDebugLevel(const std::string& name, int level) 296 { 297 int globalSoftDebugLevel = -1; 298 for (std::list<OutputListener*>::const_iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it) 299 { 300 if ((*it)->name_ == name) 301 (*it)->softDebugLevel_ = level; 302 if ((*it)->softDebugLevel_ > globalSoftDebugLevel) 303 globalSoftDebugLevel = (*it)->softDebugLevel_; 304 } 305 // Update global soft debug level 306 OutputHandler::softDebugLevel_s = globalSoftDebugLevel; 230 307 } 231 308 } -
code/branches/pickup2/src/libraries/util/OutputHandler.h
r5738 r6412 23 23 * Fabian 'x3n' Landau 24 24 * Co-authors: 25 * ...25 * Reto Grieder 26 26 * 27 27 */ 28 28 29 29 /** 30 @file 31 @brief Definition of the OutputHandler class. 32 33 The OutputHandler acts like std::cout, but output isn't only shown in the console, 34 but also written to the logfile and the ingame shell. 30 @file 31 @brief 32 Declaration of classes related to output (logging). 35 33 */ 36 34 … … 40 38 #include "UtilPrereqs.h" 41 39 42 #include < iostream>43 #include < fstream>40 #include <list> 41 #include <ostream> 44 42 #include <string> 45 46 #include "OutputBuffer.h"43 #include <vector> 44 #include <utility> 47 45 48 46 namespace orxonox 49 47 { 50 //! The OutputHandler acts like std::cout, but redirects output to the console, the logfile and the ingame shell. 48 /** 49 @brief 50 Denotes different levels of text output (log output) 51 52 0, None : Very important output 53 1, Error : Errors 54 2, Warning: Warnings 55 3, Info : Information 56 4, Debug : Debug information 57 5, Verbose: More debug information 58 6, Ultra : Crazy debug information 59 */ 60 namespace OutputLevel 61 { 62 enum Value 63 { 64 None = 0, 65 Error = 1, 66 Warning = 2, 67 Info = 3, 68 Debug = 4, 69 Verbose = 5, 70 Ultra = 6, 71 }; 72 } 73 74 // Forward declarations for classes in the source file 75 class LogFileWriter; 76 class ConsoleWriter; 77 class MemoryLogWriter; 78 79 /** 80 @brief 81 The OutputHandler acts like std::cout, but output isn't only shown in the console. 82 83 You can register your own listener for output by inheriting from OutputListner. 84 And if you need the output previously processed, iterate over it with 85 OutputHandler::getOutputVector[Begin/End]. 86 The way to output text is to first set the desired output level with 87 OutputHandler::getOutStream(level) and then use the "<<" operator like with std::cout. 88 */ 51 89 class _UtilExport OutputHandler 52 90 { 53 91 public: 54 enum OutputDevice 55 { 56 LD_All = 0, 57 LD_Console = 1, 58 LD_Logfile = 2, 59 LD_Shell = 3 60 }; 61 62 static OutputHandler& getOutStream(); 63 64 /** @brief Puts some text on the outstream. @param text The text */ 92 //! Returns a reference to the only existing instance of the OutputHandler class. 93 static OutputHandler& getInstance(); 94 95 //! Sets the output level and returns a stream to be used with "<<" 96 static inline OutputHandler& getOutStream(int level) 97 { return OutputHandler::getInstance().setOutputLevel(level); } 98 99 typedef std::vector<std::pair<int, std::string> >::const_iterator OutputVectorIterator; 100 //! Returns an iterator to the beginning of the all-output vector 101 OutputVectorIterator getOutputVectorBegin() const; 102 //! Returns an iterator to the end of the all-output vector 103 OutputVectorIterator getOutputVectorEnd() const; 104 105 //! Writes to all output devices 65 106 static inline const std::string& log(const std::string& text) 66 { OutputHandler::getOutStream( ).setOutputLevel(0); OutputHandler::getOutStream().output(text + "\n"); return text; }67 68 / ** @brief Puts an error on the outstream. @param text The text */107 { OutputHandler::getOutStream(0).output(text) << std::endl; return text; } 108 109 //! Writes an error message to the output 69 110 static inline const std::string& error(const std::string& text) 70 { OutputHandler::getOutStream( ).setOutputLevel(1); OutputHandler::getOutStream().output(text + "\n"); return text; }71 72 / ** @brief Puts a warning on the outstream. @param text The text */111 { OutputHandler::getOutStream(1).output(text) << std::endl; return text; } 112 113 //! Writes a warning message to the output 73 114 static inline const std::string& warning(const std::string& text) 74 { OutputHandler::getOutStream( ).setOutputLevel(2); OutputHandler::getOutStream().output(text + "\n"); return text; }75 76 / ** @brief Puts an info on the outstream. @param text The text */115 { OutputHandler::getOutStream(2).output(text) << std::endl; return text; } 116 117 //! Writes an informational message to the output 77 118 static inline const std::string& info(const std::string& text) 78 { OutputHandler::getOutStream( ).setOutputLevel(3); OutputHandler::getOutStream().output(text + "\n"); return text; }79 80 / ** @brief Puts some debug output on the outstream. @param text The text */119 { OutputHandler::getOutStream(3).output(text) << std::endl; return text; } 120 121 //! Writes a debug message to the output 81 122 static inline const std::string& debug(const std::string& text) 82 { OutputHandler::getOutStream().setOutputLevel(4); OutputHandler::getOutStream().output(text + "\n"); return text; } 83 84 /** @brief Returns a reference to the logfile. @return The logfile */ 85 inline std::ofstream& getLogfile() 86 { return this->logfile_; } 87 88 /** @brief Returns a pointer to the OutputBuffer. @return The OutputBuffer */ 89 inline OutputBuffer* getOutputBuffer() 90 { return this->outputBuffer_; } 91 92 /** @brief Sets the level of the incoming output. @param level The level of the incoming output @return The OutputHandler itself */ 123 { OutputHandler::getOutStream(4).output(text) << std::endl; return text; } 124 125 //! Registers an object that receives output via a provided std::ostream 126 void registerOutputListener(OutputListener* listener); 127 //! Unregisters an object that receives output via a provided std::ostream 128 void unregisterOutputListener(OutputListener* listener); 129 130 //! Set the log path once the program has been properly initialised 131 void setLogPath(const std::string& path); 132 //! Disables the std::cout stream for output 133 void disableCout(); 134 //! Enables the std::cout stream for output (startup behaviour) 135 void enableCout(); 136 137 //! Sets the level of the incoming output and returns the OutputHandler 93 138 inline OutputHandler& setOutputLevel(int level) 94 139 { this->outputLevel_ = level; return *this; } 95 140 96 / ** @brief Returns the level of the incoming output. @return The level */141 //! Returns the level of the incoming output 97 142 inline int getOutputLevel() const 98 143 { return this->outputLevel_; } 99 144 100 static void setSoftDebugLevel(OutputHandler::OutputDevice device, int level); 101 static int getSoftDebugLevel(OutputHandler::OutputDevice device = OutputHandler::LD_All); 102 103 static void setLogPath(const std::string& path); 104 105 void setOutputBuffer(OutputBuffer* buffer); 106 145 //! Returns the maximum debug level over all registered listeners (devices) 146 static int getSoftDebugLevel() { return softDebugLevel_s; } 147 //! Returns the soft debug level for a device by its name @return The level or -1 if the listener was not found 148 int getSoftDebugLevel(const std::string& name) const; 149 //! Sets the soft debug level for a listener by its name @remarks Only works for registered listeners! 150 void setSoftDebugLevel(const std::string& name, int level); 151 152 /** 153 @brief 154 General template that copes with all output. 155 Required because operator << might be ambiguous. 156 @a output will be streamed into every listener with an appropriate debug level 157 @return 158 Returns a reference to the OutputHandler so you can use it again directly 159 */ 107 160 template <class T> 108 161 OutputHandler& output(const T& output); 109 162 110 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */163 //! Overloaded << operator, redirects the output to the listeners 111 164 inline OutputHandler& operator<<(unsigned char val) { return this->output(val); } 112 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */165 //! Overloaded << operator, redirects the output to the listeners 113 166 inline OutputHandler& operator<<(short val) { return this->output(val); } 114 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */167 //! Overloaded << operator, redirects the output to the listeners 115 168 inline OutputHandler& operator<<(unsigned short val) { return this->output(val); } 116 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */169 //! Overloaded << operator, redirects the output to the listeners 117 170 inline OutputHandler& operator<<(int val) { return this->output(val); } 118 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */171 //! Overloaded << operator, redirects the output to the listeners 119 172 inline OutputHandler& operator<<(unsigned int val) { return this->output(val); } 120 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */173 //! Overloaded << operator, redirects the output to the listeners 121 174 inline OutputHandler& operator<<(long val) { return this->output(val); } 122 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */175 //! Overloaded << operator, redirects the output to the listeners 123 176 inline OutputHandler& operator<<(unsigned long val) { return this->output(val); } 124 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */177 //! Overloaded << operator, redirects the output to the listeners 125 178 inline OutputHandler& operator<<(long long val) { return this->output(val); } 126 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */179 //! Overloaded << operator, redirects the output to the listeners 127 180 inline OutputHandler& operator<<(unsigned long long val) { return this->output(val); } 128 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */181 //! Overloaded << operator, redirects the output to the listeners 129 182 inline OutputHandler& operator<<(float val) { return this->output(val); } 130 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */183 //! Overloaded << operator, redirects the output to the listeners 131 184 inline OutputHandler& operator<<(double val) { return this->output(val); } 132 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */185 //! Overloaded << operator, redirects the output to the listeners 133 186 inline OutputHandler& operator<<(long double val) { return this->output(val); } 134 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */187 //! Overloaded << operator, redirects the output to the listeners 135 188 inline OutputHandler& operator<<(const void* val) { return this->output(val); } 136 / ** @brief Overloaded << operator, redirects the output to the console and the logfile. @param val The value that should be shown in the console @return A reference to the OutputHandler itself */189 //! Overloaded << operator, redirects the output to the listeners 137 190 inline OutputHandler& operator<<(bool val) { return this->output(val); } 138 191 139 OutputHandler& operator<<(std::streambuf* sb); 140 141 OutputHandler& operator<<(std::ostream& (*manipulator)(std::ostream&)); 142 OutputHandler& operator<<(std::ios& (*manipulator)(std::ios&)); 143 OutputHandler& operator<<(std::ios_base& (*manipulator)(std::ios_base&)); 192 //! Overloaded << operator, redirects the output to the listeners 193 inline OutputHandler& operator<<(std::streambuf* sb) { return this->output(sb); } 194 195 //! Overloaded << operator, redirect the output of classes with self defined 'operator <<' to the listeners 196 template <class T> 197 inline OutputHandler& operator<<(const T& val) { return this->output(val); } 198 199 //! Overloaded << operator for std manipulators like std::endl, redirects the output to the listeners 200 inline OutputHandler& operator<<(std::ostream& (*manip)(std::ostream&)) { return this->output(manip); } 201 //! Overloaded << operator for std manipulators like std::endl, redirects the output to the listeners 202 inline OutputHandler& operator<<(std::ios& (*manip)(std::ios&)) { return this->output(manip); } 203 //! Overloaded << operator for std manipulators like std::endl, redirects the output to the listeners 204 inline OutputHandler& operator<<(std::ios_base& (*manip)(std::ios_base&)) { return this->output(manip); } 205 206 //! Dummy operator required by Debug.h for the ternary operator 207 inline operator int() const { return 0; } 208 209 //! Name of the OutputListener that writes to the log file 210 static const std::string logFileOutputListenerName_s; 144 211 145 212 private: 146 explicitOutputHandler();147 OutputHandler(const OutputHandler& oh);148 virtual ~OutputHandler();149 150 std:: ofstream logfile_; //!< The logfile where the output is logged151 std::string logfilename_; //!< The name of the logfile152 OutputBuffer fallbackBuffer_; //!< The OutputBuffer that gets used if there is no other OutputBuffer153 OutputBuffer* outputBuffer_; //!< The OutputBuffer to put output in (usually used by the Shell)154 int outputLevel_; //!< The level of the incoming output155 int softDebugLevel_[4]; //!< The soft debug level for each OutputDevice - the configurable maximal output level213 OutputHandler(); 214 ~OutputHandler(); 215 OutputHandler(const OutputHandler& rhs); //! Unused and undefined 216 217 std::list<OutputListener*> listeners_; //!< Array with all registered output listeners 218 int outputLevel_; //!< The level of the incoming output 219 LogFileWriter* logFile_; //!< Listener that writes to the log file 220 ConsoleWriter* consoleWriter_; //!< Listener for std::cout (just program beginning) 221 MemoryLogWriter* output_; //!< Listener that Stores ALL output below the current soft debug level 222 static int softDebugLevel_s; //!< Maximum of all soft debug levels. @note This is only static for faster access 156 223 }; 157 224 158 225 /** 159 @brief Redirects the output to the console and the logfile. 160 @param output The value that should be shown in the console 161 @return A reference to the OutputHandler itself 226 @brief 227 Interface for listening to output. 228 @remarks 229 Remember to register the listener (not done automatically!) 162 230 */ 231 class OutputListener 232 { 233 friend class OutputHandler; 234 235 public: 236 OutputListener(const std::string& name) 237 : outputStream_(NULL) 238 , name_(name) 239 , softDebugLevel_(OutputLevel::Info) 240 {} 241 virtual ~OutputListener() {} 242 243 //! Gets called whenever output is put into the stream 244 virtual void outputChanged(int level) {} 245 //! Returns the name of this output listener 246 const std::string& getOutputListenerName() const { return this->name_; } 247 //! Returns the soft debug level of the listener 248 int getSoftDebugLevel() const { return this->softDebugLevel_; } 249 //! Sets the soft debug level of the listener 250 void setSoftDebugLevel(int level) 251 { 252 this->softDebugLevel_ = level; 253 OutputHandler::getInstance().setSoftDebugLevel(this->name_, level); 254 } 255 256 protected: 257 std::ostream* outputStream_; //!< Pointer to the associated output stream, can be NULL 258 259 private: 260 const std::string name_; //!< Name of the listener, constant and unique! 261 int softDebugLevel_; //!< Current soft debug level that defines what kind of output is written to the stream 262 }; 263 163 264 template<class T> 164 OutputHandler& OutputHandler::output(const T& output) 165 { 166 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Console) >= this->outputLevel_) 167 std::cout << output; 168 169 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Logfile) >= this->outputLevel_) 265 inline OutputHandler& OutputHandler::output(const T& output) 266 { 267 for (std::list<OutputListener*>::const_iterator it = this->listeners_.begin(); it != this->listeners_.end(); ++it) 170 268 { 171 this->logfile_ << output; 172 this->logfile_.flush(); 269 if (this->outputLevel_ <= (*it)->softDebugLevel_ && (*it)->outputStream_ != NULL) 270 { 271 std::ostream& stream = *((*it)->outputStream_); 272 stream << output; 273 stream.flush(); 274 (*it)->outputChanged(this->outputLevel_); 275 } 173 276 } 174 175 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Shell) >= this->outputLevel_)176 (*this->outputBuffer_) << output;177 277 178 278 return *this; 179 279 } 180 181 /**182 @brief Overloading of the non-member << operator to redirect the output of classes with self defined '<< to std::ostream' operators to the console and the logfile.183 @param out The OutputHandler itself184 @param output The class that should be shown in the console185 @return The OutputHandler itself186 */187 template<class T>188 OutputHandler& operator<<(OutputHandler& out, const T& output)189 {190 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Console) >= out.getOutputLevel())191 std::cout << output;192 193 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Logfile) >= out.getOutputLevel())194 {195 out.getLogfile() << output;196 out.getLogfile().flush();197 }198 199 if (OutputHandler::getSoftDebugLevel(OutputHandler::LD_Shell) >= out.getOutputLevel())200 (*out.getOutputBuffer()) << output;201 202 return out;203 }204 280 } 205 281 -
code/branches/pickup2/src/libraries/util/Serialise.h
r5738 r6412 37 37 #include <cstring> 38 38 #include "util/Math.h" 39 #include "util/mbool.h" 39 40 40 41 namespace orxonox{ 41 42 // general template declaration 43 42 44 43 /** @brief returns the size of the variable in a datastream */ 45 template <class T> inline uint32_t returnSize( const T& );44 template <class T> inline uint32_t returnSize( const T& variable ); 46 45 /** @brief loads the value of a variable out of the bytestream and increases the mem pointer */ 47 template <class T> inline void loadAndIncrease( const T& , uint8_t*&);46 template <class T> inline void loadAndIncrease( const T& variable, uint8_t*& mem ); 48 47 /** @brief saves the value of a variable into the bytestream and increases the mem pointer */ 49 template <class T> inline void saveAndIncrease( const T& , uint8_t*&);48 template <class T> inline void saveAndIncrease( const T& variable, uint8_t*& mem ); 50 49 /** @brief checks whether the variable of type T is the same as in the bytestream */ 51 template <class T> inline bool checkEquality( const T&, uint8_t*);50 template <class T> inline bool checkEquality( const T& variable, uint8_t* mem ); 52 51 53 52 // =================== Template specialisation stuff ============= … … 203 202 return sizeof(uint32_t); 204 203 } 205 204 206 205 template <> inline void loadAndIncrease( const unsigned int& variable, uint8_t*& mem ) 207 206 { … … 376 375 double temp; 377 376 memcpy(&temp, mem, sizeof(uint64_t)); 378 *(long double*)( &variable ) = static_cast< constlong double>(temp);377 *(long double*)( &variable ) = static_cast<long double>(temp); 379 378 mem += returnSize( variable ); 380 379 } … … 471 470 return variable==Degree(*r); 472 471 } 473 474 472 473 // =========== Vector2 474 475 template <> inline uint32_t returnSize( const Vector2& variable ) 476 { 477 return returnSize( variable.x )+returnSize( variable.y ); 478 } 479 480 template <> inline void saveAndIncrease( const Vector2& variable, uint8_t*& mem ) 481 { 482 saveAndIncrease( variable.x, mem ); 483 saveAndIncrease( variable.y, mem ); 484 } 485 486 template <> inline void loadAndIncrease( const Vector2& variable, uint8_t*& mem ) 487 { 488 loadAndIncrease( variable.x, mem ); 489 loadAndIncrease( variable.y, mem ); 490 } 491 492 template <> inline bool checkEquality( const Vector2& variable, uint8_t* mem ) 493 { 494 return checkEquality(variable.x, mem) && checkEquality(variable.y, mem+returnSize(variable.x)); 495 } 496 497 // =========== Vector3 498 499 template <> inline uint32_t returnSize( const Vector3& variable ) 500 { 501 return returnSize( variable.x )+returnSize( variable.y )+returnSize( variable.z ); 502 } 503 504 template <> inline void saveAndIncrease( const Vector3& variable, uint8_t*& mem ) 505 { 506 saveAndIncrease( variable.x, mem ); 507 saveAndIncrease( variable.y, mem ); 508 saveAndIncrease( variable.z, mem ); 509 } 510 511 template <> inline void loadAndIncrease( const Vector3& variable, uint8_t*& mem ) 512 { 513 loadAndIncrease( variable.x, mem ); 514 loadAndIncrease( variable.y, mem ); 515 loadAndIncrease( variable.z, mem ); 516 } 517 518 template <> inline bool checkEquality( const Vector3& variable, uint8_t* mem ) 519 { 520 return checkEquality(variable.x, mem) && checkEquality(variable.y, mem+returnSize(variable.x)) && 521 checkEquality(variable.z, mem+returnSize(variable.x)+returnSize(variable.y)); 522 } 523 524 // =========== Vector4 525 526 template <> inline uint32_t returnSize( const Vector4& variable ) 527 { 528 return returnSize( variable.w )+returnSize( variable.x )+returnSize( variable.y )+returnSize( variable.z ); 529 } 530 531 template <> inline void saveAndIncrease( const Vector4& variable, uint8_t*& mem ) 532 { 533 saveAndIncrease( variable.w, mem ); 534 saveAndIncrease( variable.x, mem ); 535 saveAndIncrease( variable.y, mem ); 536 saveAndIncrease( variable.z, mem ); 537 } 538 539 template <> inline void loadAndIncrease( const Vector4& variable, uint8_t*& mem ) 540 { 541 loadAndIncrease( variable.w, mem ); 542 loadAndIncrease( variable.x, mem ); 543 loadAndIncrease( variable.y, mem ); 544 loadAndIncrease( variable.z, mem ); 545 } 546 547 template <> inline bool checkEquality( const Vector4& variable, uint8_t* mem ) 548 { 549 return checkEquality(variable.w, mem) && checkEquality(variable.x, mem+returnSize(variable.w)) && 550 checkEquality(variable.y, mem+returnSize(variable.w)+returnSize(variable.x)) && 551 checkEquality(variable.z, mem+returnSize(variable.w)+returnSize(variable.x)+returnSize(variable.y)); 552 } 553 554 // =========== Quaternion 555 556 template <> inline uint32_t returnSize( const Quaternion& variable ) 557 { 558 return returnSize( variable.w )+returnSize( variable.x )+returnSize( variable.y )+returnSize( variable.z ); 559 } 560 561 template <> inline void saveAndIncrease( const Quaternion& variable, uint8_t*& mem ) 562 { 563 saveAndIncrease( variable.w, mem ); 564 saveAndIncrease( variable.x, mem ); 565 saveAndIncrease( variable.y, mem ); 566 saveAndIncrease( variable.z, mem ); 567 } 568 569 template <> inline void loadAndIncrease( const Quaternion& variable, uint8_t*& mem ) 570 { 571 loadAndIncrease( variable.w, mem ); 572 loadAndIncrease( variable.x, mem ); 573 loadAndIncrease( variable.y, mem ); 574 loadAndIncrease( variable.z, mem ); 575 } 576 577 template <> inline bool checkEquality( const Quaternion& variable, uint8_t* mem ) 578 { 579 return checkEquality(variable.w, mem) && checkEquality(variable.x, mem+returnSize(variable.w)) && 580 checkEquality(variable.y, mem+returnSize(variable.w)+returnSize(variable.x)) && 581 checkEquality(variable.z, mem+returnSize(variable.w)+returnSize(variable.x)+returnSize(variable.y)); 582 } 583 584 // =========== ColourValue 585 586 template <> inline uint32_t returnSize( const ColourValue& variable ) 587 { 588 return returnSize( variable.r )+returnSize( variable.g )+returnSize( variable.b )+returnSize( variable.a ); 589 } 590 591 template <> inline void saveAndIncrease( const ColourValue& variable, uint8_t*& mem ) 592 { 593 saveAndIncrease( variable.r, mem ); 594 saveAndIncrease( variable.g, mem ); 595 saveAndIncrease( variable.b, mem ); 596 saveAndIncrease( variable.a, mem ); 597 } 598 599 template <> inline void loadAndIncrease( const ColourValue& variable, uint8_t*& mem ) 600 { 601 loadAndIncrease( variable.r, mem ); 602 loadAndIncrease( variable.g, mem ); 603 loadAndIncrease( variable.b, mem ); 604 loadAndIncrease( variable.a, mem ); 605 } 606 607 template <> inline bool checkEquality( const ColourValue& variable, uint8_t* mem ) 608 { 609 return checkEquality(variable.r, mem) && checkEquality(variable.g, mem+returnSize(variable.r)) && 610 checkEquality(variable.b, mem+returnSize(variable.r)+returnSize(variable.g)) && 611 checkEquality(variable.a, mem+returnSize(variable.r)+returnSize(variable.g)+returnSize(variable.b)); 612 } 613 614 // =========== mbool 615 616 template <> inline uint32_t returnSize( const mbool& variable ) 617 { 618 return returnSize( (unsigned char&)((mbool&)variable).getMemory() ); 619 } 620 621 template <> inline void saveAndIncrease( const mbool& variable, uint8_t*& mem ) 622 { 623 saveAndIncrease( (unsigned char&)((mbool&)variable).getMemory(), mem ); 624 } 625 626 template <> inline void loadAndIncrease( const mbool& variable, uint8_t*& mem ) 627 { 628 loadAndIncrease( (unsigned char&)((mbool&)variable).getMemory(), mem ); 629 } 630 631 template <> inline bool checkEquality( const mbool& variable, uint8_t* mem ) 632 { 633 return checkEquality( (unsigned char&)((mbool&)variable).getMemory(), mem ); 634 } 475 635 } 476 636 -
code/branches/pickup2/src/libraries/util/Singleton.h
r5929 r6412 56 56 57 57 //! Update method called by ClassSingletonManager (if used) 58 void updateSingleton(const Clock& time) { static_cast<T*>(T::singletonPtr_s)->update(time); }58 void preUpdateSingleton(const Clock& time) { static_cast<T*>(T::singletonPtr_s)->preUpdate(time); } 59 59 //! Empty update method for the static polymorphism 60 void update(const Clock& time) { } 60 void preUpdate(const Clock& time) { } 61 //! Update method called by ClassSingletonManager (if used) 62 void postUpdateSingleton(const Clock& time) { static_cast<T*>(T::singletonPtr_s)->postUpdate(time); } 63 //! Empty update method for the static polymorphism 64 void postUpdate(const Clock& time) { } 61 65 62 66 protected: -
code/branches/pickup2/src/libraries/util/StringUtils.cc
r5738 r6412 40 40 namespace orxonox 41 41 { 42 std::string BLANKSTRING ("");42 std::string BLANKSTRING; 43 43 44 44 std::string getUniqueNumberString() … … 54 54 { 55 55 size_t pos; 56 while ((pos = (*str).find(" ")) < (*str).length())57 (*str).erase(pos, 1);58 while ((pos = (*str).find("\t")) < (*str).length())59 (*str).erase(pos, 1);60 while ((pos = (*str).find("\n")) < (*str).length())61 (*str).erase(pos, 1);56 while ((pos = str->find(' ')) < str->length()) 57 str->erase(pos, 1); 58 while ((pos = str->find('\t')) < str->length()) 59 str->erase(pos, 1); 60 while ((pos = str->find('\n')) < str->length()) 61 str->erase(pos, 1); 62 62 } 63 63 … … 69 69 std::string getStripped(const std::string& str) 70 70 { 71 std::string output = std::string(str);71 std::string output(str); 72 72 strip(&output); 73 73 return output; … … 98 98 size_t quote = start - 1; 99 99 100 while ((quote = str.find(' \"', quote + 1)) != std::string::npos)100 while ((quote = str.find('"', quote + 1)) != std::string::npos) 101 101 { 102 102 size_t backslash = quote; … … 231 231 { 232 232 // Strip the line, whitespaces are disturbing 233 std::stringteststring = getStripped(str);233 const std::string& teststring = getStripped(str); 234 234 235 235 // There are four possible comment-symbols: … … 259 259 bool isEmpty(const std::string& str) 260 260 { 261 std::string temp = getStripped(str); 262 return ((temp == "") || (temp.size() == 0)); 261 return getStripped(str).empty(); 263 262 } 264 263 … … 303 302 for (size_t pos = 0; (pos = output.find('\f', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\f"); } 304 303 for (size_t pos = 0; (pos = output.find('\a', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\a"); } 305 for (size_t pos = 0; (pos = output.find('"' , pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\\""); }304 for (size_t pos = 0; (pos = output.find('"' , pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\\""); } 306 305 for (size_t pos = 0; (pos = output.find('\0', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\0"); } 307 306 … … 319 318 return str; 320 319 321 std::string output = "";320 std::string output; 322 321 for (size_t pos = 0; pos < str.size() - 1; ) 323 322 { … … 363 362 std::string getLowercase(const std::string& str) 364 363 { 365 std::string output = std::string(str);364 std::string output(str); 366 365 lowercase(&output); 367 366 return output; … … 387 386 std::string getUppercase(const std::string& str) 388 387 { 389 std::string output = std::string(str);388 std::string output(str); 390 389 uppercase(&output); 391 390 return output; -
code/branches/pickup2/src/libraries/util/SubString.cc
r5738 r6412 270 270 } 271 271 else 272 { 273 static std::string empty; 274 return empty; 275 } 272 return ""; 276 273 } 277 274 … … 557 554 void SubString::debug() const 558 555 { 559 printf("Substring-information::count=% d ::", this->strings.size());556 printf("Substring-information::count=%zd ::", this->strings.size()); 560 557 for (unsigned int i = 0; i < this->strings.size(); i++) 561 558 printf("s%d='%s'::", i, this->strings[i].c_str()); -
code/branches/pickup2/src/libraries/util/UtilPrereqs.h
r5929 r6412 87 87 class IntVector3; 88 88 class MultiType; 89 class OutputBuffer;90 class OutputBufferListener;91 89 class OutputHandler; 90 class OutputListener; 92 91 template <ScopeID::Value> 93 92 class Scope; … … 132 131 } 133 132 133 // Just so you don't have to include StringUtils.h everywhere just for this 134 namespace orxonox 135 { 136 extern _UtilExport std::string BLANKSTRING; 137 } 138 139 134 140 #endif /* _UtilPrereqs_H__ */ -
code/branches/pickup2/src/libraries/util/mbool.h
r5738 r6412 67 67 inline bool operator!() const 68 68 { return (!this->value_.bool_); } 69 69 70 70 inline unsigned char& getMemory(){ return value_.memory_; } 71 71
Note: See TracChangeset
for help on using the changeset viewer.