Add log verbosity level

This commit is contained in:
Attila Uygun 2023-06-28 22:09:56 +02:00
parent 1148e48085
commit c6546b43b5
32 changed files with 459 additions and 411 deletions

View File

@ -10,7 +10,7 @@
#define HERE std::make_tuple(__func__, __FILE__, __LINE__) #define HERE std::make_tuple(__func__, __FILE__, __LINE__)
// Helper for logging location info, e.g. LOG << LOCATION(from) // Helper for logging location info, e.g. LOG(0) << LOCATION(from)
#define LOCATION(from) \ #define LOCATION(from) \
std::get<0>(from) << "() [" << [](std::string path) -> std::string { \ std::get<0>(from) << "() [" << [](std::string path) -> std::string { \
size_t last_slash_pos = path.find_last_of("\\/"); \ size_t last_slash_pos = path.find_last_of("\\/"); \

View File

@ -6,15 +6,27 @@
#include <cstdio> #include <cstdio>
#endif #endif
#include <cstdlib> #include <cstdlib>
#include <string>
namespace base { namespace base {
namespace {
int g_max_log_verbosity_level = 0;
} // namespace
// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
// an object of the correct type on the LHS of the unused part of the ternary // an object of the correct type on the LHS of the unused part of the ternary
// operator. // operator.
std::ostream* LogMessage::swallow_stream; std::ostream* LogMessage::swallow_stream;
LogMessage::LogMessage(const char* file, int line) : file_(file), line_(line) {} int GlobalMaxLogVerbosityLevel() {
return g_max_log_verbosity_level;
}
LogMessage::LogMessage(const char* file, int line, int verbosity_level)
: file_(file), line_(line), verbosity_level_(verbosity_level) {}
LogMessage::~LogMessage() { LogMessage::~LogMessage() {
stream_ << std::endl; stream_ << std::endl;
@ -24,30 +36,32 @@ LogMessage::~LogMessage() {
if (last_slash_pos != std::string::npos) if (last_slash_pos != std::string::npos)
filename = filename.substr(last_slash_pos + 1); filename = filename.substr(last_slash_pos + 1);
#if defined(__ANDROID__) #if defined(__ANDROID__)
__android_log_print(ANDROID_LOG_ERROR, "kaliber", "[%s:%d] %s", __android_log_print(ANDROID_LOG_ERROR, "kaliber", "%d [%s:%d] %s",
filename.c_str(), line_, text.c_str()); verbosity_level_, filename.c_str(), line_, text.c_str());
#else #else
printf("[%s:%d] %s", filename.c_str(), line_, text.c_str()); printf("%d [%s:%d] %s", verbosity_level_, filename.c_str(), line_,
text.c_str());
#endif #endif
} }
// static
LogAbort LogAbort::Check(const char* file, int line, const char* expr) { LogAbort LogAbort::Check(const char* file, int line, const char* expr) {
LogAbort instance(new LogMessage(file, line)); LogAbort instance(new LogMessage(file, line, 0));
instance.GetLog().stream() << "CHECK: " instance.GetLog().stream() << "CHECK(" << expr << ") ";
<< "(" << expr << ") ";
return instance; return instance;
} }
// static
LogAbort LogAbort::DCheck(const char* file, int line, const char* expr) { LogAbort LogAbort::DCheck(const char* file, int line, const char* expr) {
LogAbort instance(new LogMessage(file, line)); LogAbort instance(new LogMessage(file, line, 0));
instance.GetLog().stream() << "DCHECK: " instance.GetLog().stream() << "DCHECK(" << expr << ") ";
<< "(" << expr << ") ";
return instance; return instance;
} }
// static
LogAbort LogAbort::NotReached(const char* file, int line) { LogAbort LogAbort::NotReached(const char* file, int line) {
LogAbort instance(new LogMessage(file, line)); LogAbort instance(new LogMessage(file, line, 0));
instance.GetLog().stream() << "NOTREACHED "; instance.GetLog().stream() << "NOTREACHED() ";
return instance; return instance;
} }

View File

@ -11,45 +11,66 @@
// CHECK(condition) terminates the process if the condition is false. // CHECK(condition) terminates the process if the condition is false.
// NOTREACHED annotates unreachable codepaths and terminates the process if // NOTREACHED annotates unreachable codepaths and terminates the process if
// reached. // reached.
#define LOG base::LogMessage(__FILE__, __LINE__).stream() #define LOG(verbosity_level) \
#define LOG_IF(condition) \ LAZY_STREAM( \
LAZY_STREAM(condition, base::LogMessage(__FILE__, __LINE__).stream()) LOG_IS_ON(verbosity_level), \
#define CHECK(condition) \ ::base::LogMessage(__FILE__, __LINE__, verbosity_level).stream())
LAZY_STREAM( \ #define LOG_IF(verbosity_level, condition) \
!(condition), \ LAZY_STREAM( \
base::LogAbort::Check(__FILE__, __LINE__, #condition).GetLog().stream()) LOG_IS_ON(verbosity_level) && (condition), \
::base::LogMessage(__FILE__, __LINE__, verbosity_level).stream())
#define CHECK(condition) \
LAZY_STREAM(!(condition), \
::base::LogAbort::Check(__FILE__, __LINE__, #condition) \
.GetLog() \
.stream())
#define NOTREACHED \ #define NOTREACHED() \
base::LogAbort::NotReached(__FILE__, __LINE__).GetLog().stream() ::base::LogAbort::NotReached(__FILE__, __LINE__).GetLog().stream()
// Macros for logging which are active only in debug builds. // Macros for logging which are active only in debug builds.
#ifdef _DEBUG #ifdef _DEBUG
#define DLOG base::LogMessage(__FILE__, __LINE__).stream() #define DLOG(verbosity_level) \
#define DLOG_IF(condition) \ LAZY_STREAM( \
LAZY_STREAM(condition, base::LogMessage(__FILE__, __LINE__).stream()) LOG_IS_ON(verbosity_level), \
#define DCHECK(condition) \ ::base::LogMessage(__FILE__, __LINE__, verbosity_level).stream())
LAZY_STREAM(!(condition), \ #define DLOG_IF(verbosity_level, condition) \
base::LogAbort::DCheck(__FILE__, __LINE__, #condition) \ LAZY_STREAM( \
.GetLog() \ LOG_IS_ON(verbosity_level) && (condition), \
::base::LogMessage(__FILE__, __LINE__, verbosity_level).stream())
#define DCHECK(condition) \
LAZY_STREAM(!(condition), \
::base::LogAbort::DCheck(__FILE__, __LINE__, #condition) \
.GetLog() \
.stream()) .stream())
#else #else
// "debug mode" logging is compiled away to nothing for release builds. // "debug mode" logging is compiled away to nothing for release builds.
#define DLOG EAT_STREAM_PARAMETERS #define DLOG(verbosity_level) EAT_STREAM_PARAMETERS
#define DLOG_IF(condition) EAT_STREAM_PARAMETERS #define DLOG_IF(verbosity_level, condition) EAT_STREAM_PARAMETERS
#define DCHECK(condition) EAT_STREAM_PARAMETERS #define DCHECK(condition) EAT_STREAM_PARAMETERS
#endif #endif
// Helper macro which avoids evaluating the arguments to a stream if // Helper macro which avoids evaluating the arguments to a stream if
// the condition doesn't hold. // the condition doesn't hold.
#define LAZY_STREAM(condition, stream) \ #define LAZY_STREAM(condition, stream) \
!(condition) ? (void)0 : base::LogMessage::Voidify() & (stream) !(condition) ? (void)0 : ::base::LogMessage::Voidify() & (stream)
// Avoid any pointless instructions to be emitted by the compiler. // Avoid any pointless instructions to be emitted by the compiler.
#define EAT_STREAM_PARAMETERS \ #define EAT_STREAM_PARAMETERS \
LAZY_STREAM(false, *base::LogMessage::swallow_stream) LAZY_STREAM(false, *::base::LogMessage::swallow_stream)
#if defined(MAX_LOG_VERBOSITY_LEVEL)
#define LOG_IS_ON(verbosity_level) \
((verbosity_level) <= MAX_LOG_VERBOSITY_LEVEL)
#else
#define LOG_IS_ON(verbosity_level) \
((verbosity_level) <= ::base::GlobalMaxLogVerbosityLevel())
#endif
namespace base { namespace base {
int GlobalMaxLogVerbosityLevel();
class LogMessage { class LogMessage {
public: public:
class Voidify { class Voidify {
@ -61,18 +82,17 @@ class LogMessage {
void operator&(std::ostream&) {} void operator&(std::ostream&) {}
}; };
LogMessage(const char* file, int line); LogMessage(const char* file, int line, int verbosity_level);
~LogMessage(); ~LogMessage();
LogMessage& base() { return *this; }
std::ostream& stream() { return stream_; } std::ostream& stream() { return stream_; }
static std::ostream* swallow_stream; static std::ostream* swallow_stream;
protected: protected:
const char* file_; const char* file_;
const int line_; int line_;
int verbosity_level_;
std::ostringstream stream_; std::ostringstream stream_;
}; };

View File

@ -86,7 +86,7 @@ void TaskRunner::RunTasks() {
auto [from, task_cb] = task; auto [from, task_cb] = task;
#if 0 #if 0
LOG << __func__ << " from: " << LOCATION(from); LOG(0) << __func__ << " from: " << LOCATION(from);
#endif #endif
task_cb(); task_cb();

View File

@ -1343,7 +1343,7 @@ class Matrix4 {
M_x_RotZ(angles[2]); M_x_RotZ(angles[2]);
break; break;
default: default:
NOTREACHED; NOTREACHED();
} }
} }
@ -1534,7 +1534,7 @@ class Matrix4 {
break; break;
} }
default: default:
NOTREACHED; NOTREACHED();
} }
return -angles; return -angles;
} }

View File

@ -58,17 +58,17 @@ bool Demo::PreInitialize() {
Engine::Get().AsyncLoadSound("boss_music", "Game_2_Boss.mp3", true); Engine::Get().AsyncLoadSound("boss_music", "Game_2_Boss.mp3", true);
if (!enemy_.PreInitialize()) { if (!enemy_.PreInitialize()) {
LOG << "Failed to create the enemy."; LOG(0) << "Failed to create the enemy.";
return false; return false;
} }
if (!player_.PreInitialize()) { if (!player_.PreInitialize()) {
LOG << "Failed to create the enemy."; LOG(0) << "Failed to create the enemy.";
return false; return false;
} }
if (!menu_.PreInitialize()) { if (!menu_.PreInitialize()) {
LOG << "Failed to create the menu."; LOG(0) << "Failed to create the menu.";
return false; return false;
} }
@ -79,32 +79,32 @@ bool Demo::Initialize() {
saved_data_.Load(kSaveFileName); saved_data_.Load(kSaveFileName);
if (!sky_.Create(false)) { if (!sky_.Create(false)) {
LOG << "Could not create the sky."; LOG(0) << "Could not create the sky.";
return false; return false;
} }
if (!enemy_.Initialize()) { if (!enemy_.Initialize()) {
LOG << "Failed to create the enemy."; LOG(0) << "Failed to create the enemy.";
return false; return false;
} }
if (!player_.Initialize()) { if (!player_.Initialize()) {
LOG << "Failed to create the enemy."; LOG(0) << "Failed to create the enemy.";
return false; return false;
} }
if (!hud_.Initialize()) { if (!hud_.Initialize()) {
LOG << "Failed to create the hud."; LOG(0) << "Failed to create the hud.";
return false; return false;
} }
if (!menu_.Initialize()) { if (!menu_.Initialize()) {
LOG << "Failed to create the menu."; LOG(0) << "Failed to create the menu.";
return false; return false;
} }
if (!credits_.Initialize()) { if (!credits_.Initialize()) {
LOG << "Failed to create the credits."; LOG(0) << "Failed to create the credits.";
return false; return false;
} }
@ -191,7 +191,7 @@ void Demo::ContextLost() {
void Demo::LostFocus() {} void Demo::LostFocus() {}
void Demo::GainedFocus(bool from_interstitial_ad) { void Demo::GainedFocus(bool from_interstitial_ad) {
DLOG << __func__ << " from_interstitial_ad: " << from_interstitial_ad; DLOG(0) << __func__ << " from_interstitial_ad: " << from_interstitial_ad;
if (!from_interstitial_ad) { if (!from_interstitial_ad) {
// if (saved_data_.root().get(kLaunchCount, Json::Value(0)).asInt() > // if (saved_data_.root().get(kLaunchCount, Json::Value(0)).asInt() >
// kLaunchCountBeforeAd) // kLaunchCountBeforeAd)
@ -327,7 +327,7 @@ void Demo::UpdateMenuState(float delta_time) {
Engine::Get().Exit(); Engine::Get().Exit();
break; break;
default: default:
NOTREACHED << "- Unknown menu option: " << menu_.selected_option(); NOTREACHED() << "- Unknown menu option: " << menu_.selected_option();
} }
} }
@ -411,7 +411,7 @@ void Demo::StartNextStage(bool boss) {
waiting_for_next_wave_ = true; waiting_for_next_wave_ = true;
hud_.SetProgress(wave_ > 0 ? 0 : 1); hud_.SetProgress(wave_ > 0 ? 0 : 1);
DLOG_IF(wave_ > 0 && stage_time_ > 0) DLOG_IF(0, wave_ > 0 && stage_time_ > 0)
<< "wave: " << wave_ << " time: " << stage_time_ / 60.0f; << "wave: " << wave_ << " time: " << stage_time_ / 60.0f;
stage_time_ = 0; stage_time_ = 0;
@ -432,7 +432,7 @@ void Demo::StartNextStage(bool boss) {
music_.Stop(10); music_.Stop(10);
} }
boss_fight_ = true; boss_fight_ = true;
DLOG << "Boss fight."; DLOG(0) << "Boss fight.";
} else { } else {
size_t bonus_factor = [&]() -> size_t { size_t bonus_factor = [&]() -> size_t {
if (wave_ <= 3) if (wave_ <= 3)
@ -444,8 +444,8 @@ void Demo::StartNextStage(bool boss) {
return 100; return 100;
}(); }();
size_t bonus_score = wave_score_ * (bonus_factor - 1); size_t bonus_score = wave_score_ * (bonus_factor - 1);
DLOG << "total_score_" << total_score_ << " wave " << wave_ DLOG(0) << "total_score_" << total_score_ << " wave " << wave_
<< " score: " << wave_score_ << " bonus: " << bonus_score; << " score: " << wave_score_ << " bonus: " << bonus_score;
if (bonus_score > 0) { if (bonus_score > 0) {
delta_score_ += bonus_score; delta_score_ += bonus_score;
@ -484,7 +484,7 @@ void Demo::StartNextStage(bool boss) {
total_enemies_ = 23.0897f * log((float)wave_ + 1.0f) - 10.0f; total_enemies_ = 23.0897f * log((float)wave_ + 1.0f) - 10.0f;
last_num_enemies_killed_ = 0; last_num_enemies_killed_ = 0;
boss_fight_ = false; boss_fight_ = false;
DLOG << "wave: " << wave_ << " total_enemies_: " << total_enemies_; DLOG(0) << "wave: " << wave_ << " total_enemies_: " << total_enemies_;
} }
hud_.SetScore(total_score_, true); hud_.SetScore(total_score_, true);
@ -535,7 +535,7 @@ void Demo::SetDelayedWork(float seconds, base::Closure cb) {
} }
void Demo::BenchmarkResult(int avarage_fps) { void Demo::BenchmarkResult(int avarage_fps) {
LOG << __func__ << " avarage_fps: " << avarage_fps; LOG(0) << __func__ << " avarage_fps: " << avarage_fps;
if (avarage_fps < 30) if (avarage_fps < 30)
sky_.Create(true); sky_.Create(true);
} }

View File

@ -510,7 +510,7 @@ void Enemy::OnWaveStarted(int wave, bool boss_fight) {
return 1.0f; return 1.0f;
return 1.6f; return 1.6f;
}(); }();
DLOG << "boss_spawn_time_factor_: " << boss_spawn_time_factor_; DLOG(0) << "boss_spawn_time_factor_: " << boss_spawn_time_factor_;
SpawnBoss(); SpawnBoss();
} }
} }
@ -601,7 +601,7 @@ void Enemy::SpawnUnit(EnemyType enemy_type,
e.sprite.Create("crate_tex", {8, 3}); e.sprite.Create("crate_tex", {8, 3});
break; break;
default: default:
NOTREACHED << "- Unkown enemy type: " << enemy_type; NOTREACHED() << "- Unkown enemy type: " << enemy_type;
} }
e.sprite.SetZOrder(11); e.sprite.SetZOrder(11);
@ -778,7 +778,7 @@ void Enemy::SpawnBoss() {
e.enemy_type = kEnemyType_Boss; e.enemy_type = kEnemyType_Boss;
e.damage_type = kDamageType_Any; e.damage_type = kDamageType_Any;
e.total_health = e.hit_points = 41.1283f * log((float)game->wave()) - 20.0f; e.total_health = e.hit_points = 41.1283f * log((float)game->wave()) - 20.0f;
DLOG << " Boss health: " << e.total_health; DLOG(0) << " Boss health: " << e.total_health;
Vector2f hit_box_pos = Vector2f hit_box_pos =
boss_.GetPosition() - boss_.GetSize() * Vector2f(0, 0.2f); boss_.GetPosition() - boss_.GetSize() * Vector2f(0, 0.2f);

View File

@ -19,7 +19,7 @@ bool Font::Load(const std::string& file_name) {
auto buffer = AssetFile::ReadWholeFile( auto buffer = AssetFile::ReadWholeFile(
file_name.c_str(), Engine::Get().GetRootPath().c_str(), &buffer_size); file_name.c_str(), Engine::Get().GetRootPath().c_str(), &buffer_size);
if (!buffer) { if (!buffer) {
LOG << "Failed to read font file."; LOG(0) << "Failed to read font file.";
return false; return false;
} }
@ -29,7 +29,7 @@ bool Font::Load(const std::string& file_name) {
// It's tighly packed. // It's tighly packed.
glyph_cache_ = std::make_unique<uint8_t[]>(kGlyphSize * kGlyphSize); glyph_cache_ = std::make_unique<uint8_t[]>(kGlyphSize * kGlyphSize);
if (!glyph_cache_) { if (!glyph_cache_) {
LOG << "Failed to allocate glyph cache."; LOG(0) << "Failed to allocate glyph cache.";
break; break;
} }
@ -38,7 +38,7 @@ bool Font::Load(const std::string& file_name) {
if (stbtt_BakeFontBitmap((unsigned char*)buffer.get(), 0, kFontHeight, if (stbtt_BakeFontBitmap((unsigned char*)buffer.get(), 0, kFontHeight,
glyph_cache_.get(), kGlyphSize, kGlyphSize, glyph_cache_.get(), kGlyphSize, kGlyphSize,
kFirstChar, kNumChars, glyph_info_) <= 0) { kFirstChar, kNumChars, glyph_info_) <= 0) {
LOG << "Failed to bake the glyph cache: "; LOG(0) << "Failed to bake the glyph cache: ";
glyph_cache_.reset(); glyph_cache_.reset();
break; break;
} }
@ -68,10 +68,10 @@ static void StretchBlit_I8_to_RGBA32(int dst_x0,
int dst_pitch, int dst_pitch,
const uint8_t* src_i, const uint8_t* src_i,
int src_pitch) { int src_pitch) {
// LOG << "-- StretchBlit: --"; // LOG(0) << "-- StretchBlit: --";
// LOG << "dst: rect(" << dst_x0 << ", " << dst_y0 << ")..(" // LOG(0) << "dst: rect(" << dst_x0 << ", " << dst_y0 << ")..("
// << dst_x1 << ".." << dst_y1 << "), pitch(" << dst_pitch << ")"; // << dst_x1 << ".." << dst_y1 << "), pitch(" << dst_pitch << ")";
// LOG << "src: rect(" << src_x0 << ", " << src_y0 << ")..(" // LOG(0) << "src: rect(" << src_x0 << ", " << src_y0 << ")..("
// << src_x1 << ".." << src_y1 << "), pitch(" << src_pitch << ")"; // << src_x1 << ".." << src_y1 << "), pitch(" << src_pitch << ")";
int dst_width = dst_x1 - dst_x0, dst_height = dst_y1 - dst_y0, int dst_width = dst_x1 - dst_x0, dst_height = dst_y1 - dst_y0,
@ -80,8 +80,8 @@ static void StretchBlit_I8_to_RGBA32(int dst_x0,
// int dst_dx = dst_width > 0 ? 1 : -1, // int dst_dx = dst_width > 0 ? 1 : -1,
// dst_dy = dst_height > 0 ? 1 : -1; // dst_dy = dst_height > 0 ? 1 : -1;
// LOG << "dst_width = " << dst_width << ", dst_height = " << dst_height; // LOG(0) << "dst_width = " << dst_width << ", dst_height = " << dst_height;
// LOG << "src_width = " << src_width << ", src_height = " << src_height; // LOG(0) << "src_width = " << src_width << ", src_height = " << src_height;
uint8_t* dst = dst_rgba + (dst_x0 + dst_y0 * dst_pitch) * 4; uint8_t* dst = dst_rgba + (dst_x0 + dst_y0 * dst_pitch) * 4;
const uint8_t* src = src_i + (src_x0 + src_y0 * src_pitch) * 1; const uint8_t* src = src_i + (src_x0 + src_y0 * src_pitch) * 1;
@ -159,7 +159,7 @@ void Font::CalculateBoundingBox(const std::string& text,
CalculateBoundingBox(text, x0, y0, x1, y1); CalculateBoundingBox(text, x0, y0, x1, y1);
width = x1 - x0; width = x1 - x0;
height = y1 - y0; height = y1 - y0;
// LOG << "width = " << width << ", height = " << height; // LOG(0) << "width = " << width << ", height = " << height;
} }
void Font::Print(int x, void Font::Print(int x,
@ -167,7 +167,7 @@ void Font::Print(int x,
const std::string& text, const std::string& text,
uint8_t* buffer, uint8_t* buffer,
int width) const { int width) const {
// LOG("Font::Print() = %s\n", text); // LOG(0)("Font::Print() = %s\n", text);
if (!glyph_cache_) if (!glyph_cache_)
return; return;
@ -184,7 +184,7 @@ void Font::Print(int x,
stbtt_GetBakedQuad(glyph_info_, kGlyphSize, kGlyphSize, *ptr - kFirstChar, stbtt_GetBakedQuad(glyph_info_, kGlyphSize, kGlyphSize, *ptr - kFirstChar,
&fx, &fy, &q, 1); &fx, &fy, &q, 1);
// LOG("-- glyph --\nxy = (%f %f) .. (%f %f)\nuv = (%f %f) .. (%f %f)\n", // LOG(0)("-- glyph --\nxy = (%f %f) .. (%f %f)\nuv = (%f %f) .. (%f %f)\n",
// q.x0, q.y0, q.x1, q.y1, q.s0, q.t0, q.s1, q.t1); // q.x0, q.y0, q.x1, q.y1, q.s0, q.t0, q.s1, q.t1);
int ix0 = (int)q.x0, iy0 = (int)q.y0, ix1 = (int)q.x1, iy1 = (int)q.y1, int ix0 = (int)q.x0, iy0 = (int)q.y0, ix1 = (int)q.x1, iy1 = (int)q.y1,

View File

@ -138,7 +138,7 @@ bool Image::Load(const std::string& file_name) {
auto file_buffer = AssetFile::ReadWholeFile( auto file_buffer = AssetFile::ReadWholeFile(
file_name.c_str(), Engine::Get().GetRootPath().c_str(), &buffer_size); file_name.c_str(), Engine::Get().GetRootPath().c_str(), &buffer_size);
if (!file_buffer) { if (!file_buffer) {
LOG << "Failed to read file: " << file_name; LOG(0) << "Failed to read file: " << file_name;
return false; return false;
} }
@ -146,16 +146,16 @@ bool Image::Load(const std::string& file_name) {
buffer_.reset((uint8_t*)stbi_load_from_memory( buffer_.reset((uint8_t*)stbi_load_from_memory(
(const stbi_uc*)file_buffer.get(), buffer_size, &w, &h, &c, 0)); (const stbi_uc*)file_buffer.get(), buffer_size, &w, &h, &c, 0));
if (!buffer_) { if (!buffer_) {
LOG << "Failed to load image file: " << file_name; LOG(0) << "Failed to load image file: " << file_name;
return false; return false;
} }
LOG << "Loaded " << file_name << ". number of color components: " << c; LOG(0) << "Loaded " << file_name << ". number of color components: " << c;
uint8_t* converted_buffer = NULL; uint8_t* converted_buffer = NULL;
switch (c) { switch (c) {
case 1: case 1:
// LOG("Converting image from 1 to 4 channels.\n"); // LOG(0)("Converting image from 1 to 4 channels.\n");
// Assume it's an intensity, duplicate it to RGB and fill A with opaque. // Assume it's an intensity, duplicate it to RGB and fill A with opaque.
converted_buffer = converted_buffer =
(uint8_t*)AlignedAlloc<16>(w * h * 4 * sizeof(uint8_t)); (uint8_t*)AlignedAlloc<16>(w * h * 4 * sizeof(uint8_t));
@ -168,7 +168,7 @@ bool Image::Load(const std::string& file_name) {
break; break;
case 3: case 3:
// LOG("Converting image from 3 to 4 channels.\n"); // LOG(0)("Converting image from 3 to 4 channels.\n");
// Add an opaque channel. // Add an opaque channel.
converted_buffer = converted_buffer =
(uint8_t*)AlignedAlloc<16>(w * h * 4 * sizeof(uint8_t)); (uint8_t*)AlignedAlloc<16>(w * h * 4 * sizeof(uint8_t));
@ -185,8 +185,8 @@ bool Image::Load(const std::string& file_name) {
case 2: case 2:
default: default:
LOG << "Image had unsuitable number of color components: " << c << " " LOG(0) << "Image had unsuitable number of color components: " << c << " "
<< file_name; << file_name;
buffer_.reset(); buffer_.reset();
return false; return false;
} }
@ -234,8 +234,8 @@ void Image::ConvertToPow2() {
int new_width = RoundUpToPow2(width_); int new_width = RoundUpToPow2(width_);
int new_height = RoundUpToPow2(height_); int new_height = RoundUpToPow2(height_);
if ((new_width != width_) || (new_height != height_)) { if ((new_width != width_) || (new_height != height_)) {
LOG << "Converting image from (" << width_ << ", " << height_ << ") to (" LOG(0) << "Converting image from (" << width_ << ", " << height_ << ") to ("
<< new_width << ", " << new_height << ")"; << new_width << ", " << new_height << ")";
int bigger_size = new_width * new_height * 4 * sizeof(uint8_t); int bigger_size = new_width * new_height * 4 * sizeof(uint8_t);
uint8_t* bigger_buffer = (uint8_t*)AlignedAlloc<16>(bigger_size); uint8_t* bigger_buffer = (uint8_t*)AlignedAlloc<16>(bigger_size);
@ -292,7 +292,7 @@ bool Image::Compress() {
return false; return false;
} }
LOG << "Compressing image. Format: " << format_; LOG(0) << "Compressing image. Format: " << format_;
unsigned compressedSize = GetSize(); unsigned compressedSize = GetSize();
uint8_t* compressedBuffer = uint8_t* compressedBuffer =

View File

@ -22,7 +22,7 @@ bool Mesh::Create(Primitive primitive,
num_indices_ = num_indices; num_indices_ = num_indices;
if (!ParseVertexDescription(vertex_description, vertex_description_)) { if (!ParseVertexDescription(vertex_description, vertex_description_)) {
LOG << "Failed to parse vertex description."; LOG(0) << "Failed to parse vertex description.";
return false; return false;
} }
@ -50,7 +50,7 @@ bool Mesh::Load(const std::string& file_name) {
Engine::Get().GetRootPath().c_str(), Engine::Get().GetRootPath().c_str(),
&buffer_size, true); &buffer_size, true);
if (!json_mesh) { if (!json_mesh) {
LOG << "Failed to read file: " << file_name; LOG(0) << "Failed to read file: " << file_name;
return false; return false;
} }
@ -60,7 +60,7 @@ bool Mesh::Load(const std::string& file_name) {
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
if (!reader->parse(json_mesh.get(), json_mesh.get() + buffer_size, &root, if (!reader->parse(json_mesh.get(), json_mesh.get() + buffer_size, &root,
&err)) { &err)) {
LOG << "Failed to load mesh. Json parser error: " << err; LOG(0) << "Failed to load mesh. Json parser error: " << err;
return false; return false;
} }
@ -70,7 +70,7 @@ bool Mesh::Load(const std::string& file_name) {
} else if (primitive_str == "TriangleStrip") { } else if (primitive_str == "TriangleStrip") {
primitive_ = kPrimitive_TriangleStrip; primitive_ = kPrimitive_TriangleStrip;
} else { } else {
LOG << "Failed to load mesh. Invalid primitive: " << primitive_str; LOG(0) << "Failed to load mesh. Invalid primitive: " << primitive_str;
return false; return false;
} }
@ -78,7 +78,7 @@ bool Mesh::Load(const std::string& file_name) {
if (!ParseVertexDescription(root["vertex_description"].asString(), if (!ParseVertexDescription(root["vertex_description"].asString(),
vertex_description_)) { vertex_description_)) {
LOG << "Failed to parse vertex description."; LOG(0) << "Failed to parse vertex description.";
return false; return false;
} }
@ -90,18 +90,19 @@ bool Mesh::Load(const std::string& file_name) {
const Json::Value vertices = root["vertices"]; const Json::Value vertices = root["vertices"];
if (vertices.size() != array_size) { if (vertices.size() != array_size) {
LOG << "Failed to load mesh. Vertex array size: " << vertices.size() LOG(0) << "Failed to load mesh. Vertex array size: " << vertices.size()
<< ", expected " << array_size; << ", expected " << array_size;
return false; return false;
} }
int vertex_buffer_size = GetVertexSize() * num_vertices_; int vertex_buffer_size = GetVertexSize() * num_vertices_;
if (vertex_buffer_size <= 0) { if (vertex_buffer_size <= 0) {
LOG << "Failed to load mesh. Invalid vertex size."; LOG(0) << "Failed to load mesh. Invalid vertex size.";
return false; return false;
} }
LOG << "Loaded " << file_name << ". Vertex array size: " << vertices.size(); LOG(0) << "Loaded " << file_name
<< ". Vertex array size: " << vertices.size();
vertices_ = std::make_unique<char[]>(vertex_buffer_size); vertices_ = std::make_unique<char[]>(vertex_buffer_size);
@ -131,7 +132,7 @@ bool Mesh::Load(const std::string& file_name) {
*((unsigned short*)dst) = (unsigned short)vertices[i].asUInt(); *((unsigned short*)dst) = (unsigned short)vertices[i].asUInt();
break; break;
default: default:
NOTREACHED << "- Unknown data type: " << data_type; NOTREACHED() << "- Unknown data type: " << data_type;
} }
dst += type_size; dst += type_size;
++i; ++i;

View File

@ -86,7 +86,7 @@ bool ShaderSource::Load(const std::string& name) {
if (!fragment_source_) if (!fragment_source_)
return false; return false;
LOG << "Loaded " << name; LOG(0) << "Loaded " << name;
return true; return true;
} }
@ -99,7 +99,7 @@ size_t ShaderSource::LoadInternal(const std::string& name,
auto source = AssetFile::ReadWholeFile( auto source = AssetFile::ReadWholeFile(
name.c_str(), Engine::Get().GetRootPath().c_str(), &size, true); name.c_str(), Engine::Get().GetRootPath().c_str(), &size, true);
if (!source) { if (!source) {
LOG << "Failed to read file: " << name; LOG(0) << "Failed to read file: " << name;
return 0; return 0;
} }

View File

@ -31,7 +31,7 @@ bool Sound::Load(const std::string& file_name, bool stream) {
Engine::Get().GetRootPath().c_str(), Engine::Get().GetRootPath().c_str(),
&buffer_size, false); &buffer_size, false);
if (!encoded_data_) { if (!encoded_data_) {
LOG << "Failed to read file: " << file_name; LOG(0) << "Failed to read file: " << file_name;
return false; return false;
} }
@ -44,15 +44,15 @@ bool Sound::Load(const std::string& file_name, bool stream) {
reinterpret_cast<uint8_t*>(encoded_data_.get()), reinterpret_cast<uint8_t*>(encoded_data_.get()),
buffer_size, MP3D_SEEK_TO_BYTE); buffer_size, MP3D_SEEK_TO_BYTE);
if (err) { if (err) {
LOG << "Failed to decode file: " << file_name << " error: " << err; LOG(0) << "Failed to decode file: " << file_name << " error: " << err;
return false; return false;
} }
LOG << (stream ? "Streaming " : "Loaded ") << file_name << ". " LOG(0) << (stream ? "Streaming " : "Loaded ") << file_name << ". "
<< mp3_dec_->samples << " samples, " << mp3_dec_->info.channels << mp3_dec_->samples << " samples, " << mp3_dec_->info.channels
<< " channels, " << mp3_dec_->info.hz << " hz, " << " channels, " << mp3_dec_->info.hz << " hz, "
<< "layer " << mp3_dec_->info.layer << ", " << "layer " << mp3_dec_->info.layer << ", "
<< "avg_bitrate_kbps " << mp3_dec_->info.bitrate_kbps; << "avg_bitrate_kbps " << mp3_dec_->info.bitrate_kbps;
SetAudioConfig(mp3_dec_->info.channels, mp3_dec_->info.hz); SetAudioConfig(mp3_dec_->info.channels, mp3_dec_->info.hz);
@ -120,7 +120,7 @@ void Sound::StreamInternal(size_t num_samples, bool loop) {
size_t samples_read = size_t samples_read =
mp3dec_ex_read(mp3_dec_.get(), buffer.get(), num_samples); mp3dec_ex_read(mp3_dec_.get(), buffer.get(), num_samples);
if (samples_read != num_samples && mp3_dec_->last_error) { if (samples_read != num_samples && mp3_dec_->last_error) {
LOG << "mp3 decode error: " << mp3_dec_->last_error; LOG(0) << "mp3 decode error: " << mp3_dec_->last_error;
break; break;
} }

View File

@ -256,7 +256,7 @@ void AudioMixer::RenderAudio(float* output_buffer, size_t num_frames) {
std::bind(&AudioMixer::DoStream, this, *it, flags & kLoop), std::bind(&AudioMixer::DoStream, this, *it, flags & kLoop),
true); true);
} else { } else {
DLOG << "Mixer buffer underrun!"; DLOG(0) << "Mixer buffer underrun!";
} }
} }
} }

View File

@ -14,7 +14,7 @@ AudioSinkAlsa::AudioSinkAlsa(AudioSink::Delegate* delegate)
: delegate_(delegate) {} : delegate_(delegate) {}
AudioSinkAlsa::~AudioSinkAlsa() { AudioSinkAlsa::~AudioSinkAlsa() {
LOG << "Shutting down audio."; LOG(0) << "Shutting down audio.";
TerminateAudioThread(); TerminateAudioThread();
snd_pcm_drop(device_); snd_pcm_drop(device_);
@ -22,7 +22,7 @@ AudioSinkAlsa::~AudioSinkAlsa() {
} }
bool AudioSinkAlsa::Initialize() { bool AudioSinkAlsa::Initialize() {
LOG << "Initializing audio."; LOG(0) << "Initializing audio.";
int err; int err;
@ -33,7 +33,7 @@ bool AudioSinkAlsa::Initialize() {
// direct hardware device with software format conversion. // direct hardware device with software format conversion.
if ((err = snd_pcm_open(&device_, "default", SND_PCM_STREAM_PLAYBACK, 0)) < if ((err = snd_pcm_open(&device_, "default", SND_PCM_STREAM_PLAYBACK, 0)) <
0) { 0) {
LOG << "Cannot open audio device. Error: " << snd_strerror(err); LOG(0) << "Cannot open audio device. Error: " << snd_strerror(err);
return false; return false;
} }
@ -43,39 +43,40 @@ bool AudioSinkAlsa::Initialize() {
// Init hw_params with full configuration space. // Init hw_params with full configuration space.
if ((err = snd_pcm_hw_params_any(device_, hw_params)) < 0) { if ((err = snd_pcm_hw_params_any(device_, hw_params)) < 0) {
LOG << "Cannot initialize hardware parameter structure. Error: " LOG(0) << "Cannot initialize hardware parameter structure. Error: "
<< snd_strerror(err); << snd_strerror(err);
break; break;
} }
if ((err = snd_pcm_hw_params_set_access( if ((err = snd_pcm_hw_params_set_access(
device_, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) { device_, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
LOG << "Cannot set access type. Error: " << snd_strerror(err); LOG(0) << "Cannot set access type. Error: " << snd_strerror(err);
break; break;
} }
if ((err = snd_pcm_hw_params_set_format(device_, hw_params, if ((err = snd_pcm_hw_params_set_format(device_, hw_params,
SND_PCM_FORMAT_FLOAT)) < 0) { SND_PCM_FORMAT_FLOAT)) < 0) {
LOG << "Cannot set sample format. Error: " << snd_strerror(err); LOG(0) << "Cannot set sample format. Error: " << snd_strerror(err);
break; break;
} }
// Disable software resampler. // Disable software resampler.
if ((err = snd_pcm_hw_params_set_rate_resample(device_, hw_params, 0)) < if ((err = snd_pcm_hw_params_set_rate_resample(device_, hw_params, 0)) <
0) { 0) {
LOG << "Cannot disbale software resampler. Error: " << snd_strerror(err); LOG(0) << "Cannot disbale software resampler. Error: "
<< snd_strerror(err);
break; break;
} }
unsigned sample_rate = 48000; unsigned sample_rate = 48000;
if ((err = snd_pcm_hw_params_set_rate_near(device_, hw_params, &sample_rate, if ((err = snd_pcm_hw_params_set_rate_near(device_, hw_params, &sample_rate,
0)) < 0) { 0)) < 0) {
LOG << "Cannot set sample rate. Error: " << snd_strerror(err); LOG(0) << "Cannot set sample rate. Error: " << snd_strerror(err);
break; break;
} }
if ((err = snd_pcm_hw_params_set_channels(device_, hw_params, 2)) < 0) { if ((err = snd_pcm_hw_params_set_channels(device_, hw_params, 2)) < 0) {
LOG << "Cannot set channel count. Error: " << snd_strerror(err); LOG(0) << "Cannot set channel count. Error: " << snd_strerror(err);
break; break;
} }
@ -83,26 +84,26 @@ bool AudioSinkAlsa::Initialize() {
unsigned period_time = 4000; unsigned period_time = 4000;
if ((err = snd_pcm_hw_params_set_period_time_near(device_, hw_params, if ((err = snd_pcm_hw_params_set_period_time_near(device_, hw_params,
&period_time, 0)) < 0) { &period_time, 0)) < 0) {
LOG << "Cannot set periods. Error: " << snd_strerror(err); LOG(0) << "Cannot set periods. Error: " << snd_strerror(err);
break; break;
} }
unsigned periods = 3; unsigned periods = 3;
if ((err = snd_pcm_hw_params_set_periods_near(device_, hw_params, &periods, if ((err = snd_pcm_hw_params_set_periods_near(device_, hw_params, &periods,
0)) < 0) { 0)) < 0) {
LOG << "Cannot set periods. Error: " << snd_strerror(err); LOG(0) << "Cannot set periods. Error: " << snd_strerror(err);
break; break;
} }
// Apply HW parameter settings to PCM device and prepare device. // Apply HW parameter settings to PCM device and prepare device.
if ((err = snd_pcm_hw_params(device_, hw_params)) < 0) { if ((err = snd_pcm_hw_params(device_, hw_params)) < 0) {
LOG << "Cannot set parameters. Error: " << snd_strerror(err); LOG(0) << "Cannot set parameters. Error: " << snd_strerror(err);
break; break;
} }
if ((err = snd_pcm_prepare(device_)) < 0) { if ((err = snd_pcm_prepare(device_)) < 0) {
LOG << "Cannot prepare audio interface for use. Error: " LOG(0) << "Cannot prepare audio interface for use. Error: "
<< snd_strerror(err); << snd_strerror(err);
break; break;
} }
@ -120,15 +121,15 @@ bool AudioSinkAlsa::Initialize() {
snd_pcm_hw_params_get_periods(hw_params, &periods, nullptr); snd_pcm_hw_params_get_periods(hw_params, &periods, nullptr);
snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size); snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
LOG << "Alsa Audio:"; LOG(0) << "Alsa Audio:";
LOG << " access: " << snd_pcm_access_name(access); LOG(0) << " access: " << snd_pcm_access_name(access);
LOG << " format: " << snd_pcm_format_name(format); LOG(0) << " format: " << snd_pcm_format_name(format);
LOG << " channel count: " << num_channels; LOG(0) << " channel count: " << num_channels;
LOG << " sample rate: " << sample_rate; LOG(0) << " sample rate: " << sample_rate;
LOG << " period size: " << period_size; LOG(0) << " period size: " << period_size;
LOG << " period time: " << period_time; LOG(0) << " period time: " << period_time;
LOG << " periods: " << periods; LOG(0) << " periods: " << periods;
LOG << " buffer_size: " << buffer_size; LOG(0) << " buffer_size: " << buffer_size;
num_channels_ = num_channels; num_channels_ = num_channels;
sample_rate_ = sample_rate; sample_rate_ = sample_rate;
@ -158,7 +159,7 @@ size_t AudioSinkAlsa::GetHardwareSampleRate() {
void AudioSinkAlsa::StartAudioThread() { void AudioSinkAlsa::StartAudioThread() {
DCHECK(!audio_thread_.joinable()); DCHECK(!audio_thread_.joinable());
LOG << "Starting audio thread."; LOG(0) << "Starting audio thread.";
terminate_audio_thread_.store(false, std::memory_order_relaxed); terminate_audio_thread_.store(false, std::memory_order_relaxed);
suspend_audio_thread_.store(false, std::memory_order_relaxed); suspend_audio_thread_.store(false, std::memory_order_relaxed);
audio_thread_ = std::thread(&AudioSinkAlsa::AudioThreadMain, this); audio_thread_ = std::thread(&AudioSinkAlsa::AudioThreadMain, this);
@ -168,7 +169,7 @@ void AudioSinkAlsa::TerminateAudioThread() {
if (!audio_thread_.joinable()) if (!audio_thread_.joinable())
return; return;
LOG << "Terminating audio thread"; LOG(0) << "Terminating audio thread";
terminate_audio_thread_.store(true, std::memory_order_relaxed); terminate_audio_thread_.store(true, std::memory_order_relaxed);
suspend_audio_thread_.store(true, std::memory_order_relaxed); suspend_audio_thread_.store(true, std::memory_order_relaxed);
audio_thread_.join(); audio_thread_.join();
@ -192,7 +193,7 @@ void AudioSinkAlsa::AudioThreadMain() {
while (snd_pcm_writei(device_, buffer.get(), num_frames) < 0) { while (snd_pcm_writei(device_, buffer.get(), num_frames) < 0) {
snd_pcm_prepare(device_); snd_pcm_prepare(device_);
DLOG << "Alsa buffer underrun!"; DLOG(0) << "Alsa buffer underrun!";
} }
} }
} }

View File

@ -11,12 +11,12 @@ AudioSinkOboe::AudioSinkOboe(AudioSink::Delegate* delegate)
: callback_(std::make_unique<StreamCallback>(this)), delegate_(delegate) {} : callback_(std::make_unique<StreamCallback>(this)), delegate_(delegate) {}
AudioSinkOboe::~AudioSinkOboe() { AudioSinkOboe::~AudioSinkOboe() {
LOG << "Shutting down audio."; LOG(0) << "Shutting down audio.";
stream_->stop(); stream_->stop();
} }
bool AudioSinkOboe::Initialize() { bool AudioSinkOboe::Initialize() {
LOG << "Initializing audio."; LOG(0) << "Initializing audio.";
return RestartStream(); return RestartStream();
} }
@ -49,7 +49,7 @@ oboe::DataCallbackResult AudioSinkOboe::StreamCallback::onAudioReady(
void AudioSinkOboe::StreamCallback::onErrorAfterClose( void AudioSinkOboe::StreamCallback::onErrorAfterClose(
oboe::AudioStream* oboe_stream, oboe::AudioStream* oboe_stream,
oboe::Result error) { oboe::Result error) {
LOG << "Error after close. Error: " << oboe::convertToText(error); LOG(0) << "Error after close. Error: " << oboe::convertToText(error);
audio_sink_->RestartStream(); audio_sink_->RestartStream();
} }
@ -66,15 +66,15 @@ bool AudioSinkOboe::RestartStream() {
->setCallback(callback_.get()) ->setCallback(callback_.get())
->openManagedStream(stream_); ->openManagedStream(stream_);
LOG << "Oboe Audio Stream:"; LOG(0) << "Oboe Audio Stream:";
LOG << " performance mode: " << (int)stream_->getPerformanceMode(); LOG(0) << " performance mode: " << (int)stream_->getPerformanceMode();
LOG << " format: " << (int)stream_->getFormat(); LOG(0) << " format: " << (int)stream_->getFormat();
LOG << " channel count: " << stream_->getChannelCount(); LOG(0) << " channel count: " << stream_->getChannelCount();
LOG << " sample rate: " << stream_->getSampleRate(); LOG(0) << " sample rate: " << stream_->getSampleRate();
if (result != oboe::Result::OK) { if (result != oboe::Result::OK) {
LOG << "Failed to create the playback stream. Error: " LOG(0) << "Failed to create the playback stream. Error: "
<< oboe::convertToText(result); << oboe::convertToText(result);
return false; return false;
} }

View File

@ -49,7 +49,7 @@ Engine::Engine(Platform* platform)
} }
Engine::~Engine() { Engine::~Engine() {
LOG << "Shutting down engine."; LOG(0) << "Shutting down engine.";
thread_pool_.CancelTasks(); thread_pool_.CancelTasks();
thread_pool_.Shutdown(); thread_pool_.Shutdown();
@ -107,7 +107,7 @@ void Engine::Run() {
} }
void Engine::Initialize() { void Engine::Initialize() {
LOG << "Initializing engine."; LOG(0) << "Initializing engine.";
thread_pool_.Initialize(); thread_pool_.Initialize();
@ -116,17 +116,17 @@ void Engine::Initialize() {
// Normalize viewport. // Normalize viewport.
if (GetScreenWidth() > GetScreenHeight()) { if (GetScreenWidth() > GetScreenHeight()) {
float aspect_ratio = (float)GetScreenWidth() / (float)GetScreenHeight(); float aspect_ratio = (float)GetScreenWidth() / (float)GetScreenHeight();
LOG << "aspect ratio: " << aspect_ratio; LOG(0) << "aspect ratio: " << aspect_ratio;
screen_size_ = {aspect_ratio * 2.0f, 2.0f}; screen_size_ = {aspect_ratio * 2.0f, 2.0f};
projection_.CreateOrthoProjection(-aspect_ratio, aspect_ratio, -1.0f, 1.0f); projection_.CreateOrthoProjection(-aspect_ratio, aspect_ratio, -1.0f, 1.0f);
} else { } else {
float aspect_ratio = (float)GetScreenHeight() / (float)GetScreenWidth(); float aspect_ratio = (float)GetScreenHeight() / (float)GetScreenWidth();
LOG << "aspect_ratio: " << aspect_ratio; LOG(0) << "aspect_ratio: " << aspect_ratio;
screen_size_ = {2.0f, aspect_ratio * 2.0f}; screen_size_ = {2.0f, aspect_ratio * 2.0f};
projection_.CreateOrthoProjection(-1.0, 1.0, -aspect_ratio, aspect_ratio); projection_.CreateOrthoProjection(-1.0, 1.0, -aspect_ratio, aspect_ratio);
} }
LOG << "image scale factor: " << GetImageScaleFactor(); LOG(0) << "image scale factor: " << GetImageScaleFactor();
system_font_ = std::make_unique<Font>(); system_font_ = std::make_unique<Font>();
system_font_->Load("engine/RobotoMono-Regular.ttf"); system_font_->Load("engine/RobotoMono-Regular.ttf");
@ -257,7 +257,7 @@ void Engine::SetImageSource(const std::string& asset_name,
CreateImageCB create_image, CreateImageCB create_image,
bool persistent) { bool persistent) {
if (textures_.contains(asset_name) && textures_[asset_name].use_count > 0) { if (textures_.contains(asset_name) && textures_[asset_name].use_count > 0) {
DLOG << "Texture in use: " << asset_name; DLOG(0) << "Texture in use: " << asset_name;
return; return;
} }
@ -268,7 +268,7 @@ void Engine::SetImageSource(const std::string& asset_name,
void Engine::RefreshImage(const std::string& asset_name) { void Engine::RefreshImage(const std::string& asset_name) {
auto it = textures_.find(asset_name); auto it = textures_.find(asset_name);
if (it == textures_.end()) { if (it == textures_.end()) {
DLOG << "Texture not found: " << asset_name; DLOG(0) << "Texture not found: " << asset_name;
return; return;
} }
@ -282,7 +282,7 @@ void Engine::RefreshImage(const std::string& asset_name) {
Texture* Engine::AcquireTexture(const std::string& asset_name) { Texture* Engine::AcquireTexture(const std::string& asset_name) {
auto it = textures_.find(asset_name); auto it = textures_.find(asset_name);
if (it == textures_.end()) { if (it == textures_.end()) {
DLOG << "Texture not found: " << asset_name; DLOG(0) << "Texture not found: " << asset_name;
return nullptr; return nullptr;
} }
@ -298,7 +298,7 @@ Texture* Engine::AcquireTexture(const std::string& asset_name) {
void Engine::ReleaseTexture(const std::string& asset_name) { void Engine::ReleaseTexture(const std::string& asset_name) {
auto it = textures_.find(asset_name); auto it = textures_.find(asset_name);
if (it == textures_.end()) { if (it == textures_.end()) {
DLOG << "Texture not found: " << asset_name; DLOG(0) << "Texture not found: " << asset_name;
return; return;
} }
@ -311,7 +311,7 @@ void Engine::ReleaseTexture(const std::string& asset_name) {
void Engine::SetShaderSource(const std::string& asset_name, void Engine::SetShaderSource(const std::string& asset_name,
const std::string& file_name) { const std::string& file_name) {
if (shaders_.contains(asset_name)) { if (shaders_.contains(asset_name)) {
DLOG << "Shader already exists: " << asset_name; DLOG(0) << "Shader already exists: " << asset_name;
return; return;
} }
@ -321,7 +321,7 @@ void Engine::SetShaderSource(const std::string& asset_name,
Shader* Engine::GetShader(const std::string& asset_name) { Shader* Engine::GetShader(const std::string& asset_name) {
auto it = shaders_.find(asset_name); auto it = shaders_.find(asset_name);
if (it == shaders_.end()) { if (it == shaders_.end()) {
DLOG << "Shader not found: " << asset_name; DLOG(0) << "Shader not found: " << asset_name;
return nullptr; return nullptr;
} }
@ -339,7 +339,7 @@ void Engine::AsyncLoadSound(const std::string& asset_name,
const std::string& file_name, const std::string& file_name,
bool stream) { bool stream) {
if (audio_buses_.contains(asset_name)) { if (audio_buses_.contains(asset_name)) {
DLOG << "AudioBus already exists: " << asset_name; DLOG(0) << "AudioBus already exists: " << asset_name;
return; return;
} }
@ -355,7 +355,7 @@ void Engine::AsyncLoadSound(const std::string& asset_name,
std::shared_ptr<AudioBus> Engine::GetAudioBus(const std::string& asset_name) { std::shared_ptr<AudioBus> Engine::GetAudioBus(const std::string& asset_name) {
auto it = audio_buses_.find(asset_name); auto it = audio_buses_.find(asset_name);
if (it == audio_buses_.end()) { if (it == audio_buses_.end()) {
DLOG << "AudioBus not found: " << asset_name; DLOG(0) << "AudioBus not found: " << asset_name;
return nullptr; return nullptr;
} }
@ -569,19 +569,21 @@ void Engine::CreateRendererInternal(RendererType type) {
type == RendererType::kOpenGL)) type == RendererType::kOpenGL))
return; return;
if (type == RendererType::kVulkan) if (type == RendererType::kVulkan) {
renderer_ = renderer_ =
std::make_unique<RendererVulkan>(std::bind(&Engine::ContextLost, this)); std::make_unique<RendererVulkan>(std::bind(&Engine::ContextLost, this));
else if (type == RendererType::kOpenGL) } else if (type == RendererType::kOpenGL) {
renderer_ = renderer_ =
std::make_unique<RendererOpenGL>(std::bind(&Engine::ContextLost, this)); std::make_unique<RendererOpenGL>(std::bind(&Engine::ContextLost, this));
else } else {
NOTREACHED; NOTREACHED();
}
bool result = renderer_->Initialize(platform_); bool result = renderer_->Initialize(platform_);
if (!result && type == RendererType::kVulkan) { if (!result && type == RendererType::kVulkan) {
LOG << "Failed to initialize " << renderer_->GetDebugName() << " renderer."; LOG(0) << "Failed to initialize " << renderer_->GetDebugName()
LOG << "Fallback to OpenGL renderer."; << " renderer.";
LOG(0) << "Fallback to OpenGL renderer.";
CreateRendererInternal(RendererType::kOpenGL); CreateRendererInternal(RendererType::kOpenGL);
return; return;
} }
@ -645,7 +647,7 @@ void Engine::CreateRenderResources() {
pass_through_shader_->Create(std::move(source), quad_->vertex_description(), pass_through_shader_->Create(std::move(source), quad_->vertex_description(),
quad_->primitive(), false); quad_->primitive(), false);
} else { } else {
LOG << "Could not create pass through shader."; LOG(0) << "Could not create pass through shader.";
} }
// Create the shader we can reuse for solid rendering. // Create the shader we can reuse for solid rendering.
@ -654,7 +656,7 @@ void Engine::CreateRenderResources() {
solid_shader_->Create(std::move(source), quad_->vertex_description(), solid_shader_->Create(std::move(source), quad_->vertex_description(),
quad_->primitive(), false); quad_->primitive(), false);
} else { } else {
LOG << "Could not create solid shader."; LOG(0) << "Could not create solid shader.";
} }
for (auto& t : textures_) { for (auto& t : textures_) {

View File

@ -27,7 +27,7 @@ bool PersistentData::Load(const std::string& file_name, StorageType type) {
ScopedFILE file; ScopedFILE file;
file.reset(fopen(file_path.c_str(), "r")); file.reset(fopen(file_path.c_str(), "r"));
if (!file) { if (!file) {
LOG << "Failed to open file " << file_path; LOG(0) << "Failed to open file " << file_path;
return false; return false;
} }
@ -41,8 +41,8 @@ bool PersistentData::Load(const std::string& file_name, StorageType type) {
buffer = std::make_unique<char[]>(size + 1); buffer = std::make_unique<char[]>(size + 1);
size_t bytes_read = fread(buffer.get(), 1, size, file.get()); size_t bytes_read = fread(buffer.get(), 1, size, file.get());
if (!bytes_read) { if (!bytes_read) {
LOG << "Failed to read a buffer of size: " << size << " from file " LOG(0) << "Failed to read a buffer of size: " << size << " from file "
<< file_path; << file_path;
return false; return false;
} }
buffer[size] = 0; buffer[size] = 0;
@ -52,7 +52,7 @@ bool PersistentData::Load(const std::string& file_name, StorageType type) {
Json::CharReaderBuilder builder; Json::CharReaderBuilder builder;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
if (!reader->parse(buffer.get(), buffer.get() + size, &root_, &err)) { if (!reader->parse(buffer.get(), buffer.get() + size, &root_, &err)) {
LOG << "Failed to parse save file. Json parser error: " << err; LOG(0) << "Failed to parse save file. Json parser error: " << err;
return false; return false;
} }
@ -86,13 +86,13 @@ bool PersistentData::SaveAs(const std::string& file_name, StorageType type) {
ScopedFILE file; ScopedFILE file;
file.reset(fopen(file_path.c_str(), "w")); file.reset(fopen(file_path.c_str(), "w"));
if (!file) { if (!file) {
LOG << "Failed to create file " << file_path; LOG(0) << "Failed to create file " << file_path;
return false; return false;
} }
std::string data = stream.str(); std::string data = stream.str();
if (fwrite(data.c_str(), data.size(), 1, file.get()) != 1) { if (fwrite(data.c_str(), data.size(), 1, file.get()) != 1) {
LOG << "Failed to write to file " << file_path; LOG(0) << "Failed to write to file " << file_path;
return false; return false;
} }

View File

@ -23,8 +23,8 @@ std::unique_ptr<char[]> AssetFile::ReadWholeFile(const std::string& file_name,
// Read all of it. // Read all of it.
size_t bytes_read = file.Read(buffer.get(), size); size_t bytes_read = file.Read(buffer.get(), size);
if (!bytes_read) { if (!bytes_read) {
LOG << "Failed to read a buffer of size: " << size << " from file " LOG(0) << "Failed to read a buffer of size: " << size << " from file "
<< file_name; << file_name;
return nullptr; return nullptr;
} }

View File

@ -16,14 +16,14 @@ bool AssetFile::Open(const std::string& file_name,
// Try to open the zip archive. // Try to open the zip archive.
archive_ = unzOpen(root_path.c_str()); archive_ = unzOpen(root_path.c_str());
if (!archive_) { if (!archive_) {
LOG << "Failed to open zip file: " << root_path; LOG(0) << "Failed to open zip file: " << root_path;
break; break;
} }
// Try to find the file. // Try to find the file.
std::string full_name = "assets/" + file_name; std::string full_name = "assets/" + file_name;
if (UNZ_OK != unzLocateFile(archive_, full_name.c_str(), 1)) { if (UNZ_OK != unzLocateFile(archive_, full_name.c_str(), 1)) {
LOG << "Failed to locate file in zip archive: " << file_name; LOG(0) << "Failed to locate file in zip archive: " << file_name;
break; break;
} }
@ -31,14 +31,14 @@ bool AssetFile::Open(const std::string& file_name,
unz_file_info info; unz_file_info info;
if (UNZ_OK != if (UNZ_OK !=
unzGetCurrentFileInfo(archive_, &info, NULL, 0, NULL, 0, NULL, 0)) { unzGetCurrentFileInfo(archive_, &info, NULL, 0, NULL, 0, NULL, 0)) {
LOG << "Failed to get file info: " << file_name; LOG(0) << "Failed to get file info: " << file_name;
break; break;
} }
uncompressed_size_ = info.uncompressed_size; uncompressed_size_ = info.uncompressed_size;
// Open the current file. // Open the current file.
if (UNZ_OK != unzOpenCurrentFile(archive_)) { if (UNZ_OK != unzOpenCurrentFile(archive_)) {
LOG << "Failed to open file: " << file_name; LOG(0) << "Failed to open file: " << file_name;
break; break;
} }

View File

@ -289,7 +289,7 @@ void Platform::HandleCmd(android_app* app, int32_t cmd) {
break; break;
case APP_CMD_INIT_WINDOW: case APP_CMD_INIT_WINDOW:
DLOG << "APP_CMD_INIT_WINDOW"; DLOG(0) << "APP_CMD_INIT_WINDOW";
if (app->window != NULL) { if (app->window != NULL) {
platform->SetFrameRate(60); platform->SetFrameRate(60);
if (platform->observer_) if (platform->observer_)
@ -298,13 +298,13 @@ void Platform::HandleCmd(android_app* app, int32_t cmd) {
break; break;
case APP_CMD_TERM_WINDOW: case APP_CMD_TERM_WINDOW:
DLOG << "APP_CMD_TERM_WINDOW"; DLOG(0) << "APP_CMD_TERM_WINDOW";
if (platform->observer_) if (platform->observer_)
platform->observer_->OnWindowDestroyed(); platform->observer_->OnWindowDestroyed();
break; break;
case APP_CMD_CONFIG_CHANGED: case APP_CMD_CONFIG_CHANGED:
DLOG << "APP_CMD_CONFIG_CHANGED"; DLOG(0) << "APP_CMD_CONFIG_CHANGED";
if (platform->app_->window != NULL && platform->observer_) if (platform->app_->window != NULL && platform->observer_)
platform->observer_->OnWindowResized( platform->observer_->OnWindowResized(
ANativeWindow_getWidth(app->window), ANativeWindow_getWidth(app->window),
@ -312,11 +312,11 @@ void Platform::HandleCmd(android_app* app, int32_t cmd) {
break; break;
case APP_CMD_STOP: case APP_CMD_STOP:
DLOG << "APP_CMD_STOP"; DLOG(0) << "APP_CMD_STOP";
break; break;
case APP_CMD_GAINED_FOCUS: case APP_CMD_GAINED_FOCUS:
DLOG << "APP_CMD_GAINED_FOCUS"; DLOG(0) << "APP_CMD_GAINED_FOCUS";
// platform->timer_.Reset(); // platform->timer_.Reset();
platform->has_focus_ = true; platform->has_focus_ = true;
if (platform->observer_) if (platform->observer_)
@ -325,35 +325,35 @@ void Platform::HandleCmd(android_app* app, int32_t cmd) {
break; break;
case APP_CMD_LOST_FOCUS: case APP_CMD_LOST_FOCUS:
DLOG << "APP_CMD_LOST_FOCUS"; DLOG(0) << "APP_CMD_LOST_FOCUS";
platform->has_focus_ = false; platform->has_focus_ = false;
if (platform->observer_) if (platform->observer_)
platform->observer_->LostFocus(); platform->observer_->LostFocus();
break; break;
case APP_CMD_LOW_MEMORY: case APP_CMD_LOW_MEMORY:
DLOG << "APP_CMD_LOW_MEMORY"; DLOG(0) << "APP_CMD_LOW_MEMORY";
break; break;
} }
} }
Platform::Platform(android_app* app) { Platform::Platform(android_app* app) {
LOG << "Initializing platform."; LOG(0) << "Initializing platform.";
app_ = app; app_ = app;
mobile_device_ = true; mobile_device_ = true;
root_path_ = ::GetApkPath(app->activity); root_path_ = ::GetApkPath(app->activity);
LOG << "Root path: " << root_path_.c_str(); LOG(0) << "Root path: " << root_path_.c_str();
data_path_ = ::GetDataPath(app->activity); data_path_ = ::GetDataPath(app->activity);
LOG << "Data path: " << data_path_.c_str(); LOG(0) << "Data path: " << data_path_.c_str();
shared_data_path_ = ::GetSharedDataPath(app->activity); shared_data_path_ = ::GetSharedDataPath(app->activity);
LOG << "Shared data path: " << shared_data_path_.c_str(); LOG(0) << "Shared data path: " << shared_data_path_.c_str();
device_dpi_ = ::GetDensityDpi(app); device_dpi_ = ::GetDensityDpi(app);
LOG << "Device DPI: " << device_dpi_; LOG(0) << "Device DPI: " << device_dpi_;
app->userData = reinterpret_cast<void*>(this); app->userData = reinterpret_cast<void*>(this);
app->onAppCmd = Platform::HandleCmd; app->onAppCmd = Platform::HandleCmd;
@ -375,7 +375,7 @@ Platform::Platform(android_app* app) {
} }
Platform::~Platform() { Platform::~Platform() {
LOG << "Shutting down platform."; LOG(0) << "Shutting down platform.";
} }
void Platform::Update() { void Platform::Update() {
@ -388,7 +388,7 @@ void Platform::Update() {
if (source != NULL) if (source != NULL)
source->process(app_, source); source->process(app_, source);
if (app_->destroyRequested != 0) { if (app_->destroyRequested != 0) {
LOG << "App destroy requested."; LOG(0) << "App destroy requested.";
should_exit_ = true; should_exit_ = true;
break; break;
} }

View File

@ -14,16 +14,16 @@ namespace eng {
void KaliberMain(Platform* platform); void KaliberMain(Platform* platform);
Platform::Platform() { Platform::Platform() {
LOG << "Initializing platform."; LOG(0) << "Initializing platform.";
root_path_ = "../../"; root_path_ = "../../";
LOG << "Root path: " << root_path_.c_str(); LOG(0) << "Root path: " << root_path_.c_str();
data_path_ = "./"; data_path_ = "./";
LOG << "Data path: " << data_path_.c_str(); LOG(0) << "Data path: " << data_path_.c_str();
shared_data_path_ = "./"; shared_data_path_ = "./";
LOG << "Shared data path: " << shared_data_path_.c_str(); LOG(0) << "Shared data path: " << shared_data_path_.c_str();
bool res = CreateWindow(800, 1205); bool res = CreateWindow(800, 1205);
CHECK(res) << "Failed to create window."; CHECK(res) << "Failed to create window.";
@ -36,7 +36,7 @@ Platform::Platform() {
} }
Platform::~Platform() { Platform::~Platform() {
LOG << "Shutting down platform."; LOG(0) << "Shutting down platform.";
DestroyWindow(); DestroyWindow();
} }
@ -111,8 +111,8 @@ bool Platform::CreateWindow(int width, int height) {
// Try to open the local display. // Try to open the local display.
display_ = XOpenDisplay(NULL); display_ = XOpenDisplay(NULL);
if (!display_) { if (!display_) {
LOG << "Can't connect to X server. Try to set the DISPLAY environment " LOG(0) << "Can't connect to X server. Try to set the DISPLAY environment "
"variable (hostname:number.screen_number)."; "variable (hostname:number.screen_number).";
return false; return false;
} }
@ -120,10 +120,10 @@ bool Platform::CreateWindow(int width, int height) {
XVisualInfo* visual_info = GetXVisualInfo(display_); XVisualInfo* visual_info = GetXVisualInfo(display_);
if (!visual_info) { if (!visual_info) {
LOG << "No appropriate visual found."; LOG(0) << "No appropriate visual found.";
return false; return false;
} }
LOG << "Visual " << (void*)visual_info->visualid << " selected"; LOG(0) << "Visual " << (void*)visual_info->visualid << " selected";
// Create the main window. // Create the main window.
XSetWindowAttributes window_attributes; XSetWindowAttributes window_attributes;

View File

@ -41,7 +41,7 @@ RendererOpenGL::~RendererOpenGL() {
} }
void RendererOpenGL::Shutdown() { void RendererOpenGL::Shutdown() {
LOG << "Shutting down renderer."; LOG(0) << "Shutting down renderer.";
is_initialized_ = false; is_initialized_ = false;
ShutdownInternal(); ShutdownInternal();
} }
@ -50,7 +50,7 @@ uint64_t RendererOpenGL::CreateGeometry(std::unique_ptr<Mesh> mesh) {
// Verify that we have a valid layout and get the total byte size per vertex. // Verify that we have a valid layout and get the total byte size per vertex.
GLuint vertex_size = mesh->GetVertexSize(); GLuint vertex_size = mesh->GetVertexSize();
if (!vertex_size) { if (!vertex_size) {
LOG << "Invalid vertex layout"; LOG(0) << "Invalid vertex layout";
return 0; return 0;
} }
@ -59,7 +59,7 @@ uint64_t RendererOpenGL::CreateGeometry(std::unique_ptr<Mesh> mesh) {
std::vector<GeometryOpenGL::Element> vertex_layout; std::vector<GeometryOpenGL::Element> vertex_layout;
if (!SetupVertexLayout(mesh->vertex_description(), vertex_size, if (!SetupVertexLayout(mesh->vertex_description(), vertex_size,
vertex_array_objects_, vertex_layout)) { vertex_array_objects_, vertex_layout)) {
LOG << "Invalid vertex layout"; LOG(0) << "Invalid vertex layout";
return 0; return 0;
} }
@ -212,7 +212,7 @@ void RendererOpenGL::UpdateTexture(uint64_t resource_id,
break; break;
#endif #endif
default: default:
NOTREACHED << "- Unhandled texure format: " << image->GetFormat(); NOTREACHED() << "- Unhandled texure format: " << image->GetFormat();
} }
glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, image->GetWidth(), glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, image->GetWidth(),
@ -230,7 +230,7 @@ void RendererOpenGL::UpdateTexture(uint64_t resource_id,
} }
if (err != GL_NO_ERROR) if (err != GL_NO_ERROR)
LOG << "GL ERROR after glCompressedTexImage2D: " << (int)err; LOG(0) << "GL ERROR after glCompressedTexImage2D: " << (int)err;
} else { } else {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->GetWidth(), glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->GetWidth(),
image->GetHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image->GetHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE,
@ -290,7 +290,7 @@ uint64_t RendererOpenGL::CreateShader(
char* buffer = (char*)malloc(length); char* buffer = (char*)malloc(length);
if (buffer) { if (buffer) {
glGetProgramInfoLog(id, length, NULL, buffer); glGetProgramInfoLog(id, length, NULL, buffer);
LOG << "Could not link program:\n" << buffer; LOG(0) << "Could not link program:\n" << buffer;
free(buffer); free(buffer);
} }
} }
@ -401,7 +401,7 @@ void RendererOpenGL::SetUniform(uint64_t resource_id,
} }
void RendererOpenGL::ContextLost() { void RendererOpenGL::ContextLost() {
LOG << "Context lost."; LOG(0) << "Context lost.";
DestroyAllResources(); DestroyAllResources();
context_lost_cb_(); context_lost_cb_();
@ -419,13 +419,13 @@ bool RendererOpenGL::InitCommon() {
reinterpret_cast<const char*>(glGetString(GL_RENDERER)); reinterpret_cast<const char*>(glGetString(GL_RENDERER));
const char* version = reinterpret_cast<const char*>(glGetString(GL_VERSION)); const char* version = reinterpret_cast<const char*>(glGetString(GL_VERSION));
LOG << "OpenGL:"; LOG(0) << "OpenGL:";
LOG << " vendor: " << (const char*)glGetString(GL_VENDOR); LOG(0) << " vendor: " << (const char*)glGetString(GL_VENDOR);
LOG << " renderer: " << renderer; LOG(0) << " renderer: " << renderer;
LOG << " version: " << version; LOG(0) << " version: " << version;
LOG << " shader version: " LOG(0) << " shader version: "
<< (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION); << (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
LOG << "Screen size: " << screen_width_ << ", " << screen_height_; LOG(0) << "Screen size: " << screen_width_ << ", " << screen_height_;
// Setup extensions. // Setup extensions.
std::stringstream stream((const char*)glGetString(GL_EXTENSIONS)); std::stringstream stream((const char*)glGetString(GL_EXTENSIONS));
@ -435,9 +435,9 @@ bool RendererOpenGL::InitCommon() {
extensions.insert(token); extensions.insert(token);
#if 0 #if 0
LOG << " extensions:"; LOG(0) << " extensions:";
for (auto& ext : extensions) for (auto& ext : extensions)
LOG << " " << ext.c_str()); LOG(0) << " " << ext.c_str());
#endif #endif
// Check for supported texture compression extensions. // Check for supported texture compression extensions.
@ -472,16 +472,16 @@ bool RendererOpenGL::InitCommon() {
// Ancient hardware is not supported. // Ancient hardware is not supported.
if (!npot_) if (!npot_)
LOG << "NPOT not supported."; LOG(0) << "NPOT not supported.";
if (vertex_array_objects_) if (vertex_array_objects_)
LOG << "Supports Vertex Array Objects."; LOG(0) << "Supports Vertex Array Objects.";
LOG << "TextureCompression:"; LOG(0) << "TextureCompression:";
LOG << " atc: " << texture_compression_.atc; LOG(0) << " atc: " << texture_compression_.atc;
LOG << " dxt1: " << texture_compression_.dxt1; LOG(0) << " dxt1: " << texture_compression_.dxt1;
LOG << " etc1: " << texture_compression_.etc1; LOG(0) << " etc1: " << texture_compression_.etc1;
LOG << " s3tc: " << texture_compression_.s3tc; LOG(0) << " s3tc: " << texture_compression_.s3tc;
glViewport(0, 0, screen_width_, screen_height_); glViewport(0, 0, screen_width_, screen_height_);
@ -580,7 +580,7 @@ GLuint RendererOpenGL::CreateShader(const char* source, GLenum type) {
char* buffer = (char*)malloc(length); char* buffer = (char*)malloc(length);
if (buffer) { if (buffer) {
glGetShaderInfoLog(shader, length, NULL, buffer); glGetShaderInfoLog(shader, length, NULL, buffer);
LOG << "Could not compile shader " << type << ":\n" << buffer; LOG(0) << "Could not compile shader " << type << ":\n" << buffer;
free(buffer); free(buffer);
} }
glDeleteShader(shader); glDeleteShader(shader);
@ -622,8 +622,8 @@ GLint RendererOpenGL::GetUniformLocation(
if (index >= 0) if (index >= 0)
uniforms[name] = index; uniforms[name] = index;
else else
LOG << "Cannot find uniform " << name.c_str() << " (shader: " << id LOG(0) << "Cannot find uniform " << name.c_str() << " (shader: " << id
<< ")"; << ")";
} }
return index; return index;
} }

View File

@ -9,7 +9,7 @@
namespace eng { namespace eng {
bool RendererOpenGL::Initialize(Platform* platform) { bool RendererOpenGL::Initialize(Platform* platform) {
LOG << "Initializing renderer."; LOG(0) << "Initializing renderer.";
window_ = platform->GetWindow(); window_ = platform->GetWindow();
ndk_helper::GLContext* gl_context = ndk_helper::GLContext::GetInstance(); ndk_helper::GLContext* gl_context = ndk_helper::GLContext::GetInstance();

View File

@ -6,7 +6,7 @@
namespace eng { namespace eng {
bool RendererOpenGL::Initialize(Platform* platform) { bool RendererOpenGL::Initialize(Platform* platform) {
LOG << "Initializing renderer."; LOG(0) << "Initializing renderer.";
display_ = platform->GetDisplay(); display_ = platform->GetDisplay();
window_ = platform->GetWindow(); window_ = platform->GetWindow();
@ -21,14 +21,14 @@ bool RendererOpenGL::Initialize(Platform* platform) {
XVisualInfo* visual_info = glXChooseVisual(display_, 0, glx_attributes); XVisualInfo* visual_info = glXChooseVisual(display_, 0, glx_attributes);
glx_context_ = glXCreateContext(display_, visual_info, NULL, GL_TRUE); glx_context_ = glXCreateContext(display_, visual_info, NULL, GL_TRUE);
if (!glx_context_) { if (!glx_context_) {
LOG << "Couldn't create the glx context."; LOG(0) << "Couldn't create the glx context.";
return false; return false;
} }
glXMakeCurrent(display_, window_, glx_context_); glXMakeCurrent(display_, window_, glx_context_);
if (GLEW_OK != glewInit()) { if (GLEW_OK != glewInit()) {
LOG << "Couldn't initialize OpenGL extension wrangler."; LOG(0) << "Couldn't initialize OpenGL extension wrangler.";
return false; return false;
} }

View File

@ -24,7 +24,7 @@ bool ParseVertexDescription(const std::string& vd_str, VertexDescription& out) {
while (token) { while (token) {
// Check for invalid format. // Check for invalid format.
if (strlen(token) != 3) { if (strlen(token) != 3) {
LOG << "Invalid format: " << token; LOG(0) << "Invalid format: " << token;
return false; return false;
} }
@ -44,14 +44,14 @@ bool ParseVertexDescription(const std::string& vd_str, VertexDescription& out) {
attrib_type = kAttribType_TexCoord; attrib_type = kAttribType_TexCoord;
break; break;
default: default:
LOG << "Unknown attribute: " << token; LOG(0) << "Unknown attribute: " << token;
return false; return false;
} }
// There can be between 1 and 4 elements in an attribute. // There can be between 1 and 4 elements in an attribute.
ElementCount num_elements = token[1] - '1' + 1; ElementCount num_elements = token[1] - '1' + 1;
if (num_elements < 1 || num_elements > 4) { if (num_elements < 1 || num_elements > 4) {
LOG << "Invalid number of elements: " << token; LOG(0) << "Invalid number of elements: " << token;
return false; return false;
} }
@ -84,7 +84,7 @@ bool ParseVertexDescription(const std::string& vd_str, VertexDescription& out) {
type_size = sizeof(unsigned short); type_size = sizeof(unsigned short);
break; break;
default: default:
LOG << "Unknown data type: " << token; LOG(0) << "Unknown data type: " << token;
return false; return false;
} }

View File

@ -22,7 +22,7 @@ void Texture::Update(std::unique_ptr<Image> image) {
void Texture::Destroy() { void Texture::Destroy() {
if (IsValid()) { if (IsValid()) {
DLOG << "Texture destroyed. resource_id: " << resource_id_; DLOG(0) << "Texture destroyed. resource_id: " << resource_id_;
renderer_->DestroyTexture(resource_id_); renderer_->DestroyTexture(resource_id_);
resource_id_ = 0; resource_id_ = 0;
} }

View File

@ -313,7 +313,7 @@ VkIndexType GetIndexType(eng::DataType data_type) {
default: default:
break; break;
} }
NOTREACHED << "Invalid index type: " << data_type; NOTREACHED() << "Invalid index type: " << data_type;
return VK_INDEX_TYPE_UINT16; return VK_INDEX_TYPE_UINT16;
} }
@ -331,7 +331,7 @@ VkFormat GetImageFormat(eng::Image::Format format) {
default: default:
break; break;
} }
NOTREACHED << "Invalid format: " << format; NOTREACHED() << "Invalid format: " << format;
return VK_FORMAT_R8G8B8A8_UNORM; return VK_FORMAT_R8G8B8A8_UNORM;
} }
@ -346,7 +346,7 @@ std::pair<int, int> GetBlockSizeForImageFormat(VkFormat format) {
default: default:
break; break;
} }
NOTREACHED << "Invalid format: " << string_VkFormat(format); NOTREACHED() << "Invalid format: " << string_VkFormat(format);
return {0, 0}; return {0, 0};
} }
@ -362,7 +362,7 @@ std::pair<int, int> GetNumBlocksForImageFormat(VkFormat format,
default: default:
break; break;
} }
NOTREACHED << "Invalid format: " << string_VkFormat(format); NOTREACHED() << "Invalid format: " << string_VkFormat(format);
return {width, height}; return {width, height};
} }
@ -537,11 +537,11 @@ uint64_t RendererVulkan::CreateShader(
std::string error; std::string error;
spirv[0] = CompileGlsl(EShLangVertex, source->GetVertexSource(), &error); spirv[0] = CompileGlsl(EShLangVertex, source->GetVertexSource(), &error);
if (!error.empty()) if (!error.empty())
DLOG << source->name() << " vertex shader compile error: " << error; DLOG(0) << source->name() << " vertex shader compile error: " << error;
spirv[1] = spirv[1] =
CompileGlsl(EShLangFragment, source->GetFragmentSource(), &error); CompileGlsl(EShLangFragment, source->GetFragmentSource(), &error);
if (!error.empty()) if (!error.empty())
DLOG << source->name() << " fragment shader compile error: " << error; DLOG(0) << source->name() << " fragment shader compile error: " << error;
it = spirv_cache_.insert({source->name(), spirv}).first; it = spirv_cache_.insert({source->name(), spirv}).first;
} }
@ -558,7 +558,7 @@ uint64_t RendererVulkan::CreateShader(
if (vkCreateShaderModule(device_, &shader_module_info, nullptr, if (vkCreateShaderModule(device_, &shader_module_info, nullptr,
&vert_shader_module) != VK_SUCCESS) { &vert_shader_module) != VK_SUCCESS) {
DLOG << "vkCreateShaderModule failed!"; DLOG(0) << "vkCreateShaderModule failed!";
return 0; return 0;
} }
} }
@ -573,7 +573,7 @@ uint64_t RendererVulkan::CreateShader(
if (vkCreateShaderModule(device_, &shader_module_info, nullptr, if (vkCreateShaderModule(device_, &shader_module_info, nullptr,
&frag_shader_module) != VK_SUCCESS) { &frag_shader_module) != VK_SUCCESS) {
DLOG << "vkCreateShaderModule failed!"; DLOG(0) << "vkCreateShaderModule failed!";
return 0; return 0;
} }
} }
@ -581,7 +581,7 @@ uint64_t RendererVulkan::CreateShader(
auto& shader = shaders_[++last_resource_id_] = {}; auto& shader = shaders_[++last_resource_id_] = {};
if (!CreatePipelineLayout(shader, spirv_vertex, spirv_fragment)) if (!CreatePipelineLayout(shader, spirv_vertex, spirv_fragment))
DLOG << "Failed to create pipeline layout!"; DLOG(0) << "Failed to create pipeline layout!";
VkPipelineShaderStageCreateInfo vert_shader_stage_info{}; VkPipelineShaderStageCreateInfo vert_shader_stage_info{};
vert_shader_stage_info.sType = vert_shader_stage_info.sType =
@ -709,7 +709,7 @@ uint64_t RendererVulkan::CreateShader(
if (vkCreateGraphicsPipelines(device_, VK_NULL_HANDLE, 1, &pipeline_info, if (vkCreateGraphicsPipelines(device_, VK_NULL_HANDLE, 1, &pipeline_info,
nullptr, &shader.pipeline) != VK_SUCCESS) nullptr, &shader.pipeline) != VK_SUCCESS)
DLOG << "failed to create graphics pipeline."; DLOG(0) << "failed to create graphics pipeline.";
vkDestroyShaderModule(device_, frag_shader_module, nullptr); vkDestroyShaderModule(device_, frag_shader_module, nullptr);
vkDestroyShaderModule(device_, vert_shader_module, nullptr); vkDestroyShaderModule(device_, vert_shader_module, nullptr);
@ -863,14 +863,16 @@ bool RendererVulkan::InitializeInternal() {
VkResult err = vkCreateCommandPool(device_, &cmd_pool_info, nullptr, VkResult err = vkCreateCommandPool(device_, &cmd_pool_info, nullptr,
&frames_[i].setup_command_pool); &frames_[i].setup_command_pool);
if (err) { if (err) {
DLOG << "vkCreateCommandPool failed with error " << string_VkResult(err); DLOG(0) << "vkCreateCommandPool failed with error "
<< string_VkResult(err);
return false; return false;
} }
err = vkCreateCommandPool(device_, &cmd_pool_info, nullptr, err = vkCreateCommandPool(device_, &cmd_pool_info, nullptr,
&frames_[i].draw_command_pool); &frames_[i].draw_command_pool);
if (err) { if (err) {
DLOG << "vkCreateCommandPool failed with error " << string_VkResult(err); DLOG(0) << "vkCreateCommandPool failed with error "
<< string_VkResult(err);
return false; return false;
} }
@ -885,8 +887,8 @@ bool RendererVulkan::InitializeInternal() {
err = vkAllocateCommandBuffers(device_, &cmdbuf_info, err = vkAllocateCommandBuffers(device_, &cmdbuf_info,
&frames_[i].setup_command_buffer); &frames_[i].setup_command_buffer);
if (err) { if (err) {
DLOG << "vkAllocateCommandBuffers failed with error " DLOG(0) << "vkAllocateCommandBuffers failed with error "
<< string_VkResult(err); << string_VkResult(err);
continue; continue;
} }
@ -894,8 +896,8 @@ bool RendererVulkan::InitializeInternal() {
err = vkAllocateCommandBuffers(device_, &cmdbuf_info, err = vkAllocateCommandBuffers(device_, &cmdbuf_info,
&frames_[i].draw_command_buffer); &frames_[i].draw_command_buffer);
if (err) { if (err) {
DLOG << "vkAllocateCommandBuffers failed with error " DLOG(0) << "vkAllocateCommandBuffers failed with error "
<< string_VkResult(err); << string_VkResult(err);
continue; continue;
} }
} }
@ -919,8 +921,8 @@ bool RendererVulkan::InitializeInternal() {
VkResult err = vkCreateDescriptorSetLayout(device_, &ds_layout_info, nullptr, VkResult err = vkCreateDescriptorSetLayout(device_, &ds_layout_info, nullptr,
&descriptor_set_layout_); &descriptor_set_layout_);
if (err) { if (err) {
DLOG << "Error (" << string_VkResult(err) DLOG(0) << "Error (" << string_VkResult(err)
<< ") creating descriptor set layout for set"; << ") creating descriptor set layout for set";
return false; return false;
} }
@ -947,18 +949,18 @@ bool RendererVulkan::InitializeInternal() {
err = vkCreateSampler(device_, &sampler_info, nullptr, &sampler_); err = vkCreateSampler(device_, &sampler_info, nullptr, &sampler_);
if (err) { if (err) {
DLOG << "vkCreateSampler failed with error " << string_VkResult(err); DLOG(0) << "vkCreateSampler failed with error " << string_VkResult(err);
return false; return false;
} }
texture_compression_.dxt1 = IsFormatSupported(VK_FORMAT_BC1_RGB_UNORM_BLOCK); texture_compression_.dxt1 = IsFormatSupported(VK_FORMAT_BC1_RGB_UNORM_BLOCK);
texture_compression_.s3tc = IsFormatSupported(VK_FORMAT_BC3_UNORM_BLOCK); texture_compression_.s3tc = IsFormatSupported(VK_FORMAT_BC3_UNORM_BLOCK);
LOG << "TextureCompression:"; LOG(0) << "TextureCompression:";
LOG << " atc: " << texture_compression_.atc; LOG(0) << " atc: " << texture_compression_.atc;
LOG << " dxt1: " << texture_compression_.dxt1; LOG(0) << " dxt1: " << texture_compression_.dxt1;
LOG << " etc1: " << texture_compression_.etc1; LOG(0) << " etc1: " << texture_compression_.etc1;
LOG << " s3tc: " << texture_compression_.s3tc; LOG(0) << " s3tc: " << texture_compression_.s3tc;
// Use a background thread for filling up staging buffers and recording setup // Use a background thread for filling up staging buffers and recording setup
// commands. // commands.
@ -970,7 +972,7 @@ bool RendererVulkan::InitializeInternal() {
BeginFrame(); BeginFrame();
if (context_lost_ && context_lost_cb_) { if (context_lost_ && context_lost_cb_) {
LOG << "Context lost."; LOG(0) << "Context lost.";
context_lost_cb_(); context_lost_cb_();
} }
return true; return true;
@ -980,7 +982,7 @@ void RendererVulkan::Shutdown() {
if (device_ == VK_NULL_HANDLE) if (device_ == VK_NULL_HANDLE)
return; return;
LOG << "Shutting down renderer."; LOG(0) << "Shutting down renderer.";
task_runner_.CancelTasks(); task_runner_.CancelTasks();
quit_.store(true, std::memory_order_relaxed); quit_.store(true, std::memory_order_relaxed);
semaphore_.release(); semaphore_.release();
@ -1035,14 +1037,16 @@ void RendererVulkan::BeginFrame() {
VkResult err = vkBeginCommandBuffer( VkResult err = vkBeginCommandBuffer(
frames_[current_frame_].setup_command_buffer, &cmdbuf_begin); frames_[current_frame_].setup_command_buffer, &cmdbuf_begin);
if (err) { if (err) {
DLOG << "vkBeginCommandBuffer failed with error " << string_VkResult(err); DLOG(0) << "vkBeginCommandBuffer failed with error "
<< string_VkResult(err);
return; return;
} }
err = vkBeginCommandBuffer(frames_[current_frame_].draw_command_buffer, err = vkBeginCommandBuffer(frames_[current_frame_].draw_command_buffer,
&cmdbuf_begin); &cmdbuf_begin);
if (err) { if (err) {
DLOG << "vkBeginCommandBuffer failed with error " << string_VkResult(err); DLOG(0) << "vkBeginCommandBuffer failed with error "
<< string_VkResult(err);
return; return;
} }
@ -1073,7 +1077,8 @@ void RendererVulkan::FlushSetupBuffer() {
VkResult err = vkBeginCommandBuffer( VkResult err = vkBeginCommandBuffer(
frames_[current_frame_].setup_command_buffer, &cmdbuf_begin); frames_[current_frame_].setup_command_buffer, &cmdbuf_begin);
if (err) { if (err) {
DLOG << "vkBeginCommandBuffer failed with error " << string_VkResult(err); DLOG(0) << "vkBeginCommandBuffer failed with error "
<< string_VkResult(err);
return; return;
} }
context_.AppendCommandBuffer(frames_[current_frame_].setup_command_buffer, context_.AppendCommandBuffer(frames_[current_frame_].setup_command_buffer,
@ -1286,7 +1291,7 @@ bool RendererVulkan::InsertStagingBuffer() {
&std::get<0>(block.buffer), &std::get<0>(block.buffer),
&std::get<1>(block.buffer), &block.alloc_info); &std::get<1>(block.buffer), &block.alloc_info);
if (err) { if (err) {
DLOG << "vmaCreateBuffer failed with error " << string_VkResult(err); DLOG(0) << "vmaCreateBuffer failed with error " << string_VkResult(err);
return false; return false;
} }
@ -1327,8 +1332,8 @@ RendererVulkan::DescPool* RendererVulkan::AllocateDescriptorPool() {
VkResult err = vkCreateDescriptorPool(device_, &descriptor_pool_create_info, VkResult err = vkCreateDescriptorPool(device_, &descriptor_pool_create_info,
nullptr, &desc_pool); nullptr, &desc_pool);
if (err) { if (err) {
DLOG << "vkCreateDescriptorPool failed with error " DLOG(0) << "vkCreateDescriptorPool failed with error "
<< string_VkResult(err); << string_VkResult(err);
return VK_NULL_HANDLE; return VK_NULL_HANDLE;
} }
@ -1350,7 +1355,7 @@ void RendererVulkan::FreeDescriptorPool(DescPool* desc_pool) {
return; return;
} }
} }
NOTREACHED; NOTREACHED();
} }
} }
@ -1383,8 +1388,8 @@ bool RendererVulkan::AllocateBuffer(Buffer<VkBuffer>& buffer,
VkResult err = vmaCreateBuffer(allocator_, &buffer_info, &allocation_info, VkResult err = vmaCreateBuffer(allocator_, &buffer_info, &allocation_info,
&vk_buffer, &allocation, nullptr); &vk_buffer, &allocation, nullptr);
if (err) { if (err) {
DLOG << "Can't create buffer of size: " << std::to_string(size) DLOG(0) << "Can't create buffer of size: " << std::to_string(size)
<< ", error " << string_VkResult(err); << ", error " << string_VkResult(err);
return false; return false;
} }
@ -1500,7 +1505,7 @@ bool RendererVulkan::AllocateImage(Buffer<VkImage>& image,
VkResult err = vmaCreateImage(allocator_, &image_create_info, &allocInfo, VkResult err = vmaCreateImage(allocator_, &image_create_info, &allocInfo,
&vk_image, &allocation, nullptr); &vk_image, &allocation, nullptr);
if (err) { if (err) {
DLOG << "vmaCreateImage failed with error " << string_VkResult(err); DLOG(0) << "vmaCreateImage failed with error " << string_VkResult(err);
return false; return false;
} }
@ -1526,7 +1531,7 @@ bool RendererVulkan::AllocateImage(Buffer<VkImage>& image,
if (err) { if (err) {
vmaDestroyImage(allocator_, vk_image, allocation); vmaDestroyImage(allocator_, vk_image, allocation);
DLOG << "vkCreateImageView failed with error " << string_VkResult(err); DLOG(0) << "vkCreateImageView failed with error " << string_VkResult(err);
return false; return false;
} }
@ -1547,7 +1552,8 @@ bool RendererVulkan::AllocateImage(Buffer<VkImage>& image,
&descriptor_set); &descriptor_set);
if (err) { if (err) {
--std::get<1>(*desc_pool); --std::get<1>(*desc_pool);
DLOG << "Cannot allocate descriptor sets, error " << string_VkResult(err); DLOG(0) << "Cannot allocate descriptor sets, error "
<< string_VkResult(err);
return false; return false;
} }
@ -1682,7 +1688,7 @@ bool RendererVulkan::CreatePipelineLayout(
SpvReflectResult result = spvReflectCreateShaderModule( SpvReflectResult result = spvReflectCreateShaderModule(
spirv_vertex.size(), spirv_vertex.data(), &module_vertex); spirv_vertex.size(), spirv_vertex.data(), &module_vertex);
if (result != SPV_REFLECT_RESULT_SUCCESS) { if (result != SPV_REFLECT_RESULT_SUCCESS) {
DLOG << "SPIR-V reflection failed to parse vertex shader."; DLOG(0) << "SPIR-V reflection failed to parse vertex shader.";
return false; return false;
} }
@ -1690,7 +1696,7 @@ bool RendererVulkan::CreatePipelineLayout(
result = spvReflectCreateShaderModule( result = spvReflectCreateShaderModule(
spirv_fragment.size(), spirv_fragment.data(), &module_fragment); spirv_fragment.size(), spirv_fragment.data(), &module_fragment);
if (result != SPV_REFLECT_RESULT_SUCCESS) { if (result != SPV_REFLECT_RESULT_SUCCESS) {
DLOG << "SPIR-V reflection failed to parse fragment shader."; DLOG(0) << "SPIR-V reflection failed to parse fragment shader.";
spvReflectDestroyShaderModule(&module_vertex); spvReflectDestroyShaderModule(&module_vertex);
return false; return false;
} }
@ -1705,13 +1711,13 @@ bool RendererVulkan::CreatePipelineLayout(
result = spvReflectEnumerateDescriptorBindings(&module_vertex, result = spvReflectEnumerateDescriptorBindings(&module_vertex,
&binding_count, nullptr); &binding_count, nullptr);
if (result != SPV_REFLECT_RESULT_SUCCESS) { if (result != SPV_REFLECT_RESULT_SUCCESS) {
DLOG << "SPIR-V reflection failed to enumerate fragment shader " DLOG(0) << "SPIR-V reflection failed to enumerate fragment shader "
"descriptor bindings."; "descriptor bindings.";
break; break;
} }
if (binding_count > 0) { if (binding_count > 0) {
DLOG << "SPIR-V reflection found " << binding_count DLOG(0) << "SPIR-V reflection found " << binding_count
<< " descriptor bindings in vertex shader."; << " descriptor bindings in vertex shader.";
break; break;
} }
@ -1719,12 +1725,12 @@ bool RendererVulkan::CreatePipelineLayout(
result = spvReflectEnumerateDescriptorBindings(&module_fragment, result = spvReflectEnumerateDescriptorBindings(&module_fragment,
&binding_count, nullptr); &binding_count, nullptr);
if (result != SPV_REFLECT_RESULT_SUCCESS) { if (result != SPV_REFLECT_RESULT_SUCCESS) {
DLOG << "SPIR-V reflection failed to enumerate fragment shader " DLOG(0) << "SPIR-V reflection failed to enumerate fragment shader "
"descriptor bindings."; "descriptor bindings.";
break; break;
} }
DLOG << __func__ << " binding_count: " << binding_count; DLOG(0) << __func__ << " binding_count: " << binding_count;
if (binding_count > 0) { if (binding_count > 0) {
// Collect binding names and validate that only COMBINED_IMAGE_SAMPLER // Collect binding names and validate that only COMBINED_IMAGE_SAMPLER
@ -1735,31 +1741,31 @@ bool RendererVulkan::CreatePipelineLayout(
&module_fragment, &binding_count, bindings.data()); &module_fragment, &binding_count, bindings.data());
if (result != SPV_REFLECT_RESULT_SUCCESS) { if (result != SPV_REFLECT_RESULT_SUCCESS) {
DLOG << "SPIR-V reflection failed to get descriptor bindings for " DLOG(0) << "SPIR-V reflection failed to get descriptor bindings for "
"fragment shader."; "fragment shader.";
break; break;
} }
for (size_t i = 0; i < binding_count; ++i) { for (size_t i = 0; i < binding_count; ++i) {
const SpvReflectDescriptorBinding& binding = *bindings[i]; const SpvReflectDescriptorBinding& binding = *bindings[i];
DLOG << __func__ << " name: " << binding.name DLOG(0) << __func__ << " name: " << binding.name
<< " descriptor_type: " << binding.descriptor_type << " descriptor_type: " << binding.descriptor_type
<< " set: " << binding.set << " binding: " << binding.binding; << " set: " << binding.set << " binding: " << binding.binding;
if (binding.binding > 0) { if (binding.binding > 0) {
DLOG << "SPIR-V reflection found " << binding_count DLOG(0) << "SPIR-V reflection found " << binding_count
<< " bindings in vertex shader. Only one binding per set is " << " bindings in vertex shader. Only one binding per set is "
"supported"; "supported";
break; break;
} }
if (binding.descriptor_type != if (binding.descriptor_type !=
SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) { SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) {
DLOG << "SPIR-V reflection found descriptor type " DLOG(0) << "SPIR-V reflection found descriptor type "
<< binding.descriptor_type << binding.descriptor_type
<< " in fragment shader. Only COMBINED_IMAGE_SAMPLER type is " << " in fragment shader. Only COMBINED_IMAGE_SAMPLER type is "
"supported."; "supported.";
break; break;
} }
@ -1780,17 +1786,17 @@ bool RendererVulkan::CreatePipelineLayout(
result = result =
spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr); spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr);
if (result != SPV_REFLECT_RESULT_SUCCESS) { if (result != SPV_REFLECT_RESULT_SUCCESS) {
DLOG << "SPIR-V reflection failed to enumerate push constats in shader " DLOG(0) << "SPIR-V reflection failed to enumerate push constats in "
"stage " "shader stage "
<< stage; << stage;
return false; return false;
} }
if (pc_count) { if (pc_count) {
if (pc_count > 1) { if (pc_count > 1) {
DLOG << "SPIR-V reflection found " << pc_count DLOG(0) << "SPIR-V reflection found " << pc_count
<< " push constats blocks in shader stage " << stage << " push constats blocks in shader stage " << stage
<< ". Only one push constant block is supported."; << ". Only one push constant block is supported.";
return false; return false;
} }
@ -1798,7 +1804,7 @@ bool RendererVulkan::CreatePipelineLayout(
result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count,
pconstants.data()); pconstants.data());
if (result != SPV_REFLECT_RESULT_SUCCESS) { if (result != SPV_REFLECT_RESULT_SUCCESS) {
DLOG << "SPIR-V reflection failed to obtaining push constants."; DLOG(0) << "SPIR-V reflection failed to obtaining push constants.";
return false; return false;
} }
} }
@ -1819,18 +1825,19 @@ bool RendererVulkan::CreatePipelineLayout(
break; break;
if (pc_count_vertex != pc_count_fragment) { if (pc_count_vertex != pc_count_fragment) {
DLOG << "SPIR-V reflection found different push constant blocks across " DLOG(0) << "SPIR-V reflection found different push constant blocks "
"shader stages."; "across shader stages.";
break; break;
} }
if (pc_count_vertex) { if (pc_count_vertex) {
DLOG << __func__ << " PushConstants size: " << pconstants_vertex[0]->size DLOG(0) << __func__
<< " count: " << pconstants_vertex[0]->member_count; << " PushConstants size: " << pconstants_vertex[0]->size
<< " count: " << pconstants_vertex[0]->member_count;
if (pconstants_vertex[0]->size != pconstants_fragment[0]->size) { if (pconstants_vertex[0]->size != pconstants_fragment[0]->size) {
DLOG << "SPIR-V reflection found different push constant blocks across " DLOG(0) << "SPIR-V reflection found different push constant blocks "
"shader stages."; "across shader stages.";
break; break;
} }
@ -1841,10 +1848,11 @@ bool RendererVulkan::CreatePipelineLayout(
size_t offset = 0; size_t offset = 0;
for (uint32_t j = 0; j < pconstants_vertex[0]->member_count; j++) { for (uint32_t j = 0; j < pconstants_vertex[0]->member_count; j++) {
DLOG << __func__ << " name: " << pconstants_vertex[0]->members[j].name DLOG(0) << __func__
<< " size: " << pconstants_vertex[0]->members[j].size << " name: " << pconstants_vertex[0]->members[j].name
<< " padded_size: " << " size: " << pconstants_vertex[0]->members[j].size
<< pconstants_vertex[0]->members[j].padded_size; << " padded_size: "
<< pconstants_vertex[0]->members[j].padded_size;
shader.variables[pconstants_vertex[0]->members[j].name] = { shader.variables[pconstants_vertex[0]->members[j].name] = {
pconstants_vertex[0]->members[j].size, offset}; pconstants_vertex[0]->members[j].size, offset};
@ -1886,7 +1894,7 @@ bool RendererVulkan::CreatePipelineLayout(
if (vkCreatePipelineLayout(device_, &pipeline_layout_create_info, nullptr, if (vkCreatePipelineLayout(device_, &pipeline_layout_create_info, nullptr,
&shader.pipeline_layout) != VK_SUCCESS) { &shader.pipeline_layout) != VK_SUCCESS) {
DLOG << "Failed to create pipeline layout!"; DLOG(0) << "Failed to create pipeline layout!";
break; break;
} }
@ -1992,7 +2000,7 @@ void RendererVulkan::SetupThreadMain(int preallocate) {
for (int i = 0; i < preallocate; i++) { for (int i = 0; i < preallocate; i++) {
bool err = InsertStagingBuffer(); bool err = InsertStagingBuffer();
LOG_IF(!err) << "Failed to create staging buffer."; LOG_IF(0, !err) << "Failed to create staging buffer.";
} }
for (;;) { for (;;) {
@ -2015,11 +2023,11 @@ bool RendererVulkan::SetUniformInternal(ShaderVulkan& shader,
T val) { T val) {
auto it = shader.variables.find(name); auto it = shader.variables.find(name);
if (it == shader.variables.end()) { if (it == shader.variables.end()) {
DLOG << "No variable found with name " << name; DLOG(0) << "No variable found with name " << name;
return false; return false;
} }
if (it->second[0] != sizeof(val)) { if (it->second[0] != sizeof(val)) {
DLOG << "Size mismatch for variable " << name; DLOG(0) << "Size mismatch for variable " << name;
return false; return false;
} }

View File

@ -8,18 +8,18 @@
namespace eng { namespace eng {
bool RendererVulkan::Initialize(Platform* platform) { bool RendererVulkan::Initialize(Platform* platform) {
LOG << "Initializing renderer."; LOG(0) << "Initializing renderer.";
screen_width_ = ANativeWindow_getWidth(platform->GetWindow()); screen_width_ = ANativeWindow_getWidth(platform->GetWindow());
screen_height_ = ANativeWindow_getHeight(platform->GetWindow()); screen_height_ = ANativeWindow_getHeight(platform->GetWindow());
if (!context_.Initialize()) { if (!context_.Initialize()) {
LOG << "Failed to initialize Vulkan context."; LOG(0) << "Failed to initialize Vulkan context.";
return false; return false;
} }
if (!context_.CreateWindow(platform->GetWindow(), screen_width_, if (!context_.CreateWindow(platform->GetWindow(), screen_width_,
screen_height_)) { screen_height_)) {
LOG << "Vulkan context failed to create window."; LOG(0) << "Vulkan context failed to create window.";
return false; return false;
} }

View File

@ -6,7 +6,7 @@
namespace eng { namespace eng {
bool RendererVulkan::Initialize(Platform* platform) { bool RendererVulkan::Initialize(Platform* platform) {
LOG << "Initializing renderer."; LOG(0) << "Initializing renderer.";
XWindowAttributes xwa; XWindowAttributes xwa;
XGetWindowAttributes(platform->GetDisplay(), platform->GetWindow(), &xwa); XGetWindowAttributes(platform->GetDisplay(), platform->GetWindow(), &xwa);
@ -14,12 +14,12 @@ bool RendererVulkan::Initialize(Platform* platform) {
screen_height_ = xwa.height; screen_height_ = xwa.height;
if (!context_.Initialize()) { if (!context_.Initialize()) {
LOG << "Failed to initialize Vulkan context."; LOG(0) << "Failed to initialize Vulkan context.";
return false; return false;
} }
if (!context_.CreateWindow(platform->GetDisplay(), platform->GetWindow(), if (!context_.CreateWindow(platform->GetDisplay(), platform->GetWindow(),
screen_width_, screen_height_)) { screen_width_, screen_height_)) {
LOG << "Vulkan context failed to create window."; LOG(0) << "Vulkan context failed to create window.";
return false; return false;
} }

View File

@ -12,7 +12,7 @@
{ \ { \
entrypoint = (PFN_vk##entrypoint)func(obj, "vk" #entrypoint); \ entrypoint = (PFN_vk##entrypoint)func(obj, "vk" #entrypoint); \
if (entrypoint == nullptr) { \ if (entrypoint == nullptr) { \
DLOG << #func << " failed to find vk"; \ DLOG(0) << #func << " failed to find vk"; \
return false; \ return false; \
} \ } \
} }
@ -164,16 +164,16 @@ VKAPI_ATTR VkBool32 VKAPI_CALL VulkanContext::DebugMessengerCallback(
switch (message_severity) { switch (message_severity) {
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
LOG << error_message; LOG(0) << error_message;
break; break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
LOG << error_message; LOG(0) << error_message;
break; break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
LOG << error_message; LOG(0) << error_message;
break; break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
LOG << error_message; LOG(0) << error_message;
break; break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT: case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT:
break; break;
@ -195,7 +195,7 @@ VkBool32 VulkanContext::CheckLayers(uint32_t check_count,
} }
} }
if (!found) { if (!found) {
DLOG << "Can't find layer: " << check_names[i]; DLOG(0) << "Can't find layer: " << check_names[i];
return 0; return 0;
} }
} }
@ -216,8 +216,8 @@ bool VulkanContext::CreateValidationLayers() {
uint32_t instance_layer_count = 0; uint32_t instance_layer_count = 0;
err = vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr); err = vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr);
if (err) { if (err) {
DLOG << "vkEnumerateInstanceLayerProperties failed. Error: " DLOG(0) << "vkEnumerateInstanceLayerProperties failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -230,8 +230,8 @@ bool VulkanContext::CreateValidationLayers() {
err = vkEnumerateInstanceLayerProperties(&instance_layer_count, err = vkEnumerateInstanceLayerProperties(&instance_layer_count,
instance_layers.get()); instance_layers.get());
if (err) { if (err) {
DLOG << "vkEnumerateInstanceLayerProperties failed. Error: " DLOG(0) << "vkEnumerateInstanceLayerProperties failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -287,8 +287,8 @@ bool VulkanContext::InitializeExtensions() {
err = vkEnumerateInstanceExtensionProperties( err = vkEnumerateInstanceExtensionProperties(
nullptr, &instance_extension_count, nullptr); nullptr, &instance_extension_count, nullptr);
if (err) { if (err) {
DLOG << "vkEnumerateInstanceExtensionProperties failed. Error: " DLOG(0) << "vkEnumerateInstanceExtensionProperties failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -298,8 +298,8 @@ bool VulkanContext::InitializeExtensions() {
err = vkEnumerateInstanceExtensionProperties( err = vkEnumerateInstanceExtensionProperties(
nullptr, &instance_extension_count, instance_extensions.get()); nullptr, &instance_extension_count, instance_extensions.get());
if (err) { if (err) {
DLOG << "vkEnumerateInstanceExtensionProperties failed. Error: " DLOG(0) << "vkEnumerateInstanceExtensionProperties failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
for (uint32_t i = 0; i < instance_extension_count; i++) { for (uint32_t i = 0; i < instance_extension_count; i++) {
@ -331,18 +331,18 @@ bool VulkanContext::InitializeExtensions() {
} }
} }
if (enabled_extension_count_ >= kMaxExtensions) { if (enabled_extension_count_ >= kMaxExtensions) {
DLOG << "Enabled extension count reaches kMaxExtensions"; DLOG(0) << "Enabled extension count reaches kMaxExtensions";
return false; return false;
} }
} }
} }
if (!surfaceExtFound) { if (!surfaceExtFound) {
DLOG << "No surface extension found."; DLOG(0) << "No surface extension found.";
return false; return false;
} }
if (!platformSurfaceExtFound) { if (!platformSurfaceExtFound) {
DLOG << "No platform surface extension found."; DLOG(0) << "No platform surface extension found.";
return false; return false;
} }
@ -403,18 +403,18 @@ bool VulkanContext::CreatePhysicalDevice() {
if (instance_ == VK_NULL_HANDLE) { if (instance_ == VK_NULL_HANDLE) {
VkResult err = vkCreateInstance(&inst_info, nullptr, &instance_); VkResult err = vkCreateInstance(&inst_info, nullptr, &instance_);
if (err == VK_ERROR_INCOMPATIBLE_DRIVER) { if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
DLOG DLOG(0)
<< "Cannot find a compatible Vulkan installable client driver (ICD)."; << "Cannot find a compatible Vulkan installable client driver (ICD).";
return false; return false;
} }
if (err == VK_ERROR_EXTENSION_NOT_PRESENT) { if (err == VK_ERROR_EXTENSION_NOT_PRESENT) {
DLOG DLOG(0)
<< "Cannot find a specified extension library. Make sure your layers " << "Cannot find a specified extension library. Make sure your layers "
"path is set appropriately. "; "path is set appropriately. ";
return false; return false;
} }
if (err) { if (err) {
DLOG << "vkCreateInstance failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateInstance failed. Error: " << string_VkResult(err);
return false; return false;
} }
} }
@ -424,13 +424,13 @@ bool VulkanContext::CreatePhysicalDevice() {
// Make initial call to query gpu_count. // Make initial call to query gpu_count.
VkResult err = vkEnumeratePhysicalDevices(instance_, &gpu_count, nullptr); VkResult err = vkEnumeratePhysicalDevices(instance_, &gpu_count, nullptr);
if (err) { if (err) {
DLOG << "vkEnumeratePhysicalDevices failed. Error: " DLOG(0) << "vkEnumeratePhysicalDevices failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
if (gpu_count == 0) { if (gpu_count == 0) {
DLOG << "vkEnumeratePhysicalDevices reported zero accessible devices."; DLOG(0) << "vkEnumeratePhysicalDevices reported zero accessible devices.";
return false; return false;
} }
@ -438,8 +438,8 @@ bool VulkanContext::CreatePhysicalDevice() {
err = err =
vkEnumeratePhysicalDevices(instance_, &gpu_count, physical_devices.get()); vkEnumeratePhysicalDevices(instance_, &gpu_count, physical_devices.get());
if (err) { if (err) {
DLOG << "vkEnumeratePhysicalDevices failed. Error: " DLOG(0) << "vkEnumeratePhysicalDevices failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
// Grab the first physical device for now. // Grab the first physical device for now.
@ -454,8 +454,8 @@ bool VulkanContext::CreatePhysicalDevice() {
err = vkEnumerateDeviceExtensionProperties(gpu_, nullptr, err = vkEnumerateDeviceExtensionProperties(gpu_, nullptr,
&device_extension_count, nullptr); &device_extension_count, nullptr);
if (err) { if (err) {
DLOG << "vkEnumerateDeviceExtensionProperties failed. Error: " DLOG(0) << "vkEnumerateDeviceExtensionProperties failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -465,8 +465,8 @@ bool VulkanContext::CreatePhysicalDevice() {
err = vkEnumerateDeviceExtensionProperties( err = vkEnumerateDeviceExtensionProperties(
gpu_, nullptr, &device_extension_count, device_extensions.get()); gpu_, nullptr, &device_extension_count, device_extensions.get());
if (err) { if (err) {
DLOG << "vkEnumerateDeviceExtensionProperties failed. Error: " DLOG(0) << "vkEnumerateDeviceExtensionProperties failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -478,7 +478,7 @@ bool VulkanContext::CreatePhysicalDevice() {
VK_KHR_SWAPCHAIN_EXTENSION_NAME; VK_KHR_SWAPCHAIN_EXTENSION_NAME;
} }
if (enabled_extension_count_ >= kMaxExtensions) { if (enabled_extension_count_ >= kMaxExtensions) {
DLOG << "Enabled extension count reaches kMaxExtensions"; DLOG(0) << "Enabled extension count reaches kMaxExtensions";
return false; return false;
} }
} }
@ -491,15 +491,15 @@ bool VulkanContext::CreatePhysicalDevice() {
VK_KHR_MAINTENANCE1_EXTENSION_NAME; VK_KHR_MAINTENANCE1_EXTENSION_NAME;
} }
if (enabled_extension_count_ >= kMaxExtensions) { if (enabled_extension_count_ >= kMaxExtensions) {
DLOG << "Enabled extension count reaches kMaxExtensions"; DLOG(0) << "Enabled extension count reaches kMaxExtensions";
return false; return false;
} }
} }
} }
if (!swapchain_ext_found) { if (!swapchain_ext_found) {
DLOG << "vkEnumerateDeviceExtensionProperties failed to find " DLOG(0) << "vkEnumerateDeviceExtensionProperties failed to find "
"the " VK_KHR_SWAPCHAIN_EXTENSION_NAME " extension."; "the " VK_KHR_SWAPCHAIN_EXTENSION_NAME " extension.";
return false; return false;
} }
@ -512,7 +512,7 @@ bool VulkanContext::CreatePhysicalDevice() {
instance_, "vkDestroyDebugUtilsMessengerEXT"); instance_, "vkDestroyDebugUtilsMessengerEXT");
if (nullptr == CreateDebugUtilsMessengerEXT || if (nullptr == CreateDebugUtilsMessengerEXT ||
nullptr == DestroyDebugUtilsMessengerEXT) { nullptr == DestroyDebugUtilsMessengerEXT) {
DLOG << "GetProcAddr: Failed to init VK_EXT_debug_utils"; DLOG(0) << "GetProcAddr: Failed to init VK_EXT_debug_utils";
return false; return false;
} }
@ -522,31 +522,31 @@ bool VulkanContext::CreatePhysicalDevice() {
case VK_SUCCESS: case VK_SUCCESS:
break; break;
case VK_ERROR_OUT_OF_HOST_MEMORY: case VK_ERROR_OUT_OF_HOST_MEMORY:
DLOG << "CreateDebugUtilsMessengerEXT: out of host memory"; DLOG(0) << "CreateDebugUtilsMessengerEXT: out of host memory";
return false; return false;
default: default:
DLOG << "CreateDebugUtilsMessengerEXT: unknown failure"; DLOG(0) << "CreateDebugUtilsMessengerEXT: unknown failure";
return false; return false;
break; break;
} }
} }
vkGetPhysicalDeviceProperties(gpu_, &gpu_props_); vkGetPhysicalDeviceProperties(gpu_, &gpu_props_);
LOG << "Vulkan:"; LOG(0) << "Vulkan:";
LOG << " Name: " << gpu_props_.deviceName; LOG(0) << " Name: " << gpu_props_.deviceName;
LOG << " Tame: " << string_VkPhysicalDeviceType(gpu_props_.deviceType); LOG(0) << " Tame: " << string_VkPhysicalDeviceType(gpu_props_.deviceType);
LOG << " Vendor ID: " << gpu_props_.vendorID; LOG(0) << " Vendor ID: " << gpu_props_.vendorID;
LOG << " API version: " << VK_VERSION_MAJOR(gpu_props_.apiVersion) << "." LOG(0) << " API version: " << VK_VERSION_MAJOR(gpu_props_.apiVersion) << "."
<< VK_VERSION_MINOR(gpu_props_.apiVersion) << "." << VK_VERSION_MINOR(gpu_props_.apiVersion) << "."
<< VK_VERSION_PATCH(gpu_props_.apiVersion); << VK_VERSION_PATCH(gpu_props_.apiVersion);
LOG << " Driver version: " << VK_VERSION_MAJOR(gpu_props_.driverVersion) LOG(0) << " Driver version: " << VK_VERSION_MAJOR(gpu_props_.driverVersion)
<< "." << VK_VERSION_MINOR(gpu_props_.driverVersion) << "." << "." << VK_VERSION_MINOR(gpu_props_.driverVersion) << "."
<< VK_VERSION_PATCH(gpu_props_.driverVersion); << VK_VERSION_PATCH(gpu_props_.driverVersion);
// Call with NULL data to get count, // Call with NULL data to get count,
vkGetPhysicalDeviceQueueFamilyProperties(gpu_, &queue_family_count_, nullptr); vkGetPhysicalDeviceQueueFamilyProperties(gpu_, &queue_family_count_, nullptr);
if (queue_family_count_ == 0) { if (queue_family_count_ == 0) {
DLOG << "Failed to query queue family count."; DLOG(0) << "Failed to query queue family count.";
return false; return false;
} }
@ -610,7 +610,7 @@ bool VulkanContext::CreateDevice() {
} }
err = vkCreateDevice(gpu_, &sdevice, nullptr, &device_); err = vkCreateDevice(gpu_, &sdevice, nullptr, &device_);
if (err) { if (err) {
DLOG << "vkCreateDevice failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateDevice failed. Error: " << string_VkResult(err);
return false; return false;
} }
return true; return true;
@ -655,7 +655,7 @@ bool VulkanContext::InitializeQueues(VkSurfaceKHR surface) {
// Generate error if could not find both a graphics and a present queue // Generate error if could not find both a graphics and a present queue
if (graphics_queue_family_index == std::numeric_limits<uint32_t>::max() || if (graphics_queue_family_index == std::numeric_limits<uint32_t>::max() ||
present_queue_family_index == std::numeric_limits<uint32_t>::max()) { present_queue_family_index == std::numeric_limits<uint32_t>::max()) {
DLOG << "Could not find both graphics and present queues."; DLOG(0) << "Could not find both graphics and present queues.";
return false; return false;
} }
@ -688,16 +688,16 @@ bool VulkanContext::InitializeQueues(VkSurfaceKHR surface) {
VkResult err = VkResult err =
GetPhysicalDeviceSurfaceFormatsKHR(gpu_, surface, &format_count, nullptr); GetPhysicalDeviceSurfaceFormatsKHR(gpu_, surface, &format_count, nullptr);
if (err) { if (err) {
DLOG << "GetPhysicalDeviceSurfaceFormatsKHR failed. Error: " DLOG(0) << "GetPhysicalDeviceSurfaceFormatsKHR failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
auto surf_formats = std::make_unique<VkSurfaceFormatKHR[]>(format_count); auto surf_formats = std::make_unique<VkSurfaceFormatKHR[]>(format_count);
err = GetPhysicalDeviceSurfaceFormatsKHR(gpu_, surface, &format_count, err = GetPhysicalDeviceSurfaceFormatsKHR(gpu_, surface, &format_count,
surf_formats.get()); surf_formats.get());
if (err) { if (err) {
DLOG << "GetPhysicalDeviceSurfaceFormatsKHR failed. Error: " DLOG(0) << "GetPhysicalDeviceSurfaceFormatsKHR failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -714,7 +714,7 @@ bool VulkanContext::InitializeQueues(VkSurfaceKHR surface) {
format_ = desired_format; format_ = desired_format;
color_space_ = surf_formats[0].colorSpace; color_space_ = surf_formats[0].colorSpace;
} else if (format_count < 1) { } else if (format_count < 1) {
DLOG << "Format count less than 1."; DLOG(0) << "Format count less than 1.";
return false; return false;
} else { } else {
// Find the first format that we support. // Find the first format that we support.
@ -733,7 +733,7 @@ bool VulkanContext::InitializeQueues(VkSurfaceKHR surface) {
end_of_find_format: end_of_find_format:
if (format_ == VK_FORMAT_UNDEFINED) { if (format_ == VK_FORMAT_UNDEFINED) {
DLOG << "No usable surface format found."; DLOG(0) << "No usable surface format found.";
return false; return false;
} }
} }
@ -765,26 +765,26 @@ bool VulkanContext::CreateSemaphores() {
for (uint32_t i = 0; i < kFrameLag; i++) { for (uint32_t i = 0; i < kFrameLag; i++) {
err = vkCreateFence(device_, &fence_ci, nullptr, &fences_[i]); err = vkCreateFence(device_, &fence_ci, nullptr, &fences_[i]);
if (err) { if (err) {
DLOG << "vkCreateFence failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateFence failed. Error: " << string_VkResult(err);
return false; return false;
} }
err = vkCreateSemaphore(device_, &semaphoreCreateInfo, nullptr, err = vkCreateSemaphore(device_, &semaphoreCreateInfo, nullptr,
&image_acquired_semaphores_[i]); &image_acquired_semaphores_[i]);
if (err) { if (err) {
DLOG << "vkCreateSemaphore failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateSemaphore failed. Error: " << string_VkResult(err);
return false; return false;
} }
err = vkCreateSemaphore(device_, &semaphoreCreateInfo, nullptr, err = vkCreateSemaphore(device_, &semaphoreCreateInfo, nullptr,
&draw_complete_semaphores_[i]); &draw_complete_semaphores_[i]);
if (err) { if (err) {
DLOG << "vkCreateSemaphore failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateSemaphore failed. Error: " << string_VkResult(err);
return false; return false;
} }
if (separate_present_queue_) { if (separate_present_queue_) {
err = vkCreateSemaphore(device_, &semaphoreCreateInfo, nullptr, err = vkCreateSemaphore(device_, &semaphoreCreateInfo, nullptr,
&image_ownership_semaphores_[i]); &image_ownership_semaphores_[i]);
if (err) { if (err) {
DLOG << "vkCreateSemaphore failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateSemaphore failed. Error: " << string_VkResult(err);
return false; return false;
} }
} }
@ -856,8 +856,8 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = GetPhysicalDeviceSurfaceCapabilitiesKHR(gpu_, window->surface, err = GetPhysicalDeviceSurfaceCapabilitiesKHR(gpu_, window->surface,
&surf_capabilities); &surf_capabilities);
if (err) { if (err) {
DLOG << "GetPhysicalDeviceSurfaceCapabilitiesKHR failed. Error: " DLOG(0) << "GetPhysicalDeviceSurfaceCapabilitiesKHR failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -865,8 +865,8 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = GetPhysicalDeviceSurfacePresentModesKHR(gpu_, window->surface, err = GetPhysicalDeviceSurfacePresentModesKHR(gpu_, window->surface,
&present_mode_count, nullptr); &present_mode_count, nullptr);
if (err) { if (err) {
DLOG << "GetPhysicalDeviceSurfacePresentModesKHR failed. Error: " DLOG(0) << "GetPhysicalDeviceSurfacePresentModesKHR failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -875,8 +875,8 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = GetPhysicalDeviceSurfacePresentModesKHR( err = GetPhysicalDeviceSurfacePresentModesKHR(
gpu_, window->surface, &present_mode_count, present_modes.get()); gpu_, window->surface, &present_mode_count, present_modes.get());
if (err) { if (err) {
DLOG << "GetPhysicalDeviceSurfacePresentModesKHR failed. Error: " DLOG(0) << "GetPhysicalDeviceSurfacePresentModesKHR failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -947,7 +947,7 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
} }
if (swapchain_present_mode != fallback_present_mode) { if (swapchain_present_mode != fallback_present_mode) {
LOG << "Present mode " << swapchain_present_mode << " is not supported"; LOG(0) << "Present mode " << swapchain_present_mode << " is not supported";
swapchain_present_mode = fallback_present_mode; swapchain_present_mode = fallback_present_mode;
} }
@ -1023,7 +1023,7 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = CreateSwapchainKHR(device_, &swapchain_ci, nullptr, &window->swapchain); err = CreateSwapchainKHR(device_, &swapchain_ci, nullptr, &window->swapchain);
if (err) { if (err) {
DLOG << "CreateSwapchainKHR failed. Error: " << string_VkResult(err); DLOG(0) << "CreateSwapchainKHR failed. Error: " << string_VkResult(err);
return false; return false;
} }
@ -1031,7 +1031,7 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = GetSwapchainImagesKHR(device_, window->swapchain, &sp_image_count, err = GetSwapchainImagesKHR(device_, window->swapchain, &sp_image_count,
nullptr); nullptr);
if (err) { if (err) {
DLOG << "GetSwapchainImagesKHR failed. Error: " << string_VkResult(err); DLOG(0) << "GetSwapchainImagesKHR failed. Error: " << string_VkResult(err);
return false; return false;
} }
@ -1039,7 +1039,7 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
// Assign for the first time. // Assign for the first time.
swapchain_image_count_ = sp_image_count; swapchain_image_count_ = sp_image_count;
} else if (swapchain_image_count_ != sp_image_count) { } else if (swapchain_image_count_ != sp_image_count) {
DLOG << "Swapchain image count mismatch"; DLOG(0) << "Swapchain image count mismatch";
return false; return false;
} }
@ -1048,7 +1048,7 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = GetSwapchainImagesKHR(device_, window->swapchain, err = GetSwapchainImagesKHR(device_, window->swapchain,
&swapchain_image_count_, swapchain_images.get()); &swapchain_image_count_, swapchain_images.get());
if (err) { if (err) {
DLOG << "GetSwapchainImagesKHR failed. Error: " << string_VkResult(err); DLOG(0) << "GetSwapchainImagesKHR failed. Error: " << string_VkResult(err);
return false; return false;
} }
@ -1085,7 +1085,7 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = vkCreateImageView(device_, &color_image_view, nullptr, err = vkCreateImageView(device_, &color_image_view, nullptr,
&window->swapchain_image_resources[i].view); &window->swapchain_image_resources[i].view);
if (err) { if (err) {
DLOG << "vkCreateImageView failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateImageView failed. Error: " << string_VkResult(err);
return false; return false;
} }
} }
@ -1169,7 +1169,7 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = vkCreateRenderPass(device_, &rp_info, nullptr, &window->render_pass); err = vkCreateRenderPass(device_, &rp_info, nullptr, &window->render_pass);
if (err) { if (err) {
DLOG << "vkCreateRenderPass failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateRenderPass failed. Error: " << string_VkResult(err);
return false; return false;
} }
@ -1194,7 +1194,8 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
device_, &fb_info, nullptr, device_, &fb_info, nullptr,
&window->swapchain_image_resources[i].frame_buffer); &window->swapchain_image_resources[i].frame_buffer);
if (err) { if (err) {
DLOG << "vkCreateFramebuffer failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateFramebuffer failed. Error: "
<< string_VkResult(err);
return false; return false;
} }
} }
@ -1212,7 +1213,7 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = vkCreateCommandPool(device_, &present_cmd_pool_info, nullptr, err = vkCreateCommandPool(device_, &present_cmd_pool_info, nullptr,
&window->present_cmd_pool); &window->present_cmd_pool);
if (err) { if (err) {
DLOG << "vkCreateCommandPool failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateCommandPool failed. Error: " << string_VkResult(err);
return false; return false;
} }
@ -1228,8 +1229,8 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
device_, &present_cmd_info, device_, &present_cmd_info,
&window->swapchain_image_resources[i].graphics_to_present_cmd); &window->swapchain_image_resources[i].graphics_to_present_cmd);
if (err) { if (err) {
DLOG << "vkAllocateCommandBuffers failed. Error: " DLOG(0) << "vkAllocateCommandBuffers failed. Error: "
<< string_VkResult(err); << string_VkResult(err);
return false; return false;
} }
@ -1243,7 +1244,8 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
window->swapchain_image_resources[i].graphics_to_present_cmd, window->swapchain_image_resources[i].graphics_to_present_cmd,
&cmd_buf_info); &cmd_buf_info);
if (err) { if (err) {
DLOG << "vkBeginCommandBuffer failed. Error: " << string_VkResult(err); DLOG(0) << "vkBeginCommandBuffer failed. Error: "
<< string_VkResult(err);
return false; return false;
} }
@ -1267,7 +1269,7 @@ bool VulkanContext::UpdateSwapChain(Window* window) {
err = vkEndCommandBuffer( err = vkEndCommandBuffer(
window->swapchain_image_resources[i].graphics_to_present_cmd); window->swapchain_image_resources[i].graphics_to_present_cmd);
if (err) { if (err) {
DLOG << "vkEndCommandBuffer failed. Error: " << string_VkResult(err); DLOG(0) << "vkEndCommandBuffer failed. Error: " << string_VkResult(err);
return false; return false;
} }
} }
@ -1306,7 +1308,7 @@ bool VulkanContext::CreateDepthImage(Window* window) {
VkResult err = VkResult err =
vkCreateImage(device_, &depth_image_ci, nullptr, &window->depth_image); vkCreateImage(device_, &depth_image_ci, nullptr, &window->depth_image);
if (err) { if (err) {
DLOG << "vkCreateImage failed. Error: " << string_VkResult(err); DLOG(0) << "vkCreateImage failed. Error: " << string_VkResult(err);
return false; return false;
} }
@ -1325,7 +1327,7 @@ bool VulkanContext::CreateDepthImage(Window* window) {
} }
} }
if (mti == memProperties.memoryTypeCount) { if (mti == memProperties.memoryTypeCount) {
DLOG << "Memort type index not found."; DLOG(0) << "Memort type index not found.";
return false; return false;
} }
@ -1338,7 +1340,7 @@ bool VulkanContext::CreateDepthImage(Window* window) {
err = vkAllocateMemory(device_, &alloc_info, nullptr, err = vkAllocateMemory(device_, &alloc_info, nullptr,
&window->depth_image_memory); &window->depth_image_memory);
if (err) { if (err) {
DLOG << "vkAllocateMemory failed. Error: " << string_VkResult(err); DLOG(0) << "vkAllocateMemory failed. Error: " << string_VkResult(err);
return false; return false;
} }
@ -1375,7 +1377,7 @@ bool VulkanContext::CreateDepthImage(Window* window) {
if (err) { if (err) {
vkDestroyImage(device_, window->depth_image, nullptr); vkDestroyImage(device_, window->depth_image, nullptr);
vkFreeMemory(device_, window->depth_image_memory, nullptr); vkFreeMemory(device_, window->depth_image_memory, nullptr);
DLOG << "vkCreateImageView failed with error " << std::to_string(err); DLOG(0) << "vkCreateImageView failed with error " << std::to_string(err);
return false; return false;
} }
return true; return true;
@ -1408,7 +1410,7 @@ void VulkanContext::Flush(bool all) {
vkQueueSubmit(graphics_queue_, 1, &submit_info, VK_NULL_HANDLE); vkQueueSubmit(graphics_queue_, 1, &submit_info, VK_NULL_HANDLE);
command_buffers_[0] = nullptr; command_buffers_[0] = nullptr;
if (err) { if (err) {
DLOG << "vkQueueSubmit failed. Error: " << string_VkResult(err); DLOG(0) << "vkQueueSubmit failed. Error: " << string_VkResult(err);
return; return;
} }
@ -1443,16 +1445,16 @@ bool VulkanContext::PrepareBuffers() {
if (err == VK_ERROR_OUT_OF_DATE_KHR) { if (err == VK_ERROR_OUT_OF_DATE_KHR) {
// swapchain is out of date (e.g. the window was resized) and must be // swapchain is out of date (e.g. the window was resized) and must be
// recreated: // recreated:
DLOG << "Swapchain is out of date, recreating."; DLOG(0) << "Swapchain is out of date, recreating.";
UpdateSwapChain(&window_); UpdateSwapChain(&window_);
} else if (err == VK_SUBOPTIMAL_KHR) { } else if (err == VK_SUBOPTIMAL_KHR) {
// swapchain is not as optimal as it could be, but the platform's // swapchain is not as optimal as it could be, but the platform's
// presentation engine will still present the image correctly. // presentation engine will still present the image correctly.
DLOG << "Swapchain is suboptimal, recreating."; DLOG(0) << "Swapchain is suboptimal, recreating.";
UpdateSwapChain(&window_); UpdateSwapChain(&window_);
break; break;
} else if (err != VK_SUCCESS) { } else if (err != VK_SUCCESS) {
DLOG << "AcquireNextImageKHR failed. Error: " << string_VkResult(err); DLOG(0) << "AcquireNextImageKHR failed. Error: " << string_VkResult(err);
return false; return false;
} }
} while (err != VK_SUCCESS); } while (err != VK_SUCCESS);
@ -1489,7 +1491,7 @@ bool VulkanContext::SwapBuffers() {
submit_info.pSignalSemaphores = &draw_complete_semaphores_[frame_index_]; submit_info.pSignalSemaphores = &draw_complete_semaphores_[frame_index_];
err = vkQueueSubmit(graphics_queue_, 1, &submit_info, fences_[frame_index_]); err = vkQueueSubmit(graphics_queue_, 1, &submit_info, fences_[frame_index_]);
if (err) { if (err) {
DLOG << "vkQueueSubmit failed. Error: " << string_VkResult(err); DLOG(0) << "vkQueueSubmit failed. Error: " << string_VkResult(err);
return false; return false;
} }
@ -1520,7 +1522,7 @@ bool VulkanContext::SwapBuffers() {
submit_info.pSignalSemaphores = &image_ownership_semaphores_[frame_index_]; submit_info.pSignalSemaphores = &image_ownership_semaphores_[frame_index_];
err = vkQueueSubmit(present_queue_, 1, &submit_info, null_fence); err = vkQueueSubmit(present_queue_, 1, &submit_info, null_fence);
if (err) { if (err) {
DLOG << "vkQueueSubmit failed. Error: " << string_VkResult(err); DLOG(0) << "vkQueueSubmit failed. Error: " << string_VkResult(err);
return false; return false;
} }
} }
@ -1561,13 +1563,13 @@ bool VulkanContext::SwapBuffers() {
if (err == VK_ERROR_OUT_OF_DATE_KHR) { if (err == VK_ERROR_OUT_OF_DATE_KHR) {
// Swapchain is out of date (e.g. the window was resized) and must be // Swapchain is out of date (e.g. the window was resized) and must be
// recreated. // recreated.
DLOG << "Swapchain is out of date."; DLOG(0) << "Swapchain is out of date.";
} else if (err == VK_SUBOPTIMAL_KHR) { } else if (err == VK_SUBOPTIMAL_KHR) {
// Swapchain is not as optimal as it could be, but the platform's // Swapchain is not as optimal as it could be, but the platform's
// presentation engine will still present the image correctly. // presentation engine will still present the image correctly.
DLOG << "Swapchain is Suboptimal."; DLOG(0) << "Swapchain is Suboptimal.";
} else if (err) { } else if (err) {
DLOG << "QueuePresentKHR failed. Error: " << string_VkResult(err); DLOG(0) << "QueuePresentKHR failed. Error: " << string_VkResult(err);
return false; return false;
} }

View File

@ -19,8 +19,8 @@ bool VulkanContext::CreateWindow(ANativeWindow* window, int width, int height) {
VkResult err = VkResult err =
vkCreateAndroidSurfaceKHR(instance_, &surface_info, nullptr, &surface); vkCreateAndroidSurfaceKHR(instance_, &surface_info, nullptr, &surface);
if (err != VK_SUCCESS) { if (err != VK_SUCCESS) {
LOG << "vkCreateAndroidSurfaceKHR failed with error " LOG(0) << "vkCreateAndroidSurfaceKHR failed with error "
<< std::to_string(err); << std::to_string(err);
return false; return false;
} }

View File

@ -23,8 +23,8 @@ bool VulkanContext::CreateWindow(Display* display,
VkResult err = VkResult err =
vkCreateXlibSurfaceKHR(instance_, &surface_info, nullptr, &surface); vkCreateXlibSurfaceKHR(instance_, &surface_info, nullptr, &surface);
if (err != VK_SUCCESS) { if (err != VK_SUCCESS) {
LOG << "vkCreateAndroidSurfaceKHR failed with error " LOG(0) << "vkCreateAndroidSurfaceKHR failed with error "
<< std::to_string(err); << std::to_string(err);
return false; return false;
} }