Changeset 6417 for code/trunk/src/libraries
- Timestamp:
- Dec 25, 2009, 10:23:58 PM (15 years ago)
- Location:
- code/trunk
- Files:
-
- 2 deleted
- 161 edited
- 2 copied
Legend:
- Unmodified
- Added
- Removed
-
code/trunk
- Property svn:mergeinfo changed
-
code/trunk/src/libraries/core/ArgumentCompletionFunctions.cc
r5929 r6417 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/trunk/src/libraries/core/BaseObject.cc
r5929 r6417 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/trunk/src/libraries/core/BaseObject.h
r5929 r6417 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/trunk/src/libraries/core/CMakeLists.txt
r6105 r6417 86 86 TOLUA_FILES 87 87 CommandExecutor.h 88 ConfigFileManager.h 89 Game.h 90 GameMode.h 91 GUIManager.h 88 92 Loader.h 89 93 LuaState.h 94 PathConfig.h 95 input/InputManager.h 96 input/KeyBinder.h 97 input/KeyBinderManager.h 90 98 DEFINE_SYMBOL 91 99 "CORE_SHARED_BUILD" -
code/trunk/src/libraries/core/ClassTreeMask.cc
r5929 r6417 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/trunk/src/libraries/core/CommandEvaluation.cc
r5781 r6417 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/trunk/src/libraries/core/CommandEvaluation.h
r5781 r6417 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/trunk/src/libraries/core/CommandExecutor.cc
r5929 r6417 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/trunk/src/libraries/core/CommandExecutor.h
r5781 r6417 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/trunk/src/libraries/core/CommandLineParser.cc
r6021 r6417 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/trunk/src/libraries/core/ConfigFileManager.cc
r5929 r6417 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/trunk/src/libraries/core/ConfigFileManager.h
r6105 r6417 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 _CoreExport bool config(const std::string& classname, const std::string& varname, const std::string& value); 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 57 61 _CoreExport bool tconfig(const std::string& classname, const std::string& varname, const std::string& value); 58 62 _CoreExport void reloadConfig(); … … 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/trunk/src/libraries/core/ConfigValueContainer.h
r5738 r6417 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/trunk/src/libraries/core/ConfigValueIncludes.h
r6105 r6417 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, entryname, sectionname, defvalue) \ 50 static orxonox::Identifier* identifier##varname = this->getIdentifier(); \ 51 orxonox::ConfigValueContainer* container##varname = identifier##varname->getConfigValueContainer(entryname); \ 52 if (!container##varname) \ 53 { \ 54 container##varname = new orxonox::ConfigValueContainer(type, identifier##varname, sectionname, entryname, defvalue, varname); \ 55 identifier##varname->addConfigValueContainer(entryname, 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, #varname, identifier##varname->getName(), 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/trunk/src/libraries/core/ConsoleCommandCompilation.cc
r6105 r6417 35 35 #include "util/Debug.h" 36 36 #include "util/ExprParser.h" 37 #include "util/StringUtils.h" 37 38 #include "ConsoleCommand.h" 38 39 … … 142 143 } 143 144 144 std::string output = "";145 std::string output; 145 146 while (file.good() && !file.eof()) 146 147 { … … 158 159 float calculate(const std::string& calculation) 159 160 { 160 ExprParser expr(calculation); 161 ExprParser expr; 162 expr.parse(calculation); 161 163 if (expr.getSuccess()) 162 164 { … … 165 167 COUT(3) << "Greetings from the restaurant at the end of the universe." << std::endl; 166 168 } 167 if ( expr.getRemains() != "")169 if (!expr.getRemains().empty()) 168 170 { 169 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; 170 172 } 171 173 return static_cast<float>(expr.getResult()); -
code/trunk/src/libraries/core/Core.cc
r6105 r6417 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" … … 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 ORXONOX_RELEASE 108 const unsigned int defaultLevelLogFile = 3; 109 #else 110 const unsigned int defaultLevelLogFile = 4; 111 #endif 112 SetConfigValueGeneric(ConfigFileType::Settings, softDebugLevelLogFile_, "softDebugLevelLogFile", "OutputHandler", defaultLevelLogFile) 113 .description("The maximum level of debug output shown in the log file"); 114 OutputHandler::getInstance().setSoftDebugLevel(OutputHandler::logFileOutputListenerName_s, this->softDebugLevelLogFile_); 115 116 SetConfigValue(language_, Language::getInstance().defaultLanguage_) 117 .description("The language of the in game text") 118 .callback(this, &CoreConfiguration::languageChanged); 119 SetConfigValue(bInitializeRandomNumberGenerator_, true) 120 .description("If true, all random actions are different each time you start the game") 121 .callback(this, &CoreConfiguration::initializeRandomNumberGenerator); 122 } 123 124 /** 125 @brief Callback function if the language has changed. 126 */ 127 void languageChanged() 128 { 129 // Read the translation file after the language was configured 130 Language::getInstance().readTranslatedLanguageFile(); 131 } 132 133 /** 134 @brief Sets the language in the config-file back to the default. 135 */ 136 void resetLanguage() 137 { 138 ResetConfigValue(language_); 139 } 140 141 void initializeRandomNumberGenerator() 142 { 143 static bool bInitialized = false; 144 if (!bInitialized && this->bInitializeRandomNumberGenerator_) 145 { 146 srand(static_cast<unsigned int>(time(0))); 147 rand(); 148 bInitialized = true; 149 } 150 } 151 152 int softDebugLevelLogFile_; //!< The debug level for the log file (belongs to OutputHandler) 153 std::string language_; //!< The language 154 bool bInitializeRandomNumberGenerator_; //!< If true, srand(time(0)) is called 155 }; 156 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 157 83 158 84 Core::Core(const std::string& cmdLine) … … 161 87 // Cleanup guard for external console commands that don't belong to an Identifier 162 88 , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands) 163 , configuration_(new CoreConfiguration()) // Don't yet create config values!164 89 , bGraphicsLoaded_(false) 165 90 { … … 218 143 this->languageInstance_.reset(new Language()); 219 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 220 150 // create persistent io console 221 151 this->ioConsole_.reset(new IOConsole()); … … 223 153 // creates the class hierarchy for all classes with factories 224 154 Identifier::createClassHierarchy(); 225 226 // Do this soon after the ConfigFileManager has been created to open up the227 // possibility to configure everything below here228 this->configuration_->initialise();229 155 230 156 // Load OGRE excluding the renderer and the render window … … 245 171 Core::~Core() 246 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 } 247 213 } 248 214 … … 296 262 } 297 263 298 /** 299 @brief Returns the configured language. 300 */ 301 /*static*/ const std::string& Core::getLanguage() 302 { 303 return Core::getInstance().configuration_->language_; 304 } 305 306 /** 307 @brief Sets the language in the config-file back to the default. 308 */ 309 /*static*/ void Core::resetLanguage() 310 { 311 Core::getInstance().configuration_->resetLanguage(); 264 //! Sets the language in the config-file back to the default. 265 void Core::resetLanguage() 266 { 267 ResetConfigValue(language_); 312 268 } 313 269 … … 360 316 void Core::preUpdate(const Clock& time) 361 317 { 362 // singletons from other libraries363 ScopedSingletonManager:: update<ScopeID::Root>(time);318 // Update singletons before general ticking 319 ScopedSingletonManager::preUpdate<ScopeID::Root>(time); 364 320 if (this->bGraphicsLoaded_) 365 321 { 366 // process input events367 this->inputManager_-> update(time);368 // process gui events369 this->guiManager_-> update(time);370 // graphics singletons from other libraries371 ScopedSingletonManager:: update<ScopeID::Graphics>(time);372 } 373 // process console text374 this->ioConsole_-> update(time);375 // process thread commands376 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); 377 333 } 378 334 379 335 void Core::postUpdate(const Clock& time) 380 336 { 337 // Update singletons just before rendering 338 ScopedSingletonManager::postUpdate<ScopeID::Root>(time); 381 339 if (this->bGraphicsLoaded_) 382 340 { 341 // Update singletons just before rendering 342 ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time); 383 343 // Render (doesn't throw) 384 this->graphicsManager_-> update(time);344 this->graphicsManager_->postUpdate(time); 385 345 } 386 346 } -
code/trunk/src/libraries/core/Core.h
r6105 r6417 34 34 35 35 #include <cassert> 36 #include <string> 36 37 #include <boost/scoped_ptr.hpp> 37 #include "util/OutputHandler.h"38 #include "util/Scope.h"39 38 #include "util/ScopeGuard.h" 40 39 #include "util/Singleton.h" 40 #include "core/OrxonoxClass.h" 41 41 42 42 namespace orxonox 43 43 { 44 class CoreConfiguration;45 46 44 /** 47 45 @brief … … 50 48 You should only create this singleton once because it destroys the identifiers! 51 49 */ 52 class _CoreExport Core : public Singleton<Core> 50 class _CoreExport Core : public Singleton<Core>, public OrxonoxClass 53 51 { 54 52 typedef Loki::ScopeGuardImpl0<void (*)()> SimpleScopeGuard; … … 69 67 void setConfigValues(); 70 68 71 static const std::string& getLanguage(); 72 static void resetLanguage(); 69 //! Returns the configured language. 70 const std::string& getLanguage() 71 { return this->language_; } 72 void resetLanguage(); 73 73 74 74 private: 75 75 Core(const Core&); //!< Don't use (undefined symbol) 76 77 void languageChanged(); 78 void initRandomNumberGenerator(); 76 79 77 80 void preUpdate(const Clock& time); … … 82 85 83 86 void setThreadAffinity(int limitToCPU); 84 87 // MANAGED SINGLETONS/OBJECTS 85 88 // Mind the order for the destruction! 86 89 scoped_ptr<PathConfig> pathConfig_; … … 92 95 scoped_ptr<Language> languageInstance_; 93 96 scoped_ptr<IOConsole> ioConsole_; 94 scoped_ptr<CoreConfiguration> configuration_;95 97 scoped_ptr<TclBind> tclBind_; 96 98 scoped_ptr<TclThreadManager> tclThreadManager_; 99 scoped_ptr<Scope<ScopeID::Root> > rootScope_; 97 100 // graphical 98 101 scoped_ptr<GraphicsManager> graphicsManager_; //!< Interface to OGRE 99 102 scoped_ptr<InputManager> inputManager_; //!< Interface to OIS 100 103 scoped_ptr<GUIManager> guiManager_; //!< Interface to GUI 101 scoped_ptr<Scope<ScopeID::Root> > rootScope_;102 104 scoped_ptr<Scope<ScopeID::Graphics> > graphicsScope_; 103 105 104 106 bool bGraphicsLoaded_; 105 static Core* singletonPtr_s; 107 int softDebugLevelLogFile_; //!< The debug level for the log file (belongs to OutputHandler) 108 std::string language_; //!< The language 109 bool bInitRandomNumberGenerator_; //!< If true, srand(time(0)) is called 110 111 static Core* singletonPtr_s; 106 112 }; 107 113 } -
code/trunk/src/libraries/core/DynLib.cc
r6073 r6417 79 79 m_hInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() ); 80 80 81 if ( !m_hInst)81 if (!m_hInst) 82 82 ThrowException( 83 83 General, … … 92 92 COUT(4) << "Unloading module " << mName << std::endl; 93 93 94 if ( DYNLIB_UNLOAD( m_hInst ))94 if (DYNLIB_UNLOAD( m_hInst )) 95 95 { 96 96 ThrowException( … … 132 132 return std::string(mac_errorBundle()); 133 133 #else 134 return std::string("");134 return ""; 135 135 #endif 136 136 } -
code/trunk/src/libraries/core/Event.cc
r5929 r6417 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/trunk/src/libraries/core/Event.h
r5929 r6417 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/trunk/src/libraries/core/EventIncludes.h
r5929 r6417 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/trunk/src/libraries/core/Executor.cc
r5738 r6417 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/trunk/src/libraries/core/Executor.h
r5738 r6417 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/trunk/src/libraries/core/Functor.h
r5929 r6417 35 35 #include "util/Debug.h" 36 36 #include "util/MultiType.h" 37 #include "util/StringUtils.h"38 37 39 38 namespace orxonox -
code/trunk/src/libraries/core/GUIManager.cc
r6105 r6417 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" 58 #include "Core.h" 55 59 #include "LuaState.h" 56 60 #include "PathConfig.h" … … 59 63 namespace orxonox 60 64 { 65 static void key_esc() 66 { GUIManager::getInstance().keyESC(); } 67 SetConsoleCommandShortcutExternAlias(key_esc, "keyESC"); 68 61 69 class CEGUILogger : public CEGUI::DefaultLogger 62 70 { … … 85 93 GUIManager* GUIManager::singletonPtr_s = 0; 86 94 95 SetConsoleCommandShortcut(GUIManager, showGUI).accessLevel(AccessLevel::User).defaultValue(1, false).defaultValue(2, true); 96 SetConsoleCommandShortcut(GUIManager, hideGUI).accessLevel(AccessLevel::User); 97 87 98 /** 88 99 @brief … … 101 112 , resourceProvider_(0) 102 113 , camera_(NULL) 114 , bShowIngameGUI_(false) 103 115 { 104 116 using namespace CEGUI; … … 113 125 // setup scripting 114 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_); 115 130 scriptModule_.reset(new LuaScriptModule(luaState_->getInternalLuaState())); 116 131 … … 127 142 128 143 // Initialise the basic Lua code 129 rootFileInfo_ = Resource::getInfo("InitialiseGUI.lua", "GUI"); 130 this->luaState_->doFile("InitialiseGUI.lua", "GUI", false); 144 this->luaState_->doFile("InitialiseGUI.lua"); 131 145 132 146 // Align CEGUI mouse with OIS mouse … … 156 170 This time value is then used to provide a fluent animation of the GUI. 157 171 */ 158 void GUIManager:: update(const Clock& time)172 void GUIManager::preUpdate(const Clock& time) 159 173 { 160 174 assert(guiSystem_); … … 203 217 For more details check out loadGUI_2.lua where the function presides. 204 218 */ 205 void GUIManager::showGUI(const std::string& name) 206 { 207 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 + "\")"); 208 252 } 209 253 … … 304 348 } 305 349 } 350 351 void GUIManager::subscribeEventHelper(CEGUI::Window* window, const std::string& event, const std::string& function) 352 { 353 window->subscribeScriptedEvent(event, function); 354 } 306 355 } -
code/trunk/src/libraries/core/GUIManager.h
r5929 r6417 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/trunk/src/libraries/core/Game.cc
r6021 r6417 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/trunk/src/libraries/core/Game.h
r5929 r6417 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/trunk/src/libraries/core/GameMode.h
r5929 r6417 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/trunk/src/libraries/core/GameState.cc
r5738 r6417 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/trunk/src/libraries/core/GraphicsManager.cc
r6105 r6417 100 100 101 101 // At first, add the root paths of the data directories as resource locations 102 Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem" , "dataRoot", false);102 Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem"); 103 103 // Load resources 104 resources_.reset(new XMLFile(" resources.oxr", "dataRoot"));104 resources_.reset(new XMLFile("DefaultResources.oxr")); 105 105 resources_->setLuaSupport(false); 106 106 Loader::open(resources_.get()); … … 109 109 if (PathConfig::isDevelopmentRun()) 110 110 { 111 Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem" , "externalDataRoot", false);112 extResources_.reset(new XMLFile("resources.oxr" , "externalDataRoot"));111 Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem"); 112 extResources_.reset(new XMLFile("resources.oxr")); 113 113 extResources_->setLuaSupport(false); 114 114 Loader::open(extResources_.get()); … … 208 208 shared_array<char> data(new char[output.str().size()]); 209 209 // Debug optimisations 210 const std::string outputStr = output.str();210 const std::string& outputStr = output.str(); 211 211 char* rawData = data.get(); 212 212 for (unsigned i = 0; i < outputStr.size(); ++i) … … 238 238 COUT(3) << "Setting up Ogre..." << std::endl; 239 239 240 if (ogreConfigFile_ == "")240 if (ogreConfigFile_.empty()) 241 241 { 242 242 COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl; 243 243 ModifyConfigValue(ogreConfigFile_, tset, "config.cfg"); 244 244 } 245 if (ogreLogFile_ == "")245 if (ogreLogFile_.empty()) 246 246 { 247 247 COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl; … … 285 285 { 286 286 // just to make sure the next statement doesn't segfault 287 if (ogrePluginsDirectory_ == "")288 ogrePluginsDirectory_ = ".";287 if (ogrePluginsDirectory_.empty()) 288 ogrePluginsDirectory_ = '.'; 289 289 290 290 boost::filesystem::path folder(ogrePluginsDirectory_); … … 341 341 need the time. So we shouldn't run into problems. 342 342 */ 343 void GraphicsManager:: update(const Clock& time)343 void GraphicsManager::postUpdate(const Clock& time) 344 344 { 345 345 Ogre::FrameEvent evt; … … 395 395 { 396 396 int orxonoxLevel; 397 switch (lml) 398 { 399 case Ogre::LML_TRIVIAL: 400 orxonoxLevel = this->ogreLogLevelTrivial_; 401 break; 402 case Ogre::LML_NORMAL: 403 orxonoxLevel = this->ogreLogLevelNormal_; 404 break; 405 case Ogre::LML_CRITICAL: 406 orxonoxLevel = this->ogreLogLevelCritical_; 407 break; 408 default: 409 orxonoxLevel = 0; 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: "; 410 421 } 411 422 OutputHandler::getOutStream(orxonoxLevel) 412 << "Ogre: "<< message << std::endl;423 << introduction << message << std::endl; 413 424 } 414 425 … … 440 451 { 441 452 assert(this->renderWindow_); 442 443 this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".jpg"); 453 this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png"); 444 454 } 445 455 } -
code/trunk/src/libraries/core/GraphicsManager.h
r6105 r6417 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_; } -
code/trunk/src/libraries/core/IOConsole.cc
r6105 r6417 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/trunk/src/libraries/core/IOConsole.h
r6105 r6417 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/trunk/src/libraries/core/IRC.cc
r5781 r6417 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/trunk/src/libraries/core/Identifier.cc
r5929 r6417 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/trunk/src/libraries/core/Identifier.h
r5929 r6417 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/trunk/src/libraries/core/Language.cc
r5929 r6417 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/trunk/src/libraries/core/Language.h
r5738 r6417 116 116 { 117 117 friend class Singleton<Language>; 118 friend class Core Configuration;118 friend class Core; 119 119 120 120 public: -
code/trunk/src/libraries/core/Loader.cc
r5929 r6417 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/trunk/src/libraries/core/LuaState.cc
r6105 r6417 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_); … … 185 173 } 186 174 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);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/trunk/src/libraries/core/LuaState.h
r5781 r6417 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/trunk/src/libraries/core/MemoryArchive.cc
r5940 r6417 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/trunk/src/libraries/core/MemoryArchive.h
r5781 r6417 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/trunk/src/libraries/core/Namespace.cc
r5781 r6417 173 173 { 174 174 if (i > 0) 175 output += "\n";175 output += '\n'; 176 176 177 177 output += (*it)->toString(indentation); -
code/trunk/src/libraries/core/NamespaceNode.cc
r5781 r6417 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/trunk/src/libraries/core/OrxonoxClass.cc
r6105 r6417 49 49 this->referenceCount_ = 0; 50 50 this->requestedDestruction_ = false; 51 // Optimisation 52 this->objectPointers_.reserve(6); 51 53 } 52 54 … … 55 57 { 56 58 // if (!this->requestedDestruction_) 57 // 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; 58 60 59 61 assert(this->referenceCount_ <= 0); 60 62 61 delete this->metaList_;63 this->unregisterObject(); 62 64 63 65 // parents_ exists only if isCreatingHierarchy() of the associated Identifier returned true while creating the class 64 66 if (this->parents_) 65 67 delete this->parents_; 66 68 67 69 // reset all weak pointers pointing to this object 68 70 for (std::set<WeakPtr<OrxonoxClass>*>::iterator it = this->weakPointers_.begin(); it != this->weakPointers_.end(); ) … … 76 78 this->requestedDestruction_ = true; 77 79 if (this->referenceCount_ == 0) 78 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; 79 92 } 80 93 -
code/trunk/src/libraries/core/OrxonoxClass.h
r6105 r6417 73 73 74 74 void destroy(); 75 void unregisterObject(); 75 76 76 77 /** @brief Function to collect the SetConfigValue-macro calls. */ … … 134 135 { return const_cast<OrxonoxClass*>(this)->getDerivedPointer<T>(classID); } 135 136 137 protected: 138 virtual void preDestroy() {} 139 136 140 private: 137 141 /** @brief Increments the reference counter (for smart pointers). */ … … 140 144 /** @brief Decrements the reference counter (for smart pointers). */ 141 145 inline void decrementReferenceCount() 142 { --this->referenceCount_; if (this->referenceCount_ == 0 && this->requestedDestruction_) { delete this; } } 143 146 { 147 --this->referenceCount_; 148 if (this->referenceCount_ == 0 && this->requestedDestruction_) 149 this->destroy(); 150 } 151 144 152 /** @brief Register a weak pointer which points to this object. */ 145 153 template <class T> -
code/trunk/src/libraries/core/PathConfig.cc
r6105 r6417 226 226 if (!CommandLineParser::getArgument("writingPathSuffix")->hasDefaultValue()) 227 227 { 228 std::stringdirectory(CommandLineParser::getValue("writingPathSuffix").getString());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 264 265 265 // Make sure the path exists, otherwise don't load modules … … 273 273 while (file != end) 274 274 { 275 std::stringfilename = file->BOOST_LEAF_FUNCTION();275 const std::string& filename = file->BOOST_LEAF_FUNCTION(); 276 276 277 277 // Check if the file ends with the exension in question … … 281 281 { 282 282 // We've found a helper file 283 std::stringlibrary = filename.substr(0, filename.size() - moduleextensionlength);283 const std::string& library = filename.substr(0, filename.size() - moduleextensionlength); 284 284 modulePaths.push_back((modulePath_ / library).file_string()); 285 285 } -
code/trunk/src/libraries/core/PathConfig.h
r5929 r6417 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/trunk/src/libraries/core/Resource.cc
r5781 r6417 28 28 29 29 #include "Resource.h" 30 31 #include <OgreException.h> 30 32 #include <OgreResourceGroupManager.h> 31 33 … … 34 36 std::string Resource::DEFAULT_GROUP(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); 35 37 36 DataStreamPtr Resource::open(const std::string& name , const std::string& group, bool bSearchGroupsIfNotFound)38 DataStreamPtr Resource::open(const std::string& name) 37 39 { 38 return Ogre::ResourceGroupManager::getSingleton().openResource(name, group, bSearchGroupsIfNotFound); 40 return Ogre::ResourceGroupManager::getSingleton().openResource(name, 41 Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true); 39 42 } 40 43 41 DataStreamListPtr Resource::openMulti(const std::string& pattern , const std::string& group)44 DataStreamListPtr Resource::openMulti(const std::string& pattern) 42 45 { 43 return Ogre::ResourceGroupManager::getSingleton().openResources(pattern, group); 46 DataStreamListPtr resources(new Ogre::DataStreamList()); 47 const Ogre::StringVector& groups = Ogre::ResourceGroupManager::getSingleton().getResourceGroups(); 48 for (Ogre::StringVector::const_iterator it = groups.begin(); it != groups.end(); ++it) 49 { 50 DataStreamListPtr temp = Ogre::ResourceGroupManager::getSingleton().openResources(pattern, *it); 51 resources->insert(resources->end(), temp->begin(), temp->end()); 52 } 53 return resources; 44 54 } 45 55 46 bool Resource::exists(const std::string& name , const std::string& group)56 bool Resource::exists(const std::string& name) 47 57 { 48 return Ogre::ResourceGroupManager::getSingleton().resourceExists(group, name); 58 try 59 { 60 Ogre::ResourceGroupManager::getSingleton().findGroupContainingResource(name); 61 return true; 62 } 63 catch (const Ogre::Exception&) 64 { 65 return false; 66 } 49 67 } 50 68 51 shared_ptr<ResourceInfo> Resource::getInfo(const std::string& name , const std::string& group)69 shared_ptr<ResourceInfo> Resource::getInfo(const std::string& name) 52 70 { 71 std::string group; 72 try 73 { 74 group = Ogre::ResourceGroupManager::getSingleton().findGroupContainingResource(name); 75 } 76 catch (const Ogre::Exception&) 77 { 78 return shared_ptr<ResourceInfo>(); 79 } 53 80 Ogre::FileInfoListPtr infos = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(group, name); 54 81 for (std::vector<Ogre::FileInfo>::const_iterator it = infos->begin(); it != infos->end(); ++it) … … 67 94 return shared_ptr<ResourceInfo>(); 68 95 } 96 97 StringVectorPtr Resource::findResourceNames(const std::string& pattern) 98 { 99 StringVectorPtr resourceNames(new Ogre::StringVector()); 100 const Ogre::StringVector& groups = Ogre::ResourceGroupManager::getSingleton().getResourceGroups(); 101 for (Ogre::StringVector::const_iterator it = groups.begin(); it != groups.end(); ++it) 102 { 103 StringVectorPtr temp = Ogre::ResourceGroupManager::getSingleton().findResourceNames(*it, pattern); 104 resourceNames->insert(resourceNames->end(), temp->begin(), temp->end()); 105 } 106 return resourceNames; 107 } 69 108 } -
code/trunk/src/libraries/core/Resource.h
r5929 r6417 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/trunk/src/libraries/core/ScopedSingletonManager.h
r6035 r6417 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 … … 54 55 55 56 template<ScopeID::Value scope> 56 static void update(const Clock& time)57 static void preUpdate(const Clock& time) 57 58 { 58 59 assert(Scope<scope>::isActive()); 59 60 for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(scope); it != getManagersByScope().upper_bound(scope); ++it) 60 it->second-> update(time);61 it->second->preUpdate(time); 61 62 } 62 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; 63 72 64 73 static std::map<std::string, ScopedSingletonManager*>& getManagers(); … … 112 121 113 122 //! Called every frame by the ScopedSingletonManager 114 void update(const Clock& time) 115 { 116 assert(Scope<scope>::isActive()); 117 // assuming T inherits Singleton<T> 118 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); 119 136 } 120 137 … … 145 162 try 146 163 { singletonPtr_ = new T(); } 164 catch (const InitialisationAbortedException& ex) 165 { COUT(3) << ex.getDescription() << std::endl; } 147 166 catch (...) 148 167 { COUT(1) << "Singleton creation failed: " << Exception::handleMessage() << std::endl; } … … 169 188 170 189 //! Called every frame by the ScopedSingletonManager 171 void update(const Clock& time)190 void preUpdate(const Clock& time) 172 191 { 173 192 assert(Scope<scope>::isActive()); 174 193 // assuming T inherits Singleton<T> 175 194 if (singletonPtr_ != NULL) 176 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); 177 205 } 178 206 -
code/trunk/src/libraries/core/Shell.cc
r6105 r6417 45 45 SetConsoleCommandShortcut(OutputHandler, debug); 46 46 47 Shell::Shell(const std::string& consoleName, bool bScrollable , bool bPrependOutputLevel)47 Shell::Shell(const std::string& consoleName, bool bScrollable) 48 48 : OutputListener(consoleName) 49 49 , inputBuffer_(new InputBuffer()) 50 50 , consoleName_(consoleName) 51 , bPrependOutputLevel_(bPrependOutputLevel)52 51 , bScrollable_(bScrollable) 53 52 { … … 63 62 this->configureInputBuffer(); 64 63 65 // Get a config file for the command history 66 this->commandHistoryConfigFileType_ = ConfigFileManager::getInstance().getNewConfigFileType(); 67 ConfigFileManager::getInstance().setFilename(this->commandHistoryConfigFileType_, "commandHistory.ini"); 68 69 // Use a stringstream object to buffer the output and get it line by line in update() 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 70 68 this->outputStream_ = &this->outputBuffer_; 71 69 … … 99 97 SetConfigValue(historyOffset_, 0) 100 98 .callback(this, &Shell::commandHistoryOffsetChanged); 101 SetConfigValueVectorGeneric(commandHistoryConfigFileType_, commandHistory_, std::vector<std::string>());99 setConfigValueGeneric(this, &commandHistory_, ConfigFileType::CommandHistory, "Shell", "commandHistory_", std::vector<std::string>()); 102 100 103 101 #ifdef ORXONOX_RELEASE … … 106 104 const unsigned int defaultLevel = 3; 107 105 #endif 108 SetConfigValueGeneric(ConfigFileType::Settings, softDebugLevel_, "softDebugLevel" + this->consoleName_, "OutputHandler", defaultLevel)106 setConfigValueGeneric(this, &softDebugLevel_, ConfigFileType::Settings, "OutputHandler", "softDebugLevel" + this->consoleName_, defaultLevel) 109 107 .description("The maximal level of debug output shown in the Shell"); 110 108 this->setSoftDebugLevel(this->softDebugLevel_); … … 163 161 164 162 for (unsigned int i = instance.historyOffset_; i < instance.commandHistory_.size(); ++i) 165 instance.addOutput Line(instance.commandHistory_[i], -1);163 instance.addOutput(instance.commandHistory_[i] + '\n', -1); 166 164 for (unsigned int i = 0; i < instance.historyOffset_; ++i) 167 instance.addOutput Line(instance.commandHistory_[i], -1);165 instance.addOutput(instance.commandHistory_[i] + '\n', -1); 168 166 } 169 167 */ … … 191 189 } 192 190 193 void Shell::addOutputLine(const std::string& line, int level) 194 { 195 // Make sure we really only have one line per line (no new lines!) 196 SubString lines(line, '\n'); 197 for (unsigned i = 0; i < lines.size(); ++i) 198 { 199 if (level <= this->softDebugLevel_) 200 this->outputLines_.push_front(lines[i]); 201 this->updateListeners<&ShellListener::lineAdded>(); 202 } 191 void Shell::addOutput(const std::string& text, LineType type) 192 { 193 this->outputBuffer_ << text; 194 this->outputChanged(type); 203 195 } 204 196 … … 214 206 } 215 207 216 std::list<std::string>::const_iterator Shell::getNewestLineIterator() const208 Shell::LineList::const_iterator Shell::getNewestLineIterator() const 217 209 { 218 210 if (this->scrollPosition_) … … 222 214 } 223 215 224 std::list<std::string>::const_iterator Shell::getEndIterator() const216 Shell::LineList::const_iterator Shell::getEndIterator() const 225 217 { 226 218 return this->outputLines_.end(); … … 234 226 } 235 227 236 std::stringShell::getFromHistory() const228 const std::string& Shell::getFromHistory() const 237 229 { 238 230 unsigned int index = mod(static_cast<int>(this->historyOffset_) - static_cast<int>(this->historyPosition_), this->maxHistoryLength_); … … 240 232 return this->commandHistory_[index]; 241 233 else 242 return "";243 } 244 245 void Shell::outputChanged(int l evel)234 return BLANKSTRING; 235 } 236 237 void Shell::outputChanged(int lineType) 246 238 { 247 239 bool newline = false; … … 259 251 newline = (!eof && !fail); 260 252 261 if (!newline && output == "")253 if (!newline && output.empty()) 262 254 break; 263 255 264 256 if (this->bFinishedLastLine_) 265 257 { 266 if (this->bPrependOutputLevel_) 267 output.insert(0, 1, static_cast<char>(level)); 268 269 this->outputLines_.push_front(output); 258 this->outputLines_.push_front(std::make_pair(output, static_cast<LineType>(lineType))); 270 259 271 260 if (this->scrollPosition_) … … 277 266 278 267 if (!this->scrollPosition_) 279 {280 268 this->updateListeners<&ShellListener::lineAdded>(); 281 }282 269 } 283 270 else 284 271 { 285 (*this->outputLines_.begin())+= output;272 this->outputLines_.front().first += output; 286 273 this->bFinishedLastLine_ = newline; 287 274 this->updateListeners<&ShellListener::onlyLastLineChanged>(); 288 275 } 276 this->bFinishedLastLine_ = newline; 289 277 290 278 } while (newline); … … 320 308 321 309 if (!CommandExecutor::execute(this->inputBuffer_->get())) 322 this->addOutputLine("Error: Can't execute \"" + this->inputBuffer_->get() + "\".", 1); 310 { 311 this->outputBuffer_ << "Error: Can't execute \"" << this->inputBuffer_->get() << "\"." << std::endl; 312 this->outputChanged(Error); 313 } 323 314 324 315 this->clearInput(); … … 328 319 { 329 320 this->inputBuffer_->set(CommandExecutor::complete(this->inputBuffer_->get())); 330 this->addOutputLine(CommandExecutor::hint(this->inputBuffer_->get()), -1); 321 this->outputBuffer_ << CommandExecutor::hint(this->inputBuffer_->get()) << std::endl; 322 this->outputChanged(Hint); 331 323 332 324 this->inputChanged(); … … 408 400 return; 409 401 unsigned int cursorPosition = this->getCursorPosition(); 410 std::stringinput_str(this->getInput().substr(0, cursorPosition)); // only search for the expression from the beginning of the inputline until the cursor position402 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 411 403 for (unsigned int newPos = this->historyPosition_ + 1; newPos <= this->historyOffset_; newPos++) 412 404 { … … 426 418 return; 427 419 unsigned int cursorPosition = this->getCursorPosition(); 428 std::stringinput_str(this->getInput().substr(0, cursorPosition)); // only search for the expression from the beginning420 const std::string& input_str(this->getInput().substr(0, cursorPosition)); // only search for the expression from the beginning 429 421 for (unsigned int newPos = this->historyPosition_ - 1; newPos > 0; newPos--) 430 422 { -
code/trunk/src/libraries/core/Shell.h
r6105 r6417 65 65 { 66 66 public: 67 Shell(const std::string& consoleName, bool bScrollable, bool bPrependOutputLevel = false); 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 }; 80 81 Shell(const std::string& consoleName, bool bScrollable); 68 82 ~Shell(); 69 83 … … 82 96 { return this->inputBuffer_->getCursorPosition(); } 83 97 84 inline std::stringgetInput() const98 inline const std::string& getInput() const 85 99 { return this->inputBuffer_->get(); } 86 100 87 std::list<std::string>::const_iterator getNewestLineIterator() const; 88 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; 89 104 90 void addOutput Line(const std::string& line, int level = 0);105 void addOutput(const std::string& text, LineType type = None); 91 106 void clearOutput(); 92 107 … … 103 118 104 119 void addToHistory(const std::string& command); 105 std::stringgetFromHistory() const;120 const std::string& getFromHistory() const; 106 121 void clearInput(); 107 122 // OutputListener … … 139 154 std::stringstream outputBuffer_; 140 155 bool bFinishedLastLine_; 141 std::list<std::string>outputLines_;142 std::list<std::string>::const_iteratorscrollIterator_;156 LineList outputLines_; 157 LineList::const_iterator scrollIterator_; 143 158 unsigned int scrollPosition_; 144 159 unsigned int historyPosition_; 145 ConfigFileType commandHistoryConfigFileType_;146 160 147 161 std::string promptPrefix_; 148 162 const std::string consoleName_; 149 const bool bPrependOutputLevel_;150 163 const bool bScrollable_; 151 164 -
code/trunk/src/libraries/core/SmartPtr.h
r5929 r6417 84 84 this->base_->decrementReferenceCount(); 85 85 } 86 86 87 87 inline const SmartPtr& operator=(int) 88 88 { -
code/trunk/src/libraries/core/SubclassIdentifier.h
r5929 r6417 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/trunk/src/libraries/core/TclBind.cc
r5929 r6417 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/trunk/src/libraries/core/TclBind.h
r5781 r6417 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/trunk/src/libraries/core/TclThreadManager.cc
r5929 r6417 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/trunk/src/libraries/core/TclThreadManager.h
r5781 r6417 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/trunk/src/libraries/core/Template.cc
r5781 r6417 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/trunk/src/libraries/core/Template.h
r5781 r6417 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/trunk/src/libraries/core/Thread.cc
r5738 r6417 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/trunk/src/libraries/core/Thread.h
r5738 r6417 50 50 private: 51 51 void threadLoop(); 52 52 53 53 Executor* executor_; 54 54 bool isWorking_; -
code/trunk/src/libraries/core/ThreadPool.cc
r5738 r6417 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/trunk/src/libraries/core/ThreadPool.h
r5738 r6417 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/trunk/src/libraries/core/WeakPtr.h
r5929 r6417 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/trunk/src/libraries/core/XMLFile.h
r5781 r6417 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/trunk/src/libraries/core/XMLPort.h
r5929 r6417 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/trunk/src/libraries/core/input/Button.cc
r5929 r6417 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/trunk/src/libraries/core/input/Button.h
r5781 r6417 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/trunk/src/libraries/core/input/InputBuffer.cc
r6105 r6417 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 … … 93 93 } 94 94 95 void InputBuffer::setMaxLength(unsigned int length) 96 { 97 this->maxLength_ = length; 98 if (this->buffer_.size() > length) 99 this->buffer_.resize(length); 100 } 101 95 102 void InputBuffer::set(const std::string& input, bool update) 96 103 { … … 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 -
code/trunk/src/libraries/core/input/InputBuffer.h
r6105 r6417 82 82 83 83 void setConfigValues(); 84 85 unsigned int getMaxLength() const { return this->maxLength_; } 86 void setMaxLength(unsigned int length); 84 87 85 88 template <class T> … … 175 178 std::list<BaseInputBufferListenerTuple*> listeners_; 176 179 std::string allowedChars_; 180 unsigned int maxLength_; 177 181 unsigned int cursor_; 178 182 -
code/trunk/src/libraries/core/input/InputCommands.h
r5781 r6417 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/trunk/src/libraries/core/input/InputDevice.h
r5929 r6417 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/trunk/src/libraries/core/input/InputManager.cc
r6105 r6417 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/trunk/src/libraries/core/input/InputManager.h
r6084 r6417 41 41 #include "InputState.h" 42 42 43 // tolua_begin 43 44 namespace orxonox 44 45 { … … 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. … … 96 99 was submitted while updating, the request will be postponed until the next update call. 97 100 */ 98 void update(const Clock& time);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(); … … 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 … … 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/trunk/src/libraries/core/input/InputPrereqs.h
r5781 r6417 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/trunk/src/libraries/core/input/InputState.cc
r5929 r6417 102 102 if (enterFunctor_) 103 103 (*enterFunctor_)(); 104 104 105 105 } 106 106 -
code/trunk/src/libraries/core/input/JoyStick.cc
r5781 r6417 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/trunk/src/libraries/core/input/JoyStickQuantityListener.h
r5781 r6417 29 29 /** 30 30 @file 31 @brief 31 @brief 32 32 */ 33 33 -
code/trunk/src/libraries/core/input/KeyBinder.cc
r5929 r6417 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/trunk/src/libraries/core/input/KeyBinder.h
r5929 r6417 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/trunk/src/libraries/core/input/KeyBinderManager.cc
r5929 r6417 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/trunk/src/libraries/core/input/KeyBinderManager.h
r5929 r6417 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/trunk/src/libraries/core/input/KeyDetector.cc
r5929 r6417 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/trunk/src/libraries/core/input/KeyDetector.h
r5929 r6417 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/trunk/src/libraries/core/input/Keyboard.cc
r5781 r6417 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/trunk/src/libraries/network/Client.cc
r5965 r6417 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 ); … … 111 113 return true; 112 114 } 113 115 114 116 void Client::printRTT(){ 115 117 COUT(0) << "Round trip time to server is " << ClientConnection::getRTT() << " ms" << endl; … … 137 139 { 138 140 timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD; 139 // COUT(3) << ".";141 // COUT(3) << '.'; 140 142 if ( isConnected() && isSynched_ ) 141 143 { … … 153 155 } 154 156 sendPackets(); // flush the enet queue 155 157 156 158 Connection::processQueue(); 157 159 if(gamestate.processGamestates()) … … 165 167 return; 166 168 } 167 169 168 170 void Client::connectionClosed() 169 171 { -
code/trunk/src/libraries/network/ClientConnection.cc
r5965 r6417 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; … … 146 146 this->connectionClosed(); 147 147 } 148 148 149 149 uint32_t ClientConnection::getRTT() 150 { 150 { 151 151 assert(server_); 152 152 return server_->roundTripTime; -
code/trunk/src/libraries/network/ClientConnection.h
r5961 r6417 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 … … 59 59 virtual void addPeer(ENetEvent* event); 60 60 virtual void removePeer(ENetEvent* event); 61 61 62 62 bool disconnectConnection(); 63 63 // enet stuff -
code/trunk/src/libraries/network/ClientConnectionListener.cc
r5929 r6417 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/trunk/src/libraries/network/ClientConnectionListener.h
r5929 r6417 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/trunk/src/libraries/network/ClientInformation.cc
r5961 r6417 46 46 namespace orxonox 47 47 { 48 48 49 49 50 50 ClientInformation *ClientInformation::head_=0; -
code/trunk/src/libraries/network/Connection.cc
r5929 r6417 75 75 void Connection::processQueue() { 76 76 ENetEvent event; 77 77 78 78 assert(this->host_); 79 79 -
code/trunk/src/libraries/network/Connection.h
r5929 r6417 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/trunk/src/libraries/network/FunctionCallManager.cc
r6073 r6417 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 } 42 FunctionCallManager::clientMap_[clientID] = new packet::FunctionCalls; 43 FunctionCallManager::clientMap_[clientID]->setClientID(clientID); 44 } 45 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/trunk/src/libraries/network/FunctionCallManager.h
r6073 r6417 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/trunk/src/libraries/network/GamestateClient.cc
r5929 r6417 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/trunk/src/libraries/network/GamestateHandler.cc
r5781 r6417 33 33 34 34 GamestateHandler *GamestateHandler::instance_=0; 35 35 36 36 GamestateHandler::GamestateHandler() 37 37 { -
code/trunk/src/libraries/network/GamestateManager.cc
r5929 r6417 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/trunk/src/libraries/network/NetworkFunction.cc
r5929 r6417 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/trunk/src/libraries/network/NetworkFunction.h
r5781 r6417 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/trunk/src/libraries/network/NetworkPrereqs.h
r5929 r6417 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/trunk/src/libraries/network/Server.cc
r5961 r6417 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 166 unsigned int Server::getRTT(unsigned int clientID){ … … 168 168 return ClientInformation::findClient(clientID)->getRTT(); 169 169 } 170 170 171 171 void Server::printRTT() 172 172 { … … 317 317 } 318 318 COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl; 319 319 320 320 // synchronise class ids 321 321 syncClassid(temp->getID()); 322 322 323 323 // now synchronise functionIDs 324 324 packet::FunctionIDs *fIDs = new packet::FunctionIDs(); … … 326 326 bool b = fIDs->send(); 327 327 assert(b); 328 328 329 329 temp->setSynched(true); 330 330 COUT(4) << "sending welcome" << std::endl; … … 344 344 return true; 345 345 } 346 346 347 347 void Server::disconnectClient( ClientInformation *client ){ 348 348 ServerConnection::disconnectClient( client ); -
code/trunk/src/libraries/network/Server.h
r5961 r6417 66 66 unsigned int shipID(){return 0;} 67 67 unsigned int playerID(){return 0;} 68 68 69 69 void addPeer(ENetEvent *event); 70 70 void removePeer(ENetEvent *event); 71 71 72 72 bool createClient(int clientID); 73 73 void disconnectClient( ClientInformation *client); -
code/trunk/src/libraries/network/ServerConnection.cc
r5929 r6417 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/trunk/src/libraries/network/ServerConnection.h
r5929 r6417 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/trunk/src/libraries/network/TrafficControl.cc
r6073 r6417 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]; … … 152 152 for(itvec = objectListTemp[gamestateID].begin(); itvec != objectListTemp[gamestateID].end(); itvec++) 153 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 back154 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;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 166 } 167 167 } … … 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; … … 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/trunk/src/libraries/network/TrafficControl.h
r6073 r6417 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 … … 131 131 { return instance_->ack(clientID, gamestateID); } 132 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 133 134 134 bool prioritySort(uint32_t clientID, obj i, obj j); 135 135 bool dataSort(obj i, obj j); -
code/trunk/src/libraries/network/packet/Acknowledgement.cc
r5781 r6417 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/trunk/src/libraries/network/packet/Chat.cc
r5781 r6417 35 35 namespace orxonox { 36 36 namespace packet { 37 37 38 38 #define PACKET_FLAGS_CHAT PacketFlag::Reliable 39 39 #define _PACKETID 0 -
code/trunk/src/libraries/network/packet/ClassID.cc
r5929 r6417 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/trunk/src/libraries/network/packet/ClassID.h
r6073 r6417 36 36 namespace packet { 37 37 38 38 39 39 /** 40 40 @author -
code/trunk/src/libraries/network/packet/DeleteObjects.cc
r5781 r6417 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/trunk/src/libraries/network/packet/FunctionCalls.cc
r5781 r6417 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/trunk/src/libraries/network/packet/FunctionIDs.cc
r5781 r6417 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/trunk/src/libraries/network/packet/FunctionIDs.h
r6073 r6417 36 36 namespace packet { 37 37 38 38 39 39 /** 40 40 @author -
code/trunk/src/libraries/network/packet/Gamestate.cc
r5929 r6417 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/trunk/src/libraries/network/packet/Packet.cc
r6105 r6417 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(){ -
code/trunk/src/libraries/network/synchronisable/CMakeLists.txt
r5781 r6417 2 2 NetworkCallbackManager.cc 3 3 Synchronisable.cc 4 SynchronisableSpecialisations.cc5 4 SynchronisableVariable.cc 6 5 ) -
code/trunk/src/libraries/network/synchronisable/NetworkCallback.h
r6073 r6417 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 { … … 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/trunk/src/libraries/network/synchronisable/NetworkCallbackManager.cc
r5781 r6417 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/trunk/src/libraries/network/synchronisable/NetworkCallbackManager.h
r5781 r6417 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/trunk/src/libraries/network/synchronisable/Synchronisable.cc
r5929 r6417 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/trunk/src/libraries/network/synchronisable/Synchronisable.h
r5929 r6417 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/trunk/src/libraries/network/synchronisable/SynchronisableVariable.h
r5781 r6417 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/trunk/src/libraries/tools/BillboardSet.cc
r5781 r6417 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/trunk/src/libraries/tools/CMakeLists.txt
r5929 r6417 23 23 LINK_LIBRARIES 24 24 core 25 network 25 26 SOURCE_FILES ${TOOLS_SRC_FILES} 26 27 ) -
code/trunk/src/libraries/tools/Mesh.cc
r5781 r6417 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/trunk/src/libraries/tools/ParticleInterface.cc
r5781 r6417 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/trunk/src/libraries/tools/ResourceLocation.cc
r5929 r6417 92 92 { 93 93 // Remove from Ogre paths 94 resourceGroup_. erase();94 resourceGroup_.clear(); 95 95 try 96 96 { -
code/trunk/src/libraries/tools/Shader.cc
r5781 r6417 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/trunk/src/libraries/tools/TextureGenerator.cc
r5781 r6417 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/trunk/src/libraries/tools/Timer.cc
r5929 r6417 112 112 this->deleteExecutor(); 113 113 } 114 114 115 115 /** 116 116 @brief Initializes the Timer -
code/trunk/src/libraries/tools/Timer.h
r5929 r6417 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/trunk/src/libraries/tools/interfaces/TimeFactorListener.h
r5781 r6417 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/trunk/src/libraries/tools/interfaces/ToolsInterfaceCompilation.cc
r5781 r6417 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/trunk/src/libraries/util/Clipboard.cc
r5958 r6417 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; … … 96 96 if (hData == NULL) 97 97 return ""; 98 std::string output = static_cast<char*>(GlobalLock(hData));98 std::string output(static_cast<char*>(GlobalLock(hData))); 99 99 GlobalUnlock(hData); 100 100 CloseClipboard(); … … 119 119 namespace orxonox 120 120 { 121 static std::string clipboard = ""; //!< Keeps the text of our internal clipboard121 static std::string clipboard; //!< Keeps the text of our internal clipboard 122 122 123 123 /** -
code/trunk/src/libraries/util/Clock.cc
r5929 r6417 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/trunk/src/libraries/util/Clock.h
r5929 r6417 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/trunk/src/libraries/util/Convert.h
r5738 r6417 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/trunk/src/libraries/util/Debug.h
r6105 r6417 71 71 using std::endl; 72 72 73 //! Adjust to discard certain output with level > hardDebugLevel at compile time 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) 74 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() 85 { 86 return 0; 87 } 75 88 } 76 89 … … 79 92 Logs text output: use exactly like std::cout, but specify an output 80 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 ;) 81 98 @example 82 99 COUT(3) << "Some info" << std::endl; … … 88 105 #define COUT(level) \ 89 106 /*if*/ (level > orxonox::hardDebugLevel) ? \ 90 0\107 orxonox::debugDummyFunction() \ 91 108 /*else*/ : \ 92 109 /*if*/ (level > orxonox::OutputHandler::getSoftDebugLevel()) ? \ 93 0\110 orxonox::debugDummyFunction() \ 94 111 /*else*/ : \ 95 112 orxonox::OutputHandler::getOutStream(level) -
code/trunk/src/libraries/util/Exception.cc
r5781 r6417 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/trunk/src/libraries/util/Exception.h
r5747 r6417 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/trunk/src/libraries/util/ExprParser.cc
r5738 r6417 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/trunk/src/libraries/util/ExprParser.h
r5738 r6417 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/trunk/src/libraries/util/Math.cc
r5738 r6417 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/trunk/src/libraries/util/Math.h
r5738 r6417 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/trunk/src/libraries/util/MathConvert.h
r5738 r6417 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/trunk/src/libraries/util/MultiType.h
r5738 r6417 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/trunk/src/libraries/util/MultiTypeValue.h
r5738 r6417 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/trunk/src/libraries/util/OutputHandler.cc
r6105 r6417 39 39 #include <cstdlib> 40 40 #include <fstream> 41 #include <iostream> 41 42 #include <sstream> 42 43 … … 76 77 #ifdef ORXONOX_PLATFORM_WINDOWS 77 78 char* pTempDir = getenv("TEMP"); 78 this->logFilename_ = std::string(pTempDir) + "/"+ logFileBaseName_g;79 this->logFilename_ = std::string(pTempDir) + '/' + logFileBaseName_g; 79 80 #else 80 81 this->logFilename_ = std::string("/tmp/") + logFileBaseName_g; … … 174 175 void outputChanged(int level) 175 176 { 176 // Read ostringstream and store it 177 this->output_.push_back(std::make_pair(level, this->buffer_.str())); 178 // Clear content and flags 179 this->buffer_.str(std::string()); 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 } 180 184 this->buffer_.clear(); 181 185 } … … 214 218 this->registerOutputListener(this->consoleWriter_); 215 219 216 this->output_ 220 this->output_ = new MemoryLogWriter(); 217 221 // We capture as much input as the listener with the highest level 218 222 this->output_->softDebugLevel_ = getSoftDebugLevel(); … … 224 228 { 225 229 delete this->logFile_; 230 delete this->consoleWriter_; 226 231 delete this->output_; 227 232 } -
code/trunk/src/libraries/util/Serialise.h
r5738 r6417 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/trunk/src/libraries/util/Singleton.h
r5929 r6417 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/trunk/src/libraries/util/StringUtils.cc
r5738 r6417 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/trunk/src/libraries/util/SubString.cc
r6061 r6417 270 270 } 271 271 else 272 { 273 static std::string empty; 274 return empty; 275 } 272 return ""; 276 273 } 277 274 -
code/trunk/src/libraries/util/UtilPrereqs.h
r6105 r6417 131 131 } 132 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 133 140 #endif /* _UtilPrereqs_H__ */ -
code/trunk/src/libraries/util/mbool.h
r5738 r6417 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.