diff --git a/MobileGL/MG_Util/Miscellany/IndexGenerator.h b/MobileGL/MG_Util/Miscellany/IndexGenerator.h index c1b5a713..18238c50 100644 --- a/MobileGL/MG_Util/Miscellany/IndexGenerator.h +++ b/MobileGL/MG_Util/Miscellany/IndexGenerator.h @@ -1,52 +1,58 @@ #pragma once +#include +#include +#include namespace MobileGL { template class IndexGenerator { public: - IndexGenerator() : next_index_(1) {} - explicit IndexGenerator(IndexType n) : next_index_(1) { - is_valid_.reserve(n); + explicit IndexGenerator(size_t initial_capacity = 1024) + : next_index_(0) + { + is_valid_.reserve(initial_capacity); } void Generate(size_t n, IndexType* indices) { - if (n <= 0) { - return; - } + if (n == 0) return; - size_t count_from_freed = std::min(n, freed_indices_.size()); - for (size_t i = 0; i < count_from_freed; ++i) { + size_t from_freed = std::min(n, freed_indices_.size()); + for (size_t i = 0; i < from_freed; ++i) { indices[i] = freed_indices_.back(); freed_indices_.pop_back(); - if (indices[i] >= is_valid_.size()) { - is_valid_.resize(static_cast(indices[i]) + 1, false); - } - is_valid_[indices[i]] = true; + is_valid_[indices[i]] = 1; } - for (size_t i = count_from_freed; i < n; ++i) { - indices[i] = next_index_++; - if (indices[i] >= is_valid_.size()) { - is_valid_.resize(static_cast(indices[i]) + 1, false); + size_t need_new = n - from_freed; + if (need_new > 0) { + size_t required = next_index_ + need_new; + if (required > is_valid_.size()) { + size_t new_cap = std::max(required, is_valid_.size() * 2); + is_valid_.resize(new_cap, 0); + } + for (size_t i = 0; i < need_new; ++i) { + indices[from_freed + i] = next_index_; + is_valid_[next_index_] = 1; + ++next_index_; } - is_valid_[indices[i]] = true; } } void Delete(IndexType index) { - if (index < is_valid_.size() && is_valid_[index] == true) { - is_valid_[index] = false; + if (index < is_valid_.size() && is_valid_[index]) { + is_valid_[index] = 0; freed_indices_.push_back(index); } } bool IsValid(IndexType index) const { - return index < is_valid_.size() && is_valid_[index] == true; + return index < is_valid_.size() && is_valid_[index]; } private: - IndexType next_index_; - std::vector freed_indices_; - std::vector is_valid_; + IndexType next_index_ = 0; + std::vector freed_indices_; + std::vector is_valid_; }; -} \ No newline at end of file + +}