From 9204c6ca624c21f21436e11d4aead126a481ec8a Mon Sep 17 00:00:00 2001 From: Stephan Vedder Date: Wed, 4 May 2022 13:42:30 +0200 Subject: Use range based loops where applicable --- Source/AI/navmesh.cpp | 14 +- Source/AI/sample.cpp | 38 +- Source/AI/sample_interfaces.cpp | 6 +- Source/Asset/Asset/animation.cpp | 304 ++++++----- Source/Asset/Asset/character.cpp | 26 +- Source/Asset/Asset/item.cpp | 30 +- Source/Asset/Asset/levelset.cpp | 5 +- Source/Asset/Asset/lipsyncfile.cpp | 4 +- Source/Asset/Asset/material.cpp | 5 +- Source/Asset/Asset/objectfile.cpp | 16 +- Source/Asset/Asset/reactions.cpp | 4 +- Source/Asset/Asset/syncedanimation.cpp | 8 +- Source/Asset/Asset/voicefile.cpp | 5 +- Source/Asset/assetmanagerthreadhandler.cpp | 6 +- Source/Editors/actors_editor.cpp | 137 ++--- Source/Editors/map_editor.cpp | 343 ++++++------ Source/Editors/sky_editor.cpp | 3 +- Source/GUI/IMUI/im_container.cpp | 46 +- Source/GUI/IMUI/im_divider.cpp | 110 ++-- Source/GUI/IMUI/im_element.cpp | 98 ++-- Source/GUI/IMUI/im_events.cpp | 8 +- Source/GUI/IMUI/im_support.cpp | 8 +- Source/GUI/IMUI/imgui.cpp | 114 ++-- Source/GUI/IMUI/imui.cpp | 3 +- Source/GUI/IMUI/imui_script.cpp | 4 +- Source/GUI/dimgui/dimgui.cpp | 262 +++++----- Source/GUI/dimgui/modmenu.cpp | 82 ++- Source/GUI/dimgui/settings_screen.cpp | 45 +- Source/Game/EntityDescription.cpp | 59 +-- Source/Game/characterscript.cpp | 24 +- Source/Game/color_tint_component.cpp | 3 +- Source/Game/level.cpp | 202 ++++--- Source/Game/levelinfo.cpp | 18 +- Source/Game/paths.cpp | 30 +- Source/Game/reactionscript.cpp | 6 +- Source/Game/savefile.cpp | 62 +-- Source/Game/terraininfo.cpp | 16 +- Source/Graphics/animationclient.cpp | 16 +- Source/Graphics/animationreader.cpp | 22 +- Source/Graphics/bloodsurface.cpp | 20 +- Source/Graphics/camera.cpp | 40 +- Source/Graphics/csg.cpp | 86 ++- Source/Graphics/detailobjectsurface.cpp | 12 +- Source/Graphics/drawbatch.cpp | 74 +-- Source/Graphics/dynamiclightcollection.cpp | 6 +- Source/Graphics/flares.cpp | 15 +- Source/Graphics/font_renderer.cpp | 4 +- Source/Graphics/halfedge.cpp | 18 +- Source/Graphics/hudimage.cpp | 3 +- Source/Graphics/kdtreecluster.cpp | 48 +- Source/Graphics/lightprobecollection.cpp | 26 +- Source/Graphics/model.cpp | 72 ++- Source/Graphics/modelsurfacewalker.cpp | 32 +- Source/Graphics/palette.cpp | 8 +- Source/Graphics/particles.cpp | 37 +- Source/Graphics/shaders.cpp | 61 ++- Source/Graphics/simplify.cpp | 53 +- Source/Graphics/skeleton.cpp | 176 +++---- Source/Graphics/terrain.cpp | 44 +- Source/Graphics/text.cpp | 4 +- Source/Graphics/textures.cpp | 19 +- Source/Images/nv_image.cpp | 4 +- Source/Images/texture_data.cpp | 4 +- Source/Internal/config.cpp | 16 +- Source/Internal/error.cpp | 6 +- Source/Internal/filesystem.cpp | 40 +- Source/Internal/hardware_specs.cpp | 18 +- Source/Internal/locale.cpp | 8 +- Source/Internal/modloading.cpp | 167 +++--- Source/Internal/path_set.cpp | 3 +- Source/Internal/timer.cpp | 8 +- Source/Internal/treestructure.cpp | 20 +- Source/JSON/jsoncpp.cpp | 19 +- Source/JSON/jsonhelper.cpp | 4 +- Source/Logging/logdata.cpp | 46 +- Source/Main/altmain.cpp | 12 +- Source/Main/engine.cpp | 201 +++---- Source/Main/scenegraph.cpp | 186 +++---- Source/Math/mat4.cpp | 4 +- Source/Memory/stack_allocator.cpp | 8 +- Source/Objects/ambientsoundobject.cpp | 3 +- Source/Objects/decalobject.cpp | 3 +- Source/Objects/dynamiclightobject.cpp | 3 +- Source/Objects/envobject.cpp | 41 +- Source/Objects/envobjectattach.cpp | 6 +- Source/Objects/group.cpp | 77 ++- Source/Objects/hotspot.cpp | 7 +- Source/Objects/itemobject.cpp | 47 +- Source/Objects/lightprobeobject.cpp | 3 +- Source/Objects/movementobject.cpp | 116 ++--- Source/Objects/navmeshconnectionobject.cpp | 27 +- Source/Objects/object.cpp | 19 +- Source/Objects/pathpointobject.cpp | 27 +- Source/Objects/placeholderobject.cpp | 20 +- Source/Objects/reflectioncaptureobject.cpp | 3 +- Source/Objects/riggedobject.cpp | 580 ++++++++++----------- Source/Objects/terrainobject.cpp | 25 +- .../Searchers/Seekers/actorobjectlevelseeker.cpp | 14 +- Source/Ogda/manifestresult.cpp | 4 +- Source/Online/Message/attach_to_message.cpp | 3 +- Source/Online/Message/movement_object_update.cpp | 4 +- Source/Online/online.cpp | 25 +- Source/Online/online_utility.cpp | 16 +- Source/Physics/bulletobject.cpp | 4 +- Source/Physics/bulletworld.cpp | 54 +- .../add_on/scripthelper/scripthelper.cpp | 5 +- Source/Scripting/angelscript/ascontext.cpp | 8 +- Source/Scripting/angelscript/ascrashdump.cpp | 26 +- Source/Scripting/angelscript/asdebugger.cpp | 36 +- Source/Scripting/angelscript/asfuncs.cpp | 144 +++-- Source/Scripting/angelscript/asprofiler.cpp | 58 +-- Source/Scripting/scriptfile.cpp | 14 +- Source/Scripting/scriptparams.cpp | 6 +- Source/Sound/al_audio.cpp | 8 +- Source/Sound/sound.cpp | 6 +- Source/Sound/soundtrack.cpp | 52 +- Source/Sound/threaded_sound_wrapper.cpp | 6 +- Source/UnitTests/block_allocator_tester.cpp | 6 +- Source/UserInput/input.cpp | 106 ++-- Source/UserInput/keyTranslator.cpp | 10 +- Source/UserInput/keyboard.cpp | 4 +- Source/UserInput/keycommands.cpp | 12 +- Source/UserInput/mouse.cpp | 4 +- Source/Utility/binn_util.cpp | 4 +- Source/Utility/strings.cpp | 6 +- Source/XML/Parsers/activemodsparser.cpp | 20 +- Source/XML/Parsers/assetloadwarningparser.cpp | 10 +- Source/XML/level_loader.cpp | 30 +- 128 files changed, 2540 insertions(+), 2996 deletions(-) diff --git a/Source/AI/navmesh.cpp b/Source/AI/navmesh.cpp index 756f2486..d6bae61a 100644 --- a/Source/AI/navmesh.cpp +++ b/Source/AI/navmesh.cpp @@ -319,8 +319,7 @@ namespace { bool Convex2DCollide(const vector points[2], const vector &axes) { bool intersects = true; - for(size_t i=0, len=axes.size(); i &point_vec = points[i]; @@ -460,8 +459,8 @@ void VoxellizeMesh(const vector &faces, const vector &verti points[0].push_back(vec2((vox_x+i%2)*VOXEL_SIZE+bounds[0], (vox_z+i/2)*VOXEL_SIZE+bounds[2])); } points[1].clear(); - for(int i=0; i<3; ++i){ - points[1].push_back(vec2(vert[i][0], vert[i][2])); + for(auto & i : vert){ + points[1].push_back(vec2(i[0], i[2])); } axes.clear(); axes.push_back(vec2(1,0)); @@ -474,8 +473,8 @@ void VoxellizeMesh(const vector &faces, const vector &verti if(Convex2DCollide(points, axes)){ old_points.clear(); new_points.clear(); - for(int i=0; i<3; ++i){ - old_points.push_back(vec3(vert[i][0], vert[i][1], vert[i][2])); + for(auto & i : vert){ + old_points.push_back(vec3(i[0], i[1], i[2])); } vector plane_normal; vector plane_d; @@ -520,8 +519,7 @@ void VoxellizeMesh(const vector &faces, const vector &verti for(int vox_x = 0; vox_x < voxel_dim[0]; ++vox_x){ int column_index = vox_z * voxel_dim[0] + vox_x; ColumnEntryList list = columns[column_index]; - for(ColumnEntryList::iterator iter = list.begin(); iter != list.end(); ++iter){ - const ColumnEntry &entry = *iter; + for(auto & entry : list){ vec3 pos; pos[0] = vox_x * VOXEL_SIZE + bounds[0]; pos[1] = entry.y * VOXEL_SIZE + bounds[1]; diff --git a/Source/AI/sample.cpp b/Source/AI/sample.cpp index 6c65668f..d332e3ec 100644 --- a/Source/AI/sample.cpp +++ b/Source/AI/sample.cpp @@ -51,8 +51,8 @@ Sample::Sample() : m_navQuery = dtAllocNavMeshQuery(); m_crowd = dtAllocCrowd(); - for (int i = 0; i < MAX_TOOLS; i++) - m_toolStates[i] = 0; + for (auto & toolState : m_toolStates) + toolState = 0; } Sample::~Sample() @@ -61,8 +61,8 @@ Sample::~Sample() dtFreeNavMesh(m_navMesh); dtFreeCrowd(m_crowd); delete m_tool; - for (int i = 0; i < MAX_TOOLS; i++) - delete m_toolStates[i]; + for (auto & toolState : m_toolStates) + delete toolState; } void Sample::setTool(SampleTool* tool) @@ -201,46 +201,46 @@ void Sample::handleUpdate(const float dt) void Sample::updateToolStates(const float dt) { - for (int i = 0; i < MAX_TOOLS; i++) + for (auto & toolState : m_toolStates) { - if (m_toolStates[i]) - m_toolStates[i]->handleUpdate(dt); + if (toolState) + toolState->handleUpdate(dt); } } void Sample::initToolStates(Sample* sample) { - for (int i = 0; i < MAX_TOOLS; i++) + for (auto & toolState : m_toolStates) { - if (m_toolStates[i]) - m_toolStates[i]->init(sample); + if (toolState) + toolState->init(sample); } } void Sample::resetToolStates() { - for (int i = 0; i < MAX_TOOLS; i++) + for (auto & toolState : m_toolStates) { - if (m_toolStates[i]) - m_toolStates[i]->reset(); + if (toolState) + toolState->reset(); } } void Sample::renderToolStates() { - for (int i = 0; i < MAX_TOOLS; i++) + for (auto & toolState : m_toolStates) { - if (m_toolStates[i]) - m_toolStates[i]->handleRender(); + if (toolState) + toolState->handleRender(); } } void Sample::renderOverlayToolStates(double* proj, double* model, int* view) { - for (int i = 0; i < MAX_TOOLS; i++) + for (auto & toolState : m_toolStates) { - if (m_toolStates[i]) - m_toolStates[i]->handleRenderOverlay(proj, model, view); + if (toolState) + toolState->handleRenderOverlay(proj, model, view); } } diff --git a/Source/AI/sample_interfaces.cpp b/Source/AI/sample_interfaces.cpp index d42109b8..c7e83dc7 100644 --- a/Source/AI/sample_interfaces.cpp +++ b/Source/AI/sample_interfaces.cpp @@ -94,11 +94,11 @@ void BuildContext::dumpLog(const char* format, ...) if (*msg == '\t') { int count = 1; - for (int j = 0; j < 4; ++j) + for (int j : TAB_STOPS) { - if (n < TAB_STOPS[j]) + if (n < j) { - count = TAB_STOPS[j] - n; + count = j - n; break; } } diff --git a/Source/Asset/Asset/animation.cpp b/Source/Asset/Asset/animation.cpp index 9ad6dd95..b3be6248 100644 --- a/Source/Asset/Asset/animation.cpp +++ b/Source/Asset/Asset/animation.cpp @@ -149,9 +149,7 @@ void Animation::CalcInvertBoneMats() { } void Animation::UpdateIKBones() { - for(unsigned i=0; i &weapon_matrices = anim_output.weapon_matrices; - for(unsigned j=0; jbone_mats.resize(num_bone_mats); mat4 temp; - for(unsigned j=0; jbone_mats.size(); j++){ + for(auto & bone_mat : keyframe->bone_mats){ fread(&temp.entries, sizeof(float), 16, file); - keyframe->bone_mats[j] = temp; + bone_mat = temp; } if(version>=7){ @@ -753,13 +747,13 @@ int Animation::ReadFromFile( FILE * file ) { fread(&num_events, sizeof(int), 1, file); keyframe->events.resize(num_events); - for(unsigned j=0; jevents.size(); j++){ - fread(&keyframe->events[j].which_bone, sizeof(int), 1, file); + for(auto & event : keyframe->events){ + fread(&event.which_bone, sizeof(int), 1, file); int string_size; fread(&string_size, sizeof(int), 1, file); vector string_buffer(string_size+1,'\0'); fread(&string_buffer[0], sizeof(char), string_size, file); - keyframe->events[j].event_string = &string_buffer[0]; + event.event_string = &string_buffer[0]; } } @@ -768,20 +762,20 @@ int Animation::ReadFromFile( FILE * file ) { fread(&num_ik_bones, sizeof(int), 1, file); keyframe->ik_bones.resize(num_ik_bones); - for(unsigned j=0; jik_bones.size(); j++){ + for(auto & ik_bone : keyframe->ik_bones){ // used to be ik_bones start and end vec3 filler; fread(&filler, sizeof(vec3), 1, file); fread(&filler, sizeof(vec3), 1, file); int path_length; fread(&path_length, sizeof(int), 1, file); - keyframe->ik_bones[j].bone_path.resize(path_length); - fread(&keyframe->ik_bones[j].bone_path[0], sizeof(int), path_length, file); + ik_bone.bone_path.resize(path_length); + fread(&ik_bone.bone_path[0], sizeof(int), path_length, file); int string_size; fread(&string_size, sizeof(int), 1, file); vector string_buffer(string_size+1,'\0'); fread(&string_buffer[0], sizeof(char), string_size, file); - keyframe->ik_bones[j].label = &string_buffer[0]; + ik_bone.label = &string_buffer[0]; } } @@ -790,13 +784,13 @@ int Animation::ReadFromFile( FILE * file ) { fread(&num_shape_keys, sizeof(int), 1, file); keyframe->shape_keys.resize(num_shape_keys); - for(unsigned j=0; jshape_keys.size(); j++){ - fread(&keyframe->shape_keys[j].weight, sizeof(float), 1, file); + for(auto & shape_key : keyframe->shape_keys){ + fread(&shape_key.weight, sizeof(float), 1, file); int string_size; fread(&string_size, sizeof(int), 1, file); vector string_buffer(string_size+1,'\0'); fread(&string_buffer[0], sizeof(char), string_size, file); - keyframe->shape_keys[j].label = &string_buffer[0]; + shape_key.label = &string_buffer[0]; } } if(version>=6){ @@ -804,13 +798,13 @@ int Animation::ReadFromFile( FILE * file ) { fread(&num_status_keys, sizeof(int), 1, file); keyframe->status_keys.resize(num_status_keys); - for(unsigned j=0; jstatus_keys.size(); j++){ - fread(&keyframe->status_keys[j].weight, sizeof(float), 1, file); + for(auto & status_key : keyframe->status_keys){ + fread(&status_key.weight, sizeof(float), 1, file); int string_size; fread(&string_size, sizeof(int), 1, file); vector string_buffer(string_size+1,'\0'); fread(&string_buffer[0], sizeof(char), string_size, file); - keyframe->status_keys[j].label = &string_buffer[0]; + status_key.label = &string_buffer[0]; } } if(centered){ @@ -910,21 +904,21 @@ AnimOutput mix( const AnimOutput &a, const AnimOutput &b, float alpha ) map ik_bones; map::iterator iter; - for(unsigned i=0; i::iterator iter; // Add shape keys from A - for(unsigned i=0; i status_keys; map::iterator iter; - for(unsigned i=0; i::iterator iter; // Add shape keys from A - for(unsigned i=0; i status_keys; map::iterator iter; - for(unsigned i=0; isecond; + for(auto & ik_bone_weight : ik_bone_weights){ + BlendedBonePath &blended_bone_path = ik_bone_weight.second; int bone = blended_bone_path.ik_bone.bone_path.back(); BoneTransform bone_transforms[4]; for(int j=0; j<4; ++j){ @@ -1435,8 +1429,8 @@ void Animation::GetMatrices( float normalized_time, AnimOutput &anim_output, con anim_output.ik_bones.resize(ik_bone_weights.size()); int index = 0; - for(IKBoneMap::iterator iter = ik_bone_weights.begin(); iter != ik_bone_weights.end(); ++iter){ - anim_output.ik_bones[index] = (*iter).second; + for(auto & ik_bone_weight : ik_bone_weights){ + anim_output.ik_bones[index] = ik_bone_weight.second; ++index; } @@ -1539,9 +1533,9 @@ float Animation::GetGroundSpeed( const BlendMap& blendmap ) const { vector Animation::GetEvents(int& anim_id, bool mirror) const { vector normalized_events; - for(unsigned i=0; i Animation::GetEvents(int& anim_id, bool mirror) normalized_event.event = the_event; normalized_event.anim_id = anim_id; - normalized_event.time = NormalizedFromLocal((float)keyframes[i].time); + normalized_event.time = NormalizedFromLocal((float)keyframe.time); } } @@ -1559,8 +1553,8 @@ vector Animation::GetEvents(int& anim_id, bool mirror) SkeletonAssetRef sar = Engine::Instance()->GetAssetManager()->LoadSync(skeleton_file_path); const SkeletonFileData& skeleton_file_data = sar->GetData(); const vector& symmetry = skeleton_file_data.symmetry; - for(size_t i=0, len=normalized_events.size(); i Animation::GetEvents(int& anim_id, bool mirror) void Animation::RecalcCaches() { // Cache which bones use IK in each frame - for(unsigned i=0; i events = aar->GetEvents(anim_id,false); - for(vector::const_iterator iter = events.begin(); - iter != events.end(); ++iter) + for(const auto & event : events) { - const NormalizedAnimationEvent& event = (*iter); if(event_str == event.event.event_string){ return aar->AbsoluteTimeFromNormalized(event.time) * 0.001f; } diff --git a/Source/Asset/Asset/character.cpp b/Source/Asset/Asset/character.cpp index a6d84e9d..5dc1a4d1 100644 --- a/Source/Asset/Asset/character.cpp +++ b/Source/Asset/Asset/character.cpp @@ -267,23 +267,23 @@ void Character::ReturnPaths( PathSet &path_set ) { //Materials::Instance()->ReturnRef(clothing_path)->ReturnPaths(path_set); Engine::Instance()->GetAssetManager()->LoadSync(clothing_path)->ReturnPaths(path_set); } - for(unsigned i=0; imodel_name, morph_info[i].label)); + for(auto & info : morph_info){ + if(info.num_steps == 1){ + path_set.insert("morph "+GetMorphPath(ofr->model_name, info.label)); } else { - for(int j=0; jmodel_name, oss.str())); } } } - for(StringMap::iterator iter = anim_paths.begin(); iter != anim_paths.end(); ++iter) { - ReturnAnimationAssetRef(iter->second)->ReturnPaths(path_set); + for(auto & anim_path : anim_paths) { + ReturnAnimationAssetRef(anim_path.second)->ReturnPaths(path_set); } - for(StringMap::iterator iter = attack_paths.begin(); iter != attack_paths.end(); ++iter) { + for(auto & attack_path : attack_paths) { //Attacks::Instance()->ReturnRef(iter->second)->ReturnPaths(path_set); - Engine::Instance()->GetAssetManager()->LoadSync(iter->second)->ReturnPaths(path_set); + Engine::Instance()->GetAssetManager()->LoadSync(attack_path.second)->ReturnPaths(path_set); } if(!voice_path.empty()){ //VoiceFiles::Instance()->ReturnRef(voice_path)->ReturnPaths(path_set); @@ -315,10 +315,10 @@ float Character::GetDefaultScale() { } bool Character::GetMorphMeta(const string& label, vec3 & start, vec3 & end) { - for(size_t i=0, len=morph_meta.size(); iReturnPaths(path_set); - if(!attachment[i].anim_base.empty()){ - ReturnAnimationAssetRef(attachment[i].anim_base)->ReturnPaths(path_set); + for(auto & i : attachment){ + if(i.exists){ + ReturnAnimationAssetRef(i.anim)->ReturnPaths(path_set); + if(!i.anim_base.empty()){ + ReturnAnimationAssetRef(i.anim_base)->ReturnPaths(path_set); } } } //ObjectFiles::Instance()->ReturnRef(obj_path)->ReturnPaths(path_set); Engine::Instance()->GetAssetManager()->LoadSync(obj_path)->ReturnPaths(path_set); - for(std::map::iterator iter = anim_overrides.begin(); - iter != anim_overrides.end(); ++iter) + for(auto & anim_override : anim_overrides) { - ReturnAnimationAssetRef(iter->second)->ReturnPaths(path_set); + ReturnAnimationAssetRef(anim_override.second)->ReturnPaths(path_set); } - for(std::map::iterator iter = anim_blend.begin(); - iter != anim_blend.end(); ++iter) + for(auto & iter : anim_blend) { - ReturnAnimationAssetRef(iter->second)->ReturnPaths(path_set); + ReturnAnimationAssetRef(iter.second)->ReturnPaths(path_set); } - for(std::map::iterator iter = attack_overrides.begin(); - iter != attack_overrides.end(); ++iter) + for(auto & attack_override : attack_overrides) { //Attacks::Instance()->ReturnRef(iter->second)->ReturnPaths(path_set); - Engine::Instance()->GetAssetManager()->LoadSync(iter->second)->ReturnPaths(path_set); + Engine::Instance()->GetAssetManager()->LoadSync(attack_override.second)->ReturnPaths(path_set); } - for(std::map::iterator iter = reaction_overrides.begin(); - iter != reaction_overrides.end(); ++iter) + for(auto & reaction_override : reaction_overrides) { //Reactions::Instance()->ReturnRef(iter->second)->ReturnPaths(path_set); - Engine::Instance()->GetAssetManager()->LoadSync(iter->second)->ReturnPaths(path_set); + Engine::Instance()->GetAssetManager()->LoadSync(reaction_override.second)->ReturnPaths(path_set); } } diff --git a/Source/Asset/Asset/levelset.cpp b/Source/Asset/Asset/levelset.cpp index d3452b3e..c03c741b 100644 --- a/Source/Asset/Asset/levelset.cpp +++ b/Source/Asset/Asset/levelset.cpp @@ -84,10 +84,9 @@ void LevelSet::ReportLoad() { } void LevelSet::ReturnPaths( PathSet &path_set ) { - for(std::list::iterator iter = level_paths_.begin(); - iter != level_paths_.end(); ++iter) + for(auto & level_path : level_paths_) { - path_set.insert("level "+(*iter)); + path_set.insert("level "+level_path); } } diff --git a/Source/Asset/Asset/lipsyncfile.cpp b/Source/Asset/Asset/lipsyncfile.cpp index 5fde962f..71da3275 100644 --- a/Source/Asset/Asset/lipsyncfile.cpp +++ b/Source/Asset/Asset/lipsyncfile.cpp @@ -144,8 +144,8 @@ void LipSyncFileReader::UpdateWeights() { iter->second = 0.0f; } - for(unsigned i=0; i &inner_map = iter->second; - for(std::map::const_iterator iter2 = inner_map.begin(); - iter2 != inner_map.end(); ++iter2) + for(const auto & pair : inner_map) { - const MaterialEvent &me = iter2 ->second; + const MaterialEvent &me = pair.second; if(!me.soundgroup.empty()){ //SoundGroupInfoCollection::Instance()->ReturnRef(me.soundgroup)->ReturnPaths(path_set); Engine::Instance()->GetAssetManager()->LoadSync(me.soundgroup)->ReturnPaths(path_set); diff --git a/Source/Asset/Asset/objectfile.cpp b/Source/Asset/Asset/objectfile.cpp index b2a92c5f..0774715a 100644 --- a/Source/Asset/Asset/objectfile.cpp +++ b/Source/Asset/Asset/objectfile.cpp @@ -292,18 +292,18 @@ void ObjectFile::ReturnPaths( PathSet& path_set ) if(!palette_map_path.empty()){ path_set.insert("texture "+palette_map_path); } - for(unsigned i=0; iReturnRef(m_detail_materials[i])->ReturnPaths(path_set); - Engine::Instance()->GetAssetManager()->LoadSync(m_detail_materials[i])->ReturnPaths(path_set); + Engine::Instance()->GetAssetManager()->LoadSync(detail_material)->ReturnPaths(path_set); } - for(unsigned i=0; i SyncedAnimationGroup::GetEvents(int& anim_id, bool mirrored) const { std::vector normalized_events; - for(unsigned i=0; i new_events; - const AnimationAsset& animation = (*animations[i].animation); + const AnimationAsset& animation = (*i.animation); new_events = animation.GetEvents(anim_id, mirrored); normalized_events.insert(normalized_events.end(), new_events.begin(), @@ -455,8 +455,8 @@ float SyncedAnimationGroup::AbsoluteTimeFromNormalized( float normalized_time ) void SyncedAnimationGroup::ReturnPaths( PathSet& path_set ) { path_set.insert("synced_animation "+path_); - for(unsigned i=0; iReturnPaths(path_set); + for(auto & animation : animations){ + animation.animation->ReturnPaths(path_set); } } diff --git a/Source/Asset/Asset/voicefile.cpp b/Source/Asset/Asset/voicefile.cpp index ce8b2c02..ffc38b87 100644 --- a/Source/Asset/Asset/voicefile.cpp +++ b/Source/Asset/Asset/voicefile.cpp @@ -93,11 +93,10 @@ const std::string & VoiceFile::GetVoicePath( const std::string voice ) { void VoiceFile::ReturnPaths( PathSet &path_set ) { path_set.insert("voice "+path_); - for(std::map::iterator iter = voice_paths.begin(); - iter != voice_paths.end(); ++iter) + for(auto & voice_path : voice_paths) { //SoundGroupInfoCollection::Instance()->ReturnRef(iter->second)->ReturnPaths(path_set); - Engine::Instance()->GetAssetManager()->LoadSync(iter->second)->ReturnPaths(path_set); + Engine::Instance()->GetAssetManager()->LoadSync(voice_path.second)->ReturnPaths(path_set); } } diff --git a/Source/Asset/assetmanagerthreadhandler.cpp b/Source/Asset/assetmanagerthreadhandler.cpp index 30216db5..ddc03175 100644 --- a/Source/Asset/assetmanagerthreadhandler.cpp +++ b/Source/Asset/assetmanagerthreadhandler.cpp @@ -121,8 +121,8 @@ AssetManagerThreadHandler::AssetManagerThreadHandler(int thread_count) : stop(fa AssetManagerThreadHandler::~AssetManagerThreadHandler() { stop = true; - for( unsigned i = 0; i < threads.size(); i++ ) { - threads[i]->join(); - threads[i] = NULL; + for(auto & thread : threads) { + thread->join(); + thread = NULL; } } diff --git a/Source/Editors/actors_editor.cpp b/Source/Editors/actors_editor.cpp index cba260aa..91f8c876 100644 --- a/Source/Editors/actors_editor.cpp +++ b/Source/Editors/actors_editor.cpp @@ -130,21 +130,21 @@ bool ActorsEditor_AddEntity(SceneGraph* scenegraph, Object* o, std::map } std::vector children; o->GetChildren(&children); - for(size_t i=0, len=children.size(); iGetID(); - if( ActorsEditor_AddEntity(scenegraph, children[i], id_remap, group_addition, level_loading) == false ) { + for(auto & child : children) { + int old_id = child->GetID(); + if( ActorsEditor_AddEntity(scenegraph, child, id_remap, group_addition, level_loading) == false ) { LOGE << "Failed adding child entity, removing from self" << std::endl; - o->ChildLost(children[i]); - delete children[i]; - children[i] = NULL; + o->ChildLost(child); + delete child; + child = NULL; } else { - if(old_id != children[i]->GetID() && id_remap == NULL) { + if(old_id != child->GetID() && id_remap == NULL) { LOGW << "id_remap is NULL when adding entity with children" << std::endl; continue; } if(id_remap != NULL) - id_remap->insert(std::pair(old_id, children[i]->GetID())); + id_remap->insert(std::pair(old_id, child->GetID())); } } @@ -166,9 +166,9 @@ bool ActorsEditor_AddEntity(SceneGraph* scenegraph, Object* o, std::map return true; } else { LOGE << "Failed at adding entity" << std::endl; - for( unsigned i = 0; i < children.size(); i++ ) { - if( children[i] ) { - children[i]->SetParent(NULL); + for(auto & child : children) { + if( child ) { + child->SetParent(NULL); } } return false; @@ -177,11 +177,9 @@ bool ActorsEditor_AddEntity(SceneGraph* scenegraph, Object* o, std::map } static void GetFlattenedDescList(EntityDescriptionList *desc_list, std::vector *flat_desc_list){ - for(size_t desc_index=0, len=desc_list->size(); - desc_indexat(desc_index); + EntityDescription *desc = &desc_index; flat_desc_list->push_back(desc); GetFlattenedDescList(&desc->children, flat_desc_list); } @@ -192,12 +190,9 @@ void LocalizeIDs(EntityDescriptionList *desc_list, bool keep_external_connection GetFlattenedDescList(desc_list, &flat_desc_list); std::map scene_ids; typedef std::map::iterator Iter; - for(size_t desc_index=0, len=flat_desc_list.size(); - desc_indexGetField(EDF_ID); + EntityDescriptionField *edf = desc->GetField(EDF_ID); if(edf){ int id; memread(&id, sizeof(int), 1, edf->data); @@ -214,21 +209,15 @@ void LocalizeIDs(EntityDescriptionList *desc_list, bool keep_external_connection } } // TODO: do this in O(n) instead of O(n^2) - for(size_t desc_index=0, len=flat_desc_list.size(); - desc_indexGetField(EDF_CONNECTIONS); + EntityDescriptionField *edf = desc->GetField(EDF_CONNECTIONS); if(edf) { std::vector connections; std::vector write_connections; edf->ReadIntVec(&connections); - for(size_t connection_index=0, len=connections.size(); - connection_indexsecond; @@ -245,11 +234,8 @@ void LocalizeIDs(EntityDescriptionList *desc_list, bool keep_external_connection std::vector connections; std::vector write_connections; edf->ReadItemConnectionDataVec(&connections); - for(size_t connection_index=0, len=connections.size(); - connection_indexsecond; @@ -266,12 +252,8 @@ void LocalizeIDs(EntityDescriptionList *desc_list, bool keep_external_connection std::vector connections; std::vector write_connections; edf->ReadNavMeshConnectionDataVec(&connections); - for(size_t connection_index=0, len=connections.size(); - connection_indexsecond; @@ -288,11 +270,8 @@ void LocalizeIDs(EntityDescriptionList *desc_list, bool keep_external_connection std::vector connections; std::vector write_connections; edf->ReadIntVec(&connections); - for(size_t connection_index=0, len=connections.size(); - connection_indexsecond; @@ -311,8 +290,7 @@ void LocalizeIDs(EntityDescriptionList *desc_list, bool keep_external_connection void ActorsEditor_CopySelectedEntities(SceneGraph* scenegraph, EntityDescriptionList *desc_list) { desc_list->clear(); // Add non-grouped objects to copy list - for (size_t i=0, len = scenegraph->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph->objects_) { if (obj->Selected() && obj->permission_flags&Object::CAN_COPY) { desc_list->resize(desc_list->size()+1); obj->GetDesc(desc_list->back()); @@ -322,9 +300,8 @@ void ActorsEditor_CopySelectedEntities(SceneGraph* scenegraph, EntityDescription EntityType GetTypeFromDesc( const EntityDescription& desc ) { EntityType type; - for (unsigned i = 0; i ActorsEditor_AddEntitiesAtPosition(const Path& source, Scen std::map id_remap; std::vector new_objects; - for (unsigned i = 0; i < desc_list.size(); i++) { - if (GetTypeFromDesc(desc_list[i]) == _decal_object) { + for (const auto & i : desc_list) { + if (GetTypeFromDesc(i) == _decal_object) { // Check we are not exceeding max decal limit if ((scenegraph->decal_objects_.size() - scenegraph->dynamic_decals.size()) >= scenegraph->kMaxStaticDecals) { DisplayError("Warning", "Static decal limit exceeded, cannot add new one!"); return new_objects; } } - Object* new_entity = CreateObjectFromDesc(desc_list[i]); + Object* new_entity = CreateObjectFromDesc(i); if( new_entity ) { vec3 offset = (new_entity->GetTranslation() - copied_center); vec3 pos = spawn_pos; @@ -553,12 +530,12 @@ std::vector ActorsEditor_AddEntitiesAtPosition(const Path& source, Scen } } - for (size_t i=0, len=new_objects.size(); iRemapReferences(id_remap); + for (auto & new_object : new_objects) { + new_object->RemapReferences(id_remap); } - for (size_t i=0, len=new_objects.size(); iReceiveObjectMessage(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); + for (auto & new_object : new_objects) { + new_object->ReceiveObjectMessage(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); } if( in_new_prefab ) { @@ -625,15 +602,15 @@ void ActorsEditor_AddEntitiesIntoPrefab(Object* obj,SceneGraph *scenegraph, con std::map id_remap; std::vector new_objects; - for (unsigned i = 0; i < desc_list.size(); i++) { - if (GetTypeFromDesc(desc_list[i]) == _decal_object) { + for (const auto & desc : desc_list) { + if (GetTypeFromDesc(desc) == _decal_object) { // Check we are not exceeding max decal limit if ((scenegraph->decal_objects_.size() - scenegraph->dynamic_decals.size()) >= scenegraph->kMaxStaticDecals) { DisplayError("Warning", "Static decal limit exceeded, cannot add new one!"); return; } } - Object* new_entity = CreateObjectFromDesc(desc_list[i]); + Object* new_entity = CreateObjectFromDesc(desc); if( new_entity ) { //Position offset from calculated relative origo. @@ -665,12 +642,12 @@ void ActorsEditor_AddEntitiesIntoPrefab(Object* obj,SceneGraph *scenegraph, con } } - for (size_t i=0, len=new_objects.size(); iRemapReferences(id_remap); + for (auto & new_object : new_objects) { + new_object->RemapReferences(id_remap); } - for (size_t i=0, len=new_objects.size(); iReceiveObjectMessage(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); + for (auto & new_object : new_objects) { + new_object->ReceiveObjectMessage(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); } vec3 orig_trans = prefab->GetTranslation(); @@ -684,9 +661,9 @@ void ActorsEditor_AddEntitiesIntoPrefab(Object* obj,SceneGraph *scenegraph, con prefab->SetRotation(quaternion()); prefab->SetScale(vec3(1.0f)); - for(size_t i=0, len=new_objects.size(); iSetParent(prefab); prefab->children.push_back(child); } @@ -758,12 +735,9 @@ void ActorsEditor_UnlocalizeIDs(EntityDescriptionList *desc_list, SceneGraph *sc GetFlattenedDescList(desc_list, &flat_desc_list); std::map scene_ids; typedef std::map::iterator Iter; - for(size_t desc_index=0, len=flat_desc_list.size(); - desc_indexGetField(EDF_ID); + EntityDescriptionField *edf = desc->GetField(EDF_ID); if(edf){ int id; memread(&id, sizeof(int), 1, edf->data); @@ -774,21 +748,15 @@ void ActorsEditor_UnlocalizeIDs(EntityDescriptionList *desc_list, SceneGraph *sc scene_ids.insert(std::pair(id, new_id)); } } - for(size_t desc_index=0, len=flat_desc_list.size(); - desc_indexGetField(EDF_CONNECTIONS); + EntityDescriptionField *edf = desc->GetField(EDF_CONNECTIONS); if(edf) { std::vector connections; std::vector write_connections; edf->ReadIntVec(&connections); - for(size_t connection_index=0, len=connections.size(); - connection_indexsecond; @@ -802,11 +770,8 @@ void ActorsEditor_UnlocalizeIDs(EntityDescriptionList *desc_list, SceneGraph *sc std::vector connections; std::vector write_connections; edf->ReadItemConnectionDataVec(&connections); - for(size_t connection_index=0, len=connections.size(); - connection_indexsecond; @@ -820,11 +785,8 @@ void ActorsEditor_UnlocalizeIDs(EntityDescriptionList *desc_list, SceneGraph *sc std::vector connections; std::vector write_connections; edf->ReadNavMeshConnectionDataVec(&connections); - for(size_t connection_index=0, len=connections.size(); - connection_indexsecond; @@ -838,11 +800,8 @@ void ActorsEditor_UnlocalizeIDs(EntityDescriptionList *desc_list, SceneGraph *sc std::vector connections; std::vector write_connections; edf->ReadIntVec(&connections); - for(size_t connection_index=0, len=connections.size(); - connection_indexsecond; diff --git a/Source/Editors/map_editor.cpp b/Source/Editors/map_editor.cpp index ba852653..333b7bf5 100644 --- a/Source/Editors/map_editor.cpp +++ b/Source/Editors/map_editor.cpp @@ -195,8 +195,7 @@ static Object::ConnectionType GetConnectionType(const std::vector &sele bool navmesh_connection_objects_only = true; bool single_placeholder_object = (selected.size()==1); bool hotspots_only = true; - for(unsigned i=0; iGetType(); if(type != _movement_object) { movement_objects_only = false; @@ -289,11 +288,8 @@ void MapEditor::RemoveObject(Object* o, SceneGraph* scenegraph, bool removed_by_ char buf[BUF_SIZE]; snprintf(buf, BUF_SIZE, "notify_deleted %d", o->GetID()); scenegraph->level->Message(buf); - for (SceneGraph::object_list::iterator iter = scenegraph->objects_.begin(); - iter != scenegraph->objects_.end(); - ++iter) + for (auto obj : scenegraph->objects_) { - Object* obj = *iter; obj->NotifyDeleted(o); } scenegraph->UnlinkObject(o); @@ -445,8 +441,8 @@ void MapEditor::RibbonItemClicked(const std::string& item, bool param) { LightProbeCollection& lpc = scenegraph_->light_probe_collection; for(size_t light_probe_index=0, len=lpc.light_probes.size(); light_probe_indexobjects_.begin(); - iter != scenegraph->objects_.end(); ++iter) + for (auto obj : scenegraph->objects_) { - Object* obj = (*iter); if (obj->Selected()) { obj->ReceiveObjectMessageVAList(type, args); } @@ -594,8 +588,7 @@ void MapEditor::Initialize(SceneGraph* s) { } void MapEditor::UpdateEnabledObjects() { - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { obj->editor_visible = type_visible_.IsTypeEnabled(obj->GetType()); if(!type_enable_.IsTypeEnabled(obj->GetType())){ obj->Select(false); @@ -604,8 +597,8 @@ void MapEditor::UpdateEnabledObjects() { } void MapEditor::InitializeColorHistory() { - for(int i = 0; i < kColorHistoryLen; ++i) { - color_history_[i] = vec4(1.0f); + for(auto & i : color_history_) { + i = vec4(1.0f); } } @@ -620,12 +613,11 @@ void DrawWeaponConnectionUI(const SceneGraph* scenegraph, IMUIContext &imui_cont vec3 cam_up = ActiveCameras::Get()->GetUpVector(); vec3 cam_right = cross(cam_facing, cam_up); int ui_index = 0; - for(unsigned i=0; imovement_objects_.size(); ++i){ - MovementObject* mo = (MovementObject*)scenegraph->movement_objects_[i]; + for(auto movement_object : scenegraph->movement_objects_){ + MovementObject* mo = (MovementObject*)movement_object; std::list list; mo->rigged_object()->AvailableItemSlots(item_ref, &list); - for(std::list::iterator iter = list.begin(); iter != list.end(); ++iter){ - AttachmentSlot& slot = *iter; + for(auto & slot : list){ mat4 circle_transform; circle_transform.SetColumn(0, cam_right * 0.1f); circle_transform.SetColumn(1, cam_up * 0.1f); @@ -808,9 +800,9 @@ static void DrawControlledFace(const Box& box_, const Object* object_, int face_ mat[1] = mat[0] * transform_test; for(int i=0; i<3; ++i){ for(int j=0; j<2; ++j){ - for(int k=0; k<2; ++k){ - points[0] = mat[k] * vec3(0.5f, 0.0f, -0.5f+0.5f*(float)i); - points[1] = mat[k] * vec3(0.5f, 1.0f-(float)j*2.0f, -0.5f+0.5f*(float)i); + for(const auto & k : mat){ + points[0] = k * vec3(0.5f, 0.0f, -0.5f+0.5f*(float)i); + points[1] = k * vec3(0.5f, 1.0f-(float)j*2.0f, -0.5f+0.5f*(float)i); DebugDraw::Instance()->AddLine(points[0], points[1], vec4(color, 1.0f), vec4(color, 0.0f), _delete_on_draw); } } @@ -840,8 +832,7 @@ void MapEditor::Draw() { if(!Graphics::Instance()->media_mode()){ if(active_tool_ != EditorTypes::CONNECT && active_tool_ != EditorTypes::DISCONNECT) { - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { if(obj->editor_visible){ const EntityType& type = obj->GetType(); @@ -860,8 +851,8 @@ void MapEditor::Draw() { } if(always_draw_hotspot_connections) { vec3 start = obj->GetTranslation(); - for(size_t j = 0; j < obj->connected_to.size(); ++j) { - vec3 end = scenegraph_->GetObjectFromID(obj->connected_to[j])->GetTranslation(); + for(int j : obj->connected_to) { + vec3 end = scenegraph_->GetObjectFromID(j)->GetTranslation(); DebugDraw::Instance()->AddLine(start, end, vec4(0.0f,1.0f,0.0f,0.8f), _delete_on_draw); } } @@ -908,14 +899,13 @@ void MapEditor::Draw() { float highlit_obj_dist = FLT_MAX; if(connection_type != Object::kCTNone) { - for(size_t i = 0; i < scenegraph_->objects_.size(); ++i) { - Object* obj = scenegraph_->objects_[i]; + for(auto obj : scenegraph_->objects_) { if(IsTypeEnabled(obj->GetType())) { bool add_object = obj->Selected(); if(!obj->Selected()) { - for(size_t j = 0; j < selected.size(); ++j) { - if(selected[j]->GetType() == _hotspot_object) { - Hotspot* selected_obj = (Hotspot*)selected[j]; + for(auto & j : selected) { + if(j->GetType() == _hotspot_object) { + Hotspot* selected_obj = (Hotspot*)j; if(selected_obj->AcceptConnectionsTo(*obj)) { if(obj->GetType() == _hotspot_object) { if(((Hotspot*)obj)->AcceptConnectionsFromImplemented()) { @@ -935,7 +925,7 @@ void MapEditor::Draw() { break; } } else { - add_object = obj->AcceptConnectionsFrom(connection_type, *selected[j]); + add_object = obj->AcceptConnectionsFrom(connection_type, *j); if(!add_object) { add_object = false; break; @@ -963,23 +953,23 @@ void MapEditor::Draw() { float highlit_obj_dist = FLT_MAX; std::vector connected_ids; connected_ids.reserve(64); - for(size_t i = 0; i < selected.size(); ++i) { - Object* selected_obj = selected[i]; + for(auto & i : selected) { + Object* selected_obj = i; box_objects.push_back(selected_obj); connected_ids.clear(); - selected[i]->GetConnectionIDs(&connected_ids); - for(size_t j = 0; j < connected_ids.size(); ++j) { - Object* obj = scenegraph_->GetObjectFromID(connected_ids[j]); + i->GetConnectionIDs(&connected_ids); + for(int connected_id : connected_ids) { + Object* obj = scenegraph_->GetObjectFromID(connected_id); GetClosest(mouseray, obj, highlit_obj, highlit_obj_dist); box_objects.push_back(obj); } - for(size_t j = 0; j < selected_obj->connected_to.size(); ++j) { - Object* obj = scenegraph_->GetObjectFromID(selected_obj->connected_to[j]); + for(int j : selected_obj->connected_to) { + Object* obj = scenegraph_->GetObjectFromID(j); GetClosest(mouseray, obj, highlit_obj, highlit_obj_dist); box_objects.push_back(obj); } - for(size_t j = 0; j < selected_obj->connected_from.size(); ++j) { - Object* obj = scenegraph_->GetObjectFromID(selected_obj->connected_from[j]); + for(int j : selected_obj->connected_from) { + Object* obj = scenegraph_->GetObjectFromID(j); GetClosest(mouseray, obj, highlit_obj, highlit_obj_dist); box_objects.push_back(obj); } @@ -996,8 +986,8 @@ void MapEditor::Draw() { selected_objects[i] = selected[i]; } std::vector &movement_objects = scenegraph_->movement_objects_; - for(size_t i=0, len=movement_objects.size(); irigged_object()->DrawBoneConnectUI(selected_objects, (int) selected.size(), imui_context, active_tool_, mo->GetID())){ QueueSaveHistoryState(); } @@ -1005,22 +995,22 @@ void MapEditor::Draw() { } } - for(size_t i = 0; i < selected.size(); ++i) { - vec3 start = selected[i]->GetTranslation(); - for(size_t j = 0; j < selected[i]->connected_to.size(); ++j) { - vec3 end = scenegraph_->GetObjectFromID(selected[i]->connected_to[j])->GetTranslation(); + for(auto & i : selected) { + vec3 start = i->GetTranslation(); + for(size_t j = 0; j < i->connected_to.size(); ++j) { + vec3 end = scenegraph_->GetObjectFromID(i->connected_to[j])->GetTranslation(); DebugDraw::Instance()->AddLine(start, end, vec4(0.0f,1.0f,0.0f,0.8f), _delete_on_draw); DebugDraw::Instance()->AddLine(start, end, vec4(0.0f,1.0f,0.0f,0.3f), _delete_on_draw, _DD_XRAY); } - for(size_t j = 0; j < selected[i]->connected_from.size(); ++j) { - vec3 end = scenegraph_->GetObjectFromID(selected[i]->connected_from[j])->GetTranslation(); + for(size_t j = 0; j < i->connected_from.size(); ++j) { + vec3 end = scenegraph_->GetObjectFromID(i->connected_from[j])->GetTranslation(); DebugDraw::Instance()->AddLine(start, end, vec4(1.0f,0.0f,0.0f,0.8f), _delete_on_draw); DebugDraw::Instance()->AddLine(start, end, vec4(1.0f,0.0f,0.0f,0.3f), _delete_on_draw, _DD_XRAY); } } - for(size_t i = 0; i < box_objects.size(); ++i) { - DrawBox(box_objects[i]->box_, box_objects[i], box_objects[i] == highlit_obj || box_objects[i]->Selected(), box_objects[i]->box_color); + for(auto & box_object : box_objects) { + DrawBox(box_object->box_, box_object, box_object == highlit_obj || box_object->Selected(), box_object->box_color); } } else { imui_context.ClearHot(); @@ -1087,8 +1077,7 @@ static Collision lineCheckSelected(SceneGraph::object_list &objects, const vec3 vec3 normal; int collided=-1; int collide=-1; - for(size_t i=0, len=objects.size(); iSelected()) { collide = obj->lineCheck(start,new_end,point,&normal); if(collide!=-1) { @@ -1298,14 +1287,13 @@ void MapEditor::Update(GameCursor* cursor) { } scenegraph_->level->SaveHistoryState(chunks, state_id); std::vector entities; - for(size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for(auto obj : scenegraph_->objects_){ if(!obj->parent && !obj->exclude_from_undo){ entities.push_back(obj); } } - for (unsigned i=0; iSaveHistoryState(chunks, state_id); + for (auto & entitie : entities) { + entitie->SaveHistoryState(chunks, state_id); } sky_editor_->SaveHistoryState(chunks, state_id); // Find out how many chunks have been changed @@ -1435,8 +1423,8 @@ void MapEditor::DeleteSelected() { objects_to_delete.push_back(obj); } } - for(size_t i=0, len=objects_to_delete.size(); i 1){ std::vector child_ids; - for(size_t i=0, len=selected.size(); iparent){ - child_ids.push_back(selected[i]->GetID()); + for(auto & i : selected){ + if(!i->parent){ + child_ids.push_back(i->GetID()); } } if(child_ids.size() > 1){ @@ -1482,16 +1470,16 @@ void MapEditor::GroupSelected() { bool MapEditor::ContainsPrefabsRecursively( std::vector objects ) { bool res = false; - for( unsigned i = 0; i < objects.size(); i++ ) { - if( objects[i]->IsGroupDerived() ) { - Group *g = static_cast(objects[i]); + for(auto & object : objects) { + if( object->IsGroupDerived() ) { + Group *g = static_cast(object); std::vector kids; - for( unsigned k = 0; k < g->children.size(); k++ ) { - kids.push_back(g->children[k].direct_ptr); + for(auto & k : g->children) { + kids.push_back(k.direct_ptr); } res = res || ContainsPrefabsRecursively(kids); - if( objects[i]->GetType() == _prefab ) { + if( object->GetType() == _prefab ) { res = true; } } @@ -1542,9 +1530,9 @@ int MapEditor::PrefabSelected() { } } else if(selected.size() > 0) { std::vector child_ids; - for(size_t i=0, len=selected.size(); iparent){ - child_ids.push_back(selected[i]->GetID()); + for(auto & i : selected){ + if(!i->parent){ + child_ids.push_back(i->GetID()); } } if(child_ids.size() > 0){ @@ -1579,32 +1567,29 @@ int MapEditor::PrefabSelected() { void MapEditor::UngroupSelected() { RibbonFlash(gui, "ungroup"); ReturnSelected(&selected); - for(size_t i=0, len=selected.size(); iGetType() == _group || selected[i]->GetType() == _prefab){ - selected[i]->SetParent(NULL); // Disconnects from any parent objects + for(auto & i : selected){ + if(i->GetType() == _group || i->GetType() == _prefab){ + i->SetParent(NULL); // Disconnects from any parent objects // Notify everyone that object is deleted const int BUF_SIZE = 255; char buf[BUF_SIZE]; - snprintf(buf, BUF_SIZE, "notify_deleted %d", selected[i]->GetID()); + snprintf(buf, BUF_SIZE, "notify_deleted %d", i->GetID()); scenegraph_->level->Message(buf); - for (SceneGraph::object_list::iterator iter = scenegraph_->objects_.begin(); - iter != scenegraph_->objects_.end(); - ++iter) + for (auto obj : scenegraph_->objects_) { - Object* obj = *iter; - obj->NotifyDeleted(selected[i]); + obj->NotifyDeleted(i); } - scenegraph_->UnlinkObject(selected[i]); - selected[i]->Dispose(); - delete(selected[i]); + scenegraph_->UnlinkObject(i); + i->Dispose(); + delete i; } } QueueSaveHistoryState(); } bool MapEditor::IsSomethingSelected() { - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]->Selected()) { + for (auto & object : scenegraph_->objects_) { + if (object->Selected()) { return true; } } @@ -1791,8 +1776,8 @@ void MapEditor::HandleShortcuts( const LineSegment &mouseray ) { Object::ConnectionType connection_type = GetConnectionType(selected); if(connection_type != Object::kCTNone) { // Disable connection if mouse is over object, so we can still alt-drag clone Collision mouseray_collision_selected = lineCheckActiveSelected(scenegraph_, mouseray.start, mouseray.end, NULL, NULL); - for(size_t i=0, len=selected.size(); iConnectTo(*hit_obj)){ // something_happened = true; //} } else if(active_tool_ == EditorTypes::DISCONNECT) { - Object* obj = selected[i]; + Object* obj = i; Object* hit_obj = c.hit_what; //if(obj->Disconnect(*hit_obj)){ //something_happened = true; @@ -1898,8 +1883,8 @@ void MapEditor::HandleShortcuts( const LineSegment &mouseray ) { } static bool MouseWasClickedThisTimestep(Mouse* mouse) { - for (int i = 0; i < Mouse::NUM_BUTTONS; i++) { - if (mouse->mouse_down_[i] == Mouse::CLICKED) return true; + for (int i : mouse->mouse_down_) { + if (i == Mouse::CLICKED) return true; } return false; } @@ -1910,34 +1895,34 @@ int MapEditor::ReplaceObjects( const std::vector& objects, const std::s ActorsEditor_UnlocalizeIDs(&add_desc_list_, scenegraph_); - for(size_t i = 0; i < objects.size(); i++) { - std::vector new_objects = ActorsEditor_AddEntitiesAtPosition(add_desc_list_source_, scenegraph_, add_desc_list_, objects[i]->GetTranslation(), create_as_prefab_); + for(auto object : objects) { + std::vector new_objects = ActorsEditor_AddEntitiesAtPosition(add_desc_list_source_, scenegraph_, add_desc_list_, object->GetTranslation(), create_as_prefab_); if(!new_objects.empty()){ - vec3 scale = objects[i]->GetScale(); - vec3 dims = objects[i]->box_.dims; + vec3 scale = object->GetScale(); + vec3 dims = object->box_.dims; vec3 target_dims = dims * scale; if(create_as_prefab_) { Prefab* prefab = static_cast(new_objects[0]); vec3 prefab_scale = target_dims / prefab->original_scale_; prefab->SetScale(prefab->original_scale_ * prefab_scale); - prefab->SetRotation(objects[i]->GetRotation()); - prefab->SetTranslation(objects[i]->GetTranslation()); + prefab->SetRotation(object->GetRotation()); + prefab->SetTranslation(object->GetTranslation()); prefab->PropagateTransformsDown(true); } else { - for(size_t j = 0; j < new_objects.size(); j++) { - vec3 new_dims = new_objects[j]->box_.dims; + for(auto & new_object : new_objects) { + vec3 new_dims = new_object->box_.dims; vec3 target_scale = target_dims / new_dims; - new_objects[j]->SetScale(target_scale); - new_objects[j]->SetRotation(objects[i]->GetRotation()); - new_objects[j]->SetTranslation(objects[i]->GetTranslation()); + new_object->SetScale(target_scale); + new_object->SetRotation(object->GetRotation()); + new_object->SetTranslation(object->GetTranslation()); } } } - RemoveObject(objects[i], scenegraph_, true); + RemoveObject(object, scenegraph_, true); } QueueSaveHistoryState(); @@ -2072,8 +2057,8 @@ static Collision GetSelectableInLineSegment(SceneGraph *scenegraph, const LineSe void CalculateGroupString(Object* obj, std::string& str) { if(obj->GetType() == _group || obj->GetType() == _prefab){ Group* group = (Group*)obj; - for(size_t i=0, len=group->children.size(); ichildren[i].direct_ptr, str); + for(auto & i : group->children){ + CalculateGroupString(i.direct_ptr, str); } } else { str = str + obj->obj_file; @@ -2081,8 +2066,7 @@ void CalculateGroupString(Object* obj, std::string& str) { } void MapEditor::SelectAll(){ - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { EntityType type = obj->GetType(); if(type_enable_.IsTypeEnabled(type) && obj->permission_flags & Object::CAN_SELECT && !obj->parent){ obj->Select(true); @@ -2098,8 +2082,7 @@ void MapEditor::ReloadAllPrefabs() { while( active_depth ) { active_depth = false; prefabs.clear(); - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { if( obj->GetGroupDepth() == current_depth ) { active_depth = true; if(obj->GetType() == _prefab){ @@ -2108,8 +2091,8 @@ void MapEditor::ReloadAllPrefabs() { } } - for(unsigned i = 0; i < prefabs.size(); i++) { - ReloadPrefab(prefabs[i],GetSceneGraph()); + for(auto & prefab : prefabs) { + ReloadPrefab(prefab,GetSceneGraph()); } current_depth++; } @@ -2117,8 +2100,7 @@ void MapEditor::ReloadAllPrefabs() { void MapEditor::ReloadPrefabs(const Path& path) { std::vector prefabs; - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { if(obj->GetType() == _prefab){ Prefab* prefab = static_cast(obj); if(strmtch(prefab->prefab_path.GetFullPath(),path.GetFullPath())) { @@ -2127,8 +2109,8 @@ void MapEditor::ReloadPrefabs(const Path& path) { } } - for(unsigned i = 0; i < prefabs.size(); i++) { - ReloadPrefab(prefabs[i],GetSceneGraph()); + for(auto & prefab : prefabs) { + ReloadPrefab(prefab,GetSceneGraph()); } } @@ -2154,8 +2136,8 @@ bool MapEditor::ReloadPrefab(Object *obj, SceneGraph* scenegraph) { prefab->GetBottomUpCompleteChildren(&ret_children); - for( unsigned i = 0; i < ret_children.size(); i++) { - RemoveObject(ret_children[i], scenegraph, true); + for(auto & i : ret_children) { + RemoveObject(i, scenegraph, true); } EntityDescriptionList desc_list; @@ -2244,24 +2226,21 @@ bool MapEditor::CheckForSelections( const LineSegment& mouseray ) { } if(KeyCommand::CheckPressed(keyboard, KeyCommand::kSelectSimilar, KIMF_LEVEL_EDITOR_GENERAL)) { std::vector selected_string; - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { if(obj->GetType() == _group || obj->GetType() == _prefab){ CalculateGroupString(obj, obj->obj_file); } } - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { if(obj->Selected()){ selected_string.push_back(obj->obj_file); } } - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { if(!obj->Selected() && obj->permission_flags & Object::CAN_SELECT){ const std::string& to_string = obj->obj_file; - for (size_t j = 0; j < selected_string.size(); j++) { - if (to_string == selected_string[j] ){ + for (auto & j : selected_string) { + if (to_string == j ){ obj->Select(true); break; } @@ -2299,8 +2278,8 @@ bool MapEditor::CheckForSelections( const LineSegment& mouseray ) { } void MapEditor::DeselectAll(SceneGraph *scenegraph) { - for(size_t i=0, len=scenegraph->objects_.size(); iobjects_[i]->Select(false); + for(auto & object : scenegraph->objects_) { + object->Select(false); } } @@ -2339,11 +2318,8 @@ void MapEditor::SaveEntities(TiXmlNode* root) { const float _difference_threshold = 0.000001f; SceneGraph::object_list ordered_objects = scenegraph_->objects_; std::sort(ordered_objects.begin(), ordered_objects.end(), IDCompare); - for (SceneGraph::object_list::iterator iter = ordered_objects.begin(); - iter != ordered_objects.end(); - ++iter) + for (auto obj : ordered_objects) { - Object* obj = *iter; // Only save object if it has no parent and is not an exact duplicate of another object at same transform if(!obj->parent && !obj->exclude_from_save) { if( ClosestMatch(obj->GetTransform(), matrices) <= _difference_threshold ) @@ -2497,8 +2473,8 @@ void MapEditor::SavePrefab(bool do_overwrite) { doc.LinkEndChild(parent); EntityDescriptionList descriptions; - for( unsigned i = 0; i < group->children.size(); i++) { - const ScriptParamMap &script_param_map = group->children[i].direct_ptr->GetScriptParams()->GetParameterMap(); + for(auto & i : group->children) { + const ScriptParamMap &script_param_map = i.direct_ptr->GetScriptParams()->GetParameterMap(); const ScriptParamMap::const_iterator it = script_param_map.find("No Save"); if(it != script_param_map.end()){ const ScriptParam ¶m = it->second; @@ -2508,13 +2484,13 @@ void MapEditor::SavePrefab(bool do_overwrite) { } EntityDescription desc; - group->children[i].direct_ptr->GetDesc(desc); + i.direct_ptr->GetDesc(desc); descriptions.push_back(desc); } LocalizeIDs(&descriptions, false); - for( unsigned i = 0; i < descriptions.size(); i++ ) { - descriptions[i].SaveToXML(parent); + for(auto & description : descriptions) { + description.SaveToXML(parent); //group->children[i].direct_ptr->SaveToXML(parent); } doc.SaveFile(buf); @@ -2543,8 +2519,7 @@ void MapEditor::SaveSelected() { // write out entities TiXmlElement* parent = new TiXmlElement("ActorObjects"); doc.LinkEndChild(parent); - for(size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for(auto obj : scenegraph_->objects_) { if (obj->Selected()) { obj->SaveToXML(parent); } @@ -2589,8 +2564,7 @@ void MapEditor::BringAllToCurrentState(int old_state){ // Create map for easy saved-chunk lookup Type_ID_Time_ChunkMap save_states; // Loop through saved chunks to populate lookup map - for(std::list::iterator iter = state_history_.chunks.begin(); iter != state_history_.chunks.end(); ++iter) { - SavedChunk& chunk = (*iter); + for(auto & chunk : state_history_.chunks) { save_states[chunk.type][chunk.obj_id][chunk.state_id] = &chunk; } @@ -2609,16 +2583,16 @@ void MapEditor::BringAllToCurrentState(int old_state){ } } // Loop through each chunk and set each object to the most appropriate saved chunk - for(Type_ID_Time_ChunkMap::iterator iter = save_states.begin(); iter != save_states.end(); ++iter) { - const ChunkType::ChunkType &type = iter->first; - ID_Time_ChunkMap &submap = iter->second; - for(ID_Time_ChunkMap::iterator iter = submap.begin(); iter != submap.end(); ++iter) { + for(auto & save_state : save_states) { + const ChunkType::ChunkType &type = save_state.first; + ID_Time_ChunkMap &submap = save_state.second; + for(auto & iter : submap) { SavedChunk* the_chunk = NULL; - Time_ChunkMap &timeline = iter->second; + Time_ChunkMap &timeline = iter.second; // Find the last entry that is before the current time - for(Time_ChunkMap::iterator iter2 = timeline.begin(); iter2 != timeline.end(); ++iter2) { - const int &time = iter2->first; - SavedChunk *chunk = iter2->second; + for(auto & iter2 : timeline) { + const int &time = iter2.first; + SavedChunk *chunk = iter2.second; if(time == state_history_.current_state) { the_chunk = chunk; } @@ -2651,8 +2625,7 @@ void MapEditor::BringAllToCurrentState(int old_state){ } } - for(size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for(auto obj : scenegraph_->objects_){ static const int kBufSize = 256; char msg[kBufSize]; FormatString(msg, kBufSize, "added_object %d", obj->GetID()); @@ -2666,8 +2639,8 @@ void MapEditor::BringAllToCurrentState(int old_state){ scenegraph_->SendMessageToAllObjects(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); // Restore selection - for(size_t i=0, len=selected_ids.size(); iGetObjectFromID(selected_ids[i]); + for(int selected_id : selected_ids){ + Object* obj = scenegraph_->GetObjectFromID(selected_id); if(obj){ obj->Select(true); } @@ -2755,8 +2728,8 @@ void MapEditor::AddLightProbes() { // Cover entire level with probes vec3 minval = vec3(FLT_MAX, FLT_MAX, FLT_MAX); vec3 maxval = vec3(-FLT_MAX, -FLT_MAX, -FLT_MAX); - for (size_t i = 0, len = scenegraph_->visible_objects_.size(); i < len; ++i) { - vec3 objtrans = scenegraph_->visible_objects_[i]->GetTranslation(); + for (auto & visible_object : scenegraph_->visible_objects_) { + vec3 objtrans = visible_object->GetTranslation(); maxval.x() = max(maxval.x(), objtrans.x()); minval.x() = min(minval.x(), objtrans.x()); maxval.y() = max(maxval.y(), objtrans.y()); @@ -2793,8 +2766,8 @@ void MapEditor::ToggleImposter() { void MapEditor::SetImposter(bool set) { ReturnSelected(&selected); - for(unsigned i=0; iSetImposter(set); + for(auto & i : selected){ + i->SetImposter(set); } } @@ -2894,8 +2867,8 @@ int MapEditor::CreateObject( const std::string& path) { std::string file_type; Path source; ActorsEditor_LoadEntitiesFromFile(path, desc_list, &file_type,&source); - for(unsigned i=0; iGetID(); } else { @@ -2908,9 +2881,9 @@ int MapEditor::CreateObject( const std::string& path) { void MapEditor::ReturnSelected(std::vector *selected_objects) { selected_objects->clear(); - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]->Selected()) { - selected_objects->push_back(scenegraph_->objects_[i]); + for (auto & object : scenegraph_->objects_) { + if (object->Selected()) { + selected_objects->push_back(object); } } } @@ -2932,8 +2905,7 @@ bool MapEditor::IsTypeEnabled( EntityType type ) { void MapEditor::SetTypeEnabled( EntityType type, bool enabled ) { type_enable_.SetTypeEnabled(type, enabled); - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { if(!type_enable_.IsTypeEnabled(obj->GetType())){ obj->Select(false); } @@ -2946,8 +2918,7 @@ bool MapEditor::IsTypeVisible( EntityType type ) { void MapEditor::SetTypeVisible( EntityType type, bool visible ) { type_visible_.SetTypeEnabled(type, visible); - for (size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for (auto obj : scenegraph_->objects_) { obj->editor_visible = type_visible_.IsTypeEnabled(obj->GetType()); } } @@ -2971,11 +2942,8 @@ Object* MapEditor::GetSelectedCameraObject() { Object* selected = NULL; bool multiple = false; // Check for any camera preview objects - for(SceneGraph::object_list::iterator iter = scenegraph_->objects_.begin(); - iter != scenegraph_->objects_.end(); - ++iter) + for(auto obj : scenegraph_->objects_) { - Object* obj = *iter; if(obj->GetType() == _placeholder_object){ PlaceholderObject* po = (PlaceholderObject*)obj; if(po->GetSpecialType() == PlaceholderObject::kCamPreview){ @@ -2989,11 +2957,8 @@ Object* MapEditor::GetSelectedCameraObject() { } // If multiple camera preview objects are found, then check for any that are selected if(multiple){ - for(SceneGraph::object_list::iterator iter = scenegraph_->objects_.begin(); - iter != scenegraph_->objects_.end(); - ++iter) + for(auto obj : scenegraph_->objects_) { - Object* obj = *iter; if(obj->GetType() == _placeholder_object){ PlaceholderObject* po = (PlaceholderObject*)obj; if(po->GetSpecialType() == PlaceholderObject::kCamPreview && po->Selected()){ @@ -3015,8 +2980,7 @@ void MapEditor::UpdateGPUSkinning() { } void MapEditor::CarveAgainstTerrain() { - for(std::vector::iterator iter = scenegraph_->visible_static_meshes_.begin(); iter != scenegraph_->visible_static_meshes_.end(); ++iter){ - EnvObject* eo = *iter; + for(auto eo : scenegraph_->visible_static_meshes_){ if(eo->Selected()){ CSGResultCombined results; if(CollideObjects(*scenegraph_->bullet_world_, @@ -3574,11 +3538,8 @@ static bool GetMouseTransformation( } static void EndTransformation(SceneGraph *scenegraph, EditorTypes::Tool type, Object* control_obj, ControlEditorInfo* control_editor_info, GameCursor* cursor) { - for(SceneGraph::object_list::iterator iter = scenegraph->objects_.begin(); - iter != scenegraph->objects_.end(); - ++iter) + for(auto obj : scenegraph->objects_) { - Object* obj = *iter; if (obj->Selected()) { obj->HandleTransformationOccurred(); } @@ -3631,8 +3592,8 @@ void MapEditor::UpdateTransformTool(SceneGraph *scenegraph, EditorTypes::Tool ty ActorsEditor_UnlocalizeIDs(©_desc_list, scenegraph); MapEditor::DeselectAll(scenegraph); std::vector new_objects; - for (size_t i=0, len=copy_desc_list.size(); ipermission_flags & Object::CAN_SELECT){ @@ -3648,16 +3609,13 @@ void MapEditor::UpdateTransformTool(SceneGraph *scenegraph, EditorTypes::Tool ty LOGE << "Failed to entity" << std::endl; } } - for (size_t i=0, len=new_objects.size(); iReceiveObjectMessage(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); + for (auto & new_object : new_objects) { + new_object->ReceiveObjectMessage(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); } } state_ = MapEditor::kTransformDrag; - for (SceneGraph::object_list::iterator iter = scenegraph->objects_.begin(); - iter != scenegraph->objects_.end(); - ++iter) + for (auto obj : scenegraph->objects_) { - Object* obj = *iter; obj->start_transform.translation = obj->GetTranslation(); obj->start_transform.rotation = obj->GetRotation(); obj->start_transform.scale = obj->GetScale(); @@ -3673,11 +3631,8 @@ void MapEditor::UpdateTransformTool(SceneGraph *scenegraph, EditorTypes::Tool ty } else if (state_ == MapEditor::kTransformDrag && transformation_happened) { // continue std::vector moved_objects; PROFILER_ZONE(g_profiler_ctx, "Updating transform"); - for (SceneGraph::object_list::iterator iter = scenegraph->objects_.begin(); - iter != scenegraph->objects_.end(); - ++iter) + for (auto obj : scenegraph->objects_) { - Object* obj = *iter; if (obj->Selected()) { obj->SetTranslation(obj->start_transform.translation + curr_tool_transform.translation); obj->SetRotation(curr_tool_transform.rotation * obj->start_transform.rotation); @@ -3693,8 +3648,8 @@ void MapEditor::UpdateTransformTool(SceneGraph *scenegraph, EditorTypes::Tool ty std::ostringstream oss; oss << "moved_objects"; - for(size_t i=0, len=moved_objects.size(); ilevel->Message(oss.str()); diff --git a/Source/Editors/sky_editor.cpp b/Source/Editors/sky_editor.cpp index 276b3a0b..5e0b194e 100644 --- a/Source/Editors/sky_editor.cpp +++ b/Source/Editors/sky_editor.cpp @@ -519,8 +519,7 @@ void SkyEditor::SaveHistoryState( std::list &chunk_list, int state_i bool SkyEditor::ReadChunk( SavedChunk &the_chunk ) { bool something_changed = false; EntityDescription &desc = the_chunk.desc; - for(unsigned i=0; isetOwnerParent( _owner, this ); } - for( FEMap::iterator it = floatingContents.begin(); - it != floatingContents.end(); - ++it ) { - it->second->getElement()->setOwnerParent(_owner, this); + for(auto & floatingContent : floatingContents) { + floatingContent.second->getElement()->setOwnerParent(_owner, this); } } @@ -254,10 +252,8 @@ void IMContainer::clear() { floatingContents.clear(); - for( FEMap::iterator it = deletemap.begin(); - it != deletemap.end(); - ++it ) { - delete it->second; + for(auto & it : deletemap) { + delete it.second; } // clear the contained element @@ -306,10 +302,8 @@ void IMContainer::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) contents->update( delta, drawOffset + drawDisplacement + contentsOffset, guistate); } - for( FEMap::iterator it = floatingContents.begin(); - it != floatingContents.end(); - ++it ) { - AHFloatingElement* floatingElement = it->second; + for(auto & floatingContent : floatingContents) { + AHFloatingElement* floatingElement = floatingContent.second; floatingElement->getElement()->update( delta, drawOffset + drawDisplacement + floatingElement->relativePos, guistate ); if(floatingContents.empty()) { @@ -361,10 +355,8 @@ void IMContainer::render( vec2 drawOffset, vec2 clipPos, vec2 clipSize ) { } // Render the floating elements - for( FEMap::iterator it = floatingContents.begin(); - it != floatingContents.end(); - ++it ) { - AHFloatingElement* floatingElement = it->second; + for(auto & floatingContent : floatingContents) { + AHFloatingElement* floatingElement = floatingContent.second; floatingElement->getElement()->render( drawOffset + drawDisplacement + floatingElement->relativePos, currentClipPos, currentClipSize ); } @@ -392,11 +384,9 @@ void IMContainer::render( vec2 drawOffset, vec2 clipPos, vec2 clipSize ) { } // Now trigger the children - for( FEMap::iterator it = floatingContents.begin(); - it != floatingContents.end(); - ++it ) { + for(auto & floatingContent : floatingContents) { - AHFloatingElement* felement = it->second; + AHFloatingElement* felement = floatingContent.second; // see if we need to center this element @@ -526,10 +516,8 @@ void IMContainer::checkRegion() { contents->doScreenResize(); } - for( FEMap::iterator it = floatingContents.begin(); - it != floatingContents.end(); - ++it ) { - it->second->getElement()->doScreenResize(); + for(auto & floatingContent : floatingContents) { + floatingContent.second->getElement()->doScreenResize(); } } @@ -841,10 +829,8 @@ void IMContainer::setPauseBehaviors( bool pause ) { contents->setPauseBehaviors( pause ); } - for( FEMap::iterator it = floatingContents.begin(); - it != floatingContents.end(); - ++it ) { - AHFloatingElement* floatingElement = it->second; + for(auto & floatingContent : floatingContents) { + AHFloatingElement* floatingElement = floatingContent.second; floatingElement->getElement()->setPauseBehaviors( pause ); } } @@ -868,8 +854,8 @@ void IMContainer::clense() { std::vector IMContainer::getFloatingContents() { std::vector elements; elements.reserve(floatingContents.size()); - for(FEMap::iterator iter = floatingContents.begin(); iter != floatingContents.end(); ++iter) { - IMElement* element = iter->second->getElement(); + for(auto & floatingContent : floatingContents) { + IMElement* element = floatingContent.second->getElement(); //element->AddRef(); elements.push_back(element); } diff --git a/Source/GUI/IMUI/im_divider.cpp b/Source/GUI/IMUI/im_divider.cpp index 280eca4b..c34523c0 100644 --- a/Source/GUI/IMUI/im_divider.cpp +++ b/Source/GUI/IMUI/im_divider.cpp @@ -87,8 +87,8 @@ void IMDivider::setOwnerParent( IMGUI* _owner, IMElement* _parent ) { parent = _parent; // Simply pass this on to the children - for( unsigned int i = 0; i < containers.size(); i++ ) { - containers[i]->setOwnerParent( owner, this ); + for(auto & container : containers) { + container->setOwnerParent( owner, this ); } } @@ -107,8 +107,8 @@ void IMDivider::setAlignment( ContainerAlignment xAlignment, ContainerAlignment contentsYAlignment = yAlignment; if( reposition ) { - for( unsigned int i = 0; i < containers.size(); i++ ) { - containers[i]->setAlignment( xAlignment, yAlignment ); + for(auto & container : containers) { + container->setAlignment( xAlignment, yAlignment ); } } @@ -121,10 +121,8 @@ void IMDivider::setAlignment( ContainerAlignment xAlignment, ContainerAlignment */ void IMDivider::clear() { std::vector containers_copy = containers; - for(std::vector::iterator iter = containers_copy.begin(); - iter != containers_copy.end(); - ++iter) { - (*iter)->Release(); + for(auto & iter : containers_copy) { + iter->Release(); } containers.resize(0); onRelayout(); @@ -151,15 +149,15 @@ void IMDivider::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) { vec2 currentDrawOffset = drawOffset + drawDisplacement; // Simply pass this on to the children - for( unsigned int i = 0; i < containers.size(); i++ ) { + for(auto & container : containers) { - containers[i]->update( delta, currentDrawOffset, guistate ); + container->update( delta, currentDrawOffset, guistate ); if( orientation == DOVertical ) { - currentDrawOffset.y() += containers[i]->getSizeY(); + currentDrawOffset.y() += container->getSizeY(); } else { - currentDrawOffset.x() += containers[i]->getSizeX(); + currentDrawOffset.x() += container->getSizeX(); } } @@ -197,20 +195,20 @@ void IMDivider::render( vec2 drawOffset, vec2 clipPos, vec2 clipSize ) { // Simply pass this on to the children vec2 currentDrawOffset = drawOffset + drawDisplacement; - for( unsigned int i = 0; i < containers.size(); i++ ) { + for(auto & container : containers) { - containers[i]->render( currentDrawOffset, currentClipPos, currentClipSize ); + container->render( currentDrawOffset, currentClipPos, currentClipSize ); if( orientation == DOVertical ) { - if( containers[i]->getSizeY() > 0 ) { - currentDrawOffset.y() += containers[i]->getSizeY(); + if( container->getSizeY() > 0 ) { + currentDrawOffset.y() += container->getSizeY(); } } else { - if( containers[i]->getSizeX() > 0 ) { - currentDrawOffset.x() += containers[i]->getSizeX(); + if( container->getSizeX() > 0 ) { + currentDrawOffset.x() += container->getSizeX(); } } } @@ -231,13 +229,13 @@ void IMDivider::checkRegions() { if( orientation == DOVertical ) { // First calculate the height - for( unsigned int i = 0; i < containers.size(); i++ ) { + for(auto & container : containers) { // see if this element is a dynamic spacer // first check if there is an element in this container - if( containers[i]->contents != NULL ) { + if( container->contents != NULL ) { // now see if we can cast it - if( IMSpacer* spacer = dynamic_cast( containers[i]->contents ) ) { + if( IMSpacer* spacer = dynamic_cast( container->contents ) ) { if( spacer != NULL && spacer->isStatic == false ) { // queue this up dynamicSpacers.push_back( spacer ); @@ -248,7 +246,7 @@ void IMDivider::checkRegions() { } // add to our total - totalSize += containers[i]->getSizeY(); + totalSize += container->getSizeY(); } @@ -256,8 +254,8 @@ void IMDivider::checkRegions() { // see if we've got dynamic spacers and spare space if( dynamicSpacers.size() > 0 && totalSize < parent->getSizeY() ) { float spacerSize = (parent->getSizeY() - totalSize )/((float) dynamicSpacers.size() ); - for( unsigned int i = 0; i < dynamicSpacers.size(); i++ ) { - dynamicSpacers[i]->setSizeY( spacerSize ); + for(auto & dynamicSpacer : dynamicSpacers) { + dynamicSpacer->setSizeY( spacerSize ); addedSpace += spacerSize; } } @@ -268,16 +266,16 @@ void IMDivider::checkRegions() { // Now just fit the divider to the widest element float maxSize = UNDEFINEDSIZE; - for( unsigned int i = 0; i < containers.size(); i++ ) { - if( containers[i]->getSizeX() > maxSize ) { - maxSize = containers[i]->getSizeX(); + for(auto & container : containers) { + if( container->getSizeX() > maxSize ) { + maxSize = container->getSizeX(); } } // if we've grown then resize the container and its elements - for( unsigned int i = 0; i < containers.size(); i++ ) { - if( containers[i]->getSizeX() != maxSize ) { - containers[i]->setSizeX( maxSize ); + for(auto & container : containers) { + if( container->getSizeX() != maxSize ) { + container->setSizeX( maxSize ); } } @@ -289,13 +287,13 @@ void IMDivider::checkRegions() { else { // First calculate the height - for( unsigned int i = 0; i < containers.size(); i++ ) { + for(auto & container : containers) { // see if this element is a dynamic spacer // first check if there is an element in this container - if( containers[i]->contents != NULL ) { + if( container->contents != NULL ) { // now see if we can cast it - IMSpacer* spacer = dynamic_cast( containers[i]->contents ); + IMSpacer* spacer = dynamic_cast( container->contents ); if( spacer != NULL && spacer->isStatic == false ) { // queue this up @@ -306,7 +304,7 @@ void IMDivider::checkRegions() { } // add to our total - totalSize += containers[i]->getSizeX(); + totalSize += container->getSizeX(); } @@ -314,8 +312,8 @@ void IMDivider::checkRegions() { // see if we've got dynamic spacers and spare space if( dynamicSpacers.size() > 0 && totalSize < parent->getSizeX() ) { float spacerSize = (parent->getSizeX() - totalSize )/((float)dynamicSpacers.size() ); - for( unsigned int i = 0; i < dynamicSpacers.size(); i++ ) { - dynamicSpacers[i]->setSizeX( spacerSize ); + for(auto & dynamicSpacer : dynamicSpacers) { + dynamicSpacer->setSizeX( spacerSize ); addedSpace += spacerSize; } } @@ -326,16 +324,16 @@ void IMDivider::checkRegions() { // Now just fit the divider to the widest element float maxSize = UNDEFINEDSIZE; - for( unsigned int i = 0; i < containers.size(); i++ ) { - if( containers[i]->getSizeY() > maxSize ) { - maxSize = containers[i]->getSizeY(); + for(auto & container : containers) { + if( container->getSizeY() > maxSize ) { + maxSize = container->getSizeY(); } } // if we've grown then resize the container and its elements - for( unsigned int i = 0; i < containers.size(); i++ ) { - if( containers[i]->getSizeY() != maxSize ) { - containers[i]->setSizeY( maxSize ); + for(auto & container : containers) { + if( container->getSizeY() != maxSize ) { + container->setSizeY( maxSize ); } } @@ -357,8 +355,8 @@ void IMDivider::doRelayout() { IMElement::doRelayout(); // First pass this down to the children - for( unsigned int i = 0; i < containers.size(); i++ ) { - containers[i]->doRelayout(); + for(auto & container : containers) { + container->doRelayout(); } checkRegions(); @@ -376,8 +374,8 @@ void IMDivider::doScreenResize() { IMElement::doScreenResize(); // Pass this down to the children - for( unsigned int i = 0; i < containers.size(); i++ ) { - containers[i]->doScreenResize(); + for(auto & container : containers) { + container->doScreenResize(); } onRelayout(); @@ -472,10 +470,10 @@ IMContainer* IMDivider::getContainerAt( unsigned int i ) { * */ IMContainer* IMDivider::getContainerOf( std::string const& _name ) { - for( unsigned int i = 0; i < containers.size(); i++ ) { + for(auto & container : containers) { - if( containers[i]->contents != NULL && containers[i]->contents->getName() == _name ) { - return containers[i]; + if( container->contents != NULL && container->contents->getName() == _name ) { + return container; } } return NULL; @@ -590,9 +588,9 @@ IMElement* IMDivider::findElement( std::string const& elementName ) { else { // If not, pass the request onto the children - for( unsigned int i = 0; i < containers.size(); i++ ) { + for(auto & container : containers) { - IMElement* results = containers[i]->findElement( elementName ); + IMElement* results = container->findElement( elementName ); if( results != NULL ) { return results; @@ -606,8 +604,8 @@ IMElement* IMDivider::findElement( std::string const& elementName ) { void IMDivider::setPauseBehaviors( bool pause ) { IMElement::setPauseBehaviors( pause ); - for( unsigned int i = 0; i < containers.size(); i++ ) { - containers[i]->setPauseBehaviors( pause ); + for(auto & container : containers) { + container->setPauseBehaviors( pause ); } } @@ -633,10 +631,8 @@ IMDivider::~IMDivider() { std::vector deletelist = containers; containers.clear(); - for( std::vector::iterator it = deletelist.begin(); - it != deletelist.end(); - ++it ) { - (*it)->Release(); + for(auto & it : deletelist) { + it->Release(); } } diff --git a/Source/GUI/IMUI/im_element.cpp b/Source/GUI/IMUI/im_element.cpp index 864dc1cf..3de21eec 100644 --- a/Source/GUI/IMUI/im_element.cpp +++ b/Source/GUI/IMUI/im_element.cpp @@ -864,10 +864,8 @@ bool IMElement::hasUpdateBehavior(std::string const& behaviorName) void IMElement::clearUpdateBehaviors() { // iterate through all the behaviors and clean them up - for( UBMap::iterator it = updateBehaviors.begin(); - it != updateBehaviors.end(); - ++it ) { - IMUpdateBehavior* updater = it->second; + for(auto & updateBehavior : updateBehaviors) { + IMUpdateBehavior* updater = updateBehavior.second; updater->cleanUp( this ); updater->Release(); } @@ -949,10 +947,8 @@ bool IMElement::hasUpdateBehavior(std::string const& behaviorName) void IMElement::clearMouseOverBehaviors() { // iterate through all the behaviors and clean them up - for( MOBMap::iterator it = mouseOverBehaviors.begin(); - it != mouseOverBehaviors.end(); - ++it ) { - IMMouseOverBehavior* updater = it->second; + for(auto & mouseOverBehavior : mouseOverBehaviors) { + IMMouseOverBehavior* updater = mouseOverBehavior.second; updater->Release(); updater->cleanUp( this ); } @@ -1032,10 +1028,8 @@ void IMElement::addLeftMouseClickBehavior( IMMouseClickBehavior* behavior, std:: void IMElement::clearLeftMouseClickBehaviors() { // iterate through all the behaviors and clean them up - for( MCBMap::iterator it = leftMouseClickBehaviors.begin(); - it != leftMouseClickBehaviors.end(); - ++it ) { - IMMouseClickBehavior* updater = it->second; + for(auto & leftMouseClickBehavior : leftMouseClickBehaviors) { + IMMouseClickBehavior* updater = leftMouseClickBehavior.second; updater->cleanUp( this ); updater->Release(); } @@ -1058,18 +1052,16 @@ void IMElement::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) { { std::vector remove_list; - for( UBMap::iterator it = updateBehaviors.begin(); - it != updateBehaviors.end(); - ++it ) { + for(auto & updateBehavior : updateBehaviors) { - IMUpdateBehavior* updater = it->second; + IMUpdateBehavior* updater = updateBehavior.second; // See if this behavior has been initialized if( !updater->initialized ) { if( !updater->initialize( this, delta, drawOffset, guistate ) ) { // If the behavior has indicated it should not begin remove it - remove_list.push_back(it->first); + remove_list.push_back(updateBehavior.first); continue; } else { @@ -1079,7 +1071,7 @@ void IMElement::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) { if( !updater->update( this, delta, drawOffset, guistate ) ) { // If the behavior has indicated it is done - remove_list.push_back(it->first); + remove_list.push_back(updateBehavior.first); } } @@ -1103,22 +1095,18 @@ void IMElement::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) { mouseOver = true; // Update behaviors - for( MOBMap::iterator it = mouseOverBehaviors.begin(); - it != mouseOverBehaviors.end(); - ++it ) { + for(auto & mouseOverBehavior : mouseOverBehaviors) { - IMMouseOverBehavior* behavior = it->second; + IMMouseOverBehavior* behavior = mouseOverBehavior.second; behavior->onStart( this, delta, drawOffset, guistate ); } } else { // Update behaviors - for( MOBMap::iterator it = mouseOverBehaviors.begin(); - it != mouseOverBehaviors.end(); - ++it ) { + for(auto & mouseOverBehavior : mouseOverBehaviors) { - IMMouseOverBehavior* behavior = it->second; + IMMouseOverBehavior* behavior = mouseOverBehavior.second; behavior->onContinue( this, delta, drawOffset, guistate ); } @@ -1129,14 +1117,12 @@ void IMElement::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) { if( mouseOver ) { std::vector remove_list; - for( MOBMap::iterator it = mouseOverBehaviors.begin(); - it != mouseOverBehaviors.end(); - ++it ) { - IMMouseOverBehavior* behavior = it->second; + for(auto & mouseOverBehavior : mouseOverBehaviors) { + IMMouseOverBehavior* behavior = mouseOverBehavior.second; if( !behavior->onFinish( this, delta, drawOffset, guistate ) ) { // If the behavior has indicated it is done - remove_list.push_back(it->first); + remove_list.push_back(mouseOverBehavior.first); } } @@ -1175,16 +1161,14 @@ void IMElement::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) { std::vector remove_list; // Update behaviors - for( MCBMap::iterator it = leftMouseClickBehaviors.begin(); - it != leftMouseClickBehaviors.end(); - ++it ) { + for(auto & leftMouseClickBehavior : leftMouseClickBehaviors) { guistate.clickHandled = true; - IMMouseClickBehavior* behavior = it->second; + IMMouseClickBehavior* behavior = leftMouseClickBehavior.second; if( !behavior->onDown( this, delta, drawOffset, guistate ) ) { // If the behavior has indicated it is done - remove_list.push_back(it->first); + remove_list.push_back(leftMouseClickBehavior.first); } } @@ -1203,17 +1187,15 @@ void IMElement::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) { } std::vector remove_list; - for( MCBMap::iterator it = leftMouseClickBehaviors.begin(); - it != leftMouseClickBehaviors.end(); - ++it ) { + for(auto & leftMouseClickBehavior : leftMouseClickBehaviors) { guistate.clickHandled = true; - IMMouseClickBehavior* behavior = it->second; + IMMouseClickBehavior* behavior = leftMouseClickBehavior.second; if( !behavior->onStillDown( this, delta, drawOffset, guistate ) ) { // If the behavior has indicated it is done - remove_list.push_back(it->first); + remove_list.push_back(leftMouseClickBehavior.first); } } @@ -1229,17 +1211,15 @@ void IMElement::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) { case IMUIContext::kMouseUp: { if(mouse_clicking){ - for( MCBMap::iterator it = leftMouseClickBehaviors.begin(); - it != leftMouseClickBehaviors.end(); - ++it ) { + for(auto & leftMouseClickBehavior : leftMouseClickBehaviors) { guistate.clickHandled = true; - IMMouseClickBehavior* behavior = it->second; + IMMouseClickBehavior* behavior = leftMouseClickBehavior.second; if( !behavior->onUp( this, delta, drawOffset, guistate ) ) { // If the behavior has indicated it is done - removeLeftMouseClickBehavior( it->first ); + removeLeftMouseClickBehavior( leftMouseClickBehavior.first ); } } @@ -1250,16 +1230,14 @@ void IMElement::update( uint64_t delta, vec2 drawOffset, GUIState& guistate ) { mouseOver = false; { std::vector remove_list; - for( MOBMap::iterator it = mouseOverBehaviors.begin(); - it != mouseOverBehaviors.end(); - ++it ) { + for(auto & mouseOverBehavior : mouseOverBehaviors) { guistate.clickHandled = true; - IMMouseOverBehavior* behavior = it->second; + IMMouseOverBehavior* behavior = mouseOverBehavior.second; if( !behavior->onFinish( this, delta, drawOffset, guistate ) ) { // If the behavior has indicated it is done - remove_list.push_back( it->first ); + remove_list.push_back( mouseOverBehavior.first ); } } @@ -1687,24 +1665,18 @@ void IMElement::setScriptMouseOver(bool mouseOver) { */ IMElement::~IMElement() { LOG_ASSERT(refCount == 0); - for( UBMap::iterator it = updateBehaviors.begin(); - it != updateBehaviors.end(); - ++it ) { - it->second->Release(); + for(auto & updateBehavior : updateBehaviors) { + updateBehavior.second->Release(); } updateBehaviors.clear(); - for( MOBMap::iterator it = mouseOverBehaviors.begin(); - it != mouseOverBehaviors.end(); - ++it ) { - it->second->Release(); + for(auto & mouseOverBehavior : mouseOverBehaviors) { + mouseOverBehavior.second->Release(); } mouseOverBehaviors.clear(); - for( MCBMap::iterator it = leftMouseClickBehaviors.begin(); - it != leftMouseClickBehaviors.end(); - ++it ) { - it->second->Release(); + for(auto & leftMouseClickBehavior : leftMouseClickBehaviors) { + leftMouseClickBehavior.second->Release(); } leftMouseClickBehaviors.clear(); diff --git a/Source/GUI/IMUI/im_events.cpp b/Source/GUI/IMUI/im_events.cpp index 41d65898..9a9dfb0d 100644 --- a/Source/GUI/IMUI/im_events.cpp +++ b/Source/GUI/IMUI/im_events.cpp @@ -41,13 +41,13 @@ void IMEvents::DeRegisterListener( IMEventListener *listener ) { } void IMEvents::TriggerDestroyed(IMElement* elem) { - for( unsigned i = 0; i < listeners.size(); i++ ) { - listeners[i]->DestroyedIMElement(elem); + for(auto & listener : listeners) { + listener->DestroyedIMElement(elem); } } void IMEvents::TriggerDestroyed(IMGUI* imgui) { - for( unsigned i = 0; i < listeners.size(); i++ ) { - listeners[i]->DestroyedIMGUI(imgui); + for(auto & listener : listeners) { + listener->DestroyedIMGUI(imgui); } } diff --git a/Source/GUI/IMUI/im_support.cpp b/Source/GUI/IMUI/im_support.cpp index 46975d5a..bfd8a8cf 100644 --- a/Source/GUI/IMUI/im_support.cpp +++ b/Source/GUI/IMUI/im_support.cpp @@ -251,12 +251,10 @@ void IMReferenceCountTracker::logSanityCheck() { else { LOGI << "Error: There still " << totalRefCountObjs << " LIVE IMGUI elements" << std::endl; - for( std::map::iterator it = typeCounts.begin(); - it != typeCounts.end(); - ++it ) { + for(auto & typeCount : typeCounts) { - if( it->second != 0 ) { - LOGI << it->first << ": " << it->second << std::endl; + if( typeCount.second != 0 ) { + LOGI << typeCount.first << ": " << typeCount.second << std::endl; } } diff --git a/Source/GUI/IMUI/imgui.cpp b/Source/GUI/IMUI/imgui.cpp index fc3d25e8..f858e779 100644 --- a/Source/GUI/IMUI/imgui.cpp +++ b/Source/GUI/IMUI/imgui.cpp @@ -283,25 +283,19 @@ void IMGUI::setFooterPanels( float first, float second, float third ) { */ void IMGUI::setup() { - for( std::vector::iterator it = header.begin(); - it != header.end(); - ++it ) { + for(auto & it : header) { - (*it)->Release(); + it->Release(); } - for( std::vector::iterator it = footer.begin(); - it != footer.end(); - ++it ) { + for(auto & it : footer) { - (*it)->Release(); + it->Release(); } - for( std::vector::iterator it = main.begin(); - it != main.end(); - ++it ) { + for(auto & it : main) { - (*it)->Release(); + it->Release(); } header.clear(); @@ -336,17 +330,15 @@ void IMGUI::setup() { // Go through the list of pending panels, create them and total their widths int panelCount = 0; - for( std::vector::iterator it = pendingHeaderPanels.begin(); - it != pendingHeaderPanels.end(); - ++it ) { + for(float & pendingHeaderPanel : pendingHeaderPanels) { IMContainer* panel = new IMContainer( "header" + numbering[panelCount], - SizePolicy(*it), + SizePolicy(pendingHeaderPanel), SizePolicy(headerHeight) ); panel->setOwnerParent( this, NULL ); header.push_back( panel ); - totalWidth += *it; + totalWidth += pendingHeaderPanel; } @@ -373,18 +365,16 @@ void IMGUI::setup() { // Go through the list of pending panels, create them and total their widths int panelCount = 0; - for( std::vector::iterator it = pendingFooterPanels.begin(); - it != pendingFooterPanels.end(); - ++it ) { + for(float & pendingFooterPanel : pendingFooterPanels) { IMContainer* panel = new IMContainer( "footer" + numbering[panelCount], - SizePolicy(*it), + SizePolicy(pendingFooterPanel), SizePolicy(footerHeight) ); panel->setOwnerParent( this, NULL ); footer.push_back( panel ); - totalWidth += *it; + totalWidth += pendingFooterPanel; } @@ -411,18 +401,16 @@ void IMGUI::setup() { // Go through the list of pending panels, create them and total their widths int panelCount = 0; - for( std::vector::iterator it = pendingMainPanels.begin(); - it != pendingMainPanels.end(); - ++it ) { + for(float & pendingMainPanel : pendingMainPanels) { IMContainer* panel = new IMContainer( "main" + numbering[panelCount], - SizePolicy(*it), + SizePolicy(pendingMainPanel), SizePolicy(mainHeight) ); panel->setOwnerParent( this, NULL ); main.push_back( panel ); - totalWidth += *it; + totalWidth += pendingMainPanel; } @@ -545,8 +533,8 @@ void IMGUI::clear() { containerList[i]->Release(); } - for( int i = 0; i < int(messageQueue.size()); ++i ) { - messageQueue[i]->Release(); + for(auto & i : messageQueue) { + i->Release(); } messageQueue.clear(); } @@ -682,26 +670,20 @@ void IMGUI::doRelayout() { backgrounds[ layer ]->doRelayout(); } - for( std::vector::iterator it = header.begin(); - it != header.end(); - ++it ) { - (*it)->doRelayout(); + for(auto & it : header) { + it->doRelayout(); } - for( std::vector::iterator it = footer.begin(); - it != footer.end(); - ++it ) { - (*it)->doRelayout(); + for(auto & it : footer) { + it->doRelayout(); } - for( std::vector::iterator it = main.begin(); - it != main.end(); - ++it ) { - (*it)->doRelayout(); + for(auto & it : main) { + it->doRelayout(); } - for( unsigned int layer = 0; layer < foregrounds.size(); ++layer ) { - foregrounds[ layer ]->doRelayout(); + for(auto & foreground : foregrounds) { + foreground->doRelayout(); } // MJB Note: I'm aware that redoing the layout for the whole structure @@ -856,31 +838,25 @@ void IMGUI::doScreenResize() { backgrounds[ layer ]->doScreenResize(); } - for( std::vector::iterator it = header.begin(); - it != header.end(); - ++it ) { - (*it)->doScreenResize(); + for(auto & it : header) { + it->doScreenResize(); } - for( std::vector::iterator it = footer.begin(); - it != footer.end(); - ++it ) { - (*it)->doScreenResize(); + for(auto & it : footer) { + it->doScreenResize(); } - for( std::vector::iterator it = main.begin(); - it != main.end(); - ++it ) { - (*it)->doScreenResize(); + for(auto & it : main) { + it->doScreenResize(); } - for( unsigned int layer = 0; layer < foregrounds.size(); ++layer ) { + for(auto & foreground : foregrounds) { // reset the size - foregrounds[ layer ]->setSizePolicy( SizePolicy(screenMetrics.GUISpace.x()), + foreground->setSizePolicy( SizePolicy(screenMetrics.GUISpace.x()), SizePolicy(screenMetrics.GUISpace.y()) ); - foregrounds[ layer ]->doScreenResize(); + foreground->doScreenResize(); } doRelayout(); @@ -962,8 +938,8 @@ void IMGUI::render() { IMGUI_IMUIContext->render(); // render the foregrounds - for( unsigned int layer = 0; layer < foregrounds.size(); ++layer ) { - foregrounds[ layer ]->render( origin, origin, vec2( UNDEFINEDSIZE, UNDEFINEDSIZE ) ); + for(auto & foreground : foregrounds) { + foreground->render( origin, origin, vec2( UNDEFINEDSIZE, UNDEFINEDSIZE ) ); IMGUI_IMUIContext->render(); } @@ -1069,10 +1045,8 @@ void IMGUI::drawBox( vec2 boxPos, vec2 boxSize, vec4 boxColor, int zOrder, bool IMElement* IMGUI::findElement( std::string const& elementName ) { - for( std::vector::iterator it = header.begin(); - it != header.end(); - ++it ) { - IMElement* foundElement = (*it)->findElement( elementName ); + for(auto & it : header) { + IMElement* foundElement = it->findElement( elementName ); if( foundElement != NULL ) { foundElement->AddRef(); @@ -1080,10 +1054,8 @@ IMElement* IMGUI::findElement( std::string const& elementName ) { } } - for( std::vector::iterator it = footer.begin(); - it != footer.end(); - ++it ) { - IMElement* foundElement = (*it)->findElement( elementName ); + for(auto & it : footer) { + IMElement* foundElement = it->findElement( elementName ); if( foundElement != NULL ) { foundElement->AddRef(); @@ -1091,10 +1063,8 @@ IMElement* IMGUI::findElement( std::string const& elementName ) { } } - for( std::vector::iterator it = main.begin(); - it != main.end(); - ++it ) { - IMElement* foundElement = (*it)->findElement( elementName ); + for(auto & it : main) { + IMElement* foundElement = it->findElement( elementName ); if( foundElement != NULL ) { foundElement->AddRef(); diff --git a/Source/GUI/IMUI/imui.cpp b/Source/GUI/IMUI/imui.cpp index e43cb6ca..42475779 100644 --- a/Source/GUI/IMUI/imui.cpp +++ b/Source/GUI/IMUI/imui.cpp @@ -334,8 +334,7 @@ void IMUIContext::deriveFontDimensions( IMUIText& text ) { LOGE << "Got utf8 exception \"" << ner.what() << "\" this might indicate invalid utf-8 data" << std::endl; } - for(unsigned i=0; i dimensions[ 0 ] ) { diff --git a/Source/GUI/IMUI/imui_script.cpp b/Source/GUI/IMUI/imui_script.cpp index 7ca15e02..adb3cade 100644 --- a/Source/GUI/IMUI/imui_script.cpp +++ b/Source/GUI/IMUI/imui_script.cpp @@ -126,8 +126,8 @@ static CScriptArray* AS_GetFloatingContents(IMContainer* element) { array->Reserve(vals.size()); - for( unsigned i = 0; i < vals.size(); i++ ) { - array->InsertLast((void*)&vals[i]); + for(auto & val : vals) { + array->InsertLast((void*)&val); } return array; diff --git a/Source/GUI/dimgui/dimgui.cpp b/Source/GUI/dimgui/dimgui.cpp index 726877e2..47190d8c 100644 --- a/Source/GUI/dimgui/dimgui.cpp +++ b/Source/GUI/dimgui/dimgui.cpp @@ -415,8 +415,8 @@ static void DrawColorPicker(Object** selected, unsigned selected_count, SceneGra for(unsigned selected_i=0; selected_iGetPalette(); - for(size_t i=0, len=palette->size(); iat(i); + for(auto & i : *palette){ + LabeledColor* labeled_color = &i; bool found = false; for(unsigned palette_i = 0; palette_i < labeled_color_count; palette_i++) { if(strcmp(labeled_colors[palette_i], labeled_color->label.c_str()) == 0) { @@ -449,8 +449,8 @@ static void DrawColorPicker(Object** selected, unsigned selected_count, SceneGra for (unsigned selected_i = 0; selected_i < selected_count; ++selected_i) { MovementObject* mo = (MovementObject*)selected[selected_i]; OGPalette* palette = mo->GetPalette(); - for (size_t i = 0, len = palette->size(); i < len; ++i) { - LabeledColor* labeled_color = &palette->at(i); + for (auto & i : *palette) { + LabeledColor* labeled_color = &i; bool found = false; if (strcmp(labeled_colors[palette_index], labeled_color->label.c_str()) == 0) { color = labeled_color->color; @@ -508,8 +508,7 @@ static void DrawColorPicker(Object** selected, unsigned selected_count, SceneGra if(!color_changed) me->AddColorToHistory(color); - for(size_t i = 0, len = scenegraph->objects_.size(); i < len; ++i) { - Object* obj = scenegraph->objects_[i]; + for(auto obj : scenegraph->objects_) { if(obj->Selected()){ if(obj->GetType() == _env_object) { EnvObject* eo = (EnvObject*)obj; @@ -541,8 +540,7 @@ static void DrawColorPicker(Object** selected, unsigned selected_count, SceneGra static void DrawAudioDebug() { std::vector sound_sources = Engine::Instance()->GetSound()->GetCurrentSoundSources(); if(ImGui::TreeNode("Sounds", "Sounds: %d", (int)sound_sources.size())){ - for( unsigned i = 0; i < sound_sources.size(); i++ ) { - SoundSourceInfo &ss = sound_sources[i]; + for(auto & ss : sound_sources) { ImGui::Text("%s :%f %f %f", ss.name, ss.pos[0], ss.pos[1], ss.pos[2]); } ImGui::TreePop(); @@ -570,23 +568,23 @@ static void DrawAudioDebug() { static float v = 0.0f; static std::string selected_layer_name = ""; - for( unsigned i = 0; i < layers.size(); i++ ) { - float layer_gain = Engine::Instance()->GetSound()->GetLayerGain(layers[i]); - ImGui::Text("%s %f", layers[i].c_str(), layer_gain ); + for(auto & layer : layers) { + float layer_gain = Engine::Instance()->GetSound()->GetLayerGain(layer); + ImGui::Text("%s %f", layer.c_str(), layer_gain ); if( ImGui::IsItemClicked() ) { - if( selected_layer_name == layers[i] ) { + if( selected_layer_name == layer ) { selected_layer_name = ""; } else { - selected_layer_name = layers[i]; + selected_layer_name = layer; v = layer_gain; } } - if( selected_layer_name == layers[i] ) { - if( ImGui::DragFloat(layers[i].c_str(),&v, 0.01f, 0.0f, 1.0f) ) { + if( selected_layer_name == layer ) { + if( ImGui::DragFloat(layer.c_str(),&v, 0.01f, 0.0f, 1.0f) ) { LOGI << "Settings layer gain" << std::endl; - Engine::Instance()->GetSound()->SetLayerGain(layers[i],v); + Engine::Instance()->GetSound()->SetLayerGain(layer,v); } } } @@ -633,14 +631,14 @@ static bool DrawScriptParamsEditor(ScriptParams* params) { const ScriptParamMap& spm = params->GetParameterMap(); ImGui::Columns(3); int id = 0; - for(ScriptParamMap::const_iterator iter = spm.begin(); iter != spm.end(); ++iter){ - const ScriptParam& sp = iter->second; + for(const auto & iter : spm){ + const ScriptParam& sp = iter.second; const ScriptParamParts::Editor& editor = sp.editor(); - FormatString(buf, kBufSize, "%s", iter->first.c_str()); + FormatString(buf, kBufSize, "%s", iter.first.c_str()); ImGui::PushItemWidth(-1); // Don't make space for invisible labels ImGui::PushID(id++); if(ImGui::InputText("###inputnamething", buf, kBufSize, ImGuiInputTextFlags_EnterReturnsTrue)){ - FormatString(rename_buf[0], kBufSize, "%s", iter->first.c_str()); + FormatString(rename_buf[0], kBufSize, "%s", iter.first.c_str()); FormatString(rename_buf[1], kBufSize, "%s", buf); rename = true; } @@ -663,7 +661,7 @@ static bool DrawScriptParamsEditor(ScriptParams* params) { case ScriptParamEditorType::CHECKBOX:{ bool checked = (sp.GetInt()==1); if(ImGui::Checkbox("", &checked)){ - params->ASSetInt(iter->first, checked?1:0); + params->ASSetInt(iter.first, checked?1:0); changed = true; } break;} @@ -671,7 +669,7 @@ static bool DrawScriptParamsEditor(ScriptParams* params) { vec3 color = ColorFromString(sp.GetString().c_str()); if(ImGui::ColorEdit3("", &color[0])){ FormatString(buf, kBufSize, "%d, %d, %d", (int)(color[0]*255), (int)(color[1]*255), (int)(color[2]*255)); - params->ASSetString(iter->first, buf); + params->ASSetString(iter.first, buf); changed = true; } break;} @@ -691,13 +689,13 @@ static bool DrawScriptParamsEditor(ScriptParams* params) { if(is_float){ float val = sp.GetFloat() * details_flt[3]; if(ImGui::SliderFloat("", &val, details_flt[0] * details_flt[3], details_flt[1] * details_flt[3])){ - params->ASSetFloat(iter->first, val / details_flt[3]); + params->ASSetFloat(iter.first, val / details_flt[3]); changed = true; } } else { int val = (int) (sp.GetInt() * details_flt[3]); if(ImGui::SliderInt("", &val, (int) (details_flt[0] * details_flt[3]), (int) (details_flt[1] * details_flt[3]))){ - params->ASSetInt(iter->first, (int) (val / details_flt[3])); + params->ASSetInt(iter.first, (int) (val / details_flt[3])); changed = true; } } @@ -710,14 +708,14 @@ static bool DrawScriptParamsEditor(ScriptParams* params) { if( sp.GetString().size() < (kBufSize - 1) ) { FormatString(buf, kBufSize, "%s", sp.GetString().c_str()); if(ImGui::InputText("##smallertextfield", buf, kBufSize)){ - params->ASSetString(iter->first, buf); + params->ASSetString(iter.first, buf); changed = true; } } else if( sp.GetString().size() < kLargerBufSize ) { char* larger_buf = (char*)alloc.stack.Alloc(kLargerBufSize); FormatString(larger_buf, kLargerBufSize, "%s", sp.GetString().c_str()); if(ImGui::InputTextMultiline("##largertextfield", larger_buf, kLargerBufSize)){ - params->ASSetString(iter->first, larger_buf); + params->ASSetString(iter.first, larger_buf); changed = true; } alloc.stack.Free(larger_buf); @@ -727,13 +725,13 @@ static bool DrawScriptParamsEditor(ScriptParams* params) { } else if(sp.IsInt()){ int val = sp.GetInt(); if(ImGui::InputInt("", &val)){ - params->ASSetInt(iter->first, val); + params->ASSetInt(iter.first, val); changed = true; } } else if(sp.IsFloat()){ int val = (int) sp.GetFloat(); if(ImGui::InputInt("", &val)){ - params->ASSetFloat(iter->first, (float) val); + params->ASSetFloat(iter.first, (float) val); changed = true; } } @@ -747,7 +745,7 @@ static bool DrawScriptParamsEditor(ScriptParams* params) { ImGui::PushID(id++); if(ImGui::Button("x")){ to_delete = true; - FormatString(rename_buf[0], kBufSize, "%s", iter->first.c_str()); + FormatString(rename_buf[0], kBufSize, "%s", iter.first.c_str()); } ImGui::PopID(); ImGui::NextColumn(); @@ -817,9 +815,9 @@ static void PrintConnections(MovementObject* mov, { if(ImGui::TreeNodeEx(name)) { if (ImGui::BeginListBox("Connected")) { - for (std::list::const_iterator it = list.begin(); it != list.end(); ++it) { - if (it->attachment_type == type && it->attachment_mirror == mirrored) { - Object* obj = (*it).obj; + for (const auto & it : list) { + if (it.attachment_type == type && it.attachment_mirror == mirrored) { + Object* obj = it.obj; char buffer[512]; obj->GetDisplayName(buffer, 512); if (ImGui::Selectable(buffer, false)) { @@ -840,8 +838,8 @@ static void PrintConnections(MovementObject* mov, } bool found = false; - for (std::list::const_iterator it = list.begin(); it != list.end(); ++it) { - if (obj->GetID() == (*it)->GetID() && it->attachment_type == type && it->attachment_mirror == mirrored) { + for (const auto & it : list) { + if (obj->GetID() == it->GetID() && it.attachment_type == type && it.attachment_mirror == mirrored) { found = true; break; } @@ -996,8 +994,7 @@ static void DrawObjectInfoFlat(Object* obj) { strcpy(text.data(), "Nothing"); int item_index = 0; int path_point_count = 0; - for(size_t i = 0; i < scenegraph->path_points_.size(); ++i) { - Object* obj = scenegraph->path_points_[i]; + for(auto obj : scenegraph->path_points_) { if(!(only_named && obj->GetName().empty())) { GetDisplayName(obj, text); if(obj->GetID() == mov->connected_pathpoint_id) { @@ -1007,8 +1004,7 @@ static void DrawObjectInfoFlat(Object* obj) { } } int movement_object_count = 0; - for(size_t i = 0; i < scenegraph->movement_objects_.size(); ++i) { - Object* obj = scenegraph->movement_objects_[i]; + for(auto obj : scenegraph->movement_objects_) { if(!(only_named && obj->GetName().empty()) && mov->GetID() != obj->GetID()) { GetDisplayName(obj, text); if(obj->GetID() == mov->connected_pathpoint_id) { @@ -1042,8 +1038,8 @@ static void DrawObjectInfoFlat(Object* obj) { RiggedObject* rig = mov->rigged_object(); if(rig && !rig->children.empty()) { if (ImGui::BeginListBox("Attached objects")) { - for (size_t i = 0; i < rig->children.size(); ++i) { - Object* ptr = rig->children[i].direct_ptr; + for (auto & i : rig->children) { + Object* ptr = i.direct_ptr; char buffer[512]; ptr->GetDisplayName(buffer, 512); if (ImGui::Selectable(buffer, false)) { @@ -1080,8 +1076,8 @@ static void DrawObjectInfoFlat(Object* obj) { case _path_point_object:{ PathPointObject* path_obj = (PathPointObject*)obj; if (ImGui::BeginListBox("Connected")) { - for (size_t i = 0; i < scenegraph->movement_objects_.size(); ++i) { - MovementObject* mov_obj = (MovementObject*)scenegraph->movement_objects_[i]; + for (auto & movement_object : scenegraph->movement_objects_) { + MovementObject* mov_obj = (MovementObject*)movement_object; if (mov_obj->connected_pathpoint_id == path_obj->GetID()) { char buffer[512]; mov_obj->GetDisplayName(buffer, 512); @@ -1101,8 +1097,8 @@ static void DrawObjectInfoFlat(Object* obj) { ImGui::EndListBox(); } if (ImGui::BeginListBox("Available characters")) { - for (size_t i = 0; i < scenegraph->movement_objects_.size(); ++i) { - MovementObject* obj = (MovementObject*)scenegraph->movement_objects_[i]; + for (auto & movement_object : scenegraph->movement_objects_) { + MovementObject* obj = (MovementObject*)movement_object; if (obj->connected_pathpoint_id != path_obj->GetID()) { char buffer[512]; obj->GetDisplayName(buffer, 512); @@ -1136,15 +1132,15 @@ static void DrawObjectInfoFlat(Object* obj) { ImGui::EndListBox(); } if (ImGui::BeginListBox("Available")) { - for (size_t i = 0; i < scenegraph->navmesh_connections_.size(); ++i) { - NavmeshConnectionObject* obj = (NavmeshConnectionObject*)scenegraph->navmesh_connections_[i]; + for (auto & navmesh_connection : scenegraph->navmesh_connections_) { + NavmeshConnectionObject* obj = (NavmeshConnectionObject*)navmesh_connection; if (obj->GetID() == nav_con->GetID() || (!show_connected && !obj->connections.empty())) { continue; } bool connected = false; - for (size_t j = 0; j < nav_con->connections.size(); j++) { - if (obj->GetID() == nav_con->connections[j].other_object_id) { + for (auto & connection : nav_con->connections) { + if (obj->GetID() == connection.other_object_id) { connected = true; break; } @@ -1583,8 +1579,8 @@ static bool TreeScenegraphElementVisible(Object* obj, Object* root, char* buf) { if(search_children_scenegraph && obj->IsGroupDerived()) { char child_buf[kBufSize]; Group* group = static_cast(obj); - for(size_t i = 0; i < group->children.size(); i++) { - group->children[i].direct_ptr->GetDisplayName(child_buf, kBufSize); + for(auto & i : group->children) { + i.direct_ptr->GetDisplayName(child_buf, kBufSize); if(scenegraph_filter.PassFilter( child_buf )) { return true; } @@ -1758,17 +1754,17 @@ static void ParseSpawner() { const std::vector& mods = ModLoading::Instance().GetMods(); - for( unsigned i = 0; i < mods.size(); i++ ) { - if( mods[i]->IsActive() ) { - for( unsigned u = 0; u < mods[i]->items.size(); u++ ) { - const ModInstance::Item& item = mods[i]->items[u]; + for(auto mod : mods) { + if( mod->IsActive() ) { + for( unsigned u = 0; u < mod->items.size(); u++ ) { + const ModInstance::Item& item = mod->items[u]; SpawnerTab* spawner_tab_ptr = &spawner_tabs[std::string(item.category)]; spawner_tab_ptr->resize(spawner_tab_ptr->size()+1); SpawnerItem* new_item = &spawner_tab_ptr->back(); - new_item->mod_source_title = mods[i]->name; + new_item->mod_source_title = mod->name; new_item->display_name = item.title; new_item->path = item.path; new_item->thumbnail_path = item.thumbnail; @@ -2075,9 +2071,9 @@ void DrawImGui(Graphics* graphics, SceneGraph* scenegraph, GUI* gui, AssetManage char temp[kBufSize]; FormatString(buf, kBufSize, "Keys(game): "); Keyboard::KeyStatusMap* keys = &Input::Instance()->getKeyboard().keys; - for(Keyboard::KeyStatusMap::iterator iter = keys->begin(); iter != keys->end(); ++iter){ - if(iter->second.down){ - FormatString(temp, kBufSize, "%s%s ", buf, SDLKeycodeToString(iter->first)); + for(auto & key : *keys){ + if(key.second.down){ + FormatString(temp, kBufSize, "%s%s ", buf, SDLKeycodeToString(key.first)); FormatString(buf, kBufSize, "%s", temp); } } @@ -2417,16 +2413,16 @@ void DrawImGui(Graphics* graphics, SceneGraph* scenegraph, GUI* gui, AssetManage bool any_selected_object_has_custom_gui = false; bool selected_items_changed = false; - for(unsigned selected_i = 0; selected_i < selected.size(); ++selected_i) { - if(selected[selected_i]->GetType() == _hotspot_object) { - Hotspot* hotspot = (Hotspot*)selected[selected_i]; + for(auto & selected_i : selected) { + if(selected_i->GetType() == _hotspot_object) { + Hotspot* hotspot = (Hotspot*)selected_i; if(hotspot->HasCustomGUI()) { any_selected_object_has_custom_gui = true; break; } - } else if(selected[selected_i]->GetType() == _placeholder_object) { - PlaceholderObject* placeholder = (PlaceholderObject*)selected[selected_i]; + } else if(selected_i->GetType() == _placeholder_object) { + PlaceholderObject* placeholder = (PlaceholderObject*)selected_i; if(placeholder->GetScriptParams()->HasParam("Dialogue")) { any_selected_object_has_custom_gui = true; @@ -2444,9 +2440,9 @@ void DrawImGui(Graphics* graphics, SceneGraph* scenegraph, GUI* gui, AssetManage LOGI << "Launch custom editor(s)" << std::endl; scenegraph->level->Message("edit_selected_dialogue"); - for(unsigned selected_i = 0; selected_i < selected.size(); ++selected_i) { - if(selected[selected_i]->GetType() == _hotspot_object) { - Hotspot* hotspot = (Hotspot*)selected[selected_i]; + for(auto & selected_i : selected) { + if(selected_i->GetType() == _hotspot_object) { + Hotspot* hotspot = (Hotspot*)selected_i; if(hotspot->HasCustomGUI()) { hotspot->LaunchCustomGUI(); @@ -2526,8 +2522,8 @@ void DrawImGui(Graphics* graphics, SceneGraph* scenegraph, GUI* gui, AssetManage } bool any_movement_objects_selected = false; - for(unsigned selected_i = 0; selected_i < selected.size(); ++selected_i) { - if(selected[selected_i]->GetType() == _movement_object) { + for(auto & selected_i : selected) { + if(selected_i->GetType() == _movement_object) { any_movement_objects_selected = true; break; } @@ -2590,22 +2586,22 @@ void DrawImGui(Graphics* graphics, SceneGraph* scenegraph, GUI* gui, AssetManage } if (spawner_global_filter.IsActive()) { - for (SpawnerTabMap::iterator tab_iter = spawner_tabs.begin(); tab_iter != spawner_tabs.end(); ++tab_iter) { - SpawnerTab* tab = &tab_iter->second; + for (auto & spawner_tab : spawner_tabs) { + SpawnerTab* tab = &spawner_tab.second; - for (SpawnerTab::iterator item_iter = tab->begin(); item_iter != tab->end(); ++item_iter) { - std::string item_display_name = tab_iter->first + " -> " + item_iter->display_name; + for (auto & item_iter : *tab) { + std::string item_display_name = spawner_tab.first + " -> " + item_iter.display_name; - if (spawner_global_filter.PassFilter( item_iter->mod_source_title.c_str() ) || spawner_global_filter.PassFilter(item_display_name.c_str())) { - AddSpawnerItem(&(*item_iter), scenegraph); + if (spawner_global_filter.PassFilter( item_iter.mod_source_title.c_str() ) || spawner_global_filter.PassFilter(item_display_name.c_str())) { + AddSpawnerItem(&item_iter, scenegraph); } } } } else { - for (SpawnerTabMap::iterator tab_iter = spawner_tabs.begin(); tab_iter != spawner_tabs.end(); ++tab_iter) { - if (ImGui::BeginMenu(tab_iter->first.c_str())) { - SpawnerTab* tab = &tab_iter->second; - ImGuiTextFilter& current_tab_filter = spawner_tab_filters[tab_iter->first]; + for (auto & spawner_tab : spawner_tabs) { + if (ImGui::BeginMenu(spawner_tab.first.c_str())) { + SpawnerTab* tab = &spawner_tab.second; + ImGuiTextFilter& current_tab_filter = spawner_tab_filters[spawner_tab.first]; //if (ImGui::IsWindowHovered()) { // ImGui::SetKeyboardFocusHere(); @@ -2616,9 +2612,9 @@ void DrawImGui(Graphics* graphics, SceneGraph* scenegraph, GUI* gui, AssetManage current_tab_filter.Build(); } - for (SpawnerTab::iterator item_iter = tab->begin(); item_iter != tab->end(); ++item_iter) { - if (current_tab_filter.PassFilter(item_iter->mod_source_title.c_str()) || current_tab_filter.PassFilter(item_iter->display_name.c_str())) { - AddSpawnerItem(&(*item_iter), scenegraph); + for (auto & item_iter : *tab) { + if (current_tab_filter.PassFilter(item_iter.mod_source_title.c_str()) || current_tab_filter.PassFilter(item_iter.display_name.c_str())) { + AddSpawnerItem(&item_iter, scenegraph); } } ImGui::EndMenu(); @@ -2828,9 +2824,9 @@ Mark Stockton\nMikko Tarmia"); if(scenegraph && scenegraph->level) { bool draw_menu = false; const std::vector& contexts = scenegraph->level->as_contexts_; - for(std::vector::iterator iter = scenegraph->level->as_contexts_.begin(); iter != scenegraph->level->as_contexts_.end(); ++iter) { - if(iter->context_name == "mod_level_hook") { - if(iter->ctx->HasFunction(iter->as_funcs.menu)) { + for(auto & as_context : scenegraph->level->as_contexts_) { + if(as_context.context_name == "mod_level_hook") { + if(as_context.ctx->HasFunction(as_context.as_funcs.menu)) { draw_menu = true; break; } @@ -2838,9 +2834,9 @@ Mark Stockton\nMikko Tarmia"); } if(draw_menu && ImGui::BeginMenu("Mods")) { const std::vector& contexts = scenegraph->level->as_contexts_; - for(std::vector::iterator iter = scenegraph->level->as_contexts_.begin(); iter != scenegraph->level->as_contexts_.end(); ++iter) { - if(iter->context_name == "mod_level_hook") { - iter->ctx->CallScriptFunction(iter->as_funcs.menu); + for(auto & as_context : scenegraph->level->as_contexts_) { + if(as_context.context_name == "mod_level_hook") { + as_context.ctx->CallScriptFunction(as_context.as_funcs.menu); } } ImGui::EndMenu(); @@ -2896,12 +2892,12 @@ Mark Stockton\nMikko Tarmia"); for (SpawnerTabMap::iterator tab_iter = spawner_tabs.begin(); !item_clicked && tab_iter != spawner_tabs.end(); ++tab_iter) { SpawnerTab* tab = &tab_iter->second; - for (SpawnerTab::iterator item_iter = tab->begin(); item_iter != tab->end(); ++item_iter) { - std::string item_display_name = tab_iter->first + " -> " + item_iter->display_name; + for (auto & item_iter : *tab) { + std::string item_display_name = tab_iter->first + " -> " + item_iter.display_name; - if (spawner_global_filter.PassFilter( item_iter->mod_source_title.c_str() ) || spawner_global_filter.PassFilter(item_display_name.c_str())) { - if (pressed_number == items + 1 && scenegraph->map_editor->state_ == MapEditor::kIdle && scenegraph->map_editor->LoadEntitiesFromFile(item_iter->path)==0) { - scenegraph->level->PushSpawnerItemRecent(*item_iter); + if (spawner_global_filter.PassFilter( item_iter.mod_source_title.c_str() ) || spawner_global_filter.PassFilter(item_display_name.c_str())) { + if (pressed_number == items + 1 && scenegraph->map_editor->state_ == MapEditor::kIdle && scenegraph->map_editor->LoadEntitiesFromFile(item_iter.path)==0) { + scenegraph->level->PushSpawnerItemRecent(item_iter); scenegraph->map_editor->active_tool_ = EditorTypes::ADD_ONCE; item_clicked = true; break; @@ -2913,23 +2909,23 @@ Mark Stockton\nMikko Tarmia"); } else { int items = 0; if (spawner_global_filter.IsActive()) { - for (SpawnerTabMap::iterator tab_iter = spawner_tabs.begin(); tab_iter != spawner_tabs.end(); ++tab_iter) { - SpawnerTab* tab = &tab_iter->second; + for (auto & spawner_tab : spawner_tabs) { + SpawnerTab* tab = &spawner_tab.second; - for (SpawnerTab::iterator item_iter = tab->begin(); item_iter != tab->end(); ++item_iter) { - std::string item_display_name = tab_iter->first + " -> " + item_iter->display_name; + for (auto & item_iter : *tab) { + std::string item_display_name = spawner_tab.first + " -> " + item_iter.display_name; - if (spawner_global_filter.PassFilter( item_iter->mod_source_title.c_str() ) || spawner_global_filter.PassFilter(item_display_name.c_str())) { + if (spawner_global_filter.PassFilter( item_iter.mod_source_title.c_str() ) || spawner_global_filter.PassFilter(item_display_name.c_str())) { if(items < 9) { char buffer[32]; sprintf(buffer, "%i", items + 1); ImGui::Text("%s", buffer); ImGui::SameLine(0.0f, 16.0f); - if(AddSpawnerItem(&(*item_iter), scenegraph)) { + if(AddSpawnerItem(&item_iter, scenegraph)) { item_clicked = true; } } else { - if(AddSpawnerItem(&(*item_iter), scenegraph)) { + if(AddSpawnerItem(&item_iter, scenegraph)) { item_clicked = true; } } @@ -3176,11 +3172,9 @@ Mark Stockton\nMikko Tarmia"); ImGui::Checkbox("Search children", &search_children_scenegraph); ImGui::Checkbox("Named Only", &show_named_only_scenegraph); if( show_flat_scenegraph ) { - for(size_t i=0, len=scenegraph->objects_.size(); iobjects_){ const int kBufSize = 512; char buf[kBufSize]; - Object* obj = scenegraph->objects_[i]; - if((show_named_only_scenegraph == false || obj->GetName().empty() == false) && obj->selectable_) { obj->GetDisplayName(buf, kBufSize); if (scenegraph_filter.IsActive() && !scenegraph_filter.PassFilter( buf )){ @@ -3189,8 +3183,8 @@ Mark Stockton\nMikko Tarmia"); if(obj->IsGroupDerived()) { char child_buf[kBufSize]; Group* group = static_cast(obj); - for(size_t i = 0; i < group->children.size(); i++) { - group->children[i].direct_ptr->GetDisplayName(child_buf, kBufSize); + for(auto & i : group->children) { + i.direct_ptr->GetDisplayName(child_buf, kBufSize); if(scenegraph_filter.PassFilter( child_buf )) { pass = true; break; @@ -3372,13 +3366,12 @@ Mark Stockton\nMikko Tarmia"); ImGui::RadioButton("No climb", &paintbrush_type, 9); if(paintbrush_type == 9) { if(ImGui::Button("Apply 'no climb' to all unlabeled surfaces")){ - for(size_t obj_index=0, len=scenegraph->collide_objects_.size(); obj_indexcollide_objects_[obj_index]; + for(auto obj : scenegraph->collide_objects_){ if(obj->GetType() == _env_object){ EnvObject* eo = (EnvObject*)obj; - for(size_t i=0, len=eo->normal_override_custom.size(); inormal_override_custom[i] == vec4(0.0f)){ - eo->normal_override_custom[i] = vec4(0.0f,9.5f,0.0f,1.0f); + for(auto & i : eo->normal_override_custom){ + if(i == vec4(0.0f)){ + i = vec4(0.0f,9.5f,0.0f,1.0f); } } eo->normal_override_buffer_dirty = true; @@ -3468,8 +3461,8 @@ Mark Stockton\nMikko Tarmia"); } if(paint_type == 0){ if(actually_painting){ - for(size_t i=0, len=eo->normal_override_custom.size(); inormal_override_custom[i] = norm; + for(auto & i : eo->normal_override_custom){ + i = norm; } eo->normal_override_buffer_dirty = true; } @@ -3505,11 +3498,11 @@ Mark Stockton\nMikko Tarmia"); std::vector checked; checked.resize(half_edges.size(), 0); std::queue to_check; - for(size_t index=0, len=half_edges.size(); indexvert[0]]*3; - memcpy(&verts[i], &model->vertices[vert_index], sizeof(vec3)); + memcpy(&vert, &model->vertices[vert_index], sizeof(vec3)); curr = curr->next; } @@ -3578,15 +3571,15 @@ Mark Stockton\nMikko Tarmia"); } } eo->ledge_lines.clear(); - for(size_t index=0, len=half_edges.size(); indextwin) { if( (int)eo->normal_override_custom.size() > half_edge_faces[curr->id] ) { int curr_color = (int)(eo->normal_override_custom[half_edge_faces[curr->id]][1]); int neighbor_color = (int)(eo->normal_override_custom[half_edge_faces[curr->twin->id]][1]); if(curr_color == 6 && neighbor_color < 4){ - for(int j=0; j<2; ++j){ - int vert_index = processed_model.old_vert_id[curr->vert[j]]*3; + for(int j : curr->vert){ + int vert_index = processed_model.old_vert_id[j]*3; eo->ledge_lines.push_back(vert_index); } } @@ -3683,8 +3676,8 @@ Mark Stockton\nMikko Tarmia"); std::string current_hot_join_char = online->GetDefaultHotJoinCharacter(); ImGui::Text(("Hot join character: " + current_hot_join_char).c_str()); if (ImGui::BeginMenu("Select hot join character")) { - for (uint32_t i = 0; i < character_tab->size(); i++) { - SpawnerItem * item = &((*character_tab)[i]); // no way that the asm is pretty here + for (auto & i : *character_tab) { + SpawnerItem * item = &i; // no way that the asm is pretty here if (IsCharacterSelceted(item)) { online->SetDefaultHotJoinCharacter(item->path); @@ -3793,8 +3786,8 @@ Mark Stockton\nMikko Tarmia"); // Display actual chat messages ImGui::PushTextWrapPos(); - for(size_t i = 0; i < chat_messages.size(); i++) { - ImGui::Text(chat_messages[i].message.c_str()); + for(const auto & chat_message : chat_messages) { + ImGui::Text(chat_message.message.c_str()); } ImGui::PopTextWrapPos(); @@ -4728,8 +4721,7 @@ Mark Stockton\nMikko Tarmia"); const int kBufSize = 1024; char* buf_sanityerror = (char*)alloc.stack.Alloc(kBufSize); char* buf_dispname = (char*)alloc.stack.Alloc(kBufSize); - for( unsigned i = 0; i < SceneGraph::kMaxWarnings; i++ ) { - ObjectSanityState& sanity = scenegraph->sanity_list[i]; + for(auto & sanity : scenegraph->sanity_list) { if(sanity.Valid() && sanity.Ok() == false) { Object* obj = scenegraph->GetObjectFromID(sanity.GetID()); if(obj) { @@ -4790,11 +4782,11 @@ Mark Stockton\nMikko Tarmia"); ImGui::Text("File breakpoints"); const std::vector > global_breakpoints = ASDebugger::GetGlobalBreakpoints(); - for(size_t i = 0; i < global_breakpoints.size(); ++i) { + for(const auto & global_breakpoint : global_breakpoints) { char buffer[256]; - sprintf(buffer, "%s:%d", global_breakpoints[i].first.c_str(), global_breakpoints[i].second); + sprintf(buffer, "%s:%d", global_breakpoint.first.c_str(), global_breakpoint.second); if(ImGui::Button(buffer)) { - ASDebugger::RemoveGlobalBreakpoint(global_breakpoints[i].first.c_str(), global_breakpoints[i].second); + ASDebugger::RemoveGlobalBreakpoint(global_breakpoint.first.c_str(), global_breakpoint.second); } } @@ -4861,8 +4853,8 @@ Mark Stockton\nMikko Tarmia"); bool is_breakpoint = false; if(breakpoints != NULL) { - for(size_t i = 0; i < breakpoints->size(); ++i) { - if(breakpoints->at(i) == line_nr) { + for(int breakpoint : *breakpoints) { + if(breakpoint == line_nr) { is_breakpoint = true; break; } @@ -4918,9 +4910,9 @@ Mark Stockton\nMikko Tarmia"); ImGui::Text("Each time point is calculated by taking the max time over %d frames", ASProfiler::GetMaxWindowSize()); ImGui::Text("Times may appear to be lagging because not all functions are called each frame"); - for(size_t i = 0; i < active_contexts.size(); ++i) { - if(active_contexts[i]->profiler.enabled) - active_contexts[i]->profiler.Draw(); + for(auto active_context : active_contexts) { + if(active_context->profiler.enabled) + active_context->profiler.Draw(); } ImGui::End(); diff --git a/Source/GUI/dimgui/modmenu.cpp b/Source/GUI/dimgui/modmenu.cpp index 2525ed60..30fb2ecc 100644 --- a/Source/GUI/dimgui/modmenu.cpp +++ b/Source/GUI/dimgui/modmenu.cpp @@ -88,22 +88,22 @@ static std::vector > > GetCatego const std::vector mods = ModLoading::Instance().GetAllMods(); - for( uint32_t i = 0; i < mods.size() ; i++ ) { - if( mods[i]->IsCore() ) { - categorized_mods[5].second.push_back( mods[i] ); - } else if( mods[i]->modsource == ModSourceLocalModFolder ) { - categorized_mods[0].second.push_back( mods[i] ); - } else if( mods[i]->modsource == ModSourceSteamworks ) { - if( mods[i]->IsOwnedByCurrentUser() ) { - categorized_mods[3].second.push_back( mods[i] ); + for(auto mod : mods) { + if( mod->IsCore() ) { + categorized_mods[5].second.push_back( mod ); + } else if( mod->modsource == ModSourceLocalModFolder ) { + categorized_mods[0].second.push_back( mod ); + } else if( mod->modsource == ModSourceSteamworks ) { + if( mod->IsOwnedByCurrentUser() ) { + categorized_mods[3].second.push_back( mod ); } else { - if( mods[i]->IsFavorite() ) { - categorized_mods[4].second.push_back( mods[i] ); + if( mod->IsFavorite() ) { + categorized_mods[4].second.push_back( mod ); } else { - if( mods[i]->IsSubscribed() ) { - categorized_mods[1].second.push_back( mods[i] ); + if( mod->IsSubscribed() ) { + categorized_mods[1].second.push_back( mod ); } else { - categorized_mods[2].second.push_back( mods[i] ); + categorized_mods[2].second.push_back( mod ); } } } @@ -152,8 +152,7 @@ static void DrawSimpleModMenu( ) { for(; modcatit != categmods.end(); modcatit++ ) { const std::vector mods = modcatit->second; if( mods.size() > 0 && ImGui::TreeNodeEx(modcatit->first,ImGuiTreeNodeFlags_DefaultOpen) ) { - for(uint32_t i = 0; i < mods.size(); ++i) { - ModInstance* mod = mods[i]; + for(auto mod : mods) { bool active = mod->IsActive(); ModID sid = mod->GetSid(); ImGui::PushID(sid.id); @@ -262,8 +261,7 @@ static void DrawAdvancedModMenu(Engine* engine) { for(; modcatit != categmods.end(); modcatit++ ) { const std::vector mods = modcatit->second; if( mods.size() > 0 && ImGui::TreeNodeEx(modcatit->first,ImGuiTreeNodeFlags_DefaultOpen) ) { - for(uint32_t i = 0; i < mods.size(); ++i) { - ModInstance* mod = mods[i]; + for(auto mod : mods) { bool active = mod->IsActive(); ModID sid = mod->GetSid(); ImGui::PushID(sid.id); @@ -449,23 +447,23 @@ static void DrawAdvancedModMenu(Engine* engine) { std::vector validity_errors = modi->GetValidityErrorsArr(); ImGui::Text( "Errors:" ); - for( unsigned i = 0; i < validity_errors.size(); i++ ) { + for(auto & validity_error : validity_errors) { ImGui::NextColumn(); - ImGui::Text( "%s", validity_errors[i].c_str() ); + ImGui::Text( "%s", validity_error.c_str() ); ImGui::NextColumn(); } ImGui::Separator(); ImGui::Text( "Mod Dependencies:" ); - for( unsigned i = 0; i < modi->mod_dependencies.size(); i++ ) { + for(auto & mod_dependencie : modi->mod_dependencies) { ImGui::NextColumn(); - ImGui::Text( "%s", modi->mod_dependencies[i].id.c_str() ); + ImGui::Text( "%s", mod_dependencie.id.c_str() ); ImGui::NextColumn(); } ImGui::Separator(); ImGui::Text( "Supported Version:" ); - for( unsigned i = 0; i < modi->supported_versions.size(); i++ ) { + for(auto & supported_version : modi->supported_versions) { ImGui::NextColumn(); - ImGui::Text( "%s", modi->supported_versions[i].c_str() ); + ImGui::Text( "%s", supported_version.c_str() ); ImGui::NextColumn(); } ImGui::Separator(); @@ -578,25 +576,25 @@ static void DrawAdvancedModMenu(Engine* engine) { ImGui::Separator(); ImGui::Text( "Items:" ); - for( unsigned i = 0; i < modi->items.size(); i++ ) { + for(auto & item : modi->items) { ImGui::NextColumn(); - ImGui::Text("%s", modi->items[i].title.c_str()); + ImGui::Text("%s", item.title.c_str()); ImGui::NextColumn(); } ImGui::Separator(); ImGui::Text( "Levels:" ); - for( unsigned i = 0; i < modi->levels.size(); i++ ) { + for(auto & level : modi->levels) { ImGui::NextColumn(); - ImGui::Text("%s", modi->levels[i].title.c_str()); + ImGui::Text("%s", level.title.c_str()); ImGui::NextColumn(); } ImGui::Separator(); ImGui::Text( "Campaigns:" ); - for( unsigned i = 0; i < modi->campaigns.size(); ++i) { + for(auto & campaign : modi->campaigns) { ImGui::NextColumn(); - ImGui::Text("%s", modi->campaigns[i].title.c_str()); + ImGui::Text("%s", campaign.title.c_str()); ImGui::NextColumn(); } @@ -605,9 +603,9 @@ static void DrawAdvancedModMenu(Engine* engine) { for( unsigned i = 0; i < modi->campaigns.size(); i++ ) { ImGui::Text("%s levels:", modi->campaigns[i].title.c_str()); - for( unsigned j = 0; j < modi->campaigns[i].levels.size(); j++ ) { + for(auto & level : modi->campaigns[i].levels) { ImGui::NextColumn(); - ImGui::Text("%s", modi->campaigns[i].levels[j].title.c_str()); + ImGui::Text("%s", level.title.c_str()); ImGui::NextColumn(); } @@ -624,20 +622,20 @@ static void DrawAdvancedModMenu(Engine* engine) { ImGui::Text("Parameter Data"); ImGui::Separator(); - for( unsigned i = 0; i < modi->levels.size(); i++ ) { - if(ImGui::TreeNode(modi->levels[i].title.c_str(),"%s level", modi->levels[i].title.c_str())) { - ImguiDrawParameter(&modi->levels[i].parameter,"",0); + for(auto & level : modi->levels) { + if(ImGui::TreeNode(level.title.c_str(),"%s level", level.title.c_str())) { + ImguiDrawParameter(&level.parameter,"",0); ImGui::TreePop(); } } - for(unsigned i = 0; i < modi->campaigns.size(); ++i) { + for(auto & campaign : modi->campaigns) { ImGui::PushID("campaign_params"); - if(ImGui::TreeNode(modi->campaigns[i].id.c_str(), "%s campaign", modi->campaigns[i].title.c_str())) { - ImguiDrawParameter(&modi->campaigns[i].parameter,"",0); - for( unsigned j = 0; j < modi->campaigns[i].levels.size(); j++ ) { - if(ImGui::TreeNode(modi->campaigns[i].levels[j].title.c_str(),"%s level", modi->campaigns[i].levels[j].title.c_str())){ - ImguiDrawParameter(&modi->campaigns[i].levels[j].parameter,"",0); + if(ImGui::TreeNode(campaign.id.c_str(), "%s campaign", campaign.title.c_str())) { + ImguiDrawParameter(&campaign.parameter,"",0); + for( unsigned j = 0; j < campaign.levels.size(); j++ ) { + if(ImGui::TreeNode(campaign.levels[j].title.c_str(),"%s level", campaign.levels[j].title.c_str())){ + ImguiDrawParameter(&campaign.levels[j].parameter,"",0); ImGui::TreePop(); } } @@ -1183,8 +1181,8 @@ void DrawModMenu(Engine* engine) { ImGui::SetNextWindowSize(ImVec2(1024.0f, 768.0f), ImGuiCond_FirstUseEver); ImGui::Begin("Manifest", &show_manifest); if( modi ) { - for( unsigned i = 0; i < modi->manifest.size(); i++ ) { - ImGui::Text( "%s", modi->manifest[i].c_str() ); + for(auto & i : modi->manifest) { + ImGui::Text( "%s", i.c_str() ); } } ImGui::End(); diff --git a/Source/GUI/dimgui/settings_screen.cpp b/Source/GUI/dimgui/settings_screen.cpp index e3e8abd2..5643d59a 100644 --- a/Source/GUI/dimgui/settings_screen.cpp +++ b/Source/GUI/dimgui/settings_screen.cpp @@ -300,8 +300,8 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ dropdown_item = 0; for(int i=0; i<3; ++i){ Config::Map& map = global_settings[i].map_; - for(Config::Map::iterator iter = map.begin(); iter != map.end(); ++iter ){ - if(config.GetRef(iter->first) != iter->second.data){ + for(auto & iter : map){ + if(config.GetRef(iter.first) != iter.second.data){ dropdown_item = i + 1; break; } @@ -320,8 +320,8 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ if(dropdown_item != 0){ int curr_global_setting = dropdown_item-1; Config::Map& map = global_settings[curr_global_setting].map_; - for(Config::Map::iterator iter = map.begin(); iter != map.end(); ++iter ){ - config.GetRef(iter->first) = iter->second.data; + for(auto & iter : map){ + config.GetRef(iter.first) = iter.second.data; } UpdateMultisampleSetting(config.GetRef("multisample").toNumber()); UpdateAnisotropy(config.GetRef("anisotropy").toNumber()); @@ -1129,8 +1129,7 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ if (ImGui::BeginMenu("Campaign Progress (Dangerous)")) { if(ImGui::Button("Unlock all campaign levels")){ std::vector campaigns = ModLoading::Instance().GetCampaigns(); - for( size_t i = 0; i < campaigns.size(); i++ ) { - ModInstance::Campaign camp = campaigns[i]; + for(auto camp : campaigns) { SavedLevel& s = Engine::Instance()->save_file_.GetSave(camp.id.str(),"linear_campaign",""); for( size_t k = 0; k < camp.levels.size(); k++ ) { s.SetArrayValue("unlocked_levels",k,camp.levels[k].id.str()); @@ -1141,8 +1140,7 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ if(ImGui::BeginMenu("Unlock level in campaign")) { std::vector campaigns = ModLoading::Instance().GetCampaigns(); - for( size_t i = 0; i < campaigns.size(); i++ ) { - ModInstance::Campaign camp = campaigns[i]; + for(auto camp : campaigns) { if(ImGui::BeginMenu(camp.title.c_str())) { for( size_t k = 0; k < camp.levels.size(); k++ ) { if(ImGui::Button(camp.levels[k].title.c_str())) { @@ -1159,8 +1157,7 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ if(ImGui::Button("Clear all campaign progress")){ std::vector campaigns = ModLoading::Instance().GetCampaigns(); - for( size_t i = 0; i < campaigns.size(); i++ ) { - ModInstance::Campaign camp = campaigns[i]; + for(auto camp : campaigns) { SavedLevel& s = Engine::Instance()->save_file_.GetSave(camp.id.str(),"linear_campaign",""); s.ClearData(); } @@ -1170,15 +1167,14 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ std::vector difficulties = config.GetDifficultyPresets(); if(ImGui::BeginMenu("Finish All Levels On Difficulty")) { - for( size_t k = 0; k < difficulties.size(); k++ ) { - if( ImGui::Button(difficulties[k].c_str())) { + for(auto & difficultie : difficulties) { + if( ImGui::Button(difficultie.c_str())) { std::vector campaigns = ModLoading::Instance().GetCampaigns(); - for( size_t i = 0; i < campaigns.size(); i++ ) { - ModInstance::Campaign camp = campaigns[i]; + for(auto camp : campaigns) { for( size_t j = 0; j < camp.levels.size(); j++ ) { SavedLevel& s = Engine::Instance()->save_file_.GetSave(camp.id.str(),"linear_campaign",camp.levels[j].id.str()); - if( false == s.ArrayContainsValue("finished_difficulties",difficulties[k]) ) { - s.AppendArrayValue("finished_difficulties",difficulties[k]); + if( false == s.ArrayContainsValue("finished_difficulties",difficultie) ) { + s.AppendArrayValue("finished_difficulties",difficultie); } } } @@ -1190,17 +1186,16 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ if(ImGui::BeginMenu("Finish Level On Difficulty")) { std::vector campaigns = ModLoading::Instance().GetCampaigns(); - for( size_t i = 0; i < campaigns.size(); i++ ) { - ModInstance::Campaign camp = campaigns[i]; + for(auto camp : campaigns) { if(ImGui::BeginMenu(camp.title)) { for( size_t j = 0; j < camp.levels.size(); j++ ) { ModInstance::Level level = camp.levels[j]; if(ImGui::BeginMenu(level.title)) { - for( size_t k = 0; k < difficulties.size(); k++ ) { - if( ImGui::Button(difficulties[k].c_str())) { + for(auto & difficultie : difficulties) { + if( ImGui::Button(difficultie.c_str())) { SavedLevel& s = Engine::Instance()->save_file_.GetSave(camp.id.str(),"linear_campaign",level.id.str()); - if( false == s.ArrayContainsValue("finished_difficulties",difficulties[k]) ) { - s.AppendArrayValue("finished_difficulties",difficulties[k]); + if( false == s.ArrayContainsValue("finished_difficulties",difficultie) ) { + s.AppendArrayValue("finished_difficulties",difficultie); } Engine::Instance()->save_file_.QueueWriteInPlace(); } @@ -1216,8 +1211,7 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ if(ImGui::Button("Clear All Linear Level Data")) { std::vector campaigns = ModLoading::Instance().GetCampaigns(); - for( size_t i = 0; i < campaigns.size(); i++ ) { - ModInstance::Campaign camp = campaigns[i]; + for(auto camp : campaigns) { for( size_t j = 0; j < camp.levels.size(); j++ ) { SavedLevel& s = Engine::Instance()->save_file_.GetSave(camp.id.str(),"linear_campaign",camp.levels[j].id.str()); s.ClearData(); @@ -1228,8 +1222,7 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ if(ImGui::BeginMenu("Clear Save Data For Level")) { std::vector campaigns = ModLoading::Instance().GetCampaigns(); - for( size_t i = 0; i < campaigns.size(); i++ ) { - ModInstance::Campaign camp = campaigns[i]; + for(auto camp : campaigns) { if(ImGui::BeginMenu(camp.title)) { for( size_t j = 0; j < camp.levels.size(); j++ ) { ModInstance::Level level = camp.levels[j]; diff --git a/Source/Game/EntityDescription.cpp b/Source/Game/EntityDescription.cpp index ac038e32..0392ae63 100644 --- a/Source/Game/EntityDescription.cpp +++ b/Source/Game/EntityDescription.cpp @@ -93,27 +93,27 @@ void EntityDescription::AddString( EntityDescriptionFieldType type, const std::s } const EntityDescriptionField* EntityDescription::GetField( EntityDescriptionFieldType type ) const { - for(unsigned i=0; iGetAssetManager()->LoadSync(str)->ReturnPaths(path_set); break; case _group:{ - for(EntityDescriptionList::iterator iter = children.begin(); iter != children.end(); ++iter){ - EntityDescription& child = (*iter); + for(auto & child : children){ child.ReturnPaths(path_set); } break;} case _prefab:{ - for(EntityDescriptionList::iterator iter = children.begin(); iter != children.end(); ++iter){ - EntityDescription& child = (*iter); + for(auto & child : children){ child.ReturnPaths(path_set); } break;} @@ -222,8 +219,7 @@ void EntityDescription::AddType( EntityDescriptionFieldType type ) { void EntityDescription::SaveToXML( TiXmlElement* parent ) const { TiXmlElement* object = new TiXmlElement("Unknown Type"); parent->LinkEndChild(object); - for(unsigned i=0; iLinkEndChild(connections_el); - for(size_t i=0, len=connections.size(); iSetAttribute("id", connections[i]); + connection->SetAttribute("id", i); connections_el->LinkEndChild(connection); } break;} @@ -387,9 +383,9 @@ void EntityDescription::SaveToXML( TiXmlElement* parent ) const { // Write connections to XML TiXmlElement* connections_el = new TiXmlElement("ConnectionsFrom"); object->LinkEndChild(connections_el); - for(size_t i=0, len=connections.size(); iSetAttribute("id", connections[i]); + connection->SetAttribute("id", i); connections_el->LinkEndChild(connection); } break;} @@ -399,8 +395,7 @@ void EntityDescription::SaveToXML( TiXmlElement* parent ) const { // Write item connections to XML TiXmlElement* item_connections_el = new TiXmlElement("ItemConnections"); object->LinkEndChild(item_connections_el); - for(size_t i=0, len=item_connections.size(); iSetAttribute("id", item_connection.id); item_connection_el->SetAttribute("type", item_connection.attachment_type); @@ -491,14 +486,12 @@ void EntityDescription::SaveToXML( TiXmlElement* parent ) const { Deserialize(field.data, aeo_vec); TiXmlElement* env_object_attachments = new TiXmlElement("EnvObjectAttachments"); object->LinkEndChild(env_object_attachments); - for(unsigned i=0; iLinkEndChild(connection); - const AttachedEnvObject& aeo = aeo_vec[i]; - for(unsigned j=0; jLinkEndChild(bone_connect_el); - const BoneConnect &bone_connect = aeo.bone_connects[j]; bone_connect_el->SetAttribute("bone_id", bone_connect.bone_id); bone_connect_el->SetAttribute("num_connections", bone_connect.num_connections); int index; @@ -528,8 +521,7 @@ void EntityDescription::SaveToXML( TiXmlElement* parent ) const { TiXmlElement* navmesh_connections_el = new TiXmlElement("NavMeshConnections"); object->LinkEndChild(navmesh_connections_el); - for(size_t i=0, len=navmesh_connections.size(); iSetAttribute("other_object_id", navmesh_connection.other_object_id); navmesh_connection_el->SetAttribute("offmesh_connection_id", navmesh_connection.offmesh_connection_id); @@ -574,10 +566,8 @@ void EntityDescription::SaveToXML( TiXmlElement* parent ) const { } } - for(EntityDescriptionList::const_iterator iter = children.begin(); - iter != children.end(); ++iter) + for(const auto & child : children) { - const EntityDescription& child = (*iter); child.SaveToXML(object); } } @@ -1262,10 +1252,9 @@ void ClearDescID(EntityDescription *desc) { memwrite(&null_id, sizeof(int), 1, edf->data); } EntityDescriptionList &children = desc->children; - for(EntityDescriptionList::iterator it = children.begin(); - it != children.end(); ++it) + for(auto & it : children) { - ClearDescID(&(*it)); + ClearDescID(&it); } } diff --git a/Source/Game/characterscript.cpp b/Source/Game/characterscript.cpp index bb713cf9..e1b12631 100644 --- a/Source/Game/characterscript.cpp +++ b/Source/Game/characterscript.cpp @@ -46,9 +46,9 @@ std::string CharacterScriptGetter::GetSkeletonPath( ) { } std::string CharacterScriptGetter::GetAnimPath( const std::string& action ) { - for(unsigned i=0; iHasAnimOverride(action)){ - return items[i]->GetAnimOverride(action); + for(auto & item : items){ + if(item->HasAnimOverride(action)){ + return item->GetAnimOverride(action); } } CharAnimOverrideMap::iterator iter = char_anim_overrides_.find(action); @@ -65,18 +65,18 @@ const std::string & CharacterScriptGetter::GetTag(const std::string &key) { char CharacterScriptGetter::GetAnimFlags( const std::string& action ) { - for(unsigned i=0; iHasAnimOverride(action)){ - return items[i]->GetAnimOverrideFlags(action); + for(auto & item : items){ + if(item->HasAnimOverride(action)){ + return item->GetAnimOverrideFlags(action); } } return 0; } std::string CharacterScriptGetter::GetAttackPath( const std::string& action ) { - for(unsigned i=0; iHasAttackOverride(action)){ - return items[i]->GetAttackOverride(action); + for(auto & item : items){ + if(item->HasAttackOverride(action)){ + return item->GetAttackOverride(action); } } return character_ref->GetAttackPath(action); @@ -86,11 +86,9 @@ int CharacterScriptGetter::OnSameTeam( const std::string& char_path ) { //CharacterRef other = Characters::Instance()->ReturnRef(char_path); CharacterRef other = Engine::Instance()->GetAssetManager()->LoadSync(char_path); const std::set &team_set = character_ref->GetTeamSet(); - for(std::set::const_iterator iter = team_set.begin(); - iter != team_set.end(); - ++iter) + for(const auto & iter : team_set) { - if(other->IsOnTeam(*iter)){ + if(other->IsOnTeam(iter)){ return 1; } } diff --git a/Source/Game/color_tint_component.cpp b/Source/Game/color_tint_component.cpp index fdc24574..56f1e6a3 100644 --- a/Source/Game/color_tint_component.cpp +++ b/Source/Game/color_tint_component.cpp @@ -58,8 +58,7 @@ void ColorTintComponent::LoadDescriptionFromXML( EntityDescription& desc, const } void ColorTintComponent::SetFromDescription( const EntityDescription& desc ) { - for(unsigned i=0; iGetASNetwork()->DeRegisterASNetworkCallback(this); old_col_map_.clear(); - for(int i=0; iHasFunction(as_contexts_[i].as_funcs.start_dialogue)) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.start_dialogue); + for (const auto & as_context : as_contexts_) { + if (as_context.ctx->HasFunction(as_context.as_funcs.start_dialogue)) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.start_dialogue); } } } void Level::RegisterMPCallbacks() const { - for (unsigned i = 0; i < as_contexts_.size(); i++) { - if (as_contexts_[i].ctx->HasFunction(as_contexts_[i].as_funcs.register_mp_callbacks)) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.register_mp_callbacks); + for (const auto & as_context : as_contexts_) { + if (as_context.ctx->HasFunction(as_context.as_funcs.register_mp_callbacks)) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.register_mp_callbacks); } } } @@ -163,8 +163,8 @@ void Level::Initialize(SceneGraph *scenegraph, GUI* gui) { } if(!npc_script_.empty()) { - for(size_t i = 0; i < scenegraph->movement_objects_.size(); ++i) { - MovementObject* obj = (MovementObject*)scenegraph->movement_objects_[i]; + for(auto & movement_object : scenegraph->movement_objects_) { + MovementObject* obj = (MovementObject*)movement_object; if(obj->GetNPCObjectScript().empty()) { obj->ChangeControlScript(npc_script_); } @@ -191,8 +191,8 @@ void Level::Initialize(SceneGraph *scenegraph, GUI* gui) { as_collisions.reset(new ASCollisions(scenegraph)); - for(unsigned i = 0; i < as_contexts_.size(); i++) { - ASContext* ctx = new ASContext(as_contexts_[i].context_name.c_str(),as_data); + for(auto & as_context : as_contexts_) { + ASContext* ctx = new ASContext(as_context.context_name.c_str(),as_data); AttachASNetwork(ctx); AttachUIQueries(ctx); @@ -220,40 +220,40 @@ void Level::Initialize(SceneGraph *scenegraph, GUI* gui) { character_script_getter_.AttachToScript(ctx, "character_getter"); as_collisions->AttachToContext(ctx); - as_contexts_[i].as_funcs.init = ctx->RegisterExpectedFunction("void Init(string level_name)", true); - as_contexts_[i].as_funcs.update = ctx->RegisterExpectedFunction("void Update(int is_paused)", false); - as_contexts_[i].as_funcs.update_deprecated = ctx->RegisterExpectedFunction("void Update()", false); - - as_contexts_[i].as_funcs.hotspot_exit = ctx->RegisterExpectedFunction("void HotspotExit(string event, MovementObject @mo)", false); - as_contexts_[i].as_funcs.hotspot_enter = ctx->RegisterExpectedFunction("void HotspotEnter(string event, MovementObject @mo)", false); - as_contexts_[i].as_funcs.receive_message = ctx->RegisterExpectedFunction("void ReceiveMessage(string message)", false); - as_contexts_[i].as_funcs.draw_gui = ctx->RegisterExpectedFunction("void DrawGUI()", false); - as_contexts_[i].as_funcs.draw_gui2 = ctx->RegisterExpectedFunction("void DrawGUI2()", false); - as_contexts_[i].as_funcs.draw_gui3 = ctx->RegisterExpectedFunction("void DrawGUI3()", false); - as_contexts_[i].as_funcs.has_focus = ctx->RegisterExpectedFunction("bool HasFocus()", false); - as_contexts_[i].as_funcs.dialogue_camera_control = ctx->RegisterExpectedFunction("bool DialogueCameraControl()", false); - as_contexts_[i].as_funcs.save_history_state = ctx->RegisterExpectedFunction("void SaveHistoryState(SavedChunk@ chunk)", false); - as_contexts_[i].as_funcs.read_chunk = ctx->RegisterExpectedFunction("void ReadChunk(SavedChunk@ chunk)", false); - as_contexts_[i].as_funcs.set_window_dimensions = ctx->RegisterExpectedFunction("void SetWindowDimensions(int width, int height)", false); - as_contexts_[i].as_funcs.incoming_tcp_data = ctx->RegisterExpectedFunction("void IncomingTCPData(uint socket, array@ data)", false); - - as_contexts_[i].as_funcs.pre_script_reload = ctx->RegisterExpectedFunction("void PreScriptReload()", false); - as_contexts_[i].as_funcs.post_script_reload = ctx->RegisterExpectedFunction("void PostScriptReload()", false); - - as_contexts_[i].as_funcs.menu = ctx->RegisterExpectedFunction("void Menu()", false); - as_contexts_[i].as_funcs.register_mp_callbacks = ctx->RegisterExpectedFunction("void RegisterMPCallBacks()", false); - as_contexts_[i].as_funcs.start_dialogue = ctx->RegisterExpectedFunction("void StartDialogue(const string &in name", false); + as_context.as_funcs.init = ctx->RegisterExpectedFunction("void Init(string level_name)", true); + as_context.as_funcs.update = ctx->RegisterExpectedFunction("void Update(int is_paused)", false); + as_context.as_funcs.update_deprecated = ctx->RegisterExpectedFunction("void Update()", false); + + as_context.as_funcs.hotspot_exit = ctx->RegisterExpectedFunction("void HotspotExit(string event, MovementObject @mo)", false); + as_context.as_funcs.hotspot_enter = ctx->RegisterExpectedFunction("void HotspotEnter(string event, MovementObject @mo)", false); + as_context.as_funcs.receive_message = ctx->RegisterExpectedFunction("void ReceiveMessage(string message)", false); + as_context.as_funcs.draw_gui = ctx->RegisterExpectedFunction("void DrawGUI()", false); + as_context.as_funcs.draw_gui2 = ctx->RegisterExpectedFunction("void DrawGUI2()", false); + as_context.as_funcs.draw_gui3 = ctx->RegisterExpectedFunction("void DrawGUI3()", false); + as_context.as_funcs.has_focus = ctx->RegisterExpectedFunction("bool HasFocus()", false); + as_context.as_funcs.dialogue_camera_control = ctx->RegisterExpectedFunction("bool DialogueCameraControl()", false); + as_context.as_funcs.save_history_state = ctx->RegisterExpectedFunction("void SaveHistoryState(SavedChunk@ chunk)", false); + as_context.as_funcs.read_chunk = ctx->RegisterExpectedFunction("void ReadChunk(SavedChunk@ chunk)", false); + as_context.as_funcs.set_window_dimensions = ctx->RegisterExpectedFunction("void SetWindowDimensions(int width, int height)", false); + as_context.as_funcs.incoming_tcp_data = ctx->RegisterExpectedFunction("void IncomingTCPData(uint socket, array@ data)", false); + + as_context.as_funcs.pre_script_reload = ctx->RegisterExpectedFunction("void PreScriptReload()", false); + as_context.as_funcs.post_script_reload = ctx->RegisterExpectedFunction("void PostScriptReload()", false); + + as_context.as_funcs.menu = ctx->RegisterExpectedFunction("void Menu()", false); + as_context.as_funcs.register_mp_callbacks = ctx->RegisterExpectedFunction("void RegisterMPCallBacks()", false); + as_context.as_funcs.start_dialogue = ctx->RegisterExpectedFunction("void StartDialogue(const string &in name", false); - ctx->LoadScript(as_contexts_[i].path); + ctx->LoadScript(as_context.path); - as_contexts_[i].ctx = ctx; + as_context.ctx = ctx; } - for(unsigned i = 0; i < as_contexts_.size(); i++) { + for(auto & as_context : as_contexts_) { LOGI << "Calling void Init(string level_name) for level hook file." << std::endl; ASArglist args; args.AddObject(&scenegraph->level_name_); - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.init, &args); + as_context.ctx->CallScriptFunction(as_context.as_funcs.init, &args); } @@ -272,10 +272,10 @@ void Level::Update(bool paused) { args.Add(paused?1:0); std::vector::iterator cit = as_contexts_.begin(); PROFILER_ENTER(g_profiler_ctx, "Level script Update()"); - for( unsigned i = 0; i < as_contexts_.size(); i++ ) { - if( as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.update, &args) == false) { + for(auto & as_context : as_contexts_) { + if( as_context.ctx->CallScriptFunction(as_context.as_funcs.update, &args) == false) { if(paused == false) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.update_deprecated, &args2); + as_context.ctx->CallScriptFunction(as_context.as_funcs.update_deprecated, &args2); } } } @@ -290,8 +290,8 @@ void Level::Update(bool paused) { bool angelscriptCallSuccesfull = false; - for (unsigned i = 0; i < as_contexts_.size(); i++) { - if (as_contexts_[i].ctx->CallMPCallBack(update.state, temp) ) { + for (auto & as_context : as_contexts_) { + if (as_context.ctx->CallMPCallBack(update.state, temp) ) { angelscriptCallSuccesfull = true; } } @@ -308,8 +308,8 @@ void Level::Update(bool paused) { bool angelscriptCallSuccesfull = false; - for (unsigned i = 0; i < as_contexts_.size(); i++) { - if (as_contexts_[i].ctx->CallMPCallBack(update.state, temp)) { + for (auto & as_context : as_contexts_) { + if (as_context.ctx->CallMPCallBack(update.state, temp)) { angelscriptCallSuccesfull = true; } } @@ -342,14 +342,13 @@ void Level::HandleCollisions( CollisionPtrMap &col_map, SceneGraph &scenegraph ) old_col_ptr_map.clear(); { CollisionMap &map = old_col_map_; - for(CollisionMap::iterator iter = map.begin(); iter != map.end(); ++iter){ - int id = iter->first; + for(auto & iter : map){ + int id = iter.first; Object* obj_a_ptr = scenegraph.GetObjectFromID(id); if(obj_a_ptr){ - CollisionSet &set = iter->second; - for(CollisionSet::iterator iter = set.begin(); iter != set.end(); ++iter){ - int id = *iter; - Object* obj_b_ptr = scenegraph.GetObjectFromID(id); + CollisionSet &set = iter.second; + for(int id : set){ + Object* obj_b_ptr = scenegraph.GetObjectFromID(id); if(obj_b_ptr){ old_col_ptr_map[obj_a_ptr].insert(obj_b_ptr); } @@ -450,11 +449,11 @@ void Level::HandleCollisions( CollisionPtrMap &col_map, SceneGraph &scenegraph ) // Convert old collision pointers to ids CollisionPtrMap &map = col_map; old_col_map_.clear(); - for(CollisionPtrMap::iterator iter = map.begin(); iter != map.end(); ++iter){ - int id_a = ((Object*)iter->first)->GetID(); - CollisionPtrSet &set = iter->second; - for(CollisionPtrSet::iterator iter = set.begin(); iter != set.end(); ++iter){ - int id_b = ((Object*)(*iter))->GetID(); + for(auto & iter : map){ + int id_a = ((Object*)iter.first)->GetID(); + CollisionPtrSet &set = iter.second; + for(auto iter : set){ + int id_b = ((Object*)iter)->GetID(); old_col_map_[id_a].insert(id_b); } } @@ -470,8 +469,8 @@ void Level::HandleCollisions( CollisionPtrMap &col_map, SceneGraph &scenegraph ) args.AddObject((void*)&exit_call_queue_it->first->GetScriptFile()); args.AddAddress((void*)exit_call_queue_it->second); - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.hotspot_exit, &args); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.hotspot_exit, &args); } } @@ -482,8 +481,8 @@ void Level::HandleCollisions( CollisionPtrMap &col_map, SceneGraph &scenegraph ) args.AddObject((void*)&enter_call_queue_it->first->GetScriptFile()); args.AddAddress((void*)enter_call_queue_it->second); - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.hotspot_enter, &args); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.hotspot_enter, &args); } } } @@ -526,18 +525,18 @@ void Level::Message( const std::string &msg ) { online->SendLevelMessage(msg); } - for( unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.receive_message, &args); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.receive_message, &args); } - for(int i=0, len=level_event_receivers.size(); iGetObjectFromID(level_event_receivers[i]); + for(int level_event_receiver : level_event_receivers){ + Object* obj = scenegraph->GetObjectFromID(level_event_receiver); if(obj){ obj->ReceiveScriptMessage("level_event " + msg); } else { const int kBufSize = 256; char buf[kBufSize]; - FormatString(buf, kBufSize, "Could not find level event receiver with id %d", level_event_receivers[i]); + FormatString(buf, kBufSize, "Could not find level event receiver with id %d", level_event_receiver); DisplayError("Error", buf); } } @@ -789,11 +788,11 @@ void Level::DefineLevelTypePublic(ASContext *as_context) { void Level::GetCollidingObjects( int id, CScriptArray *array ) { int collision[2]; - for(CollisionMap::iterator iter = old_col_map_.begin(); iter != old_col_map_.end(); ++iter){ - collision[0] = iter->first; - CollisionSet &set = iter->second; - for(CollisionSet::iterator iter = set.begin(); iter != set.end(); ++iter){ - collision[1] = *iter; + for(auto & iter : old_col_map_){ + collision[0] = iter.first; + CollisionSet &set = iter.second; + for(int iter : set){ + collision[1] = iter; if(collision[0] == id){ array->InsertLast(&collision[1]); } else if(collision[1] == id){ @@ -805,16 +804,16 @@ void Level::GetCollidingObjects( int id, CScriptArray *array ) { void Level::Draw() { PROFILER_GPU_ZONE(g_profiler_ctx, "Level::Draw"); - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.draw_gui); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.draw_gui); } hud_images.Draw(); - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.draw_gui2); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.draw_gui2); } hud_images.Draw(); - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.draw_gui3); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.draw_gui3); } hud_images.Draw(); } @@ -824,8 +823,7 @@ void Level::SetFromLevelInfo( const LevelInfo &li ) { pc_script_ = li.pc_script_; npc_script_ = li.npc_script_; level_script_paths.clear(); - for(int i=0, len=li.script_paths_.size(); iCallScriptFunction(as_contexts_[i].as_funcs.has_focus, &args, &return_arg); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.has_focus, &args, &return_arg); if(has_focus) { return true; } @@ -858,8 +856,8 @@ bool Level::DialogueCameraControl() { ASArg return_arg; return_arg.data = &dialogue_control; return_arg.type = _as_bool; - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.dialogue_camera_control, &args, &return_arg); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.dialogue_camera_control, &args, &return_arg); if(dialogue_control) { return true; } @@ -890,8 +888,8 @@ void Level::SaveHistoryState(std::list & chunks, int state_id) { ASArglist args; args.AddAddress(&saved_chunk); - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.save_history_state, &args); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.save_history_state, &args); } AddChunkToHistory(chunks, state_id, saved_chunk); } @@ -900,8 +898,8 @@ void Level::ReadChunk(const SavedChunk &the_chunk) { ASArglist args; args.AddAddress((void*)&the_chunk); - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.read_chunk, &args); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.read_chunk, &args); } } @@ -910,9 +908,9 @@ bool Level::isMetaDataDirty() { return true; } - for(size_t i = 0; i < scenegraph->objects_.size(); ++i) { - if(scenegraph->objects_[i]->GetType() == _placeholder_object) { - PlaceholderObject* obj = (PlaceholderObject*)scenegraph->objects_[i]; + for(auto & object : scenegraph->objects_) { + if(object->GetType() == _placeholder_object) { + PlaceholderObject* obj = (PlaceholderObject*)object; if(obj->GetScriptParams()->HasParam("Dialogue")) { if(obj->unsaved_changes) { return true; @@ -926,9 +924,9 @@ bool Level::isMetaDataDirty() { void Level::setMetaDataClean() { metaDataDirty = false; - for(size_t i = 0; i < scenegraph->objects_.size(); ++i) { - if(scenegraph->objects_[i]->GetType() == _placeholder_object) { - ((PlaceholderObject*)scenegraph->objects_[i])->unsaved_changes = false; + for(auto & object : scenegraph->objects_) { + if(object->GetType() == _placeholder_object) { + ((PlaceholderObject*)object)->unsaved_changes = false; } } } @@ -954,8 +952,8 @@ void Level::WindowResized(ivec2 value ) { ASArglist args; args.Add(value[0]); args.Add(value[1]); - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.set_window_dimensions, &args); + for(auto & as_context : as_contexts_) { + as_context.ctx->CallScriptFunction(as_context.as_funcs.set_window_dimensions, &args); } } @@ -977,8 +975,8 @@ std::vector Level::GetRecentlyCreatedItems() { } void Level::IncomingTCPData(SocketID socket, uint8_t* data, size_t len) { - for(unsigned i = 0; i < as_contexts_.size(); i++ ) { - asIScriptEngine *engine = as_contexts_[i].ctx->GetEngine(); + for(auto & as_context : as_contexts_) { + asIScriptEngine *engine = as_context.ctx->GetEngine(); asITypeInfo *arrayType = engine->GetTypeInfoByDecl("array"); CScriptArray* array = CScriptArray::Create(arrayType); @@ -992,7 +990,7 @@ void Level::IncomingTCPData(SocketID socket, uint8_t* data, size_t len) { args.Add(socket); args.AddAddress((void*)array); - as_contexts_[i].ctx->CallScriptFunction(as_contexts_[i].as_funcs.incoming_tcp_data, &args, NULL); + as_context.ctx->CallScriptFunction(as_context.as_funcs.incoming_tcp_data, &args, NULL); array->Release(); } diff --git a/Source/Game/levelinfo.cpp b/Source/Game/levelinfo.cpp index 306db12a..3bce0033 100644 --- a/Source/Game/levelinfo.cpp +++ b/Source/Game/levelinfo.cpp @@ -43,8 +43,8 @@ void LevelInfo::Print() LOGI << "Script: " << script_ << std::endl; terrain_info_.Print(); - for(unsigned i=0; iAddLine(GetPointPosition(connections[i].point_ids[0]), - GetPointPosition(connections[i].point_ids[1]), + for(auto & connection : connections){ + DebugDraw::Instance()->AddLine(GetPointPosition(connection.point_ids[0]), + GetPointPosition(connection.point_ids[1]), vec4(0.0f,0.5f,0.5f,0.5f), _delete_on_draw); } @@ -78,12 +78,12 @@ vec3 AIPaths::GetPointPosition( int point_id ) { int AIPaths::GetConnectedPoint( int point_id ) { - for(unsigned i=0; iHasReactionOverride(path)){ - path = items[i]->GetReactionOverride(path); + for(auto & item : items){ + if(item->HasReactionOverride(path)){ + path = item->GetReactionOverride(path); } } //reaction_ref = Reactions::Instance()->ReturnRef(path); diff --git a/Source/Game/savefile.cpp b/Source/Game/savefile.cpp index 8d03557b..e4811714 100644 --- a/Source/Game/savefile.cpp +++ b/Source/Game/savefile.cpp @@ -102,11 +102,11 @@ namespace { } SavedLevel& SaveFile::GetSavedLevelDeprecated( const std::string& name ) { - for( size_t i = 0; i < levels_.size(); i++ ) { - if( levels_[i].campaign_id_ == "" && - levels_[i].save_category_ == "" && - levels_[i].save_name_ == name ) { - return levels_[i]; + for(auto & level : levels_) { + if( level.campaign_id_ == "" && + level.save_category_ == "" && + level.save_name_ == name ) { + return level; } } @@ -119,11 +119,11 @@ SavedLevel& SaveFile::GetSavedLevelDeprecated( const std::string& name ) { } SavedLevel& SaveFile::GetSave(const std::string campaign_id, const std::string save_category, const std::string level_name) { - for( size_t i = 0; i < levels_.size(); i++ ) { - if( levels_[i].campaign_id_ == campaign_id && - levels_[i].save_category_ == save_category && - levels_[i].save_name_ == level_name ) { - return levels_[i]; + for(auto & level : levels_) { + if( level.campaign_id_ == campaign_id && + level.save_category_ == save_category && + level.save_name_ == level_name ) { + return level; } } @@ -146,10 +146,10 @@ size_t SaveFile::GetSaveCount() { } bool SaveFile::SaveExist(const std::string campaign_id, const std::string save_category, const std::string level_name) { - for( size_t i = 0; i < levels_.size(); i++ ) { - if( levels_[i].campaign_id_ == campaign_id && - levels_[i].save_category_ == save_category && - levels_[i].save_name_ == level_name ) { + for(auto & level : levels_) { + if( level.campaign_id_ == campaign_id && + level.save_category_ == save_category && + level.save_name_ == level_name ) { return true; } } @@ -313,17 +313,17 @@ bool SaveFile::SerializeToRAM( std::vector *mem_ptr ) { if(!file.WriteBytes(&num_levels, sizeof(num_levels))){ return false; } - for(std::vector::iterator it = levels_.begin(); it != levels_.end(); ++it){ - if(!WriteString(&file, &it->campaign_id_)){ + for(auto & level : levels_){ + if(!WriteString(&file, &level.campaign_id_)){ return false; } - if(!WriteString(&file, &it->save_category_)){ + if(!WriteString(&file, &level.save_category_)){ return false; } - if(!WriteString(&file, &it->save_name_)){ + if(!WriteString(&file, &level.save_name_)){ return false; } - if(!it->SerializeToRAM(&file)){ + if(!level.SerializeToRAM(&file)){ return false; } } @@ -442,8 +442,8 @@ void SavedLevel::AppendArrayValue(const std::string &key, const std::string& val bool SavedLevel::ArrayContainsValue(const std::string &key, const std::string& val) { std::vector &v = array_data_[key]; - for( size_t i = 0; i < v.size(); i++ ) { - if(v[i] == val){ + for(auto & i : v) { + if(i == val){ return true; } } @@ -497,11 +497,11 @@ bool SavedLevel::SerializeToRAM( MemWriteFileDescriptor *file_ptr ) { if(!file.WriteBytes(&num_saved_vals, sizeof(num_saved_vals))){ return false; } - for(DataMap::iterator it = data_.begin(); it != data_.end(); ++it){ - if(!WriteString(&file, &it->first)){ + for(auto & it : data_){ + if(!WriteString(&file, &it.first)){ return false; } - if(!WriteString(&file, &it->second)){ + if(!WriteString(&file, &it.second)){ return false; } } @@ -512,17 +512,17 @@ bool SavedLevel::SerializeToRAM( MemWriteFileDescriptor *file_ptr ) { if(!file.WriteBytes(&num_saved_array_vals, sizeof(num_saved_array_vals))){ return false; } - for(ArrayDataMap::iterator it = array_data_.begin(); it != array_data_.end(); it++) { - if(!WriteString(&file, &it->first)){ + for(auto & it : array_data_) { + if(!WriteString(&file, &it.first)){ return false; } - uint16_t num_saved_array_sub_vals = it->second.size(); + uint16_t num_saved_array_sub_vals = it.second.size(); if(!file.WriteBytes(&num_saved_array_sub_vals, sizeof(num_saved_array_sub_vals))){ return false; } - for(std::vector::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++) { + for(std::vector::iterator it2 = it.second.begin(); it2 != it.second.end(); it2++) { if(!WriteString(&file, &(*it2))){ return false; } @@ -535,11 +535,11 @@ bool SavedLevel::SerializeToRAM( MemWriteFileDescriptor *file_ptr ) { if(!file.WriteBytes(&num_saved_int32_vals, sizeof(num_saved_int32_vals))){ return false; } - for(Int32Map::iterator it = data_int32_.begin(); it != data_int32_.end(); ++it){ - if(!WriteString(&file, &it->first)){ + for(auto & it : data_int32_){ + if(!WriteString(&file, &it.first)){ return false; } - int32_t val = it->second; + int32_t val = it.second; if(!file.WriteBytes(&val, sizeof(val))){ return false; } diff --git a/Source/Game/terraininfo.cpp b/Source/Game/terraininfo.cpp index 9f5c9643..231822bd 100644 --- a/Source/Game/terraininfo.cpp +++ b/Source/Game/terraininfo.cpp @@ -43,14 +43,14 @@ void TerrainInfo::Print() LOGI << "Model Override: " << model_override << std::endl; LOGI << "Shader Extra: " << shader_extra << std::endl; LOGI << "Detail maps:" << std::endl; - for (unsigned i=0; i AnimationClient::GetActiveEvents() { events.pop(); } } - for(unsigned i=0; i &events = layers[i].reader.GetActiveEvents(); + for(auto & layer : layers){ + std::queue &events = layer.reader.GetActiveEvents(); while(!events.empty()){ total_events.push(events.front()); events.pop(); @@ -157,8 +157,8 @@ void AnimationClient::Update(float timestep) { } } fade_out.Update(blendmap, as_context, timestep); - for(unsigned i=0; i &weap_anim_info_map = ang_anim_output.weap_anim_info_map; - for(int i=0, len=ang_anim_output.ik_bones.size(); i normalized_time){ - return (*anim).AbsoluteTimeFromNormalized(events[i].time - normalized_time) / speed_mult * 0.001f; + for(auto & i : events){ + if(i.event.event_string == event){ + if(i.time > normalized_time){ + return (*anim).AbsoluteTimeFromNormalized(i.time - normalized_time) / speed_mult * 0.001f; } } } @@ -207,8 +207,8 @@ void AnimationReader::AttachTo( const AnimationAssetRef &_ref ) { last_rotation = 0.0f; skip_offset = false; callback_string.clear(); - for(int i=0; i<_max_animated_items; ++i){ - animated_item_ids[i] = -1; + for(int & animated_item_id : animated_item_ids){ + animated_item_id = -1; } const AnimationAsset &anim = (*_ref); int anim_id = 0; @@ -280,8 +280,8 @@ AnimationReader::AnimationReader(): mirrored(false), speed_mult(1.0f) { - for(int i=0; i<_max_animated_items; ++i){ - animated_item_ids[i] = -1; + for(int & animated_item_id : animated_item_ids){ + animated_item_id = -1; } } @@ -348,9 +348,9 @@ void AnimationReader::GetPrevEvents( const BlendMap &blendmap, float timestep ) float AnimationReader::GetAnimationEventTime( const std::string & event_name, const BlendMap &blend_map ) const { - for(unsigned i=0; i normalized_time && events[i].event.event_string == event_name){ - float time = events[i].time - normalized_time; + for(const auto & event : events){ + if(event.time > normalized_time && event.event.event_string == event_name){ + float time = event.time - normalized_time; const AnimationAsset &anim_asset = (*anim); time /= anim_asset.GetFrequency(blend_map); return time; diff --git a/Source/Graphics/bloodsurface.cpp b/Source/Graphics/bloodsurface.cpp index 0f855201..43b68215 100644 --- a/Source/Graphics/bloodsurface.cpp +++ b/Source/Graphics/bloodsurface.cpp @@ -310,8 +310,8 @@ void BloodSurface::Update(SceneGraph *scenegraph, float timestep, bool force_upd } PROFILER_ENTER(g_profiler_ctx, "Fill blood_points in Update texture"); - for(std::vector::iterator iter = trace[i].begin(); iter != trace[i].end(); ++iter) { - const int face_index = (*iter).tri*3; + for(auto & iter : trace[i]) { + const int face_index = iter.tri*3; vec2 tex_coords[3]; for(int i=0; i<3; ++i){ int index = model->faces[face_index+i]*2; @@ -320,12 +320,12 @@ void BloodSurface::Update(SceneGraph *scenegraph, float timestep, bool force_upd } } - const vec3 &start = (*iter).start; + const vec3 &start = iter.start; vec2 start_uv = tex_coords[0] * start[0] + tex_coords[1] * start[1] + tex_coords[2] * start[2]; - const vec3 &end = (*iter).end; + const vec3 &end = iter.end; vec2 end_uv = tex_coords[0] * end[0] + tex_coords[1] * end[1] + tex_coords[2] * end[2]; @@ -341,17 +341,15 @@ void BloodSurface::Update(SceneGraph *scenegraph, float timestep, bool force_upd } if(i==0){ blood_points.reserve(blood_points.size()+cut_lines.size()*40); - for(std::vector::iterator iter = cut_lines.begin(); - iter != cut_lines.end(); - ++iter) + for(auto & cut_line : cut_lines) { for(unsigned i=0; i<10; ++i){ vec2 test_offset(RangedRandomFloat(-ts,ts), RangedRandomFloat(-ts,ts)); - blood_points.push_back(iter->start[0]+test_offset[0]); - blood_points.push_back(iter->start[1]+test_offset[1]); - blood_points.push_back(iter->end[0]+test_offset[0]); - blood_points.push_back(iter->end[1]+test_offset[1]); + blood_points.push_back(cut_line.start[0]+test_offset[0]); + blood_points.push_back(cut_line.start[1]+test_offset[1]); + blood_points.push_back(cut_line.end[0]+test_offset[0]); + blood_points.push_back(cut_line.end[1]+test_offset[1]); } } cut_lines.clear(); diff --git a/Source/Graphics/camera.cpp b/Source/Graphics/camera.cpp index 4489f482..4817cade 100644 --- a/Source/Graphics/camera.cpp +++ b/Source/Graphics/camera.cpp @@ -643,12 +643,12 @@ void Camera::calcFrustumPlanes( const mat4 &_p, const mat4 &_mv ) { //Check if a sphere is visible int Camera::checkSphereInFrustum( vec3 where, float radius ) const { int sphere_in_frustum = 2; - for (int i = 0; i < 6; ++i ) { + for (auto frustumPlane : frustumPlanes) { float d = - frustumPlanes[i][0] * where.x() + - frustumPlanes[i][1] * where.y() + - frustumPlanes[i][2] * where.z() + - frustumPlanes[i][3]; + frustumPlane[0] * where.x() + + frustumPlane[1] * where.y() + + frustumPlane[2] * where.z() + + frustumPlane[3]; if( d <= -radius ) { return 0; // Sphere is entirely outside one of the frustum planes } else if(d < radius){ @@ -704,13 +704,13 @@ void Camera::checkSpheresInFrustum(int count, float* where_x, float* where_y, fl __m128 is_in_view_distance = _mm_cmplt_ps(distance_squared, cull_distance_squared4); inside = _mm_and_ps(inside, is_in_view_distance); - for (unsigned p = 0; p < 6; ++p) { - const __m128& plane_n_x4 = simdFrustumPlanes[p].normal_x; - const __m128& plane_n_y4 = simdFrustumPlanes[p].normal_y; - const __m128& plane_n_z4 = simdFrustumPlanes[p].normal_z; + for (const auto & simdFrustumPlane : simdFrustumPlanes) { + const __m128& plane_n_x4 = simdFrustumPlane.normal_x; + const __m128& plane_n_y4 = simdFrustumPlane.normal_y; + const __m128& plane_n_z4 = simdFrustumPlane.normal_z; __m128 n_dot_pos = simd_dot_product(where_x4, where_y4, where_z4, plane_n_x4, plane_n_y4, plane_n_z4); - __m128 plane_test = _mm_cmpgt_ps(_mm_add_ps(n_dot_pos, simdFrustumPlanes[p].d), neg_radius4); + __m128 plane_test = _mm_cmpgt_ps(_mm_add_ps(n_dot_pos, simdFrustumPlane.d), neg_radius4); inside = _mm_and_ps(inside, plane_test); } @@ -731,12 +731,12 @@ void Camera::checkSpheresInFrustum(int count, float* where_x, float* where_y, fl center_to_cam[2] * center_to_cam[2]; if (distance_squared < cull_distance_squared) { - for (int p = 0; p < 6; ++p) { + for (auto frustumPlane : frustumPlanes) { float n_dot_pos = - frustumPlanes[p][0] * where_x[i] + - frustumPlanes[p][1] * where_y[i] + - frustumPlanes[p][2] * where_z[i]; - bool plane_test = n_dot_pos + frustumPlanes[p][3] > -radius; + frustumPlane[0] * where_x[i] + + frustumPlane[1] * where_y[i] + + frustumPlane[2] * where_z[i]; + bool plane_test = n_dot_pos + frustumPlane[3] > -radius; inside = inside && plane_test; } } else { @@ -754,7 +754,7 @@ int Camera::checkBoxInFrustum(vec3 start, vec3 end) const int total_in = 0; vec3 point; - for(int p = 0; p < 6; ++p) { + for(auto frustumPlane : frustumPlanes) { int in_count = 8; bool box_in_frustum = 1; @@ -768,10 +768,10 @@ int Camera::checkBoxInFrustum(vec3 start, vec3 end) const else point.z()=end.z(); // test this point against the planes - if( frustumPlanes[p][0] * point.x() + - frustumPlanes[p][1] * point.y() + - frustumPlanes[p][2] * point.z() + - frustumPlanes[p][3] < 0) { + if( frustumPlane[0] * point.x() + + frustumPlane[1] * point.y() + + frustumPlane[2] * point.z() + + frustumPlane[3] < 0) { box_in_frustum = 0; in_count--; } diff --git a/Source/Graphics/csg.cpp b/Source/Graphics/csg.cpp index 932d894e..bd758410 100644 --- a/Source/Graphics/csg.cpp +++ b/Source/Graphics/csg.cpp @@ -58,9 +58,9 @@ namespace Test { temp_points[0][1] = a.edge->points[1]; temp_points[1][0] = b.edge->points[0]; temp_points[1][1] = b.edge->points[1]; - for(int i=0; i<2; ++i){ - if(temp_points[i][0] > temp_points[i][1]){ - std::swap(temp_points[i][0], temp_points[i][1]); + for(auto & temp_point : temp_points){ + if(temp_point[0] > temp_point[1]){ + std::swap(temp_point[0], temp_point[1]); } } if(temp_points[0][0] == temp_points[1][0]){ @@ -119,9 +119,9 @@ namespace { points[0][i] = a.points[i]; points[1][i] = b.points[i]; } - for(int i=0; i<2; ++i){ - if(points[i][0] > points[i][1]){ - std::swap(points[i][0], points[i][1]); + for(auto & point : points){ + if(point[0] > point[1]){ + std::swap(point[0], point[1]); } } if(points[0][0] == points[1][0]){ @@ -203,13 +203,13 @@ namespace { struct vec3d { double entries[3]; vec3d(double val){ - for(int i=0; i<3; ++i){ - entries[i] = val; + for(double & entrie : entries){ + entrie = val; } } vec3d(){ - for(int i=0; i<3; ++i){ - entries[i] = 0.0; + for(double & entrie : entries){ + entrie = 0.0; } } double& operator[](int which){ @@ -583,8 +583,8 @@ namespace { } std::sort(vert_sort.begin(), vert_sort.end(), VertSortById); // -- set faces to use merge targets - for(int i=0, len=faces.size(); ivertices.push_back(vec[2]); } shape->faces.reserve(model.faces.size()); - for(int i=0, len=model.faces.size(); ifaces.push_back(model.faces[i]); + for(unsigned int face : model.faces){ + shape->faces.push_back(face); } // Create Bullet collision shape shape->vertices_float.reserve(shape->vertices.size()); @@ -765,10 +765,10 @@ namespace { edge_angle.reserve(on_edge.size()); vec2d mid_point; mid_point = (triangle_points[0].flat_coord + triangle_points[1].flat_coord + triangle_points[2].flat_coord) * (1.0 / 3.0); - for(int j=0, len=on_edge.size(); j labeled_edges[i].points[1]){ - std::swap(labeled_edges[i].points[0], labeled_edges[i].points[1]); + for(auto & labeled_edge : labeled_edges){ + labeled_edge.points[0] = triangle_point_remap[labeled_edge.points[0]]; + labeled_edge.points[1] = triangle_point_remap[labeled_edge.points[1]]; + if(labeled_edge.points[0] > labeled_edge.points[1]){ + std::swap(labeled_edge.points[0], labeled_edge.points[1]); } } // Get points to input to triangulation std::vector points; - for(int i=0, len=triangle_points.size(); isize()/3; - for(int j=0, len=triangle_points.size(); jpush_back(triangle_points[j].coord[k]); - output.new_bary->push_back(triangle_points[j].bary[k]); + output.new_vertices->push_back(triangle_point.coord[k]); + output.new_bary->push_back(triangle_point.bary[k]); output.new_vert_tri_points->push_back(tri_vert_id[k]); } } @@ -937,8 +937,7 @@ namespace { } std::vector triangle_side(faces.size()/3, TrianglePoint::UNKNOWN); // Get outside/inside of edges neighboring edge - for(int i=0, len=labeled_edges.size(); ipush_back(faces[j]+vert_start); + for(unsigned int face : faces){ + output.new_faces->push_back(face+vert_start); } - for(int j=0, len=triangle_side.size(); jpush_back(triangle_side[j]); + for(auto & j : triangle_side){ + output.new_triangle_sides->push_back(j); } old_index = new_index; } @@ -1006,8 +1005,7 @@ namespace { void MergeTriIntersects(std::vector &tri_intersect_info) { std::vector test_points; std::vector test_point_distances; - for(int i=0, len=tri_intersect_info.size(); i &faces, const std::vector &v TriNeighborInfo tri_neighbor_info; GetTriNeighbors(merged_faces, vertices, &tri_neighbor_info, true); bool non_three_neighbor = false; - for(int i=0, len=tri_neighbor_info.num_tri_neighbors.size(); ifaces.reserve(csg_model->faces.size()+result.indices.size()); int old_faces = csg_model->verts.size()/3; if(!flip){ - for(int i=0, len=result.indices.size(); ifaces.push_back(result.indices[i] + old_faces); + for(int indice : result.indices){ + csg_model->faces.push_back(indice + old_faces); } } else { for(int i=0, len=result.indices.size(); i tri_intersect_info; - for(MeshCollisionCallback::TriPairSet::iterator iter = cb.tri_pairs.begin(); iter != cb.tri_pairs.end(); ++iter){ + for(const auto & tri_pair : cb.tri_pairs){ // Get triangle vertices vec3d tri[2][3]; - const MeshCollisionCallback::TriPair &tri_pair = *iter; int tri_index = tri_pair.first*3; for(int j=0; j<3; ++j){ int vert_index = shape[1].faces[tri_index+j]*3; diff --git a/Source/Graphics/detailobjectsurface.cpp b/Source/Graphics/detailobjectsurface.cpp index babe4fd9..4b256ff0 100644 --- a/Source/Graphics/detailobjectsurface.cpp +++ b/Source/Graphics/detailobjectsurface.cpp @@ -73,7 +73,7 @@ void DetailObjectSurface::AttachTo( const Model& model, mat4 transform ) { vec3 verts[3]; int face_index = 0; int vert_index; - for(unsigned i=0; ibounding_sphere_center, - added_batches[i].batch->bounding_sphere_radius)){ - added_batches[i].batch->SetStartState(); + for(auto & added_batche : added_batches){ + if(camera.checkSphereInFrustum(added_batche.batch->bounding_sphere_center, + added_batche.batch->bounding_sphere_radius)){ + added_batche.batch->SetStartState(); //glPushMatrix(); //glMultMatrixf(added_batches[i].batch->transform); - Graphics::Instance()->SetModelMatrix(added_batches[i].batch->transform, added_batches[i].batch->inv_transpose_transform); + Graphics::Instance()->SetModelMatrix(added_batche.batch->transform, added_batche.batch->inv_transpose_transform); - DrawVertexArrayRange(added_batches[i].start_face, - added_batches[i].end_face, - added_batches[i].start_vertex, - added_batches[i].end_vertex); + DrawVertexArrayRange(added_batche.start_face, + added_batche.end_face, + added_batche.start_vertex, + added_batche.end_vertex); //glPopMatrix(); - added_batches[i].batch->SetEndState(); + added_batche.batch->SetEndState(); } } EndVertexArrays(); @@ -212,8 +212,8 @@ void DrawBatch::DrawElements( GLuint size, const GLuint* data ) { face_ptr = NULL; normal_ptr = NULL; vertex_ptr = NULL; - for(int i=0; i<8; i++){ - tex_coord_ptr[i] = NULL; + for(auto & i : tex_coord_ptr){ + i = NULL; } } @@ -223,8 +223,8 @@ void DrawBatch::AddBatch( const DrawBatch &other ) { } if(other.added_batches.size()){ - for(unsigned i=0; iDispose(); vbo_vertices->Dispose(); vbo_normals->Dispose(); - for(int i=0; i<8; i++){ - vbo_tex_coords[i]->Dispose(); + for(auto & vbo_tex_coord : vbo_tex_coords){ + vbo_tex_coord->Dispose(); } draw_times = 0; @@ -348,8 +348,8 @@ void DrawBatch::SetStartState() const { shaders->setProgram(shader_id); - for(unsigned i=0; iold_position = flare->position; flare->slow_visible = mix(flare->visible,flare->slow_visible,_slow_visible_inertia); if(flare->visible == 0.0f && flare->slow_visible < 0.01f){ @@ -444,9 +443,9 @@ void Flares::DeleteFlare(Flare* flare){ std::vector::iterator flare_iter = std::find(flares.begin(), flares.end(), flare); if(flare_iter != flares.end()){ Flare* flare = (*flare_iter); - for(unsigned i=0; iquery.size(); ++i){ - if(flare->query[i].created){ - glDeleteQueries(1,&flare->query[i].id); + for(auto & i : flare->query){ + if(i.created){ + glDeleteQueries(1,&i.id); } } delete flare; @@ -463,9 +462,9 @@ void Flares::CleanupFlares() { for(;it != flares.end(); ++it) { Flare* flare = (*it); - for(unsigned i=0; iquery.size(); ++i){ - if(flare->query[i].created){ - glDeleteQueries(1,&flare->query[i].id); + for(auto & i : flare->query){ + if(i.created){ + glDeleteQueries(1,&i.id); } } delete (*it); diff --git a/Source/Graphics/font_renderer.cpp b/Source/Graphics/font_renderer.cpp index f6e39015..3067607b 100644 --- a/Source/Graphics/font_renderer.cpp +++ b/Source/Graphics/font_renderer.cpp @@ -104,8 +104,8 @@ struct FontRendererImpl { FontRendererImpl::~FontRendererImpl() { - for (FontMap::iterator it = faces_.begin(); it != faces_.end(); ++it) { - FontFace &face = it->second; + for (auto & it : faces_) { + FontFace &face = it.second; FT_Done_Face(face.face); face.face = NULL; } diff --git a/Source/Graphics/halfedge.cpp b/Source/Graphics/halfedge.cpp index d5ded797..d7628b9d 100644 --- a/Source/Graphics/halfedge.cpp +++ b/Source/Graphics/halfedge.cpp @@ -125,12 +125,10 @@ void CollapseParentRecord(ParentRecordList &a, ParentRecordList &b, float weight if(&a == &b){ return; } - for(ParentRecordList::iterator iter = a.begin(); iter != a.end(); ++iter){ - ParentRecord &pr = *iter; + for(auto & pr : a){ pr.weight *= (1.0f - weight); } - for(ParentRecordList::iterator iter = b.begin(); iter != b.end(); ++iter){ - ParentRecord &pr = *iter; + for(auto & pr : b){ pr.weight *= weight; } a.splice(a.end(), b); @@ -146,8 +144,7 @@ void CollapseEdge(HalfEdgeNodeHeap &heap, HalfEdge *edge, std::vector& ve CollapseParentRecord(vert_parents[edge->vert[0]], vert_parents[edge->vert[1]], edge->pos); CollapseVertPositions(vertices, edge->vert, edge->pos); HalfEdgeSet vert_edge_set = vert_edges[edge->vert[1]]; - for(HalfEdgeSet::iterator iter = vert_edge_set.begin(); iter != vert_edge_set.end(); ++iter){ - HalfEdge* change_edge = *iter; + for(auto change_edge : vert_edge_set){ if(change_edge == edge || !change_edge->valid){ continue; } @@ -164,8 +161,7 @@ void CollapseEdge(HalfEdgeNodeHeap &heap, HalfEdge *edge, std::vector& ve CollapseParentRecord(tex_parents[edge->tex[0]], tex_parents[edge->tex[1]], edge->pos); CollapseTexPositions(tex_coords, edge->tex, edge->pos); HalfEdgeSet tex_edge_set = tex_edges[edge->tex[1]]; - for(HalfEdgeSet::iterator iter = tex_edge_set.begin(); iter != tex_edge_set.end(); ++iter){ - HalfEdge* change_edge = *iter; + for(auto change_edge : tex_edge_set){ if(change_edge == edge || !change_edge->valid){ continue; } @@ -185,8 +181,7 @@ void CollapseEdge(HalfEdgeNodeHeap &heap, HalfEdge *edge, std::vector& ve CollapseTexPositions(tex_coords, rev_tex, edge->pos); CollapseParentRecord(tex_parents[rev_tex[0]], tex_parents[rev_tex[1]], edge->pos); HalfEdgeSet tex_edge_set = tex_edges[rev_tex[1]]; - for(HalfEdgeSet::iterator iter = tex_edge_set.begin(); iter != tex_edge_set.end(); ++iter){ - HalfEdge* change_edge = *iter; + for(auto change_edge : tex_edge_set){ if(change_edge == edge || !change_edge->valid){ continue; } @@ -208,8 +203,7 @@ void CollapseEdge(HalfEdgeNodeHeap &heap, HalfEdge *edge, std::vector& ve CollapseHalfEdge(heap, edge->twin); } // Recalc err and update heap - for(std::set::iterator iter = affected_edges.begin(); iter != affected_edges.end(); ++iter){ - HalfEdge* affected_edge = *iter; + for(auto affected_edge : affected_edges){ if(!affected_edge->valid){ continue; } diff --git a/Source/Graphics/hudimage.cpp b/Source/Graphics/hudimage.cpp index c3518849..a4233367 100644 --- a/Source/Graphics/hudimage.cpp +++ b/Source/Graphics/hudimage.cpp @@ -94,10 +94,9 @@ void HUDImages::Draw() { { PROFILER_ZONE(g_profiler_ctx, "HUDImages draw loop"); - for(unsigned i=0; i &cluster_center, node.cluster_info.closest_clusters.clear(); if(candidates.size() == 1){ node.cluster_info.closest_clusters.push_back(candidates[0]); - for(unsigned i=0; i<2; ++i){ - if(node.child[i]){ - GetClosestClusters(*node.child[i], + for(auto & i : node.child){ + if(i){ + GetClosestClusters(*i, cluster_center, node.cluster_info.closest_clusters); } @@ -103,9 +103,9 @@ void GetClosestClusters( KDNode &node, const std::vector &cluster_center, node.cluster_info.closest_clusters.push_back(candidates[i]); }*/ } - for(unsigned i=0; i<2; ++i){ - if(node.child[i]){ - GetClosestClusters(*node.child[i], + for(auto & i : node.child){ + if(i){ + GetClosestClusters(*i, cluster_center, node.cluster_info.closest_clusters); } @@ -253,8 +253,8 @@ KDNode::KDNode( const vec3 &_min_bounds, const vec3 &_max_bounds, std::vector_rand_pick_threshold){ std::vector median_points(_rand_pick_threshold); - for(unsigned i=0; i child_points; - for(unsigned i=0; icontent_bounds[0] = median_point; child[0]->content_bounds[1] = median_point; - for(unsigned i=0; icontent_bounds[0][j]){ - child[0]->content_bounds[0][j] = child_points[i][j]; + if(child_point[j] < child[0]->content_bounds[0][j]){ + child[0]->content_bounds[0][j] = child_point[j]; } - if(child_points[i][j] > child[0]->content_bounds[1][j]){ - child[0]->content_bounds[1][j] = child_points[i][j]; + if(child_point[j] > child[0]->content_bounds[1][j]){ + child[0]->content_bounds[1][j] = child_point[j]; } } } @@ -332,22 +332,22 @@ KDNode::KDNode( const vec3 &_min_bounds, const vec3 &_max_bounds, std::vector plane_coord){ - child_points.push_back(points[i]); + for(auto & point : points){ + if(point.entries[axis] > plane_coord){ + child_points.push_back(point); } } child[1] = new KDNode(child_min, child_max, child_points, depth+1); child[1]->content_bounds[0] = child_points[0]; child[1]->content_bounds[1] = child_points[0]; - for(unsigned i=0; icontent_bounds[0][j]){ - child[1]->content_bounds[0][j] = child_points[i][j]; + if(child_point[j] < child[1]->content_bounds[0][j]){ + child[1]->content_bounds[0][j] = child_point[j]; } - if(child_points[i][j] > child[1]->content_bounds[1][j]){ - child[1]->content_bounds[1][j] = child_points[i][j]; + if(child_point[j] > child[1]->content_bounds[1][j]){ + child[1]->content_bounds[1][j] = child_point[j]; } } } diff --git a/Source/Graphics/lightprobecollection.cpp b/Source/Graphics/lightprobecollection.cpp index 78906493..8280a03c 100644 --- a/Source/Graphics/lightprobecollection.cpp +++ b/Source/Graphics/lightprobecollection.cpp @@ -183,9 +183,9 @@ LightProbe* LightProbeCollection::GetNextProbeToProcess() { } LightProbe* LightProbeCollection::GetProbeFromID(int id) { - for(int i=0, len=light_probes.size(); i 255)?255:val; ++index; } @@ -624,8 +624,8 @@ void LightProbeCollection::UpdateTextureBuffer(BulletWorld& bw) { } } } - for(int avg_index=0; avg_index<18; ++avg_index){ - avg_col[avg_index] /= num_positive; + for(int & avg_index : avg_col){ + avg_index /= num_positive; } // Assign average color to negative probes in this tet for(int point=0; point<4; ++point){ @@ -720,8 +720,8 @@ void LightProbeCollection::UpdateTextureBuffer(BulletWorld& bw) { buf_u[buf_index++] = neighbors_u[2]; buf_u[buf_index++] = neighbors_u[3]; - for(int i=0; i<18; ++i){ - buf_u[buf_index++] = colors_u[i]; + for(unsigned int i : colors_u){ + buf_u[buf_index++] = i; } buf_u[buf_index++] = 0; buf_u[buf_index++] = 0; @@ -934,15 +934,15 @@ void LightProbeCollection::Draw(BulletWorld& bw) { CHECK_GL_ERROR(); // Check long name if short name is not found - for(int i=0; i<5; ++i){ - if(indices[i] == GL_INVALID_INDEX){ + for(unsigned int indice : indices){ + if(indice == GL_INVALID_INDEX){ glGetUniformIndices(programHandle, 5, &names[5], indices); break; } } - for(int i=0; i<5; ++i){ - if(indices[i] == GL_INVALID_INDEX){ + for(unsigned int indice : indices){ + if(indice == GL_INVALID_INDEX){ return; } } diff --git a/Source/Graphics/model.cpp b/Source/Graphics/model.cpp index 1dbcfeaf..be0f3a71 100644 --- a/Source/Graphics/model.cpp +++ b/Source/Graphics/model.cpp @@ -858,9 +858,9 @@ void CopyTexCoords2( Model &a, const Model& b ) { [floorf(n_i[2]*100.0f)]; normal_index += 3; vert_index += 3; - for(unsigned j=0; j fifo(32, -1); unsigned index = 0; - for(unsigned i=0; i order(vertices.size()/3, -1); unsigned index = 0; - for(unsigned i=0; i &vertices, const std: std::vector tris(faces.size()/3); int index = 0; - for(int i=0, len=tris.size(); i tris[i].edges[j].points[1]){ - std::swap(tris[i].edges[j].points[0], tris[i].edges[j].points[1]); - tris[i].edge_swapped[j] = true; + if(tri.edges[j].points[0] > tri.edges[j].points[1]){ + std::swap(tri.edges[j].points[0], tri.edges[j].points[1]); + tri.edge_swapped[j] = true; } else { - tris[i].edge_swapped[j] = false; + tri.edge_swapped[j] = false; } } index += 3; @@ -133,12 +133,10 @@ void ModelSurfaceWalker::AttachTo(const std::vector &vertices, const std: // Use the list of triangles for each edge to get a list of neighbors for // each triangle tri_info.resize(tris.size()); - for(std::map >::iterator iter = edge_tris.begin(); - iter != edge_tris.end(); - ++iter) + for(auto & edge_tri : edge_tris) { - const Edge& edge = iter->first; - const std::vector &faces = iter->second; + const Edge& edge = edge_tri.first; + const std::vector &faces = edge_tri.second; if(faces.size() == 2){ for(unsigned i=0; i<2; ++i){ const int &face = faces[i]; @@ -158,16 +156,16 @@ void ModelSurfaceWalker::AttachTo(const std::vector &vertices, const std: // Get the length of each edge of each triangle vec3 points[3]; int face_index = 0; - for(unsigned i=0; i &data ) void WritePaletteToXML( const OGPalette & palette, TiXmlElement* palette_el ) { - for(unsigned i=0; iLinkEndChild(color_el); - const std::string &label = palette[i].label; - const vec3 &color = palette[i].color; - const char& channel = palette[i].channel; + const std::string &label = i.label; + const vec3 &color = i.color; + const char& channel = i.channel; color_el->SetAttribute("label", label.c_str()); color_el->SetAttribute("channel", channel); color_el->SetDoubleAttribute("red", color[0]); diff --git a/Source/Graphics/particles.cpp b/Source/Graphics/particles.cpp index dd4f166c..ee200498 100644 --- a/Source/Graphics/particles.cpp +++ b/Source/Graphics/particles.cpp @@ -197,8 +197,7 @@ void DrawGPUParticleField(SceneGraph *scenegraph, const char* type) { std::vector light_volume_matrix; std::vector light_volume_matrix_inverse; - for(int i=0, len=scenegraph->light_volume_objects_.size(); ilight_volume_objects_[i]; + for(auto obj : scenegraph->light_volume_objects_){ const mat4 &mat = obj->GetTransform(); light_volume_matrix.push_back(mat); light_volume_matrix_inverse.push_back(invert(mat)); @@ -243,8 +242,8 @@ void DrawGPUParticleField(SceneGraph *scenegraph, const char* type) { static GLfloat data_vec[20*1000]; int val=0; for(int i=0; i<1000; ++i){ - for(int j=0; j<20; ++j){ - data_vec[val++] = data[j]; + for(float j : data){ + data_vec[val++] = j; } } data_vbo.Fill(kVBOStatic | kVBOFloat,sizeof(data_vec), (void*)data_vec); @@ -256,8 +255,8 @@ void DrawGPUParticleField(SceneGraph *scenegraph, const char* type) { int val = 0; int val2 = 0; for(int i=0; i<1000; ++i){ - for(int j=0; j<6; ++j){ - index_vec[val2++]=index[j]+val; + for(unsigned int j : index){ + index_vec[val2++]=j+val; } val += 4; } @@ -379,8 +378,7 @@ void Particle::Draw(SceneGraph *scenegraph, DrawType draw_type, const mat4& proj std::vector light_volume_matrix; std::vector light_volume_matrix_inverse; - for(int i=0, len=scenegraph->objects_.size(); iobjects_[i]; + for(auto obj : scenegraph->objects_){ const mat4 &mat = obj->GetTransform(); light_volume_matrix.push_back(mat); light_volume_matrix_inverse.push_back(invert(mat)); @@ -538,11 +536,11 @@ void Particle::Draw(SceneGraph *scenegraph, DrawType draw_type, const mat4& proj graphics->ResetVertexAttribArrays(); CHECK_GL_ERROR(); } - for(ParticleList::iterator iter = connected.begin(); iter != connected.end(); ++iter) { - if(this < (*iter)) { + for(auto & iter : connected) { + if(this < iter) { float thickness = interp_size; vec3 a = interp_position; - vec3 b = (*iter)->interp_position; + vec3 b = iter->interp_position; vec3 up,right,cam_to_particle; vec3 vertices[4]; @@ -871,8 +869,8 @@ void ParticleSystem::Draw(SceneGraph *scenegraph) { PROFILER_ENTER(g_profiler_ctx, "Interpolate particles"); float interp = game_timer.GetInterpWeight(); - for (unsigned i=0, len=particles.size(); iGetPos(); - for (unsigned i=0;icam_dist=distance_squared(particles[i]->interp_position, cam_pos); + for (auto & particle : particles){ + particle->cam_dist=distance_squared(particle->interp_position, cam_pos); } PROFILER_ENTER(g_profiler_ctx, "Sort particles"); std::sort(particles.begin(), particles.end(), CParticleCompare); @@ -945,9 +943,8 @@ void ParticleSystem::Draw(SceneGraph *scenegraph) { } else { std::vector light_volume_matrix; std::vector light_volume_matrix_inverse; - for(int i=0, len=scenegraph->light_volume_objects_.size(); ilight_volume_objects_[i]; - const mat4 &mat = obj->GetTransform(); + for(auto obj : scenegraph->light_volume_objects_){ + const mat4 &mat = obj->GetTransform(); light_volume_matrix.push_back(mat); light_volume_matrix_inverse.push_back(invert(mat)); } @@ -1309,8 +1306,8 @@ unsigned ParticleSystem::MakeParticle( SceneGraph *scenegraph, const std::string //Dispose of particle system void ParticleSystem::Dispose() { - for(ParticleVector::iterator it = particles.begin(); it != particles.end(); ++it){ - delete (*it); + for(auto & particle : particles){ + delete particle; } particles.clear(); } diff --git a/Source/Graphics/shaders.cpp b/Source/Graphics/shaders.cpp index cdf934ec..00309463 100644 --- a/Source/Graphics/shaders.cpp +++ b/Source/Graphics/shaders.cpp @@ -45,20 +45,19 @@ extern bool g_single_pass_shadow_cascade; void Shaders::Dispose() { CHECK_GL_ERROR(); - for(unsigned i=0; i= 0 ) { - glDetachShader(program.gl_program, shaders[program.shader_ids[i]].gl_shader); + for(int shader_id : program.shader_ids){ + if( shader_id >= 0 ) { + glDetachShader(program.gl_program, shaders[shader_id].gl_shader); } } glDeleteProgram(program.gl_program); } } - for(unsigned i=0; iuse_tangent = true; } - if(definitions[i] == "ALPHA"){ + if(definition == "ALPHA"){ shader->transparent = true; } - if(definitions[i] == "DEPTH_ONLY") { + if(definition == "DEPTH_ONLY") { shader->depth_only = true; } - if(definitions[i] == "PARTICLE") { + if(definition == "PARTICLE") { shader->particle = true; } - if(definitions[i] == "NO_VELOCITY_BUF") { + if(definition == "NO_VELOCITY_BUF") { no_velocity_buf_defined = true; } } @@ -297,8 +296,8 @@ static void Preprocess(Shader* shader, ShaderType type, const std::vector= 0 && shaders[program.shader_ids[j]].gl_shader == UNLOADED_SHADER_ID){ + for(int shader_id : program.shader_ids){ + if(shader_id >= 0 && shaders[shader_id].gl_shader == UNLOADED_SHADER_ID){ unloaded = true; break; } @@ -386,8 +385,8 @@ void Shaders::Reload(bool force) { int Shaders::returnShader(const char *path, ShaderType type, const std::vector &definitions) { std::string full_path; full_path = path; - for(unsigned i=0; i // Count number of times each vertex is called in vert_indices num_tc.clear(); num_tc.resize(model->vertices.size()/3, 0); - for(int i=0, len=model->vert_indices.size(); ivert_indices[i] != -1){ - ++num_tc[model->vert_indices[i]]; + for(int vert_indice : model->vert_indices){ + if(vert_indice != -1){ + ++num_tc[vert_indice]; } } // Index for fast access @@ -154,8 +154,8 @@ static void GetTexCoordNumPerVertex(const SimplifyModel *model, std::vector index += num_tc[i]; } // Clear num_tc for reuse - for(int i=0, len=num_tc.size(); i tc(model->vert_indices.size()); @@ -338,10 +338,10 @@ static bool GenerateEdgePairs(WOLFIRE_SIMPLIFY::SimplifyModel& processed_model, LOGI << "Validating edge pairs." << std::endl; bool missing_pair = false; bool invalid_pair = false; - for(size_t i=0, len=half_edges.size(); itwin == NULL || half_edges[i].twin->twin != &half_edges[i]){ + } else if(half_edge.twin->twin == NULL || half_edge.twin->twin != &half_edge){ invalid_pair = true; } } @@ -363,8 +363,7 @@ static bool GenerateEdgePairs(WOLFIRE_SIMPLIFY::SimplifyModel& processed_model, static void CalculateEdgeErrors(vector& half_edges, SimplifyModel& processed_model, vector& quadrics_, bool include_tex) { LOGI << "Calculating edge error..." << std::endl; - for(int i=0, len=half_edges.size(); i& half_edges, SimplifyModel& pro static void InitHeap(vector& half_edges, HalfEdgeNodeHeap& heap, HalfEdgeSetVec& vert_edges, HalfEdgeSetVec& tex_edges, bool include_tex) { LOGI << "Adding edges to heap..." << std::endl; - for(int i=0, len=half_edges.size(); ivert[0]].insert(edge); vert_edges[edge->vert[1]].insert(edge); if(include_tex) { @@ -650,15 +649,15 @@ bool WOLFIRE_SIMPLIFY::SimplifySimpleModel(const Model& input, Model* output, in } } - for(int i=0, len=processed_model.vert_indices.size(); i &parents) { - for(Skeleton::SimpleIKBoneMap::const_iterator iter = simple_ik_bones.begin(); iter != simple_ik_bones.end(); ++iter){ - const SimpleIKBone &ik_bone = iter->second; - const char *label = iter->first.c_str(); + for(const auto & simple_ik_bone : simple_ik_bones){ + const SimpleIKBone &ik_bone = simple_ik_bone.second; + const char *label = simple_ik_bone.first.c_str(); int curr_bone = ik_bone.bone_id; for(int i=0; ipoints[i] == joint_bones[1]->points[j]){ - shared_point = joint_bones[0]->points[i]; + for(int point : joint_bones[0]->points){ + for(int j : joint_bones[1]->points) { + if(point == j){ + shared_point = point; } } } @@ -142,32 +142,31 @@ void Skeleton::CreateHinge(const SelectedJoint &selected_joint, const vec3 &forc void Skeleton::SetGravity( bool enable ) { if(enable){ - for(unsigned i=0; iSetGravity(true); + physics_bone.bullet_object->SetGravity(true); //physics_bones[i].bullet_object->SetDamping(0.0f); } } else { - for(unsigned i=0; iSetGravity(true); + physics_bone.bullet_object->SetGravity(true); //physics_bones[i].bullet_object->SetDamping(1.0f); } } } void Skeleton::UnlinkFromBulletWorld() { - for(unsigned i=0; iUnlinkObject(physics_bones[i].bullet_object); + for(auto & physics_bone : physics_bones){ + if(physics_bone.bullet_object){ + bullet_world->UnlinkObject(physics_bone.bullet_object); } } - for(unsigned i=0; iUnlinkConstraint(joint.bt_joint); } @@ -175,8 +174,8 @@ void Skeleton::UnlinkFromBulletWorld() { bullet_world->UnlinkConstraint(joint.fixed_joint); } } - for(unsigned i=0; iUnlinkConstraint(null_constraints[i]); + for(auto & null_constraint : null_constraints){ + bullet_world->UnlinkConstraint(null_constraint); } } @@ -192,8 +191,7 @@ void Skeleton::LinkToBulletWorld() { num = 0; int num2 = 0; int num3 = 0; - for(unsigned i=0; iLinkConstraint(joint.bt_joint); if(joint.type == FIXED_JOINT){ @@ -208,8 +206,8 @@ void Skeleton::LinkToBulletWorld() { } } num = 0; - for(unsigned i=0; iLinkConstraint(null_constraints[i]); + for(auto & null_constraint : null_constraints){ + bullet_world->LinkConstraint(null_constraint); ++num; } } @@ -342,8 +340,7 @@ static void ShapesFromFZX(const FZXAssetRef& fzx_ref, { std::vector &custom_shapes = *custom_shapes_ptr; std::vector &num_custom_shapes = *num_custom_shapes_ptr; - for(int i=0, len=fzx_ref->objects.size(); iobjects[i]; + for(auto & object : fzx_ref->objects){ // Parse label string const std::string &label = object.label; int last_space_index = 0; @@ -634,9 +631,9 @@ void Skeleton::CreatePhysicsSkeleton(float scale, const FZXAssetRef& fzx_ref) { } int Skeleton::GetAttachedBone( BulletObject* object ) { - for(unsigned i=0; iGetPosition() * - physics_bones[i].bullet_object->GetMass(); - total_mass += physics_bones[i].bullet_object->GetMass(); + center += physics_bone.bullet_object->GetPosition() * + physics_bone.bullet_object->GetMass(); + total_mass += physics_bone.bullet_object->GetMass(); } center /= total_mass; return center; @@ -948,10 +941,10 @@ void Skeleton::CreateBallJoint(const SelectedJoint &selected_joint) { Bone* joint_bones[2]; joint_bones[0] = &bones[selected_joint.bones[0]]; joint_bones[1] = &bones[selected_joint.bones[1]]; - for(int i=0; i<2; i++){ - for(int j=0; j<2; j++) { - if(joint_bones[0]->points[i] == joint_bones[1]->points[j]){ - shared_point = joint_bones[0]->points[i]; + for(int point : joint_bones[0]->points){ + for(int j : joint_bones[1]->points) { + if(point == j){ + shared_point = point; } } } @@ -998,10 +991,10 @@ void Skeleton::CreateRotationalConstraint(const SelectedJoint &selected_joint) { Bone* joint_bones[2]; joint_bones[0] = &bones[selected_joint.bones[0]]; joint_bones[1] = &bones[selected_joint.bones[1]]; - for(int i=0; i<2; i++){ - for(int j=0; j<2; j++) { - if(joint_bones[0]->points[i] == joint_bones[1]->points[j]){ - shared_point = joint_bones[0]->points[i]; + for(int point : joint_bones[0]->points){ + for(int j : joint_bones[1]->points) { + if(point == j){ + shared_point = point; } } } @@ -1096,8 +1089,7 @@ void Skeleton::DeleteJoint(PhysicsJoint *joint){ } void Skeleton::RefreshFixedJoints(const std::vector &mats){ - for(unsigned i=0; icom_offset; @@ -1112,14 +1104,13 @@ void Skeleton::RefreshFixedJoints(const std::vector &mats){ void Skeleton::PhysicsDispose() { // Remove child shapes - for (unsigned i = 0; i < child_shapes.size(); i++) { - delete child_shapes[i]; + for (auto & child_shape : child_shapes) { + delete child_shape; } child_shapes.clear(); // Remove joints - for(unsigned i=0; iRemoveJoint(&joint.bt_joint); } @@ -1130,15 +1121,15 @@ void Skeleton::PhysicsDispose() { physics_joints.clear(); // Remove null constraints - for(unsigned i=0; iRemoveJoint(&null_constraints[i]); + for(auto & null_constraint : null_constraints){ + bullet_world->RemoveJoint(&null_constraint); } null_constraints.clear(); // Remove objects - for(unsigned i=0; iRemoveObject(&physics_bones[i].bullet_object); - col_bullet_world->RemoveObject(&physics_bones[i].col_bullet_object); + for(auto & physics_bone : physics_bones){ + bullet_world->RemoveObject(&physics_bone.bullet_object); + col_bullet_world->RemoveObject(&physics_bone.col_bullet_object); } physics_bones.clear(); @@ -1168,12 +1159,12 @@ void Skeleton::GetPhysicsObjectsFromSelectedJoint( std::vector &selected_bullet_bones, const SelectedJoint & selected_joint ) { - for(unsigned i=0; i > connected; - for(unsigned i=0; iCheckForNAN(); + for(auto & physics_bone : physics_bones){ + if(physics_bone.bullet_object){ + physics_bone.bullet_object->CheckForNAN(); } } } @@ -1466,8 +1456,8 @@ void Skeleton::AlternateHull( const std::string &model_name, const vec3 &old_cen for(unsigned i=0; i &group = groups[i]; vec3 center_accum(0.0f); - for(unsigned j=0; j::iterator iter = detail_object_surfaces.begin(); - iter != detail_object_surfaces.end(); ++iter) + for(auto & detail_object_surface : detail_object_surfaces) { - delete (*iter); + delete detail_object_surface; } detail_object_surfaces.clear(); detail_maps_info.clear(); @@ -204,10 +203,9 @@ void Terrain::GLInit(Sky* sky) { sky->BakeSecondPass(&baked_texture_ref); heightmap_.LoadData(heightmap_.path(), HeightmapImage::DOWNSAMPLED); - for(std::list::iterator iter = detail_object_surfaces.begin(); - iter != detail_object_surfaces.end(); ++iter) + for(auto & detail_object_surface : detail_object_surfaces) { - (*iter)->SetBaseTextures(color_texture_ref, normal_map_ref); + detail_object_surface->SetBaseTextures(color_texture_ref, normal_map_ref); } CHECK_GL_ERROR(); } @@ -383,16 +381,16 @@ void RemoveDoubledTriangles(Model *model) { } // Mark triangles with normals facing down as bad - for(unsigned i=0; iface_normals[possible_bad_faces[i]][1]<0){ - bad_faces.push_back(possible_bad_faces[i]); + for(int & possible_bad_face : possible_bad_faces){ + if(model->face_normals[possible_bad_face][1]<0){ + bad_faces.push_back(possible_bad_face); } } - for(unsigned i=0; ifaces[bad_faces[i]*3+0] = 0; - model->faces[bad_faces[i]*3+1] = 0; - model->faces[bad_faces[i]*3+2] = 0; + for(int bad_face : bad_faces){ + model->faces[bad_face*3+0] = 0; + model->faces[bad_face*3+1] = 0; + model->faces[bad_face*3+2] = 0; } } @@ -478,8 +476,8 @@ void Terrain::CalculateSimplifiedTerrain() { Model temp; temp.SimpleLoadTriangleCutObj(abs_uv2_path); CopyTexCoords2(terrain_simplified_model, temp); - for(unsigned i=0; iGetModel(model_id); terrain_simplified_model.LoadObj(model_override, 0); - for(unsigned i=0; i &_deta detail_object_surfaces.resize(detail_object_layers.size()); int counter = 0; Model &terrain_simplified_model = Models::Instance()->GetModel(model_id); - for(std::list::iterator iter = detail_object_surfaces.begin(); - iter != detail_object_surfaces.end(); ++iter) + for(auto & detail_object_surface : detail_object_surfaces) { static const mat4 identity; - *iter = new DetailObjectSurface(); - DetailObjectSurface& dos = *(*iter); + detail_object_surface = new DetailObjectSurface(); + DetailObjectSurface& dos = *detail_object_surface; dos.AttachTo(terrain_simplified_model, identity); dos.GetTrisInPatches(identity); dos.LoadDetailModel(detail_object_layers[counter].obj_path); @@ -1029,10 +1026,9 @@ void Terrain::SetDetailObjectLayers( const std::vector &_deta ++counter; } if(normal_map_ref.valid()){ - for(std::list::iterator iter = detail_object_surfaces.begin(); - iter != detail_object_surfaces.end(); ++iter) + for(auto & detail_object_surface : detail_object_surfaces) { - (*iter)->SetBaseTextures(color_texture_ref, normal_map_ref); + detail_object_surface->SetBaseTextures(color_texture_ref, normal_map_ref); } } } diff --git a/Source/Graphics/text.cpp b/Source/Graphics/text.cpp index ac743fae..748aeb33 100644 --- a/Source/Graphics/text.cpp +++ b/Source/Graphics/text.cpp @@ -158,8 +158,8 @@ void TextCanvas::GetBGRA( MemoryBlock *mem_to_fill ) { } void TextCanvas::Clear() { - for(unsigned i=0, len=pixels_.size(); i::iterator it = deferred_delete_textures.begin(); it != deferred_delete_textures.end(); it++) { - GLuint tex_id = *it; + for (unsigned int tex_id : deferred_delete_textures) { LOGI << "Deferred delete of texture " << tex_id << std::endl; glDeleteTextures(1, &tex_id); } @@ -853,8 +852,8 @@ void Textures::TextureToVRAM(unsigned int which) { if(tex.gl_texture_id != UNLOADED_ID)return; - for( unsigned i = 0; i < tex.sub_textures.size(); i++ ) { - tex.sub_textures[i].texture_data->EnsureInRAM(); + for(auto & sub_texture : tex.sub_textures) { + sub_texture.texture_data->EnsureInRAM(); } bool is_array = (tex.sub_textures.size() > 1); @@ -2670,8 +2669,8 @@ bool Textures::ReloadAsCompressed(const TextureRef& texref) { CreateParentDirs(newPath.c_str()); - for (unsigned int i = 0; i < texture.sub_textures.size(); i++) { - TextureData *tex_data = texture.sub_textures[i].texture_data; + for (auto & sub_texture : texture.sub_textures) { + TextureData *tex_data = sub_texture.texture_data; LOG_ASSERT(tex_data != NULL); if (!tex_data->HasMipmaps()) { tex_data->GenerateMipmaps(); diff --git a/Source/Images/nv_image.cpp b/Source/Images/nv_image.cpp index bee79992..35e1816e 100644 --- a/Source/Images/nv_image.cpp +++ b/Source/Images/nv_image.cpp @@ -58,8 +58,8 @@ Image::~Image() { // //////////////////////////////////////////////////////////// void Image::freeData() { - for (vector::iterator it = _data.begin(); it != _data.end(); it++) { - delete []*it; + for (auto & it : _data) { + delete []it; } _data.clear(); } diff --git a/Source/Images/texture_data.cpp b/Source/Images/texture_data.cpp index cea80339..e5dfc186 100644 --- a/Source/Images/texture_data.cpp +++ b/Source/Images/texture_data.cpp @@ -230,8 +230,8 @@ bool TextureData::Load(const char *abs_path) { // try to determine color space string src(abs_path); - for (string::size_type i = 0; i < src.size(); i++) { - src[i] = tolower(src[i]); + for (char & i : src) { + i = tolower(i); } if (src.rfind("_c.") != string::npos) { m_colorSpace = TextureData::sRGB; diff --git a/Source/Internal/config.cpp b/Source/Internal/config.cpp index ed651389..1e0006d6 100644 --- a/Source/Internal/config.cpp +++ b/Source/Internal/config.cpp @@ -181,8 +181,8 @@ std::vector Config::GetPossibleResolutions() { if ((mode.h <= desktopDisplayMode.h && mode.w <= desktopDisplayMode.w && std::fabs(resolutionAspect - desktopAspect) < 0.01f) || static_cast(config["fullscreen"].toNumber()) == FullscreenMode::kFullscreen) { bool resolutionFound = false; - for (size_t i = 0; i < commonResolutions.size(); ++i) { - if (commonResolutions[i].w == mode.w && commonResolutions[i].h == mode.h) { + for (auto & commonResolution : commonResolutions) { + if (commonResolution.w == mode.w && commonResolution.h == mode.h) { resolutionFound = true; break; } @@ -312,8 +312,8 @@ void Config::SetSettingsToPreset(std::string preset_name ) return; } Config::Map& map = GetPresets()[index].map_; - for(Config::Map::iterator iter = map.begin(); iter != map.end(); ++iter ){ - config.GetRef(iter->first) = iter->second.data; + for(auto & iter : map){ + config.GetRef(iter.first) = iter.second.data; } } @@ -323,8 +323,8 @@ std::string Config::GetSettingsPreset(){ // Determine if we match any of the global_settings presets for(int i=0; i<4; ++i){ Config::Map& map = GetPresets()[i].map_; - for(Config::Map::iterator iter = map.begin(); iter != map.end(); ++iter ){ - if(config.GetRef(iter->first) != iter->second.data){ + for(auto & iter : map){ + if(config.GetRef(iter.first) != iter.second.data){ preset = i + 1; break; } @@ -512,9 +512,9 @@ bool Config::Save(const std::string& filename) { std::vector > vec(map_.begin(), map_.end()); std::sort(vec.begin(), vec.end(), ConfigValCompare()); - for(unsigned i=0; i mods = ModLoading::Instance().GetAllMods(); - for( unsigned i = 0; i < mods.size(); i++ ) { - if( mods[i]->IsActive() && mods[i]->IsCore() == false) { + for(auto & mod : mods) { + if( mod->IsActive() && mod->IsCore() == false) { if( active_mods == false ) { modlist << "Following mods are active" << std::endl; active_mods = true; @@ -214,7 +214,7 @@ ErrorResponse DisplayError(const char* title, const char* contents, ErrorType ty modlist << ", "; } } - modlist << mods[i]->id; + modlist << mod->id; active_count++; } } diff --git a/Source/Internal/filesystem.cpp b/Source/Internal/filesystem.cpp index 7262efdb..72de7b25 100644 --- a/Source/Internal/filesystem.cpp +++ b/Source/Internal/filesystem.cpp @@ -1112,10 +1112,10 @@ void ClearCache( bool dry_run ) modids = ModLoading::Instance().GetModsSid(); #endif modids.push_back(CoreGameModID); - for( unsigned i = 0; i < modids.size(); i++ ) + for(auto & modid : modids) { stringstream write_data_path; - write_data_path << GetWritePath(modids[i]); + write_data_path << GetWritePath(modid); write_data_path << "Data/"; vector write_dir_files; @@ -1185,16 +1185,12 @@ void ClearCache( bool dry_run ) vector keep_files; vector remove_files; - for( vector::iterator pit = write_dir_files.begin(); - pit != write_dir_files.end(); - pit++ ) + for(auto & write_dir_file : write_dir_files) { bool found = false; - for( vector >::iterator fit = remove_with_ending.begin(); - fit != remove_with_ending.end(); - fit++ ) + for(auto & fit : remove_with_ending) { - if( hasBeginning( *pit, fit->first) && hasEnding( *pit, fit->second ) ) + if( hasBeginning( write_dir_file, fit.first) && hasEnding( write_dir_file, fit.second ) ) { found = true; } @@ -1203,11 +1199,9 @@ void ClearCache( bool dry_run ) if( found ) { /* Second pass with exclusion, if there's one match, regret inclusion, exclusion overrides */ - for( vector >::iterator fit = exclude_with_ending.begin(); - fit != exclude_with_ending.end(); - fit++ ) + for(auto & fit : exclude_with_ending) { - if( hasBeginning( *pit, fit->first) && ( fit->second.empty() || hasEnding( *pit, fit->second ) ) ) + if( hasBeginning( write_dir_file, fit.first) && ( fit.second.empty() || hasEnding( write_dir_file, fit.second ) ) ) { found = false; } @@ -1216,17 +1210,17 @@ void ClearCache( bool dry_run ) if( found ) { - remove_files.push_back( *pit ); + remove_files.push_back( write_dir_file ); } else { - keep_files.push_back( *pit ); + keep_files.push_back( write_dir_file ); } } - for( unsigned int i = 0; i < remove_files.size(); i++ ) + for(auto & remove_file : remove_files) { - string path = write_data_path.str() + remove_files[i]; + string path = write_data_path.str() + remove_file; LOGI << "Removing: " << path << endl; if( dry_run == false ) { @@ -1242,9 +1236,9 @@ void ClearCache( bool dry_run ) { //Create a set with all unique folder paths set folder_paths; - for( unsigned int i = 0; i < remove_files.size(); i++ ) + for(auto & remove_file : remove_files) { - string base = SplitPathFileName( remove_files[i] ).first; + string base = SplitPathFileName( remove_file ).first; while( base.empty() == false ) { @@ -1268,9 +1262,9 @@ void ClearCache( bool dry_run ) sort(empty_folder_paths.begin(), empty_folder_paths.end(), string_sort_by_length_r ); - for( unsigned i = 0; i < empty_folder_paths.size(); i++ ) + for(auto & empty_folder_path : empty_folder_paths) { - string path = write_data_path.str() + empty_folder_paths[i]; + string path = write_data_path.str() + empty_folder_path; LOGI << "Removing Empty Folder:" << path << endl; if( deletefile(path.c_str()) != 0 ) { @@ -1280,9 +1274,9 @@ void ClearCache( bool dry_run ) } } - for( unsigned int i = 0; i < keep_files.size(); i++ ) + for(auto & keep_file : keep_files) { - string path = write_data_path.str() + keep_files[i]; + string path = write_data_path.str() + keep_file; LOGI << "Keeping: " << path << endl; } } diff --git a/Source/Internal/hardware_specs.cpp b/Source/Internal/hardware_specs.cpp index dd4cf554..3b0b3977 100644 --- a/Source/Internal/hardware_specs.cpp +++ b/Source/Internal/hardware_specs.cpp @@ -155,20 +155,20 @@ static std::vector extensions; static void LazyInit() { if(initialized == false) { - for (unsigned int i = 0; i < ARRAYSIZE(GLQUERY_INFOS); ++i) { + for (auto i : GLQUERY_INFOS) { GLint values[2]; - glGetIntegerv(GLQUERY_INFOS[i].m_GLint, values); + glGetIntegerv(i.m_GLint, values); GLenum err = glGetError(); if (err != GL_NONE) { - integer_limits[GLQUERY_INFOS[i].m_name] = -1; - } else if (GLQUERY_INFOS[i].m_numValues == 1) { - integer_limits[GLQUERY_INFOS[i].m_name] = values[0]; + integer_limits[i.m_name] = -1; + } else if (i.m_numValues == 1) { + integer_limits[i.m_name] = values[0]; - if( GLQUERY_INFOS[i].m_GLint == GL_MAX_TEXTURE_SIZE ) { + if( i.m_GLint == GL_MAX_TEXTURE_SIZE ) { max_texture_size = values[0]; } } else { - ivec2_limits[GLQUERY_INFOS[i].m_name] = ivec2(values[0],values[1]); + ivec2_limits[i.m_name] = ivec2(values[0],values[1]); } } @@ -271,8 +271,8 @@ void PrintGPU(std::string &total_string, bool short_output) } total_string += "\n[Available OpenGL extensions]\n"; - for (int i = 0; i < extensions.size(); i++) { - FormatString(temp_string, TEMP_STRING_LENGTH, "%s\n", extensions[i].c_str()); + for (auto & extension : extensions) { + FormatString(temp_string, TEMP_STRING_LENGTH, "%s\n", extension.c_str()); total_string += temp_string; } } diff --git a/Source/Internal/locale.cpp b/Source/Internal/locale.cpp index c7a1d8a9..aeedd919 100644 --- a/Source/Internal/locale.cpp +++ b/Source/Internal/locale.cpp @@ -78,11 +78,11 @@ static CScriptArray* ASGetLocaleShortcodes() { CScriptArray *array = CScriptArray::Create(arrayType, (asUINT)0); array->Reserve(locales.size()); - for(LocaleMap::iterator iter = locales.begin(); iter != locales.end(); ++iter) { + for(auto & locale : locales) { // InsertLast doesn't actually do anything but copy from the pointer, // so a const_cast would be fine, but maybe an update to AS could change // that - std::string str = iter->first; + std::string str = locale.first; array->InsertLast(&str); } @@ -96,11 +96,11 @@ static CScriptArray* ASGetLocaleNames() { CScriptArray *array = CScriptArray::Create(arrayType, (asUINT)0); array->Reserve(locales.size()); - for(LocaleMap::iterator iter = locales.begin(); iter != locales.end(); ++iter) { + for(auto & locale : locales) { // InsertLast doesn't actually do anything but copy from the pointer, // so a const_cast would be fine, but maybe an update to AS could change // that - std::string str = iter->second; + std::string str = locale.second; array->InsertLast(&str); } diff --git a/Source/Internal/modloading.cpp b/Source/Internal/modloading.cpp index f9b2bf29..5975c23c 100644 --- a/Source/Internal/modloading.cpp +++ b/Source/Internal/modloading.cpp @@ -1131,12 +1131,11 @@ void ModInstance::Reload( ) { } //Check if mod has files in root folder we don't like. - for( unsigned i = 0; i < manifest.size(); i++ ) { + for(auto & str : manifest) { bool is_root = true; - std::string &str = manifest[i]; - for( unsigned k = 0; k < str.size(); k++ ) { - if( str[k] == '/' ) { + for(char k : str) { + if( k == '/' ) { is_root = false; } } @@ -1740,11 +1739,11 @@ std::vector ModInstance::GetIDCollisionsWithActiveMods() const { std::vector::iterator modit = ModLoading::Instance().mods.begin(); std::set campaign_ids; - for(size_t i = 0; i < campaigns.size(); i++) { - if(campaign_ids.count(campaigns[i].id) != 0) + for(const auto & campaign : campaigns) { + if(campaign_ids.count(campaign.id) != 0) colliding_sids.push_back(sid); else - campaign_ids.insert(campaigns[i].id); + campaign_ids.insert(campaign.id); } for(; modit != ModLoading::Instance().mods.end(); modit++ ) { @@ -2143,10 +2142,10 @@ std::vector::iterator ModLoading::GetMod( const std::string& path } bool ModLoading::IsCampaignPresent(const std::string& campaign) { - for (uint32_t i = 0; i < mods.size(); i++) { - if (mods[i]->IsActive()) { - for (uint32_t j = 0; j < mods[i]->campaigns.size(); j++) { - if (strmtch(mods[i]->campaigns[j].id, campaign)) { + for (auto & mod : mods) { + if (mod->IsActive()) { + for (uint32_t j = 0; j < mod->campaigns.size(); j++) { + if (strmtch(mod->campaigns[j].id, campaign)) { return true; } } @@ -2156,11 +2155,11 @@ bool ModLoading::IsCampaignPresent(const std::string& campaign) { } bool ModLoading::CampaignHasLevel(const std::string& campaign, const std::string& level_path) { - for (uint32_t i = 0; i < mods.size(); i++) { - if (mods[i]->IsActive()) { - for (uint32_t j = 0; j < mods[i]->campaigns.size(); j++) { - if (strmtch(mods[i]->campaigns[j].id, campaign)) { - for (const auto& level : mods[i]->campaigns[j].levels){ + for (auto & mod : mods) { + if (mod->IsActive()) { + for (uint32_t j = 0; j < mod->campaigns.size(); j++) { + if (strmtch(mod->campaigns[j].id, campaign)) { + for (const auto& level : mod->campaigns[j].levels){ LOGI << "path: " << std::string("Data/Levels/") + level.path.str() << std::endl; LOGI << "Level path: " << level_path << std::endl; if (level.path.str() == level_path) { @@ -2248,11 +2247,11 @@ bool ModLoading::IsActive( std::string id ) { } ModInstance::Campaign ModLoading::GetCampaign(std::string& campaign_id) { - for( uint32_t i = 0; i < mods.size(); i++ ) { - if( mods[i]->IsActive() ) { - for( uint32_t j = 0; j < mods[i]->campaigns.size(); j++) { - if( strmtch( mods[i]->campaigns[j].id, campaign_id ) ) { - return mods[i]->campaigns[j]; + for(auto & mod : mods) { + if( mod->IsActive() ) { + for( uint32_t j = 0; j < mod->campaigns.size(); j++) { + if( strmtch( mod->campaigns[j].id, campaign_id ) ) { + return mod->campaigns[j]; } } } @@ -2261,11 +2260,11 @@ ModInstance::Campaign ModLoading::GetCampaign(std::string& campaign_id) { } ModInstance* ModLoading::GetModInstance(const std::string& campaign_id) { - for (uint32_t i = 0; i < mods.size(); i++) { - if (mods[i]->IsActive()) { - for (uint32_t j = 0; j < mods[i]->campaigns.size(); j++) { - if (strmtch(mods[i]->campaigns[j].id, campaign_id)) { - return mods[i]; + for (auto & mod : mods) { + if (mod->IsActive()) { + for (uint32_t j = 0; j < mod->campaigns.size(); j++) { + if (strmtch(mod->campaigns[j].id, campaign_id)) { + return mod; } } } @@ -2275,11 +2274,11 @@ ModInstance* ModLoading::GetModInstance(const std::string& campaign_id) { std::vector ModLoading::GetCampaigns() { std::vector campaigns; - for( uint32_t i = 0; i < mods.size(); i++ ) { - if( mods[i]->IsActive() ) { - for( uint32_t j = 0; j < mods[i]->campaigns.size(); j++ ) { - if(strlen( mods[i]->campaigns[j].title ) > 0 ) { - campaigns.push_back(mods[i]->campaigns[j]); + for(auto & mod : mods) { + if( mod->IsActive() ) { + for( uint32_t j = 0; j < mod->campaigns.size(); j++ ) { + if(strlen( mod->campaigns[j].title ) > 0 ) { + campaigns.push_back(mod->campaigns[j]); } } } @@ -2290,9 +2289,9 @@ std::vector ModLoading::GetCampaigns() { std::vector ModLoading::GetModsMatchingID(std::string id) { std::vector lmods; - for( uint32_t i = 0; i < mods.size(); i++ ) { - if( strmtch( mods[i]->id, id ) ) { - lmods.push_back(mods[i]); + for(auto & mod : mods) { + if( strmtch( mod->id, id ) ) { + lmods.push_back(mod); } } return lmods; @@ -2300,9 +2299,9 @@ std::vector ModLoading::GetModsMatchingID(std::string id) { std::vector ModLoading::GetSteamModsMatchingID(std::string id) { std::vector lmods; - for( uint32_t i = 0; i < mods.size(); i++ ) { - if( strmtch( mods[i]->id, id ) && mods[i]->modsource == ModSourceSteamworks) { - lmods.push_back(mods[i]); + for(auto & mod : mods) { + if( strmtch( mod->id, id ) && mod->modsource == ModSourceSteamworks) { + lmods.push_back(mod); } } return lmods; @@ -2310,9 +2309,9 @@ std::vector ModLoading::GetSteamModsMatchingID(std::string id) { std::vector ModLoading::GetLocalModsMatchingID(std::string id) { std::vector lmods; - for( uint32_t i = 0; i < mods.size(); i++ ) { - if( strmtch( mods[i]->id, id ) && mods[i]->modsource == ModSourceLocalModFolder) { - lmods.push_back(mods[i]); + for(auto & mod : mods) { + if( strmtch( mod->id, id ) && mod->modsource == ModSourceLocalModFolder) { + lmods.push_back(mod); } } return lmods; @@ -2320,9 +2319,9 @@ std::vector ModLoading::GetLocalModsMatchingID(std::string id) { std::vector ModLoading::GetLocalMods() { std::vector lmods; - for( uint32_t i = 0; i < mods.size(); i++ ) { - if(mods[i]->modsource == ModSourceLocalModFolder) { - lmods.push_back(mods[i]); + for(auto & mod : mods) { + if(mod->modsource == ModSourceLocalModFolder) { + lmods.push_back(mod); } } return lmods; @@ -2330,8 +2329,8 @@ std::vector ModLoading::GetLocalMods() { std::vector ModLoading::GetAllMods() { std::vector lmods; - for( uint32_t i = 0; i < mods.size(); i++ ) { - lmods.push_back(mods[i]); + for(auto & mod : mods) { + lmods.push_back(mod); } return lmods; } @@ -2348,12 +2347,12 @@ void ModLoading::AddMod( const std::string& path ) { std::string ModLoading::WhichCampaignLevelBelongsTo(const std::string & level_path) { - for (uint32_t i = 0; i < mods.size(); i++) { - if (mods[i]->IsActive()) { - for (uint32_t j = 0; j < mods[i]->campaigns.size(); j++) { - for (const auto& level : mods[i]->campaigns[j].levels) { + for (auto & mod : mods) { + if (mod->IsActive()) { + for (uint32_t j = 0; j < mod->campaigns.size(); j++) { + for (const auto& level : mod->campaigns[j].levels) { if (std::string("Data/Levels/") + level.path.str() == level_path) { - return mods[i]->campaigns[j].id.str(); + return mod->campaigns[j].id.str(); } } } @@ -2423,22 +2422,22 @@ void ModLoading::DetectMods() { std::vector verifiedMods; - for( unsigned i = 0; i < newMods.size(); i++ ) { + for(auto & newMod : newMods) { bool already_in_list = false; bool has_mod_xml = false; - if( CheckFileAccess(std::string(newMods[i] + "/mod.xml").c_str() ) ) { + if( CheckFileAccess(std::string(newMod + "/mod.xml").c_str() ) ) { has_mod_xml = true; } if( has_mod_xml ) { - for( unsigned k = 0; k < verifiedMods.size(); k++ ) { - if( AreSame( std::string(newMods[i] + "/mod.xml").c_str(), std::string(verifiedMods[k] + "/mod.xml").c_str() ) ) { + for(auto & verifiedMod : verifiedMods) { + if( AreSame( std::string(newMod + "/mod.xml").c_str(), std::string(verifiedMod + "/mod.xml").c_str() ) ) { already_in_list = true; } } if( already_in_list == false ) { - verifiedMods.push_back(newMods[i]); + verifiedMods.push_back(newMod); } } } @@ -2479,37 +2478,37 @@ void ModLoading::SetMods( std::vector modpaths ) { missingPaths = currentPaths; stillPaths = std::vector(); //Empty as intersection is guaranteed to be zero } else { - for( unsigned k = 0; k < modpaths.size(); k++ ) { + for(auto & modpath : modpaths) { bool found = false; - for( unsigned i = 0; i < currentPaths.size(); i++ ) { - if( modpaths[k] == currentPaths[i] ) { + for(auto & currentPath : currentPaths) { + if( modpath == currentPath ) { found = true; } } if( found == false ) { - newPaths.push_back( modpaths[k] ); + newPaths.push_back( modpath ); } } - for( unsigned i = 0; i < currentPaths.size(); i++ ) { + for(auto & currentPath : currentPaths) { bool found = false; - for( unsigned k = 0; k < modpaths.size(); k++ ) { - if( modpaths[k] == currentPaths[i] ) { + for(auto & modpath : modpaths) { + if( modpath == currentPath ) { found = true; } } if( found == false ) { - missingPaths.push_back( currentPaths[i] ); + missingPaths.push_back( currentPath ); } } - for( unsigned i = 0; i < currentPaths.size(); i++ ) { + for(auto & currentPath : currentPaths) { bool found = false; - for( unsigned k = 0; k < modpaths.size(); k++ ) { - if( modpaths[k] == currentPaths[i] ) { + for(auto & modpath : modpaths) { + if( modpath == currentPath ) { found = true; } } if( found ) { - stillPaths.push_back( currentPaths[i] ); + stillPaths.push_back( currentPath ); } } } @@ -2544,8 +2543,8 @@ const std::vector& ModLoading::GetMods() { const std::vector ModLoading::GetModsSid() { std::vector vals; - for( unsigned i = 0; i < mods.size(); i++ ) { - vals.push_back( mods[i]->GetSid() ); + for(auto & mod : mods) { + vals.push_back( mod->GetSid() ); } return vals; } @@ -2624,10 +2623,8 @@ std::ostream& operator<<(std::ostream& os, const ModInstance::ModDependency &md os << "-Versions-" << std::endl; - for( std::vector::const_iterator sit = md.versions.begin(); - sit != md.versions.end(); - sit++) { - os << *sit << std::endl; + for(const auto & version : md.versions) { + os << version << std::endl; } return os; @@ -2642,34 +2639,26 @@ std::ostream& operator<<(std::ostream& os, const ModInstance &mi ) { os << "Valid:" << mi.GetValidity() << std::endl; os << "-Supported Versions-" << std::endl; - for( std::vector::const_iterator sit = mi.supported_versions.begin(); - sit != mi.supported_versions.end(); - sit++) { - os << *sit << std::endl; + for(const auto & supported_version : mi.supported_versions) { + os << supported_version << std::endl; } os << "-Mod Dependencies-" << std::endl; - for( std::vector::const_iterator mdit = mi.mod_dependencies.begin(); - mdit != mi.mod_dependencies.end(); - mdit++) { - os << *mdit << std::endl; + for(const auto & mod_dependencie : mi.mod_dependencies) { + os << mod_dependencie << std::endl; } os << "-Manifest -" << std::endl; - for( std::vector::const_iterator sit = mi.manifest.begin(); - sit != mi.manifest.end(); - sit++) { - os << *sit << std::endl; + for(const auto & sit : mi.manifest) { + os << sit << std::endl; } os << "-Overloaded Files-" << std::endl; - for( std::vector::const_iterator sit = mi.overload_files.begin(); - sit != mi.overload_files.end(); - sit++) { - os << *sit << std::endl; + for(const auto & overload_file : mi.overload_files) { + os << overload_file << std::endl; } return os; diff --git a/Source/Internal/path_set.cpp b/Source/Internal/path_set.cpp index 9ac3148c..43c7e580 100644 --- a/Source/Internal/path_set.cpp +++ b/Source/Internal/path_set.cpp @@ -28,8 +28,7 @@ void PathSetUtil::GetCachedFiles( PathSet& path_set ) { PathSet new_path_set; - for(PathSet::iterator iter = path_set.begin(); iter != path_set.end(); ++iter){ - const std::string &labeled_path = (*iter); + for(const auto & labeled_path : path_set){ size_t space_pos = labeled_path.find(' '); if(space_pos == std::string::npos){ DisplayError("Error", ("No space found in labeled string: "+labeled_path).c_str()); diff --git a/Source/Internal/timer.cpp b/Source/Internal/timer.cpp index 33fef26d..91848e1c 100644 --- a/Source/Internal/timer.cpp +++ b/Source/Internal/timer.cpp @@ -89,8 +89,8 @@ float Timer::GetRenderTime() { float Timer::GetAverageFrameTime() { float sum = .0f; - for (int i = 0; i < NUM_AVERAGED_FRAMES; i++) { - sum += frame[i]; + for (unsigned long i : frame) { + sum += i; } return sum / (float)NUM_AVERAGED_FRAMES; @@ -185,7 +185,7 @@ Timer::Timer(): last_tick(0), wall_time(0) { - for(int i=0; i &parents){ int GetNumChildren(int parent, const std::vector &parents){ int num_children = 0; - for(unsigned i=0; i &parents){ if(parents[parent] != -1){ ++num_connections; } - for(unsigned i=0; i GetChildrenRecursive( int parent, const std::vector &paren if(parents[i] == parent){ children.push_back(i); std::vector sub_children = GetChildrenRecursive(i, parents); - for(unsigned j=0; j FindTreePath( int a, int b, const std::vector &parents ) queue.pop(); std::vector connections = GetConnections(path.back(), parents); - for(unsigned i=0; iisArray() || !node->isValidIndex(arg.index_)) { // Error: unable to resolve path (array value expected at position... @@ -3718,8 +3711,7 @@ const Value& Path::resolve(const Value& root) const { Value Path::resolve(const Value& root, const Value& defaultValue) const { const Value* node = &root; - for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) { - const PathArgument& arg = *it; + for (const auto & arg : args_) { if (arg.kind_ == PathArgument::kindIndex) { if (!node->isArray() || !node->isValidIndex(arg.index_)) return defaultValue; @@ -3737,8 +3729,7 @@ Value Path::resolve(const Value& root, const Value& defaultValue) const { Value& Path::make(Value& root) const { Value* node = &root; - for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) { - const PathArgument& arg = *it; + for (const auto & arg : args_) { if (arg.kind_ == PathArgument::kindIndex) { if (!node->isArray()) { // Error: node is not an array at position ... diff --git a/Source/JSON/jsonhelper.cpp b/Source/JSON/jsonhelper.cpp index 5385c0da..15685bed 100644 --- a/Source/JSON/jsonhelper.cpp +++ b/Source/JSON/jsonhelper.cpp @@ -55,9 +55,9 @@ void testJSON() { Json::Value::Members members = root.getMemberNames(); - for( Json::Value::Members::iterator itr = members.begin(); itr != members.end(); ++itr ) + for(auto & member : members) { - std::cout << *itr << std::endl; + std::cout << member << std::endl; } diff --git a/Source/Logging/logdata.cpp b/Source/Logging/logdata.cpp index 59c5bd4c..85147c7d 100644 --- a/Source/Logging/logdata.cpp +++ b/Source/Logging/logdata.cpp @@ -109,24 +109,24 @@ void LogSystem::RegisterLogHandler( LogTypeMask types, LogHandler* newHandler ) //Disable if enabled first. enabledLogTypes = 0; - for( int i = 0; i < LOGGER_LIMIT; i++ ) + for(auto & handler : handlers) { - if( handlers[i].handler == newHandler ) + if( handler.handler == newHandler ) { - handlers[i].types = 0U; - handlers[i].handler = NULL; - } else if (handlers[i].handler != NULL) { - enabledLogTypes |= handlers[i].types; + handler.types = 0U; + handler.handler = NULL; + } else if (handler.handler != NULL) { + enabledLogTypes |= handler.types; } } //Then enable. - for( int i = 0; i < LOGGER_LIMIT; i++ ) + for(auto & handler : handlers) { - if( handlers[i].handler == NULL ) + if( handler.handler == NULL ) { - handlers[i].types = types; - handlers[i].handler = newHandler; + handler.types = types; + handler.handler = newHandler; worked = true; break; } @@ -144,14 +144,14 @@ void LogSystem::DeregisterLogHandler( LogHandler* newHandler ) logMutex.lock(); enabledLogTypes = 0; - for( int i = 0; i < LOGGER_LIMIT; i++ ) + for(auto & handler : handlers) { - if( handlers[i].handler == newHandler ) + if( handler.handler == newHandler ) { - handlers[i].types = 0U; - handlers[i].handler = NULL; - } else if (handlers[i].handler != NULL) { - enabledLogTypes |= handlers[i].types; + handler.types = 0U; + handler.handler = NULL; + } else if (handler.handler != NULL) { + enabledLogTypes |= handler.types; } } @@ -160,11 +160,11 @@ void LogSystem::DeregisterLogHandler( LogHandler* newHandler ) void LogSystem::Flush() { - for( int i = 0; i < LOGGER_LIMIT; i++ ) + for(auto & handler : handlers) { - if( handlers[i].handler != NULL) + if( handler.handler != NULL) { - handlers[i].handler->Flush(); + handler.handler->Flush(); } } } @@ -337,12 +337,12 @@ LogSystem::LogData::~LogData() string msg = ss.str(); - for( int i = 0; i < LOGGER_LIMIT; i++ ) + for(auto & handler : handlers) { - if( handlers[i].handler != NULL && - (m_type & handlers[i].types) ) + if( handler.handler != NULL && + (m_type & handler.types) ) { - handlers[i].handler->Log( m_type, m_line, m_filename, m_prefix, msg.c_str(), m_message ); + handler.handler->Log( m_type, m_line, m_filename, m_prefix, msg.c_str(), m_message ); } } diff --git a/Source/Main/altmain.cpp b/Source/Main/altmain.cpp index 1fe0a547..f1ffb05a 100644 --- a/Source/Main/altmain.cpp +++ b/Source/Main/altmain.cpp @@ -57,8 +57,7 @@ void CompressPathSet(PathSet path_set, const std::string &base_folder, const std::string &dst){ bool first_path = true; - for(PathSet::iterator iter = path_set.begin(); iter != path_set.end(); ++iter){ - const std::string &full_path = (*iter); + for(const auto & full_path : path_set){ const char* truncated_path = &full_path[base_folder.length()]; Zip(full_path, dst, truncated_path, first_path?_YES_OVERWRITE:_APPEND_OVERWRITE); first_path = false; @@ -141,8 +140,7 @@ int TestMain( int argc, char* argv[], const char* overloaded_write_dir, const ch LOGI << "Objects: " << ref->objects.size() << std::endl; const char* key_words[] = {"left", "capsule", "box", "sphere"}; const int num_key_words = sizeof(key_words)/sizeof(key_words[0]); - for(size_t i=0, len=ref->objects.size(); iobjects[i]; + for(auto & object : ref->objects){ // Parse label string const std::string &label = object.label; size_t last_space_index = 0; @@ -160,10 +158,10 @@ int TestMain( int argc, char* argv[], const char* overloaded_write_dir, const ch ++count; } bool match = false; - for(int k=0; kDispose(); ActiveCameras::Get()->SetCameraObject(NULL); @@ -917,9 +917,9 @@ void Engine::UpdateControls(float timestep, bool loading_screen) { std::vector selected; scenegraph_->ReturnSelected(&selected); - for(unsigned selected_i = 0; selected_i < selected.size(); ++selected_i) { - if(selected[selected_i]->GetType() == _hotspot_object) { - Hotspot* hotspot = (Hotspot*)selected[selected_i]; + for(auto & selected_i : selected) { + if(selected_i->GetType() == _hotspot_object) { + Hotspot* hotspot = (Hotspot*)selected_i; if(hotspot->HasCustomGUI()) { hotspot->LaunchCustomGUI(); @@ -1076,8 +1076,8 @@ struct VoxelField { vec3 voxel_field_bounds[2]; float voxel_size; VoxelField() { - for(int i=0; i<3; ++i){ - voxel_field_dims[i] = 0; + for(int & voxel_field_dim : voxel_field_dims){ + voxel_field_dim = 0; } voxel_size = 0.5f; } @@ -1085,13 +1085,11 @@ struct VoxelField { static void RasterizeTrisToVoxelField(const std::vector& tri_verts, VoxelField& field) { vec3 intersect_bounds[2] = {vec3(FLT_MAX), vec3(-FLT_MAX)}; - for(size_t tri_index=0, num_tri_verts=tri_verts.size(); - tri_index < num_tri_verts; - ++tri_index) + for(const auto & tri_vert : tri_verts) { for(int j=0; j<3; ++j){ - intersect_bounds[0][j] = min(intersect_bounds[0][j], tri_verts[tri_index][j]); - intersect_bounds[1][j] = max(intersect_bounds[1][j], tri_verts[tri_index][j]); + intersect_bounds[0][j] = min(intersect_bounds[0][j], tri_vert[j]); + intersect_bounds[1][j] = max(intersect_bounds[1][j], tri_vert[j]); } } @@ -1164,10 +1162,10 @@ static void RasterizeTrisToVoxelField(const std::vector& tri_verts, VoxelF // Rasterize clipped polygon to voxel field if(!new_poly_verts.empty()){ vec3 poly_bounds_min(FLT_MAX), poly_bounds_max(-FLT_MAX); - for(size_t i=0, len=new_poly_verts.size(); i& tri_verts, VoxelF } // Merge overlapping voxel spans - for(size_t span_index=0, len=field.spans.size(); span_index& span_list = field.spans[span_index]; + for(auto & span_list : field.spans){ span_list.sort(VoxelSpanHeightSort); for(std::list::iterator iter = span_list.begin(); iter != span_list.end(); @@ -1299,11 +1296,8 @@ void PlaceLightProbes(SceneGraph* scenegraph, vec3 translation, quaternion rotat temp_object.setCollisionShape(&shape); temp_object.setWorldTransform(transform); // Check for collision with each object - for(SceneGraph::object_list::iterator iter = scenegraph->collide_objects_.begin(); - iter != scenegraph->collide_objects_.end(); - ++iter) + for(auto object : scenegraph->collide_objects_) { - Object* object = (*iter); EntityType object_type = object->GetType(); if(object_type == _env_object || object_type == _terrain_type){ // Extract model from object @@ -1330,9 +1324,9 @@ void PlaceLightProbes(SceneGraph* scenegraph, vec3 translation, quaternion rotat object->scenegraph_->bullet_world_->GetPairCollisions(temp_object, *bullet_object->body, cb); // Add transformed triangles to list const std::vector& tris = tlr[bullet_object]; - for(unsigned tri_index=0; tri_indexfaces[face_index+j]*3; for(int k=0; k<3; ++k){ @@ -1423,11 +1417,8 @@ void PlaceLightProbes(SceneGraph* scenegraph, vec3 translation, quaternion rotat std::list& empty_span_list = empty_box_spans[column_index]; span_list.sort(VoxelSpanHeightSort); VoxelSpan* prev_span = NULL; - for(std::list::iterator iter = span_list.begin(); - iter != span_list.end(); - ++iter) + for(auto & span : span_list) { - VoxelSpan& span = *iter; if(prev_span){ VoxelSpan empty_span; empty_span.height[0] = prev_span->height[1]; @@ -1504,11 +1495,8 @@ void PlaceLightProbes(SceneGraph* scenegraph, vec3 translation, quaternion rotat std::list& span_list = cropped_voxel_field_spans[column_index]; std::list& empty_span_list = empty_field_spans[column_index]; VoxelSpan* prev_span = NULL; - for(std::list::iterator iter = span_list.begin(); - iter != span_list.end(); - ++iter) + for(auto & span : span_list) { - VoxelSpan& span = *iter; if(prev_span){ VoxelSpan empty_span; empty_span.height[0] = prev_span->height[1]; @@ -1549,11 +1537,9 @@ void PlaceLightProbes(SceneGraph* scenegraph, vec3 translation, quaternion rotat { column_start_index[column_index] = span_vector.size(); std::list& span_list = empty_field_spans[column_index]; - for(std::list::iterator iter = span_list.begin(); - iter != span_list.end(); - ++iter) + for(auto & iter : span_list) { - span_vector.push_back(*iter); + span_vector.push_back(iter); } } // Cap start index list to avoid special case when finding num spans per column @@ -2055,9 +2041,9 @@ void Engine::Update() { std::string campaign_id = sc->GetCampaignID(); ModInstance::Campaign camp = ModLoading::Instance().GetCampaign(campaign_id); - for( size_t i = 0; i < camp.levels.size(); i++ ) { - if( strmtch(camp.levels[i].id, current_engine_state_.id) ) { - std::string short_path = std::string("Data/Levels/") + std::string(camp.levels[i].path); + for(auto & level : camp.levels) { + if( strmtch(level.id, current_engine_state_.id) ) { + std::string short_path = std::string("Data/Levels/") + std::string(level.path); if( FileExists( short_path, kAnyPath ) ) { @@ -2236,16 +2222,16 @@ void Engine::Update() { scenegraph_->level->Update(paused); } - for(size_t i=0, len=scenegraph_->movement_objects_.size(); imovement_objects_[i]; + for(auto & movement_object : scenegraph_->movement_objects_) { + MovementObject* mo = (MovementObject*)movement_object; if(mo->controlled){ mo->UpdatePaused(); } } HandleRabbotToggleControls(); - for(size_t i = 0; i < active_contexts.size(); ++i) { - active_contexts[i]->profiler.Update(); + for(auto active_context : active_contexts) { + active_context->profiler.Update(); } } } else { @@ -2297,9 +2283,7 @@ void Engine::Update() { } if (Online::Instance()->IsActive()) { - for (uint32_t i = 0; i < scenegraph_->visible_static_meshes_.size(); i++) { - EnvObject * eo = scenegraph_->visible_static_meshes_[i]; - + for (auto eo : scenegraph_->visible_static_meshes_) { eo->Update(game_timer.timestep); } } @@ -2329,13 +2313,13 @@ void Engine::Update() { // Disposing of an object might in turn queue up more items // to delete, so make we loop until we're at the end of // object_ids_to_delete - for(size_t i = 0; i < scenegraph_->object_ids_to_delete.size(); ++i){ - scenegraph_->map_editor->DeleteID(scenegraph_->object_ids_to_delete[i]); + for(int i : scenegraph_->object_ids_to_delete){ + scenegraph_->map_editor->DeleteID(i); } scenegraph_->object_ids_to_delete.clear(); - for(size_t i = 0; i < active_contexts.size(); ++i) { - active_contexts[i]->profiler.Update(); + for(auto active_context : active_contexts) { + active_context->profiler.Update(); } } sound.UpdateGameTimescale(powf(game_timer.time_scale / current_global_scale_mult, 0.5f)); @@ -3064,8 +3048,7 @@ void Engine::DrawScene(DrawingViewport drawing_viewport, Engine::PostEffectsType ActiveCameras::Get()->tint = vec3(1.0); ActiveCameras::Get()->vignette_tint = vec3(1.0); float predraw_time = game_timer.GetRenderTime(); - for(int i=0; i<(int)scenegraph_->objects_.size(); ++i){ - Object* obj = scenegraph_->objects_[i]; + for(auto obj : scenegraph_->objects_){ if(!obj->parent){ obj->PreDrawCamera(predraw_time); } @@ -3530,8 +3513,8 @@ static void CalculateMinMax(const mat4& model_to_light_transform, const Model& m model.max_coords, }; - for(int i = 0; i < 8; ++i) { - vec2 light_space_vert = CalculateMulMat4Vec3(model_to_light_transform, bounding_corners[i]); + for(const auto & bounding_corner : bounding_corners) { + vec2 light_space_vert = CalculateMulMat4Vec3(model_to_light_transform, bounding_corner); result_min_max_bounds[0] = std::min(light_space_vert[0], result_min_max_bounds[0]); result_min_max_bounds[1] = std::min(light_space_vert[1], result_min_max_bounds[1]); result_min_max_bounds[2] = std::max(light_space_vert[0], result_min_max_bounds[2]); @@ -3596,20 +3579,14 @@ static bool UpdateShadowCache(SceneGraph* scenegraph) { if(shadow_cache_dirty_sun_moved) { // Dirty all objects once, so iterative processing can clean them up - for(std::vector::iterator it = scenegraph->visible_static_meshes_shadow_cache_bounds_.begin(); - it != scenegraph->visible_static_meshes_shadow_cache_bounds_.end(); - ++it) + for(auto & lb : scenegraph->visible_static_meshes_shadow_cache_bounds_) { - ShadowCacheObjectLightBounds& lb = *it; if(!lb.is_ignored) { lb.is_calculated = false; } } - for(std::vector::iterator it = scenegraph->terrain_objects_shadow_cache_bounds_.begin(); - it != scenegraph->terrain_objects_shadow_cache_bounds_.end(); - ++it) + for(auto & lb : scenegraph->terrain_objects_shadow_cache_bounds_) { - ShadowCacheObjectLightBounds& lb = *it; lb.is_calculated = false; } } @@ -3655,11 +3632,8 @@ static bool UpdateShadowCache(SceneGraph* scenegraph) { } if(shadow_cache_dirty_level_loaded || !max_updates_hit) { - for(std::vector::iterator it = scenegraph->visible_static_meshes_shadow_cache_bounds_.begin(); - it != scenegraph->visible_static_meshes_shadow_cache_bounds_.end(); - ++it) + for(auto & lb : scenegraph->visible_static_meshes_shadow_cache_bounds_) { - ShadowCacheObjectLightBounds& lb = *it; if(!lb.is_ignored) { bounds[0] = std::min(lb.min_bounds[0], bounds[0]); bounds[1] = std::min(lb.min_bounds[1], bounds[1]); @@ -3667,11 +3641,8 @@ static bool UpdateShadowCache(SceneGraph* scenegraph) { bounds[3] = std::max(lb.max_bounds[1], bounds[3]); } } - for(std::vector::iterator it = scenegraph->terrain_objects_shadow_cache_bounds_.begin(); - it != scenegraph->terrain_objects_shadow_cache_bounds_.end(); - ++it) + for(auto & lb : scenegraph->terrain_objects_shadow_cache_bounds_) { - ShadowCacheObjectLightBounds& lb = *it; bounds[0] = std::min(lb.min_bounds[0], bounds[0]); bounds[1] = std::min(lb.min_bounds[1], bounds[1]); bounds[2] = std::max(lb.max_bounds[0], bounds[2]); @@ -4069,9 +4040,9 @@ static void UpdateShadowCascades(SceneGraph* scenegraph) { int num_shadow_view_frustum_planes = 0; vec4 shadow_view_frustum_planes[30]; // Add camera frustum panes if they are facing the direction the light is coming from - for(int i=0; i<6; ++i) { - if(dot(light_dir, view_frustum_planes[i].xyz()) >= 0.0f){ - shadow_view_frustum_planes[num_shadow_view_frustum_planes] = view_frustum_planes[i]; + for(const auto & view_frustum_plane : view_frustum_planes) { + if(dot(light_dir, view_frustum_plane.xyz()) >= 0.0f){ + shadow_view_frustum_planes[num_shadow_view_frustum_planes] = view_frustum_plane; ++num_shadow_view_frustum_planes; } } @@ -4210,8 +4181,7 @@ static void UpdateShadowCascades(SceneGraph* scenegraph) { { // Perform per-frame, per-camera functions, like character LOD and spawning grass PROFILER_GPU_ZONE(g_profiler_ctx, "Pre-draw camera"); float predraw_time = game_timer.GetRenderTime(); - for(int i=0; i<(int)scenegraph->objects_.size(); ++i){ - Object* obj = scenegraph->objects_[i]; + for(auto obj : scenegraph->objects_){ if(!obj->parent){ obj->PreDrawCamera(predraw_time); } @@ -4245,8 +4215,7 @@ static void UpdateShadowCascades(SceneGraph* scenegraph) { { // Perform per-frame, per-camera functions, like character LOD and spawning grass PROFILER_GPU_ZONE(g_profiler_ctx, "Pre-draw camera"); float predraw_time = game_timer.GetRenderTime(); - for(int i=0; i<(int)scenegraph->objects_.size(); ++i){ - Object* obj = scenegraph->objects_[i]; + for(auto obj : scenegraph->objects_){ if(!obj->parent){ obj->PreDrawCamera(predraw_time); } @@ -4357,15 +4326,13 @@ void SaveCollisionNormals(const SceneGraph* scenegraph) { fwrite(kCollisionNormalIdentifier, strlen(kCollisionNormalIdentifier), 1, file); fwrite(&kCollisionNormalVersion, sizeof(int), 1, file); int num_objects = 0; - for(size_t i=0, len=scenegraph->visible_static_meshes_.size(); ivisible_static_meshes_[i]; + for(auto eo : scenegraph->visible_static_meshes_){ if(eo->GetCollisionModelID() != -1){ ++num_objects; } } fwrite(&num_objects, sizeof(int), 1, file); - for(size_t i=0, len=scenegraph->visible_static_meshes_.size(); ivisible_static_meshes_[i]; + for(auto eo : scenegraph->visible_static_meshes_){ if(eo->GetCollisionModelID() != -1){ int id = eo->GetID(); fwrite(&id, sizeof(int), 1, file); @@ -4563,8 +4530,7 @@ void Engine::Draw() { { // Perform per-frame calculations (like character shadows or LOD) PROFILER_GPU_ZONE(g_profiler_ctx, "Pre-draw frame"); float predraw_time = game_timer.GetRenderTime(); - for(int i=0; i<(int)scenegraph_->objects_.size(); ++i){ - Object* obj = scenegraph_->objects_[i]; + for(auto obj : scenegraph_->objects_){ if(!obj->parent){ obj->PreDrawFrame(predraw_time); } @@ -4578,8 +4544,7 @@ void Engine::Draw() { PROFILER_GPU_ZONE(g_profiler_ctx, "Updating reflection capture cubemaps"); std::vector textures; - for(size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for(auto obj : scenegraph_->objects_){ ReflectionCaptureObject* reflection_obj = (ReflectionCaptureObject*)obj; if(obj->GetType() == _reflection_capture_object){ if(reflection_obj->cube_map_ref.valid()){ @@ -4592,8 +4557,7 @@ void Engine::Draw() { textures.push_back(scenegraph_->sky->GetSpecularCubeMapTexture()); scenegraph_->ref_cap_matrix.clear(); scenegraph_->ref_cap_matrix_inverse.clear(); - for(size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for(auto obj : scenegraph_->objects_){ ReflectionCaptureObject* reflection_obj = (ReflectionCaptureObject*)obj; if(obj->GetType() == _reflection_capture_object){ if(reflection_obj->cube_map_ref.valid()){ @@ -4776,10 +4740,10 @@ void Engine::Draw() { } // Finalize second bounce light probes if (kLightProbe2pass && scenegraph_->light_probe_collection.to_process.empty()){ - for(size_t i=0, len=scenegraph_->light_probe_collection.light_probes.size(); ilight_probe_collection.light_probes){ for(int j=0; j<6; ++j){ - scenegraph_->light_probe_collection.light_probes[i].ambient_cube_color[j] = - scenegraph_->light_probe_collection.light_probes[i].ambient_cube_color_buf[j]; + light_probe.ambient_cube_color[j] = + light_probe.ambient_cube_color_buf[j]; } } kLightProbe2pass = false; @@ -4801,12 +4765,8 @@ void Engine::Draw() { if(kDrawSpans){ for(int span_index=0, len=(int)g_voxel_field.spans.size(); span_index& span_list = g_voxel_field.spans[span_index]; - for(std::list::iterator iter = span_list.begin(); - iter != span_list.end(); - ++iter) + for(auto span : span_list) { - VoxelSpan span = *iter; - int voxel_x = span_index / g_voxel_field.voxel_field_dims[2]; int voxel_z = span_index % g_voxel_field.voxel_field_dims[2]; vec3 pos = vec3( @@ -4826,8 +4786,8 @@ void Engine::Draw() { { PROFILER_GPU_ZONE(g_profiler_ctx, "Update light volume objects"); LightVolumeObject* lvo = NULL; - for(size_t i=0, len=scenegraph_->light_volume_objects_.size(); ilight_volume_objects_[i]; + for(auto & light_volume_object : scenegraph_->light_volume_objects_){ + lvo = light_volume_object; } if(lvo && lvo->dirty && !IsBeingMoved(scenegraph_->map_editor, lvo)){ @@ -4871,8 +4831,8 @@ void Engine::Draw() { { if( g_no_reflection_capture == false ) { PROFILER_GPU_ZONE(g_profiler_ctx, "Update reflection capture objects"); - for(size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for(auto & object : scenegraph_->objects_){ + Object* obj = object; ReflectionCaptureObject* reflection_obj = (ReflectionCaptureObject*)obj; if(obj->GetType() == _reflection_capture_object && reflection_obj->dirty){ bool media_mode = graphics->media_mode(); @@ -4882,13 +4842,13 @@ void Engine::Draw() { reflection_obj->cube_map_ref = Textures::Instance()->makeCubemapTexture(128, 128, GL_RGBA16F, GL_RGBA, Textures::MIPMAPS); Textures::Instance()->SetTextureName(reflection_obj->cube_map_ref, "Reflection Capture Cubemap"); } - DrawCubeMap(reflection_obj->cube_map_ref, scenegraph_->objects_[i]->GetTranslation(), + DrawCubeMap(reflection_obj->cube_map_ref, object->GetTranslation(), scenegraph_->light_probe_collection.cube_map_fbo, SceneGraph::kStaticOnly); // Blur cubemap to represent different levels of roughness CubemapMipChain(reflection_obj->cube_map_ref, Cubemap::SPHERE, NULL); graphics->SetMediaMode(media_mode); ReadAverageColorsFromCubemap(reflection_obj->avg_color, reflection_obj->cube_map_ref); - ((ReflectionCaptureObject*)(scenegraph_->objects_[i]))->dirty = false; + ((ReflectionCaptureObject*)object)->dirty = false; scenegraph_->cubemaps_need_refresh = true; } } @@ -5653,12 +5613,12 @@ void Engine::PreloadAssets(const Path &level_path) { std::vector &preload_files = AssetPreload::Instance().GetPreloadFiles(); LOGI << "Starting Preloading for: " << level_path << std::endl; - for( unsigned i = 0; i < preload_files.size(); i++ ) { - if( preload_files[i].all_levels || preload_files[i].level_name == level_path.GetOriginalPathStr() ) { + for(auto & preload_file : preload_files) { + if( preload_file.all_levels || preload_file.level_name == level_path.GetOriginalPathStr() ) { //LOGI << "Preloading: " << preload_files[i].path << " " << preload_files[i].asset_type << " " << preload_files[i].load_flags << std::endl; - Path p = FindFilePath( preload_files[i].path, kAnyPath, false ); + Path p = FindFilePath( preload_file.path, kAnyPath, false ); if( p.isValid() ) { - GetAssetManager()->LoadSync(preload_files[i].asset_type, preload_files[i].path, preload_files[i].load_flags, HOLD_LOAD_MASK_PRELOAD); + GetAssetManager()->LoadSync(preload_file.asset_type, preload_file.path, preload_file.load_flags, HOLD_LOAD_MASK_PRELOAD); } } } @@ -5908,8 +5868,7 @@ void Engine::LoadLevel(Path queued_level) { { PROFILER_ZONE(g_profiler_ctx, "Send 'added_object' messages"); - for(size_t i=0, len=scenegraph_->objects_.size(); iobjects_[i]; + for(auto obj : scenegraph_->objects_){ static const int kBufSize = 256; char msg[kBufSize]; FormatString(msg, kBufSize, "added_object %d", obj->GetID()); @@ -6030,16 +5989,16 @@ void Engine::QueueLevelCacheGeneration(const Path& path) { } void Engine::GenerateLevelCache(ModInstance* mod_instance) { - for(size_t i = 0; i < mod_instance->levels.size(); ++i) { + for(auto & level : mod_instance->levels) { std::string path = "Data/levels/"; - path += mod_instance->levels[i].path; + path += level.path; QueueLevelCacheGeneration(FindFilePath(path, kAnyPath)); } - for(size_t i = 0; i < mod_instance->campaigns.size(); ++i) { - for(size_t j = 0; j < mod_instance->campaigns[i].levels.size(); ++j) { + for(auto & campaign : mod_instance->campaigns) { + for(size_t j = 0; j < campaign.levels.size(); ++j) { std::string path = "Data/levels/"; - path += mod_instance->campaigns[i].levels[j].path; + path += campaign.levels[j].path; QueueLevelCacheGeneration(FindFilePath(path, kAnyPath)); } @@ -6517,9 +6476,9 @@ void Engine::ScriptableUICallback(const std::string &level) std::string campaign_id = sc->GetCampaignID(); ModInstance::Campaign campaign = ModLoading::Instance().GetCampaign(campaign_id); - for( size_t i = 0; i < campaign.levels.size(); i++ ) { - if( campaign.levels[i].path == long_path || campaign.levels[i].path == short_path ) { - level_id = campaign.levels[i].id; + for(auto & level : campaign.levels) { + if( level.path == long_path || level.path == short_path ) { + level_id = level.id; } } } @@ -6746,10 +6705,10 @@ ScriptableCampaign* Engine::GetCurrentCampaign() { return current_engine_state_.campaign.GetPtr(); } } else { - for( unsigned int i = 0; i < state_history.size(); i++ ) { - if( state_history[i].type == kEngineCampaignState ){ - if( state_history[i].campaign.Valid() ) { - return state_history[i].campaign.GetPtr(); + for(auto & i : state_history) { + if( i.type == kEngineCampaignState ){ + if( i.campaign.Valid() ) { + return i.campaign.GetPtr(); } } } @@ -6762,9 +6721,9 @@ std::string Engine::GetCurrentLevelID() { if(current_engine_state_.type == kEngineLevelState || current_engine_state_.type == kEngineEditorLevelState ) { return current_engine_state_.id; } else { - for( unsigned int i = 0; i < state_history.size(); i++ ) { - if( state_history[i].type == kEngineLevelState || state_history[i].type == kEngineEditorLevelState){ - return state_history[i].id; + for(auto & i : state_history) { + if( i.type == kEngineLevelState || i.type == kEngineEditorLevelState){ + return i.id; } } } diff --git a/Source/Main/scenegraph.cpp b/Source/Main/scenegraph.cpp index ab4bcafb..109d5fbb 100644 --- a/Source/Main/scenegraph.cpp +++ b/Source/Main/scenegraph.cpp @@ -189,8 +189,8 @@ SceneGraph::SceneGraph() , hotspots_modified_(false) { memset(destruction_sanity,0,destruction_sanity_size*sizeof(Object*)); - for( unsigned i = 0; i < destruction_memory_size; i++ ) { - destruction_memory_ids[i] = -1; + for(int & destruction_memory_id : destruction_memory_ids) { + destruction_memory_id = -1; } memset(destruction_memory_strings,'\0',destruction_memory_size*destruction_memory_string_size); @@ -298,15 +298,15 @@ bool SceneGraph::addObject(Object* new_object) { } void SceneGraph::LinkObject(Object* new_object) { - for( size_t i = 0; i < destruction_sanity_size; i++ ) { - if( destruction_sanity[i] == new_object ) { - destruction_sanity[i] = NULL; + for(auto & i : destruction_sanity) { + if( i == new_object ) { + i = NULL; } } - for( size_t i = 0; i < destruction_memory_size; i++ ) { - if( destruction_memory_ids[i] == new_object->GetID() ) { - destruction_memory_ids[i] = 0; + for(int & destruction_memory_id : destruction_memory_ids) { + if( destruction_memory_id == new_object->GetID() ) { + destruction_memory_id = 0; } } @@ -386,8 +386,7 @@ Collision SceneGraph::lineCheck(const vec3 &start, const vec3 &end) { LineCheckAll(start, end, &collisions); Collision *closest = NULL; float closest_distance; - for(std::vector::iterator it = collisions.begin(); it != collisions.end(); ++it) { - Collision &c = *it; + for(auto & c : collisions) { float dist = distance_squared(start, c.hit_where); if(!closest || dist < closest_distance){ closest = &c; @@ -406,8 +405,7 @@ Collision SceneGraph::lineCheckCollidable(const vec3 &start, const vec3 &end, Ob LineCheckAll(start, end, &collisions); Collision *closest = NULL; float closest_distance; - for(std::vector::iterator it = collisions.begin(); it != collisions.end(); ++it) { - Collision &c = *it; + for(auto & c : collisions) { if(c.hit_what->collidable && c.hit_what != not_hit){ float dist = distance_squared(start, c.hit_where); if(!closest || dist < closest_distance){ @@ -425,8 +423,7 @@ Collision SceneGraph::lineCheckCollidable(const vec3 &start, const vec3 &end, Ob void SceneGraph::LineCheckAll(const vec3 &start, const vec3 &end, std::vector *collisions) { PROFILER_ZONE(g_profiler_ctx, "SceneGraph::LineCheckAll"); - for(object_list::iterator it = objects_.begin(); it != objects_.end(); ++it) { - Object* obj = *it; + for(auto obj : objects_) { vec3 point, normal; int collision_tri = obj->lineCheck(start, end, &point, &normal); if(collision_tri != -1) { @@ -631,8 +628,7 @@ void SceneGraph::Draw(SceneGraph::SceneDrawType scene_draw_type) { PROFILER_ENTER(g_profiler_ctx, "List visible objects / frustum cull"); if( !nav_mesh_renderer_.IsCollisionMeshVisible() ) { - for(std::vector::iterator it = visible_static_mesh_indices_.begin(); it != visible_static_mesh_indices_.end(); ++it) { - uint16_t index = *it; + for(unsigned short index : visible_static_mesh_indices_) { EnvObject* eo = visible_static_meshes_[index]; if(!eo->transparent && eo->enabled_) { if(camera->checkSphereInFrustum(eo->sphere_center_, eo->sphere_radius_)){ @@ -679,8 +675,7 @@ void SceneGraph::Draw(SceneGraph::SceneDrawType scene_draw_type) { batch_start = i; } } - for(int i = 0; i < detail_objects_surfaces_to_draw.size(); ++i) { - auto current = detail_objects_surfaces_to_draw[i]; + for(auto current : detail_objects_surfaces_to_draw) { current.draw_owner->DrawDetailObjectInstances(current.instance_array, current.num_instances, Object::kFullDraw); } if(g_draw_collision){ @@ -732,8 +727,8 @@ void SceneGraph::Draw(SceneGraph::SceneDrawType scene_draw_type) { { //First non transparent, then transparent objects. PROFILER_ZONE(g_profiler_ctx, "Draw objects"); - for(object_list::iterator it = visible_objects_.begin(); it != visible_objects_.end(); ++it) { - Object& obj = *(*it); + for(auto & visible_object : visible_objects_) { + Object& obj = *visible_object; const EntityType& obj_type = obj.GetType(); switch(obj_type){ case _decal_object: @@ -830,14 +825,14 @@ void SceneGraph::Draw(SceneGraph::SceneDrawType scene_draw_type) { { PROFILER_ZONE(g_profiler_ctx, "Draw transparent objects"); - for(std::vector::iterator it = visible_static_meshes_.begin(); it != visible_static_meshes_.end(); ++it) { - EnvObject& obj = *(*it); + for(auto & visible_static_meshe : visible_static_meshes_) { + EnvObject& obj = *visible_static_meshe; if(obj.enabled_ && obj.transparent){ PROFILER_ZONE(g_profiler_ctx,"%s %d draw",CStringFromEntityType(((Object*)&obj)->GetType()),obj.GetID()); // Avoid calling EnvObject::Draw repeatedly, so matrices etc can be shared instead of reacquired for every draw call // TODO: last_ofr_is_valid is set to false in EnvObject::Draw - is it important? - obj.DrawInstances(&(*it), 1, proj_view_mat, prev_proj_view_mat, &shadow_matrix, cam_pos, Object::kFullDraw); - obj.DrawDetailObjectInstances(&(*it), 1, Object::kFullDraw); + obj.DrawInstances(&visible_static_meshe, 1, proj_view_mat, prev_proj_view_mat, &shadow_matrix, cam_pos, Object::kFullDraw); + obj.DrawDetailObjectInstances(&visible_static_meshe, 1, Object::kFullDraw); } } } @@ -850,8 +845,8 @@ void SceneGraph::Draw(SceneGraph::SceneDrawType scene_draw_type) { glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); } if(!Graphics::Instance()->media_mode() && map_editor->state_ != MapEditor::kInGame){ - for(object_list::iterator it = decal_objects_.begin(); it != decal_objects_.end(); ++it) { - Object &obj = *(*it); + for(auto & decal_object : decal_objects_) { + Object &obj = *decal_object; if(obj.enabled_ && obj.Selected() && obj.editor_visible) { PROFILER_ZONE(g_profiler_ctx,"%s %d draw",CStringFromEntityType(obj.GetType()),obj.GetID()); obj.ReceiveObjectMessage(OBJECT_MSG::DRAW); @@ -869,8 +864,8 @@ void SceneGraph::Draw(SceneGraph::SceneDrawType scene_draw_type) { // Draw hotspots if(map_editor->state_ == MapEditor::kInGame || map_editor->IsTypeEnabled(_hotspot_object)){ PROFILER_ZONE(g_profiler_ctx,"Draw Hotspots"); - for (object_list::iterator it = hotspots_.begin(); it != hotspots_.end(); ++it) { - ((Hotspot*)(*it))->Draw(); + for (auto & hotspot : hotspots_) { + ((Hotspot*)hotspot)->Draw(); } } { @@ -890,26 +885,26 @@ void SceneGraph::Draw(SceneGraph::SceneDrawType scene_draw_type) { Object* SceneGraph::GetLastSelected() { Object * res = NULL; - for( unsigned i = 0; i < objects_.size(); i++ ) { - if( res == NULL || objects_[i]->Selected() > res->Selected() ) { - res = objects_[i]; + for(auto & object : objects_) { + if( res == NULL || object->Selected() > res->Selected() ) { + res = object; } } return res; } void SceneGraph::ReturnSelected(std::vector* selected) { - for( unsigned i = 0; i < objects_.size(); i++ ) { - if( objects_[i]->Selected() ) { - selected->push_back(objects_[i]); + for(auto & object : objects_) { + if( object->Selected() ) { + selected->push_back(object); } } } void SceneGraph::UnselectAll() { - for( unsigned i = 0; i < objects_.size(); i++ ) { - if( objects_[i]->Selected() ) { - objects_[i]->Select(false); + for(auto & object : objects_) { + if( object->Selected() ) { + object->Select(false); } } } @@ -974,9 +969,9 @@ void SceneGraph::Update(float timestep, float curr_game_time) { ObjectSanityState oss = objects_[i]->GetSanity(); if( oss.Ok() ) { - for( unsigned k = 0; k < kMaxWarnings; k++ ) { - if( sanity_list[k].GetID() == oss.GetID() ) { - sanity_list[k] = ObjectSanityState(); + for(auto & k : sanity_list) { + if( k.GetID() == oss.GetID() ) { + k = ObjectSanityState(); } } } else { @@ -1150,9 +1145,9 @@ void SceneGraph::UnlinkObject(Object *o) { } } - for( unsigned i = 0; i < kMaxWarnings; i++ ) { - if( sanity_list[i].GetID() == id ) { - sanity_list[i] = ObjectSanityState(); + for(auto & i : sanity_list) { + if( i.GetID() == id ) { + i = ObjectSanityState(); } } } @@ -1559,15 +1554,15 @@ vec3 SceneGraph::GetColorAtPoint( const vec3 &pos ) void SceneGraph::UpdatePhysicsTransforms() { - for(std::vector::iterator it = visible_static_meshes_.begin(); it != visible_static_meshes_.end(); ++it){ - (*it)->UpdatePhysicsTransform(); + for(auto & visible_static_meshe : visible_static_meshes_){ + visible_static_meshe->UpdatePhysicsTransform(); } } void SceneGraph::GetPlayerCharacterIDs(int* num_avatars, int avatar_ids[], int max_avatars) { *num_avatars = 0; - for(unsigned i=0; i < movement_objects_.size(); ++i) { - MovementObject* mo = (MovementObject*)movement_objects_[i]; + for(auto & movement_object : movement_objects_) { + MovementObject* mo = (MovementObject*)movement_object; if(mo->is_player){ if(*num_avatars < max_avatars){ avatar_ids[*num_avatars] = mo->GetID(); @@ -1581,8 +1576,8 @@ void SceneGraph::GetPlayerCharacterIDs(int* num_avatars, int avatar_ids[], int m void SceneGraph::GetNPCCharacterIDs(int * num_avatars, int avatar_ids[], int max_avatars) { *num_avatars = 0; - for (unsigned i = 0; i < movement_objects_.size(); ++i) { - MovementObject* mo = (MovementObject*)movement_objects_[i]; + for (auto & movement_object : movement_objects_) { + MovementObject* mo = (MovementObject*)movement_object; if (!mo->is_player) { if (*num_avatars < max_avatars) { avatar_ids[*num_avatars] = mo->GetID(); @@ -1597,8 +1592,8 @@ void SceneGraph::GetNPCCharacterIDs(int * num_avatars, int avatar_ids[], int max void SceneGraph::GetCharacterIDs(int *num_avatars, int avatar_ids[], int max_avatars) { *num_avatars = 0; - for (unsigned i = 0; i < movement_objects_.size(); ++i) { - MovementObject* mo = (MovementObject*)movement_objects_[i]; + for (auto & movement_object : movement_objects_) { + MovementObject* mo = (MovementObject*)movement_object; if (*num_avatars < max_avatars) { avatar_ids[*num_avatars] = mo->GetID(); ++*num_avatars; @@ -1643,8 +1638,8 @@ float SceneGraph::GetMaterialSharpPenetration( const vec3 &pos, Object* excluded void SceneGraph::GetSweptSphereCollisionCharacters( const vec3 &pos, const vec3 &pos2, float radius, SphereCollision &as_col ) { vec3 end = pos2; - for(unsigned i=0; irigged_object()->skeleton().GetSweptSphereCollisionCharacter(pos, end, radius, as_col); end = as_col.position; } @@ -1655,8 +1650,8 @@ int SceneGraph::CheckRayCollisionCharacters( const vec3 &start, const vec3 &end, vec3 temp_point; vec3 temp_normal; int char_id = -1; - for(unsigned i=0; irigged_object()->skeleton().CheckRayCollision(start, new_end, &temp_point, &temp_normal); if(bone_col != NULL){ if(point){ @@ -1686,8 +1681,7 @@ void SceneGraph::SendMessageToAllObjects( OBJECT_MSG::Type type ) { //passing way past the end. Likely because objects_ is sometimes changed as a result of this call. //This solution means that most objects get called, some might not if they are first destroyed. //New objects will also be called assuming they are added last to the list. - for( unsigned int i = 0; i < objects_.size(); i++ ) { - Object* obj = objects_[i]; + for(auto obj : objects_) { if( obj ) { obj->ReceiveObjectMessage(type); @@ -1700,8 +1694,7 @@ void SceneGraph::SendMessageToAllObjects( OBJECT_MSG::Type type ) { } void SceneGraph::SendScriptMessageToAllObjects( std::string& msg ) { - for( unsigned int i = 0; i < objects_.size(); i++ ) { - Object* obj = objects_[i]; + for(auto obj : objects_) { if( obj ) { obj->ReceiveObjectMessage(OBJECT_MSG::SCRIPT, &msg); @@ -1738,8 +1731,7 @@ std::vector SceneGraph::GetControllableMovementObjects() { } bool SceneGraph::VerifySanity() { - for( unsigned i = 0; i < kMaxWarnings; i++ ) { - ObjectSanityState& sanity = sanity_list[i]; + for(auto & sanity : sanity_list) { if(sanity.Valid() && sanity.Ok() == false) { return false; } @@ -1774,15 +1766,15 @@ void SceneGraph::DrawDepthMap(const mat4& proj_view_matrix, const vec4* cull_pla visible_objects_copy = visible_objects_; PROFILER_ZONE(g_profiler_ctx, "Draw dynamic objects"); if(scene_draw_type == kStaticAndDynamic){ - for(object_list::iterator it = visible_objects_copy.begin(); it != visible_objects_copy.end(); ++it) { - Object& obj = *(*it); + for(auto & it : visible_objects_copy) { + Object& obj = *it; if(obj.enabled_ && obj.GetType() != _decal_object && obj.GetType() != _env_object){ obj.DrawDepthMap(proj_view_matrix, cull_planes, num_cull_planes, object_draw_type); } } } else { - for(object_list::iterator it = visible_objects_copy.begin(); it != visible_objects_copy.end(); ++it) { - Object& obj = *(*it); + for(auto & it : visible_objects_copy) { + Object& obj = *it; if(obj.enabled_ && obj.GetType() == _terrain_type){ obj.DrawDepthMap(proj_view_matrix, cull_planes, num_cull_planes, object_draw_type); } @@ -1805,8 +1797,7 @@ void SceneGraph::DrawDepthMap(const mat4& proj_view_matrix, const vec4* cull_pla static_meshes_to_draw.clear(); static_meshes_to_draw.reserve(visible_static_meshes_.size()); PROFILER_ENTER(g_profiler_ctx, "List visible objects / frustum cull"); - for(std::vector::iterator it = visible_static_mesh_indices_.begin(); it != visible_static_mesh_indices_.end(); ++it) { - uint16_t index = *it; + for(unsigned short index : visible_static_mesh_indices_) { EnvObject* eo = visible_static_meshes_[index]; if(!eo->transparent && eo->enabled_) { bool culled = false; @@ -1851,8 +1842,7 @@ void SceneGraph::DrawDepthMap(const mat4& proj_view_matrix, const vec4* cull_pla batch_start = i; } } - for(unsigned int i = 0; i < detail_objects_surfaces_to_draw.size(); ++i) { - auto current = detail_objects_surfaces_to_draw[i]; + for(auto current : detail_objects_surfaces_to_draw) { current.draw_owner->DrawDetailObjectInstances(current.instance_array, current.num_instances, object_draw_type); } } @@ -1903,11 +1893,11 @@ void SceneGraph::UnlinkUpdateObject(Object* obj, int entry) { } void SceneGraph::Dispose() { - for(object_list::iterator it = objects_.begin(); it != objects_.end(); ++it) { - (*it)->Dispose(); + for(auto & object : objects_) { + object->Dispose(); } - for(object_list::iterator it = objects_.begin(); it != objects_.end(); ++it) { - delete (*it); + for(auto & object : objects_) { + delete object; } object_from_id_map_.clear(); if(bullet_world_){ @@ -2945,8 +2935,8 @@ int SceneGraph::CountObjectsWithName(const char* name) { bool SceneGraph::IsObjectSane(Object* obj) { if(obj == NULL) return false; - for( size_t i = 0; i < destruction_sanity_size; i++ ) { - if( destruction_sanity[i] == obj ) { + for(auto & i : destruction_sanity) { + if( i == obj ) { return false; } } @@ -2973,9 +2963,9 @@ void SceneGraph::DumpState() { if( output.is_open() ) { LOGI << "Dumping all objects in scenegraph into " << dump_path << std::endl; - for( size_t i = 0; i < objects_.size(); i++ ) { + for(auto & object : objects_) { if( output.good() ) { - output << "[" << objects_[i]->GetID() << "]: \"" << CStringFromEntityType(objects_[i]->GetType()) << "\" " << objects_[i]->GetName() << std::endl; + output << "[" << object->GetID() << "]: \"" << CStringFromEntityType(object->GetType()) << "\" " << object->GetName() << std::endl; } } } else { @@ -3055,15 +3045,15 @@ void SceneGraph::PreloadForDrawType(std::map& preload_shaders, } UpdateShaderSuffix(this, draw_type); - for(std::map::iterator iter = preload_shaders.begin(); iter != preload_shaders.end(); ++iter) { - if(iter->second & type) { + for(auto & preload_shader : preload_shaders) { + if(preload_shader.second & type) { const int kShaderStrSize = 1024; char buf[kShaderStrSize]; - FormatString(buf, kShaderStrSize, "%s %s", iter->first.c_str(), global_shader_suffix); + FormatString(buf, kShaderStrSize, "%s %s", preload_shader.first.c_str(), global_shader_suffix); Shaders::OptionalShaders optional = Shaders::kNone; - if(iter->second & kOptionalGeometry) + if(preload_shader.second & kOptionalGeometry) optional = Shaders::kGeometry; - else if(iter->second & kOptionalTessellation) + else if(preload_shader.second & kOptionalTessellation) optional = Shaders::kTesselation; shaders->createProgram(shaders->returnProgram(buf, optional)); } @@ -3084,12 +3074,12 @@ void SceneGraph::PreloadShaders() { , "envobject #DETAIL_OBJECT #TERRAIN #PLANT #LESS_PLANT_MOVEMENT" }; - for(int i = 0; i < 6; ++i) { + for(auto & detail_object_name : detail_object_names) { const int kShaderStrSize = 1024; char buf[2][kShaderStrSize]; char* shader_str[2] = {buf[0], buf[1]}; - FormatString(shader_str[0], kShaderStrSize, "%s", detail_object_names[i]); + FormatString(shader_str[0], kShaderStrSize, "%s", detail_object_name); if(!Graphics::Instance()->config_.detail_object_decals()) { FormatString(shader_str[1], kShaderStrSize, "%s %s", shader_str[0], "#NO_DECALS"); std::swap(shader_str[0], shader_str[1]); @@ -3114,19 +3104,19 @@ void SceneGraph::PreloadShaders() { , kWireframe , kDecal }; - for(int i = 0; i < 6; ++i) - PreloadForDrawType(preload_shaders, preload_types[i]); + for(auto preload_type : preload_types) + PreloadForDrawType(preload_shaders, preload_type); // Load everything that isn't any of the above types Shaders* shaders = Shaders::Instance(); - for(std::map::iterator iter = preload_shaders.begin(); iter != preload_shaders.end(); ++iter) { - if((iter->second & kPreloadTypeAll) == 0) { + for(auto & preload_shader : preload_shaders) { + if((preload_shader.second & kPreloadTypeAll) == 0) { Shaders::OptionalShaders optional = Shaders::kNone; - if(iter->second & kOptionalGeometry) + if(preload_shader.second & kOptionalGeometry) optional = Shaders::kGeometry; - else if(iter->second & kOptionalTessellation) + else if(preload_shader.second & kOptionalTessellation) optional = Shaders::kTesselation; - shaders->createProgram(shaders->returnProgram(iter->first, optional)); + shaders->createProgram(shaders->returnProgram(preload_shader.first, optional)); } } } @@ -3134,12 +3124,9 @@ void SceneGraph::PreloadShaders() { void SceneGraph::LoadReflectionCaptureCubemaps() { PROFILER_ZONE(g_profiler_ctx, "Load reflection capture cubemaps"); - for (object_list::iterator iter = objects_.begin(); - iter != objects_.end(); - ++iter) + for (auto obj : objects_) { - Object* obj = *iter; - if(obj->GetType() == _reflection_capture_object){ + if(obj->GetType() == _reflection_capture_object){ char save_path[kPathSize]; FormatString(save_path, kPathSize, "%s_refl_cap_%d.hdrcube", level_path_.GetOriginalPath(), obj->GetID()); char abs_path[kPathSize]; @@ -3162,12 +3149,9 @@ void SceneGraph::LoadReflectionCaptureCubemaps() //TODO: make a version that only clears the dynamic cubemaps. void SceneGraph::UnloadReflectionCaptureCubemaps() { - for (object_list::iterator iter = objects_.begin(); - iter != objects_.end(); - ++iter) + for (auto obj : objects_) { - Object* obj = *iter; - if(obj->GetType() == _reflection_capture_object){ + if(obj->GetType() == _reflection_capture_object){ ReflectionCaptureObject* rco = (ReflectionCaptureObject*)obj; rco->cube_map_ref.clear(); rco->dirty = true; diff --git a/Source/Math/mat4.cpp b/Source/Math/mat4.cpp index 903006f0..b3a7ac19 100644 --- a/Source/Math/mat4.cpp +++ b/Source/Math/mat4.cpp @@ -437,8 +437,8 @@ mat4 mat4::operator-(void) const { mat4 result(*this); - for (int i = 0; i<16; i++) - result.entries[i]=-result.entries[i]; + for (float & entrie : result.entries) + entrie=-entrie; return result; } diff --git a/Source/Memory/stack_allocator.cpp b/Source/Memory/stack_allocator.cpp index 6e5b9142..4e07c452 100644 --- a/Source/Memory/stack_allocator.cpp +++ b/Source/Memory/stack_allocator.cpp @@ -101,8 +101,8 @@ uintptr_t StackAllocator::TopBlockSize() { } void StackAllocator::Init(void* p_mem, size_t p_size) { - for (int i = 0; i < kMaxBlocks; i++) { - stack_block_pts[i] = 0; + for (unsigned long & stack_block_pt : stack_block_pts) { + stack_block_pt = 0; } mem = p_mem; size = p_size; @@ -110,8 +110,8 @@ void StackAllocator::Init(void* p_mem, size_t p_size) { } void StackAllocator::Dispose() { - for (int i = 0; i < kMaxBlocks; i++) { - stack_block_pts[i] = 0; + for (unsigned long & stack_block_pt : stack_block_pts) { + stack_block_pt = 0; } mem = 0; size = 0; diff --git a/Source/Objects/ambientsoundobject.cpp b/Source/Objects/ambientsoundobject.cpp index 99dd6539..c53eb0c2 100644 --- a/Source/Objects/ambientsoundobject.cpp +++ b/Source/Objects/ambientsoundobject.cpp @@ -68,8 +68,7 @@ AmbientSoundObject::~AmbientSoundObject() { bool AmbientSoundObject::SetFromDesc( const EntityDescription& desc ){ bool ret = Object::SetFromDesc(desc); if( ret ) { - for(unsigned i=0; isize(); iat(i); + for(auto & detail_object_surface : *detail_object_surfaces){ + delete detail_object_surface; } detail_object_surfaces->clear(); detail_object_surfaces->resize(ofr->m_detail_object_layers.size()); int counter = 0; - for(EnvObject::DOSList::iterator iter = detail_object_surfaces->begin(); - iter != detail_object_surfaces->end(); ++iter) + for(auto & dos : *detail_object_surfaces) { - DetailObjectSurface*& dos = (*iter); dos = new DetailObjectSurface(); DetailObjectLayer& dol = ofr->m_detail_object_layers[counter]; dos->AttachTo(Models::Instance()->GetModel(model_id), transform); @@ -212,8 +210,8 @@ const MaterialEvent& EnvObject::GetMaterialEvent( const std::string &the_event, EnvObject::~EnvObject() { RemovePhysicsShape(); - for(int i=0, len=detail_object_surfaces.size(); i light_volume_matrix; std::vector light_volume_matrix_inverse; - for(int i=0, len=scenegraph_->light_volume_objects_.size(); ilight_volume_objects_[i]; + for(auto obj : scenegraph_->light_volume_objects_){ const mat4 &mat = obj->GetTransform(); light_volume_matrix.push_back(mat); light_volume_matrix_inverse.push_back(invert(mat)); @@ -900,10 +897,9 @@ void EnvObject::PreDrawCamera(float curr_game_time) { return; } - for(DOSList::iterator iter = detail_object_surfaces.begin(); - iter != detail_object_surfaces.end(); ++iter) + for(auto & detail_object_surface : detail_object_surfaces) { - (*iter)->PreDrawCamera(transform_); + detail_object_surface->PreDrawCamera(transform_); } } @@ -1019,15 +1015,15 @@ void CreatePointCloud(std::vector &points, const Model &model, const Image vec3 verts[3]; int face_index = 0; int vert_index; - for(unsigned i=0; i &points, const Model &model, const Image } vec3 center; - for(unsigned i=0; iSetColorTint(GetDisplayTint()); + for(auto & detail_object_surface : detail_object_surfaces){ + detail_object_surface->SetColorTint(GetDisplayTint()); } CalculateDisplayTint_(); break;} case OBJECT_MSG::SET_OVERBRIGHT: { color_tint_component_.ReceiveObjectMessageVAList(type, args); - for(int i=0, len=detail_object_surfaces.size(); iSetOverbright(GetOverbright()); + for(auto & detail_object_surface : detail_object_surfaces){ + detail_object_surface->SetOverbright(GetOverbright()); } CalculateDisplayTint_(); break;} diff --git a/Source/Objects/envobjectattach.cpp b/Source/Objects/envobjectattach.cpp index fa32f75c..36b8e655 100644 --- a/Source/Objects/envobjectattach.cpp +++ b/Source/Objects/envobjectattach.cpp @@ -31,8 +31,7 @@ void Serialize(const std::vector& aeo, std::vector &dat const AttachedEnvObject &attached_env_object = aeo[i]; memwrite(&attached_env_object.direct_ptr, sizeof(attached_env_object.direct_ptr), 1, data); memwrite(&attached_env_object.legacy_obj_id, sizeof(attached_env_object.legacy_obj_id), 1, data); - for(unsigned j=0; j &data, std::vector& attached_env_object.bone_connection_dirty = false; memread(&attached_env_object.direct_ptr, sizeof(attached_env_object.direct_ptr), 1, data, index); memread(&attached_env_object.legacy_obj_id, sizeof(attached_env_object.legacy_obj_id), 1, data, index); - for(unsigned j=0; j* ret_children) { } void Group::GetBottomUpCompleteChildren(std::vector* ret_children) { - for(int i=0, len=children.size(); iGetBottomUpCompleteChildren(ret_children); ret_children->push_back(obj); } } void Group::GetTopDownCompleteChildren(std::vector* ret_children) { - for(int i=0, len=children.size(); ipush_back(obj); } - for(int i=0, len=children.size(); iGetTopDownCompleteChildren(ret_children); } } @@ -99,19 +99,16 @@ void Group::ChildLost(Object *obj){ void Group::FinalizeLoadedConnections() { Object::FinalizeLoadedConnections(); - for(int i=0, len=children.size(); iReceiveObjectMessage(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); + for(auto & i : children){ + i.direct_ptr->ReceiveObjectMessage(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); } } bool Group::SetFromDesc( const EntityDescription &desc ) { bool ret = Object::SetFromDesc(desc); if( ret ) { - for (int i=0, len=desc.children.size(); - iSetParent(this); @@ -134,8 +131,8 @@ bool Group::SetFromDesc( const EntityDescription &desc ) { void Group::GetDesc(EntityDescription &desc) const { Object::GetDesc(desc); desc.AddInt(EDF_VERSION, 1); - for(int i=0, len=children.size(); iGetType() == _group || obj->GetType() == _prefab) && !obj->Selected()){ Group* child_group = (Group*)obj; child_group->InitRelMats(); @@ -156,9 +153,9 @@ void Group::InitRelMats() { } // Get child transforms relative to group transform - for(int i=0, len=children.size(); iGetRotation(); child.rel_translation = (invert(GetRotation()) * ((obj->GetTranslation() - translation_))/scale_); @@ -172,8 +169,8 @@ void Group::InitShape() { return; } - for(int i=0, len=children.size(); iGetType() == _group || obj->GetType() == _prefab) && !obj->Selected()){ Group* child_group = (Group*)obj; child_group->InitShape(); @@ -184,9 +181,9 @@ void Group::InitShape() { static const int MAX_POINTS = 800; int num_points = 0; vec3 points[MAX_POINTS]; - for(int i=0, len=children.size(); iPreDrawFrame(curr_game_time); @@ -251,8 +247,7 @@ void Group::SetTranslationRotationFast(const vec3& trans, const quaternion& rota } void Group::PropagateTransformsDownFast(bool deep) { - for(int i=0, len=children.size(); iSetTranslationRotationFast(translation_ + (GetRotation() * (scale_ * child.rel_translation)), GetRotation() * child.rel_rotation); @@ -265,8 +260,7 @@ void Group::PropagateTransformsDownFast(bool deep) { } void Group::PropagateTransformsDown(bool deep) { - for(int i=0, len=children.size(); iSetScale((invert(child.rel_rotation) * child.rel_scale) * scale_); @@ -288,8 +282,7 @@ void Group::PreDrawCamera(float curr_game_time) { return; } - for(int i=0, len=children.size(); iPreDrawCamera(curr_game_time); @@ -307,8 +300,8 @@ void Group::ChildMoved(Object::MoveType type) { } void Group::UpdateParentHierarchy() { - for(int i=0, len=children.size(); iUpdateParentHierarchy(); + for(auto & i : children){ + i.direct_ptr->UpdateParentHierarchy(); } } @@ -322,8 +315,7 @@ void Group::GetDisplayName(char* buf, int buf_size) { void Group::SetEnabled(bool val) { enabled_ = val; - for(int i=0, len=children.size(); iSetEnabled(val); @@ -333,8 +325,7 @@ void Group::SetEnabled(bool val) { } void Group::HandleTransformationOccured() { - for(int i=0, len=children.size(); iHandleTransformationOccurred(); @@ -361,8 +352,8 @@ void Group::ReceiveObjectMessageVAList( OBJECT_MSG::Type type, va_list args ) { } void Group::RemapReferences(std::map id_map) { - for(int i=0, len=children.size(); iRemapReferences(id_map); + for(auto & i : children){ + i.direct_ptr->RemapReferences(id_map); } } @@ -373,8 +364,8 @@ ObjectSanityState Group::GetSanity() { sanity_flags |= kObjectSanity_G_Empty; } - for( uint32_t i = 0; i < children.size(); i++ ) { - if( children[i].direct_ptr ) { + for(auto & i : children) { + if( i.direct_ptr ) { } else { sanity_flags |= kObjectSanity_G_NullChild; } @@ -393,10 +384,10 @@ ObjectSanityState Group::GetSanity() { std::vector connections; obj->GetConnectionIDs(&connections); - for( uint32_t k = 0; k < connections.size(); k++ ) { + for(int connection : connections) { bool internally_connected = false; for( uint32_t t = 0; t < all_children.size(); t++ ) { - if(all_children[i] && all_children[t]->GetID() == connections[k] ) { + if(all_children[i] && all_children[t]->GetID() == connection ) { internally_connected = true; } } diff --git a/Source/Objects/hotspot.cpp b/Source/Objects/hotspot.cpp index 630baa4d..c4f0db8b 100644 --- a/Source/Objects/hotspot.cpp +++ b/Source/Objects/hotspot.cpp @@ -394,8 +394,7 @@ void Hotspot::ASSetBoolVar( const std::string &name, bool value ) { bool Hotspot::SetFromDesc( const EntityDescription& desc ) { bool ret = Object::SetFromDesc(desc); if( ret ) { - for(unsigned i=0; iReserve(connected_to.size()); - for(size_t i = 0; i < connected_to.size(); ++i) { - array->InsertLast(&connected_to[i]); + for(int & i : connected_to) { + array->InsertLast(&i); } return array; } diff --git a/Source/Objects/itemobject.cpp b/Source/Objects/itemobject.cpp index 50b1a3f2..61f7a5e7 100644 --- a/Source/Objects/itemobject.cpp +++ b/Source/Objects/itemobject.cpp @@ -753,17 +753,15 @@ void ItemObject::AddReader( ItemObjectScriptReader* reader ) { if(reader->holding){ std::list to_invalidate; - for(std::list::iterator iter = readers_.begin(); - iter != readers_.end(); ++iter) + for(auto & reader : readers_) { - if((*iter)->stuck || (*iter)->holding){ - to_invalidate.push_back(*iter); + if(reader->stuck || reader->holding){ + to_invalidate.push_back(reader); } } - for(std::list::iterator iter = to_invalidate.begin(); - iter != to_invalidate.end(); ++iter) + for(auto & iter : to_invalidate) { - (*iter)->Invalidate(); + iter->Invalidate(); } } readers_.push_back(reader); @@ -982,10 +980,9 @@ void ItemObject::GetPhysicsVel( vec3 & linear_vel, vec3 & angular_vel ) bool ItemObject::IsHeld() { bool held = false; - for(std::list::iterator iter = readers_.begin(); - iter != readers_.end(); ++iter) + for(auto & reader : readers_) { - if((*iter)->holding){ + if(reader->holding){ held = true; } } @@ -994,10 +991,9 @@ bool ItemObject::IsHeld() { bool ItemObject::IsConstrained() { bool constrained = false; - for(std::list::iterator iter = readers_.begin(); - iter != readers_.end(); ++iter) + for(auto & reader : readers_) { - if((*iter)->constraint){ + if(reader->constraint){ constrained = true; } } @@ -1006,10 +1002,9 @@ bool ItemObject::IsConstrained() { bool ItemObject::IsStuckInCharacter() { bool stuck = false; - for(std::list::iterator iter = readers_.begin(); - iter != readers_.end(); ++iter) + for(auto & reader : readers_) { - if((*iter)->stuck){ + if(reader->stuck){ stuck = true; } } @@ -1018,11 +1013,10 @@ bool ItemObject::IsStuckInCharacter() { int ItemObject::StuckInWhom() { int stuck_id = -1; - for(std::list::iterator iter = readers_.begin(); - iter != readers_.end(); ++iter) + for(auto & reader : readers_) { - if((*iter)->stuck && (*iter)->char_id != -1){ - stuck_id = (*iter)->char_id; + if(reader->stuck && reader->char_id != -1){ + stuck_id = reader->char_id; } } return stuck_id; @@ -1030,11 +1024,10 @@ int ItemObject::StuckInWhom() { int ItemObject::HeldByWhom() { int held_id = -1; - for(std::list::iterator iter = readers_.begin(); - iter != readers_.end(); ++iter) + for(auto & reader : readers_) { - if((*iter)->holding && (*iter)->char_id != -1){ - held_id = (*iter)->char_id; + if(reader->holding && reader->char_id != -1){ + held_id = reader->char_id; } } return held_id; @@ -1329,8 +1322,7 @@ void ItemObject::DrawItem(const mat4& proj_view_matrix, Object::DrawType type) { std::vector light_volume_matrix; std::vector light_volume_matrix_inverse; - for(int i=0, len=scenegraph_->light_volume_objects_.size(); ilight_volume_objects_[i]; + for(auto obj : scenegraph_->light_volume_objects_){ const mat4 &mat = obj->GetTransform(); light_volume_matrix.push_back(mat); light_volume_matrix_inverse.push_back(invert(mat)); @@ -1413,8 +1405,7 @@ void ItemObject::InvalidateHeldReaders() { bool ItemObject::SetFromDesc( const EntityDescription& desc ) { bool ret = Object::SetFromDesc(desc); if( ret ) { - for(unsigned i=0; i* ret_children) { std::vector attached_env_objects; Deserialize(env_object_attach_data, attached_env_objects); ret_children->reserve(attached_env_objects.size()); - for(int i=0, len=attached_env_objects.size(); ipush_back(attached_env_objects[i].direct_ptr); + ret_children->push_back(attached_env_object.direct_ptr); } } } @@ -135,11 +135,11 @@ void MovementObject::GetBottomUpCompleteChildren(std::vector* ret_child std::vector attached_env_objects; Deserialize(env_object_attach_data, attached_env_objects); ret_children->reserve(attached_env_objects.size()); - for(int i=0, len=attached_env_objects.size(); iGetBottomUpCompleteChildren(ret_children); - ret_children->push_back(attached_env_objects[i].direct_ptr); + ret_children->push_back(attached_env_object.direct_ptr); } } } @@ -209,8 +209,7 @@ void MovementObject::PreDrawFrame(float curr_game_time) { } else { if (attached_env_object.bone_connection_dirty) { - for (unsigned i = 0; i < kMaxBoneConnects; ++i) { - BoneConnect& bone_connect = attached_env_object.bone_connects[i]; + for (auto & bone_connect : attached_env_object.bone_connects) { if (bone_connect.bone_id != -1) { mat4 transform_mat = rigged_object_->display_bone_transforms[bone_connect.bone_id].GetMat4(); mat4 env_mat = Mat4FromQuaternion(obj->GetRotation()); @@ -240,14 +239,13 @@ const float kCullRadius = 2.0f; void MovementObject::ActualPreDraw(float curr_game_time) { bool dirty_attachment = false; - for(int i=0, len=rigged_object_->children.size(); ichildren[i].bone_connection_dirty){ + for(auto & i : rigged_object_->children){ + if(i.bone_connection_dirty){ dirty_attachment = true; } } rigged_object_->PreDrawFrame(curr_game_time); - for(int i=0, len=rigged_object_->children.size(); ichildren[i]; + for(auto & child : rigged_object_->children){ Object* obj = child.direct_ptr; if(obj){ obj->PreDrawFrame(curr_game_time); @@ -356,12 +354,10 @@ void MovementObject::DrawDepthMap(const mat4& proj_view_matrix, const vec4* cull if(!culled){ // Check if character is occluded from pov of active camera bool occluded = false; - for(int state_index=0, state_len=occlusion_states.size(); - state_index < state_len; - ++state_index) + for(auto & occlusion_state : occlusion_states) { - if(occlusion_states[state_index].cam_id == ActiveCameras::GetID()){ - occluded = occlusion_states[state_index].occluded; + if(occlusion_state.cam_id == ActiveCameras::GetID()){ + occluded = occlusion_state.occluded; break; } } @@ -395,8 +391,8 @@ void MovementObject::PreDrawCamera(float curr_game_time) { { PROFILER_ZONE(g_profiler_ctx, "Process occlusion queries"); - for(int query_index=0, num_queries=occlusion_queries.size(); query_indexin_progress){ continue; } @@ -435,12 +431,10 @@ void MovementObject::PreDrawCamera(float curr_game_time) { } // Check if character is occluded from pov of active camera - for(int state_index=0, state_len=occlusion_states.size(); - state_index < state_len; - ++state_index) + for(auto & occlusion_state : occlusion_states) { - if(occlusion_states[state_index].cam_id == ActiveCameras::GetID()){ - occluded = occlusion_states[state_index].occluded; + if(occlusion_state.cam_id == ActiveCameras::GetID()){ + occluded = occlusion_state.occluded; break; } } @@ -483,12 +477,10 @@ void MovementObject::Draw() { // Check if character is occluded from pov of active camera bool occluded = false; if( g_perform_occlusion_query ) { - for(int state_index=0, state_len=occlusion_states.size(); - state_index < state_len; - ++state_index) + for(auto & occlusion_state : occlusion_states) { - if(occlusion_states[state_index].cam_id == ActiveCameras::GetID()){ - occluded = occlusion_states[state_index].occluded; + if(occlusion_state.cam_id == ActiveCameras::GetID()){ + occluded = occlusion_state.occluded; break; } } @@ -578,10 +570,8 @@ void MovementObject::Draw() { } } std::list &ic = item_connections; - for(std::list::iterator iter = ic.begin(); - iter != ic.end(); ++iter) + for(auto & item : ic) { - ItemObjectScriptReader& item = (*iter); if(item.valid()){ DebugDraw::Instance()->AddLine(GetTranslation(), item->GetTranslation(), @@ -949,9 +939,9 @@ void MovementObject::Update(float timestep) { if (!rigged_object_->animated) { velocity = rigged_object_->GetAvgVelocity(); } - for (unsigned i = 0; i < attached_sounds.size(); ++i) { - si->SetOcclusionPosition(attached_sounds[i], position); - si->TranslatePosition(attached_sounds[i], velocity * timestep); + for (unsigned long & attached_sound : attached_sounds) { + si->SetOcclusionPosition(attached_sound, position); + si->TranslatePosition(attached_sound, velocity * timestep); //DebugDraw::Instance()->AddWireSphere(si->GetPosition(attached_sounds[i]), 1.0f, vec4(1.0f), _delete_on_update); } @@ -1457,10 +1447,10 @@ void MovementObject::CreateRiggedObject(){ } //} - for(unsigned i=0; iResetGlobals(); as_context->CallScriptFunction(as_funcs.set_parameters); as_context->CallScriptFunction(as_funcs.post_reset); - for(std::list::iterator iter = item_connections.begin(); - iter != item_connections.end(); ++iter) + for(auto & item_connection : item_connections) { - ItemObjectScriptReader &item_connection = (*iter); if(item_connection.attachment_type != _at_unspecified){ int which = item_connection->GetID(); AttachmentType type = item_connection.attachment_type; @@ -4477,9 +4465,7 @@ void MovementObject::FinalizeLoadedConnections() { } } - for(unsigned i=0; i item_connections_vec; - for(std::list::const_iterator iter = item_connections.begin(); - iter != item_connections.end(); ++iter) + for(const auto & script_reader : item_connections) { - const ItemObjectScriptReader& script_reader = (*iter); ItemConnectionData item_connection; item_connection.id = script_reader->GetID(); item_connection.attachment_type = script_reader.attachment_type; @@ -4565,8 +4549,8 @@ void MovementObject::GetDesc(EntityDescription &desc) const { Serialize(rigged_object_->children, temp_env_object_attach_data); desc.AddData(EDF_ENV_OBJECT_ATTACH, temp_env_object_attach_data); } - for(int i=0, len=rigged_object_->children.size(); ichildren[i].direct_ptr; + for(auto & i : rigged_object_->children){ + Object* env_obj = i.direct_ptr; if(env_obj){ desc.children.resize(desc.children.size()+1); env_obj->GetDesc(desc.children.back()); @@ -4718,8 +4702,8 @@ void MovementObject::Dispose() { as_context.reset(NULL); rigged_object_->as_context = NULL; - for(int i=0, len=occlusion_queries.size(); i item_connections; field.ReadItemConnectionDataVec(&item_connections); - for(int i=0, len=item_connections.size(); iGetAssetManager()->LoadSync(item_connections[i].attachment_str); + item_connection.id = i.id; + item_connection.mirrored = i.mirrored != 0; + item_connection.attachment_type = (AttachmentType)i.attachment_type; + if(!i.attachment_str.empty()){ + item_connection.attachment_ref = Engine::Instance()->GetAssetManager()->LoadSync(i.attachment_str); if( item_connection.attachment_ref.valid() == false ) { - LOGE << "Unable to load attachment " << item_connections[i].attachment_str << std::endl; + LOGE << "Unable to load attachment " << i.attachment_str << std::endl; } } item_connection_vec.push_back(item_connection); @@ -4822,8 +4805,8 @@ bool MovementObject::SetFromDesc( const EntityDescription &desc ) { if(!env_object_attach_data.empty()){ std::vector attached_env_objects; Deserialize(env_object_attach_data, attached_env_objects); - for (int i=0, len=attached_env_objects.size(); isecond; + total += iter.second; } transition_probability = num / total; } diff --git a/Source/Objects/navmeshconnectionobject.cpp b/Source/Objects/navmeshconnectionobject.cpp index e19f3b42..ff39081d 100644 --- a/Source/Objects/navmeshconnectionobject.cpp +++ b/Source/Objects/navmeshconnectionobject.cpp @@ -57,8 +57,8 @@ bool NavmeshConnectionObject::ConnectTo( Object& other, bool checking_other /*= return false; } else { int other_id = ppo->GetID(); - for(unsigned i=0; i* cons) { - for( uint32_t i = 0; i < connections.size(); i++ ) { - cons->push_back(connections[i].other_object_id); + for(auto & connection : connections) { + cons->push_back(connection.other_object_id); } } @@ -190,8 +190,7 @@ bool NavmeshConnectionObject::SetFromDesc( const EntityDescription& desc ) { bool ret = Object::SetFromDesc(desc); if( ret ) { //Keeping this to maintain compatability for now. There shouldn't be any alphas running this though. - for(unsigned i=0; iGetObjectFromID(connections[i].other_object_id); + for(auto & connection : connections){ + Object* obj = scenegraph_->GetObjectFromID(connection.other_object_id); if(obj){ obj->ConnectTo(*this, true); } @@ -337,20 +336,20 @@ void NavmeshConnectionObject::FinalizeLoadedConnections() { } void NavmeshConnectionObject::RemapReferences(std::map id_map) { - for(int i=0, len=connections.size(); i::iterator iter = id_map.begin(); iter != id_map.end(); ++iter) { - if(iter->second == this->GetID()) { + for(auto & iter : id_map) { + if(iter.second == this->GetID()) { is_this = true; break; } } if(!is_this) - connections[i].other_object_id = -1; + connection.other_object_id = -1; } } } diff --git a/Source/Objects/object.cpp b/Source/Objects/object.cpp index e6ffac73..68e60b17 100644 --- a/Source/Objects/object.cpp +++ b/Source/Objects/object.cpp @@ -192,8 +192,7 @@ void Object::SaveToXML( TiXmlElement* parent ) { } bool Object::SetFromDesc( const EntityDescription& desc ) { - for(unsigned i=0; iGetObjectFromID(unfinalized_connected_to[i]); + for(int & i : unfinalized_connected_to) { + Object* object = scenegraph_->GetObjectFromID(i); if(object) { if(!ConnectTo(*object, false)) { - LOGW << "Failed to connect to the object with id " << unfinalized_connected_to[i] << " after loading" << std::endl; + LOGW << "Failed to connect to the object with id " << i << " after loading" << std::endl; } } else { - LOGW << "Connected to an invalid id " << unfinalized_connected_to[i] << " after loading" << std::endl; + LOGW << "Connected to an invalid id " << i << " after loading" << std::endl; } } - for(size_t i = 0; i < unfinalized_connected_from.size(); ++i) { - Object* object = scenegraph_->GetObjectFromID(unfinalized_connected_from[i]); + for(int & i : unfinalized_connected_from) { + Object* object = scenegraph_->GetObjectFromID(i); if(object) { if(!object->ConnectTo(*this, false)) { - LOGW << "Failed to connect to the object with id " << unfinalized_connected_from[i] << " after loading" << std::endl; + LOGW << "Failed to connect to the object with id " << i << " after loading" << std::endl; } } else { - LOGW << "Connected to an invalid id " << unfinalized_connected_from[i] << " after loading" << std::endl; + LOGW << "Connected to an invalid id " << i << " after loading" << std::endl; } } diff --git a/Source/Objects/pathpointobject.cpp b/Source/Objects/pathpointobject.cpp index 22fefbc2..46f4aa7d 100644 --- a/Source/Objects/pathpointobject.cpp +++ b/Source/Objects/pathpointobject.cpp @@ -57,8 +57,8 @@ bool PathPointObject::ConnectTo( Object& other, bool checking_other /*= false*/ return false; } else { int other_id = ppo->GetID(); - for(unsigned i=0; i* cons) { - for( uint32_t i = 0; i < connection_ids.size(); i++ ) { - cons->push_back(connection_ids[i]); + for(int & connection_id : connection_ids) { + cons->push_back(connection_id); } } @@ -126,8 +126,7 @@ void PathPointObject::GetDesc(EntityDescription &desc) const { bool PathPointObject::SetFromDesc( const EntityDescription& desc ) { bool ret = Object::SetFromDesc(desc); if( ret ) { - for(unsigned i=0; imap_editor->state_ != MapEditor::kInGame) { DebugDraw::Instance()->AddWireSphere(GetTranslation(), 0.5f, vec4(0.0f,0.5f,0.5f,0.5f), _delete_on_draw); - for(unsigned i=0; iGetObjectFromID(connection_ids[i]); + for(int connection_id : connection_ids){ + Object* obj = scenegraph_->GetObjectFromID(connection_id); DebugDraw::Instance()->AddLine(GetTranslation(), obj->GetTranslation(), vec4(0.0f,0.5f,0.5f,0.5f), _delete_on_draw); } } } void PathPointObject::RemapReferences(std::map id_map) { - for( unsigned i = 0; i < connection_ids.size(); i++ ) { - if( id_map.find(connection_ids[i]) != id_map.end() ) { - connection_ids[i] = id_map[connection_ids[i]]; + for(int & connection_id : connection_ids) { + if( id_map.find(connection_id) != id_map.end() ) { + connection_id = id_map[connection_id]; } else { //The remapped id could belong to this, in which case it is valid bool is_this = false; - for(std::map::iterator iter = id_map.begin(); iter != id_map.end(); ++iter) { - if(iter->second == this->GetID()) { + for(auto & iter : id_map) { + if(iter.second == this->GetID()) { is_this = true; break; } } if(!is_this) - connection_ids[i] = -1; + connection_id = -1; } } } diff --git a/Source/Objects/placeholderobject.cpp b/Source/Objects/placeholderobject.cpp index 8253354d..37749ab9 100644 --- a/Source/Objects/placeholderobject.cpp +++ b/Source/Objects/placeholderobject.cpp @@ -61,8 +61,8 @@ PlaceholderObject::PlaceholderObject(): } void PlaceholderObject::DisposePreviewObjects() { - for(unsigned i=0, len=preview_objects_.size(); i < len; ++i){ - delete preview_objects_[i]; + for(auto & preview_object : preview_objects_){ + delete preview_object; } preview_objects_.clear(); } @@ -78,8 +78,8 @@ void PlaceholderObject::SetPreview( const std::string& path ) { Path source; ActorsEditor_LoadEntitiesFromFile(path, desc_list,&file_type, &source); preview_objects_.reserve(desc_list.size()); - for(unsigned i=0, len=desc_list.size(); i < len; ++i){ - Object* obj = CreateObjectFromDesc(desc_list[i]); + for(auto & i : desc_list){ + Object* obj = CreateObjectFromDesc(i); if(obj) { if(obj->GetType() == _env_object){ EnvObject* eo = (EnvObject*)obj; @@ -124,9 +124,9 @@ void PlaceholderObject::Draw() { } bool old_shadow_cache_dirty = shadow_cache_dirty; - for(unsigned i=0, len=preview_objects_.size(); i < len; ++i){ - preview_objects_[i]->SetTransformationMatrix(GetTransform()); - preview_objects_[i]->ReceiveObjectMessage(OBJECT_MSG::DRAW); + for(auto & preview_object : preview_objects_){ + preview_object->SetTransformationMatrix(GetTransform()); + preview_object->ReceiveObjectMessage(OBJECT_MSG::DRAW); } shadow_cache_dirty = old_shadow_cache_dirty; // We don't want to update static shadow maps just because we moved this preview object @@ -187,8 +187,7 @@ bool PlaceholderObject::SetFromDesc( const EntityDescription& desc ) { SetBillboard("Data/UI/spawner/thumbs/Utility/placeholder_arena_battle.png"); } - for(unsigned i=0; iscenegraph_ = scenegraph_; obj->Initialize(); } diff --git a/Source/Objects/reflectioncaptureobject.cpp b/Source/Objects/reflectioncaptureobject.cpp index 6487360a..0bc00a6c 100644 --- a/Source/Objects/reflectioncaptureobject.cpp +++ b/Source/Objects/reflectioncaptureobject.cpp @@ -133,8 +133,7 @@ void ReflectionCaptureObject::GetDesc(EntityDescription &desc) const { bool ReflectionCaptureObject::SetFromDesc( const EntityDescription& desc ) { bool ret = Object::SetFromDesc(desc); if( ret ) { - for(unsigned i=0; iDeleteModel(model_id[i]); + for(int i : model_id){ + Models::Instance()->DeleteModel(i); } - for(unsigned i=0; i 1e-4 || std::abs(c - d) > 1e-4) { - network_morphs[j].mod_weight = morph_targets[i].mod_weight; - network_morphs[j].disp_weight = morph_targets[i].disp_weight; - network_morphs[j].dirty = true; + network_morph.mod_weight = morph_target.mod_weight; + network_morph.disp_weight = morph_target.disp_weight; + network_morph.dirty = true; } } @@ -550,8 +549,8 @@ void RiggedObject::PreDrawCamera(float curr_game_time) { } PROFILER_ZONE(g_profiler_ctx, "RiggedObject::PreDraw"); - for(int i=0; i<4; ++i){ - need_vbo_update[i] = true; + for(bool & i : need_vbo_update){ + i = true; } Graphics::Instance()->setGLState(rigged_object_gl_state.gl_state); @@ -768,8 +767,8 @@ void RiggedObject::Draw(const mat4& proj_view_matrix, Object::DrawType type) { shaders->SetUniformVec3("blood_tint", vec3(-1,-1,-1)); // Presumably this is here to force refreshing this uniform? shaders->SetUniformVec3("blood_tint", Graphics::Instance()->config_.blood_color()); std::vector ambient_cube_color_vec; - for(int i=0; i<6; ++i){ - ambient_cube_color_vec.push_back(ambient_cube_color[i]); + for(auto & i : ambient_cube_color){ + ambient_cube_color_vec.push_back(i); } shaders->SetUniformVec3Array("ambient_cube_color", ambient_cube_color_vec); shaders->SetUniformVec3Array("tint_palette", palette_colors_srgb); @@ -795,8 +794,7 @@ void RiggedObject::Draw(const mat4& proj_view_matrix, Object::DrawType type) { std::vector light_volume_matrix; std::vector light_volume_matrix_inverse; - for(int i=0, len=scenegraph_->light_volume_objects_.size(); ilight_volume_objects_[i]; + for(auto obj : scenegraph_->light_volume_objects_){ const mat4 &mat = obj->GetTransform(); light_volume_matrix.push_back(mat); light_volume_matrix_inverse.push_back(invert(mat)); @@ -925,8 +923,8 @@ void RiggedObject::Draw(const mat4& proj_view_matrix, Object::DrawType type) { vel_vbo.Fill(model_num_verts*3*sizeof(GLfloat), &vel[0]); } else { PROFILER_ZONE(g_profiler_ctx, "Calculate null vertex velocities"); - for(int i=0, len=vel.size(); i 0){ --bone_connect.num_connections; } @@ -1138,12 +1132,11 @@ bool RiggedObject::DrawBoneConnectUI(Object* objects[], int num_obj_ids, IMUICon DebugDraw::Instance()->AddLine(start, end, bone_color, _delete_on_draw, _DD_XRAY); } - for(unsigned i=0; iSelected()){ - for(unsigned j=0; j 0){ int bone_id = bone_connect.bone_id; const Bone& bone = skeleton_.bones[skeleton_.physics_bones[bone_id].bone]; @@ -1268,13 +1261,13 @@ void RiggedObject::Update(float timestep) { } first_ragdoll_frame = false; // Updated attached items - for(AttachedItemList::iterator iter = attached_items.items.begin(); iter != attached_items.items.end(); ++iter) { - UpdateAttachedItemRagdoll(*iter, skeleton_, weapon_offset); + for(auto & item : attached_items.items) { + UpdateAttachedItemRagdoll(item, skeleton_, weapon_offset); } // Make sure attached items are not asleep if skeleton is awake - for(AttachedItemList::iterator iter = stuck_items.items.begin(); iter != stuck_items.items.end(); ++iter) { + for(auto & item : stuck_items.items) { if(skeleton_.physics_bones[0].bullet_object->IsActive()){ - iter->item->WakeUpPhysics(); + item.item->WakeUpPhysics(); } } } @@ -1284,8 +1277,8 @@ void RiggedObject::Update(float timestep) { --prev_anim_update_time; if(time_until_next_anim_update <= 0) { - for(unsigned i=0; i morph_target_names; - for(unsigned i=0; ianim_weight = @@ -1345,11 +1337,11 @@ void RiggedObject::Update(float timestep) { PROFILER_ZONE(g_profiler_ctx, "anim_client.GetMatrices()"); anim_client.GetMatrices(anim_output, &skeleton_.parents); } - for(int i=0, len=anim_output.matrices.size(); isecond; + for(auto & iter : weap_anim_info_map) { + WeapAnimInfo &weap_anim_info = iter.second; if(weap_anim_info.relative_id == -1){ weap_anim_info.bone_transform = rotmat4 * weap_anim_info.bone_transform; } @@ -1384,11 +1376,11 @@ void RiggedObject::Update(float timestep) { transforms[i].origin += total_center_offset; animation_frame_bone_matrices[i] = transforms[i]; } - for(int i=0, len=anim_output.ik_bones.size(); i::iterator iter = weap_anim_info_map.begin(); iter != weap_anim_info_map.end(); ++iter) { - WeapAnimInfo &weap_anim_info = iter->second; + for(auto & iter : weap_anim_info_map) { + WeapAnimInfo &weap_anim_info = iter.second; if(weap_anim_info.relative_id == -1){ weap_anim_info.bone_transform.origin += total_center_offset; } else { @@ -1398,11 +1390,10 @@ void RiggedObject::Update(float timestep) { // Apply animation morphs std::map morph_target_names; - for(unsigned i=0; ianim_weight = skb.weight*skb.weight_weight; @@ -1411,8 +1402,7 @@ void RiggedObject::Update(float timestep) { // Apply status keys status_keys.clear(); - for(unsigned i=0; iitem; + for(auto & iter : attached_items.items) { + ItemObjectScriptReader& item = iter.item; item.SetInterpInfo(GetTimeSinceLastAnimUpdate(), GetTimeBetweenLastTwoAnimUpdates()); } - for(AttachedItemList::iterator iter=stuck_items.items.begin(); iter != stuck_items.items.end(); ++iter) { - iter->item.SetInterpInfo(GetTimeSinceLastAnimUpdate(), GetTimeBetweenLastTwoAnimUpdates()); + for(auto & item : stuck_items.items) { + item.item.SetInterpInfo(GetTimeSinceLastAnimUpdate(), GetTimeBetweenLastTwoAnimUpdates()); } } } @@ -1498,14 +1488,13 @@ namespace { { std::vector sm_vertices(sm.vertices.size()); std::vector sm_tex_coords(sm.tex_coords.size()); - for(int i=0, len=vert_parent.size(); i 0.0f){ int parent_vert = sm.old_vert_id[pr.id]; int parent_vert_index = parent_vert*3; @@ -1514,29 +1503,28 @@ namespace { } } } - for(WOLFIRE_SIMPLIFY::ParentRecordList::iterator iter = parents.begin(); iter != parents.end(); ++iter){ - WOLFIRE_SIMPLIFY::ParentRecord pr = (*iter); + for(auto & parent : parents){ + WOLFIRE_SIMPLIFY::ParentRecord pr = parent; int parent_vert_index = pr.id*3; for(int j=0; j<3; ++j){ sm_vertices[parent_vert_index+j] = total[j]; } } } - for(int i=0, len=tex_parent.size(); iApplyTransform(transform); + physics_bone.bullet_object->ApplyTransform(transform); } ik_offset.resize(skeleton_.physics_bones.size()); @@ -1656,9 +1644,9 @@ void RiggedObject::Load(const std::string& character_path, vec3 pos, SceneGraph* } const std::vector &morphs = char_ref->GetMorphs(); - for(unsigned i=0; imodel_name, the_model_id, morphs[i].label, morphs[i].num_steps); + mt.Load(ofc->model_name, the_model_id, morph.label, morph.num_steps); morph_targets.push_back(mt); } @@ -1708,15 +1696,14 @@ void RiggedObject::Load(const std::string& character_path, vec3 pos, SceneGraph* bone_weight.clear(); bone_id.resize(sm.vertices.size()/3, 0.0f); bone_weight.resize(sm.vertices.size()/3, 0.0f); - for(int i=0, len=vert_parent.size(); i 0.0f){ int parent_vert = sm.old_vert_id[pr.id]; int parent_vert_index = parent_vert*3; @@ -1756,18 +1743,16 @@ void RiggedObject::Load(const std::string& character_path, vec3 pos, SceneGraph* } // Normalize weights to add up to 1.0 float total_weight = 0.0f; - for(int i=0,len=bone_info_accumulate.size(); i queue; - for(unsigned i=0; iAddModel(); @@ -1846,8 +1830,8 @@ void RiggedObject::Load(const std::string& character_path, vec3 pos, SceneGraph* morph_model.CopyVertCollapse(model); } } - for(unsigned i=0; ipath_); @@ -1913,9 +1897,9 @@ bool RiggedObject::InHeadChain(BulletObject* obj) { void RiggedObject::InvalidatedItem(ItemObjectScriptReader *invalidated) { int weap_id = -1; - for(AttachedItemList::iterator iter = attached_items.items.begin(); iter != attached_items.items.end(); ++iter) { - if(&(iter->item) == invalidated){ - weap_id = (iter->item)->GetID(); + for(auto & item : attached_items.items) { + if(&(item.item) == invalidated){ + weap_id = (item.item)->GetID(); break; } } @@ -2058,12 +2042,11 @@ void RiggedObject::SetItemAttachment(AttachedItem &stuck_item, AttachmentRef att void RiggedObject::SheatheItem(int id, bool on_right){ AttachedItem *item_ptr = NULL; - for(std::list::iterator iter = attached_items.items.begin(); - iter != attached_items.items.end(); ++iter) + for(auto & iter : attached_items.items) { - ItemObjectScriptReader& item = iter->item; + ItemObjectScriptReader& item = iter.item; if(item->GetID() == id){ - item_ptr = &(*iter); + item_ptr = &iter; } } if(!item_ptr){ @@ -2079,12 +2062,11 @@ void RiggedObject::SheatheItem(int id, bool on_right){ void RiggedObject::UnSheatheItem(int id, bool right_hand){ AttachedItem *item_ptr = NULL; - for(std::list::iterator iter = attached_items.items.begin(); - iter != attached_items.items.end(); ++iter) + for(auto & iter : attached_items.items) { - ItemObjectScriptReader& item = iter->item; + ItemObjectScriptReader& item = iter.item; if(item->GetID() == id){ - item_ptr = &(*iter); + item_ptr = &iter; } } if(!item_ptr){ @@ -2108,10 +2090,9 @@ void RiggedObject::DetachAllItems(){ attached_items.RemoveAll(); char_anim.clear(); - for(std::list::iterator iter = stuck_items.items.begin(); - iter != stuck_items.items.end(); ++iter) + for(auto & item : stuck_items.items) { - iter->item->ActivatePhysics(); + item.item->ActivatePhysics(); } stuck_items.items.clear(); } @@ -2162,8 +2143,7 @@ void RiggedObject::ApplyBoneMatricesToModel(bool old, int lod_level) { const bool kMorphTargetsEnabled = true; if(kMorphTargetsEnabled){ // Determine which morphs are active (have effective weight > 0) - for(unsigned k=0; kIsClient() || m_t.weight > 0.0f || (m_t.anim_weight > 0.0f && m_t.script_weight_weight < 1.0f) || (m_t.script_weight > 0.0f && m_t.script_weight_weight > 0.0f)) @@ -2184,13 +2164,11 @@ void RiggedObject::ApplyBoneMatricesToModel(bool old, int lod_level) { // Accumulate the effect of all active morphs Models *mi = Models::Instance(); int vert_id, vert_id_index; - for(unsigned k=0, len=active_morph_targets.size(); kGetModel(morph->model_id[lod_level]); const std::vector &modified_tc = morph->modified_tc[lod_level]; - for(unsigned j=0, len2=modified_tc.size(); jtex_transform_vec[vert_id] += vec2(morph_model->tex_coords[vert_id_index+0], @@ -2199,8 +2177,8 @@ void RiggedObject::ApplyBoneMatricesToModel(bool old, int lod_level) { } const std::vector &modified_vert = morph->modified_verts[lod_level]; - for(unsigned j=0,len2=modified_vert.size(); jIsClient()) { @@ -2290,9 +2268,9 @@ void MorphTarget::SetScriptWeight(float weight, float weight_weight) { } void RiggedObject::SetMTTargetWeight( const std::string &target_name, float weight, float weight_weight ) { - for(unsigned i=0; iFixDiscontinuity(); + for(auto & physics_bone : skeleton_.physics_bones){ + if(physics_bone.bullet_object){ + physics_bone.bullet_object->FixDiscontinuity(); } } } @@ -2510,8 +2488,8 @@ void RiggedObject::FixDiscontinuity() { void RiggedObject::RefreshRagdoll() { if(!animated){ - for(unsigned i=0; i::iterator iter = stuck_items.items.begin(); - iter != stuck_items.items.end(); ++iter) + for(auto & item : stuck_items.items) { - iter->item.ActivatePhysics(); - iter->item.AddConstraint(skeleton_.physics_bones[iter->bone_id].bullet_object); + item.item.ActivatePhysics(); + item.item.AddConstraint(skeleton_.physics_bones[item.bone_id].bullet_object); } } } void RiggedObject::SetDamping(float amount){ - for(unsigned i=0; i= 1.0f){ - for(std::list::iterator iter = stuck_items.items.begin(); - iter != stuck_items.items.end(); ++iter) + for(auto & item : stuck_items.items) { - iter->item->SleepPhysics(); + item.item->SleepPhysics(); } } } @@ -2573,10 +2549,9 @@ void RiggedObject::SetDamping(float amount){ void RiggedObject::UnRagdoll() { //mat4 inv_transform = invert(GetTransformationMatrix()); if(!animated){ - for(std::list::iterator iter = stuck_items.items.begin(); - iter != stuck_items.items.end(); ++iter) + for(auto & item : stuck_items.items) { - iter->item.RemoveConstraint(); + item.item.RemoveConstraint(); } anim_client.Reset(); @@ -2594,12 +2569,12 @@ vec3 RiggedObject::GetAvgPosition() { vec3 total(0.0f); int num_total = 0; - for(unsigned i=0; iGetPosition(); + total += physics_bone.bullet_object->GetPosition(); } total /= (float)num_total; @@ -2611,14 +2586,14 @@ vec3 RiggedObject::GetAvgVelocity() { vec3 total(0.0f); float divisor = 0.0f; - for(unsigned i=0; ilinked){ + for(auto & physics_bone : skeleton_.physics_bones){ + if(!physics_bone.bullet_object || + !physics_bone.bullet_object->linked){ continue; } - const float mass = skeleton_.physics_bones[i].bullet_object->GetMass(); + const float mass = physics_bone.bullet_object->GetMass(); divisor += mass; - total += skeleton_.physics_bones[i].bullet_object->GetLinearVelocity() * mass; + total += physics_bone.bullet_object->GetLinearVelocity() * mass; } total /= divisor; @@ -2629,14 +2604,14 @@ vec3 RiggedObject::GetAvgVelocity() vec3 RiggedObject::GetAvgAngularVelocity() { vec3 total(0.0f); float divisor = 0.0f; - for(unsigned i=0; ilinked){ + for(auto & physics_bone : skeleton_.physics_bones){ + if(!physics_bone.bullet_object || + !physics_bone.bullet_object->linked){ continue; } - total += skeleton_.physics_bones[i].bullet_object->GetAngularVelocity() * - skeleton_.physics_bones[i].bullet_object->GetMass(); - divisor += skeleton_.physics_bones[i].bullet_object->GetMass(); + total += physics_bone.bullet_object->GetAngularVelocity() * + physics_bone.bullet_object->GetMass(); + divisor += physics_bone.bullet_object->GetMass(); } total /= divisor; @@ -2648,11 +2623,11 @@ vec3 RiggedObject::GetAvgAngularVelocity() { quaternion RiggedObject::GetAvgRotation() { quaternion total; - for(unsigned i=0; iGetRotation() * invert(bone.initial_rotation); total += QuaternionFromMat4(rotation) * bone.bullet_object->GetMass(); @@ -2677,18 +2652,18 @@ vec3 RiggedObject::GetIKTargetPosition( const std::string &target_name ) } float RiggedObject::GetIKWeight( const std::string &target_name ) { - for(unsigned i=0; iblended_bone_paths.size(); ++i){ - if(rigged_object->blended_bone_paths[i].ik_bone.label == target_name){ - return rigged_object->blended_bone_paths[i].transform; + for(auto & blended_bone_path : rigged_object->blended_bone_paths){ + if(blended_bone_path.ik_bone.label == target_name){ + return blended_bone_path.transform; } } BoneTransform identity; @@ -2696,9 +2671,9 @@ BoneTransform GetIKTransform( RiggedObject* rigged_object, const std::string &ta } mat4 GetUnmodifiedIKTransform( RiggedObject* rigged_object, const std::string &target_name ) { - for(unsigned i=0; iblended_bone_paths.size(); ++i){ - if(rigged_object->blended_bone_paths[i].ik_bone.label == target_name){ - return rigged_object->blended_bone_paths[i].unmodified_transform.GetMat4(); + for(auto & blended_bone_path : rigged_object->blended_bone_paths){ + if(blended_bone_path.ik_bone.label == target_name){ + return blended_bone_path.unmodified_transform.GetMat4(); } } mat4 identity; @@ -2706,9 +2681,9 @@ mat4 GetUnmodifiedIKTransform( RiggedObject* rigged_object, const std::string &t } vec3 RiggedObject::GetIKTargetAnimPosition( const std::string &target_name ) { - for(unsigned i=0; iCopyModel(base_model_id); Model& model = Models::Instance()->GetModel(model_id[0]); - for(int i=0, len=(int)model.vertices.size(); ivertices[index+0]; model.vertices[index+1] = the_model->vertices[index+1]; model.vertices[index+2] = the_model->vertices[index+2]; } - for(unsigned j=0; jtex_coords[tc_index+0]; model.tex_coords[tc_index+1] = the_model->tex_coords[tc_index+1]; } } else { - for(unsigned j=0; jDeleteModel(model_id[i]); } } - for(unsigned i=0; iowner_object = owner; + physics_bone.bullet_object->owner_object = owner; } } @@ -3109,18 +3083,18 @@ vec3 RiggedObject::GetIKChainPos( const std::string &target_name, int which ) void RiggedObject::EnableSleep() { - for(unsigned i=0; iCanSleep(); + for(auto & physics_bone : skeleton_.physics_bones){ + if(physics_bone.bullet_object){ + physics_bone.bullet_object->CanSleep(); } } } void RiggedObject::DisableSleep() { - for(unsigned i=0; iNoSleep(); + for(auto & physics_bone : skeleton_.physics_bones){ + if(physics_bone.bullet_object){ + physics_bone.bullet_object->NoSleep(); } } } @@ -3136,11 +3110,11 @@ void RiggedObject::HandleLipSyncMorphTargets(float timestep) { const std::map &mw = lipsync_reader.GetMorphWeights(); std::map::const_iterator iter; for(iter = mw.begin(); iter != mw.end(); ++iter){ - for(unsigned i=0; ifirst){ - morph_targets[i].script_weight = - mix(morph_targets[i].script_weight, iter->second, 0.5f); - morph_targets[i].script_weight_weight = 1.0f; + for(auto & morph_target : morph_targets){ + if(morph_target.name == iter->first){ + morph_target.script_weight = + mix(morph_target.script_weight, iter->second, 0.5f); + morph_target.script_weight_weight = 1.0f; break; } } @@ -3148,9 +3122,9 @@ void RiggedObject::HandleLipSyncMorphTargets(float timestep) { lipsync_reader.Update(timestep); if(!lipsync_reader.valid()){ for(iter = mw.begin(); iter != mw.end(); ++iter){ - for(unsigned i=0; ifirst){ - morph_targets[i].script_weight_weight = 0.0f; + for(auto & morph_target : morph_targets){ + if(morph_target.name == iter->first){ + morph_target.script_weight_weight = 0.0f; break; } } @@ -3210,10 +3184,9 @@ void RiggedObject::SetCharAnim( const std::string &path, char flags, const std:: const float _item_blend_fade_speed = 5.0f; void RiggedObject::CheckItemAnimBlends(const std::string &path, char flags) { anim_client.ClearBlendAnimation(); - for(std::list::iterator iter = attached_items.items.begin(); - iter != attached_items.items.end(); ++iter) + for(auto & iter : attached_items.items) { - ItemObjectScriptReader& item = iter->item; + ItemObjectScriptReader& item = iter.item; if(item->item_ref()->HasAnimBlend(path) && item->state() == ItemObject::kWielded){ const std::string &a_path = item->item_ref()->GetAnimBlend(path); anim_client.SetBlendAnimation(a_path); @@ -3255,8 +3228,8 @@ void RiggedObject::MPCutPlane(const vec3 & normal, const vec3 & pos, const vec3 } else { //blood_surface.AddBloodToTriangles(hit_list); - for (unsigned i = 0; i < hit_list.size(); ++i) { - GetTransformedTri(hit_list[i], mp_points); + for (int i : hit_list) { + GetTransformedTri(i, mp_points); if (dot(cross(mp_points[1] - mp_points[0], mp_points[2] - mp_points[0]), dir) > 0.0f) { continue; } @@ -3270,8 +3243,8 @@ void RiggedObject::MPCutPlane(const vec3 & normal, const vec3 & pos, const vec3 } vec2 tex_points[3]; for (unsigned j = 0; j < 3; ++j) { - tex_points[j][0] = model->tex_coords[model->faces[hit_list[i] * 3 + j] * 2 + 0]; - tex_points[j][1] = model->tex_coords[model->faces[hit_list[i] * 3 + j] * 2 + 1]; + tex_points[j][0] = model->tex_coords[model->faces[i * 3 + j] * 2 + 0]; + tex_points[j][1] = model->tex_coords[model->faces[i * 3 + j] * 2 + 1]; } @@ -3297,13 +3270,13 @@ void RiggedObject::MPCutPlane(const vec3 & normal, const vec3 & pos, const vec3 if (type == _light || RangedRandomFloat(0.0f, 1.0f) < 0.6f) { vec2 bleed_point = mix(tex_intersect_points[0], tex_intersect_points[1], 0.5f); vec3 coords = bary_coords(bleed_point, tex_points[0], tex_points[1], tex_points[2]); - blood_surface.CreateDripInTri(hit_list[i], coords, RangedRandomFloat(0.1f, 1.0f), RangedRandomFloat(0.0f, 1.0f), true, SurfaceWalker::BLOOD); + blood_surface.CreateDripInTri(i, coords, RangedRandomFloat(0.1f, 1.0f), RangedRandomFloat(0.0f, 1.0f), true, SurfaceWalker::BLOOD); } if (type == _heavy || RangedRandomFloat(0.0f, 1.0f) < 0.2f) { vec2 bleed_point = mix(tex_intersect_points[0], tex_intersect_points[1], 0.5f); vec3 coords = bary_coords(bleed_point, tex_points[0], tex_points[1], tex_points[2]); - blood_surface.CreateDripInTri(hit_list[i], coords, RangedRandomFloat(0.1f, 0.5f), RangedRandomFloat(0.0f, 10.0f), true, SurfaceWalker::BLOOD); + blood_surface.CreateDripInTri(i, coords, RangedRandomFloat(0.1f, 0.5f), RangedRandomFloat(0.0f, 10.0f), true, SurfaceWalker::BLOOD); } //dot(offset+dir*time, normal) = 0.0f @@ -3382,11 +3355,11 @@ void UpdateStuckItem(AttachedItem& stuck_item, const Skeleton &skeleton, bool an } void RiggedObject::UpdateAttachedItems() { - for(AttachedItemList::iterator iter = attached_items.items.begin(); iter != attached_items.items.end(); ++iter){ - UpdateAttachedItem(*iter, skeleton_, model_char_scale, weapon_offset, weap_anim_info_map, weapon_offset_retarget); + for(auto & item : attached_items.items){ + UpdateAttachedItem(item, skeleton_, model_char_scale, weapon_offset, weap_anim_info_map, weapon_offset_retarget); } - for(AttachedItemList::iterator iter = stuck_items.items.begin(); iter != stuck_items.items.end(); ++iter) { - UpdateStuckItem(*iter, skeleton_, animated); + for(auto & item : stuck_items.items) { + UpdateStuckItem(item, skeleton_, animated); } } @@ -3410,8 +3383,8 @@ void RiggedObject::CutPlane( const vec3 &normal, const vec3 &pos, const vec3 &di GetTransformedTri(i, points); pos_side = false; neg_side = false; - for (unsigned j = 0; j < 3; ++j) { - if (dot(points[j] - pos, normal) < 0.0f) { + for (const auto & point : points) { + if (dot(point - pos, normal) < 0.0f) { neg_side = true; } else { @@ -3439,8 +3412,8 @@ void RiggedObject::CutPlane( const vec3 &normal, const vec3 &pos, const vec3 &di } } else { //blood_surface.AddBloodToTriangles(hit_list); - for(unsigned i=0; i 0.0f){ continue; } @@ -3454,8 +3427,8 @@ void RiggedObject::CutPlane( const vec3 &normal, const vec3 &pos, const vec3 &di } vec2 tex_points[3]; for(unsigned j=0; j<3; ++j){ - tex_points[j][0] = model->tex_coords[model->faces[hit_list[i]*3+j]*2+0]; - tex_points[j][1] = model->tex_coords[model->faces[hit_list[i]*3+j]*2+1]; + tex_points[j][0] = model->tex_coords[model->faces[i*3+j]*2+0]; + tex_points[j][1] = model->tex_coords[model->faces[i*3+j]*2+1]; } vec2 tex_intersect_points[2]; vec3 intersect_points[2]; @@ -3480,7 +3453,7 @@ void RiggedObject::CutPlane( const vec3 &normal, const vec3 &pos, const vec3 &di vec3 coords = bary_coords(bleed_point, tex_points[0], tex_points[1], tex_points[2]); //LOGI << "BLEED POINT " << bleed_point << " coords " << coords << std::endl; - blood_surface.CreateDripInTri(hit_list[i], coords, RangedRandomFloat(0.1f,1.0f), RangedRandomFloat(0.0f,1.0f), true, SurfaceWalker::BLOOD); + blood_surface.CreateDripInTri(i, coords, RangedRandomFloat(0.1f,1.0f), RangedRandomFloat(0.0f,1.0f), true, SurfaceWalker::BLOOD); } if(type == _heavy || RangedRandomFloat(0.0f,1.0f)<0.2f){ @@ -3488,7 +3461,7 @@ void RiggedObject::CutPlane( const vec3 &normal, const vec3 &pos, const vec3 &di vec3 coords = bary_coords(bleed_point, tex_points[0], tex_points[1], tex_points[2]); //LOGI << "BLEED POINT " << bleed_point << " coords " << coords << std::endl; - blood_surface.CreateDripInTri(hit_list[i], coords, RangedRandomFloat(0.1f,0.5f), RangedRandomFloat(0.0f,10.0f), true, SurfaceWalker::BLOOD); + blood_surface.CreateDripInTri(i, coords, RangedRandomFloat(0.1f,0.5f), RangedRandomFloat(0.0f,10.0f), true, SurfaceWalker::BLOOD); } //dot(offset+dir*time, normal) = 0.0f @@ -3540,9 +3513,9 @@ void RiggedObject::Stab( const vec3 &pos, const vec3 &dir, int type, int depth ) for(int i=0, len=model->faces.size()/3; i fire_decal_matrix; std::vector water_decal_matrix; - for(int i=0, len=scenegraph_->decal_objects_.size(); idecal_objects_[i]; + for(auto & decal_object : scenegraph_->decal_objects_){ + DecalObject* obj = (DecalObject*)decal_object; if(obj->decal_file_ref->special_type == 3){ fire_decal_matrix.push_back(obj->GetTransform()); } @@ -3676,12 +3649,12 @@ void RiggedObject::AddWaterCube( const mat4 &transform ) { } void RiggedObject::UpdateCollisionObjects() { - for(unsigned i=0; iSetTransform(skeleton_.physics_bones[i].bullet_object->GetTransform()); + cbo->SetTransform(physics_bone.bullet_object->GetTransform()); cbo->UpdateTransform(); } skeleton_.UpdateCollisionWorldAABB(); @@ -3753,8 +3726,8 @@ static int ASGetBonePoint(Skeleton* skeleton, int which_bone, int which_point){ } static void ASAddVelocity(Skeleton* skeleton, const vec3& vel){ - for(int bone_index=0, num_bones=skeleton->physics_bones.size(); bone_indexphysics_bones[bone_index].bullet_object; + for(auto & physics_bone : skeleton->physics_bones){ + BulletObject* bullet_object = physics_bone.bullet_object; if(bullet_object){ bullet_object->AddLinearVelocity(vel); } @@ -3787,8 +3760,8 @@ void RotateBonesToMatchVec(RiggedObject* rigged_object, const vec3& a, const vec static void TransformAllFrameMats(RiggedObject* rigged_object, const BoneTransform &transform) { std::vector &mats = rigged_object->animation_frame_bone_matrices; - for(int i=0, len=mats.size(); iReserve(points.size()); - for(int i=0, len=points.size(); iInsertLast(&points[i]); + for(float & point : points) { + array->InsertLast(&point); } return array; } @@ -4026,8 +3999,8 @@ void RiggedObject::SaveSimplificationCache(const std::string &path) { } unsigned short checksum = skeleton_.skeleton_asset_ref->checksum()+ Models::Instance()->GetModel(model_id[0]).checksum; - for(int i=0, len=morph_targets.size(); i queue; - for(unsigned i=0; iGetModel(morph.model_id[i]); @@ -4102,8 +4075,8 @@ bool RiggedObject::LoadSimplificationCache(const std::string& path) { } unsigned short checksum = skeleton_.skeleton_asset_ref->checksum()+ Models::Instance()->GetModel(model_id[0]).checksum; - for(int i=0, len=morph_targets.size(); i queue; - for(unsigned i=0; iAddModel(); @@ -4237,8 +4210,8 @@ void RiggedObject::CreateFurModel( int model_id, int fur_model_id ) { // verts { std::vector included(fur_ref_model.vertices.size()/3, false); - for(unsigned i=0; i RiggedObject::GetWieldedItemRefs() const { int num_wielded = 0; - for(std::list::const_iterator iter = attached_items.items.begin(); - iter != attached_items.items.end(); ++iter) + for(const auto & iter : attached_items.items) { - const ItemObjectScriptReader& item = iter->item; + const ItemObjectScriptReader& item = iter.item; if(item->GetID() == primary_weapon_id){ ++num_wielded; } } std::vector wielded_item_refs(num_wielded); num_wielded = 0; - for(std::list::const_iterator iter = attached_items.items.begin(); - iter != attached_items.items.end(); ++iter) + for(const auto & iter : attached_items.items) { - const ItemObjectScriptReader& item = iter->item; + const ItemObjectScriptReader& item = iter.item; if(item->GetID() == primary_weapon_id){ wielded_item_refs[num_wielded++] = item->item_ref(); } @@ -4783,11 +4754,10 @@ void RiggedObject::AvailableItemSlots( const ItemRef& item_ref, AttachmentSlotLi DrawAvailableAttachmentSlots(item_ref, _at_sheathe, skeleton_, list); } const std::list &attachment_list = item_ref->GetAttachmentList(); - for(std::list::const_iterator iter = attachment_list.begin(); - iter != attachment_list.end(); ++iter) + for(const auto & iter : attachment_list) { //AttachmentRef attachment_ref = Attachments::Instance()->ReturnRef((*iter)); - AttachmentRef attachment_ref = Engine::Instance()->GetAssetManager()->LoadSync((*iter)); + AttachmentRef attachment_ref = Engine::Instance()->GetAssetManager()->LoadSync(iter); DrawAvailableAttachment(attachment_ref, skeleton_, false, list); if(attachment_ref->mirror_allowed){ DrawAvailableAttachment(attachment_ref, skeleton_, true, list); @@ -4911,8 +4881,8 @@ void AttachedItems::Remove( int id ) { } void AttachedItems::RemoveAll() { - for(std::list::iterator iter = items.begin(); iter != items.end(); ++iter) { - iter->item->ActivatePhysics(); + for(auto & item : items) { + item.item->ActivatePhysics(); } items.clear(); } diff --git a/Source/Objects/terrainobject.cpp b/Source/Objects/terrainobject.cpp index b03466fc..786dc4a4 100644 --- a/Source/Objects/terrainobject.cpp +++ b/Source/Objects/terrainobject.cpp @@ -164,10 +164,9 @@ void TerrainObject::PreDrawCamera(float curr_game_time) { } static const mat4 identity; - for(std::list::iterator iter = terrain_.detail_object_surfaces.begin(); - iter != terrain_.detail_object_surfaces.end(); ++iter) + for(auto & detail_object_surface : terrain_.detail_object_surfaces) { - (*iter)->PreDrawCamera(identity); + detail_object_surface->PreDrawCamera(identity); } } @@ -180,10 +179,9 @@ void TerrainObject::Draw() { if(!terrain_info_.minimal) { static const mat4 identity; - for(std::list::iterator iter = terrain_.detail_object_surfaces.begin(); - iter != terrain_.detail_object_surfaces.end(); ++iter) + for(auto & detail_object_surface : terrain_.detail_object_surfaces) { - (*iter)->Draw(identity, DetailObjectSurface::TERRAIN, vec3(1.0f), scenegraph_->sky->GetSpecularCubeMapTexture(), &scenegraph_->light_probe_collection, scenegraph_); + detail_object_surface->Draw(identity, DetailObjectSurface::TERRAIN, vec3(1.0f), scenegraph_->sky->GetSpecularCubeMapTexture(), &scenegraph_->light_probe_collection, scenegraph_); } } } @@ -269,8 +267,7 @@ void TerrainObject::DrawDepthMap(const mat4& proj_view_matrix, const vec4* cull_ int vert_attrib_id = shaders->returnShaderAttrib("vertex_attrib", shader); graphics->EnableVertexAttribArray(vert_attrib_id); - for(std::list::iterator iter = terrain_.terrain_patches.begin(); iter != terrain_.terrain_patches.end(); ++iter) { - Model& patch = (*iter); + for(auto & patch : terrain_.terrain_patches) { const vec3 adjusted_min = patch.min_coords + translation; const vec3 adjusted_max = patch.max_coords + translation; if(CheckBoxAgainstPlanes(adjusted_min, adjusted_max, cull_planes, num_cull_planes)) { @@ -283,8 +280,7 @@ void TerrainObject::DrawDepthMap(const mat4& proj_view_matrix, const vec4* cull_ graphics->DrawElements(use_tesselation?GL_PATCHES:GL_TRIANGLES, (unsigned int) patch.faces.size(), GL_UNSIGNED_INT, 0); } } - for(std::list::iterator iter = terrain_.edge_terrain_patches.begin(); iter != terrain_.edge_terrain_patches.end(); ++iter) { - Model& patch = (*iter); + for(auto & patch : terrain_.edge_terrain_patches) { const vec3 adjusted_min = patch.min_coords + translation; const vec3 adjusted_max = patch.max_coords + translation; if(CheckBoxAgainstPlanes(adjusted_min, adjusted_max, cull_planes, num_cull_planes)) { @@ -542,8 +538,7 @@ void TerrainObject::DrawTerrain() { std::vector light_volume_matrix; std::vector light_volume_matrix_inverse; - for(size_t i=0, len=scenegraph_->light_volume_objects_.size(); ilight_volume_objects_[i]; + for(auto obj : scenegraph_->light_volume_objects_){ const mat4 &mat = obj->GetTransform(); light_volume_matrix.push_back(mat); light_volume_matrix_inverse.push_back(invert(mat)); @@ -579,8 +574,7 @@ void TerrainObject::DrawTerrain() { const vec3 translation = GetTranslation(); { PROFILER_GPU_ZONE(g_profiler_ctx, "Draw opaque terrain patches"); - for(std::list::iterator iter = terrain_.terrain_patches.begin(); iter != terrain_.terrain_patches.end(); ++iter) { - Model& patch = (*iter); + for(auto & patch : terrain_.terrain_patches) { const vec3 adjusted_min = patch.min_coords + translation; const vec3 adjusted_max = patch.max_coords + translation; if(ActiveCameras::Get()->checkBoxInFrustum(adjusted_min, @@ -593,8 +587,7 @@ void TerrainObject::DrawTerrain() { { PROFILER_GPU_ZONE(g_profiler_ctx, "Draw edge terrain patches"); graphics->setGLState(edge_gl_state_); - for(std::list::iterator iter = terrain_.edge_terrain_patches.begin(); iter != terrain_.edge_terrain_patches.end(); ++iter) { - Model& patch = (*iter); + for(auto & patch : terrain_.edge_terrain_patches) { const vec3 adjusted_min = patch.min_coords + translation; const vec3 adjusted_max = patch.max_coords + translation; if(ActiveCameras::Get()->checkBoxInFrustum(adjusted_min, diff --git a/Source/Ogda/Searchers/Seekers/actorobjectlevelseeker.cpp b/Source/Ogda/Searchers/Seekers/actorobjectlevelseeker.cpp index b9c9cf96..ba4a436a 100644 --- a/Source/Ogda/Searchers/Seekers/actorobjectlevelseeker.cpp +++ b/Source/Ogda/Searchers/Seekers/actorobjectlevelseeker.cpp @@ -121,9 +121,9 @@ public: while( el ) { bool found = false; - for( int i = 0; i < parameters.size(); i++ ) + for(auto & parameter : parameters) { - found |= parameters[i].Search( + found |= parameter.Search( items, item, el); @@ -523,9 +523,9 @@ void ActorObjectLevelSeeker::SearchGroup( std::vector& items, const Item& bool found = false; - for( int i = 0; i < aos.size(); i++ ) + for(auto & ao : aos) { - found |= aos[i].Search( items, item, el ); + found |= ao.Search( items, item, el ); } if( !found ) @@ -551,9 +551,9 @@ std::vector ActorObjectLevelSeeker::SearchLevelRoot( const Item& source, T "Hotspots" }; - for( int i = 0; i < ARRLEN(entity_roots); i++ ) + for(auto & entity_root : entity_roots) { - TiXmlElement* elem = hRoot.FirstChildElement(entity_roots[i]).ToElement(); + TiXmlElement* elem = hRoot.FirstChildElement(entity_root).ToElement(); if( elem ) { @@ -561,7 +561,7 @@ std::vector ActorObjectLevelSeeker::SearchLevelRoot( const Item& source, T } else { - LOGD << source << " Is missing " << entity_roots[i] << std::endl; + LOGD << source << " Is missing " << entity_root << std::endl; } } return items; diff --git a/Source/Ogda/manifestresult.cpp b/Source/Ogda/manifestresult.cpp index 61c6ea7b..fd84111d 100644 --- a/Source/Ogda/manifestresult.cpp +++ b/Source/Ogda/manifestresult.cpp @@ -76,8 +76,8 @@ const std::string& ManifestResult::GetCurrentDestHash(const std::string& base_pa std::ostream& operator<<(std::ostream& out, const ManifestResult& mr) { out << "ManifestResult( items { "; - for( int i = 0; i < mr.items.size(); i++ ) { - out << mr.items[i] << ","; + for(const auto & item : mr.items) { + out << item << ","; } out << "}," << mr.dest << "," << mr.dest_hash << "," << mr.name << "," << mr.version << "," << mr.type << ")"; return out; diff --git a/Source/Online/Message/attach_to_message.cpp b/Source/Online/Message/attach_to_message.cpp index fb2096d8..4ad62152 100644 --- a/Source/Online/Message/attach_to_message.cpp +++ b/Source/Online/Message/attach_to_message.cpp @@ -82,8 +82,7 @@ namespace OnlineMessages { MovementObject* movement_object = (MovementObject*)parent; AttachmentSlotList attachment_slots; movement_object->rigged_object()->AvailableItemSlots(item_object->item_ref(), &attachment_slots); - for (AttachmentSlotList::iterator iterator = attachment_slots.begin(); iterator != attachment_slots.end(); ++iterator) { - AttachmentSlot& slot = (*iterator); + for (auto & slot : attachment_slots) { if (slot.type == (AttachmentType)t->bone_id && slot.mirrored == t->mirrored) { movement_object->AttachItemToSlotEditor(item_object->GetID(), slot.type, slot.mirrored, slot.attachment_ref, true); break; diff --git a/Source/Online/Message/movement_object_update.cpp b/Source/Online/Message/movement_object_update.cpp index 393dcff4..17d59479 100644 --- a/Source/Online/Message/movement_object_update.cpp +++ b/Source/Online/Message/movement_object_update.cpp @@ -94,8 +94,8 @@ namespace OnlineMessages { MovementObject* mo = static_cast(object); // Check if we already have an update for the specified time - for (auto it = mo->incoming_movement_object_frames.begin(); it != mo->incoming_movement_object_frames.end(); it++) { - MovementObjectUpdate* update = static_cast(it->GetData()); + for (auto & incoming_movement_object_frame : mo->incoming_movement_object_frames) { + MovementObjectUpdate* update = static_cast(incoming_movement_object_frame.GetData()); if (update->timestamp == mou->timestamp) { LOGW << "Received MovementObjectUpdate with an identical timestamp of an existing update for object: \"" << object_id << " (" << mou->identifier << ")\"" << std::endl; return; diff --git a/Source/Online/online.cpp b/Source/Online/online.cpp index 0a9d1eb3..b1181fe3 100644 --- a/Source/Online/online.cpp +++ b/Source/Online/online.cpp @@ -579,18 +579,18 @@ const vector Online::GetPeers() { } Peer* Online::GetPeerFromConnection(NetConnectionID conn_id) { - for(int i = 0; i < online_session->connected_peers.size(); i++) { - if(online_session->connected_peers[i].conn_id == conn_id) { - return &online_session->connected_peers[i]; + for(auto & connected_peer : online_session->connected_peers) { + if(connected_peer.conn_id == conn_id) { + return &connected_peer; } } return nullptr; } Peer* Online::GetPeerFromID(PeerID peer_id) { - for(int i = 0; i < online_session->connected_peers.size(); i++) { - if(online_session->connected_peers[i].peer_id == peer_id) { - return &online_session->connected_peers[i]; + for(auto & connected_peer : online_session->connected_peers) { + if(connected_peer.peer_id == peer_id) { + return &connected_peer; } } return nullptr; @@ -1407,18 +1407,16 @@ void Online::SendMessageObjects() { //First, send persistent packages, if we see there's a new client who isn't up to date. if(host_started_level && IsHosting()) { - for(int k = 0; k < online_session->connected_peers.size(); k++) { - Peer& peer = online_session->connected_peers[k]; - + for(auto & peer : online_session->connected_peers) { if(online_session->client_connection_manager.IsClientLoaded(peer.peer_id) && online_session->client_connection_manager.HasClientGottenPersistentQueue(peer.peer_id) == false) { - for(int i = 0; i < online_session->persistent_outgoing_messages.size(); i++) { - OnlineMessageBase* omb = static_cast(message_handler.GetMessageData(online_session->persistent_outgoing_messages[i])); + for(auto & persistent_outgoing_message : online_session->persistent_outgoing_messages) { + OnlineMessageBase* omb = static_cast(message_handler.GetMessageData(persistent_outgoing_message)); if(omb != nullptr) { PackageHeader package_header; package_header.package_type = PackageHeader::Type::MESSAGE_OBJECT; - package_header.message_ref = online_session->persistent_outgoing_messages[i]; + package_header.message_ref = persistent_outgoing_message; binn* l = package_header.Serialize(); @@ -1453,8 +1451,7 @@ void Online::SendMessageObjects() { binn_free(l); - for(int k = 0; k < online_session->connected_peers.size(); k++) { - Peer& peer = online_session->connected_peers[k]; + for(auto & peer : online_session->connected_peers) { bool send_message = true; if(outgoing_message.broadcast == false && outgoing_message.target != peer.conn_id) { diff --git a/Source/Online/online_utility.cpp b/Source/Online/online_utility.cpp index 64f34e61..94735028 100644 --- a/Source/Online/online_utility.cpp +++ b/Source/Online/online_utility.cpp @@ -70,17 +70,17 @@ std::string OnlineUtility::GetActiveModsString() { bool active_mods = false; stringstream modlist; vector mods = ModLoading::Instance().GetAllMods(); - for(size_t i = 0; i < mods.size(); i++) { - if(mods[i]->IsActive() && !mods[i]->IsCore()) { + for(auto & mod : mods) { + if(mod->IsActive() && !mod->IsCore()) { if(active_mods) { modlist << ", "; } active_mods = true; - if(mods[i]->SupportsOnline()) { - modlist << mods[i]->id; + if(mod->SupportsOnline()) { + modlist << mod->id; } else { - modlist << "[" << mods[i]->id << "]"; + modlist << "[" << mod->id << "]"; } } } @@ -101,13 +101,13 @@ std::string OnlineUtility::GetActiveIncompatibleModsString() { bool active_mods = false; stringstream modlist; vector mods = ModLoading::Instance().GetAllMods(); - for(size_t i = 0; i < mods.size(); i++) { - if(mods[i]->IsActive() && !mods[i]->IsCore() && !mods[i]->SupportsOnline()) { + for(auto & mod : mods) { + if(mod->IsActive() && !mod->IsCore() && !mod->SupportsOnline()) { if(active_mods) { modlist << ", "; } active_mods = true; - modlist << "\"" << mods[i]->id << "\""; + modlist << "\"" << mod->id << "\""; } } diff --git a/Source/Physics/bulletobject.cpp b/Source/Physics/bulletobject.cpp index 33a9bdf0..727d7dc5 100644 --- a/Source/Physics/bulletobject.cpp +++ b/Source/Physics/bulletobject.cpp @@ -524,8 +524,8 @@ void BulletObject::CheckForNAN() { btTransform bt_transform; GetDisplayTransform(&bt_transform); mat4 test_mat = SafeGetOpenGLMatrix(body->getWorldTransform()); - for(unsigned i=0; i<16; ++i){ - if(test_mat.entries[i] != test_mat.entries[i]){ + for(float entrie : test_mat.entries){ + if(entrie != entrie){ LOGE << "NAN found in BulletObject" << std::endl; break; } diff --git a/Source/Physics/bulletworld.cpp b/Source/Physics/bulletworld.cpp index 7068e1af..88df2329 100644 --- a/Source/Physics/bulletworld.cpp +++ b/Source/Physics/bulletworld.cpp @@ -187,20 +187,18 @@ void BulletWorld::Dispose() { delete broadphase_interface_; broadphase_interface_ = NULL; delete collision_dispatcher_; collision_dispatcher_ = NULL; delete collision_configuration_; collision_configuration_ = NULL; - for (BulletObjectList::iterator it = dynamic_objects_.begin(); it != dynamic_objects_.end(); ++it) { - BulletObject* object = (*it); + for (auto object : dynamic_objects_) { object->Dispose(); delete object; } dynamic_objects_.clear(); - for (BulletObjectList::iterator it = static_objects_.begin(); it != static_objects_.end(); ++it) { - BulletObject* object = (*it); + for (auto object : static_objects_) { object->Dispose(); delete object; } static_objects_.clear(); - for(HullShapeCacheMap::iterator it = hull_shape_cache_.begin(); it != hull_shape_cache_.end(); ++it){ - delete it->second; + for(auto & it : hull_shape_cache_){ + delete it.second; } hull_shape_cache_.clear(); } @@ -1553,10 +1551,10 @@ void BulletWorld::UpdateBulletObjectTransforms() void BulletWorld::RemoveTempConstraints() { - for(size_t i=0; iremoveConstraint(temp_constraints_[i].second); - delete temp_constraints_[i].second; + for(auto & temp_constraint : temp_constraints_){ + if(temp_constraint.second){ + dynamics_world_->removeConstraint(temp_constraint.second); + delete temp_constraint.second; } } temp_constraints_.clear(); @@ -1571,11 +1569,11 @@ void CenterAtCOMTri(Model &mesh){ } vec3 avg_pos; int num_avg = 0; - for(unsigned i=0; i &input, std::vector &output btConvexHullShape* CreateConvexHullShape(const std::vector &verts) { btConvexHullShape* convex_hull_shape = new btConvexHullShape(); - for (unsigned i=0 ; iaddPoint(btVector3(verts[i][0],verts[i][1],verts[i][2])); + for (const auto & vert : verts) { + convex_hull_shape->addPoint(btVector3(vert[0],vert[1],vert[2])); } convex_hull_shape->setMargin(0.00f); return convex_hull_shape; @@ -1854,8 +1852,8 @@ void BulletWorld::CreateCustomHullShape( const std::string& key, const std::vect delete hsc_iter->second; } btConvexHullShape *shape = new btConvexHullShape(); - for (int i=0, len=points.size(); iaddPoint(btVector3(points[i][0], points[i][1], points[i][2])); + for (const auto & point : points) { + shape->addPoint(btVector3(point[0], point[1], point[2])); } shape->setMargin(0.00f); hull_shape_cache_[key] = shape; @@ -2059,10 +2057,10 @@ void BulletWorld::CreateSpikeConstraint( BulletObject* obj, const vec3 &from, co } void BulletWorld::ClearBoneConstraints(){ - for(size_t i=0; iremoveConstraint(fixed_constraints_[i].second); - delete fixed_constraints_[i].second; + for(auto & fixed_constraint : fixed_constraints_){ + if( fixed_constraint.second ) { + dynamics_world_->removeConstraint(fixed_constraint.second); + delete fixed_constraint.second; } } fixed_constraints_.clear(); @@ -2076,9 +2074,9 @@ void BulletWorld::FinalizeStaticEntries() { // Create meta model of all models combined vert_indices.clear(); vertices.clear(); - for(int i=0, len=static_entries.size(); iGetModel(static_entries[i].model_id); - mat4 &transform = static_entries[i].transform; + for(auto & static_entrie : static_entries){ + Model& model = Models::Instance()->GetModel(static_entrie.model_id); + mat4 &transform = static_entrie.transform; //int start_vert_indices = vert_indices.size(); int start_vertices = vertices.size()/3; for(int j=0, len=model.vertices.size(); j::iterator it = templateTypes.begin(); it != templateTypes.end(); ++it ) + for(auto type : templateTypes) { - asITypeInfo *type = *it; - TypeWriter::Write(engine, strm, type, currNamespace, currAccessMask); + TypeWriter::Write(engine, strm, type, currNamespace, currAccessMask); } // Write the object types members diff --git a/Source/Scripting/angelscript/ascontext.cpp b/Source/Scripting/angelscript/ascontext.cpp index beffb0f7..b49fd9e3 100644 --- a/Source/Scripting/angelscript/ascontext.cpp +++ b/Source/Scripting/angelscript/ascontext.cpp @@ -806,8 +806,8 @@ bool ASContext::CallMPCallBack(uint32_t state, const std::vector& data) { asITypeInfo *arrayType = engine->GetTypeInfoById(engine->GetTypeIdByDecl("array")); CScriptArray *array = CScriptArray::Create(arrayType, (asUINT)0); array->Reserve(data.size()); - for (int i = 0, len = data.size(); i < len; ++i) { - array->InsertLast(const_cast(&data[i])); + for (const char & i : data) { + array->InsertLast(const_cast(&i)); } args.AddAddress((void*)array); @@ -836,8 +836,8 @@ bool ASContext::CallMPCallBack(uint32_t state, const std::vector& asITypeInfo *arrayType = engine->GetTypeInfoById(engine->GetTypeIdByDecl("array")); CScriptArray *array = CScriptArray::Create(arrayType, (asUINT)0); array->Reserve(data.size()); - for (int i = 0, len = data.size(); i < len; ++i) { - array->InsertLast((void*)&data[i]); + for (const unsigned int & i : data) { + array->InsertLast((void*)&i); } args.AddAddress((void*)array); diff --git a/Source/Scripting/angelscript/ascrashdump.cpp b/Source/Scripting/angelscript/ascrashdump.cpp index 4f43def0..e93b8cac 100644 --- a/Source/Scripting/angelscript/ascrashdump.cpp +++ b/Source/Scripting/angelscript/ascrashdump.cpp @@ -45,14 +45,14 @@ static AngelScriptContext contexts[CONTEXT_COUNT]; void RegisterAngelscriptContext( const char* name, ASContext* ascontext ) { - for( int i = 0; i < CONTEXT_COUNT; i++ ) + for(auto & context : contexts) { - if( contexts[i].allocated == false ) + if( context.allocated == false ) { - strncpy( contexts[i].name, name, 64 ); - contexts[i].name[63] = '\0'; - contexts[i].allocated = true; - contexts[i].context = ascontext; + strncpy( context.name, name, 64 ); + context.name[63] = '\0'; + context.allocated = true; + context.context = ascontext; return; } } @@ -60,11 +60,11 @@ void RegisterAngelscriptContext( const char* name, ASContext* ascontext ) void DeregisterAngelscriptContext( ASContext* ascontext ) { - for( int i = 0; i < CONTEXT_COUNT; i++ ) + for(auto & context : contexts) { - if( contexts[i].context == ascontext ) + if( context.context == ascontext ) { - contexts[i].allocated = false; + context.allocated = false; } } } @@ -79,13 +79,13 @@ void DumpAngelscriptStates() if( output.is_open() ) { LOGI << "Dumping angelscript states to: " << dump_path << std::endl; - for( int i = 0; i < CONTEXT_COUNT; i++ ) + for(auto & context : contexts) { - if( contexts[i].allocated ) + if( context.allocated ) { - LOGI << "Dumping angelscript state for: " << contexts[i].name << std::endl; + LOGI << "Dumping angelscript state for: " << context.name << std::endl; if( output.good() ) { - contexts[i].context->DumpCallstack(output); + context.context->DumpCallstack(output); } } } diff --git a/Source/Scripting/angelscript/asdebugger.cpp b/Source/Scripting/angelscript/asdebugger.cpp index 43bd220d..6bbe6530 100644 --- a/Source/Scripting/angelscript/asdebugger.cpp +++ b/Source/Scripting/angelscript/asdebugger.cpp @@ -50,8 +50,8 @@ ASDebugger::ASDebugger() , show_global_variables(false) , show_stack_trace(false) { - for(size_t i = 0; i < global_breakpoints.size(); ++i) { - ToggleBreakpoint(global_breakpoints[i].first.c_str(), global_breakpoints[i].second); + for(auto & global_breakpoint : global_breakpoints) { + ToggleBreakpoint(global_breakpoint.first.c_str(), global_breakpoint.second); } } @@ -60,8 +60,8 @@ ASDebugger::~ASDebugger() { void ASDebugger::AddContext(ASContext* context) { bool add = true; - for(size_t i = 0; i < active_contexts.size(); ++i) { - if(active_contexts[i] == context) { + for(auto & active_context : active_contexts) { + if(active_context == context) { add = false; break; } @@ -86,8 +86,8 @@ const std::vector& ASDebugger::GetActiveContexts() { void ASDebugger::AddGlobalBreakpoint(const char* file, int line) { bool found = false; - for(size_t i = 0; i < global_breakpoints.size(); ++i) { - if(strcmp(global_breakpoints[i].first.c_str(), file) == 0 && global_breakpoints[i].second == line) { + for(auto & global_breakpoint : global_breakpoints) { + if(strcmp(global_breakpoint.first.c_str(), file) == 0 && global_breakpoint.second == line) { found = true; break; } @@ -95,8 +95,8 @@ void ASDebugger::AddGlobalBreakpoint(const char* file, int line) { if(!found) { global_breakpoints.push_back(std::pair(file, line)); - for(size_t i = 0; i < active_contexts.size(); ++i) { - active_contexts[i]->dbg.AddBreakpoint(file, line); + for(auto & active_context : active_contexts) { + active_context->dbg.AddBreakpoint(file, line); } } } @@ -105,8 +105,8 @@ void ASDebugger::RemoveGlobalBreakpoint(const char* file, int line) { for(size_t i = 0; i < global_breakpoints.size(); ++i) { if(strcmp(global_breakpoints[i].first.c_str(), file) == 0 && global_breakpoints[i].second == line) { global_breakpoints.erase(global_breakpoints.begin() + i); - for(size_t i = 0; i < active_contexts.size(); ++i) { - active_contexts[i]->dbg.RemoveBreakpoint(file, line); + for(auto & active_context : active_contexts) { + active_context->dbg.RemoveBreakpoint(file, line); } break; } @@ -312,8 +312,8 @@ void ASDebugger::AddBreakpoint(const char* file_name, int line) { { std::vector& lines = breakpoint_iter->second; - for(size_t i = 0; i < lines.size(); ++i) { - if(lines[i] == line) { + for(int i : lines) { + if(i == line) { return; } } @@ -379,8 +379,8 @@ void ASDebugger::LineCallback(asIScriptContext* ctx) { if(breakpoints == NULL) return; else { - for(size_t i = 0; i < breakpoints->size(); ++i) { - if(breakpoints->at(i) == current_line) { + for(int breakpoint : *breakpoints) { + if(breakpoint == current_line) { paused = true; auto_scroll = true; ctx->Suspend(); @@ -443,8 +443,8 @@ void ASDebugger::Continue(asIScriptContext* ctx) { if(breakpoints == NULL) return; else { - for(size_t i = 0; i < breakpoints->size(); ++i) { - if(breakpoints->at(i) == (int)lf.line_number) { + for(int breakpoint : *breakpoints) { + if(breakpoint == (int)lf.line_number) { current_file = lf.file; current_line = lf.line_number; ctx->Suspend(); @@ -726,8 +726,8 @@ ASDebugger::BreakAction ASDebugger::UpdateGUI() { bool is_breakpoint = false; if(breakpoints != NULL) { - for(size_t i = 0; i < breakpoints->size(); ++i) { - if(breakpoints->at(i) == line_nr) { + for(int breakpoint : *breakpoints) { + if(breakpoint == line_nr) { is_breakpoint = true; break; } diff --git a/Source/Scripting/angelscript/asfuncs.cpp b/Source/Scripting/angelscript/asfuncs.cpp index eb307499..0486f905 100644 --- a/Source/Scripting/angelscript/asfuncs.cpp +++ b/Source/Scripting/angelscript/asfuncs.cpp @@ -170,8 +170,8 @@ static CScriptArray* AS_GetPlayerStates() { array->Reserve(vals.size()); - for(unsigned i = 0; i < vals.size(); i++) { - array->InsertLast((void*)&vals[i]); + for(auto & val : vals) { + array->InsertLast((void*)&val); } return array; @@ -444,8 +444,8 @@ static CScriptArray* AS_GetRawKeyboardInputs() { array->Reserve(vals.size()); - for( unsigned i = 0; i < vals.size(); i++ ) { - array->InsertLast((void*)&vals[i]); + for(auto & val : vals) { + array->InsertLast((void*)&val); } return array; @@ -461,8 +461,8 @@ static CScriptArray* AS_GetRawMouseInputs() { array->Reserve(vals.size()); - for( unsigned i = 0; i < vals.size(); i++ ) { - array->InsertLast((void*)&vals[i]); + for(auto & val : vals) { + array->InsertLast((void*)&val); } return array; @@ -478,8 +478,8 @@ static CScriptArray* AS_GetRawJoystickInputs(int which) { array->Reserve(vals.size()); - for( unsigned i = 0; i < vals.size(); i++ ) { - array->InsertLast((void*)&vals[i]); + for(auto & val : vals) { + array->InsertLast((void*)&val); } return array; @@ -2452,10 +2452,8 @@ CScriptArray* ASGetSelected() { array->Reserve(the_scenegraph->objects_.size()); const SceneGraph::object_list &objects = the_scenegraph->objects_; - for(SceneGraph::object_list::const_iterator iter = objects.begin(); - iter != objects.end(); ++iter) + for(auto obj : objects) { - Object* obj = (*iter); if(obj->Selected()) { int val = obj->GetID(); array->InsertLast(&val); @@ -2545,10 +2543,8 @@ CScriptArray *ASGetObjectIDArrayType(int type) { array->Reserve(the_scenegraph->objects_.size()); const SceneGraph::object_list &objects = the_scenegraph->objects_; - for(SceneGraph::object_list::const_iterator iter = objects.begin(); - iter != objects.end(); ++iter) + for(auto obj : objects) { - Object* obj = (*iter); if(obj->GetType() == type){ int val = obj->GetID(); if(val != -1){ @@ -2567,10 +2563,9 @@ CScriptArray *ASGetObjectIDArray() { array->Reserve(the_scenegraph->objects_.size()); const SceneGraph::object_list &objects = the_scenegraph->objects_; - for(SceneGraph::object_list::const_iterator iter = objects.begin(); - iter != objects.end(); ++iter) + for(auto object : objects) { - int val = (*iter)->GetID(); + int val = object->GetID(); if(val != -1){ array->InsertLast(&val); } @@ -2593,8 +2588,8 @@ int ASCreateObject(const std::string& path, bool exclude_from_save) { std::string file_type; Path source; ActorsEditor_LoadEntitiesFromFile(path, desc_list, &file_type, &source); - for(unsigned i=0; iexclude_from_undo = exclude_from_save; obj->exclude_from_save = exclude_from_save; @@ -2690,8 +2685,7 @@ void AttachItem(Object* movement_object_base, Object* item_object_base, int type MovementObject* movement_object = (MovementObject*)movement_object_base; AttachmentSlotList attachment_slots; movement_object->rigged_object()->AvailableItemSlots(item_object->item_ref(), &attachment_slots); - for(AttachmentSlotList::iterator it = attachment_slots.begin(); it != attachment_slots.end(); ++it) { - AttachmentSlot& slot = (*it); + for(auto & slot : attachment_slots) { if(slot.mirrored == mirrored && slot.type == type){ movement_object->AttachItemToSlotEditor(item_object->GetID(), slot.type, slot.mirrored, slot.attachment_ref); break; @@ -2827,10 +2821,9 @@ CScriptArray* ASGetChildren(Object* obj) { CScriptArray *array = CScriptArray::Create(arrayType, (asUINT)0); array->Reserve(group->children.size()); - for(std::vector::const_iterator iter = group->children.begin(); - iter != group->children.end(); ++iter) + for(const auto & iter : group->children) { - int val = (*iter).direct_ptr->GetID(); + int val = iter.direct_ptr->GetID(); if(val != -1){ array->InsertLast(&val); } @@ -3201,8 +3194,8 @@ void GetCharactersInSphere( vec3 origin, float radius, CScriptArray *array ) { } void GetCharacters( CScriptArray *array ) { - for(int i=0, len=the_scenegraph->movement_objects_.size(); imovement_objects_[i]->GetID(); + for(auto & movement_object : the_scenegraph->movement_objects_){ + int val = movement_object->GetID(); array->InsertLast(&val); } } @@ -3276,9 +3269,9 @@ int ASFindFirstCharacterInGroup(int id) { Group* group = static_cast(obj); std::vector children; group->GetTopDownCompleteChildren(&children); - for( unsigned i = 0; i < children.size(); i++ ) { - if( children[i]->GetType() == _movement_object ) { - return children[i]->GetID(); + for(auto & i : children) { + if( i->GetType() == _movement_object ) { + return i->GetID(); } } } @@ -6143,10 +6136,9 @@ static CScriptArray* JSONValueGetMembers(Json::Value *self) { array->Reserve(members.size()); - for(std::vector::const_iterator iter = members.begin(); - iter != members.end(); ++iter) + for(const auto & member : members) { - array->InsertLast((void*)(&(*iter))); + array->InsertLast((void*)(&member)); } return array; } @@ -6447,8 +6439,8 @@ static CScriptArray* AS_GetPossibleResolutions() { array->Reserve(resolutions.size()); - for( unsigned i = 0; i < resolutions.size(); i++ ) { - vec2 cur_res = vec2(resolutions[i].w, resolutions[i].h); + for(auto & resolution : resolutions) { + vec2 cur_res = vec2(resolution.w, resolution.h); array->InsertLast((void*)&(cur_res)); } return array; @@ -6684,9 +6676,9 @@ static ModInstance::Parameter& ASParameterOpAssign( ModInstance::Parameter* self static ModInstance::Parameter ParameterConstStringIndex(ModInstance::Parameter *self, const std::string &key) { if(strmtch(self->type,"table")) { - for(uint32_t i = 0; i < self->parameters.size(); i++) { - if(strmtch(self->parameters[i].name,key.c_str())) { - return self->parameters[i]; + for(auto & parameter : self->parameters) { + if(strmtch(parameter.name,key.c_str())) { + return parameter; } } } @@ -6729,8 +6721,8 @@ static std::string ASParameterGetName(ModInstance::Parameter *self) { } static bool ASParameterContains(ModInstance::Parameter *self, const std::string& val) { - for(uint32_t i = 0; i < self->parameters.size(); i++ ) { - if(strmtch(self->parameters[i].value, val.c_str())) { + for(auto & parameter : self->parameters) { + if(strmtch(parameter.value, val.c_str())) { return true; } } @@ -6738,8 +6730,8 @@ static bool ASParameterContains(ModInstance::Parameter *self, const std::string& } static bool ASParameterContainsName(ModInstance::Parameter *self, const std::string& val) { - for(uint32_t i = 0; i < self->parameters.size(); i++ ) { - if(strmtch(self->parameters[i].name, val.c_str())) { + for(auto & parameter : self->parameters) { + if(strmtch(parameter.name, val.c_str())) { return true; } } @@ -7024,8 +7016,8 @@ static CScriptArray* ASGetModSids() { array->Reserve(sids.size()); - for( unsigned i = 0; i < sids.size(); i++ ) { - array->InsertLast((void*)&(sids[i])); + for(auto & sid : sids) { + array->InsertLast((void*)&sid); } return array; } @@ -7040,9 +7032,9 @@ static CScriptArray* ASGetActiveModSids() { array->Reserve(sids.size()); - for( unsigned i = 0; i < sids.size(); i++ ) { - if( ModLoading::Instance().IsActive(sids[i]) ) { - array->InsertLast((void*)&(sids[i])); + for(auto & sid : sids) { + if( ModLoading::Instance().IsActive(sid) ) { + array->InsertLast((void*)&sid); } } return array; @@ -7061,8 +7053,8 @@ static CScriptArray* ASModGetMenuItems(ModID& sid) { array->Reserve(mmi.size()); - for( unsigned i = 0; i < mmi.size(); i++ ) { - array->InsertLast((void*)&(mmi[i])); + for(auto & i : mmi) { + array->InsertLast((void*)&i); } } return array; @@ -7081,8 +7073,8 @@ static CScriptArray* ASModGetSpawnerItems(ModID& sid) { array->Reserve(msi.size()); - for(unsigned i = 0; i < msi.size(); i++) { - array->InsertLast((void*)&(msi[i])); + for(auto & i : msi) { + array->InsertLast((void*)&i); } } @@ -7099,20 +7091,20 @@ static CScriptArray* ASModGetAllSpawnerItems(bool only_include_active) { unsigned item_count = 0; - for(unsigned i = 0; i < mods.size(); i++) { - if(!only_include_active || mods[i]->IsActive() ) { - item_count += mods[i]->items.size(); + for(auto mod : mods) { + if(!only_include_active || mod->IsActive() ) { + item_count += mod->items.size(); } } array->Reserve(item_count); - for(unsigned i = 0; i < mods.size(); i++) { - if(!only_include_active || mods[i]->IsActive() ) { - const std::vector& msi = mods[i]->items; + for(auto mod : mods) { + if(!only_include_active || mod->IsActive() ) { + const std::vector& msi = mod->items; - for(unsigned i = 0; i < msi.size(); i++) { - array->InsertLast((void*)&(msi[i])); + for(const auto & i : msi) { + array->InsertLast((void*)&i); } } } @@ -7143,8 +7135,8 @@ static CScriptArray* ASModGetCampaigns( ModID& sid ) { array->Reserve(campaigns.size()); - for(unsigned i = 0; i < campaigns.size(); i++) { - array->InsertLast((void*)&(campaigns[i])); + for(auto & campaign : campaigns) { + array->InsertLast((void*)&campaign); } } return array; @@ -7164,8 +7156,8 @@ static CScriptArray* ASGetCampaigns() { array->Reserve(campaigns.size()); - for( unsigned i = 0; i < campaigns.size(); i++ ) { - array->InsertLast((void*)&(campaigns[i])); + for(auto & campaign : campaigns) { + array->InsertLast((void*)&campaign); } return array; @@ -7293,9 +7285,9 @@ static std::string ASCampaignGetMenuScript( void *m ) { static std::string ASCampaignGetAttribute( void *m, std::string& id ) { std::vector& attributes = ((ModInstance::Campaign*)m)->attributes; - for( unsigned int i = 0; i < attributes.size(); i++ ) { - if( strmtch( attributes[i].id, id.c_str()) ){ - return attributes[i].value.str(); + for(auto & attribute : attributes) { + if( strmtch( attribute.id, id.c_str()) ){ + return attribute.value.str(); } } return ""; @@ -7311,17 +7303,17 @@ static CScriptArray* ASCampaignGetLevels(void *m) { array->Reserve(mmi.size()); - for( unsigned i = 0; i < mmi.size(); i++ ) { - array->InsertLast((void*)&(mmi[i])); + for(auto & i : mmi) { + array->InsertLast((void*)&i); } return array; } static ModInstance::Level ASCampaignGetLevel(ModInstance::Campaign *m, const std::string& id) { - for( unsigned i = 0; i < m->levels.size(); i++ ) { - if( strmtch(id, m->levels[i].id) ) { - return m->levels[i]; + for(auto & level : m->levels) { + if( strmtch(id, level.id) ) { + return level; } } return ModInstance::Level(); @@ -7340,8 +7332,8 @@ static CScriptArray* ASModGetModCampaignLevels(ModID& sid) { array->Reserve(mmi.size()); - for( unsigned i = 0; i < mmi.size(); i++ ) { - array->InsertLast((void*)&(mmi[i])); + for(auto & i : mmi) { + array->InsertLast((void*)&i); } } return array; @@ -7360,8 +7352,8 @@ static CScriptArray* ASModGetModSingleLevels(ModID& sid) { array->Reserve(mmi.size()); - for( unsigned i = 0; i < mmi.size(); i++ ) { - array->InsertLast((void*)&(mmi[i])); + for(auto & i : mmi) { + array->InsertLast((void*)&i); } } return array; @@ -7450,8 +7442,8 @@ static void ASOpenWorkshop() { static void ASDeactivateAllMods() { std::vector mods = ModLoading::Instance().GetAllMods(); - for( unsigned i = 0; i < mods.size(); i++ ) { - mods[i]->Activate(false); + for(auto & mod : mods) { + mod->Activate(false); } } diff --git a/Source/Scripting/angelscript/asprofiler.cpp b/Source/Scripting/angelscript/asprofiler.cpp index 09338480..cb239a72 100644 --- a/Source/Scripting/angelscript/asprofiler.cpp +++ b/Source/Scripting/angelscript/asprofiler.cpp @@ -39,17 +39,17 @@ ASProfiler::ASProfiler() {} ASProfiler::~ASProfiler() { - for(size_t i = 0; i < zone_times.size(); ++i) - DeleteZone(zone_times[i]); + for(auto & zone_time : zone_times) + DeleteZone(zone_time); } void ASProfiler::Update() { if(window_counter == kMaxWindowSize) { - for(size_t i = 0; i < zone_times.size(); ++i) { - MoveForward(zone_times[i]); + for(auto & zone_time : zone_times) { + MoveForward(zone_time); } - for(size_t i = 0; i < script_function_times.size(); ++i) { - MoveForward(&script_function_times[i]); + for(auto & script_function_time : script_function_times) { + MoveForward(&script_function_time); } window_counter = 0; } else { @@ -70,20 +70,20 @@ void ASProfiler::Draw() { } uint64_t zone_time = 0; - for(size_t i = 0; i < zone_times.size(); ++i) { - zone_time += zone_times[i]->times.back(); + for(auto & i : zone_times) { + zone_time += i->times.back(); } sprintf(buffer, "%s: %f###%p", context->current_script.GetOriginalPath(), zone_time * 0.001f, (void*)context); if(ImGui::TreeNode(buffer)) { - for(size_t i = 0; i < script_function_times.size(); ++i) { - ZoneTime* zone = &script_function_times[i]; + for(auto & script_function_time : script_function_times) { + ZoneTime* zone = &script_function_time; ImGui::Text("%s", zone->name.c_str()); ImGui::PlotHistogram("", &TimeGetter, zone->times.data(), kTimeHistorySize, 0, NULL, 0.0f, 5000.0f, ImVec2(0,40)); } - for(size_t i = 0; i < zone_times.size(); ++i) { - DrawZone(zone_times[i]); + for(auto & zone_time : zone_times) { + DrawZone(zone_time); } ImGui::TreePop(); } @@ -91,8 +91,8 @@ void ASProfiler::Draw() { void ASProfiler::AddContext(ASContext* context) { bool add = true; - for(size_t i = 0; i < active_contexts.size(); ++i) { - if(active_contexts[i] == context) { + for(auto & active_context : active_contexts) { + if(active_context == context) { add = false; break; } @@ -125,9 +125,9 @@ void ASProfiler::ASEnterTelemetryZone( const std::string& str ) { bool found = false; if(active_zone == NULL) { - for(size_t i = 0; i < zone_times.size(); ++i) { - if(zone_times[i]->name == str) { - active_zone = zone_times[i]; + for(auto & zone_time : zone_times) { + if(zone_time->name == str) { + active_zone = zone_time; found = true; break; } @@ -143,9 +143,9 @@ void ASProfiler::ASEnterTelemetryZone( const std::string& str ) { active_zone = zone_times.back(); } } else { - for(size_t i = 0; i < active_zone->children.size(); ++i) { - if(active_zone->children[i]->name == str) { - active_zone = active_zone->children[i]; + for(auto & i : active_zone->children) { + if(i->name == str) { + active_zone = i; found = true; break; } @@ -190,9 +190,9 @@ void ASProfiler::CallScriptFunction(const char* str) { return; ZoneTime* zone = NULL; - for(size_t i = 0; i < script_function_times.size(); ++i) { - if(strcmp(script_function_times[i].name.c_str(), str) == 0) { - zone = &script_function_times[i]; + for(auto & script_function_time : script_function_times) { + if(strcmp(script_function_time.name.c_str(), str) == 0) { + zone = &script_function_time; break; } } @@ -225,8 +225,8 @@ void ASProfiler::LeaveScriptFunction() { } void ASProfiler::DeleteZone(ZoneTime* zone) { - for(size_t i = 0; i < zone->children.size(); ++i) { - DeleteZone(zone->children[i]); + for(auto & i : zone->children) { + DeleteZone(i); } delete zone; @@ -236,8 +236,8 @@ void ASProfiler::MoveForward(ZoneTime* zone) { memmove(zone->times.data(), zone->times.data() + 1, sizeof(uint64_t) * (kTimeHistorySize - 1)); zone->times[kTimeHistorySize - 1] = 0; - for(size_t i = 0; i < zone->children.size(); ++i) { - MoveForward(zone->children[i]); + for(auto & i : zone->children) { + MoveForward(i); } } @@ -247,8 +247,8 @@ void ASProfiler::DrawZone(ZoneTime* zone) { sprintf(buffer, "%s: %f###%d", zone->name.c_str(), zone_time * 0.001f, zone->id); if(ImGui::TreeNode(buffer)) { ImGui::PlotHistogram("", &TimeGetter, zone->times.data(), kTimeHistorySize, 0, NULL, 0.0f, 5000.0f, ImVec2(0,40)); - for(size_t i = 0; i < zone->children.size(); ++i) { - DrawZone(zone->children[i]); + for(auto & i : zone->children) { + DrawZone(i); } ImGui::TreePop(); } diff --git a/Source/Scripting/scriptfile.cpp b/Source/Scripting/scriptfile.cpp index 40e3b169..5ba3345b 100644 --- a/Source/Scripting/scriptfile.cpp +++ b/Source/Scripting/scriptfile.cpp @@ -46,9 +46,9 @@ const int _num_script_open_tries = 10; std::string ScriptFile::GetModPollutionInformation() const { std::stringstream ss; - for( unsigned i = 0; i < dependencies.size(); i++ ) { - if( dependencies[i].path.GetModsource() != CoreGameModID ) { - ss << "Includes " << dependencies[i].path << " from mod " << ModLoading::Instance().GetModName(dependencies[i].path.GetModsource()) << "." << std::endl; + for(const auto & dependencie : dependencies) { + if( dependencie.path.GetModsource() != CoreGameModID ) { + ss << "Includes " << dependencie.path << " from mod " << ModLoading::Instance().GetModName(dependencie.path.GetModsource()) << "." << std::endl; } } return ss.str(); @@ -68,8 +68,8 @@ static bool AlreadyAddedIncludeFileInParentHierarchy(const ScriptFile* parent_sc bool ScriptFile::AlreadyAddedIncludeFile(const Path &path) { bool already_loaded = false; - for(unsigned i=0; iSetAttribute("name",iter->first.c_str()); - const ScriptParam &sp = iter->second; + param->SetAttribute("name",iter.first.c_str()); + const ScriptParam &sp = iter.second; sp.WriteToXML(param); params->LinkEndChild(param); } diff --git a/Source/Sound/al_audio.cpp b/Source/Sound/al_audio.cpp index f494994d..f2d29db6 100644 --- a/Source/Sound/al_audio.cpp +++ b/Source/Sound/al_audio.cpp @@ -1112,9 +1112,9 @@ void alAudio::streamerLink::update(float timestep, unsigned int current_tick) std::vector buffers = m_source->DequeueBuffers(); - for( unsigned i = 0; i < buffers.size(); i++ ) + for(auto & buffer : buffers) { - m_streamer->update(buffers[i]); + m_streamer->update(buffer); } m_source->QueueBuffers(buffers); @@ -1155,9 +1155,9 @@ void alAudio::streamerLink::stop() std::vector buffers = m_source->DequeueBuffers(); - for( unsigned i = 0; i < buffers.size(); i++ ) + for(auto & buffer : buffers) { - m_streamer->update(buffers[i]); + m_streamer->update(buffer); } m_source->QueueBuffers(buffers); diff --git a/Source/Sound/sound.cpp b/Source/Sound/sound.cpp index 45114fb3..958f9d53 100644 --- a/Source/Sound/sound.cpp +++ b/Source/Sound/sound.cpp @@ -81,8 +81,7 @@ void Sound::Dispose() { } void Sound::Update() { - for(unsigned i=0; iAddDebugText("ambient_triangles", oss.str(), 0.5f); - for(unsigned i=0; iGetSong(song.songrefs[i].name); + MusicXMLParser::Song ns = owner->GetSong(songref.name); LOGI << "Creating a PlayedLayeredSong layer: " << ns.name << std::endl; @@ -645,16 +645,16 @@ void Soundtrack::PlayedLayeredSong::update( HighResBufferSegment* buffer ) { bool Soundtrack::PlayedLayeredSong::IsAtEnd() { bool is_at_end = true; - for( unsigned i = 0; i < subsongs.size(); i++ ) { - is_at_end = is_at_end && subsongs[i]->IsAtEnd(); + for(auto & subsong : subsongs) { + is_at_end = is_at_end && subsong->IsAtEnd(); } return is_at_end; } void Soundtrack::PlayedLayeredSong::Rewind() { pcm_pos = 0; - for( unsigned i = 0; i < subsongs.size(); i++ ) { - subsongs[i]->Rewind(); + for(auto & subsong : subsongs) { + subsong->Rewind(); } } @@ -664,18 +664,18 @@ int64_t Soundtrack::PlayedLayeredSong::GetPCMPos() { void Soundtrack::PlayedLayeredSong::SetPCMPos( int64_t pos ) { pcm_pos = pos; - for( unsigned i = 0; i < subsongs.size(); i++ ) { - if( pos < subsongs[i]->GetPCMCount() ) { - subsongs[i]->SetPCMPos(pos); + for(auto & subsong : subsongs) { + if( pos < subsong->GetPCMCount() ) { + subsong->SetPCMPos(pos); } } } int64_t Soundtrack::PlayedLayeredSong::GetPCMCount() { int64_t max = 0; - for( unsigned i = 0; i < subsongs.size(); i++ ) { - if( max < subsongs[i]->GetPCMCount() ) { - max = subsongs[i]->GetPCMCount(); + for(auto & subsong : subsongs) { + if( max < subsong->GetPCMCount() ) { + max = subsong->GetPCMCount(); } } return max; @@ -697,9 +697,9 @@ bool Soundtrack::PlayedLayeredSong::SetLayerGain( const std::string& name, float gain = 0.0f; } - for( unsigned i = 0; i < subsongs.size(); i++ ) { - if( subsongs[i]->GetSongName() == name ) { - subsongs[i]->SetGain(gain); + for(auto & subsong : subsongs) { + if( subsong->GetSongName() == name ) { + subsong->SetGain(gain); return true; } } @@ -707,9 +707,9 @@ bool Soundtrack::PlayedLayeredSong::SetLayerGain( const std::string& name, float } float Soundtrack::PlayedLayeredSong::GetLayerGain( const std::string& name ) { - for( unsigned i = 0; i < subsongs.size(); i++ ) { - if( subsongs[i]->GetSongName() == name ) { - return subsongs[i]->GetGain(); + for(auto & subsong : subsongs) { + if( subsong->GetSongName() == name ) { + return subsong->GetGain(); } } return 0.0f; @@ -717,16 +717,16 @@ float Soundtrack::PlayedLayeredSong::GetLayerGain( const std::string& name ) { const std::map Soundtrack::PlayedLayeredSong::GetLayerGains() { std::map gains; - for( unsigned i = 0; i < subsongs.size(); i++ ) { - gains[subsongs[i]->GetSongName()] = subsongs[i]->GetGain(); + for(auto & subsong : subsongs) { + gains[subsong->GetSongName()] = subsong->GetGain(); } return gains; } std::vector Soundtrack::PlayedLayeredSong::GetLayerNames() const { std::vector layers; - for( unsigned i = 0; i < song.songrefs.size(); i++ ) { - layers.push_back(song.songrefs[i].name); + for(const auto & songref : song.songrefs) { + layers.push_back(songref.name); } return layers; } @@ -1348,12 +1348,12 @@ void Soundtrack::AddMusic( const Path &path ) std::map::iterator musit; for(musit = music.begin(); musit != music.end(); ++musit) { bool replace = false; - for(size_t new_i = 0; new_i < parser.music.songs.size(); ++new_i) { + for(auto & song : parser.music.songs) { for(size_t old_i = 0; old_i < musit->second.songs.size(); ++old_i) { - if(strmtch(parser.music.songs[new_i].name, musit->second.songs[old_i].name)) { - LOGW << "Track " << parser.music.songs[new_i].name << " already found in " << musit->first << ", old music set will be overwritten" << std::endl; + if(strmtch(song.name, musit->second.songs[old_i].name)) { + LOGW << "Track " << song.name << " already found in " << musit->first << ", old music set will be overwritten" << std::endl; replace = true; - if(transitionPlayer.GetSongName() == std::string(parser.music.songs[new_i].name)) + if(transitionPlayer.GetSongName() == std::string(song.name)) Stop(); break; } diff --git a/Source/Sound/threaded_sound_wrapper.cpp b/Source/Sound/threaded_sound_wrapper.cpp index 49380d83..3c987a8e 100644 --- a/Source/Sound/threaded_sound_wrapper.cpp +++ b/Source/Sound/threaded_sound_wrapper.cpp @@ -698,11 +698,11 @@ static void ThreadedSoundLoop() std::vector emitters = sound->GetActiveSounds(); - for( uint32_t i = 0; i < emitters.size(); i++ ) { + for(auto & emitter : emitters) { SoundSourceInfo ss; - strscpy(ss.name, emitters[i]->display_name.c_str(), sizeof(ss.name)); - ss.pos = emitters[i]->GetPosition(); + strscpy(ss.name, emitter->display_name.c_str(), sizeof(ss.name)); + ss.pos = emitter->GetPosition(); sdc.sound_source.push_back(ss); } diff --git a/Source/UnitTests/block_allocator_tester.cpp b/Source/UnitTests/block_allocator_tester.cpp index a6ee5f93..1afb7714 100644 --- a/Source/UnitTests/block_allocator_tester.cpp +++ b/Source/UnitTests/block_allocator_tester.cpp @@ -61,11 +61,11 @@ namespace tut uint64_t* ptrs[block_count]; - for(uint32_t i = 0; i < block_count; i++ ) + for(auto & ptr : ptrs) { - ptrs[i] = (uint64_t*)ba.Alloc(blocksize); + ptr = (uint64_t*)ba.Alloc(blocksize); - ensure( "NULL Return", ptrs[i] != NULL ); + ensure( "NULL Return", ptr != NULL ); } free(mem); } diff --git a/Source/UserInput/input.cpp b/Source/UserInput/input.cpp index b369e15d..ee1b25e6 100644 --- a/Source/UserInput/input.cpp +++ b/Source/UserInput/input.cpp @@ -69,10 +69,10 @@ namespace { void PrintControllers(const Input::JoystickMap &open_joysticks){ LOGI << "Current controllers:" << std::endl; - for(Input::JoystickMap::const_iterator iter=open_joysticks.begin(); iter!=open_joysticks.end(); ++iter){ - const Input::RC_JoystickStruct& js = iter->second; + for(const auto & open_joystick : open_joysticks){ + const Input::RC_JoystickStruct& js = open_joystick.second; SDL_Joystick* joystick = (SDL_Joystick*)js.GetConst().sdl_joystick; - LOGI << "Joystick" << iter->first << "," << SDL_JoystickName(joystick) << std::endl; + LOGI << "Joystick" << open_joystick.first << "," << SDL_JoystickName(joystick) << std::endl; } } } // namespace "" @@ -111,20 +111,20 @@ void Input::SetInvertYMouseLook(bool val) { } void Input::UpdateGamepadLookSensitivity() { - for(JoystickMap::iterator iter=open_joysticks_.begin(); iter!=open_joysticks_.end(); ++iter) + for(auto & open_joystick : open_joysticks_) { char buffer[64]; - sprintf(buffer, "gamepad_%i_look_sensitivity", iter->second->player_input); - iter->second->joystick.look_sensitivity_ = config[buffer].toNumber(); + sprintf(buffer, "gamepad_%i_look_sensitivity", open_joystick.second->player_input); + open_joystick.second->joystick.look_sensitivity_ = config[buffer].toNumber(); } } void Input::UpdateGamepadDeadzone() { - for(JoystickMap::iterator iter=open_joysticks_.begin(); iter!=open_joysticks_.end(); ++iter) + for(auto & open_joystick : open_joysticks_) { char buffer[64]; - sprintf(buffer, "gamepad_%i_deadzone", iter->second->player_input); - iter->second->joystick.deadzone = config[buffer].toNumber(); + sprintf(buffer, "gamepad_%i_deadzone", open_joystick.second->player_input); + open_joystick.second->joystick.deadzone = config[buffer].toNumber(); } } @@ -256,8 +256,8 @@ void Input::Initialize() { } void Input::Dispose() { - for(JoystickMap::iterator iter=open_joysticks_.begin(); iter!=open_joysticks_.end(); ++iter){ - RC_JoystickStruct js = iter->second; + for(auto & open_joystick : open_joysticks_){ + RC_JoystickStruct js = open_joystick.second; SDL_Joystick* joystick = (SDL_Joystick*)js->sdl_joystick; SDL_JoystickClose(joystick); } @@ -576,9 +576,9 @@ void Input::ProcessController(int controller_id, float timestep) { // Set all keydown counts to negative PlayerInput::KeyDownMap &kd = control.key_down; - for(PlayerInput::KeyDownMap::iterator iter = kd.begin(); iter != kd.end(); ++iter){ - iter->second.count *= -1; - iter->second.depth = 0.0f; + for(auto & iter : kd){ + iter.second.count *= -1; + iter.second.depth = 0.0f; } std::set active_buttons; // If any bound controller button is pressed more than halfway in @@ -594,9 +594,9 @@ void Input::ProcessController(int controller_id, float timestep) { } const Joystick& joystick = js.GetConst().joystick; const Joystick::ButtonMap& bm = joystick.buttons_down_; - for(Joystick::ButtonMap::const_iterator iter2 = bm.begin(); iter2 != bm.end(); ++iter2){ - if(iter2->second){ - float depth = iter2->second; + for(const auto & iter2 : bm){ + if(iter2.second){ + float depth = iter2.second; if(depth > 0.5f) { use_controller_input_ = true; run = false; @@ -608,30 +608,30 @@ void Input::ProcessController(int controller_id, float timestep) { } // Joystick input if(allow_controller_input_ && use_controller_input_) { - for(JoystickMap::iterator iter = open_joysticks_.begin(); iter != open_joysticks_.end(); ++iter){ - const RC_JoystickStruct js = iter->second; + for(auto & open_joystick : open_joysticks_){ + const RC_JoystickStruct js = open_joystick.second; if(js.GetConst().player_input != controller_id){ continue; } const Joystick& joystick = js.GetConst().joystick; const Joystick::ButtonMap& bm = joystick.buttons_down_; - for(Joystick::ButtonMap::const_iterator iter2 = bm.begin(); iter2 != bm.end(); ++iter2){ - if(iter2->second){ + for(const auto & iter2 : bm){ + if(iter2.second){ float sensitivity = 1.0f; - if(memcmp(iter2->first.c_str(), "look", 4) == 0) { + if(memcmp(iter2.first.c_str(), "look", 4) == 0) { sensitivity = joystick.look_sensitivity_; } - float depth = iter2->second * sensitivity; + float depth = iter2.second * sensitivity; - int &count = control.key_down[iter2->first].count; - int &depth_count = control.key_down[iter2->first].depth_count; + int &count = control.key_down[iter2.first].count; + int &depth_count = control.key_down[iter2.first].depth_count; if(count <= 0){ count *= -1; ++count; if(depth > KeyState::kDepthThreshold) ++depth_count; } - control.key_down[iter2->first].depth = depth; + control.key_down[iter2.first].depth = depth; } } } @@ -641,9 +641,9 @@ void Input::ProcessController(int controller_id, float timestep) { if(catch_kbmouse){ static const std::string kKey = "key"; const StrMap &key_map = bindings_[kKey]; - for(StrMap::const_iterator iter = key_map.begin(); iter != key_map.end(); ++iter) { - if(IsKeyDown(iter->second.c_str())) { - PlayerInputKeyDown(&control.key_down[iter->first]); + for(const auto & iter : key_map) { + if(IsKeyDown(iter.second.c_str())) { + PlayerInputKeyDown(&control.key_down[iter.first]); use_controller_input_ = false; } } @@ -657,11 +657,11 @@ void Input::ProcessController(int controller_id, float timestep) { } } // Zero all negative keydown counts - for(PlayerInput::KeyDownMap::iterator iter = kd.begin(); iter != kd.end(); ++iter){ - if(iter->second.count < 0){ - iter->second.count = 0; - iter->second.depth_count = 0; - iter->second.depth = 0.0f; + for(auto & iter : kd){ + if(iter.second.count < 0){ + iter.second.count = 0; + iter.second.depth_count = 0; + iter.second.depth = 0.0f; } } } @@ -785,15 +785,15 @@ PlayerInput* Input::GetController( int id ) { } void Input::ProcessBindings() { - for(JoystickMap::iterator js_iter = open_joysticks_.begin(); js_iter != open_joysticks_.end(); ++js_iter){ - RC_JoystickStruct js = js_iter->second; + for(auto & open_joystick : open_joysticks_){ + RC_JoystickStruct js = open_joystick.second; js->joystick.ClearBinding(); char gamepad_name[32]; FormatString(gamepad_name, 32, "gamepad_%i", js->player_input); if(!js->gamepad_bind.empty()){ StrMap& gamepad_map = bindings_[gamepad_name]; - for(StrMap::iterator xb_iter = gamepad_map.begin(); xb_iter != gamepad_map.end(); ++xb_iter){ - const std::string& input_str = xb_iter->second; + for(auto & xb_iter : gamepad_map){ + const std::string& input_str = xb_iter.second; ControllerInput::Input input = SDLStringToController(input_str.c_str()); if(input != ControllerInput::NONE){ SDL_GameControllerButtonBind bind; @@ -821,7 +821,7 @@ void Input::ProcessBindings() { break; } if(bind.bindType != SDL_CONTROLLER_BINDTYPE_NONE){ - js->joystick.ProcessBinding(input, xb_iter->first); + js->joystick.ProcessBinding(input, xb_iter.first); } } } @@ -862,8 +862,8 @@ void Input::SetUpForXPlayers( unsigned num_players ) { } if(num_players <= 1){ - for(JoystickMap::iterator iter = open_joysticks_.begin(); iter != open_joysticks_.end(); ++iter){ - RC_JoystickStruct js = iter->second; + for(auto & open_joystick : open_joysticks_){ + RC_JoystickStruct js = open_joystick.second; js->player_input = 0; std::map::iterator buttons_iter = js->joystick.buttons_down_.begin(); for(; buttons_iter != js->joystick.buttons_down_.end(); ++buttons_iter) { @@ -875,8 +875,8 @@ void Input::SetUpForXPlayers( unsigned num_players ) { if(num_players >= 2){ if(num_joysticks < (int)num_players){ int index = 1; - for(JoystickMap::iterator iter = open_joysticks_.begin(); iter != open_joysticks_.end(); ++iter){ - RC_JoystickStruct js = iter->second; + for(auto & open_joystick : open_joysticks_){ + RC_JoystickStruct js = open_joystick.second; js->player_input = index; ++index; std::map::iterator buttons_iter = js->joystick.buttons_down_.begin(); @@ -886,8 +886,8 @@ void Input::SetUpForXPlayers( unsigned num_players ) { } } else { int index = 0; - for(JoystickMap::iterator iter = open_joysticks_.begin(); iter != open_joysticks_.end(); ++iter){ - RC_JoystickStruct js = iter->second; + for(auto & open_joystick : open_joysticks_){ + RC_JoystickStruct js = open_joystick.second; js->player_input = index; ++index; std::map::iterator buttons_iter = js->joystick.buttons_down_.begin(); @@ -923,10 +923,10 @@ void CheckBinding(const Config::Map::const_iterator &iter, const std::string &ty static void CompleteGamepadBindings(const std::string &type, BindMap &bind_map) { StrMap& gamepad = bind_map[type]; - for(StrMap::iterator iter = bind_map["gamepad"].begin(), end = bind_map["gamepad"].end(); iter != end; ++iter) { - StrMap::iterator gamepad_iter = gamepad.find(iter->first); + for(auto & iter : bind_map["gamepad"]) { + StrMap::iterator gamepad_iter = gamepad.find(iter.first); if(gamepad_iter == gamepad.end()) { - gamepad[iter->first] = iter->second; + gamepad[iter.first] = iter.second; } } char buffer[128]; @@ -1055,12 +1055,12 @@ std::vector Input::GetMouseInputs() { std::vector Input::GetJoystickInputs(int player_index) { std::vector ret_inputs; - for(JoystickMap::iterator iter = open_joysticks_.begin(); iter != open_joysticks_.end(); ++iter) { - if(iter->second->player_input == player_index) { - std::vector inputs = iter->second->joystick.GetJoystickInputs(); + for(auto & open_joystick : open_joysticks_) { + if(open_joystick.second->player_input == player_index) { + std::vector inputs = open_joystick.second->joystick.GetJoystickInputs(); ret_inputs.reserve(ret_inputs.size() + inputs.size()); - for(size_t i = 0; i < inputs.size(); ++i) { - ret_inputs.push_back(inputs[i]); + for(auto & input : inputs) { + ret_inputs.push_back(input); } } } diff --git a/Source/UserInput/keyTranslator.cpp b/Source/UserInput/keyTranslator.cpp index 057a5316..dee3216e 100644 --- a/Source/UserInput/keyTranslator.cpp +++ b/Source/UserInput/keyTranslator.cpp @@ -565,20 +565,20 @@ void InitKeyTranslator() { std::vector > offsets; size_t cur_index = 0; - for( size_t i = 0; i < sizeof(SDL_SCANCODES)/sizeof(uint32_t); i++ ) { - const char* scancodename = SDL_GetScancodeName((SDL_Scancode)SDL_SCANCODES[i]); + for(unsigned int & i : SDL_SCANCODES) { + const char* scancodename = SDL_GetScancodeName((SDL_Scancode)i); size_t memlen = strlen(scancodename) + 1; if(cur_index + memlen > key_translation_memory.size()) { key_translation_memory.resize(key_translation_memory.size()+1024); } memcpy(&key_translation_memory[cur_index], scancodename, memlen); UTF8InPlaceLower(&key_translation_memory[cur_index]); - offsets.push_back(std::pair(cur_index,SDL_SCANCODES[i])); + offsets.push_back(std::pair(cur_index,i)); cur_index += memlen; } - for( size_t i = 0; i < offsets.size(); i++ ) { - keys.push_back(KeyPair(&key_translation_memory[offsets[i].first], (SDL_Scancode)offsets[i].second)); + for(auto & offset : offsets) { + keys.push_back(KeyPair(&key_translation_memory[offset.first], (SDL_Scancode)offset.second)); } keys.push_back(KeyPair("backspace", SDL_SCANCODE_BACKSPACE)); diff --git a/Source/UserInput/keyboard.cpp b/Source/UserInput/keyboard.cpp index 3cb4caf9..78edd81b 100644 --- a/Source/UserInput/keyboard.cpp +++ b/Source/UserInput/keyboard.cpp @@ -403,8 +403,8 @@ bool Keyboard::wasScancodePressed(SDL_Scancode the_key, const uint32_t kimf) con } void Keyboard::clearKeyPresses() { - for (KeyStatusMap::iterator iter = keys.begin(); iter != keys.end(); ++iter){ - KeyStatus &key = iter->second; + for (auto & iter : keys){ + KeyStatus &key = iter.second; key.pressed=0; } } diff --git a/Source/UserInput/keycommands.cpp b/Source/UserInput/keycommands.cpp index 9a66ca82..0e87ab32 100644 --- a/Source/UserInput/keycommands.cpp +++ b/Source/UserInput/keycommands.cpp @@ -345,8 +345,8 @@ void KeyCommand::Initialize() { FatalError("Error", "Hash collision in KeyCommand hash map"); } } - for(int i=0; i& arr) { binn* l_vec_int = binn_list(); - for(int i = 0; i < arr.size(); i++) { - binn_list_add_int32(l_vec_int, arr[i]); + for(int i : arr) { + binn_list_add_int32(l_vec_int, i); } binn_object_set_list(l, key, l_vec_int); diff --git a/Source/Utility/strings.cpp b/Source/Utility/strings.cpp index d77a9a8d..15914591 100644 --- a/Source/Utility/strings.cpp +++ b/Source/Utility/strings.cpp @@ -229,11 +229,9 @@ bool hasEnding (string const &fullString, string const &ending) { bool hasAnyOfEndings( const string &fullString, const vector &endings) { - for( vector::const_iterator sit = endings.begin(); - sit != endings.end(); - sit++ ) + for(const auto & ending : endings) { - if( hasEnding( fullString, *sit ) ) + if( hasEnding( fullString, ending ) ) { return true; } diff --git a/Source/XML/Parsers/activemodsparser.cpp b/Source/XML/Parsers/activemodsparser.cpp index af082dc4..acd3c7a2 100644 --- a/Source/XML/Parsers/activemodsparser.cpp +++ b/Source/XML/Parsers/activemodsparser.cpp @@ -109,12 +109,12 @@ uint32_t ActiveModsParser::Load( const std::string& path ) { bool ActiveModsParser::SerializeInto( TiXmlDocument* doc ) { TiXmlDeclaration * decl = new TiXmlDeclaration( "2.0", "", "" ); TiXmlElement * root = new TiXmlElement("ActiveMods"); - for( unsigned i = 0; i < mod_instances.size(); i++ ) { + for(auto & mod_instance : mod_instances) { TiXmlElement * mi = new TiXmlElement("ModInstance"); - mi->SetAttribute( "id", mod_instances[i].id ); - mi->SetAttribute( "activated", mod_instances[i].activated ? "true" : "false" ); + mi->SetAttribute( "id", mod_instance.id ); + mi->SetAttribute( "activated", mod_instance.activated ? "true" : "false" ); const char* modsource = ""; - switch(mod_instances[i].modsource) { + switch(mod_instance.modsource) { case ModSourceLocalModFolder: modsource = "local"; break; @@ -127,7 +127,7 @@ bool ActiveModsParser::SerializeInto( TiXmlDocument* doc ) { break; } mi->SetAttribute("modsource", modsource); - mi->SetAttribute("version", mod_instances[i].version); + mi->SetAttribute("version", mod_instance.version); root->LinkEndChild(mi); } doc->LinkEndChild(decl); @@ -174,8 +174,8 @@ void ActiveModsParser::SetModInstanceActive(const char* id, ModSource modsource, } bool ActiveModsParser::HasModInstance(const char* id, ModSource modsource) { - for( unsigned i = 0; i < mod_instances.size(); i++ ) { - if(strmtch(mod_instances[i].id,id) && mod_instances[i].modsource == modsource) { + for(auto & mod_instance : mod_instances) { + if(strmtch(mod_instance.id,id) && mod_instance.modsource == modsource) { return true; } } @@ -183,9 +183,9 @@ bool ActiveModsParser::HasModInstance(const char* id, ModSource modsource) { } ActiveModsParser::ModInstance ActiveModsParser::GetModInstance(const char* id, ModSource modsource) { - for( unsigned i = 0; i < mod_instances.size(); i++ ) { - if(strmtch(mod_instances[i].id,id) && mod_instances[i].modsource == modsource) { - return mod_instances[i]; + for(auto & mod_instance : mod_instances) { + if(strmtch(mod_instance.id,id) && mod_instance.modsource == modsource) { + return mod_instance; } } return ModInstance(id,modsource,false,""); diff --git a/Source/XML/Parsers/assetloadwarningparser.cpp b/Source/XML/Parsers/assetloadwarningparser.cpp index 64971ee4..62be1221 100644 --- a/Source/XML/Parsers/assetloadwarningparser.cpp +++ b/Source/XML/Parsers/assetloadwarningparser.cpp @@ -60,12 +60,12 @@ bool AssetLoadWarningParser::Save( const std::string& path ) { TiXmlDeclaration * decl = new TiXmlDeclaration( "2.0", "", "" ); TiXmlElement * root = new TiXmlElement("AssetWarnings"); - for( std::set::iterator sit = asset_warnings.begin(); sit != asset_warnings.end(); sit++ ) { + for(const auto & asset_warning : asset_warnings) { TiXmlElement * e = new TiXmlElement("AssetWarning"); - e->SetAttribute("asset_type",sit->asset_type.c_str()); - e->SetAttribute("path",sit->path.c_str()); - e->SetAttribute("level_name",sit->level_name.c_str()); - char flags[9]; flags_to_string(flags,sit->load_flags); e->SetAttribute("load_flags",flags); + e->SetAttribute("asset_type",asset_warning.asset_type.c_str()); + e->SetAttribute("path",asset_warning.path.c_str()); + e->SetAttribute("level_name",asset_warning.level_name.c_str()); + char flags[9]; flags_to_string(flags,asset_warning.load_flags); e->SetAttribute("load_flags",flags); root->LinkEndChild(e); } diff --git a/Source/XML/level_loader.cpp b/Source/XML/level_loader.cpp index 5464a46e..9f506f9d 100644 --- a/Source/XML/level_loader.cpp +++ b/Source/XML/level_loader.cpp @@ -107,8 +107,7 @@ void AddCamera(SceneGraph &s) { static void LoadAll(const PathSet &path_set, ThreadedSound* sound) { std::list skeleton_paths; - for(PathSet::const_iterator iter = path_set.begin(); iter != path_set.end(); ++iter) { - const std::string &entry = (*iter); + for(const auto & entry : path_set) { int space_pos = entry.find(' '); const std::string &type = entry.substr(0,space_pos); const std::string &path = entry.substr(space_pos+1, entry.size()-(space_pos+1)); @@ -248,13 +247,11 @@ static int IDAndType_CompareID(const void *a, const void *b) { static void ExtractFlatList(EntityDescriptionList *desc_list, std::vector &id_used){ uint32_t counter = 1; //Zero is assigned to the terrain //bool print_results = false; - for(EntityDescriptionList::iterator it = desc_list->begin(); - it != desc_list->end(); - ++it) + for(auto & it : *desc_list) { id_used.resize(id_used.size()+1); IDAndType *id_and_type = &id_used.back(); - id_and_type->desc = &(*it); + id_and_type->desc = ⁢ id_and_type->desc->GetEditableField(EDF_ENTITY_TYPE)->ReadInt((int*)&id_and_type->type); id_and_type->desc->GetEditableField(EDF_ID)->ReadInt(&id_and_type->id); id_and_type->counter = counter++; @@ -428,16 +425,16 @@ bool LevelLoader::LoadLevel(const Path& level_path, SceneGraph& s) { static const int kBufSize = 256; char buf[kBufSize]; - for(unsigned i=0, len=li.desc_list_.size(); idata.empty()){ FormatString(buf, kBufSize, "Adding object: %s", std::string(path_field->data.begin(), path_field->data.end()).c_str()); PROFILER_ENTER_DYNAMIC_STRING(g_profiler_ctx, buf); } else { PROFILER_ENTER(g_profiler_ctx, "Adding object: unknown"); } - Object * obj = MapEditor::AddEntityFromDesc(&s, li.desc_list_[i], true); + Object * obj = MapEditor::AddEntityFromDesc(&s, i, true); if( obj == NULL ) { LOGE << "Failed to construct object \"" << buf << "\" for level load" << std::endl; } @@ -481,8 +478,8 @@ bool LevelLoader::LoadLevel(const Path& level_path, SceneGraph& s) { s.SendMessageToAllObjects(OBJECT_MSG::FINALIZE_LOADED_CONNECTIONS); AddLoadingText("Loading ambient sounds and music..."); - for(unsigned i=0; iGetSound()->AddAmbientTriangle(li.ambient_sounds_[i]); + for(auto & ambient_sound : li.ambient_sounds_){ + Engine::Instance()->GetSound()->AddAmbientTriangle(ambient_sound); } AddLoadingText("Getting path set..."); PathSet path_set; @@ -555,8 +552,7 @@ void LevelLoader::SaveTerrain(TiXmlNode* root, SceneGraph* s) { terrain_el->LinkEndChild(terrain_sub_el); TiXmlElement *does = new TiXmlElement("DetailObjects"); - for(unsigned i=0; iSetAttribute("obj_path", dol.obj_path.c_str()); doe->SetAttribute("weight_path", dol.weight_path.c_str()); @@ -724,11 +720,11 @@ void LevelLoader::SaveLevel(SceneGraph &s, SaveLevelType type) { const std::vector& ambient_triangles = Engine::Instance()->GetSound()->GetAmbientTriangles(); - for(unsigned i=0; iLinkEndChild(ambient); - ambient->SetAttribute("path", ambient_triangles[i].path.c_str()); + ambient->SetAttribute("path", ambient_triangle.path.c_str()); } } @@ -771,8 +767,8 @@ void LevelLoader::SaveLevel(SceneGraph &s, SaveLevelType type) { std::vector recent_items = s.level->GetRecentlyCreatedItems(); - for( unsigned i = 0; i < recent_items.size(); i++ ) { - SpawnerItem* si = &recent_items[i]; + for(auto & recent_item : recent_items) { + SpawnerItem* si = &recent_item; TiXmlElement* element = new TiXmlElement("SpawnerItem"); element->SetAttribute("display_name", si->display_name.c_str()); -- cgit v1.2.3 From 30be6f88713ed6e1b043cc72cafc1df7728f0710 Mon Sep 17 00:00:00 2001 From: Stephan Vedder Date: Wed, 4 May 2022 14:27:53 +0200 Subject: Manually improve generated changes --- Source/Editors/map_editor.cpp | 21 ++++++++++----------- Source/GUI/dimgui/settings_screen.cpp | 16 ++++++++-------- Source/Graphics/csg.cpp | 12 ++++++------ Source/Graphics/lightprobecollection.cpp | 8 ++++---- Source/Graphics/model.cpp | 26 +++++++++++++------------- Source/Math/mat4.cpp | 4 ++-- Source/Objects/riggedobject.cpp | 4 ++-- Source/Physics/bulletobject.cpp | 4 ++-- 8 files changed, 47 insertions(+), 48 deletions(-) diff --git a/Source/Editors/map_editor.cpp b/Source/Editors/map_editor.cpp index 333b7bf5..9d2ba91e 100644 --- a/Source/Editors/map_editor.cpp +++ b/Source/Editors/map_editor.cpp @@ -851,8 +851,8 @@ void MapEditor::Draw() { } if(always_draw_hotspot_connections) { vec3 start = obj->GetTranslation(); - for(int j : obj->connected_to) { - vec3 end = scenegraph_->GetObjectFromID(j)->GetTranslation(); + for(int id : obj->connected_to) { + vec3 end = scenegraph_->GetObjectFromID(id)->GetTranslation(); DebugDraw::Instance()->AddLine(start, end, vec4(0.0f,1.0f,0.0f,0.8f), _delete_on_draw); } } @@ -953,23 +953,22 @@ void MapEditor::Draw() { float highlit_obj_dist = FLT_MAX; std::vector connected_ids; connected_ids.reserve(64); - for(auto & i : selected) { - Object* selected_obj = i; + for(Object* selected_obj : selected) { box_objects.push_back(selected_obj); connected_ids.clear(); - i->GetConnectionIDs(&connected_ids); + selected_obj->GetConnectionIDs(&connected_ids); for(int connected_id : connected_ids) { Object* obj = scenegraph_->GetObjectFromID(connected_id); GetClosest(mouseray, obj, highlit_obj, highlit_obj_dist); box_objects.push_back(obj); } - for(int j : selected_obj->connected_to) { - Object* obj = scenegraph_->GetObjectFromID(j); + for(int id : selected_obj->connected_to) { + Object* obj = scenegraph_->GetObjectFromID(id); GetClosest(mouseray, obj, highlit_obj, highlit_obj_dist); box_objects.push_back(obj); } - for(int j : selected_obj->connected_from) { - Object* obj = scenegraph_->GetObjectFromID(j); + for(int id : selected_obj->connected_from) { + Object* obj = scenegraph_->GetObjectFromID(id); GetClosest(mouseray, obj, highlit_obj, highlit_obj_dist); box_objects.push_back(obj); } @@ -1292,8 +1291,8 @@ void MapEditor::Update(GameCursor* cursor) { entities.push_back(obj); } } - for (auto & entitie : entities) { - entitie->SaveHistoryState(chunks, state_id); + for (auto & entity : entities) { + entity->SaveHistoryState(chunks, state_id); } sky_editor_->SaveHistoryState(chunks, state_id); // Find out how many chunks have been changed diff --git a/Source/GUI/dimgui/settings_screen.cpp b/Source/GUI/dimgui/settings_screen.cpp index 5643d59a..dd9def22 100644 --- a/Source/GUI/dimgui/settings_screen.cpp +++ b/Source/GUI/dimgui/settings_screen.cpp @@ -1167,14 +1167,14 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ std::vector difficulties = config.GetDifficultyPresets(); if(ImGui::BeginMenu("Finish All Levels On Difficulty")) { - for(auto & difficultie : difficulties) { - if( ImGui::Button(difficultie.c_str())) { + for(auto & difficulty : difficulties) { + if( ImGui::Button(difficulty.c_str())) { std::vector campaigns = ModLoading::Instance().GetCampaigns(); for(auto camp : campaigns) { for( size_t j = 0; j < camp.levels.size(); j++ ) { SavedLevel& s = Engine::Instance()->save_file_.GetSave(camp.id.str(),"linear_campaign",camp.levels[j].id.str()); - if( false == s.ArrayContainsValue("finished_difficulties",difficultie) ) { - s.AppendArrayValue("finished_difficulties",difficultie); + if( false == s.ArrayContainsValue("finished_difficulties",difficulty) ) { + s.AppendArrayValue("finished_difficulties",difficulty); } } } @@ -1191,11 +1191,11 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){ for( size_t j = 0; j < camp.levels.size(); j++ ) { ModInstance::Level level = camp.levels[j]; if(ImGui::BeginMenu(level.title)) { - for(auto & difficultie : difficulties) { - if( ImGui::Button(difficultie.c_str())) { + for(auto & difficulty : difficulties) { + if( ImGui::Button(difficulty.c_str())) { SavedLevel& s = Engine::Instance()->save_file_.GetSave(camp.id.str(),"linear_campaign",level.id.str()); - if( false == s.ArrayContainsValue("finished_difficulties",difficultie) ) { - s.AppendArrayValue("finished_difficulties",difficultie); + if( false == s.ArrayContainsValue("finished_difficulties",difficulty) ) { + s.AppendArrayValue("finished_difficulties",difficulty); } Engine::Instance()->save_file_.QueueWriteInPlace(); } diff --git a/Source/Graphics/csg.cpp b/Source/Graphics/csg.cpp index bd758410..04531b4e 100644 --- a/Source/Graphics/csg.cpp +++ b/Source/Graphics/csg.cpp @@ -203,13 +203,13 @@ namespace { struct vec3d { double entries[3]; vec3d(double val){ - for(double & entrie : entries){ - entrie = val; + for(double & entry : entries){ + entry = val; } } vec3d(){ - for(double & entrie : entries){ - entrie = 0.0; + for(double & entry : entries){ + entry = 0.0; } } double& operator[](int which){ @@ -1056,8 +1056,8 @@ void AddCSGResult(const CSGResult &result, CSGModelInfo *csg_model, const Model& csg_model->faces.reserve(csg_model->faces.size()+result.indices.size()); int old_faces = csg_model->verts.size()/3; if(!flip){ - for(int indice : result.indices){ - csg_model->faces.push_back(indice + old_faces); + for(int index : result.indices){ + csg_model->faces.push_back(index + old_faces); } } else { for(int i=0, len=result.indices.size(); iCopyModel(base_model_id); Model& model = Models::Instance()->GetModel(model_id[0]); - for(float & vertice : model.vertices){ - vertice = 0.0f; + for(float & vertex : model.vertices){ + vertex = 0.0f; } for(float & tex_coord : model.tex_coords){ tex_coord = 0.0f; diff --git a/Source/Physics/bulletobject.cpp b/Source/Physics/bulletobject.cpp index 727d7dc5..6d1c163c 100644 --- a/Source/Physics/bulletobject.cpp +++ b/Source/Physics/bulletobject.cpp @@ -524,8 +524,8 @@ void BulletObject::CheckForNAN() { btTransform bt_transform; GetDisplayTransform(&bt_transform); mat4 test_mat = SafeGetOpenGLMatrix(body->getWorldTransform()); - for(float entrie : test_mat.entries){ - if(entrie != entrie){ + for(float entry : test_mat.entries){ + if(entry != entry){ LOGE << "NAN found in BulletObject" << std::endl; break; } -- cgit v1.2.3 From 59dfb3c04c72003a9ac8bd504720237318852269 Mon Sep 17 00:00:00 2001 From: Stephan Vedder Date: Wed, 4 May 2022 14:30:48 +0200 Subject: Fixes --- Source/Internal/timer.cpp | 4 ++-- Source/Memory/stack_allocator.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Source/Internal/timer.cpp b/Source/Internal/timer.cpp index 91848e1c..2e6f84ee 100644 --- a/Source/Internal/timer.cpp +++ b/Source/Internal/timer.cpp @@ -185,7 +185,7 @@ Timer::Timer(): last_tick(0), wall_time(0) { - for(unsigned long & i : frame){ - i=0; + for (auto& i : frame) { + i = 0; } } diff --git a/Source/Memory/stack_allocator.cpp b/Source/Memory/stack_allocator.cpp index 4e07c452..1a46ffc4 100644 --- a/Source/Memory/stack_allocator.cpp +++ b/Source/Memory/stack_allocator.cpp @@ -101,7 +101,7 @@ uintptr_t StackAllocator::TopBlockSize() { } void StackAllocator::Init(void* p_mem, size_t p_size) { - for (unsigned long & stack_block_pt : stack_block_pts) { + for (auto & stack_block_pt : stack_block_pts) { stack_block_pt = 0; } mem = p_mem; @@ -110,7 +110,7 @@ void StackAllocator::Init(void* p_mem, size_t p_size) { } void StackAllocator::Dispose() { - for (unsigned long & stack_block_pt : stack_block_pts) { + for (auto & stack_block_pt : stack_block_pts) { stack_block_pt = 0; } mem = 0; -- cgit v1.2.3