Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/WolfireGames/overgrowth.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNeal Gompa (ニール・ゴンパ) <neal@gompa.dev>2022-05-06 06:37:54 +0300
committerGitHub <noreply@github.com>2022-05-06 06:37:54 +0300
commit07bd9a9daa96b1cd8acf523d3b4051ec3bbc4ff4 (patch)
treefdc115edf22d0cba3aaa42feb07c00d2ff81a411
parent536161f9ae1c7bfcdd0b8c1f694367e9d7a960ad (diff)
parent59dfb3c04c72003a9ac8bd504720237318852269 (diff)
Merge pull request #61 from feliwir/clang-tidy-modernize
Use range based loops where applicable
-rw-r--r--Source/AI/navmesh.cpp14
-rw-r--r--Source/AI/sample.cpp38
-rw-r--r--Source/AI/sample_interfaces.cpp6
-rw-r--r--Source/Asset/Asset/animation.cpp304
-rw-r--r--Source/Asset/Asset/character.cpp26
-rw-r--r--Source/Asset/Asset/item.cpp30
-rw-r--r--Source/Asset/Asset/levelset.cpp5
-rw-r--r--Source/Asset/Asset/lipsyncfile.cpp4
-rw-r--r--Source/Asset/Asset/material.cpp5
-rw-r--r--Source/Asset/Asset/objectfile.cpp16
-rw-r--r--Source/Asset/Asset/reactions.cpp4
-rw-r--r--Source/Asset/Asset/syncedanimation.cpp8
-rw-r--r--Source/Asset/Asset/voicefile.cpp5
-rw-r--r--Source/Asset/assetmanagerthreadhandler.cpp6
-rw-r--r--Source/Editors/actors_editor.cpp137
-rw-r--r--Source/Editors/map_editor.cpp342
-rw-r--r--Source/Editors/sky_editor.cpp3
-rw-r--r--Source/GUI/IMUI/im_container.cpp46
-rw-r--r--Source/GUI/IMUI/im_divider.cpp110
-rw-r--r--Source/GUI/IMUI/im_element.cpp98
-rw-r--r--Source/GUI/IMUI/im_events.cpp8
-rw-r--r--Source/GUI/IMUI/im_support.cpp8
-rw-r--r--Source/GUI/IMUI/imgui.cpp114
-rw-r--r--Source/GUI/IMUI/imui.cpp3
-rw-r--r--Source/GUI/IMUI/imui_script.cpp4
-rw-r--r--Source/GUI/dimgui/dimgui.cpp262
-rw-r--r--Source/GUI/dimgui/modmenu.cpp82
-rw-r--r--Source/GUI/dimgui/settings_screen.cpp45
-rw-r--r--Source/Game/EntityDescription.cpp59
-rw-r--r--Source/Game/characterscript.cpp24
-rw-r--r--Source/Game/color_tint_component.cpp3
-rw-r--r--Source/Game/level.cpp202
-rw-r--r--Source/Game/levelinfo.cpp18
-rw-r--r--Source/Game/paths.cpp30
-rw-r--r--Source/Game/reactionscript.cpp6
-rw-r--r--Source/Game/savefile.cpp62
-rw-r--r--Source/Game/terraininfo.cpp16
-rw-r--r--Source/Graphics/animationclient.cpp16
-rw-r--r--Source/Graphics/animationreader.cpp22
-rw-r--r--Source/Graphics/bloodsurface.cpp20
-rw-r--r--Source/Graphics/camera.cpp40
-rw-r--r--Source/Graphics/csg.cpp86
-rw-r--r--Source/Graphics/detailobjectsurface.cpp12
-rw-r--r--Source/Graphics/drawbatch.cpp74
-rw-r--r--Source/Graphics/dynamiclightcollection.cpp6
-rw-r--r--Source/Graphics/flares.cpp15
-rw-r--r--Source/Graphics/font_renderer.cpp4
-rw-r--r--Source/Graphics/halfedge.cpp18
-rw-r--r--Source/Graphics/hudimage.cpp3
-rw-r--r--Source/Graphics/kdtreecluster.cpp48
-rw-r--r--Source/Graphics/lightprobecollection.cpp26
-rw-r--r--Source/Graphics/model.cpp72
-rw-r--r--Source/Graphics/modelsurfacewalker.cpp32
-rw-r--r--Source/Graphics/palette.cpp8
-rw-r--r--Source/Graphics/particles.cpp37
-rw-r--r--Source/Graphics/shaders.cpp61
-rw-r--r--Source/Graphics/simplify.cpp53
-rw-r--r--Source/Graphics/skeleton.cpp176
-rw-r--r--Source/Graphics/terrain.cpp44
-rw-r--r--Source/Graphics/text.cpp4
-rw-r--r--Source/Graphics/textures.cpp19
-rw-r--r--Source/Images/nv_image.cpp4
-rw-r--r--Source/Images/texture_data.cpp4
-rw-r--r--Source/Internal/config.cpp16
-rw-r--r--Source/Internal/error.cpp6
-rw-r--r--Source/Internal/filesystem.cpp40
-rw-r--r--Source/Internal/hardware_specs.cpp18
-rw-r--r--Source/Internal/locale.cpp8
-rw-r--r--Source/Internal/modloading.cpp167
-rw-r--r--Source/Internal/path_set.cpp3
-rw-r--r--Source/Internal/timer.cpp8
-rw-r--r--Source/Internal/treestructure.cpp20
-rw-r--r--Source/JSON/jsoncpp.cpp19
-rw-r--r--Source/JSON/jsonhelper.cpp4
-rw-r--r--Source/Logging/logdata.cpp46
-rw-r--r--Source/Main/altmain.cpp12
-rw-r--r--Source/Main/engine.cpp201
-rw-r--r--Source/Main/scenegraph.cpp186
-rw-r--r--Source/Math/mat4.cpp4
-rw-r--r--Source/Memory/stack_allocator.cpp8
-rw-r--r--Source/Objects/ambientsoundobject.cpp3
-rw-r--r--Source/Objects/decalobject.cpp3
-rw-r--r--Source/Objects/dynamiclightobject.cpp3
-rw-r--r--Source/Objects/envobject.cpp41
-rw-r--r--Source/Objects/envobjectattach.cpp6
-rw-r--r--Source/Objects/group.cpp77
-rw-r--r--Source/Objects/hotspot.cpp7
-rw-r--r--Source/Objects/itemobject.cpp47
-rw-r--r--Source/Objects/lightprobeobject.cpp3
-rw-r--r--Source/Objects/movementobject.cpp116
-rw-r--r--Source/Objects/navmeshconnectionobject.cpp27
-rw-r--r--Source/Objects/object.cpp19
-rw-r--r--Source/Objects/pathpointobject.cpp27
-rw-r--r--Source/Objects/placeholderobject.cpp20
-rw-r--r--Source/Objects/reflectioncaptureobject.cpp3
-rw-r--r--Source/Objects/riggedobject.cpp580
-rw-r--r--Source/Objects/terrainobject.cpp25
-rw-r--r--Source/Ogda/Searchers/Seekers/actorobjectlevelseeker.cpp14
-rw-r--r--Source/Ogda/manifestresult.cpp4
-rw-r--r--Source/Online/Message/attach_to_message.cpp3
-rw-r--r--Source/Online/Message/movement_object_update.cpp4
-rw-r--r--Source/Online/online.cpp25
-rw-r--r--Source/Online/online_utility.cpp16
-rw-r--r--Source/Physics/bulletobject.cpp4
-rw-r--r--Source/Physics/bulletworld.cpp54
-rw-r--r--Source/Scripting/angelscript/add_on/scripthelper/scripthelper.cpp5
-rw-r--r--Source/Scripting/angelscript/ascontext.cpp8
-rw-r--r--Source/Scripting/angelscript/ascrashdump.cpp26
-rw-r--r--Source/Scripting/angelscript/asdebugger.cpp36
-rw-r--r--Source/Scripting/angelscript/asfuncs.cpp144
-rw-r--r--Source/Scripting/angelscript/asprofiler.cpp58
-rw-r--r--Source/Scripting/scriptfile.cpp14
-rw-r--r--Source/Scripting/scriptparams.cpp6
-rw-r--r--Source/Sound/al_audio.cpp8
-rw-r--r--Source/Sound/sound.cpp6
-rw-r--r--Source/Sound/soundtrack.cpp52
-rw-r--r--Source/Sound/threaded_sound_wrapper.cpp6
-rw-r--r--Source/UnitTests/block_allocator_tester.cpp6
-rw-r--r--Source/UserInput/input.cpp106
-rw-r--r--Source/UserInput/keyTranslator.cpp10
-rw-r--r--Source/UserInput/keyboard.cpp4
-rw-r--r--Source/UserInput/keycommands.cpp12
-rw-r--r--Source/UserInput/mouse.cpp4
-rw-r--r--Source/Utility/binn_util.cpp4
-rw-r--r--Source/Utility/strings.cpp6
-rw-r--r--Source/XML/Parsers/activemodsparser.cpp20
-rw-r--r--Source/XML/Parsers/assetloadwarningparser.cpp10
-rw-r--r--Source/XML/level_loader.cpp30
128 files changed, 2539 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<vec2> points[2], const vector<vec2> &axes) {
bool intersects = true;
- for(size_t i=0, len=axes.size(); i<len; ++i){
- const vec2& axis = axes[i];
+ for(const auto & axis : axes){
float proj_bounds[2][2];
for(size_t i=0; i<2; ++i){
const vector<vec2> &point_vec = points[i];
@@ -460,8 +459,8 @@ void VoxellizeMesh(const vector<unsigned int> &faces, const vector<float> &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<unsigned int> &faces, const vector<float> &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<vec3> plane_normal;
vector<float> plane_d;
@@ -520,8 +519,7 @@ void VoxellizeMesh(const vector<unsigned int> &faces, const vector<float> &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<keyframes.size(); i++){
- Keyframe& k = keyframes[i];
-
+ for(auto & k : keyframes){
// Initialize uses_ik vector
size_t num_bones = k.bone_mats.size();
k.uses_ik.resize(num_bones);
@@ -182,95 +180,95 @@ void Animation::WriteToFile( FILE * file ) {
int num_keyframes = (int)keyframes.size();;
fwrite(&num_keyframes, sizeof(int), 1, file);
- for(unsigned i=0; i<keyframes.size(); i++){
- fwrite(&keyframes[i].time, sizeof(int), 1, file);
+ for(auto & keyframe : keyframes){
+ fwrite(&keyframe.time, sizeof(int), 1, file);
- size_t num_weights = keyframes[i].weights.size();
+ size_t num_weights = keyframe.weights.size();
fwrite(&num_weights, sizeof(int), 1, file);
if(num_weights){
- fwrite(&keyframes[i].weights[0], sizeof(float), num_weights, file);
+ fwrite(&keyframe.weights[0], sizeof(float), num_weights, file);
}
- int num_bone_mats = (int)keyframes[i].bone_mats.size();
+ int num_bone_mats = (int)keyframe.bone_mats.size();
fwrite(&num_bone_mats, sizeof(int), 1, file);
mat4 temp;
- for(unsigned j=0; j<keyframes[i].bone_mats.size(); j++){
- temp = keyframes[i].bone_mats[j].GetMat4();
+ for(unsigned j=0; j<keyframe.bone_mats.size(); j++){
+ temp = keyframe.bone_mats[j].GetMat4();
fwrite(&temp.entries, sizeof(float), 16, file);
}
- int num_weapon_mats = (int)keyframes[i].weapon_mats.size();
+ int num_weapon_mats = (int)keyframe.weapon_mats.size();
fwrite(&num_weapon_mats, sizeof(int), 1, file);
- for(unsigned j=0; j<keyframes[i].weapon_mats.size(); j++){
- temp = keyframes[i].weapon_mats[j].GetMat4();
+ for(unsigned j=0; j<keyframe.weapon_mats.size(); j++){
+ temp = keyframe.weapon_mats[j].GetMat4();
fwrite(&temp.entries, sizeof(float), 16, file);
- fwrite(&keyframes[i].weapon_relative_id[j], sizeof(int), 1, file);
- fwrite(&keyframes[i].weapon_relative_weight[j], sizeof(float), 1, file);
+ fwrite(&keyframe.weapon_relative_id[j], sizeof(int), 1, file);
+ fwrite(&keyframe.weapon_relative_weight[j], sizeof(float), 1, file);
}
- fwrite(&keyframes[i].use_mobility, sizeof(bool), 1, file);
- if(keyframes[i].use_mobility){
+ fwrite(&keyframe.use_mobility, sizeof(bool), 1, file);
+ if(keyframe.use_mobility){
mat4 temp_mat;
- temp_mat.SetColumn(0, keyframes[i].mobility_mat.GetColumn(0));
- temp_mat.SetColumn(1, keyframes[i].mobility_mat.GetColumn(2)*-1.0f);
- temp_mat.SetColumn(2, keyframes[i].mobility_mat.GetColumn(1));
- temp_mat.SetColumn(3, keyframes[i].mobility_mat.GetColumn(3));
+ temp_mat.SetColumn(0, keyframe.mobility_mat.GetColumn(0));
+ temp_mat.SetColumn(1, keyframe.mobility_mat.GetColumn(2)*-1.0f);
+ temp_mat.SetColumn(2, keyframe.mobility_mat.GetColumn(1));
+ temp_mat.SetColumn(3, keyframe.mobility_mat.GetColumn(3));
fwrite(&temp_mat.entries, sizeof(float), 16, file);
}
- int num_events = (int)keyframes[i].events.size();
+ int num_events = (int)keyframe.events.size();
fwrite(&num_events, sizeof(int), 1, file);
- for(size_t j=0; j<keyframes[i].events.size(); j++){
- fwrite(&keyframes[i].events[j].which_bone, sizeof(int), 1, file);
- const string &event_string = keyframes[i].events[j].event_string;
+ for(size_t j=0; j<keyframe.events.size(); j++){
+ fwrite(&keyframe.events[j].which_bone, sizeof(int), 1, file);
+ const string &event_string = keyframe.events[j].event_string;
size_t string_size = event_string.size();
fwrite(&string_size, sizeof(int), 1, file);
fwrite(event_string.c_str(), sizeof(char), string_size, file);
}
- int num_ik_bones = (int)keyframes[i].ik_bones.size();
+ int num_ik_bones = (int)keyframe.ik_bones.size();
fwrite(&num_ik_bones, sizeof(int), 1, file);
- for(size_t j=0; j<keyframes[i].ik_bones.size(); j++){
+ for(size_t j=0; j<keyframe.ik_bones.size(); j++){
// Used to be ik_bones.start and end
vec3 filler;
fwrite(&filler, sizeof(vec3), 1, file);
fwrite(&filler, sizeof(vec3), 1, file);
- size_t path_length = keyframes[i].ik_bones[j].bone_path.size();
+ size_t path_length = keyframe.ik_bones[j].bone_path.size();
fwrite(&path_length, sizeof(int), 1, file);
- fwrite(&keyframes[i].ik_bones[j].bone_path[0], sizeof(int), path_length, file);
- const string &label_string = keyframes[i].ik_bones[j].label;
+ fwrite(&keyframe.ik_bones[j].bone_path[0], sizeof(int), path_length, file);
+ const string &label_string = keyframe.ik_bones[j].label;
size_t string_size = label_string.size();
fwrite(&string_size, sizeof(int), 1, file);
fwrite(label_string.c_str(),sizeof(char), string_size, file);
}
- int num_shape_keys = (int)keyframes[i].shape_keys.size();
+ int num_shape_keys = (int)keyframe.shape_keys.size();
fwrite(&num_shape_keys, sizeof(int), 1, file);
- for(size_t j=0; j<keyframes[i].shape_keys.size(); j++){
- fwrite(&keyframes[i].shape_keys[j].weight, sizeof(float), 1, file);
- const string &label_string = keyframes[i].shape_keys[j].label;
+ for(size_t j=0; j<keyframe.shape_keys.size(); j++){
+ fwrite(&keyframe.shape_keys[j].weight, sizeof(float), 1, file);
+ const string &label_string = keyframe.shape_keys[j].label;
size_t string_size = label_string.size();
fwrite(&string_size, sizeof(int), 1, file);
fwrite(label_string.c_str(),sizeof(char), string_size, file);
}
- int num_status_keys = (int)keyframes[i].status_keys.size();
+ int num_status_keys = (int)keyframe.status_keys.size();
fwrite(&num_status_keys, sizeof(int), 1, file);
- for(size_t j=0; j<keyframes[i].status_keys.size(); j++){
- fwrite(&keyframes[i].status_keys[j].weight, sizeof(float), 1, file);
- const string &label_string = keyframes[i].status_keys[j].label;
+ for(size_t j=0; j<keyframe.status_keys.size(); j++){
+ fwrite(&keyframe.status_keys[j].weight, sizeof(float), 1, file);
+ const string &label_string = keyframe.status_keys[j].label;
size_t string_size = label_string.size();
fwrite(&string_size, sizeof(int), 1, file);
fwrite(label_string.c_str(),sizeof(char), string_size, file);
}
if(centered){
- fwrite(&keyframes[i].rotation, sizeof(float), 1, file);
- fwrite(&keyframes[i].center_offset, sizeof(float), 3, file);
+ fwrite(&keyframe.rotation, sizeof(float), 1, file);
+ fwrite(&keyframe.center_offset, sizeof(float), 3, file);
}
}
}
@@ -301,19 +299,19 @@ void Animation::Center() {
} else {
// If not using mobility bone, determine center of mass
float total_mass = 0.0f;
- for(unsigned j=0; j<k.bone_mats.size(); j++){
- center += k.bone_mats[j].origin;
+ for(auto & bone_mat : k.bone_mats){
+ center += bone_mat.origin;
total_mass += 1.0f;
}
LOG_ASSERT(total_mass != 0.0f);
center /= total_mass;
}
// Subtract the center from the position of each bone
- for(unsigned j=0; j<k.bone_mats.size(); j++){
- k.bone_mats[j].origin -= center;
+ for(auto & bone_mat : k.bone_mats){
+ bone_mat.origin -= center;
}
- for(unsigned j=0; j<k.weapon_mats.size(); j++){
- k.weapon_mats[j].origin -= center;
+ for(auto & weapon_mat : k.weapon_mats){
+ weapon_mat.origin -= center;
}
k.center_offset = center;
}
@@ -327,11 +325,11 @@ void Animation::Center() {
for(int i=0; i<num_keyframes; i++){
Keyframe &k = keyframes[i];
temp_offset = base_offset;
- for(unsigned j=0; j<k.bone_mats.size(); j++){
- k.bone_mats[j].origin += temp_offset;
+ for(auto & bone_mat : k.bone_mats){
+ bone_mat.origin += temp_offset;
}
- for(unsigned j=0; j<k.weapon_mats.size(); j++){
- k.weapon_mats[j].origin += temp_offset;
+ for(auto & weapon_mat : k.weapon_mats){
+ weapon_mat.origin += temp_offset;
}
k.center_offset -= temp_offset;
}
@@ -340,11 +338,11 @@ void Animation::Center() {
Keyframe &k = keyframes[i];
mat4 rotation_mat;
rotation_mat.SetRotationY(-k.rotation);
- for(unsigned j=0; j<k.bone_mats.size(); j++){
- k.bone_mats[j] = rotation_mat * k.bone_mats[j];
+ for(auto & bone_mat : k.bone_mats){
+ bone_mat = rotation_mat * bone_mat;
}
- for(unsigned j=0; j<k.weapon_mats.size(); j++){
- k.weapon_mats[j] = rotation_mat * k.weapon_mats[j];
+ for(auto & weapon_mat : k.weapon_mats){
+ weapon_mat = rotation_mat * weapon_mat;
}
}
// Apply the inverse rotation to center offset changes
@@ -437,8 +435,7 @@ void Retarget(const AnimInput& anim_input, AnimOutput & anim_output, const strin
anim_output.matrices[i].origin *= ratio;
}
}
- for(size_t i=0, len=anim_output.ik_bones.size(); i<len; ++i){
- BlendedBonePath& bbp = anim_output.ik_bones[i];
+ for(auto & bbp : anim_output.ik_bones){
bbp.transform.origin += old_root_offset;
bbp.transform.origin *= ratio;
}
@@ -476,8 +473,8 @@ void Retarget(const AnimInput& anim_input, AnimOutput & anim_output, const strin
{
PROFILER_ZONE(g_profiler_ctx, "Calculate new bone positions using sorted bone list");
- for(size_t i=0, len=depth_sorter.size(); i<len; ++i){
- int bone_id = depth_sorter[i].bone_id;
+ for(auto & i : depth_sorter){
+ int bone_id = i.bone_id;
int parent = new_data.hier_parents[bone_id];
// Set rotation for new bones
@@ -527,21 +524,21 @@ void Retarget(const AnimInput& anim_input, AnimOutput & anim_output, const strin
matrices[i] = matrices[i] * invert(skeleton_file_data.bone_mats[i]);
}
- for(size_t j=0; j<matrices.size(); j++){
- matrices[j].rotation[0] *= -1.0f;
- matrices[j].rotation[3] *= -1.0f;
- matrices[j].origin[0] *= -1.0f;
+ for(auto & matrix : matrices){
+ matrix.rotation[0] *= -1.0f;
+ matrix.rotation[3] *= -1.0f;
+ matrix.origin[0] *= -1.0f;
}
vector<BoneTransform> &weapon_matrices = anim_output.weapon_matrices;
- for(unsigned j=0; j<weapon_matrices.size(); j++){
- MirrorBT(weapon_matrices[j], true);
+ for(auto & weapon_matrix : weapon_matrices){
+ MirrorBT(weapon_matrix, true);
}
// Swap weapon relative ids (so knife in right hand is now in left hand)
- for(unsigned j=0; j<anim_output.weapon_relative_ids.size(); j++){
- if(anim_output.weapon_relative_ids[j] != -1){
- anim_output.weapon_relative_ids[j] = symmetry[anim_output.weapon_relative_ids[j]];
+ for(int & weapon_relative_id : anim_output.weapon_relative_ids){
+ if(weapon_relative_id != -1){
+ weapon_relative_id = symmetry[weapon_relative_id];
}
}
for(unsigned j=0; j<symmetry.size(); j++){
@@ -574,31 +571,29 @@ void Retarget(const AnimInput& anim_input, AnimOutput & anim_output, const strin
anim_output.delta_rotation *= -1.0f;
anim_output.rotation *= -1.0f;
- for(unsigned j=0; j<anim_output.status_keys.size(); ++j){
- StatusKeyBlend& skey = anim_output.status_keys[j];
- SwitchStringRightLeft(skey.label);
+ for(auto & skey : anim_output.status_keys){
+ SwitchStringRightLeft(skey.label);
}
- for(unsigned j=0; j<anim_output.shape_keys.size(); ++j){
- ShapeKeyBlend& skey = anim_output.shape_keys[j];
- SwitchStringRL(skey.label);
+ for(auto & skey : anim_output.shape_keys){
+ SwitchStringRL(skey.label);
}
- for(unsigned j=0; j<anim_output.ik_bones.size(); ++j){
- string &label = anim_output.ik_bones[j].ik_bone.label;
+ for(auto & ik_bone : anim_output.ik_bones){
+ string &label = ik_bone.ik_bone.label;
SwitchStringRightLeft(label);
- BonePath& bone_path = anim_output.ik_bones[j].ik_bone.bone_path;
- anim_output.ik_bones[j].transform = anim_output.ik_bones[j].transform * skeleton_file_data.bone_mats[bone_path[0]];
- anim_output.ik_bones[j].transform.origin[0] *= -1.0f;
- anim_output.ik_bones[j].transform.rotation[0] *= -1.0f;
- anim_output.ik_bones[j].transform.rotation[3] *= -1.0f;
- for(unsigned k=0; k<bone_path.size(); ++k){
- if(bone_path[k] < (int)symmetry.size() && symmetry[bone_path[k]] != -1){
- bone_path[k] = symmetry[bone_path[k]];
+ BonePath& bone_path = ik_bone.ik_bone.bone_path;
+ ik_bone.transform = ik_bone.transform * skeleton_file_data.bone_mats[bone_path[0]];
+ ik_bone.transform.origin[0] *= -1.0f;
+ ik_bone.transform.rotation[0] *= -1.0f;
+ ik_bone.transform.rotation[3] *= -1.0f;
+ for(int & k : bone_path){
+ if(k < (int)symmetry.size() && symmetry[k] != -1){
+ k = symmetry[k];
}
}
- anim_output.ik_bones[j].transform = anim_output.ik_bones[j].transform * invert(skeleton_file_data.bone_mats[bone_path[0]]);
+ ik_bone.transform = ik_bone.transform * invert(skeleton_file_data.bone_mats[bone_path[0]]);
if(label == "left_leg" || label == "right_leg"){
- anim_output.ik_bones[j].transform.rotation = anim_output.ik_bones[j].transform.rotation * quaternion(vec4(0.0f,0.0f,1.0f,3.14f));
+ ik_bone.transform.rotation = ik_bone.transform.rotation * quaternion(vec4(0.0f,0.0f,1.0f,3.14f));
}
}
}
@@ -612,9 +607,8 @@ void Retarget(const AnimInput& anim_input, AnimOutput & anim_output, const strin
vec3 test = QuaternionFromMat4(old_data.bone_mats[ik_bone.bone_id]) * invert(QuaternionFromMat4(new_data.bone_mats[ik_bone.bone_id])) * vec3(0.0f,1.0f,0.0f);
if(test[1] < 0.0f){
anim_output.matrices[ik_bone.bone_id].rotation = anim_output.matrices[ik_bone.bone_id].rotation * quaternion(vec4(0.0f,0.0f,1.0f,3.14f));
- for(size_t i=0, len=anim_output.ik_bones.size(); i<len; ++i){
- BlendedBonePath& bbp = anim_output.ik_bones[i];
- if(bbp.ik_bone.label == "left_leg"){
+ for(auto & bbp : anim_output.ik_bones){
+ if(bbp.ik_bone.label == "left_leg"){
bbp.transform.rotation = bbp.transform.rotation * quaternion(vec4(0.0f,0.0f,1.0f,3.14f));
}
}
@@ -707,9 +701,9 @@ int Animation::ReadFromFile( FILE * file ) {
keyframe->bone_mats.resize(num_bone_mats);
mat4 temp;
- for(unsigned j=0; j<keyframe->bone_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; j<keyframe->events.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<char> 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; j<keyframe->ik_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<char> 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; j<keyframe->shape_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<char> 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; j<keyframe->status_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<char> 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<string, BlendedBonePath> ik_bones;
map<string, BlendedBonePath>::iterator iter;
- for(unsigned i=0; i<a.ik_bones.size(); ++i){
- const string& label = a.ik_bones[i].ik_bone.label;
- ik_bones[label] = a.ik_bones[i];
+ for(const auto & ik_bone : a.ik_bones){
+ const string& label = ik_bone.ik_bone.label;
+ ik_bones[label] = ik_bone;
ik_bones[label].weight *= 1.0f-alpha;
}
- for(unsigned i=0; i<b.ik_bones.size(); ++i){
- const string& label = b.ik_bones[i].ik_bone.label;
+ for(const auto & ik_bone : b.ik_bones){
+ const string& label = ik_bone.ik_bone.label;
iter = ik_bones.find(label);
if(iter == ik_bones.end()){
- ik_bones[label] = b.ik_bones[i];
+ ik_bones[label] = ik_bone;
ik_bones[label].weight *= alpha;
} else {
- ik_bones[label].weight = ik_bones[label].weight + b.ik_bones[i].weight * alpha;
- ik_bones[label].transform = mix(ik_bones[label].transform, b.ik_bones[i].transform, alpha);
+ ik_bones[label].weight = ik_bones[label].weight + ik_bone.weight * alpha;
+ ik_bones[label].transform = mix(ik_bones[label].transform, ik_bone.transform, alpha);
}
}
@@ -966,22 +960,22 @@ AnimOutput mix( const AnimOutput &a, const AnimOutput &b, float alpha )
map<string, ShapeKeyBlend>::iterator iter;
// Add shape keys from A
- for(unsigned i=0; i<a.shape_keys.size(); ++i){
- const string& label = a.shape_keys[i].label;
- shape_keys[label] = a.shape_keys[i];
+ for(const auto & shape_key : a.shape_keys){
+ const string& label = shape_key.label;
+ shape_keys[label] = shape_key;
shape_keys[label].weight_weight *= 1.0f-alpha;
}
// Merge shape keys from B
- for(unsigned i=0; i<b.shape_keys.size(); ++i){
- const string& label = b.shape_keys[i].label;
+ for(const auto & shape_key : b.shape_keys){
+ const string& label = shape_key.label;
iter = shape_keys.find(label);
if(iter == shape_keys.end()){
- shape_keys[label] = b.shape_keys[i];
+ shape_keys[label] = shape_key;
shape_keys[label].weight_weight *= alpha;
} else {
- shape_keys[label].weight = mix(shape_keys[label].weight, b.shape_keys[i].weight, alpha);
- shape_keys[label].weight_weight = shape_keys[label].weight_weight + b.shape_keys[i].weight_weight * alpha;
+ shape_keys[label].weight = mix(shape_keys[label].weight, shape_key.weight, alpha);
+ shape_keys[label].weight_weight = shape_keys[label].weight_weight + shape_key.weight_weight * alpha;
}
}
@@ -1000,21 +994,21 @@ AnimOutput mix( const AnimOutput &a, const AnimOutput &b, float alpha )
map<string, StatusKeyBlend> status_keys;
map<string, StatusKeyBlend>::iterator iter;
- for(unsigned i=0; i<a.status_keys.size(); ++i){
- const string& label = a.status_keys[i].label;
- status_keys[label] = a.status_keys[i];
+ for(const auto & status_key : a.status_keys){
+ const string& label = status_key.label;
+ status_keys[label] = status_key;
status_keys[label].weight_weight *= 1.0f-alpha;
}
- for(unsigned i=0; i<b.status_keys.size(); ++i){
- const string& label = b.status_keys[i].label;
+ for(const auto & status_key : b.status_keys){
+ const string& label = status_key.label;
iter = status_keys.find(label);
if(iter == status_keys.end()){
- status_keys[label] = b.status_keys[i];
+ status_keys[label] = status_key;
status_keys[label].weight_weight *= alpha;
} else {
- status_keys[label].weight = mix(status_keys[label].weight, b.status_keys[i].weight, alpha);
- status_keys[label].weight_weight = status_keys[label].weight_weight + b.status_keys[i].weight_weight * alpha;
+ status_keys[label].weight = mix(status_keys[label].weight, status_key.weight, alpha);
+ status_keys[label].weight_weight = status_keys[label].weight_weight + status_key.weight_weight * alpha;
}
}
@@ -1094,21 +1088,21 @@ AnimOutput add_mix( const AnimOutput &a, const AnimOutput &b, float alpha ) {
map<string, ShapeKeyBlend>::iterator iter;
// Add shape keys from A
- for(unsigned i=0; i<a.shape_keys.size(); ++i){
- const string& label = a.shape_keys[i].label;
- shape_keys[label] = a.shape_keys[i];
+ for(const auto & shape_key : a.shape_keys){
+ const string& label = shape_key.label;
+ shape_keys[label] = shape_key;
}
// Merge shape keys from B
- for(unsigned i=0; i<b.shape_keys.size(); ++i){
- const string& label = b.shape_keys[i].label;
+ for(const auto & shape_key : b.shape_keys){
+ const string& label = shape_key.label;
iter = shape_keys.find(label);
if(iter == shape_keys.end()){
- shape_keys[label] = b.shape_keys[i];
+ shape_keys[label] = shape_key;
shape_keys[label].weight_weight *= clamped_alpha;
} else {
ShapeKeyBlend& a_key = shape_keys[label];
- const ShapeKeyBlend& b_key = b.shape_keys[i];
+ const ShapeKeyBlend& b_key = shape_key;
a_key.weight = mix(a_key.weight, b_key.weight, b_key.weight_weight * clamped_alpha);
a_key.weight_weight = max(a_key.weight_weight, b_key.weight_weight * clamped_alpha);
}
@@ -1128,20 +1122,20 @@ AnimOutput add_mix( const AnimOutput &a, const AnimOutput &b, float alpha ) {
map<string, StatusKeyBlend> status_keys;
map<string, StatusKeyBlend>::iterator iter;
- for(unsigned i=0; i<a.status_keys.size(); ++i){
- const string& label = a.status_keys[i].label;
- status_keys[label] = a.status_keys[i];
+ for(const auto & status_key : a.status_keys){
+ const string& label = status_key.label;
+ status_keys[label] = status_key;
}
- for(unsigned i=0; i<b.status_keys.size(); ++i){
- const string& label = b.status_keys[i].label;
+ for(const auto & status_key : b.status_keys){
+ const string& label = status_key.label;
iter = status_keys.find(label);
if(iter == status_keys.end()){
- status_keys[label] = b.status_keys[i];
+ status_keys[label] = status_key;
status_keys[label].weight_weight *= clamped_alpha;
} else {
StatusKeyBlend& a_key = status_keys[label];
- const StatusKeyBlend& b_key = b.status_keys[i];
+ const StatusKeyBlend& b_key = status_key;
a_key.weight = mix(a_key.weight, b_key.weight, b_key.weight_weight * clamped_alpha);
a_key.weight_weight = max(a_key.weight_weight, b_key.weight_weight * clamped_alpha);
}
@@ -1422,8 +1416,8 @@ void Animation::GetMatrices( float normalized_time, AnimOutput &anim_output, con
}
}
- for(IKBoneMap::iterator iter = ik_bone_weights.begin(); iter != ik_bone_weights.end(); ++iter){
- BlendedBonePath &blended_bone_path = iter->second;
+ 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<NormalizedAnimationEvent> Animation::GetEvents(int& anim_id, bool mirror) const
{
vector<NormalizedAnimationEvent> normalized_events;
- for(unsigned i=0; i<keyframes.size(); i++){
- for(unsigned j=0; j<keyframes[i].events.size(); j++){
- const AnimationEvent &the_event = keyframes[i].events[j];
+ for(const auto & keyframe : keyframes){
+ for(unsigned j=0; j<keyframe.events.size(); j++){
+ const AnimationEvent &the_event = keyframe.events[j];
normalized_events.resize(normalized_events.size()+1);
NormalizedAnimationEvent &normalized_event =
@@ -1549,7 +1543,7 @@ vector<NormalizedAnimationEvent> 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<NormalizedAnimationEvent> Animation::GetEvents(int& anim_id, bool mirror)
SkeletonAssetRef sar = Engine::Instance()->GetAssetManager()->LoadSync<SkeletonAsset>(skeleton_file_path);
const SkeletonFileData& skeleton_file_data = sar->GetData();
const vector<int>& symmetry = skeleton_file_data.symmetry;
- for(size_t i=0, len=normalized_events.size(); i<len; ++i){
- AnimationEvent& event = normalized_events[i].event;
+ for(auto & normalized_event : normalized_events){
+ AnimationEvent& event = normalized_event.event;
SwitchStringRightLeft(event.event_string);
if(symmetry[event.which_bone] != -1){
event.which_bone = symmetry[event.which_bone];
@@ -1574,9 +1568,7 @@ vector<NormalizedAnimationEvent> Animation::GetEvents(int& anim_id, bool mirror)
void Animation::RecalcCaches() {
// Cache which bones use IK in each frame
- for(unsigned i=0; i<keyframes.size(); i++){
- Keyframe& k = keyframes[i];
-
+ for(auto & k : keyframes){
// Initialize uses_ik vector
size_t num_bones = k.bone_mats.size();
k.uses_ik.resize(num_bones);
@@ -1653,10 +1645,8 @@ float GetAnimationEventTime( const string& anim_path, const string& event_str )
AnimationAssetRef aar = ReturnAnimationAssetRef(anim_path);
int anim_id = 0;
vector<NormalizedAnimationEvent> events = aar->GetEvents(anim_id,false);
- for(vector<NormalizedAnimationEvent>::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<Material>(clothing_path)->ReturnPaths(path_set);
}
- for(unsigned i=0; i<morph_info.size(); ++i){
- if(morph_info[i].num_steps == 1){
- path_set.insert("morph "+GetMorphPath(ofr->model_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; j<morph_info[i].num_steps; ++j){
+ for(int j=0; j<info.num_steps; ++j){
ostringstream oss;
- oss << morph_info[i].label << j;
+ oss << info.label << j;
path_set.insert("morph "+GetMorphPath(ofr->model_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<Attack>(iter->second)->ReturnPaths(path_set);
+ Engine::Instance()->GetAssetManager()->LoadSync<Attack>(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(); i<len; ++i){
- if(morph_meta[i].label == label){
- start = morph_meta[i].start;
- end = morph_meta[i].end;
+ for(auto & meta : morph_meta){
+ if(meta.label == label){
+ start = meta.start;
+ end = meta.end;
return true;
}
}
diff --git a/Source/Asset/Asset/item.cpp b/Source/Asset/Asset/item.cpp
index c66a8892..87862618 100644
--- a/Source/Asset/Asset/item.cpp
+++ b/Source/Asset/Asset/item.cpp
@@ -394,37 +394,33 @@ char Item::GetAnimOverrideFlags( const std::string &anim )
void Item::ReturnPaths( PathSet &path_set )
{
path_set.insert("item "+path_);
- for(int i=0; i<kMaxAttachments; ++i){
- if(attachment[i].exists){
- ReturnAnimationAssetRef(attachment[i].anim)->ReturnPaths(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<ObjectFile>(obj_path)->ReturnPaths(path_set);
- for(std::map<std::string, std::string>::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<std::string, std::string>::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<std::string, std::string>::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<Attack>(iter->second)->ReturnPaths(path_set);
+ Engine::Instance()->GetAssetManager()->LoadSync<Attack>(attack_override.second)->ReturnPaths(path_set);
}
- for(std::map<std::string, std::string>::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<Reaction>(iter->second)->ReturnPaths(path_set);
+ Engine::Instance()->GetAssetManager()->LoadSync<Reaction>(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<std::string>::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<vis_weights.size(); ++i){
- morph_weights[id2morph[vis_weights[i].id]] += vis_weights[i].weight;
+ for(auto & vis_weight : vis_weights){
+ morph_weights[id2morph[vis_weight.id]] += vis_weight.weight;
}
}
diff --git a/Source/Asset/Asset/material.cpp b/Source/Asset/Asset/material.cpp
index c9826a98..162391eb 100644
--- a/Source/Asset/Asset/material.cpp
+++ b/Source/Asset/Asset/material.cpp
@@ -212,10 +212,9 @@ void Material::ReturnPaths( PathSet & path_set )
iter != event_map.end(); ++iter)
{
const std::map<std::string, MaterialEvent> &inner_map = iter->second;
- for(std::map<std::string, MaterialEvent>::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<SoundGroupInfo>(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; i<m_detail_color_maps.size(); ++i){
- path_set.insert("texture "+m_detail_color_maps[i]);
+ for(auto & detail_color_map : m_detail_color_maps){
+ path_set.insert("texture "+detail_color_map);
}
- for(unsigned i=0; i<m_detail_normal_maps.size(); ++i){
- path_set.insert("texture "+m_detail_normal_maps[i]);
+ for(auto & detail_normal_map : m_detail_normal_maps){
+ path_set.insert("texture "+detail_normal_map);
}
- for(unsigned i=0; i<m_detail_materials.size(); ++i){
+ for(auto & detail_material : m_detail_materials){
//Materials::Instance()->ReturnRef(m_detail_materials[i])->ReturnPaths(path_set);
- Engine::Instance()->GetAssetManager()->LoadSync<Material>(m_detail_materials[i])->ReturnPaths(path_set);
+ Engine::Instance()->GetAssetManager()->LoadSync<Material>(detail_material)->ReturnPaths(path_set);
}
- for(unsigned i=0; i<m_detail_object_layers.size(); ++i){
- m_detail_object_layers[i].ReturnPaths(path_set);
+ for(auto & detail_object_layer : m_detail_object_layers){
+ detail_object_layer.ReturnPaths(path_set);
}
}
diff --git a/Source/Asset/Asset/reactions.cpp b/Source/Asset/Asset/reactions.cpp
index b65a75a6..f6e92422 100644
--- a/Source/Asset/Asset/reactions.cpp
+++ b/Source/Asset/Asset/reactions.cpp
@@ -104,8 +104,8 @@ int Reaction::IsMirrored()
void Reaction::ReturnPaths( PathSet &path_set )
{
path_set.insert("reaction "+path_);
- for(unsigned i=0; i<anim_paths.size(); ++i){
- ReturnAnimationAssetRef(anim_paths[i]);
+ for(auto & anim_path : anim_paths){
+ ReturnAnimationAssetRef(anim_path);
}
}
diff --git a/Source/Asset/Asset/syncedanimation.cpp b/Source/Asset/Asset/syncedanimation.cpp
index 902cae17..6c90249b 100644
--- a/Source/Asset/Asset/syncedanimation.cpp
+++ b/Source/Asset/Asset/syncedanimation.cpp
@@ -417,9 +417,9 @@ float SyncedAnimationGroup::GetGroundSpeed( const BlendMap& blendmap ) const {
std::vector<NormalizedAnimationEvent> SyncedAnimationGroup::GetEvents(int& anim_id, bool mirrored) const {
std::vector<NormalizedAnimationEvent> normalized_events;
- for(unsigned i=0; i<animations.size(); i++){
+ for(const auto & i : animations){
std::vector<NormalizedAnimationEvent> 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; i<animations.size(); ++i){
- animations[i].animation->ReturnPaths(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<std::string, std::string>::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<SoundGroupInfo>(iter->second)->ReturnPaths(path_set);
+ Engine::Instance()->GetAssetManager()->LoadSync<SoundGroupInfo>(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<int,int>
}
std::vector<Object*> children;
o->GetChildren(&children);
- for(size_t i=0, len=children.size(); i<len; ++i) {
- int old_id = children[i]->GetID();
- 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<int,int>(old_id, children[i]->GetID()));
+ id_remap->insert(std::pair<int,int>(old_id, child->GetID()));
}
}
@@ -166,9 +166,9 @@ bool ActorsEditor_AddEntity(SceneGraph* scenegraph, Object* o, std::map<int,int>
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<int,int>
}
static void GetFlattenedDescList(EntityDescriptionList *desc_list, std::vector<EntityDescription*> *flat_desc_list){
- for(size_t desc_index=0, len=desc_list->size();
- desc_index<len;
- ++desc_index)
+ for(auto & desc_index : *desc_list)
{
- EntityDescription *desc = &desc_list->at(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<int,int> scene_ids;
typedef std::map<int,int>::iterator Iter;
- for(size_t desc_index=0, len=flat_desc_list.size();
- desc_index<len;
- ++desc_index)
+ for(auto desc : flat_desc_list)
{
- EntityDescription *desc = flat_desc_list[desc_index];
- EntityDescriptionField *edf = desc->GetField(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_index<len;
- ++desc_index)
+ for(auto desc : flat_desc_list)
{
- EntityDescription *desc = flat_desc_list[desc_index];
- EntityDescriptionField *edf = desc->GetField(EDF_CONNECTIONS);
+ EntityDescriptionField *edf = desc->GetField(EDF_CONNECTIONS);
if(edf) {
std::vector<int> connections;
std::vector<int> write_connections;
edf->ReadIntVec(&connections);
- for(size_t connection_index=0, len=connections.size();
- connection_index<len;
- ++connection_index )
+ for(int id : connections)
{
- int id = connections[connection_index];
Iter iter = scene_ids.find(id);
if(iter != scene_ids.end()) {
id = iter->second;
@@ -245,11 +234,8 @@ void LocalizeIDs(EntityDescriptionList *desc_list, bool keep_external_connection
std::vector<ItemConnectionData> connections;
std::vector<ItemConnectionData> write_connections;
edf->ReadItemConnectionDataVec(&connections);
- for(size_t connection_index=0, len=connections.size();
- connection_index<len;
- ++connection_index )
+ for(auto item_connection_data : connections)
{
- ItemConnectionData item_connection_data = connections[connection_index];
Iter iter = scene_ids.find(item_connection_data.id);
if(iter != scene_ids.end()) {
item_connection_data.id = iter->second;
@@ -266,12 +252,8 @@ void LocalizeIDs(EntityDescriptionList *desc_list, bool keep_external_connection
std::vector<NavMeshConnectionData> connections;
std::vector<NavMeshConnectionData> write_connections;
edf->ReadNavMeshConnectionDataVec(&connections);
- for(size_t connection_index=0, len=connections.size();
- connection_index<len;
- ++connection_index )
+ for(auto nav_mesh_connection_data : connections)
{
- NavMeshConnectionData nav_mesh_connection_data = connections[connection_index];
-
Iter iter = scene_ids.find(nav_mesh_connection_data.other_object_id);
if(iter != scene_ids.end()) {
nav_mesh_connection_data.other_object_id = iter->second;
@@ -288,11 +270,8 @@ void LocalizeIDs(EntityDescriptionList *desc_list, bool keep_external_connection
std::vector<int> connections;
std::vector<int> write_connections;
edf->ReadIntVec(&connections);
- for(size_t connection_index=0, len=connections.size();
- connection_index<len;
- ++connection_index )
+ for(int id : connections)
{
- int id = connections[connection_index];
Iter iter = scene_ids.find(id);
if(iter != scene_ids.end()) {
id = iter->second;
@@ -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(); i<len; ++i) {
- Object* obj = scenegraph->objects_[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<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
- if (field.type == EDF_ENTITY_TYPE){
+ for (const auto & field : desc.fields){
+ if (field.type == EDF_ENTITY_TYPE){
memread(&type, sizeof(int), 1, field.data);
break;
}
@@ -482,15 +459,15 @@ std::vector<Object*> ActorsEditor_AddEntitiesAtPosition(const Path& source, Scen
std::map<int,int> id_remap;
std::vector<Object*> 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<Object*> ActorsEditor_AddEntitiesAtPosition(const Path& source, Scen
}
}
- for (size_t i=0, len=new_objects.size(); i<len; ++i) {
- new_objects[i]->RemapReferences(id_remap);
+ for (auto & new_object : new_objects) {
+ new_object->RemapReferences(id_remap);
}
- for (size_t i=0, len=new_objects.size(); i<len; ++i) {
- new_objects[i]->ReceiveObjectMessage(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<int,int> id_remap;
std::vector<Object*> 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(); i<len; ++i) {
- new_objects[i]->RemapReferences(id_remap);
+ for (auto & new_object : new_objects) {
+ new_object->RemapReferences(id_remap);
}
- for (size_t i=0, len=new_objects.size(); i<len; ++i) {
- new_objects[i]->ReceiveObjectMessage(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(); i<len; ++i){
+ for(auto & new_object : new_objects){
Group::Child child;
- child.direct_ptr = new_objects[i];
+ child.direct_ptr = new_object;
child.direct_ptr->SetParent(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<int, int> scene_ids;
typedef std::map<int, int>::iterator Iter;
- for(size_t desc_index=0, len=flat_desc_list.size();
- desc_index<len;
- ++desc_index)
+ for(auto desc : flat_desc_list)
{
- EntityDescription *desc = flat_desc_list[desc_index];
- EntityDescriptionField *edf = desc->GetField(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<int, int>(id, new_id));
}
}
- for(size_t desc_index=0, len=flat_desc_list.size();
- desc_index<len;
- ++desc_index)
+ for(auto desc : flat_desc_list)
{
- EntityDescription *desc = flat_desc_list[desc_index];
- EntityDescriptionField *edf = desc->GetField(EDF_CONNECTIONS);
+ EntityDescriptionField *edf = desc->GetField(EDF_CONNECTIONS);
if(edf) {
std::vector<int> connections;
std::vector<int> write_connections;
edf->ReadIntVec(&connections);
- for(size_t connection_index=0, len=connections.size();
- connection_index<len;
- ++connection_index )
+ for(int id : connections)
{
- int id = connections[connection_index];
Iter iter = scene_ids.find(id);
if(iter != scene_ids.end())
id = iter->second;
@@ -802,11 +770,8 @@ void ActorsEditor_UnlocalizeIDs(EntityDescriptionList *desc_list, SceneGraph *sc
std::vector<ItemConnectionData> connections;
std::vector<ItemConnectionData> write_connections;
edf->ReadItemConnectionDataVec(&connections);
- for(size_t connection_index=0, len=connections.size();
- connection_index<len;
- ++connection_index )
+ for(auto write_data : connections)
{
- ItemConnectionData write_data = connections[connection_index];
Iter iter = scene_ids.find(write_data.id);
if(iter != scene_ids.end())
write_data.id = iter->second;
@@ -820,11 +785,8 @@ void ActorsEditor_UnlocalizeIDs(EntityDescriptionList *desc_list, SceneGraph *sc
std::vector<NavMeshConnectionData> connections;
std::vector<NavMeshConnectionData> write_connections;
edf->ReadNavMeshConnectionDataVec(&connections);
- for(size_t connection_index=0, len=connections.size();
- connection_index<len;
- ++connection_index )
+ for(auto write_data : connections)
{
- NavMeshConnectionData write_data = connections[connection_index];
Iter iter = scene_ids.find(write_data.other_object_id);
if(iter != scene_ids.end())
write_data.other_object_id = iter->second;
@@ -838,11 +800,8 @@ void ActorsEditor_UnlocalizeIDs(EntityDescriptionList *desc_list, SceneGraph *sc
std::vector<int> connections;
std::vector<int> write_connections;
edf->ReadIntVec(&connections);
- for(size_t connection_index=0, len=connections.size();
- connection_index<len;
- ++connection_index )
+ for(int id : connections)
{
- int id = connections[connection_index];
Iter iter = scene_ids.find(id);
if(iter != scene_ids.end())
id = iter->second;
diff --git a/Source/Editors/map_editor.cpp b/Source/Editors/map_editor.cpp
index ba852653..9d2ba91e 100644
--- a/Source/Editors/map_editor.cpp
+++ b/Source/Editors/map_editor.cpp
@@ -195,8 +195,7 @@ static Object::ConnectionType GetConnectionType(const std::vector<Object*> &sele
bool navmesh_connection_objects_only = true;
bool single_placeholder_object = (selected.size()==1);
bool hotspots_only = true;
- for(unsigned i=0; i<selected.size(); ++i) {
- const Object* obj = selected[i];
+ for(auto obj : selected) {
EntityType type = obj->GetType();
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_index<len; ++light_probe_index){
LightProbe& light_probe = lpc.light_probes[light_probe_index];
- for(int cube_face=0; cube_face<6; ++cube_face){
- light_probe.ambient_cube_color[cube_face] = vec3(0.0f);
+ for(auto & cube_face : light_probe.ambient_cube_color){
+ cube_face = vec3(0.0f);
}
lpc.MoveProbe(light_probe.id, light_probe.pos); // Hackish way to force refresh of this probe
}
@@ -474,10 +470,8 @@ void MapEditor::RibbonItemClicked(const std::string& item, bool param) {
}
static void SendMessageToSelectedObjectsVAList(SceneGraph *scenegraph, OBJECT_MSG::Type type, va_list args){
- 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->ReceiveObjectMessageVAList(type, args);
}
@@ -594,8 +588,7 @@ void MapEditor::Initialize(SceneGraph* s) {
}
void MapEditor::UpdateEnabledObjects() {
- for (size_t i=0, len=scenegraph_->objects_.size(); i<len; ++i) {
- Object* obj = scenegraph_->objects_[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; i<scenegraph->movement_objects_.size(); ++i){
- MovementObject* mo = (MovementObject*)scenegraph->movement_objects_[i];
+ for(auto movement_object : scenegraph->movement_objects_){
+ MovementObject* mo = (MovementObject*)movement_object;
std::list<AttachmentSlot> list;
mo->rigged_object()->AvailableItemSlots(item_ref, &list);
- for(std::list<AttachmentSlot>::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(); i<len; ++i) {
- Object *obj = scenegraph_->objects_[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 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);
}
}
@@ -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,22 @@ void MapEditor::Draw() {
float highlit_obj_dist = FLT_MAX;
std::vector<int> connected_ids;
connected_ids.reserve(64);
- for(size_t i = 0; i < selected.size(); ++i) {
- Object* selected_obj = selected[i];
+ for(Object* selected_obj : selected) {
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]);
+ 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(size_t j = 0; j < selected_obj->connected_to.size(); ++j) {
- Object* obj = scenegraph_->GetObjectFromID(selected_obj->connected_to[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(size_t j = 0; j < selected_obj->connected_from.size(); ++j) {
- Object* obj = scenegraph_->GetObjectFromID(selected_obj->connected_from[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);
}
@@ -996,8 +985,8 @@ void MapEditor::Draw() {
selected_objects[i] = selected[i];
}
std::vector<Object*> &movement_objects = scenegraph_->movement_objects_;
- for(size_t i=0, len=movement_objects.size(); i<len; ++i){
- MovementObject* mo = (MovementObject*)movement_objects[i];
+ for(auto & movement_object : movement_objects){
+ MovementObject* mo = (MovementObject*)movement_object;
if(mo->rigged_object()->DrawBoneConnectUI(selected_objects, (int) selected.size(), imui_context, active_tool_, mo->GetID())){
QueueSaveHistoryState();
}
@@ -1005,22 +994,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 +1076,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(); i<len; ++i){
- Object* obj = objects[i];
+ for(auto obj : objects){
if (obj->Selected()) {
collide = obj->lineCheck(start,new_end,point,&normal);
if(collide!=-1) {
@@ -1298,14 +1286,13 @@ void MapEditor::Update(GameCursor* cursor) {
}
scenegraph_->level->SaveHistoryState(chunks, state_id);
std::vector<Object*> entities;
- for(size_t i=0, len=scenegraph_->objects_.size(); i<len; ++i){
- Object* obj = scenegraph_->objects_[i];
+ for(auto obj : scenegraph_->objects_){
if(!obj->parent && !obj->exclude_from_undo){
entities.push_back(obj);
}
}
- for (unsigned i=0; i<entities.size(); ++i) {
- entities[i]->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
@@ -1435,8 +1422,8 @@ void MapEditor::DeleteSelected() {
objects_to_delete.push_back(obj);
}
}
- for(size_t i=0, len=objects_to_delete.size(); i<len; ++i){
- RemoveObject(objects_to_delete[i], scenegraph_);
+ for(auto & i : objects_to_delete){
+ RemoveObject(i, scenegraph_);
}
QueueSaveHistoryState();
}
@@ -1452,9 +1439,9 @@ void MapEditor::GroupSelected() {
ReturnSelected(&selected);
if(selected.size() > 1){
std::vector<int> child_ids;
- for(size_t i=0, len=selected.size(); i<len; ++i){
- if(!selected[i]->parent){
- 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 +1469,16 @@ void MapEditor::GroupSelected() {
bool MapEditor::ContainsPrefabsRecursively( std::vector<Object*> objects ) {
bool res = false;
- for( unsigned i = 0; i < objects.size(); i++ ) {
- if( objects[i]->IsGroupDerived() ) {
- Group *g = static_cast<Group*>(objects[i]);
+ for(auto & object : objects) {
+ if( object->IsGroupDerived() ) {
+ Group *g = static_cast<Group*>(object);
std::vector<Object*> 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 +1529,9 @@ int MapEditor::PrefabSelected() {
}
} else if(selected.size() > 0) {
std::vector<int> child_ids;
- for(size_t i=0, len=selected.size(); i<len; ++i){
- if(!selected[i]->parent){
- 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 +1566,29 @@ int MapEditor::PrefabSelected() {
void MapEditor::UngroupSelected() {
RibbonFlash(gui, "ungroup");
ReturnSelected(&selected);
- for(size_t i=0, len=selected.size(); i<len; ++i){
- if(selected[i]->GetType() == _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(); i<len; ++i) {
- if (scenegraph_->objects_[i]->Selected()) {
+ for (auto & object : scenegraph_->objects_) {
+ if (object->Selected()) {
return true;
}
}
@@ -1791,8 +1775,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(); i<len; ++i){
- if(mouseray_collision_selected.hit_what == selected[i]) {
+ for(auto & i : selected){
+ if(mouseray_collision_selected.hit_what == i) {
connection_type = Object::kCTNone;
}
}
@@ -1837,14 +1821,14 @@ void MapEditor::HandleShortcuts( const LineSegment &mouseray ) {
Object* hit_obj = c.hit_what;
if(std::find(box_objects.begin(), box_objects.end(), hit_obj) != box_objects.end()) {
ReturnSelected(&selected);
- for(unsigned i=0; i<selected.size(); ++i) {
+ for(auto & i : selected) {
if(active_tool_ == EditorTypes::CONNECT) {
- Object* obj = selected[i];
+ Object* obj = i;
//if(obj->ConnectTo(*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 +1882,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 +1894,34 @@ int MapEditor::ReplaceObjects( const std::vector<Object*>& objects, const std::s
ActorsEditor_UnlocalizeIDs(&add_desc_list_, scenegraph_);
- for(size_t i = 0; i < objects.size(); i++) {
- std::vector<Object*> new_objects = ActorsEditor_AddEntitiesAtPosition(add_desc_list_source_, scenegraph_, add_desc_list_, objects[i]->GetTranslation(), create_as_prefab_);
+ for(auto object : objects) {
+ std::vector<Object*> 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<Prefab*>(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 +2056,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(); i<len; ++i){
- CalculateGroupString(group->children[i].direct_ptr, str);
+ for(auto & i : group->children){
+ CalculateGroupString(i.direct_ptr, str);
}
} else {
str = str + obj->obj_file;
@@ -2081,8 +2065,7 @@ void CalculateGroupString(Object* obj, std::string& str) {
}
void MapEditor::SelectAll(){
- for (size_t i=0, len=scenegraph_->objects_.size(); i<len; ++i) {
- Object* obj = scenegraph_->objects_[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 +2081,7 @@ void MapEditor::ReloadAllPrefabs() {
while( active_depth ) {
active_depth = false;
prefabs.clear();
- for (size_t i=0, len=scenegraph_->objects_.size(); i<len; ++i) {
- Object* obj = scenegraph_->objects_[i];
+ for (auto obj : scenegraph_->objects_) {
if( obj->GetGroupDepth() == current_depth ) {
active_depth = true;
if(obj->GetType() == _prefab){
@@ -2108,8 +2090,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 +2099,7 @@ void MapEditor::ReloadAllPrefabs() {
void MapEditor::ReloadPrefabs(const Path& path) {
std::vector<Object*> prefabs;
- for (size_t i=0, len=scenegraph_->objects_.size(); i<len; ++i) {
- Object* obj = scenegraph_->objects_[i];
+ for (auto obj : scenegraph_->objects_) {
if(obj->GetType() == _prefab){
Prefab* prefab = static_cast<Prefab*>(obj);
if(strmtch(prefab->prefab_path.GetFullPath(),path.GetFullPath())) {
@@ -2127,8 +2108,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 +2135,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 +2225,21 @@ bool MapEditor::CheckForSelections( const LineSegment& mouseray ) {
}
if(KeyCommand::CheckPressed(keyboard, KeyCommand::kSelectSimilar, KIMF_LEVEL_EDITOR_GENERAL)) {
std::vector<std::string> selected_string;
- for (size_t i=0, len=scenegraph_->objects_.size(); i<len; ++i) {
- Object* obj = scenegraph_->objects_[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(); i<len; ++i) {
- Object* obj = scenegraph_->objects_[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(); i<len; ++i) {
- Object* obj = scenegraph_->objects_[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 +2277,8 @@ bool MapEditor::CheckForSelections( const LineSegment& mouseray ) {
}
void MapEditor::DeselectAll(SceneGraph *scenegraph) {
- for(size_t i=0, len=scenegraph->objects_.size(); i<len; ++i) {
- scenegraph->objects_[i]->Select(false);
+ for(auto & object : scenegraph->objects_) {
+ object->Select(false);
}
}
@@ -2339,11 +2317,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 +2472,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 &param = it->second;
@@ -2508,13 +2483,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 +2518,7 @@ void MapEditor::SaveSelected() {
// write out entities
TiXmlElement* parent = new TiXmlElement("ActorObjects");
doc.LinkEndChild(parent);
- 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()) {
obj->SaveToXML(parent);
}
@@ -2589,8 +2563,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<SavedChunk>::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 +2582,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 +2624,7 @@ void MapEditor::BringAllToCurrentState(int old_state){
}
}
- for(size_t i=0, len=scenegraph_->objects_.size(); i<len; ++i){
- Object* obj = scenegraph_->objects_[i];
+ for(auto obj : scenegraph_->objects_){
static const int kBufSize = 256;
char msg[kBufSize];
FormatString(msg, kBufSize, "added_object %d", obj->GetID());
@@ -2666,8 +2638,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(); i<len; ++i){
- Object* obj = scenegraph_->GetObjectFromID(selected_ids[i]);
+ for(int selected_id : selected_ids){
+ Object* obj = scenegraph_->GetObjectFromID(selected_id);
if(obj){
obj->Select(true);
}
@@ -2755,8 +2727,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 +2765,8 @@ void MapEditor::ToggleImposter() {
void MapEditor::SetImposter(bool set) {
ReturnSelected(&selected);
- for(unsigned i=0; i<selected.size(); ++i){
- selected[i]->SetImposter(set);
+ for(auto & i : selected){
+ i->SetImposter(set);
}
}
@@ -2894,8 +2866,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; i<desc_list.size(); ++i){
- Object* obj = AddEntityFromDesc(scenegraph_, desc_list[i], false);
+ for(auto & i : desc_list){
+ Object* obj = AddEntityFromDesc(scenegraph_, i, false);
if(obj){
id = obj->GetID();
} else {
@@ -2908,9 +2880,9 @@ int MapEditor::CreateObject( const std::string& path) {
void MapEditor::ReturnSelected(std::vector<Object*> *selected_objects) {
selected_objects->clear();
- for (size_t i=0, len=scenegraph_->objects_.size(); i<len; ++i) {
- if (scenegraph_->objects_[i]->Selected()) {
- selected_objects->push_back(scenegraph_->objects_[i]);
+ for (auto & object : scenegraph_->objects_) {
+ if (object->Selected()) {
+ selected_objects->push_back(object);
}
}
}
@@ -2932,8 +2904,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(); i<len; ++i) {
- Object* obj = scenegraph_->objects_[i];
+ for (auto obj : scenegraph_->objects_) {
if(!type_enable_.IsTypeEnabled(obj->GetType())){
obj->Select(false);
}
@@ -2946,8 +2917,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(); i<len; ++i) {
- Object* obj = scenegraph_->objects_[i];
+ for (auto obj : scenegraph_->objects_) {
obj->editor_visible = type_visible_.IsTypeEnabled(obj->GetType());
}
}
@@ -2971,11 +2941,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 +2956,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 +2979,7 @@ void MapEditor::UpdateGPUSkinning() {
}
void MapEditor::CarveAgainstTerrain() {
- for(std::vector<EnvObject*>::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 +3537,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 +3591,8 @@ void MapEditor::UpdateTransformTool(SceneGraph *scenegraph, EditorTypes::Tool ty
ActorsEditor_UnlocalizeIDs(&copy_desc_list, scenegraph);
MapEditor::DeselectAll(scenegraph);
std::vector<Object*> new_objects;
- for (size_t i=0, len=copy_desc_list.size(); i<len; ++i) {
- Object* new_entity = CreateObjectFromDesc(copy_desc_list[i]);
+ for (auto & i : copy_desc_list) {
+ Object* new_entity = CreateObjectFromDesc(i);
if( new_entity ) {
new_objects.push_back(new_entity);
if(new_entity->permission_flags & Object::CAN_SELECT){
@@ -3648,16 +3608,13 @@ void MapEditor::UpdateTransformTool(SceneGraph *scenegraph, EditorTypes::Tool ty
LOGE << "Failed to entity" << std::endl;
}
}
- for (size_t i=0, len=new_objects.size(); i<len; ++i) {
- new_objects[i]->ReceiveObjectMessage(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 +3630,8 @@ void MapEditor::UpdateTransformTool(SceneGraph *scenegraph, EditorTypes::Tool ty
} else if (state_ == MapEditor::kTransformDrag && transformation_happened) { // continue
std::vector<int> 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 +3647,8 @@ void MapEditor::UpdateTransformTool(SceneGraph *scenegraph, EditorTypes::Tool ty
std::ostringstream oss;
oss << "moved_objects";
- for(size_t i=0, len=moved_objects.size(); i<len; ++i){
- oss << " " << moved_objects[i];
+ for(int moved_object : moved_objects){
+ oss << " " << moved_object;
}
scenegraph_->level->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<SavedChunk> &chunk_list, int state_i
bool SkyEditor::ReadChunk( SavedChunk &the_chunk ) {
bool something_changed = false;
EntityDescription &desc = the_chunk.desc;
- for(unsigned i=0; i<desc.fields.size(); ++i){
- EntityDescriptionField& field = desc.fields[i];
+ for(auto & field : desc.fields){
switch(field.type){
case EDF_SUN_RADIUS:{
float old_m_sun_angular_rad = m_sun_angular_rad;
diff --git a/Source/GUI/IMUI/im_container.cpp b/Source/GUI/IMUI/im_container.cpp
index 8c1adcba..047e7d43 100644
--- a/Source/GUI/IMUI/im_container.cpp
+++ b/Source/GUI/IMUI/im_container.cpp
@@ -153,10 +153,8 @@ void IMContainer::setOwnerParent( IMGUI* _owner, IMElement* _parent ) {
contents->setOwnerParent( _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<IMElement*> IMContainer::getFloatingContents() {
std::vector<IMElement*> 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<IMContainer*> containers_copy = containers;
- for(std::vector<IMContainer*>::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<IMSpacer*>( containers[i]->contents ) ) {
+ if( IMSpacer* spacer = dynamic_cast<IMSpacer*>( 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<IMSpacer*>( containers[i]->contents );
+ IMSpacer* spacer = dynamic_cast<IMSpacer*>( 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<IMContainer*> deletelist = containers;
containers.clear();
- for( std::vector<IMContainer*>::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<std::string> 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<std::string> 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<std::string> 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<std::string> 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<std::string> 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<std::string, int>::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<IMContainer*>::iterator it = header.begin();
- it != header.end();
- ++it ) {
+ for(auto & it : header) {
- (*it)->Release();
+ it->Release();
}
- for( std::vector<IMContainer*>::iterator it = footer.begin();
- it != footer.end();
- ++it ) {
+ for(auto & it : footer) {
- (*it)->Release();
+ it->Release();
}
- for( std::vector<IMContainer*>::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<float>::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<float>::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<float>::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<IMContainer*>::iterator it = header.begin();
- it != header.end();
- ++it ) {
- (*it)->doRelayout();
+ for(auto & it : header) {
+ it->doRelayout();
}
- for( std::vector<IMContainer*>::iterator it = footer.begin();
- it != footer.end();
- ++it ) {
- (*it)->doRelayout();
+ for(auto & it : footer) {
+ it->doRelayout();
}
- for( std::vector<IMContainer*>::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<IMContainer*>::iterator it = header.begin();
- it != header.end();
- ++it ) {
- (*it)->doScreenResize();
+ for(auto & it : header) {
+ it->doScreenResize();
}
- for( std::vector<IMContainer*>::iterator it = footer.begin();
- it != footer.end();
- ++it ) {
- (*it)->doScreenResize();
+ for(auto & it : footer) {
+ it->doScreenResize();
}
- for( std::vector<IMContainer*>::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<IMContainer*>::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<IMContainer*>::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<IMContainer*>::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<utf32_string.size(); ++i){
- uint32_t c = utf32_string[i];
+ for(unsigned int c : utf32_string){
if(c == '\n') {
if( currentLineX > 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_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;
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<SoundSourceInfo> 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<ItemObjectScriptReader>::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<ItemObjectScriptReader>::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<Group*>(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<ModInstance*>& 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<Level::HookedASContext>& contexts = scenegraph->level->as_contexts_;
- for(std::vector<Level::HookedASContext>::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<Level::HookedASContext>& contexts = scenegraph->level->as_contexts_;
- for(std::vector<Level::HookedASContext>::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(); i<len; ++i){
+ for(auto obj : scenegraph->objects_){
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<Group*>(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_index<len; ++obj_index){
- Object* obj = scenegraph->collide_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(); i<len; ++i){
- if(eo->normal_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(); i<len; ++i){
- eo->normal_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<int> checked;
checked.resize(half_edges.size(), 0);
std::queue<HalfEdge*> to_check;
- for(size_t index=0, len=half_edges.size(); index<len; ++index){
- if(half_edges[index].vert[0] == vert_translate[0] &&
- half_edges[index].vert[1] == vert_translate[1])
+ for(auto & half_edge : half_edges){
+ if(half_edge.vert[0] == vert_translate[0] &&
+ half_edge.vert[1] == vert_translate[1])
{
- to_check.push(&half_edges[index]);
+ to_check.push(&half_edge);
}
}
vec3 start_norm;
@@ -3522,9 +3515,9 @@ Mark Stockton\nMikko Tarmia");
}
vec3 verts[3];
- for(int i=0; i<3; ++i){
+ for(auto & vert : verts){
int vert_index = processed_model.old_vert_id[curr->vert[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(); index<len; ++index){
- HalfEdge* curr = &half_edges[index];
+ for(auto & half_edge : half_edges){
+ HalfEdge* curr = &half_edge;
if(curr->twin) {
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<std::pair<std::string, int> > 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<std::pair<const char*,std::vector<ModInstance*> > > GetCatego
const std::vector<ModInstance*> 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<ModInstance*> 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<ModInstance*> 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<std::string> 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..dd9def22 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<int>());
UpdateAnisotropy(config.GetRef("anisotropy").toNumber<int>());
@@ -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<ModInstance::Campaign> 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<ModInstance::Campaign> 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<ModInstance::Campaign> 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<std::string> 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 & difficulty : difficulties) {
+ if( ImGui::Button(difficulty.c_str())) {
std::vector<ModInstance::Campaign> 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",difficulty) ) {
+ s.AppendArrayValue("finished_difficulties",difficulty);
}
}
}
@@ -1190,17 +1186,16 @@ void DrawSettingsImGui(SceneGraph* scenegraph, ImGuiSettingsType type){
if(ImGui::BeginMenu("Finish Level On Difficulty")) {
std::vector<ModInstance::Campaign> 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 & 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",difficulties[k]) ) {
- s.AppendArrayValue("finished_difficulties",difficulties[k]);
+ if( false == s.ArrayContainsValue("finished_difficulties",difficulty) ) {
+ s.AppendArrayValue("finished_difficulties",difficulty);
}
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<ModInstance::Campaign> 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<ModInstance::Campaign> 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; i<fields.size(); ++i){
- if(fields[i].type == type){
- return &fields[i];
+ for(const auto & field : fields){
+ if(field.type == type){
+ return &field;
}
}
return NULL;
}
EntityDescriptionField* EntityDescription::GetField( EntityDescriptionFieldType type ) {
- for(unsigned i=0; i<fields.size(); ++i){
- if(fields[i].type == type){
- return &fields[i];
+ for(auto & field : fields){
+ if(field.type == type){
+ return &field;
}
}
return NULL;
}
EntityDescriptionField* EntityDescription::GetEditableField( EntityDescriptionFieldType type ){
- for(unsigned i=0; i<fields.size(); ++i){
- if(fields[i].type == type){
- return &fields[i];
+ for(auto & field : fields){
+ if(field.type == type){
+ return &field;
}
}
return NULL;
@@ -132,8 +132,7 @@ void EntityDescription::AddPalette( EntityDescriptionFieldType type, const OGPal
void EntityDescription::ReturnPaths( PathSet& path_set ){
std::string str;
EntityType type = _no_type;
- for(unsigned i=0; i<fields.size(); ++i){
- EntityDescriptionField &field = fields[i];
+ for(auto & field : fields){
switch(field.type){
case EDF_FILE_PATH:
field.ReadString(&str);
@@ -176,14 +175,12 @@ void EntityDescription::ReturnPaths( PathSet& path_set ){
Engine::Instance()->GetAssetManager()->LoadSync<Item>(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; i<fields.size(); ++i){
- const EntityDescriptionField &field = fields[i];
+ for(const auto & field : fields){
switch(field.type){
case EDF_ID: {
int id;
@@ -374,9 +370,9 @@ void EntityDescription::SaveToXML( TiXmlElement* parent ) const {
// Write connections to XML
TiXmlElement* connections_el = new TiXmlElement("Connections");
object->LinkEndChild(connections_el);
- for(size_t i=0, len=connections.size(); i<len; ++i){
+ for(int i : connections){
TiXmlElement* connection = new TiXmlElement("Connection");
- connection->SetAttribute("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(); i<len; ++i){
+ for(int i : connections){
TiXmlElement* connection = new TiXmlElement("Connection");
- connection->SetAttribute("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(); i<len; ++i) {
- ItemConnectionData& item_connection = item_connections[i];
+ for(auto & item_connection : item_connections) {
TiXmlElement* item_connection_el = new TiXmlElement("ItemConnection");
item_connection_el->SetAttribute("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; i<aeo_vec.size(); ++i){
+ for(auto & aeo : aeo_vec){
TiXmlElement* connection = new TiXmlElement("EnvObjectAttachment");
env_object_attachments->LinkEndChild(connection);
- const AttachedEnvObject& aeo = aeo_vec[i];
- for(unsigned j=0; j<kMaxBoneConnects; ++j){
+ for(const auto & bone_connect : aeo.bone_connects){
TiXmlElement* bone_connect_el = new TiXmlElement("BoneConnect");
connection->LinkEndChild(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(); i<len; ++i) {
- NavMeshConnectionData& navmesh_connection = navmesh_connections[i];
+ for(auto & navmesh_connection : navmesh_connections) {
TiXmlElement* navmesh_connection_el = new TiXmlElement("NavMeshConnection");
navmesh_connection_el->SetAttribute("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; i<items.size(); ++i){
- if(items[i]->HasAnimOverride(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; i<items.size(); ++i){
- if(items[i]->HasAnimOverride(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; i<items.size(); ++i){
- if(items[i]->HasAttackOverride(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<Character>(char_path);
const std::set<std::string> &team_set = character_ref->GetTeamSet();
- for(std::set<std::string>::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; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_COLOR:
memread(tint_.entries, sizeof(float), 3, field.data);
diff --git a/Source/Game/level.cpp b/Source/Game/level.cpp
index 72aacc43..b3f5ec12 100644
--- a/Source/Game/level.cpp
+++ b/Source/Game/level.cpp
@@ -69,18 +69,18 @@ Level::~Level() {
void Level::Dispose() {
Message("dispose_level");
- for( uint32_t i = 0; i < as_contexts_.size(); i++ ) {
- delete as_contexts_[i].ctx;
- as_contexts_[i].ctx = NULL;
+ for(auto & as_context : as_contexts_) {
+ delete as_context.ctx;
+ as_context.ctx = NULL;
}
as_contexts_.clear();
Engine::Instance()->GetASNetwork()->DeRegisterASNetworkCallback(this);
old_col_map_.clear();
- for(int i=0; i<kMaxTextElements; ++i){
- text_elements[i].in_use = false;
- text_elements[i].text_canvas_texture.Reset();
+ for(auto & text_element : text_elements){
+ text_element.in_use = false;
+ text_element.text_canvas_texture.Reset();
}
}
@@ -96,17 +96,17 @@ Path Level::FindScript(const std::string& path) {
void Level::StartDialogue(const std::string& dialogue) const {
ASArglist args;
args.AddObject((void*)&dialogue);
- for (unsigned i = 0; i < as_contexts_.size(); i++) {
- if (as_contexts_[i].ctx->HasFunction(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<uint8>@ 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<uint8>@ 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<HookedASContext >::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(); i<len; ++i){
- Object* obj = scenegraph->GetObjectFromID(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(); i<len; ++i){
- const LevelInfo::StrPair &script_path = li.script_paths_[i];
+ for(const auto & script_path : li.script_paths_){
level_script_paths[script_path.first] = script_path.second;
}
recently_created_items_ = li.recently_created_items_;
@@ -843,8 +841,8 @@ bool Level::HasFocus() {
ASArg return_arg;
return_arg.data = &has_focus;
return_arg.type = _as_bool;
- for(unsigned i = 0; i < as_contexts_.size(); i++ ) {
- as_contexts_[i].ctx->CallScriptFunction(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<SavedChunk> & 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<SpawnerItem> 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<uint8>");
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; i<ambient_sounds_.size(); ++i){
- LOGI << "Ambient sound: " << ambient_sounds_[i] << std::endl;
+ for(auto & ambient_sound : ambient_sounds_){
+ LOGI << "Ambient sound: " << ambient_sound << std::endl;
}
sky_info_.Print();
@@ -76,17 +76,17 @@ void LevelInfo::ReturnPaths( PathSet &path_set )
static const int kBufSize = 256;
char buf[kBufSize];
path_set.insert("level "+path_);
- for(unsigned i=0; i<ambient_sounds_.size(); ++i){
- path_set.insert("sound "+ambient_sounds_[i]+"_1.wav");
- path_set.insert("sound "+ambient_sounds_[i]+"_2.wav");
- path_set.insert("sound "+ambient_sounds_[i]+"_3.wav");
+ for(auto & ambient_sound : ambient_sounds_){
+ path_set.insert("sound "+ambient_sound+"_1.wav");
+ path_set.insert("sound "+ambient_sound+"_2.wav");
+ path_set.insert("sound "+ambient_sound+"_3.wav");
}
terrain_info_.ReturnPaths(path_set);
sky_info_.ReturnPaths(path_set);
- for(unsigned i=0; i<script_paths_.size(); ++i){
- FormatString(buf, kBufSize, "Finding script paths: %s", script_paths_[i].first.c_str());
+ for(auto & script_path : script_paths_){
+ FormatString(buf, kBufSize, "Finding script paths: %s", script_path.first.c_str());
PROFILER_ZONE_DYNAMIC_STRING(g_profiler_ctx, buf);
- ReturnPathUtil::ReturnPathsFromPath(script_paths_[i].second, path_set);
+ ReturnPathUtil::ReturnPathsFromPath(script_path.second, path_set);
}
for(unsigned i=0; i<desc_list_.size(); ++i){
FormatString(buf, kBufSize, "Finding desc_list paths: %d", i);
diff --git a/Source/Game/paths.cpp b/Source/Game/paths.cpp
index 2688cba7..1fdf8bcf 100644
--- a/Source/Game/paths.cpp
+++ b/Source/Game/paths.cpp
@@ -39,9 +39,9 @@ void AIPaths::Draw() {
vec4(0.0f,0.5f,0.5f,0.5f),
_delete_on_draw);
}
- for(unsigned i=0; i<connections.size(); ++i){
- DebugDraw::Instance()->AddLine(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; i<connections.size(); ++i){
- if(connections[i].point_ids[0] == point_id){
- return connections[i].point_ids[1];
+ for(auto & connection : connections){
+ if(connection.point_ids[0] == point_id){
+ return connection.point_ids[1];
}
- if(connections[i].point_ids[1] == point_id){
- return connections[i].point_ids[0];
+ if(connection.point_ids[1] == point_id){
+ return connection.point_ids[0];
}
}
return -1;
@@ -91,14 +91,14 @@ int AIPaths::GetConnectedPoint( int point_id )
int AIPaths::GetOtherConnectedPoint( int point_id, int other_id )
{
- for(unsigned i=0; i<connections.size(); ++i){
- if(connections[i].point_ids[0] == point_id &&
- connections[i].point_ids[1] != other_id){
- return connections[i].point_ids[1];
+ for(auto & connection : connections){
+ if(connection.point_ids[0] == point_id &&
+ connection.point_ids[1] != other_id){
+ return connection.point_ids[1];
}
- if(connections[i].point_ids[1] == point_id &&
- connections[i].point_ids[0] != other_id){
- return connections[i].point_ids[0];
+ if(connection.point_ids[1] == point_id &&
+ connection.point_ids[0] != other_id){
+ return connection.point_ids[0];
}
}
return -1;
diff --git a/Source/Game/reactionscript.cpp b/Source/Game/reactionscript.cpp
index 1c28a9da..f19abe0e 100644
--- a/Source/Game/reactionscript.cpp
+++ b/Source/Game/reactionscript.cpp
@@ -36,9 +36,9 @@ void ReactionScriptGetter::Load( std::string _path ) {
} else {
mirror = false;
}
- for(unsigned i=0; i<items.size(); ++i){
- if(items[i]->HasReactionOverride(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<uint8_t> *mem_ptr ) {
if(!file.WriteBytes(&num_levels, sizeof(num_levels))){
return false;
}
- for(std::vector<SavedLevel>::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<std::string> &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<std::string>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++) {
+ for(std::vector<std::string>::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<detail_map_info.size(); ++i)
+ for (auto & i : detail_map_info)
{
- detail_map_info[i].Print();
+ i.Print();
}
LOGI << "Detail objects: " << std::endl;
- for (unsigned i=0; i<detail_object_info.size(); ++i)
+ for (auto & i : detail_object_info)
{
- LOGI << "Obj path: " << detail_object_info[i].obj_path << std::endl;
+ LOGI << "Obj path: " << i.obj_path << std::endl;
}
}
@@ -76,10 +76,10 @@ void TerrainInfo::ReturnPaths( PathSet &path_set )
if(!model_override.empty()){
path_set.insert("model "+model_override);
}
- for(unsigned i=0; i<detail_map_info.size(); ++i){
- detail_map_info[i].ReturnPaths(path_set);
+ for(auto & i : detail_map_info){
+ i.ReturnPaths(path_set);
}
- for(unsigned i=0; i<detail_object_info.size(); ++i){
- detail_object_info[i].ReturnPaths(path_set);
+ for(auto & i : detail_object_info){
+ i.ReturnPaths(path_set);
}
}
diff --git a/Source/Graphics/animationclient.cpp b/Source/Graphics/animationclient.cpp
index 023b64a8..96ee9a3e 100644
--- a/Source/Graphics/animationclient.cpp
+++ b/Source/Graphics/animationclient.cpp
@@ -129,8 +129,8 @@ std::queue<AnimationEvent> AnimationClient::GetActiveEvents() {
events.pop();
}
}
- for(unsigned i=0; i<layers.size(); ++i){
- std::queue<AnimationEvent> &events = layers[i].reader.GetActiveEvents();
+ for(auto & layer : layers){
+ std::queue<AnimationEvent> &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<layers.size(); ++i){
- layers[i].fade_out.Update(blendmap, as_context, timestep);
+ for(auto & layer : layers){
+ layer.fade_out.Update(blendmap, as_context, timestep);
}
UpdateLayers(timestep);
}
@@ -240,8 +240,8 @@ void AnimationClient::GetMatrices( AnimOutput &anim_output, const std::vector<in
// Apply character rotation modifier
std::map<int, WeapAnimInfo> &weap_anim_info_map = ang_anim_output.weap_anim_info_map;
- for(int i=0, len=ang_anim_output.ik_bones.size(); i<len; ++i){
- ang_anim_output.ik_bones[i].unmodified_transform = ang_anim_output.ik_bones[i].transform;
+ for(auto & ik_bone : ang_anim_output.ik_bones){
+ ik_bone.unmodified_transform = ik_bone.transform;
}
anim_output.unmodified_matrices = matrices;
@@ -348,8 +348,8 @@ void FadeCollection::clear()
float FadeCollection::GetOpac()
{
float opac = 1.0f;
- for(unsigned i=0; i<fade_out.size(); ++i){
- opac *= (1.0f-fade_out[i].opac);
+ for(auto & i : fade_out){
+ opac *= (1.0f-i.opac);
}
return opac;
}
diff --git a/Source/Graphics/animationreader.cpp b/Source/Graphics/animationreader.cpp
index 3e0f662c..8cbcd356 100644
--- a/Source/Graphics/animationreader.cpp
+++ b/Source/Graphics/animationreader.cpp
@@ -102,10 +102,10 @@ bool AnimationReader::IncrementTime( const BlendMap &blendmap, float timestep )
}
float AnimationReader::GetTimeUntilEvent(const std::string &event){
- for(unsigned i=0; i<events.size(); ++i){
- if(events[i].event.event_string == event){
- if(events[i].time > 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<events.size(); ++i){
- if(events[i].time > 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<WalkLine>::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<CutLine>::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..04531b4e 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 & entry : entries){
+ entry = val;
}
}
vec3d(){
- for(int i=0; i<3; ++i){
- entries[i] = 0.0;
+ for(double & entry : entries){
+ entry = 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(); i<len; ++i){
- faces[i] = vert_sort[faces[i]].merge_target;
+ for(int & face : faces){
+ face = vert_sort[face].merge_target;
}
if(remove_degenerate_faces){
// -- remove degenerate faces
@@ -618,8 +618,8 @@ namespace {
shape->vertices.push_back(vec[2]);
}
shape->faces.reserve(model.faces.size());
- for(int i=0, len=model.faces.size(); i<len; ++i){
- shape->faces.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<len; ++j){
+ for(int j : on_edge){
EdgeAngleSort eas;
- eas.second = on_edge[j];
- vec2d offset = triangle_points[on_edge[j]].flat_coord - mid_point;
+ eas.second = j;
+ vec2d offset = triangle_points[j].flat_coord - mid_point;
eas.first = atan2(offset[1], offset[0]);
edge_angle.push_back(eas);
}
@@ -817,21 +817,21 @@ namespace {
triangle_points.resize(index+1);
}
// Remap edges to new points
- for(int i=0, len=edges.size(); i<len; ++i){
- edges[i] = triangle_point_remap[edges[i]];
+ for(int & edge : edges){
+ edge = triangle_point_remap[edge];
}
- for(int i=0, len=labeled_edges.size(); i<len; ++i){
- labeled_edges[i].points[0] = triangle_point_remap[labeled_edges[i].points[0]];
- labeled_edges[i].points[1] = triangle_point_remap[labeled_edges[i].points[1]];
- if(labeled_edges[i].points[0] > 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<float> points;
- for(int i=0, len=triangle_points.size(); i<len; ++i){
+ for(auto & triangle_point : triangle_points){
for(int j=0; j<2; ++j){
- points.push_back((float)triangle_points[i].flat_coord[j]);
+ points.push_back((float)triangle_point.flat_coord[j]);
}
}
// Triangulate
@@ -839,10 +839,10 @@ namespace {
TriangulateWrapper(points, edges, faces);
// Add new vertices
int vert_start = output.new_bary->size()/3;
- for(int j=0, len=triangle_points.size(); j<len; ++j){
+ for(auto & triangle_point : triangle_points){
for(int k=0; k<3; ++k){
- output.new_vertices->push_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<TrianglePoint::Side> triangle_side(faces.size()/3, TrianglePoint::UNKNOWN);
// Get outside/inside of edges neighboring edge
- for(int i=0, len=labeled_edges.size(); i<len; ++i){
- LabeledEdge &edge = labeled_edges[i];
+ for(auto & edge : labeled_edges){
if(edge.side == TrianglePoint::EDGE && edge.points[2] != -1){
vec3d opposite_vert = triangle_points[edge.points[2]].coord;
vec3d mid_point = (triangle_points[edge.points[0]].coord + triangle_points[edge.points[1]].coord)*0.5f;
@@ -978,11 +977,11 @@ namespace {
}
tri_queue.pop();
}
- for(int j=0, len=faces.size(); j<len; ++j){
- output.new_faces->push_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(); j<len; ++j){
- output.new_triangle_sides->push_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<TriIntersectInfo> &tri_intersect_info) {
std::vector<vec3d> test_points;
std::vector<MergeDist> test_point_distances;
- for(int i=0, len=tri_intersect_info.size(); i<len; ++i){
- TriIntersectInfo& tii = tri_intersect_info[i];
+ for(auto & tii : tri_intersect_info){
test_points.push_back(tii.tri_intersect.true_intersect[0]);
test_points.push_back(tii.tri_intersect.true_intersect[1]);
}
@@ -1029,8 +1027,7 @@ namespace {
}
}
std::sort(test_point_distances.begin(), test_point_distances.end());
- for(int i=0, len=test_point_distances.size(); i<len; ++i){
- MergeDist &tpd = test_point_distances[i];
+ for(auto & tpd : test_point_distances){
test_points[tpd.point[1]] = test_points[tpd.point[0]];
}
for(int i=0, index=0, len=tri_intersect_info.size(); i<len; ++i, index+=2){
@@ -1047,8 +1044,8 @@ bool CheckShapeValid(const std::vector<int> &faces, const std::vector<double> &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(); i<len; ++i){
- if(tri_neighbor_info.num_tri_neighbors[i] != 3){
+ for(int num_tri_neighbor : tri_neighbor_info.num_tri_neighbors){
+ if(num_tri_neighbor != 3){
non_three_neighbor = true;
}
}
@@ -1059,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 i=0, len=result.indices.size(); i<len; ++i){
- csg_model->faces.push_back(result.indices[i] + old_faces);
+ for(int index : result.indices){
+ csg_model->faces.push_back(index + old_faces);
}
} else {
for(int i=0, len=result.indices.size(); i<len; i+=3){
@@ -1152,10 +1149,9 @@ bool CollideObjects(BulletWorld& bw, const Model &model_a, const mat4 &transform
bw.GetPairCollisions(shape[1].col_obj, shape[0].col_obj, cb);
// Process triangle intersections to eliminate false positives and get precise intersection segments
std::vector<TriIntersectInfo> 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; i<triangle_area.size(); ++i){
+ for(float & i : triangle_area){
for(unsigned j=0; j<3; ++j){
vert_index = model.faces[face_index+j]*3;
verts[j] = vec3(model.vertices[vert_index+0],
@@ -81,7 +81,7 @@ void DetailObjectSurface::AttachTo( const Model& model, mat4 transform ) {
model.vertices[vert_index+2]);
verts[j] = transform * verts[j];
}
- triangle_area[i] = length(cross(verts[2]-verts[0], verts[1]-verts[0]))*0.5f;
+ i = length(cross(verts[2]-verts[0], verts[1]-verts[0]))*0.5f;
face_index += 3;
static const bool debug_draw = false;
if(debug_draw){
@@ -784,14 +784,14 @@ void DetailObjectSurface::CalcPatchInstances( const TriInt &coords, DOPatch &pat
if(!patch.detail_instance_transforms.empty()){
PROFILER_ZONE(g_profiler_ctx, "Get bounding sphere");
vec3 sphere_center;
- for(unsigned j=0; j<patch.detail_instance_transforms.size(); ++j){
- sphere_center += patch.detail_instance_transforms[j].GetTranslationPart();
+ for(auto & detail_instance_transform : patch.detail_instance_transforms){
+ sphere_center += detail_instance_transform.GetTranslationPart();
}
sphere_center /= (float)patch.detail_instance_transforms.size();
float least_distance = distance_squared(sphere_center, patch.detail_instance_transforms[0].GetTranslationPart());
- for(unsigned j=0; j<patch.detail_instance_transforms.size(); ++j){
+ for(auto & detail_instance_transform : patch.detail_instance_transforms){
least_distance = max(least_distance,
- distance_squared(sphere_center, patch.detail_instance_transforms[j].GetTranslationPart()));
+ distance_squared(sphere_center, detail_instance_transform.GetTranslationPart()));
}
patch.sphere_center = sphere_center;
patch.sphere_radius = sqrtf(least_distance);
diff --git a/Source/Graphics/drawbatch.cpp b/Source/Graphics/drawbatch.cpp
index 112ffa43..3fa4c285 100644
--- a/Source/Graphics/drawbatch.cpp
+++ b/Source/Graphics/drawbatch.cpp
@@ -100,8 +100,8 @@ DrawBatch::DrawBatch() : visible(true),
tex_coord_elements[i] = 0;
use_vbo_texcoords[i] = true;
}
- for(int i=0; i<kMaxTextures; i++){
- texture_ref[i].clear();
+ for(auto & i : texture_ref){
+ i.clear();
}
}
@@ -126,21 +126,21 @@ void DrawBatch::Draw() {
} else {
const Camera& camera = (*ActiveCameras::Get());
SetupVertexArrays();
- for(unsigned i=0; i<added_batches.size(); i++){
- if(camera.checkSphereInFrustum(added_batches[i].batch->bounding_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; i<other.added_batches.size(); i++){
- AddBatch(*(other.added_batches[i].batch));
+ for(const auto & added_batche : other.added_batches){
+ AddBatch(*(added_batche.batch));
}
return;
}
@@ -321,8 +321,8 @@ Uniform::Uniform():
void DrawBatch::Dispose() {
normals.clear();
vertices.clear();
- for(int i=0; i<8; i++){
- tex_coords[i].clear();
+ for(auto & tex_coord : tex_coords){
+ tex_coord.clear();
}
faces.clear();
uniforms.clear();
@@ -330,8 +330,8 @@ void DrawBatch::Dispose() {
vbo_faces->Dispose();
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; i<uniforms.size(); i++){
- uniforms[i].Apply();
+ for(const auto & uniform : uniforms){
+ uniform.Apply();
}
if(use_cam_pos){
@@ -453,9 +453,9 @@ void DrawBatch::SetupVertexArrays() const {
void DrawBatch::SetUniformFloat( std::string _name, GLfloat data )
{
- for(unsigned i=0; i<uniforms.size(); ++i){
- if(uniforms[i].name == _name){
- uniforms[i].data[0] = data;
+ for(auto & uniform : uniforms){
+ if(uniform.name == _name){
+ uniform.data[0] = data;
return;
}
}
@@ -464,27 +464,27 @@ void DrawBatch::SetUniformFloat( std::string _name, GLfloat data )
void DrawBatch::MakeUniformIndividual( std::string _name )
{
- for(unsigned i=0; i<uniforms.size(); ++i){
- if(uniforms[i].name == _name){
- uniforms[i].individual = true;
+ for(auto & uniform : uniforms){
+ if(uniform.name == _name){
+ uniform.individual = true;
}
}
}
void DrawBatch::ApplyIndividualUniforms() const
{
- for(unsigned i=0; i<uniforms.size(); i++){
- if(uniforms[i].individual){
- uniforms[i].Apply();
+ for(const auto & uniform : uniforms){
+ if(uniform.individual){
+ uniform.Apply();
}
}
}
void DrawBatch::SetUniformVec3( std::string _name, const vec3 &_data )
{
- for(unsigned i=0; i<uniforms.size(); ++i){
- if(uniforms[i].name == _name){
- memcpy(&uniforms[i].data[0],
+ for(auto & uniform : uniforms){
+ if(uniform.name == _name){
+ memcpy(&uniform.data[0],
(const GLfloat*)_data.entries,
3*sizeof(GLfloat));
}
@@ -504,9 +504,9 @@ void DrawBatch::AddUniformVec4( std::string _name, const vec4 &_data ) {
}
void DrawBatch::SetUniformVec4( std::string _name, const vec4 &_data ) {
- for(unsigned i=0; i<uniforms.size(); ++i){
- if(uniforms[i].name == _name){
- memcpy(&uniforms[i].data[0],
+ for(auto & uniform : uniforms){
+ if(uniform.name == _name){
+ memcpy(&uniform.data[0],
(const GLfloat*)_data.entries,
4*sizeof(GLfloat));
}
diff --git a/Source/Graphics/dynamiclightcollection.cpp b/Source/Graphics/dynamiclightcollection.cpp
index 2f6e3b18..98cebcf6 100644
--- a/Source/Graphics/dynamiclightcollection.cpp
+++ b/Source/Graphics/dynamiclightcollection.cpp
@@ -84,9 +84,9 @@ void DynamicLightCollection::Dispose() {
}
DynamicLight* DynamicLightCollection::GetLightFromID(int id) {
- for(int i=0, len=dynamic_lights.size(); i<len; ++i){
- if(dynamic_lights[i].id == id) {
- return &dynamic_lights[i];
+ for(auto & dynamic_light : dynamic_lights){
+ if(dynamic_light.id == id) {
+ return &dynamic_light;
}
}
return NULL;
diff --git a/Source/Graphics/flares.cpp b/Source/Graphics/flares.cpp
index f199dd41..e9ac8114 100644
--- a/Source/Graphics/flares.cpp
+++ b/Source/Graphics/flares.cpp
@@ -394,8 +394,7 @@ void Flares::Update(float timestep) {
old_angle = new_angle;
new_angle = RangedRandomFloat(0.0f,360.0f);
}
- for (unsigned i=0; i<flares.size(); i++) {
- Flare* flare = flares[i];
+ for (auto flare : flares) {
flare->old_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<Flare*>::iterator flare_iter = std::find(flares.begin(), flares.end(), flare);
if(flare_iter != flares.end()){
Flare* flare = (*flare_iter);
- for(unsigned i=0; i<flare->query.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; i<flare->query.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<float>& 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<float>& 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<float>& 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<float>& ve
CollapseHalfEdge(heap, edge->twin);
}
// Recalc err and update heap
- for(std::set<HalfEdge*>::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<hud_images.size(); ++i){
+ for(auto & hi : hud_images){
PROFILER_GPU_ZONE(g_profiler_ctx, "HUDImages draw iteration");
CHECK_GL_ERROR();
- const HUDImage& hi = hud_images[i];
if(hi.color[3] <= 0.0f){
continue;
}
diff --git a/Source/Graphics/kdtreecluster.cpp b/Source/Graphics/kdtreecluster.cpp
index 9d1a7d84..6732acd8 100644
--- a/Source/Graphics/kdtreecluster.cpp
+++ b/Source/Graphics/kdtreecluster.cpp
@@ -35,9 +35,9 @@ void GetClosestClusters( KDNode &node, const std::vector<vec3> &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<vec3> &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<ve
const int _rand_pick_threshold = 20;
if((int)points.size()>_rand_pick_threshold){
std::vector<vec3> median_points(_rand_pick_threshold);
- for(unsigned i=0; i<median_points.size(); ++i){
- median_points[i] = points[rand()%points.size()];
+ for(auto & median_point : median_points){
+ median_point = points[rand()%points.size()];
}
if(axis == 0){
std::sort(median_points.begin(), median_points.end(), Vec3XCompare());
@@ -308,22 +308,22 @@ KDNode::KDNode( const vec3 &_min_bounds, const vec3 &_max_bounds, std::vector<ve
vec3 child_max = _max_bounds;
child_max[axis] = plane_coord;
std::vector<vec3> child_points;
- for(unsigned i=0; i<points.size(); ++i){
- if(points[i].entries[axis] < plane_coord){
- child_points.push_back(points[i]);
+ for(auto & point : points){
+ if(point.entries[axis] < plane_coord){
+ child_points.push_back(point);
}
}
child[0] = new KDNode(child_min, child_max, child_points, depth+1);
child[0]->content_bounds[0] = median_point;
child[0]->content_bounds[1] = median_point;
- for(unsigned i=0; i<child_points.size(); ++i){
+ for(auto & child_point : child_points){
for(unsigned j=0; j<3; ++j){
- if(child_points[i][j] < child[0]->content_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<ve
child_max = _max_bounds;
child_min[axis] = plane_coord;
child_points.clear();
- for(unsigned i=0; i<points.size(); ++i){
- if(points[i].entries[axis] > 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; i<child_points.size(); ++i){
+ for(auto & child_point : child_points){
for(unsigned j=0; j<3; ++j){
- if(child_points[i][j] < child[1]->content_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..b255ad87 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<len; ++i){
- if(light_probes[i].id == id) {
- return &light_probes[i];
+ for(auto & light_probe : light_probes){
+ if(light_probe.id == id) {
+ return &light_probe;
}
}
return NULL;
@@ -585,9 +585,9 @@ void LightProbeCollection::UpdateTextureBuffer(BulletWorld& bw) {
++index;
}
} else {
- for(int face=0; face<6; ++face){
+ for(auto & face : probe.ambient_cube_color){
for(int channel=0; channel<3; ++channel){
- unsigned val = (unsigned)(probe.ambient_cube_color[face][channel] * 255.0f / 4.0f);
+ unsigned val = (unsigned)(face[channel] * 255.0f / 4.0f);
tet_colors[index] = (val > 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 index : indices){
+ if(index == 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 index : indices){
+ if(index == GL_INVALID_INDEX){
return;
}
}
diff --git a/Source/Graphics/model.cpp b/Source/Graphics/model.cpp
index 1dbcfeaf..ca4b61a0 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<indices.size(); ++j){
- a.tex_coords2[indices[j]*2+0] = b.tex_coords[i*2+0];
- a.tex_coords2[indices[j]*2+1] = b.tex_coords[i*2+1];
+ for(int index : indices){
+ a.tex_coords2[index*2+0] = b.tex_coords[i*2+0];
+ a.tex_coords2[index*2+1] = b.tex_coords[i*2+1];
}
}
@@ -900,12 +900,12 @@ void CopyTexCoords2( Model &a, const Model& b ) {
[floorf(n_i[2]*10.0f+0.5f)];
normal_index += 3;
vert_index += 3;
- for(unsigned j=0; j<indices.size(); ++j){
- if(a.tex_coords2[indices[j]*2+0] == 0.0f &&
- a.tex_coords2[indices[j]*2+1] == 0.0f)
+ for(int index : indices){
+ if(a.tex_coords2[index*2+0] == 0.0f &&
+ a.tex_coords2[index*2+1] == 0.0f)
{
- a.tex_coords2[indices[j]*2+0] = b.tex_coords[i*2+0];
- a.tex_coords2[indices[j]*2+1] = b.tex_coords[i*2+1];
+ a.tex_coords2[index*2+0] = b.tex_coords[i*2+0];
+ a.tex_coords2[index*2+1] = b.tex_coords[i*2+1];
}
}
}
@@ -946,12 +946,12 @@ void CopyTexCoords2( Model &a, const Model& b ) {
[floorf(n_i[2]*1.0f+0.5f)];
normal_index += 3;
vert_index += 3;
- for(unsigned j=0; j<indices.size(); ++j){
- if(a.tex_coords2[indices[j]*2+0] == 0.0f &&
- a.tex_coords2[indices[j]*2+1] == 0.0f)
+ for(int index : indices){
+ if(a.tex_coords2[index*2+0] == 0.0f &&
+ a.tex_coords2[index*2+1] == 0.0f)
{
- a.tex_coords2[indices[j]*2+0] = b.tex_coords[i*2+0];
- a.tex_coords2[indices[j]*2+1] = b.tex_coords[i*2+1];
+ a.tex_coords2[index*2+0] = b.tex_coords[i*2+0];
+ a.tex_coords2[index*2+1] = b.tex_coords[i*2+1];
}
}
}
@@ -2199,8 +2199,8 @@ void Model::RemoveDuplicatedVerts() {
for(int i=0, len=unique.size(); i<len; ++i){
precollapse_vert_reorder[i] = vert_info[unique[i]].old_id;
}
- for(int i=0, len=faces.size(); i<len; ++i){
- faces[i] = new_vert[faces[i]];
+ for(unsigned int & face : faces){
+ face = new_vert[face];
}
RearrangeVertices(*this, precollapse_vert_reorder);
@@ -2306,14 +2306,14 @@ void Model::PrintACMR(){
unsigned total = 0;
std::vector<int> fifo(32, -1);
unsigned index = 0;
- for(unsigned i=0; i<faces.size(); ++i){
- for(unsigned j=0; j<fifo.size(); ++j){
- if(fifo[j] == (int)faces[i]){
+ for(unsigned int face : faces){
+ for(int j : fifo){
+ if(j == (int)face){
cache_hits++;
break;
}
}
- fifo[index] = faces[i];
+ fifo[index] = face;
index = (index+1)%fifo.size();
total++;
}
@@ -2330,8 +2330,8 @@ void Model::OptimizeTriangleOrder() {
tris[i].verts[0] = faces[index++];
tris[i].verts[1] = faces[index++];
tris[i].verts[2] = faces[index++];
- for(unsigned j=0; j<3; ++j){
- verts[tris[i].verts[j]].not_added_triangles++;
+ for(unsigned int vert : tris[i].verts){
+ verts[vert].not_added_triangles++;
}
}
@@ -2363,13 +2363,11 @@ void Model::OptimizeTriangleOrder() {
}
tris[best_triangle].added = true;
// Update not_added_triangles
- for(unsigned i=0; i<3; ++i){
- unsigned vert_id = tris[best_triangle].verts[i];
+ for(unsigned int vert_id : tris[best_triangle].verts){
--verts[vert_id].not_added_triangles;
}
// Update LRU cache
- for(unsigned i=0; i<3; ++i){
- unsigned vert_id = tris[best_triangle].verts[i];
+ for(unsigned int vert_id : tris[best_triangle].verts){
int cp = verts[vert_id].cache_pos;
// If vert is in cache, remove it and slide other verts down
if(cp != -1){
@@ -2421,10 +2419,10 @@ void Model::OptimizeTriangleOrder() {
{
unsigned index = 0;
- for(unsigned i=0; i<draw_list.size(); ++i){
- faces[index++] = tris[draw_list[i]].verts[0];
- faces[index++] = tris[draw_list[i]].verts[1];
- faces[index++] = tris[draw_list[i]].verts[2];
+ for(unsigned int i : draw_list){
+ faces[index++] = tris[i].verts[0];
+ faces[index++] = tris[i].verts[1];
+ faces[index++] = tris[i].verts[2];
}
}
}
@@ -2433,11 +2431,11 @@ void Model::OptimizeTriangleOrder() {
void Model::OptimizeVertexOrder() {
std::vector<int> order(vertices.size()/3, -1);
unsigned index = 0;
- for(unsigned i=0; i<faces.size(); ++i){
- if(order[faces[i]] == -1){
- order[faces[i]] = index++;
+ for(unsigned int & face : faces){
+ if(order[face] == -1){
+ order[face] = index++;
}
- faces[i] = order[faces[i]];
+ face = order[face];
}
optimize_vert_reorder.clear();
optimize_vert_reorder.resize(index, -1);
@@ -2496,9 +2494,9 @@ void Model::SortTrianglesBackToFront( const vec3 &camera )
std::sort(tris.begin(), tris.end(), TriScoreSorter());
index = 0;
- for(unsigned i=0; i<tris.size(); ++i){
- faces[index++] = tris[i].verts[0];
- faces[index++] = tris[i].verts[1];
- faces[index++] = tris[i].verts[2];
+ for(auto & tri : tris){
+ faces[index++] = tri.verts[0];
+ faces[index++] = tri.verts[1];
+ faces[index++] = tri.verts[2];
}
}
diff --git a/Source/Graphics/modelsurfacewalker.cpp b/Source/Graphics/modelsurfacewalker.cpp
index cd2c8314..90dd5d4e 100644
--- a/Source/Graphics/modelsurfacewalker.cpp
+++ b/Source/Graphics/modelsurfacewalker.cpp
@@ -107,16 +107,16 @@ void ModelSurfaceWalker::AttachTo(const std::vector<float> &vertices, const std:
std::vector<Tri> tris(faces.size()/3);
int index = 0;
- for(int i=0, len=tris.size(); i<len; ++i){
+ for(auto & tri : tris){
for(int j=0; j<3; ++j) {
for(int k=0; k<2; ++k){
- tris[i].edges[j].points[k] = first_dup[faces[index+(j+k)%3]];
+ tri.edges[j].points[k] = first_dup[faces[index+(j+k)%3]];
}
- if(tris[i].edges[j].points[0] > 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<float> &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<Edge, std::vector<int> >::iterator iter = edge_tris.begin();
- iter != edge_tris.end();
- ++iter)
+ for(auto & edge_tri : edge_tris)
{
- const Edge& edge = iter->first;
- const std::vector<int> &faces = iter->second;
+ const Edge& edge = edge_tri.first;
+ const std::vector<int> &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<float> &vertices, const std:
// Get the length of each edge of each triangle
vec3 points[3];
int face_index = 0;
- for(unsigned i=0; i<tri_info.size(); ++i){
- for(unsigned j=0; j<3; ++j){
- points[j] = vec3(vertices[faces[face_index]*3+0],
+ for(auto & i : tri_info){
+ for(auto & point : points){
+ point = vec3(vertices[faces[face_index]*3+0],
vertices[faces[face_index]*3+1],
vertices[faces[face_index]*3+2]);
++face_index;
}
- tri_info[i].edge_length[0] = distance(points[0], points[1]);
- tri_info[i].edge_length[1] = distance(points[1], points[2]);
- tri_info[i].edge_length[2] = distance(points[2], points[0]);
+ i.edge_length[0] = distance(points[0], points[1]);
+ i.edge_length[1] = distance(points[1], points[2]);
+ i.edge_length[2] = distance(points[2], points[0]);
}
}
diff --git a/Source/Graphics/palette.cpp b/Source/Graphics/palette.cpp
index d66afc83..44d9dd7d 100644
--- a/Source/Graphics/palette.cpp
+++ b/Source/Graphics/palette.cpp
@@ -60,12 +60,12 @@ void WritePaletteToRAM( const OGPalette& palette, std::vector<char> &data )
void WritePaletteToXML( const OGPalette & palette, TiXmlElement* palette_el )
{
- for(unsigned i=0; i<palette.size(); ++i){
+ for(const auto & i : palette){
TiXmlElement* color_el = new TiXmlElement("Color");
palette_el->LinkEndChild(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<mat4> light_volume_matrix;
std::vector<mat4> light_volume_matrix_inverse;
- for(int i=0, len=scenegraph->light_volume_objects_.size(); i<len; ++i){
- Object* obj = scenegraph->light_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<mat4> light_volume_matrix;
std::vector<mat4> light_volume_matrix_inverse;
- for(int i=0, len=scenegraph->objects_.size(); i<len; ++i){
- Object* obj = scenegraph->objects_[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(); i<len; ++i) {
- Particle& p = *particles[i];
+ for (auto & particle : particles) {
+ Particle& p = *particle;
p.interp_position = mix(p.old_position, p.position, interp);
p.interp_rotation = mix(p.old_rotation, p.rotation, interp);
p.interp_size = mix(p.old_size, p.size, interp);
@@ -881,8 +879,8 @@ void ParticleSystem::Draw(SceneGraph *scenegraph) {
PROFILER_LEAVE(g_profiler_ctx); // Interpolate particles
vec3 cam_pos = ActiveCameras::Get()->GetPos();
- for (unsigned i=0;i<particles.size();i++){
- particles[i]->cam_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<mat4> light_volume_matrix;
std::vector<mat4> light_volume_matrix_inverse;
- for(int i=0, len=scenegraph->light_volume_objects_.size(); i<len; ++i){
- Object* obj = scenegraph->light_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<programs.size(); ++i){
- Program& program = programs[i];
+ for(auto & program : programs){
if(program.gl_program != UNLOADED_SHADER_ID) {
- for(int i=0; i<kMaxShaderTypes; ++i){
- if( program.shader_ids[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; i<shaders.size(); ++i){
- if(shaders[i].gl_shader != UNLOADED_SHADER_ID) {
- glDeleteShader(shaders[i].gl_shader);
+ for(auto & shader : shaders){
+ if(shader.gl_shader != UNLOADED_SHADER_ID) {
+ glDeleteShader(shader.gl_shader);
}
}
@@ -190,20 +189,20 @@ static void Preprocess(Shader* shader, ShaderType type, const std::vector<std::s
bool no_velocity_buf_defined = false;
- for(unsigned i=0; i<definitions.size(); ++i){
- if(definitions[i] == "TANGENT"){
+ for(const auto & definition : definitions){
+ if(definition == "TANGENT"){
shader->use_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<std::s
AddShaderDefinition(&text, "TESSELATION_EVALUATOR_SHADER");
}
- for(unsigned i=0; i<definitions.size(); ++i){
- AddShaderDefinition(&text, definitions[i]);
+ for(const auto & definition : definitions){
+ AddShaderDefinition(&text, definition);
}
if (GLAD_GL_ARB_sample_shading) {
AddShaderDefinition(&text, "ARB_sample_shading_available");
@@ -367,8 +366,8 @@ void Shaders::Reload(bool force) {
Program& program = programs[i];
if(program.gl_program != UNLOADED_SHADER_ID) {
bool unloaded = false;
- for(int j=0; j<kMaxShaderTypes; ++j){
- if(program.shader_ids[j] >= 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<std::string> &definitions) {
std::string full_path;
full_path = path;
- for(unsigned i=0; i<definitions.size(); ++i){
- full_path += " #" + definitions[i];
+ for(const auto & definition : definitions){
+ full_path += " #" + definition;
}
for (unsigned i=0; i<shaders.size(); ++i){
@@ -659,8 +658,8 @@ int Shaders::returnProgram(std::string name, OptionalShaders optional_shaders) {
}
}
- for(int i=0; i<kMaxShaderTypes; ++i){
- program.shader_ids[i] = MISSING_GEOM_SHADER_ID;
+ for(int & shader_id : program.shader_ids){
+ shader_id = MISSING_GEOM_SHADER_ID;
}
program.shader_ids[_vertex] = returnShader(vertex_path.c_str(), _vertex, definitions);
@@ -1174,15 +1173,15 @@ void Shaders::SetUniformVec3Array(GLint var_id, const vec3* val, int size) {
void Shaders::ResetVRAM()
{
- for(unsigned i=0; i<shaders.size(); ++i){
- shaders[i].gl_shader = UNLOADED_SHADER_ID;
- }
- for(unsigned i=0; i<programs.size(); ++i){
- programs[i].gl_program = UNLOADED_SHADER_ID;
- programs[i].attrib_address_cache.clear();
- programs[i].uniform_address_cache.clear();
- programs[i].uniform_value_cache.clear();
- programs[i].uniform_offset_cache.clear();
+ for(auto & shader : shaders){
+ shader.gl_shader = UNLOADED_SHADER_ID;
+ }
+ for(auto & program : programs){
+ program.gl_program = UNLOADED_SHADER_ID;
+ program.attrib_address_cache.clear();
+ program.uniform_address_cache.clear();
+ program.uniform_value_cache.clear();
+ program.uniform_offset_cache.clear();
}
}
diff --git a/Source/Graphics/simplify.cpp b/Source/Graphics/simplify.cpp
index e14442b0..53da04c6 100644
--- a/Source/Graphics/simplify.cpp
+++ b/Source/Graphics/simplify.cpp
@@ -142,9 +142,9 @@ static void GetTexCoordNumPerVertex(const SimplifyModel *model, std::vector<int>
// 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(); i<len; ++i){
- if(model->vert_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<int>
index += num_tc[i];
}
// Clear num_tc for reuse
- for(int i=0, len=num_tc.size(); i<len; ++i){
- num_tc[i] = 0;
+ for(int & i : num_tc){
+ i = 0;
}
// Record texture indices
std::vector<int> 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(); i<len; ++i){
- if(half_edges[i].twin == NULL){
+ for(auto & half_edge : half_edges){
+ if(half_edge.twin == NULL){
missing_pair = true;
- } else if(half_edges[i].twin->twin == 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<HalfEdge>& half_edges, SimplifyModel& processed_model, vector<glm::mat4>& quadrics_, bool include_tex) {
LOGI << "Calculating edge error..." << std::endl;
- for(int i=0, len=half_edges.size(); i<len; ++i){
- HalfEdge& edge = half_edges[i];
+ for(auto & edge : half_edges){
if(edge.err == UNDEFINED_ERROR){
int edge_tc[2];
if(include_tex) {
@@ -385,13 +384,13 @@ static void CalculateEdgeErrors(vector<HalfEdge>& half_edges, SimplifyModel& pro
static void InitHeap(vector<HalfEdge>& 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(); i<len; ++i){
+ for(auto & half_edge : half_edges){
HalfEdgeNode node;
- node.edge = &half_edges[i];
- half_edges[i].handle = heap.insert(node);
+ node.edge = &half_edge;
+ half_edge.handle = heap.insert(node);
}
- for(int i=0, len=half_edges.size(); i<len; ++i){
- HalfEdge *edge = &half_edges[i];
+ for(auto & half_edge : half_edges){
+ HalfEdge *edge = &half_edge;
vert_edges[edge->vert[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<len; ++i){
- if(vert_parents[processed_model.vert_indices[i]].empty()) {
- processed_model.vert_indices[i] = reverse_vert_parents[processed_model.vert_indices[i]];
+ for(int & vert_indice : processed_model.vert_indices){
+ if(vert_parents[vert_indice].empty()) {
+ vert_indice = reverse_vert_parents[vert_indice];
}
}
- for(int i=0, len=processed_model.tex_indices.size(); i<len; ++i){
- if(tex_parents[processed_model.tex_indices[i]].empty()){
- processed_model.tex_indices[i] = reverse_tex_parents[processed_model.tex_indices[i]];
+ for(int & tex_indice : processed_model.tex_indices){
+ if(tex_parents[tex_indice].empty()){
+ tex_indice = reverse_tex_parents[tex_indice];
}
}
@@ -730,14 +729,14 @@ bool WOLFIRE_SIMPLIFY::SimplifyMorphLOD( const SimplifyModelInput &model_input,
}
vert_parent_vec[curr_lod] = vert_parents;
tex_parent_vec[curr_lod] = tex_parents;
- for(int i=0, len=working_model.vert_indices.size(); i<len; ++i){
- if(vert_parents[working_model.vert_indices[i]].empty()){
- working_model.vert_indices[i] = reverse_vert_parents[working_model.vert_indices[i]];
+ for(int & vert_indice : working_model.vert_indices){
+ if(vert_parents[vert_indice].empty()){
+ vert_indice = reverse_vert_parents[vert_indice];
}
}
- for(int i=0, len=working_model.tex_indices.size(); i<len; ++i){
- if(tex_parents[working_model.tex_indices[i]].empty()){
- working_model.tex_indices[i] = reverse_tex_parents[working_model.tex_indices[i]];
+ for(int & tex_indice : working_model.tex_indices){
+ if(tex_parents[tex_indice].empty()){
+ tex_indice = reverse_tex_parents[tex_indice];
}
}
last_lod_model = working_model;
diff --git a/Source/Graphics/skeleton.cpp b/Source/Graphics/skeleton.cpp
index 8428f909..eafcb849 100644
--- a/Source/Graphics/skeleton.cpp
+++ b/Source/Graphics/skeleton.cpp
@@ -58,9 +58,9 @@ struct SelectedJoint {
};
static std::string LabelFromBone(int bone, const Skeleton::SimpleIKBoneMap &simple_ik_bones, const std::vector<int> &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; i<ik_bone.chain_length; ++i){
if(curr_bone == bone){
@@ -83,10 +83,10 @@ void Skeleton::CreateHinge(const SelectedJoint &selected_joint, const vec3 &forc
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;
}
}
}
@@ -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; i<physics_bones.size(); i++){
- if(!physics_bones[i].bullet_object){
+ for(auto & physics_bone : physics_bones){
+ if(!physics_bone.bullet_object){
continue;
}
- physics_bones[i].bullet_object->SetGravity(true);
+ physics_bone.bullet_object->SetGravity(true);
//physics_bones[i].bullet_object->SetDamping(0.0f);
}
} else {
- for(unsigned i=0; i<physics_bones.size(); i++){
- if(!physics_bones[i].bullet_object){
+ for(auto & physics_bone : physics_bones){
+ if(!physics_bone.bullet_object){
continue;
}
- physics_bones[i].bullet_object->SetGravity(true);
+ physics_bone.bullet_object->SetGravity(true);
//physics_bones[i].bullet_object->SetDamping(1.0f);
}
}
}
void Skeleton::UnlinkFromBulletWorld() {
- for(unsigned i=0; i<physics_bones.size(); i++){
- if(physics_bones[i].bullet_object){
- bullet_world->UnlinkObject(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; i<physics_joints.size(); i++){
- PhysicsJoint &joint = physics_joints[i];
+ for(auto & joint : physics_joints){
if(joint.bt_joint){
bullet_world->UnlinkConstraint(joint.bt_joint);
}
@@ -175,8 +174,8 @@ void Skeleton::UnlinkFromBulletWorld() {
bullet_world->UnlinkConstraint(joint.fixed_joint);
}
}
- for(unsigned i=0; i<null_constraints.size(); i++){
- bullet_world->UnlinkConstraint(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; i<physics_joints.size(); i++){
- PhysicsJoint &joint = physics_joints[i];
+ for(auto & joint : physics_joints){
if(joint.bt_joint){
bullet_world->LinkConstraint(joint.bt_joint);
if(joint.type == FIXED_JOINT){
@@ -208,8 +206,8 @@ void Skeleton::LinkToBulletWorld() {
}
}
num = 0;
- for(unsigned i=0; i<null_constraints.size(); i++){
- bullet_world->LinkConstraint(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<CustomShape> &custom_shapes = *custom_shapes_ptr;
std::vector<int> &num_custom_shapes = *num_custom_shapes_ptr;
- for(int i=0, len=fzx_ref->objects.size(); i<len; ++i){
- const FZXObject &object = fzx_ref->objects[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; i<physics_bones.size(); i++){
- if(physics_bones[i].bullet_object == object) {
- return physics_bones[i].bone;
+ for(auto & physics_bone : physics_bones){
+ if(physics_bone.bullet_object == object) {
+ return physics_bone.bone;
}
}
return -1;
@@ -703,8 +700,7 @@ int Skeleton::Read( const std::string &path, float scale, float mass_scale, cons
// Identify objects with fixed joint to parent
fixed_obj.resize(physics_bones.size(), false);
- for(unsigned i=0; i<data.joints.size(); ++i){
- const JointData& joint = data.joints[i];
+ for(const auto & joint : data.joints){
if(joint.type == _fixed_joint){
int id[2];
id[0] = joint.bone_id[0];
@@ -799,8 +795,7 @@ int Skeleton::Read( const std::string &path, float scale, float mass_scale, cons
for(unsigned i=0; i<physics_bones.size(); ++i){
if(fixed_obj[i] && has_verts_assigned[i]){
PhysicsBone& pbi = physics_bones[i];
- for(unsigned j=0; j<physics_joints.size(); ++j){
- PhysicsJoint& joint = physics_joints[j];
+ for(auto & joint : physics_joints){
int id[2];
id[0] = bo_id[joint.bt_bone[0]];
id[1] = bo_id[joint.bt_bone[1]];
@@ -826,8 +821,7 @@ int Skeleton::Read( const std::string &path, float scale, float mass_scale, cons
for(unsigned i=0; i<physics_bones.size(); ++i){
if(fixed_obj[i] && has_verts_assigned[i]){
PhysicsBone& pbi = physics_bones[i];
- for(unsigned j=0; j<physics_joints.size(); ++j){
- PhysicsJoint& joint = physics_joints[j];
+ for(auto & joint : physics_joints){
if(joint.bt_bone[0] == pbi.bullet_object || joint.bt_bone[1] == pbi.bullet_object) {
DeleteJoint(&joint);
}
@@ -837,16 +831,15 @@ int Skeleton::Read( const std::string &path, float scale, float mass_scale, cons
}
// Remove invisible bones from parent hierarchy as well as physics world
- for(unsigned i=0; i<parents.size(); ++i){
- while(parents[i] != -1 && !has_verts_assigned[parents[i]]){
- parents[i] = parents[parents[i]];
+ for(int & parent : parents){
+ while(parent != -1 && !has_verts_assigned[parent]){
+ parent = parents[parent];
}
}
for(unsigned i=0; i<physics_bones.size(); ++i){
if(!has_verts_assigned[i]){
PhysicsBone& pbi = physics_bones[i];
- for(unsigned j=0; j<physics_joints.size(); ++j){
- PhysicsJoint& joint = physics_joints[j];
+ for(auto & joint : physics_joints){
if(joint.bt_bone[0] == pbi.bullet_object ||
joint.bt_bone[1] == pbi.bullet_object)
{
@@ -884,24 +877,24 @@ void Skeleton::ReduceROM(float how_much) {
bone = parents[bone];
}
}
- for(unsigned i=0; i<physics_joints.size(); i++){
- if(physics_joints[i].type == ROTATION_JOINT && affected[boid[physics_joints[i].bt_bone[0]]] == 1 && affected[boid[physics_joints[i].bt_bone[1]]] == 1){
- float mid = (physics_joints[i].stop_angle[0]+
- physics_joints[i].stop_angle[1])*0.5f;
- physics_joints[i].stop_angle[0] = mix(physics_joints[i].stop_angle[0],mid,how_much);
- physics_joints[i].stop_angle[1] = mix(physics_joints[i].stop_angle[1],mid,how_much);
+ for(auto & physics_joint : physics_joints){
+ if(physics_joint.type == ROTATION_JOINT && affected[boid[physics_joint.bt_bone[0]]] == 1 && affected[boid[physics_joint.bt_bone[1]]] == 1){
+ float mid = (physics_joint.stop_angle[0]+
+ physics_joint.stop_angle[1])*0.5f;
+ physics_joint.stop_angle[0] = mix(physics_joint.stop_angle[0],mid,how_much);
+ physics_joint.stop_angle[1] = mix(physics_joint.stop_angle[1],mid,how_much);
- mid = (physics_joints[i].stop_angle[2]+
- physics_joints[i].stop_angle[3])*0.5f;
- physics_joints[i].stop_angle[2] = mix(physics_joints[i].stop_angle[2],mid,how_much);
- physics_joints[i].stop_angle[3] = mix(physics_joints[i].stop_angle[3],mid,how_much);
+ mid = (physics_joint.stop_angle[2]+
+ physics_joint.stop_angle[3])*0.5f;
+ physics_joint.stop_angle[2] = mix(physics_joint.stop_angle[2],mid,how_much);
+ physics_joint.stop_angle[3] = mix(physics_joint.stop_angle[3],mid,how_much);
- mid = (physics_joints[i].stop_angle[4]+
- physics_joints[i].stop_angle[5])*0.5f;
- physics_joints[i].stop_angle[4] = mix(physics_joints[i].stop_angle[4],mid,how_much);
- physics_joints[i].stop_angle[5] = mix(physics_joints[i].stop_angle[5],mid,how_much);
+ mid = (physics_joint.stop_angle[4]+
+ physics_joint.stop_angle[5])*0.5f;
+ physics_joint.stop_angle[4] = mix(physics_joint.stop_angle[4],mid,how_much);
+ physics_joint.stop_angle[5] = mix(physics_joint.stop_angle[5],mid,how_much);
- ApplyJointRange(&physics_joints[i]);
+ ApplyJointRange(&physics_joint);
}
}
}
@@ -931,13 +924,13 @@ void Skeleton::CreateFixed(const SelectedJoint &selected_joint) {
vec3 Skeleton::GetCenterOfMass() {
vec3 center(0.0f);
float total_mass = 0.0f;
- for(unsigned i=0; i<physics_bones.size(); i++){
- if(!physics_bones[i].bullet_object){
+ for(auto & physics_bone : physics_bones){
+ if(!physics_bone.bullet_object){
continue;
}
- center += physics_bones[i].bullet_object->GetPosition() *
- 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<BoneTransform> &mats){
- for(unsigned i=0; i<physics_joints.size(); ++i){
- PhysicsJoint& joint = physics_joints[i];
+ for(auto & joint : physics_joints){
if(joint.fixed_joint){
BoneTransform a = mats[phys_id[joint.bt_bone[0]]];
a.origin += a.rotation * joint.bt_bone[0]->com_offset;
@@ -1112,14 +1104,13 @@ void Skeleton::RefreshFixedJoints(const std::vector<BoneTransform> &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; i<physics_joints.size(); i++){
- PhysicsJoint &joint = physics_joints[i];
+ for(auto & joint : physics_joints){
if(joint.bt_joint){
bullet_world->RemoveJoint(&joint.bt_joint);
}
@@ -1130,15 +1121,15 @@ void Skeleton::PhysicsDispose() {
physics_joints.clear();
// Remove null constraints
- for(unsigned i=0; i<null_constraints.size(); i++){
- bullet_world->RemoveJoint(&null_constraints[i]);
+ for(auto & null_constraint : null_constraints){
+ bullet_world->RemoveJoint(&null_constraint);
}
null_constraints.clear();
// Remove objects
- for(unsigned i=0; i<physics_bones.size(); i++){
- bullet_world->RemoveObject(&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<BulletObject*> &selected_bullet_bones,
const SelectedJoint & selected_joint )
{
- for(unsigned i=0; i<physics_bones.size(); i++){
- if(physics_bones[i].bone == selected_joint.bones[0]) {
- selected_bullet_bones[0] = physics_bones[i].bullet_object;
+ for(auto & physics_bone : physics_bones){
+ if(physics_bone.bone == selected_joint.bones[0]) {
+ selected_bullet_bones[0] = physics_bone.bullet_object;
}
- if(physics_bones[i].bone == selected_joint.bones[1]) {
- selected_bullet_bones[1] = physics_bones[i].bullet_object;
+ if(physics_bone.bone == selected_joint.bones[1]) {
+ selected_bullet_bones[1] = physics_bone.bullet_object;
}
}
}
@@ -1227,8 +1218,7 @@ void Skeleton::SetGFStrength(PhysicsJoint& joint, float _strength) {
void Skeleton::AddNullConstraints() {
std::map<BulletObject*, std::set<BulletObject*> > connected;
- for(unsigned i=0; i<physics_joints.size(); ++i){
- const PhysicsJoint& pj = physics_joints[i];
+ for(auto & pj : physics_joints){
connected[pj.bt_bone[0]].insert(pj.bt_bone[1]);
connected[pj.bt_bone[1]].insert(pj.bt_bone[0]);
}
@@ -1399,9 +1389,9 @@ void Skeleton::UpdateTwistBones(bool update_transform) {
void Skeleton::CheckForNAN()
{
- for(unsigned i=0; i<physics_bones.size(); i++){
- if(physics_bones[i].bullet_object){
- physics_bones[i].bullet_object->CheckForNAN();
+ 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<groups.size(); ++i){
const std::vector<int> &group = groups[i];
vec3 center_accum(0.0f);
- for(unsigned j=0; j<group.size(); ++j){
- const int vert_index = group[j] * 3;
+ for(int j : group){
+ const int vert_index = j * 3;
center_accum += vec3(hull_model.vertices[vert_index+0],
hull_model.vertices[vert_index+1],
hull_model.vertices[vert_index+2]);
@@ -1534,8 +1524,8 @@ void Skeleton::AlternateHull( const std::string &model_name, const vec3 &old_cen
mat4 mat;
mat.SetTranslationPart(pb.initial_position*-1.0f);
mat = transpose(pb.initial_rotation) * mat;
- for(unsigned j=0; j<group_verts.size(); ++j){
- group_verts[j] = mat*group_verts[j];
+ for(auto & group_vert : group_verts){
+ group_vert = mat*group_vert;
}
pb.col_bullet_object =
diff --git a/Source/Graphics/terrain.cpp b/Source/Graphics/terrain.cpp
index d1b84e7f..246c2d14 100644
--- a/Source/Graphics/terrain.cpp
+++ b/Source/Graphics/terrain.cpp
@@ -99,10 +99,9 @@ void Terrain::Dispose() {
LOGI << "Clearing detail maps" << std::endl;
detail_maps_info.clear();
LOGI << "Clearing detail object surfaces" << std::endl;
- for(std::list<DetailObjectSurface*>::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<DetailObjectSurface*>::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; i<possible_bad_faces.size(); i++){
- if(model->face_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; i<bad_faces.size(); i++){
- model->faces[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; i<terrain_simplified_model.tex_coords2.size(); ++i){
- terrain_simplified_model.tex_coords2[i] *= 2048.0f;
+ for(float & i : terrain_simplified_model.tex_coords2){
+ i *= 2048.0f;
}
}
@@ -617,8 +615,8 @@ void Terrain::Load(const char* name, const std::string& model_override) {
if(!model_override.empty()){
Model &terrain_simplified_model = Models::Instance()->GetModel(model_id);
terrain_simplified_model.LoadObj(model_override, 0);
- for(unsigned i=0; i<terrain_simplified_model.tex_coords2.size(); ++i){
- terrain_simplified_model.tex_coords2[i] *= 2048.0f;
+ for(float & i : terrain_simplified_model.tex_coords2){
+ i *= 2048.0f;
}
}
@@ -1005,12 +1003,11 @@ void Terrain::SetDetailObjectLayers( const std::vector<DetailObjectLayer> &_deta
detail_object_surfaces.resize(detail_object_layers.size());
int counter = 0;
Model &terrain_simplified_model = Models::Instance()->GetModel(model_id);
- for(std::list<DetailObjectSurface*>::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<DetailObjectLayer> &_deta
++counter;
}
if(normal_map_ref.valid()){
- for(std::list<DetailObjectSurface*>::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<len; ++i){
- pixels_[i] = 0;
+ for(unsigned char & pixel : pixels_){
+ pixel = 0;
}
}
diff --git a/Source/Graphics/textures.cpp b/Source/Graphics/textures.cpp
index f6ea0888..c1615046 100644
--- a/Source/Graphics/textures.cpp
+++ b/Source/Graphics/textures.cpp
@@ -349,8 +349,8 @@ void Textures::DrawImGuiDebug() {
Textures::Textures() {
process_pool = new ProcessPool(worker_app_path);
PROFILED_TEXTURE_MUTEX_LOCK
- for(unsigned int i=0; i<_texture_units; i++){
- bound_texture[i]=INVALID_ID;
+ for(unsigned int & i : bound_texture){
+ i=INVALID_ID;
}
m_wrap_t = _default_wrap;
m_wrap_s = _default_wrap;
@@ -467,8 +467,8 @@ void Textures::DisposeTexture(int which, bool free_space) {
LOGI << "Disposed texture " << texture.name << " with gl id " << texture.gl_texture_id << std::endl;
}
- for (unsigned int i = 0; i < texture.sub_textures.size(); i++) {
- delete texture.sub_textures[i].texture_data;
+ for (auto & sub_texture : texture.sub_textures) {
+ delete sub_texture.texture_data;
}
texture.sub_textures.clear();
@@ -824,8 +824,7 @@ void Textures::TextureToVRAM(unsigned int which) {
CHECK_GL_ERROR();
if (!deferred_delete_textures.empty()) {
- for (std::list<GLuint>::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<GLubyte*>::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<Resolution> Config::GetPossibleResolutions() {
if ((mode.h <= desktopDisplayMode.h && mode.w <= desktopDisplayMode.w && std::fabs(resolutionAspect - desktopAspect) < 0.01f)
|| static_cast<FullscreenMode::Mode>(config["fullscreen"].toNumber<int>()) == 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<std::pair<std::string, ConfigVal> > vec(map_.begin(), map_.end());
std::sort(vec.begin(), vec.end(), ConfigValCompare());
- for(unsigned i=0; i<vec.size(); ++i)
+ for(auto & i : vec)
{
- file << vec[i].first << ": " << vec[i].second.data.str() << "\n";
+ file << i.first << ": " << i.second.data.str() << "\n";
}
file.close();
diff --git a/Source/Internal/error.cpp b/Source/Internal/error.cpp
index 2318961d..13e2c7cf 100644
--- a/Source/Internal/error.cpp
+++ b/Source/Internal/error.cpp
@@ -202,8 +202,8 @@ ErrorResponse DisplayError(const char* title, const char* contents, ErrorType ty
bool active_mods = false;
int active_count = 0;
std::vector<ModInstance*> 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 0d42228e..2b9fa093 100644
--- a/Source/Internal/filesystem.cpp
+++ b/Source/Internal/filesystem.cpp
@@ -1115,10 +1115,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<string> write_dir_files;
@@ -1188,16 +1188,12 @@ void ClearCache( bool dry_run )
vector<string> keep_files;
vector<string> remove_files;
- for( vector<string>::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<pair<string,string> >::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;
}
@@ -1206,11 +1202,9 @@ void ClearCache( bool dry_run )
if( found )
{
/* Second pass with exclusion, if there's one match, regret inclusion, exclusion overrides */
- for( vector<pair<string,string> >::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;
}
@@ -1219,17 +1213,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 )
{
@@ -1245,9 +1239,9 @@ void ClearCache( bool dry_run )
{
//Create a set with all unique folder paths
set<string> 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 )
{
@@ -1271,9 +1265,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 )
{
@@ -1283,9 +1277,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<std::string> 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<ModID> ModInstance::GetIDCollisionsWithActiveMods() const {
std::vector<ModInstance*>::iterator modit = ModLoading::Instance().mods.begin();
std::set<const char*, CharLess> 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<ModInstance*>::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<ModInstance::Campaign> ModLoading::GetCampaigns() {
std::vector<ModInstance::Campaign> 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<ModInstance::Campaign> ModLoading::GetCampaigns() {
std::vector<ModInstance*> ModLoading::GetModsMatchingID(std::string id) {
std::vector<ModInstance*> 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<ModInstance*> ModLoading::GetModsMatchingID(std::string id) {
std::vector<ModInstance*> ModLoading::GetSteamModsMatchingID(std::string id) {
std::vector<ModInstance*> 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<ModInstance*> ModLoading::GetSteamModsMatchingID(std::string id) {
std::vector<ModInstance*> ModLoading::GetLocalModsMatchingID(std::string id) {
std::vector<ModInstance*> 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<ModInstance*> ModLoading::GetLocalModsMatchingID(std::string id) {
std::vector<ModInstance*> ModLoading::GetLocalMods() {
std::vector<ModInstance*> 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<ModInstance*> ModLoading::GetLocalMods() {
std::vector<ModInstance*> ModLoading::GetAllMods() {
std::vector<ModInstance*> 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<std::string> 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<std::string> modpaths ) {
missingPaths = currentPaths;
stillPaths = std::vector<std::string>(); //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<ModInstance*>& ModLoading::GetMods() {
const std::vector<ModID> ModLoading::GetModsSid() {
std::vector<ModID> 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<std::string>::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<std::string>::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<ModInstance::ModDependency>::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<std::string>::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<std::string>::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..2e6f84ee 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<NUM_AVERAGED_FRAMES; i++){
- frame[i]=0;
+ for (auto& i : frame) {
+ i = 0;
}
}
diff --git a/Source/Internal/treestructure.cpp b/Source/Internal/treestructure.cpp
index 6e5644c5..cf25e92c 100644
--- a/Source/Internal/treestructure.cpp
+++ b/Source/Internal/treestructure.cpp
@@ -48,8 +48,8 @@ int GetTotalNumChildren(int parent, const std::vector<int> &parents){
int GetNumChildren(int parent, const std::vector<int> &parents){
int num_children = 0;
- for(unsigned i=0; i<parents.size(); ++i){
- if(parents[i] == parent){
+ for(int i : parents){
+ if(i == parent){
++num_children;
}
}
@@ -62,8 +62,8 @@ int GetNumConnections(int parent, const std::vector<int> &parents){
if(parents[parent] != -1){
++num_connections;
}
- for(unsigned i=0; i<parents.size(); ++i){
- if(parents[i] == parent){
+ for(int i : parents){
+ if(i == parent){
++num_connections;
}
}
@@ -145,8 +145,8 @@ std::vector<int> GetChildrenRecursive( int parent, const std::vector<int> &paren
if(parents[i] == parent){
children.push_back(i);
std::vector<int> sub_children = GetChildrenRecursive(i, parents);
- for(unsigned j=0; j<sub_children.size(); ++j){
- children.push_back(sub_children[j]);
+ for(int & j : sub_children){
+ children.push_back(j);
}
}
}
@@ -179,11 +179,11 @@ std::vector<int> FindTreePath( int a, int b, const std::vector<int> &parents )
queue.pop();
std::vector<int> connections = GetConnections(path.back(), parents);
- for(unsigned i=0; i<connections.size(); ++i){
- if(find(path.begin(), path.end(),connections[i]) == path.end()){
+ for(int & connection : connections){
+ if(find(path.begin(), path.end(),connection) == path.end()){
queue.push(path);
- queue.back().push_back(connections[i]);
- if(connections[i] == b){
+ queue.back().push_back(connection);
+ if(connection == b){
return queue.back();
}
}
diff --git a/Source/JSON/jsoncpp.cpp b/Source/JSON/jsoncpp.cpp
index ae771078..7c6069bf 100644
--- a/Source/JSON/jsoncpp.cpp
+++ b/Source/JSON/jsoncpp.cpp
@@ -968,10 +968,7 @@ std::string Reader::getFormatedErrorMessages() const {
std::string Reader::getFormattedErrorMessages() const {
std::string formattedMessage;
- for (Errors::const_iterator itError = errors_.begin();
- itError != errors_.end();
- ++itError) {
- const ErrorInfo& error = *itError;
+ for (const auto & error : errors_) {
formattedMessage +=
"* " + getLocationLineAndColumn(error.token_.start_) + "\n";
formattedMessage += " " + error.message_ + "\n";
@@ -1894,10 +1891,7 @@ std::string OurReader::getLocationLineAndColumn(Location location) const {
std::string OurReader::getFormattedErrorMessages() const {
std::string formattedMessage;
- for (Errors::const_iterator itError = errors_.begin();
- itError != errors_.end();
- ++itError) {
- const ErrorInfo& error = *itError;
+ for (const auto & error : errors_) {
formattedMessage +=
"* " + getLocationLineAndColumn(error.token_.start_) + "\n";
formattedMessage += " " + error.message_ + "\n";
@@ -3695,8 +3689,7 @@ void Path::invalidPath(const std::string& /*path*/, int /*location*/) {
const Value& Path::resolve(const Value& root) 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_)) {
// 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(); i<len; ++i){
- const FZXObject &object = ref->objects[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; k<num_key_words; ++k){
- bool word_match = (strcmp(key_words[k], sub_str_buf.c_str())==0);
+ for(auto & key_word : key_words){
+ bool word_match = (strcmp(key_word, sub_str_buf.c_str())==0);
if(word_match){
- LOGI << "Token found: " << key_words[k] << std::endl;
+ LOGI << "Token found: " << key_word << std::endl;
match = true;
}
}
diff --git a/Source/Main/engine.cpp b/Source/Main/engine.cpp
index cb4e36bc..03811c27 100644
--- a/Source/Main/engine.cpp
+++ b/Source/Main/engine.cpp
@@ -623,8 +623,8 @@ void Engine::Dispose() {
if(scriptable_menu_)
delete scriptable_menu_;
- for (int i = 0; i < kNumTextAtlas; i++) {
- g_text_atlas[i].Dispose();
+ for (auto & g_text_atla : g_text_atlas) {
+ g_text_atla.Dispose();
}
Models::Instance()->Dispose();
ActiveCameras::Get()->SetCameraObject(NULL);
@@ -917,9 +917,9 @@ void Engine::UpdateControls(float timestep, bool loading_screen) {
std::vector<Object*> 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<vec3>& 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<vec3>& 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<len; ++i){
+ for(auto & new_poly_vert : new_poly_verts){
for(int j=0; j<3; ++j){
- poly_bounds_min[j] = min(poly_bounds_min[j], new_poly_verts[i][j]);
- poly_bounds_max[j] = max(poly_bounds_max[j], new_poly_verts[i][j]);
+ poly_bounds_min[j] = min(poly_bounds_min[j], new_poly_vert[j]);
+ poly_bounds_max[j] = max(poly_bounds_max[j], new_poly_vert[j]);
}
}
int span_top = (int)ceilf(poly_bounds_max[1]/field.voxel_size);
@@ -1195,8 +1193,7 @@ static void RasterizeTrisToVoxelField(const std::vector<vec3>& tri_verts, VoxelF
}
// Merge overlapping voxel spans
- for(size_t span_index=0, len=field.spans.size(); span_index<len; ++span_index){
- std::list<VoxelSpan>& span_list = field.spans[span_index];
+ for(auto & span_list : field.spans){
span_list.sort(VoxelSpanHeightSort);
for(std::list<VoxelSpan>::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<int>& tris = tlr[bullet_object];
- for(unsigned tri_index=0; tri_index<tris.size(); ++tri_index){
+ for(int tri : tris){
vec3 vert[3];
- int face_index = tris[tri_index]*3;
+ int face_index = tri*3;
for(int j=0; j<3; ++j){
int vert_index = model->faces[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<VoxelSpan>& empty_span_list = empty_box_spans[column_index];
span_list.sort(VoxelSpanHeightSort);
VoxelSpan* prev_span = NULL;
- for(std::list<VoxelSpan>::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<VoxelSpan>& span_list = cropped_voxel_field_spans[column_index];
std::list<VoxelSpan>& empty_span_list = empty_field_spans[column_index];
VoxelSpan* prev_span = NULL;
- for(std::list<VoxelSpan>::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<VoxelSpan>& span_list = empty_field_spans[column_index];
- for(std::list<VoxelSpan>::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(); i<len; ++i) {
- MovementObject* mo = (MovementObject*)scenegraph_->movement_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<ShadowCacheObjectLightBounds>::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<ShadowCacheObjectLightBounds>::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<ShadowCacheObjectLightBounds>::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<ShadowCacheObjectLightBounds>::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(); i<len; ++i){
- EnvObject* eo = scenegraph->visible_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(); i<len; ++i){
- EnvObject* eo = scenegraph->visible_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<TextureRef> textures;
- for(size_t i=0, len=scenegraph_->objects_.size(); i<len; ++i){
- Object* obj = scenegraph_->objects_[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(); i<len; ++i){
- Object* obj = scenegraph_->objects_[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(); i<len; ++i){
+ for(auto & light_probe : scenegraph_->light_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<len; ++span_index){
std::list<VoxelSpan>& span_list = g_voxel_field.spans[span_index];
- for(std::list<VoxelSpan>::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(); i<len; ++i){
- lvo = scenegraph_->light_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(); i<len; ++i){
- Object* obj = scenegraph_->objects_[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<LevelAssetPreloadParser::Asset> &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(); i<len; ++i){
- Object* obj = scenegraph_->objects_[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<Collision>::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<Collision>::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<Collision> *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<uint16_t>::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<EnvObject*>::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<Object*>* 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<EnvObject*>::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; i<movement_objects_.size(); ++i){
- MovementObject* mo = (MovementObject*)movement_objects_[i];
+ for(auto & movement_object : movement_objects_){
+ MovementObject* mo = (MovementObject*)movement_object;
mo->rigged_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; i<movement_objects_.size(); ++i){
- MovementObject* mo = (MovementObject*)movement_objects_[i];
+ for(auto & movement_object : movement_objects_){
+ MovementObject* mo = (MovementObject*)movement_object;
const btCollisionObject* bone_col = mo->rigged_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<MovementObject*> 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<uint16_t>::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<std::string, int>& preload_shaders,
}
UpdateShaderSuffix(this, draw_type);
- for(std::map<std::string, int>::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<std::string, int>::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..45267242 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 & entry : result.entries)
+ entry=-entry;
return result;
}
diff --git a/Source/Memory/stack_allocator.cpp b/Source/Memory/stack_allocator.cpp
index 6e5b9142..1a46ffc4 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 (auto & 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 (auto & 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; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_FILE_PATH: {
std::string type_file;
diff --git a/Source/Objects/decalobject.cpp b/Source/Objects/decalobject.cpp
index 256aedac..9f9f2190 100644
--- a/Source/Objects/decalobject.cpp
+++ b/Source/Objects/decalobject.cpp
@@ -143,8 +143,7 @@ void DecalObject::GetDesc(EntityDescription &desc) const {
bool DecalObject::SetFromDesc( const EntityDescription& desc ) {
bool ret = Object::SetFromDesc(desc);
if( ret ) {
- for(unsigned i=0; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_FILE_PATH: {
std::string type_file;
diff --git a/Source/Objects/dynamiclightobject.cpp b/Source/Objects/dynamiclightobject.cpp
index 5c384ab9..406fc28f 100644
--- a/Source/Objects/dynamiclightobject.cpp
+++ b/Source/Objects/dynamiclightobject.cpp
@@ -116,8 +116,7 @@ bool DynamicLightObject::SetFromDesc( const EntityDescription& desc ) {
LOG_ASSERT(light_id_ == -1);
bool ret = Object::SetFromDesc(desc);
if(ret) {
- for(unsigned i=0; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_COLOR: {
memread(color.entries, sizeof(float), 3, field.data);
diff --git a/Source/Objects/envobject.cpp b/Source/Objects/envobject.cpp
index e29e000f..d188cf6b 100644
--- a/Source/Objects/envobject.cpp
+++ b/Source/Objects/envobject.cpp
@@ -128,16 +128,14 @@ static void UpdateDetailObjectSurfaces(EnvObject::DOSList *detail_object_surface
int model_id)
{
//TODO: Make sure we aren't duplicating code from Terrain.cpp
- for(int i=0, len=detail_object_surfaces->size(); i<len; ++i){
- delete detail_object_surfaces->at(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<len; ++i){
- delete detail_object_surfaces[i];
+ for(auto & detail_object_surface : detail_object_surfaces){
+ delete detail_object_surface;
}
}
@@ -658,8 +656,7 @@ void EnvObject::DrawInstances(EnvObject** instance_array, int num_instances, con
} else {
std::vector<mat4> light_volume_matrix;
std::vector<mat4> light_volume_matrix_inverse;
- for(int i=0, len=scenegraph_->light_volume_objects_.size(); i<len; ++i){
- Object* obj = scenegraph_->light_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<vec3> &points, const Model &model, const Image
vec3 verts[3];
int face_index = 0;
int vert_index;
- for(unsigned i=0; i<triangle_area.size(); ++i){
+ for(float & i : triangle_area){
for(unsigned j=0; j<3; ++j){
vert_index = model.faces[face_index+j]*3;
verts[j] = vec3(model.vertices[vert_index+0],
model.vertices[vert_index+1],
model.vertices[vert_index+2]);
}
- triangle_area[i] = length(cross(verts[2]-verts[0], verts[1]-verts[0]))*0.5f;
- total_triangle_area += triangle_area[i];
+ i = length(cross(verts[2]-verts[0], verts[1]-verts[0]))*0.5f;
+ total_triangle_area += i;
face_index += 3;
}
}
@@ -1070,8 +1066,8 @@ void CreatePointCloud(std::vector<vec3> &points, const Model &model, const Image
}
vec3 center;
- for(unsigned i=0; i<temp_points.size(); ++i){
- center += temp_points[i];
+ for(auto & temp_point : temp_points){
+ center += temp_point;
}
center /= (float)temp_points.size();
@@ -1816,8 +1812,7 @@ void EnvObject::CreateLeaf(vec3 pos, vec3 vel, int iterations) {
bool EnvObject::SetFromDesc( const EntityDescription& desc ) {
bool ret = Object::SetFromDesc(desc);
if( ret ) {
- for(unsigned i=0; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_FILE_PATH: {
std::string type_file;
@@ -1855,15 +1850,15 @@ void EnvObject::ReceiveObjectMessageVAList( OBJECT_MSG::Type type, va_list args
case OBJECT_MSG::SET_COLOR: {
//vec3 old_color = color_tint_component_.temp_tint();
color_tint_component_.ReceiveObjectMessageVAList(type, args);
- for(int i=0, len=detail_object_surfaces.size(); i<len; ++i){
- detail_object_surfaces[i]->SetColorTint(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(); i<len; ++i){
- detail_object_surfaces[i]->SetOverbright(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<AttachedEnvObject>& aeo, std::vector<char> &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<kMaxBoneConnects; ++j){
- const BoneConnect& bone_connect = attached_env_object.bone_connects[j];
+ for(const auto & bone_connect : attached_env_object.bone_connects){
memwrite(&bone_connect.bone_id, sizeof(bone_connect.bone_id), 1, data);
memwrite(&bone_connect.num_connections, sizeof(bone_connect.num_connections), 1, data);
memwrite(&bone_connect.rel_mat, sizeof(bone_connect.rel_mat), 1, data);
@@ -50,8 +49,7 @@ void Deserialize(const std::vector<char> &data, std::vector<AttachedEnvObject>&
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<kMaxBoneConnects; ++j){
- const BoneConnect& bone_connect = attached_env_object.bone_connects[j];
+ for(const auto & bone_connect : attached_env_object.bone_connects){
memread((void*)&bone_connect.bone_id, sizeof(bone_connect.bone_id), 1, data, index);
memread((void*)&bone_connect.num_connections, sizeof(bone_connect.num_connections), 1, data, index);
memread((void*)&bone_connect.rel_mat, sizeof(bone_connect.rel_mat), 1, data, index);
diff --git a/Source/Objects/group.cpp b/Source/Objects/group.cpp
index 120fe644..c655ff16 100644
--- a/Source/Objects/group.cpp
+++ b/Source/Objects/group.cpp
@@ -67,21 +67,21 @@ void Group::GetChildren(std::vector<Object*>* ret_children) {
}
void Group::GetBottomUpCompleteChildren(std::vector<Object*>* ret_children) {
- for(int i=0, len=children.size(); i<len; ++i){
- Object *obj = children[i].direct_ptr;
+ for(auto & i : children){
+ Object *obj = i.direct_ptr;
obj->GetBottomUpCompleteChildren(ret_children);
ret_children->push_back(obj);
}
}
void Group::GetTopDownCompleteChildren(std::vector<Object*>* ret_children) {
- for(int i=0, len=children.size(); i<len; ++i){
- Object *obj = children[i].direct_ptr;
+ for(auto & i : children){
+ Object *obj = i.direct_ptr;
ret_children->push_back(obj);
}
- for(int i=0, len=children.size(); i<len; ++i){
- Object *obj = children[i].direct_ptr;
+ for(auto & i : children){
+ Object *obj = i.direct_ptr;
obj->GetTopDownCompleteChildren(ret_children);
}
}
@@ -99,19 +99,16 @@ void Group::ChildLost(Object *obj){
void Group::FinalizeLoadedConnections() {
Object::FinalizeLoadedConnections();
- for(int i=0, len=children.size(); i<len; ++i ){
- children[i].direct_ptr->ReceiveObjectMessage(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();
- i<len;
- ++i)
+ for (auto new_desc : desc.children)
{
- EntityDescription new_desc = desc.children[i];
Object* obj = CreateObjectFromDesc(new_desc);
if(obj){
obj->SetParent(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(); i<len; ++i){
- Object* obj = children[i].direct_ptr;
+ for(const auto & i : children){
+ Object* obj = i.direct_ptr;
if(obj){
if(obj == this){
FatalError("Error", "Group %d: GetDesc() including copy of itself", GetID());
@@ -147,8 +144,8 @@ void Group::GetDesc(EntityDescription &desc) const {
}
void Group::InitRelMats() {
- for(int i=0, len=children.size(); i<len; ++i){
- Object* obj = children[i].direct_ptr;
+ for(auto & i : children){
+ Object* obj = i.direct_ptr;
if(obj && (obj->GetType() == _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(); i<len; ++i){
- Child& child = children[i];
- Object* obj = children[i].direct_ptr;
+ for(auto & i : children){
+ Child& child = i;
+ Object* obj = i.direct_ptr;
if(obj){
child.rel_rotation = invert(GetRotation()) * obj->GetRotation();
child.rel_translation = (invert(GetRotation()) * ((obj->GetTranslation() - translation_))/scale_);
@@ -172,8 +169,8 @@ void Group::InitShape() {
return;
}
- for(int i=0, len=children.size(); i<len; ++i){
- Object* obj = children[i].direct_ptr;
+ for(auto & i : children){
+ Object* obj = i.direct_ptr;
if(obj && (obj->GetType() == _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(); i<len; ++i){
+ for(auto & i : children){
if(num_points <= MAX_POINTS-8){
- Object* obj = children[i].direct_ptr;
+ Object* obj = i.direct_ptr;
if(obj){
//int index = 0;
for(int j=0; j<8; ++j){
@@ -235,8 +232,7 @@ void Group::PreDrawFrame(float curr_game_time) {
PropagateTransformsDown(false);
}
- for(int i=0, len=children.size(); i<len; ++i){
- Child& child = children[i];
+ for(auto & child : children){
Object* obj = child.direct_ptr;
if(obj){
obj->PreDrawFrame(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(); i<len; ++i){
- Child& child = children[i];
+ for(auto & child : children){
Object* obj = child.direct_ptr;
if(obj){
obj->SetTranslationRotationFast(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(); i<len; ++i){
- Child& child = children[i];
+ for(auto & child : children){
Object* obj = child.direct_ptr;
if(obj){
obj->SetScale((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(); i<len; ++i){
- Child& child = children[i];
+ for(auto & child : children){
Object* obj = child.direct_ptr;
if(obj){
obj->PreDrawCamera(curr_game_time);
@@ -307,8 +300,8 @@ void Group::ChildMoved(Object::MoveType type) {
}
void Group::UpdateParentHierarchy() {
- for(int i=0, len=children.size(); i<len; ++i){
- children[i].direct_ptr->UpdateParentHierarchy();
+ 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(); i<len; ++i){
- Child& child = children[i];
+ for(auto & child : children){
Object* obj = child.direct_ptr;
if(obj){
obj->SetEnabled(val);
@@ -333,8 +325,7 @@ void Group::SetEnabled(bool val) {
}
void Group::HandleTransformationOccured() {
- for(int i=0, len=children.size(); i<len; ++i){
- Child& child = children[i];
+ for(auto & child : children){
Object* obj = child.direct_ptr;
if(obj){
obj->HandleTransformationOccurred();
@@ -361,8 +352,8 @@ void Group::ReceiveObjectMessageVAList( OBJECT_MSG::Type type, va_list args ) {
}
void Group::RemapReferences(std::map<int,int> id_map) {
- for(int i=0, len=children.size(); i<len; ++i){
- children[i].direct_ptr->RemapReferences(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<int> 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; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_FILE_PATH: {
std::string type_file;
@@ -643,8 +642,8 @@ CScriptArray* Hotspot::ASGetConnectedObjects() {
CScriptArray* array = CScriptArray::Create(arrayType);
array->Reserve(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<ItemObjectScriptReader*> to_invalidate;
- for(std::list<ItemObjectScriptReader*>::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<ItemObjectScriptReader*>::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<ItemObjectScriptReader*>::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<ItemObjectScriptReader*>::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<ItemObjectScriptReader*>::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<ItemObjectScriptReader*>::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<ItemObjectScriptReader*>::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<mat4> light_volume_matrix;
std::vector<mat4> light_volume_matrix_inverse;
- for(int i=0, len=scenegraph_->light_volume_objects_.size(); i<len; ++i){
- Object* obj = scenegraph_->light_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<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_FILE_PATH: {
std::string type_file;
diff --git a/Source/Objects/lightprobeobject.cpp b/Source/Objects/lightprobeobject.cpp
index 506e13fa..ec92c70b 100644
--- a/Source/Objects/lightprobeobject.cpp
+++ b/Source/Objects/lightprobeobject.cpp
@@ -93,8 +93,7 @@ bool LightProbeObject::SetFromDesc( const EntityDescription& desc ) {
LOG_ASSERT(!stored_coefficients);
bool ret = Object::SetFromDesc(desc);
if( ret ) {
- for(unsigned i=0; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_NEGATIVE_LIGHT_PROBE: {
int negative_int;
diff --git a/Source/Objects/movementobject.cpp b/Source/Objects/movementobject.cpp
index 97d6eed8..17eee409 100644
--- a/Source/Objects/movementobject.cpp
+++ b/Source/Objects/movementobject.cpp
@@ -121,10 +121,10 @@ void MovementObject::GetChildren(std::vector<Object*>* ret_children) {
std::vector<AttachedEnvObject> 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(); i<len; ++i){
- Object* obj = attached_env_objects[i].direct_ptr;
+ for(auto & attached_env_object : attached_env_objects){
+ Object* obj = attached_env_object.direct_ptr;
if(obj){
- ret_children->push_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<Object*>* ret_child
std::vector<AttachedEnvObject> 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(); i<len; ++i){
- Object* obj = attached_env_objects[i].direct_ptr;
+ for(auto & attached_env_object : attached_env_objects){
+ Object* obj = attached_env_object.direct_ptr;
if(obj){
obj->GetBottomUpCompleteChildren(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(); i<len; ++i){
- if(rigged_object_->children[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(); i<len; ++i){
- AttachedEnvObject& child = rigged_object_->children[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_index<num_queries; ++query_index){
- OcclusionQuery* query = &occlusion_queries[query_index];
+ for(auto & occlusion_querie : occlusion_queries){
+ OcclusionQuery* query = &occlusion_querie;
if(!query->in_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<ItemObjectScriptReader> &ic = item_connections;
- for(std::list<ItemObjectScriptReader>::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; i<palette.size(); ++i){
- for(unsigned j=0; j<old_palette.size(); ++j){
- if(palette[i].label == old_palette[j].label){
- palette[i].color = old_palette[j].color;
+ for(auto & i : palette){
+ for(auto & j : old_palette){
+ if(i.label == j.label){
+ i.color = j.color;
}
}
}
@@ -1499,10 +1489,8 @@ void MovementObject::Reset(){
as_context->ResetGlobals();
as_context->CallScriptFunction(as_funcs.set_parameters);
as_context->CallScriptFunction(as_funcs.post_reset);
- for(std::list<ItemObjectScriptReader>::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_connection_vec.size(); ++i){
- ItemConnection &item_connection = item_connection_vec[i];
-
+ for(auto & item_connection : item_connection_vec){
if( do_connection_finalization_remap ) {
if( connection_finalization_remap.find(item_connection.id) != connection_finalization_remap.end() ) {
item_connection.id = connection_finalization_remap[item_connection.id];
@@ -4544,10 +4530,8 @@ void MovementObject::GetDesc(EntityDescription &desc) const {
desc.AddIntVec(EDF_CONNECTIONS, connections);
std::vector<ItemConnectionData> item_connections_vec;
- for(std::list<ItemObjectScriptReader>::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(); i<len; ++i){
- Object* env_obj = rigged_object_->children[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<len; ++i){
- const GLuint val = occlusion_queries[i].id;
+ for(auto & occlusion_querie : occlusion_queries){
+ const GLuint val = occlusion_querie.id;
glDeleteQueries(1, &val);
}
occlusion_queries.clear();
@@ -4747,8 +4731,7 @@ void MovementObject::RemovePhysicsShapes() {
bool MovementObject::SetFromDesc( const EntityDescription &desc ) {
bool ret = Object::SetFromDesc(desc);
if( ret ) {
- for(unsigned i=0; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_FILE_PATH: {
std::string type_file;
@@ -4784,16 +4767,16 @@ bool MovementObject::SetFromDesc( const EntityDescription &desc ) {
case EDF_ITEM_CONNECTIONS:{
std::vector<ItemConnectionData> item_connections;
field.ReadItemConnectionDataVec(&item_connections);
- for(int i=0, len=item_connections.size(); i<len; ++i){
- if( item_connections[i].id != -1 ) {
+ for(auto & i : item_connections){
+ if( i.id != -1 ) {
ItemConnection item_connection;
- item_connection.id = item_connections[i].id;
- item_connection.mirrored = item_connections[i].mirrored != 0;
- item_connection.attachment_type = (AttachmentType)item_connections[i].attachment_type;
- if(!item_connections[i].attachment_str.empty()){
- item_connection.attachment_ref = Engine::Instance()->GetAssetManager()->LoadSync<Attachment>(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<Attachment>(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<AttachedEnvObject> attached_env_objects;
Deserialize(env_object_attach_data, attached_env_objects);
- for (int i=0, len=attached_env_objects.size(); i<len; ++i) {
- attached_env_objects[i].direct_ptr = NULL;
+ for (auto & attached_env_object : attached_env_objects) {
+ attached_env_object.direct_ptr = NULL;
}
for (int i=0, len=desc.children.size(); i<len; ++i) {
EntityDescription new_desc = desc.children[i];
@@ -4976,10 +4959,9 @@ float AttackHistory::Check( const std::string &str ) {
}
if(num != 0){
float total = 0;
- for(InnerTransitionMap::const_iterator iter = itm.begin();
- iter != itm.end(); ++iter)
+ for(const auto & iter : itm)
{
- total += iter->second;
+ 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<connections.size(); ++i) {
- if(connections[i].other_object_id == other_id) {
+ for(auto & connection : connections) {
+ if(connection.other_object_id == other_id) {
return false;
}
}
@@ -111,8 +111,8 @@ bool NavmeshConnectionObject::Disconnect( Object& other, bool checking_other ) {
}
void NavmeshConnectionObject::GetConnectionIDs(std::vector<int>* 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; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_NAV_MESH_CONNECTIONS:
field.ReadNavMeshConnectionDataVec(&connections);
@@ -328,8 +327,8 @@ void NavmeshConnectionObject::FinalizeLoadedConnections() {
}
// Make sure all connections are symmetric
- for(int i=0, len=connections.size(); i<len; ++i){
- Object* obj = scenegraph_->GetObjectFromID(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<int,int> id_map) {
- for(int i=0, len=connections.size(); i<len; ++i){
- if( id_map.find(connections[i].other_object_id) != id_map.end() ) {
- connections[i].other_object_id = id_map[connections[i].other_object_id];
+ for(auto & connection : connections){
+ if( id_map.find(connection.other_object_id) != id_map.end() ) {
+ connection.other_object_id = id_map[connection.other_object_id];
} else {
//The remapped id could belong to this, in which case it is valid
bool is_this = false;
- for(std::map<int,int>::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; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_ID: {
int id;
@@ -374,25 +373,25 @@ void Object::Moved(Object::MoveType type) {
}
void Object::FinalizeLoadedConnections() {
- for(size_t i = 0; i < unfinalized_connected_to.size(); ++i) {
- Object* object = scenegraph_->GetObjectFromID(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<connection_ids.size(); ++i){ // Disconnect if we're already connected
- if(connection_ids[i] == other_id){
+ for(int connection_id : connection_ids){ // Disconnect if we're already connected
+ if(connection_id == other_id){
Disconnect(other, checking_other);
}
}
@@ -103,8 +103,8 @@ bool PathPointObject::Disconnect( Object& other, bool checking_other ) {
}
void PathPointObject::GetConnectionIDs(std::vector<int>* 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; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_CONNECTIONS:
field.ReadIntVec(&connection_ids);
@@ -174,28 +173,28 @@ void PathPointObject::Draw() {
scenegraph_->map_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; i<connection_ids.size(); ++i){
- Object* obj = scenegraph_->GetObjectFromID(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<int,int> 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<int,int>::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; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_FILE_PATH: {
std::string path;
@@ -230,8 +229,7 @@ void PlaceholderObject::SetSpecialType(PlaceholderObject::PlaceholderObjectType
}
bool PlaceholderObject::Initialize() {
- for(int i=0, len=preview_objects_.size(); i<len; ++i){
- Object* obj = preview_objects_[i];
+ for(auto obj : preview_objects_){
obj->scenegraph_ = 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; i<desc.fields.size(); ++i){
- const EntityDescriptionField& field = desc.fields[i];
+ for(const auto & field : desc.fields){
switch(field.type){
case EDF_GI_COEFFICIENTS: {
memcpy(avg_color, &field.data[0], kLightProbeNumCoeffs * sizeof(float));
diff --git a/Source/Objects/riggedobject.cpp b/Source/Objects/riggedobject.cpp
index 90800644..4e3857ed 100644
--- a/Source/Objects/riggedobject.cpp
+++ b/Source/Objects/riggedobject.cpp
@@ -179,8 +179,8 @@ RiggedObject::RiggedObject() :
palette_colors.resize(max_palette_elements, vec3(1.0f));
palette_colors_srgb.resize(max_palette_elements, vec3(1.0f));
- for(int i=0; i<4; ++i){
- model_id[i] = -1;
+ for(int & i : model_id){
+ i = -1;
}
anim_update_period = 2;
@@ -205,11 +205,11 @@ RiggedObject::~RiggedObject() {
free(simd_bone_mats);
#endif
#endif
- for(int i=0; i<4; ++i){
- Models::Instance()->DeleteModel(model_id[i]);
+ for(int i : model_id){
+ Models::Instance()->DeleteModel(i);
}
- for(unsigned i=0; i<morph_targets.size(); ++i){
- morph_targets[i].Dispose();
+ for(auto & morph_target : morph_targets){
+ morph_target.Dispose();
}
// TODO: why do we get a black screen when returning to the main menu on Mac
@@ -446,14 +446,13 @@ void RiggedObject::PreDrawFrame(float curr_game_time) {
}
else {
int total_connections = 0;
- for (unsigned j = 0; j < kMaxBoneConnects; ++j) {
- total_connections += attached_env_object.bone_connects[j].num_connections;
+ for (auto & bone_connect : attached_env_object.bone_connects) {
+ total_connections += bone_connect.num_connections;
}
mat4 total_mat(0.0f);
- for (unsigned j = 0; j < kMaxBoneConnects; ++j) {
- const BoneConnect &bone_connect = attached_env_object.bone_connects[j];
- if (bone_connect.num_connections) {
+ for (const auto & bone_connect : attached_env_object.bone_connects) {
+ if (bone_connect.num_connections) {
mat4 mat = display_bone_transforms[bone_connect.bone_id].GetMat4() * bone_connect.rel_mat;
total_mat += mat * ((float)bone_connect.num_connections / (float)total_connections);
}
@@ -496,11 +495,11 @@ void RiggedObject::StoreNetworkBones() {
void RiggedObject::StoreNetworkMorphTargets() {
// first check if not present
if (morph_targets.size() != network_morphs.size()) {
- for (uint32_t i = 0; i < morph_targets.size(); i++) {
+ for (auto & morph_target : morph_targets) {
bool present = false;
- for (uint32_t j = 0; j < network_morphs.size(); j++) {
- if (morph_targets[i].name == network_morphs[j].name) {
+ for (auto & network_morph : network_morphs) {
+ if (morph_target.name == network_morph.name) {
present = true;
break;
}
@@ -509,31 +508,31 @@ void RiggedObject::StoreNetworkMorphTargets() {
if (present == false) {
MorphTargetStateStorage missing_morph;
- missing_morph.disp_weight = morph_targets[i].disp_weight;
- missing_morph.name = morph_targets[i].name;
+ missing_morph.disp_weight = morph_target.disp_weight;
+ missing_morph.name = morph_target.name;
missing_morph.dirty = true;
- missing_morph.mod_weight = morph_targets[i].mod_weight;
+ missing_morph.mod_weight = morph_target.mod_weight;
network_morphs.push_back(missing_morph);
}
}
}
- for (uint32_t i = 0; i < morph_targets.size(); i++) {
- for (uint32_t j = 0; j < network_morphs.size(); j++) {
- if (morph_targets[i].name == network_morphs[j].name) {
- float a = morph_targets[i].disp_weight;
- float b = network_morphs[j].disp_weight;
+ for (auto & morph_target : morph_targets) {
+ for (auto & network_morph : network_morphs) {
+ if (morph_target.name == network_morph.name) {
+ float a = morph_target.disp_weight;
+ float b = network_morph.disp_weight;
- float c = network_morphs[j].mod_weight;
- float d = morph_targets[i].mod_weight;
+ float c = network_morph.mod_weight;
+ float d = morph_target.mod_weight;
if (std::abs(a - b) > 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<vec3> 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<mat4> light_volume_matrix;
std::vector<mat4> light_volume_matrix_inverse;
- for(int i=0, len=scenegraph_->light_volume_objects_.size(); i<len; ++i){
- Object* obj = scenegraph_->light_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<len; ++i){
- vel[i] = 0.0f;
+ for(float & i : vel){
+ i = 0.0f;
}
vel_vbo.SetHint(model_num_verts*3*sizeof(GLfloat),kVBODynamic);
vel_vbo.Fill(model_num_verts*3*sizeof(GLfloat), &vel[0]);
@@ -1048,15 +1046,13 @@ bool RiggedObject::DrawBoneConnectUI(Object* objects[], int num_obj_ids, IMUICon
Object* obj = objects[obj_id_iter];
// Check if we already have a connection between this object and this character
bool already_attached = false;
- for(unsigned j=0; j<children.size(); ++j){
- AttachedEnvObject& attached_env_object = children[j];
+ for(auto & attached_env_object : children){
if(attached_env_object.direct_ptr == obj){
// If this object is already attached to the selected bone, increment the number of connections
attached_env_object.bone_connection_dirty = true;
already_attached = true;
bool already_attached_to_bone = false;
- for(unsigned k=0; k<kMaxBoneConnects; ++k){
- BoneConnect& bone_connect = attached_env_object.bone_connects[k];
+ for(auto & bone_connect : attached_env_object.bone_connects){
if(bone_connect.bone_id == (int)i){
++bone_connect.num_connections;
already_attached_to_bone = true;
@@ -1065,8 +1061,7 @@ bool RiggedObject::DrawBoneConnectUI(Object* objects[], int num_obj_ids, IMUICon
}
// If this object is not already attached to the bone, try to attach it with a spare slot
if(!already_attached_to_bone){
- for(unsigned k=0; k<kMaxBoneConnects; ++k){
- BoneConnect& bone_connect = attached_env_object.bone_connects[k];
+ for(auto & bone_connect : attached_env_object.bone_connects){
if(bone_connect.num_connections == 0){
bone_connect.bone_id = i;
bone_connect.num_connections = 1;
@@ -1107,8 +1102,7 @@ bool RiggedObject::DrawBoneConnectUI(Object* objects[], int num_obj_ids, IMUICon
AttachedEnvObject& attached_obj = children[j];
if(attached_obj.direct_ptr == obj){
int total_connections = 0; //NOTE(David): Number of connections remaining between object and character
- for(unsigned k=0; k<kMaxBoneConnects; ++k){
- BoneConnect& bone_connect = attached_obj.bone_connects[k];
+ for(auto & bone_connect : attached_obj.bone_connects){
if(bone_connect.bone_id == (int)i && bone_connect.num_connections > 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; i<children.size(); ++i){
- const AttachedEnvObject& attached_env_object = children[i];
- Object* obj = children[i].direct_ptr;
+ for(auto & i : children){
+ const AttachedEnvObject& attached_env_object = i;
+ Object* obj = i.direct_ptr;
if(obj && obj->Selected()){
- for(unsigned j=0; j<kMaxBoneConnects; ++j){
- const BoneConnect& bone_connect = attached_env_object.bone_connects[j];
+ for(const auto & bone_connect : attached_env_object.bone_connects){
if(bone_connect.num_connections > 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_targets.size(); ++i){
- morph_targets[i].UpdateForInterpolation();
+ for(auto & morph_target : morph_targets){
+ morph_target.UpdateForInterpolation();
}
if(!animated){
PROFILER_ZONE(g_profiler_ctx, "Update ragdoll animation");
@@ -1322,11 +1315,10 @@ void RiggedObject::Update(float timestep) {
skeleton_.RefreshFixedJoints(animation_frame_bone_matrices);
// Apply morph weights from animation output
std::map<std::string, MorphTarget*> morph_target_names;
- for(unsigned i=0; i<morph_targets.size(); ++i){
- morph_target_names[morph_targets[i].name] = &morph_targets[i];
+ for(auto & morph_target : morph_targets){
+ morph_target_names[morph_target.name] = &morph_target;
}
- for(unsigned i=0; i<anim_output.shape_keys.size(); ++i){
- const ShapeKeyBlend& skb = anim_output.shape_keys[i];
+ for(auto & skb : anim_output.shape_keys){
const std::string &label = skb.label;
if(morph_target_names.find(label) != morph_target_names.end()) {
morph_target_names[label]->anim_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(); i<len; ++i){
- anim_output.matrices[i].origin *= model_char_scale;
+ for(auto & matrice : anim_output.matrices){
+ matrice.origin *= model_char_scale;
}
- for(int i=0, len=anim_output.ik_bones.size(); i<len; ++i){
- anim_output.ik_bones[i].transform.origin *= model_char_scale;
+ for(auto & ik_bone : anim_output.ik_bones){
+ ik_bone.transform.origin *= model_char_scale;
}
weap_anim_info_map = anim_output.weap_anim_info_map;
// Copy bone transforms for further manipulation
@@ -1366,14 +1358,14 @@ void RiggedObject::Update(float timestep) {
vec4 angle_axis(0.0f,1.0f,0.0f,total_rotation);
quaternion rot(angle_axis);
mat4 rotmat4 = Mat4FromQuaternion(rot);
- for(unsigned i=0; i<transforms.size(); i++){
- transforms[i] = rotmat4 * transforms[i];
+ for(auto & transform : transforms){
+ transform = rotmat4 * transform;
}
- for(int i=0, len=anim_output.ik_bones.size(); i<len; ++i){
- anim_output.ik_bones[i].transform = rotmat4 * anim_output.ik_bones[i].transform;
+ for(auto & ik_bone : anim_output.ik_bones){
+ ik_bone.transform = rotmat4 * ik_bone.transform;
}
- for(WeapAnimInfoMap::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 = 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<len; ++i){
- anim_output.ik_bones[i].transform.origin += total_center_offset;
+ for(auto & ik_bone : anim_output.ik_bones){
+ ik_bone.transform.origin += total_center_offset;
}
- for(std::map<int, WeapAnimInfo>::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<std::string, MorphTarget*> morph_target_names;
- for(unsigned i=0; i<morph_targets.size(); ++i){
- morph_target_names[morph_targets[i].name] = &morph_targets[i];
+ for(auto & morph_target : morph_targets){
+ morph_target_names[morph_target.name] = &morph_target;
}
- for(unsigned i=0; i<anim_output.shape_keys.size(); ++i){
- const ShapeKeyBlend& skb = anim_output.shape_keys[i];
+ for(auto & skb : anim_output.shape_keys){
const std::string &label = skb.label;
if(morph_target_names.find(label) != morph_target_names.end()) {
morph_target_names[label]->anim_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; i<anim_output.status_keys.size(); ++i){
- const StatusKeyBlend key = anim_output.status_keys[i];
+ for(auto key : anim_output.status_keys){
status_keys[key.label] = key.weight*key.weight_weight;
}
@@ -1468,12 +1458,12 @@ void RiggedObject::Update(float timestep) {
}
if(animated){
- for(AttachedItemList::iterator iter = attached_items.items.begin(); iter != attached_items.items.end(); ++iter) {
- ItemObjectScriptReader& item = iter->item;
+ 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<float> sm_vertices(sm.vertices.size());
std::vector<float> sm_tex_coords(sm.tex_coords.size());
- for(int i=0, len=vert_parent.size(); i<len; ++i){
- WOLFIRE_SIMPLIFY::ParentRecordList parents = vert_parent[i];
+ for(auto parents : vert_parent){
float total[3];
- for(int j=0; j<3; ++j){
- total[j] = 0.0f;
+ for(float & j : total){
+ j = 0.0f;
}
- 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;
if(pr.weight > 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(); i<len; ++i){
- WOLFIRE_SIMPLIFY::ParentRecordList parents = tex_parent[i];
+ for(auto parents : tex_parent){
float total[2];
- for(int j=0; j<2; ++j){
- total[j] = 0.0f;
+ for(float & j : total){
+ j = 0.0f;
}
- 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_tex_index = sm.old_tex_id[pr.id]*2;
for(int j=0; j<2; ++j){
total[j] += base_model.tex_coords[parent_tex_index+j] * pr.weight;
}
}
- 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_tex_index = pr.id*2;
for(int j=0; j<2; ++j){
sm_tex_coords[parent_tex_index+j] = total[j];
@@ -1629,11 +1617,11 @@ void RiggedObject::Load(const std::string& character_path, vec3 pos, SceneGraph*
anim_client.SetRetargeting(skeleton_path);
const mat4 &transform = GetTransform();
- for(unsigned i=0; i<skeleton_.physics_bones.size(); i++){
- if(!skeleton_.physics_bones[i].bullet_object){
+ for(auto & physics_bone : skeleton_.physics_bones){
+ if(!physics_bone.bullet_object){
continue;
}
- skeleton_.physics_bones[i].bullet_object->ApplyTransform(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<MorphInfo> &morphs = char_ref->GetMorphs();
- for(unsigned i=0; i<morphs.size(); ++i){
+ for(const auto & morph : morphs){
MorphTarget mt;
- mt.Load(ofc->model_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<len; ++i){
- WOLFIRE_SIMPLIFY::ParentRecordList parents = vert_parent[i];
+ for(auto parents : vert_parent){
float total[3];
bone_info_accumulate.clear();
- for(int j=0; j<3; ++j){
- total[j] = 0.0f;
+ for(float & j : total){
+ j = 0.0f;
}
- 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;
if(pr.weight > 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<len; ++i){
- BoneInfo &bi = bone_info_accumulate[i];
+ for(auto & bi : bone_info_accumulate){
total_weight += bi.weight;
}
if(total_weight != 0.0f){
- for(int i=0,len=bone_info_accumulate.size(); i<len; ++i){
- BoneInfo &bi = bone_info_accumulate[i];
+ for(auto & bi : bone_info_accumulate){
bi.weight /= total_weight;
}
}
- 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];
@@ -1778,21 +1763,20 @@ void RiggedObject::Load(const std::string& character_path, vec3 pos, SceneGraph*
}
}
}
- for(int i=0, len=tex_parent.size(); i<len; ++i){
- WOLFIRE_SIMPLIFY::ParentRecordList parents = tex_parent[i];
+ for(auto parents : tex_parent){
float total[2];
- for(int j=0; j<2; ++j){
- total[j] = 0.0f;
+ for(float & j : total){
+ j = 0.0f;
}
- 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_tex_index = sm.old_tex_id[pr.id]*2;
for(int j=0; j<2; ++j){
total[j] += base_model.tex_coords[parent_tex_index+j] * pr.weight;
}
}
- 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_tex_index = pr.id*2;
for(int j=0; j<2; ++j){
sm.tex_coords[parent_tex_index+j] = total[j];
@@ -1828,14 +1812,14 @@ void RiggedObject::Load(const std::string& character_path, vec3 pos, SceneGraph*
model.morph_transform_vec.resize(model_num_verts);
std::queue<MorphTarget*> queue;
- for(unsigned i=0; i<morph_targets.size(); ++i){
- queue.push(&morph_targets[i]);
+ for(auto & morph_target : morph_targets){
+ queue.push(&morph_target);
}
while(!queue.empty()){
MorphTarget& morph = (*queue.front());
queue.pop();
- for(unsigned i=0; i<morph.morph_targets.size(); ++i){
- queue.push(&morph.morph_targets[i]);
+ for(auto & morph_target : morph.morph_targets){
+ queue.push(&morph_target);
}
if(morph.model_id[0] != -1) {
morph.model_id[lod_index] = Models::Instance()->AddModel();
@@ -1846,8 +1830,8 @@ void RiggedObject::Load(const std::string& character_path, vec3 pos, SceneGraph*
morph_model.CopyVertCollapse(model);
}
}
- for(unsigned i=0; i<morph_targets.size(); ++i){
- morph_targets[i].CalcVertsModified(model_id[lod_index],lod_index);
+ for(auto & morph_target : morph_targets){
+ morph_target.CalcVertsModified(model_id[lod_index],lod_index);
}
}
SaveSimplificationCache(char_ref->path_);
@@ -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<AttachedItem>::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<AttachedItem>::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<AttachedItem>::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; k<morph_targets.size(); ++k){
- MorphTarget& m_t = morph_targets[k];
+ for(auto & m_t : morph_targets){
if(online->IsClient() || 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(); k<len; ++k){
- MorphTarget* morph = active_morph_targets[k];
-
+ for(auto morph : active_morph_targets){
const Model *morph_model = &mi->GetModel(morph->model_id[lod_level]);
const std::vector<int> &modified_tc = morph->modified_tc[lod_level];
- for(unsigned j=0, len2=modified_tc.size(); j<len2; ++j){
- vert_id = modified_tc[j];
+ for(int j : modified_tc){
+ vert_id = j;
vert_id_index = vert_id*2;
model->tex_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<int> &modified_vert = morph->modified_verts[lod_level];
- for(unsigned j=0,len2=modified_vert.size(); j<len2; ++j){
- vert_id = modified_vert[j];
+ for(int j : modified_vert){
+ vert_id = j;
vert_id_index = vert_id*3;
if (online->IsClient()) {
@@ -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; i<morph_targets.size(); ++i){
- if(morph_targets[i].name == target_name){
- morph_targets[i].SetScriptWeight(weight, weight_weight);
+ for(auto & morph_target : morph_targets){
+ if(morph_target.name == target_name){
+ morph_target.SetScriptWeight(weight, weight_weight);
return;
}
}
@@ -2500,9 +2478,9 @@ void RiggedObject::FixDiscontinuity() {
Update(game_timer.timestep);
time_until_next_anim_update = 0;
Update(game_timer.timestep);
- for(unsigned i=0; i<skeleton_.physics_bones.size(); i++){
- if(skeleton_.physics_bones[i].bullet_object){
- skeleton_.physics_bones[i].bullet_object->FixDiscontinuity();
+ 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<skeleton_.physics_bones.size(); i++){
- BulletObject* b_object = skeleton_.physics_bones[i].bullet_object;
+ for(auto & physics_bone : skeleton_.physics_bones){
+ BulletObject* b_object = physics_bone.bullet_object;
if(!b_object){
continue;
}
@@ -2526,8 +2504,8 @@ void RiggedObject::Ragdoll(const vec3 &velocity) {
animated = false;
first_ragdoll_frame = true;
- for(unsigned i=0; i<skeleton_.physics_bones.size(); i++){
- BulletObject* b_object = skeleton_.physics_bones[i].bullet_object;
+ for(auto & physics_bone : skeleton_.physics_bones){
+ BulletObject* b_object = physics_bone.bullet_object;
if(!b_object){
continue;
}
@@ -2541,18 +2519,17 @@ void RiggedObject::Ragdoll(const vec3 &velocity) {
skeleton_.SetGFStrength(skeleton_.physics_joints[i], 0.0f);
}
- for(std::list<AttachedItem>::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<skeleton_.physics_bones.size(); i++){
- BulletObject* b_object = skeleton_.physics_bones[i].bullet_object;
+ for(auto & physics_bone : skeleton_.physics_bones){
+ BulletObject* b_object = physics_bone.bullet_object;
if(!b_object){
continue;
}
@@ -2562,10 +2539,9 @@ void RiggedObject::SetDamping(float amount){
}
}
if(amount >= 1.0f){
- for(std::list<AttachedItem>::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<AttachedItem>::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; i<skeleton_.physics_bones.size(); i++){
- if(!skeleton_.physics_bones[i].bullet_object){
+ for(auto & physics_bone : skeleton_.physics_bones){
+ if(!physics_bone.bullet_object){
continue;
}
num_total++;
- total += skeleton_.physics_bones[i].bullet_object->GetPosition();
+ 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; i<skeleton_.physics_bones.size(); i++){
- if(!skeleton_.physics_bones[i].bullet_object ||
- !skeleton_.physics_bones[i].bullet_object->linked){
+ 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; i<skeleton_.physics_bones.size(); i++){
- if(!skeleton_.physics_bones[i].bullet_object ||
- !skeleton_.physics_bones[i].bullet_object->linked){
+ 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; i<skeleton_.physics_bones.size(); i++){
- if(!skeleton_.physics_bones[i].bullet_object){
+ for(auto & physics_bone : skeleton_.physics_bones){
+ if(!physics_bone.bullet_object){
continue;
}
- const PhysicsBone& bone = skeleton_.physics_bones[i];
+ const PhysicsBone& bone = physics_bone;
mat4 rotation = bone.bullet_object->GetRotation() *
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; i<blended_bone_paths.size(); ++i){
- if(blended_bone_paths[i].ik_bone.label == target_name){
- return blended_bone_paths[i].weight;
+ for(auto & blended_bone_path : blended_bone_paths){
+ if(blended_bone_path.ik_bone.label == target_name){
+ return blended_bone_path.weight;
}
}
return 0.0f;
}
BoneTransform GetIKTransform( RiggedObject* rigged_object, const std::string &target_name ) {
- for(unsigned i=0; i<rigged_object->blended_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; i<rigged_object->blended_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; i<blended_bone_paths.size(); ++i){
- if(blended_bone_paths[i].ik_bone.label == target_name){
- int target_bone = blended_bone_paths[i].ik_bone.bone_path.back();
+ for(auto & blended_bone_path : blended_bone_paths){
+ if(blended_bone_path.ik_bone.label == target_name){
+ int target_bone = blended_bone_path.ik_bone.bone_path.back();
return unmodified_transforms[target_bone].origin;
}
}
@@ -2753,8 +2728,7 @@ void MorphTarget::CalcVertsModified(int base_model_id, int lod_level) {
} else {
verts_modified[lod_level].resize(model_num_verts, false);
tc_modified[lod_level].resize(model_num_verts, false);
- for(unsigned i=0; i<morph_targets.size(); ++i){
- MorphTarget &mt = morph_targets[i];
+ for(auto & mt : morph_targets){
mt.CalcVertsModified(base_model_id, lod_level);
for(int j=0; j<model_num_verts; ++j){
if(mt.verts_modified[lod_level][j]){
@@ -2795,8 +2769,8 @@ void MorphTarget::Load(const std::string &base_model_name,
script_weight_weight = 0.0f;
checksum = 0;
- for(int i=0; i<4; ++i){
- model_id[i] = -1;
+ for(int & i : model_id){
+ i = -1;
}
if(parts == 1){
@@ -2820,11 +2794,11 @@ void MorphTarget::Load(const std::string &base_model_name,
} else {
model_id[0] = Models::Instance()->CopyModel(base_model_id);
Model& model = Models::Instance()->GetModel(model_id[0]);
- for(int i=0, len=(int)model.vertices.size(); i<len; ++i){
- model.vertices[i] = 0.0f;
+ for(float & vertex : model.vertices){
+ vertex = 0.0f;
}
- for(int i=0, len=(int)model.tex_coords.size(); i<len; ++i){
- model.tex_coords[i] = 0.0f;
+ for(float & tex_coord : model.tex_coords){
+ tex_coord = 0.0f;
}
model_copy[0] = true;
for(int i=0; i<parts; ++i){
@@ -2877,20 +2851,20 @@ void MorphTarget::PreDrawCamera(int num, int progress, int lod_level, uint32_t c
if(new_weight == 0.0f || new_weight == 1.0f){
Model *the_model = (new_weight == 0.0f)?&morph_model_start:&morph_model_end;
- for(unsigned j=0; j<modified_verts[lod_level].size(); ++j){
- const int index = modified_verts[lod_level][j]*3;
+ for(int j : modified_verts[lod_level]){
+ const int index = j*3;
model.vertices[index+0] = the_model->vertices[index+0];
model.vertices[index+1] = the_model->vertices[index+1];
model.vertices[index+2] = the_model->vertices[index+2];
}
- for(unsigned j=0; j<modified_tc[lod_level].size(); ++j){
- const int tc_index = modified_tc[lod_level][j]*2;
+ for(int j : modified_tc[lod_level]){
+ const int tc_index = j*2;
model.tex_coords[tc_index+0] = the_model->tex_coords[tc_index+0];
model.tex_coords[tc_index+1] = the_model->tex_coords[tc_index+1];
}
} else {
- for(unsigned j=0; j<modified_verts[lod_level].size(); ++j){
- const int index = modified_verts[lod_level][j]*3;
+ for(int j : modified_verts[lod_level]){
+ const int index = j*3;
model.vertices[index+0] = morph_model_start.vertices[index+0]*(1.0f-new_weight);
model.vertices[index+1] = morph_model_start.vertices[index+1]*(1.0f-new_weight);
model.vertices[index+2] = morph_model_start.vertices[index+2]*(1.0f-new_weight);
@@ -2898,8 +2872,8 @@ void MorphTarget::PreDrawCamera(int num, int progress, int lod_level, uint32_t c
model.vertices[index+1] += morph_model_end.vertices[index+1]*new_weight;
model.vertices[index+2] += morph_model_end.vertices[index+2]*new_weight;
}
- for(unsigned j=0; j<modified_tc[lod_level].size(); ++j){
- const int tc_index = modified_tc[lod_level][j]*2;
+ for(int j : modified_tc[lod_level]){
+ const int tc_index = j*2;
model.tex_coords[tc_index+0] = morph_model_start.tex_coords[tc_index+0]*(1.0f-new_weight);
model.tex_coords[tc_index+1] = morph_model_start.tex_coords[tc_index+1]*(1.0f-new_weight);
model.tex_coords[tc_index+0] += morph_model_end.tex_coords[tc_index+0]*new_weight;
@@ -2934,8 +2908,8 @@ void MorphTarget::Dispose() {
Models::Instance()->DeleteModel(model_id[i]);
}
}
- for(unsigned i=0; i<morph_targets.size(); ++i){
- morph_targets[i].Dispose();
+ for(auto & morph_target : morph_targets){
+ morph_target.Dispose();
}
}
@@ -3013,11 +2987,11 @@ mat4 RiggedObject::GetBoneRotation( int bone ) {
}
void RiggedObject::SetSkeletonOwner( Object* owner ) {
- for(unsigned i=0; i<skeleton_.physics_bones.size(); ++i){
- if(!skeleton_.physics_bones[i].bullet_object){
+ for(auto & physics_bone : skeleton_.physics_bones){
+ if(!physics_bone.bullet_object){
continue;
}
- skeleton_.physics_bones[i].bullet_object->owner_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; i<skeleton_.physics_bones.size(); ++i){
- if(skeleton_.physics_bones[i].bullet_object){
- skeleton_.physics_bones[i].bullet_object->CanSleep();
+ for(auto & physics_bone : skeleton_.physics_bones){
+ if(physics_bone.bullet_object){
+ physics_bone.bullet_object->CanSleep();
}
}
}
void RiggedObject::DisableSleep()
{
- for(unsigned i=0; i<skeleton_.physics_bones.size(); ++i){
- if(skeleton_.physics_bones[i].bullet_object){
- skeleton_.physics_bones[i].bullet_object->NoSleep();
+ 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<std::string, float> &mw = lipsync_reader.GetMorphWeights();
std::map<std::string, float>::const_iterator iter;
for(iter = mw.begin(); iter != mw.end(); ++iter){
- for(unsigned i=0; i<morph_targets.size(); ++i){
- if(morph_targets[i].name == iter->first){
- 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; i<morph_targets.size(); ++i){
- if(morph_targets[i].name == iter->first){
- 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<AttachedItem>::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<hit_list.size(); ++i){
- GetTransformedTri(hit_list[i], points);
+ for(int i : hit_list){
+ GetTransformedTri(i, points);
if(dot(cross(points[1] - points[0], points[2] - points[0]), dir) > 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<len; ++i){
close_enough = false;
GetTransformedTri(i, points);
- for(unsigned j=0; j<3; ++j){
- points[j] -= dir * dot(dir, points[j] - pos);
- if(distance_squared(points[j], pos) < _stab_threshold){
+ for(auto & point : points){
+ point -= dir * dot(dir, point - pos);
+ if(distance_squared(point, pos) < _stab_threshold){
close_enough = true;
}
}
@@ -3563,11 +3536,11 @@ void RiggedObject::Stab( const vec3 &pos, const vec3 &dir, int type, int depth )
vec3 start = pos - dir * 1000.0f;
vec3 end = pos + dir * 1000.0f;
vec3 intersect;
- for(unsigned i=0; i<hit_list.size(); ++i){
- GetTransformedTri(hit_list[i], points);
+ for(int i : hit_list){
+ GetTransformedTri(i, points);
if(LineFacet(start, end, points[0], points[1], points[2], &intersect)){
for(unsigned j=0; j<10; ++j){
- blood_surface.CreateDripInTri(hit_list[i], vec3(0.333f,0.333f,0.333f), RangedRandomFloat(0.1f,1.0f), RangedRandomFloat(0.0f,10.0f), true, SurfaceWalker::BLOOD);
+ blood_surface.CreateDripInTri(i, vec3(0.333f,0.333f,0.333f), RangedRandomFloat(0.1f,1.0f), RangedRandomFloat(0.0f,10.0f), true, SurfaceWalker::BLOOD);
}
}
}
@@ -3614,8 +3587,8 @@ void RiggedObject::AddWaterCube( const mat4 &transform ) {
std::vector<mat4> fire_decal_matrix;
std::vector<mat4> water_decal_matrix;
- for(int i=0, len=scenegraph_->decal_objects_.size(); i<len; ++i){
- DecalObject* obj = (DecalObject*)scenegraph_->decal_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; i<skeleton_.physics_bones.size(); ++i){
- BulletObject* cbo = skeleton_.physics_bones[i].col_bullet_object;
+ for(auto & physics_bone : skeleton_.physics_bones){
+ BulletObject* cbo = physics_bone.col_bullet_object;
if(!cbo){
continue;
}
- cbo->SetTransform(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_index<num_bones; ++bone_index){
- BulletObject* bullet_object = skeleton->physics_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<BoneTransform> &mats = rigged_object->animation_frame_bone_matrices;
- for(int i=0, len=mats.size(); i<len; ++i){
- mats[i] = transform * mats[i];
+ for(auto & mat : mats){
+ mat = transform * mat;
}
}
@@ -3863,8 +3836,8 @@ static CScriptArray *ASGetConvexHullPoints(Skeleton* skeleton, int bone){
CScriptArray *array = CScriptArray::Create(arrayType, (asUINT)0);
array->Reserve(points.size());
- for(int i=0, len=points.size(); i<len; ++i) {
- array->InsertLast(&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<len; ++i){
- checksum += morph_targets[i].checksum;
+ for(auto & morph_target : morph_targets){
+ checksum += morph_target.checksum;
}
fwrite(&simp_cache_vers, sizeof(int), 1, file);
fwrite(&checksum, sizeof(unsigned short), 1, file);
@@ -4050,14 +4023,14 @@ void RiggedObject::SaveSimplificationCache(const std::string &path) {
}
std::queue<MorphTarget*> queue;
- for(unsigned i=0; i<morph_targets.size(); ++i){
- queue.push(&morph_targets[i]);
+ for(auto & morph_target : morph_targets){
+ queue.push(&morph_target);
}
while(!queue.empty()){
MorphTarget& morph = (*queue.front());
queue.pop();
- for(unsigned i=0; i<morph.morph_targets.size(); ++i){
- queue.push(&morph.morph_targets[i]);
+ for(auto & morph_target : morph.morph_targets){
+ queue.push(&morph_target);
}
for(unsigned i=1; i<4; ++i){
const Model& model = Models::Instance()->GetModel(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<len; ++i){
- checksum += morph_targets[i].checksum;
+ for(auto & morph_target : morph_targets){
+ checksum += morph_target.checksum;
}
unsigned short file_checksum;
fread(&file_checksum, sizeof(unsigned short), 1, file);
@@ -4145,14 +4118,14 @@ bool RiggedObject::LoadSimplificationCache(const std::string& path) {
}
std::queue<MorphTarget*> queue;
- for(unsigned i=0; i<morph_targets.size(); ++i){
- queue.push(&morph_targets[i]);
+ for(auto & morph_target : morph_targets){
+ queue.push(&morph_target);
}
while(!queue.empty()){
MorphTarget& morph = (*queue.front());
queue.pop();
- for(unsigned i=0; i<morph.morph_targets.size(); ++i){
- queue.push(&morph.morph_targets[i]);
+ for(auto & morph_target : morph.morph_targets){
+ queue.push(&morph_target);
}
for(unsigned i=1; i<4; ++i){
morph.model_id[i] = Models::Instance()->AddModel();
@@ -4237,8 +4210,8 @@ void RiggedObject::CreateFurModel( int model_id, int fur_model_id ) {
// verts
{
std::vector<bool> included(fur_ref_model.vertices.size()/3, false);
- for(unsigned i=0; i<fur_model.faces.size(); ++i){
- included[fur_model.faces[i]] = true;
+ for(unsigned int face : fur_model.faces){
+ included[face] = true;
}
int remap_index = 0;
@@ -4253,8 +4226,8 @@ void RiggedObject::CreateFurModel( int model_id, int fur_model_id ) {
fur_model.vertices.push_back(fur_ref_model.vertices[vert_index+2] - base_model.old_center[2]);
}
}
- for(unsigned i=0; i<fur_model.faces.size(); ++i){
- fur_model.faces[i] = remapped[fur_model.faces[i]];
+ for(unsigned int & face : fur_model.faces){
+ face = remapped[face];
}
}
@@ -4279,8 +4252,8 @@ void RiggedObject::CreateFurModel( int model_id, int fur_model_id ) {
for(int i=0, len=fur_model.vertices.size()/3; i<len; ++i){
vert_dup[i] = fur_model_points[fur_verts[i]].front();
}
- for(unsigned i=0; i<fur_model.faces.size(); ++i){
- fur_model.faces[i] = vert_dup[fur_model.faces[i]];
+ for(unsigned int & face : fur_model.faces){
+ face = vert_dup[face];
}
}
@@ -4713,20 +4686,18 @@ void RiggedObject::UnStickItem( int id ) {
std::vector<ItemRef> RiggedObject::GetWieldedItemRefs() const {
int num_wielded = 0;
- for(std::list<AttachedItem>::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<ItemRef> wielded_item_refs(num_wielded);
num_wielded = 0;
- for(std::list<AttachedItem>::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<std::string> &attachment_list = item_ref->GetAttachmentList();
- for(std::list<std::string>::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<Attachment>((*iter));
+ AttachmentRef attachment_ref = Engine::Instance()->GetAssetManager()->LoadSync<Attachment>(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<AttachedItem>::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<DetailObjectSurface*>::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<DetailObjectSurface*>::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<Model>::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<Model>::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<mat4> light_volume_matrix;
std::vector<mat4> light_volume_matrix_inverse;
- for(size_t i=0, len=scenegraph_->light_volume_objects_.size(); i<len; ++i){
- Object* obj = scenegraph_->light_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<Model>::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<Model>::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<Item>& 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<Item> 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<Item> 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<MovementObject*>(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<MovementObjectUpdate*>(it->GetData());
+ for (auto & incoming_movement_object_frame : mo->incoming_movement_object_frames) {
+ MovementObjectUpdate* update = static_cast<MovementObjectUpdate*>(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<Peer> 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<OnlineMessageBase*>(message_handler.GetMessageData(online_session->persistent_outgoing_messages[i]));
+ for(auto & persistent_outgoing_message : online_session->persistent_outgoing_messages) {
+ OnlineMessageBase* omb = static_cast<OnlineMessageBase*>(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<ModInstance*> 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<ModInstance*> 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..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(unsigned i=0; i<16; ++i){
- if(test_mat.entries[i] != test_mat.entries[i]){
+ for(float entry : test_mat.entries){
+ if(entry != entry){
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; i<temp_constraints_.size(); i++){
- if(temp_constraints_[i].second){
- dynamics_world_->removeConstraint(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<vertex_faces.size(); ++i){
- if(vertex_faces[i] == 1){
- avg_pos += vec3(mesh.vertices[vertex_faces[i]*3+0],
- mesh.vertices[vertex_faces[i]*3+1],
- mesh.vertices[vertex_faces[i]*3+2]);
+ for(int vertex_face : vertex_faces){
+ if(vertex_face == 1){
+ avg_pos += vec3(mesh.vertices[vertex_face*3+0],
+ mesh.vertices[vertex_face*3+1],
+ mesh.vertices[vertex_face*3+2]);
++num_avg;
}
}
@@ -1703,8 +1701,8 @@ void GetSimplifiedHull(const std::vector<vec3> &input, std::vector<vec3> &output
btConvexHullShape* CreateConvexHullShape(const std::vector<vec3> &verts) {
btConvexHullShape* convex_hull_shape = new btConvexHullShape();
- for (unsigned i=0 ; i<verts.size() ; ++i) {
- convex_hull_shape->addPoint(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(); i<len; ++i) {
- shape->addPoint(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; i<fixed_constraints_.size(); i++){
- if( fixed_constraints_[i].second ) {
- dynamics_world_->removeConstraint(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(); i<len; ++i){
- Model& model = Models::Instance()->GetModel(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<len; j+=3){
@@ -2088,8 +2086,8 @@ void BulletWorld::FinalizeStaticEntries() {
vertices.push_back(vec[1]);
vertices.push_back(vec[2]);
}
- for(int j=0, len=model.faces.size(); j<len; ++j){
- vert_indices.push_back(model.faces[j]+start_vertices);
+ for(unsigned int face : model.faces){
+ vert_indices.push_back(face+start_vertices);
}
}
// Create physics object
diff --git a/Source/Scripting/angelscript/add_on/scripthelper/scripthelper.cpp b/Source/Scripting/angelscript/add_on/scripthelper/scripthelper.cpp
index 1880b5ed..cee882f7 100644
--- a/Source/Scripting/angelscript/add_on/scripthelper/scripthelper.cpp
+++ b/Source/Scripting/angelscript/add_on/scripthelper/scripthelper.cpp
@@ -464,10 +464,9 @@ int WriteConfigToStream(asIScriptEngine *engine, ostream &strm)
// Write the members of the template types, so they can be fully registered before any other type uses them
// TODO: Order the template types based on dependency to avoid failure if one type uses instances of another
strm << "\n// Template type members\n";
- for( set<asITypeInfo*>::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<char>& data) {
asITypeInfo *arrayType = engine->GetTypeInfoById(engine->GetTypeIdByDecl("array<uint8>"));
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<char*>(&data[i]));
+ for (const char & i : data) {
+ array->InsertLast(const_cast<char*>(&i));
}
args.AddAddress((void*)array);
@@ -836,8 +836,8 @@ bool ASContext::CallMPCallBack(uint32_t state, const std::vector<unsigned int>&
asITypeInfo *arrayType = engine->GetTypeInfoById(engine->GetTypeIdByDecl("array<uint>"));
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<ASContext*>& 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<std::string, int>(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<int>& 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; i<desc_list.size(); ++i){
- Object* obj = MapEditor::AddEntityFromDesc(the_scenegraph, desc_list[i], false);
+ for(auto & i : desc_list){
+ Object* obj = MapEditor::AddEntityFromDesc(the_scenegraph, i, false);
if( obj ) {
obj->exclude_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<Group::Child>::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(); i<len; ++i){
- int val = the_scenegraph->movement_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<Group*>(obj);
std::vector<Object*> 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<std::string>::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<ModInstance::Item>& msi = mods[i]->items;
+ for(auto mod : mods) {
+ if(!only_include_active || mod->IsActive() ) {
+ const std::vector<ModInstance::Item>& 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<ModInstance::Attribute>& 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<ModInstance*> 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; i<dependencies.size(); ++i){
- if(path == dependencies[i].path){
+ for(auto & dependencie : dependencies){
+ if(path == dependencie.path){
already_loaded = true;
break;
}
@@ -89,8 +89,8 @@ unsigned GetLineNumber(std::string &script, unsigned char_pos){
unsigned GetNumLines(std::string &script){
unsigned line_number = 1;
- for(unsigned i=0; i<script.size(); i++){
- if(script[i] == '\n'){
+ for(char i : script){
+ if(i == '\n'){
line_number++;
}
}
diff --git a/Source/Scripting/scriptparams.cpp b/Source/Scripting/scriptparams.cpp
index bca4e505..81c0b953 100644
--- a/Source/Scripting/scriptparams.cpp
+++ b/Source/Scripting/scriptparams.cpp
@@ -386,10 +386,10 @@ void ReadScriptParametersFromXML( ScriptParamMap &spm, const TiXmlElement* param
void WriteScriptParamsToXML( const ScriptParamMap & pm, TiXmlElement* params )
{
- for(ScriptParamMap::const_iterator iter = pm.begin(); iter != pm.end(); ++iter){
+ for(const auto & iter : pm){
TiXmlElement* param = new TiXmlElement("parameter");
- param->SetAttribute("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<rc_alAudioBuffer> 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<rc_alAudioBuffer> 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; i<ambient_triangles.size(); ++i){
- AmbientTriangle& a_t = ambient_triangles[i];
+ for(auto & a_t : ambient_triangles){
for(unsigned j=0; j<3; ++j){
a_t.vol[j] = min(1.0f, a_t.vol[j] + m_accum_game_timestep);
SetVolume(a_t.handles[j], a_t.vol[j]);
@@ -127,8 +126,7 @@ void Sound::updateListener(vec3 pos, vec3 vel, vec3 facing, vec3 up) {
//oss << "Ambient triangles: " << ambient_triangles.size();
//GUI::Instance()->AddDebugText("ambient_triangles", oss.str(), 0.5f);
- for(unsigned i=0; i<ambient_triangles.size(); ++i){
- AmbientTriangle& a_t = ambient_triangles[i];
+ for(auto & a_t : ambient_triangles){
for(unsigned j=0; j<3; ++j){
//vec3 new_dir(dot(a_t.rel_dir[j], cross(facing, up)),
// dot(a_t.rel_dir[j], up),
diff --git a/Source/Sound/soundtrack.cpp b/Source/Sound/soundtrack.cpp
index add5d819..05843ac6 100644
--- a/Source/Sound/soundtrack.cpp
+++ b/Source/Sound/soundtrack.cpp
@@ -512,9 +512,9 @@ pcm_count(0),
sample_rate(0),
channels(0) {
bool first_creation = true;
- for( unsigned i = 0; i < song.songrefs.size(); i++ ) {
+ for(auto & songref : song.songrefs) {
PlayedSongInterface *ps = NULL;
- MusicXMLParser::Song ns = owner->GetSong(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<std::string,float> Soundtrack::PlayedLayeredSong::GetLayerGains() {
std::map<std::string,float> 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<std::string> Soundtrack::PlayedLayeredSong::GetLayerNames() const {
std::vector<std::string> 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<std::string,MusicXMLParser::Music>::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<AudioEmitter*> 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<float>();
+ sprintf(buffer, "gamepad_%i_look_sensitivity", open_joystick.second->player_input);
+ open_joystick.second->joystick.look_sensitivity_ = config[buffer].toNumber<float>();
}
}
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<float>();
+ sprintf(buffer, "gamepad_%i_deadzone", open_joystick.second->player_input);
+ open_joystick.second->joystick.deadzone = config[buffer].toNumber<float>();
}
}
@@ -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<std::string> 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<std::string, float>::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<std::string, float>::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<std::string, float>::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<Mouse::MousePress> Input::GetMouseInputs() {
std::vector<Joystick::JoystickPress> Input::GetJoystickInputs(int player_index) {
std::vector<Joystick::JoystickPress> ret_inputs;
- for(JoystickMap::iterator iter = open_joysticks_.begin(); iter != open_joysticks_.end(); ++iter) {
- if(iter->second->player_input == player_index) {
- std::vector<Joystick::JoystickPress> inputs = iter->second->joystick.GetJoystickInputs();
+ for(auto & open_joystick : open_joysticks_) {
+ if(open_joystick.second->player_input == player_index) {
+ std::vector<Joystick::JoystickPress> 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<std::pair<int,uint32_t> > 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<int,uint32_t>(cur_index,SDL_SCANCODES[i]));
+ offsets.push_back(std::pair<int,uint32_t>(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<kNumLabels; ++i){
- commands[i].num_key_events = 0;
+ for(auto & command : commands){
+ command.num_key_events = 0;
}
}
@@ -354,8 +354,8 @@ void KeyCommand::HandleKeyDownEvent( const Keyboard &keyboard, SDL_Keysym key_i
// Check for key_pressed events from longest command to shortest
int cmd_length = -1;
SDL_Scancode sc = key_id.scancode;
- for(int i=0; i<kNumLabels; ++i){
- Command &cmd = *(commands_sorted_by_length[i]);
+ for(auto & i : commands_sorted_by_length){
+ Command &cmd = *i;
if(cmd.num_key_events < cmd_length) {
return;
}
@@ -400,7 +400,7 @@ void KeyCommand::HandleKeyDownEvent( const Keyboard &keyboard, SDL_Keysym key_i
}
void KeyCommand::ClearKeyPresses() {
- for(int i=0; i<kNumLabels; ++i){
- commands[i].state = kUp;
+ for(auto & command : commands){
+ command.state = kUp;
}
}
diff --git a/Source/UserInput/mouse.cpp b/Source/UserInput/mouse.cpp
index bdd28f86..f853d6d9 100644
--- a/Source/UserInput/mouse.cpp
+++ b/Source/UserInput/mouse.cpp
@@ -51,8 +51,8 @@ Mouse::Mouse()
void Mouse::Update() {
wheel_delta_x_ = 0;
wheel_delta_y_ = 0;
- for(int i=0; i<2; ++i){
- delta_[i] = 0;
+ for(int & i : delta_){
+ i = 0;
}
for (int i = 0; i < NUM_BUTTONS; ++i) {
mouse_double_click_[i] = false;
diff --git a/Source/Utility/binn_util.cpp b/Source/Utility/binn_util.cpp
index ca5e0c54..dec7dea1 100644
--- a/Source/Utility/binn_util.cpp
+++ b/Source/Utility/binn_util.cpp
@@ -69,8 +69,8 @@ void binn_object_set_std_string(binn* l, const char* key, const string& v) {
void binn_object_set_vector_int(binn* l, const char* key, const vector<int>& 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<string> &endings)
{
- for( vector<string>::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<AssetWarning>::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<std::string> 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<IDAndType> &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 = &it;
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(); i<len; ++i){
+ for(auto & i : li.desc_list_){
buf[0] = '\0';
- const EntityDescriptionField* path_field = li.desc_list_[i].GetField(EDF_FILE_PATH);
+ const EntityDescriptionField* path_field = i.GetField(EDF_FILE_PATH);
if(path_field && !path_field->data.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; i<li.ambient_sounds_.size(); ++i){
- Engine::Instance()->GetSound()->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; i<ti.detail_object_info.size(); ++i){
- const DetailObjectLayer &dol = ti.detail_object_info[i];
+ for(const auto & dol : ti.detail_object_info){
TiXmlElement *doe = new TiXmlElement("DetailObject");
doe->SetAttribute("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<AmbientTriangle>& ambient_triangles =
Engine::Instance()->GetSound()->GetAmbientTriangles();
- for(unsigned i=0; i<ambient_triangles.size(); ++i){
+ for(const auto & ambient_triangle : ambient_triangles){
TiXmlElement* ambient;
ambient = new TiXmlElement("Ambient");
ambient_sound_element->LinkEndChild(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<SpawnerItem> 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());