Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
27
29
content
stringlengths
226
3.24k
codereview_new_cpp_data_788
int main(int argc, char** argv, char** envp) exit(1); } - dserver_rpc_set_executable_path(filename, strlen(filename)); - start_thread(&mldr_load_results); __builtin_unreachable(); Error handling, just in case (which is just exiting since we can't actually do anything without the server): ```suggestion if (dserver_rpc_set_executable_path(filename, strlen(filename)) < 0) { fprintf(stderr, "Failed to tell darlingserver about our executable path\n"); exit(1); } ``` int main(int argc, char** argv, char** envp) exit(1); } + if (dserver_rpc_set_executable_path(filename, strlen(filename)) < 0) { + fprintf(stderr, "Failed to tell darlingserver about our executable path\n"); + exit(1); + } + start_thread(&mldr_load_results); __builtin_unreachable();
codereview_new_cpp_data_789
static bool parse_smaps_firstline( static long _proc_pidinfo_pathinfo(int32_t pid, void* buffer, int32_t bufsize) { struct vchroot_unexpand_args args; - int rv = dserver_rpc_get_executable_path(pid, args.path, sizeof(args.path)); - if (rv < 0) - return rv; rv = vchroot_unexpand(&args); if (rv != 0) Like I said [here](https://github.com/darlinghq/darlingserver/pull/1/files#r842329980), negative error codes from RPC calls indicate internal errors; we should abort on internal errors (maybe handling this should be moved into the RPC wrapper code later). However, positive error codes are okay (e.g. in this case, it'd okay to get positive `ESRCH`). `_proc_pidinfo_pathinfo` is expected to return negative error codes, however, so when we get a positive error code from the server, we can negate it and return it to the user: ```suggestion if (rv < 0) { __simple_printf("dserver_rpc_get_executable_path failed internally: %d\n", rv); __simple_abort(); } else if (rv > 0) { return -rv; } ``` static bool parse_smaps_firstline( static long _proc_pidinfo_pathinfo(int32_t pid, void* buffer, int32_t bufsize) { struct vchroot_unexpand_args args; + uint64_t fullLength; + int rv = dserver_rpc_get_executable_path(pid, args.path, sizeof(args.path), &fullLength); + if (rv < 0) + { + __simple_printf("dserver_rpc_get_executable_path failed internally: %d\n", rv); + __simple_abort(); + } + else if (rv > 0) + { + return -rv; + } rv = vchroot_unexpand(&args); if (rv != 0)
codereview_new_cpp_data_832
/* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.3.9.9 */ - -#include "sessions.nanopb.h" //#include "FirebaseSessions/SourcesObjC/Protogen/nanopb/sessions.nanopb.h" This needs to be resolved - do we generate #ifs? /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.3.9.9 */ +#if SWIFT_PACKAGE +#import "SourcesObjC/Protogen/nanopb/sessions.nanopb.h" +#else +#import "FirebaseSessions/SourcesObjC/Protogen/nanopb/sessions.nanopb.h" +#endif // SWIFT_PACKAGE //#include "FirebaseSessions/SourcesObjC/Protogen/nanopb/sessions.nanopb.h"
codereview_new_cpp_data_871
/* - * Copyright 2019 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. ```suggestion * Copyright 2022 Google LLC ``` /* + * Copyright 2022 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
codereview_new_cpp_data_872
/* - * Copyright 2019 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. ```suggestion * Copyright 2022 Google LLC ``` /* + * Copyright 2022 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
codereview_new_cpp_data_957
bool ksdl_dladdr(const uintptr_t address, Dl_info* const info) for(uint32_t iSym = 0; iSym < symtabCmd->nsyms; iSym++) { - // When building with Xcode 14, symbol which n_type field equal - // to N_ENSYM will put the actual address to n_value field, see - // <mach-o/stab.h> - if (symbolTable[iSym].n_type == N_BNSYM || - symbolTable[iSym].n_type == N_ENSYM) { continue; } It seems it would not build on Xcodes prior to 14 bool ksdl_dladdr(const uintptr_t address, Dl_info* const info) for(uint32_t iSym = 0; iSym < symtabCmd->nsyms; iSym++) { + // Skip all debug N_STAB symbols + if ((symbolTable[iSym].n_type & N_STAB) > 0) + { continue; }
codereview_new_cpp_data_958
bool ksdl_dladdr(const uintptr_t address, Dl_info* const info) for(uint32_t iSym = 0; iSym < symtabCmd->nsyms; iSym++) { // Skip all debug N_STAB symbols - if ((symbolTable[iSym].n_type & N_STAB) > 0) { continue; } NIT: We actually want this to be zero, so this is a bit more specific. ```suggestion if ((symbolTable[iSym].n_type & N_STAB) != 0) ``` bool ksdl_dladdr(const uintptr_t address, Dl_info* const info) for(uint32_t iSym = 0; iSym < symtabCmd->nsyms; iSym++) { // Skip all debug N_STAB symbols + if ((symbolTable[iSym].n_type & N_STAB) != 0) { continue; }
codereview_new_cpp_data_959
bool ksobjc_ivarValue(const void* const objectPtr, int ivarIndex, void* dst) return false; } uintptr_t ivarPtr = (uintptr_t)&ivars->first; - const struct ivar_t *ivar = (void *)(ivarPtr + (uintptr_t)ivars->entsizeAndFlags * (uintptr_t)ivarIndex); uintptr_t valuePtr = (uintptr_t)objectPtr + (uintptr_t)*ivar->offset; if(!ksmem_copySafely((void*)valuePtr, dst, (int)ivar->size)) May I ask you to preserve project code style? ```suggestion const struct ivar_t* ivar = (void*)(ivarPtr + (uintptr_t)ivars->entsizeAndFlags * (uintptr_t)ivarIndex); ``` bool ksobjc_ivarValue(const void* const objectPtr, int ivarIndex, void* dst) return false; } uintptr_t ivarPtr = (uintptr_t)&ivars->first; + const struct ivar_t* ivar = (void*)(ivarPtr + (uintptr_t)ivars->entsizeAndFlags * (uintptr_t)ivarIndex); uintptr_t valuePtr = (uintptr_t)objectPtr + (uintptr_t)*ivar->offset; if(!ksmem_copySafely((void*)valuePtr, dst, (int)ivar->size))
codereview_new_cpp_data_1990
Java_com_duckduckgo_sync_crypto_SyncNativeLib_encrypt( ); // Release the input arrays - (*env)->ReleaseByteArrayElements(env, encryptedBytes, encryptedBytesElements, JNI_ABORT); - (*env)->ReleaseByteArrayElements(env, rawBytes, rawBytesElements, JNI_COMMIT); (*env)->ReleaseByteArrayElements(env, secretKey, secretKeyElements, JNI_ABORT); return result; if this is the value you want returned, you should not use JNI_ABORT, use commit instead. Java_com_duckduckgo_sync_crypto_SyncNativeLib_encrypt( ); // Release the input arrays + (*env)->ReleaseByteArrayElements(env, encryptedBytes, encryptedBytesElements, JNI_COMMIT); + (*env)->ReleaseByteArrayElements(env, rawBytes, rawBytesElements, JNI_ABORT); (*env)->ReleaseByteArrayElements(env, secretKey, secretKeyElements, JNI_ABORT); return result;
codereview_new_cpp_data_1991
DDGSyncCryptoResult ddgSyncEncrypt( return DDGSYNCCRYPTO_ENCRYPTION_FAILED; } - memcpy(&encryptedBytes[rawBytesLength + crypto_secretbox_MACBYTES], nonceBytes, crypto_secretbox_NONCEBYTES); return DDGSYNCCRYPTO_OK; } We can discard this change DDGSyncCryptoResult ddgSyncEncrypt( return DDGSYNCCRYPTO_ENCRYPTION_FAILED; } + memcpy(&encryptedBytes[crypto_secretbox_MACBYTES + rawBytesLength], nonceBytes, crypto_secretbox_NONCEBYTES); return DDGSYNCCRYPTO_OK; }
codereview_new_cpp_data_2209
std::string py_fetch_error() { // build error text std::ostringstream oss; for (Py_ssize_t i = 0, n = PyList_Size(formatted); i < n; i++) oss << as_std_string(PyList_GetItem(formatted, i)); std::string error = oss.str(); - int max_msg_len(Rf_asInteger(Rf_GetOption1(Rf_install("warning.length")))); if (error.size() > max_msg_len) { // R has a modest byte size limit for error messages, default 1000, user // adjustable up to 8170. Error messages beyond the limit are silently Out of an abundance of caution, I would recommend PROTECTing the result of `Rf_GetOption1` before calling `Rf_asInteger()`, then UNPROTECTing after. std::string py_fetch_error() { // build error text std::ostringstream oss; + // PyList_GetItem() returns a borrowed reference, no need to decref. for (Py_ssize_t i = 0, n = PyList_Size(formatted); i < n; i++) oss << as_std_string(PyList_GetItem(formatted, i)); std::string error = oss.str(); + SEXP max_msg_len_s = PROTECT(Rf_GetOption1(Rf_install("warning.length"))); + int max_msg_len(Rf_asInteger(max_msg_len_s)); + UNPROTECT(1); + if (error.size() > max_msg_len) { // R has a modest byte size limit for error messages, default 1000, user // adjustable up to 8170. Error messages beyond the limit are silently
codereview_new_cpp_data_2210
std::string py_fetch_error() { // build error text std::ostringstream oss; for (Py_ssize_t i = 0, n = PyList_Size(formatted); i < n; i++) oss << as_std_string(PyList_GetItem(formatted, i)); std::string error = oss.str(); - int max_msg_len(Rf_asInteger(Rf_GetOption1(Rf_install("warning.length")))); if (error.size() > max_msg_len) { // R has a modest byte size limit for error messages, default 1000, user // adjustable up to 8170. Error messages beyond the limit are silently nit: good practice to document as a reminder places where we're using Python APIs which provide borrowed references std::string py_fetch_error() { // build error text std::ostringstream oss; + // PyList_GetItem() returns a borrowed reference, no need to decref. for (Py_ssize_t i = 0, n = PyList_Size(formatted); i < n; i++) oss << as_std_string(PyList_GetItem(formatted, i)); std::string error = oss.str(); + SEXP max_msg_len_s = PROTECT(Rf_GetOption1(Rf_install("warning.length"))); + int max_msg_len(Rf_asInteger(max_msg_len_s)); + UNPROTECT(1); + if (error.size() > max_msg_len) { // R has a modest byte size limit for error messages, default 1000, user // adjustable up to 8170. Error messages beyond the limit are silently
codereview_new_cpp_data_2264
double integer_to_real(int x) { } void deprecate_to_char(const char* type_char) { - SEXP env = PROTECT(caller_env()); SEXP type = PROTECT(Rf_mkString(type_char)); SEXP fun = PROTECT(Rf_lang3(Rf_install(":::"), Rf_install("purrr"), Rf_install("deprecate_to_char"))); SEXP call = PROTECT(Rf_lang3(fun, type, env)); - Rf_eval(call, R_GetCurrentEnv()); UNPROTECT(4); } If `R_GetCurrentEnv()` worked (it is not functional), it would return the same thing as `caller_env()` above. double integer_to_real(int x) { } void deprecate_to_char(const char* type_char) { + SEXP env = PROTECT(current_env()); SEXP type = PROTECT(Rf_mkString(type_char)); SEXP fun = PROTECT(Rf_lang3(Rf_install(":::"), Rf_install("purrr"), Rf_install("deprecate_to_char"))); SEXP call = PROTECT(Rf_lang3(fun, type, env)); + Rf_eval(call, R_GlobalEnv); UNPROTECT(4); }
codereview_new_cpp_data_2349
SEXP pluck_impl(SEXP x, SEXP index, SEXP missing, SEXP strict_arg) { end: UNPROTECT(1); - return Rf_isNull(x) ? missing : x; } We usually do: ```suggestion return x == R_NilValue ? missing : x; ``` SEXP pluck_impl(SEXP x, SEXP index, SEXP missing, SEXP strict_arg) { end: UNPROTECT(1); + return x == R_NilValue ? missing : x; }
codereview_new_cpp_data_2840
r_obj* expr_vec_zap_srcref(r_obj* x) { attrib_zap_srcref(x); r_ssize n = r_length(x); for (r_ssize i = 0; i < n; ++i) { - r_list_poke(x, i, zap_srcref(r_list_get(x, i))); } FREE(1); Super minor, could use `v_x[i]` if you wanted, instead of `r_list_get()` r_obj* expr_vec_zap_srcref(r_obj* x) { attrib_zap_srcref(x); r_ssize n = r_length(x); + r_obj* const * v_x = r_list_cbegin(x); + for (r_ssize i = 0; i < n; ++i) { + r_list_poke(x, i, zap_srcref(v_x[i])); } FREE(1);
codereview_new_cpp_data_2841
enum is_number dbl_standalone_check_number(r_obj* x, } } - if (!r_as_bool(allow_decimal) && !r_dbl_is_decimal(value)) { return IS_NUMBER_false; } I guess we rely on these not being missing values. Seems reasonable because that would be a programmer mistake enum is_number dbl_standalone_check_number(r_obj* x, } } + if (!r_as_bool(allow_decimal) && !r_dbl_is_whole(value)) { return IS_NUMBER_false; }
codereview_new_cpp_data_2842
#include <rlang.h> -r_obj* ffi_standalone_check_is_bool(r_obj* x, - r_obj* allow_na, - r_obj* allow_null) { if (x == r_null) { return r_lgl(r_as_bool(allow_null)); } It does make me wonder if we should version them to begin with? Like `ffi_standalone_check_is_bool_1.0.7()`? Or is that too noisy? Maybe we hope that we mostly get them right the first time around so we don't have to version them much? #include <rlang.h> +r_obj* ffi_standalone_check_bool(r_obj* x, + r_obj* allow_na, + r_obj* allow_null) { if (x == r_null) { return r_lgl(r_as_bool(allow_null)); }
codereview_new_cpp_data_2844
r_obj* hash_value(XXH3_state_t* p_xx_state) { XXH64_hash_t high = hash.high64; XXH64_hash_t low = hash.low64; - // 32 for hash, 1 for terminating null added by `sprintf()` char out[32 + 1]; snprintf(out, sizeof(out), "%016" PRIx64 "%016" PRIx64, high, low); ```suggestion // 32 for hash, 1 for terminating null added by `snprintf()` ``` r_obj* hash_value(XXH3_state_t* p_xx_state) { XXH64_hash_t high = hash.high64; XXH64_hash_t low = hash.low64; + // 32 for hash, 1 for terminating null added by `snprintf()` char out[32 + 1]; snprintf(out, sizeof(out), "%016" PRIx64 "%016" PRIx64, high, low);
codereview_new_cpp_data_2862
r_ssize r_lgl_sum(r_obj* x, bool na_true) { } r_obj* r_lgl_which(r_obj* x, bool na_propagate) { - if (r_typeof(x) != R_TYPE_logical) { - r_stop_internal("Expected logical vector."); } const r_ssize n = r_length(x); Could use `r_stop_unexpected_type()`. r_ssize r_lgl_sum(r_obj* x, bool na_true) { } r_obj* r_lgl_which(r_obj* x, bool na_propagate) { + const enum r_type type = r_typeof(x); + + if (type != R_TYPE_logical) { + r_stop_unexpected_type(type); } const r_ssize n = r_length(x);
codereview_new_cpp_data_2901
Perl_thread_locale_init() /* On Windows, make sure new thread has per-thread locales enabled */ _configthreadlocale(_ENABLE_PER_THREAD_LOCALE); -# else /* This thread starts off in the C locale */ Perl_setlocale(LC_ALL, "C"); -# endif #endif } This (also) alters the behavior on Windows, I'm assuming that's intended but in that case it would be good to explicitly mention it in the commit message. Before this commit: - Win32 it called `_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);` - on everything else: it called `Perl_setlocale(LC_ALL, "C")` Now the `Perl_setlocale(LC_ALL, "C")` (or the variant with the for loop) is also called on Windows. Perl_thread_locale_init() /* On Windows, make sure new thread has per-thread locales enabled */ _configthreadlocale(_ENABLE_PER_THREAD_LOCALE); +# endif /* This thread starts off in the C locale */ Perl_setlocale(LC_ALL, "C"); #endif }
codereview_new_cpp_data_2902
S_aassign_scan(pTHX_ OP* o, bool rhs, int *scalars_p) if (o == effective_top_op) effective_top_op = next_kid; } - else - if (o == effective_top_op) - effective_top_op = o->op_sibparent; o = o->op_sibparent; /* try parent's next sibling */ } o = next_kid; Would it not be even clearer to also pull the `if` up on the same line as the `else`? S_aassign_scan(pTHX_ OP* o, bool rhs, int *scalars_p) if (o == effective_top_op) effective_top_op = next_kid; } + else if (o == effective_top_op) + effective_top_op = o->op_sibparent; o = o->op_sibparent; /* try parent's next sibling */ } o = next_kid;
codereview_new_cpp_data_3046
PG_MODULE_MAGIC; -#define BUILD_VERSION "1.0.1" #define PG_STAT_STATEMENTS_COLS 53 /* maximum of above */ #define PGSM_TEXT_FILE "/tmp/pg_stat_monitor_query" Version issue PG_MODULE_MAGIC; +#define BUILD_VERSION "1.1.0-dev" #define PG_STAT_STATEMENTS_COLS 53 /* maximum of above */ #define PGSM_TEXT_FILE "/tmp/pg_stat_monitor_query"
codereview_new_cpp_data_3047
pg_stat_monitor_internal(FunctionCallInfo fcinfo, SpinLockRelease(&e->mutex); } - /* In case plan is enable, there is no need to show 0 planid query */ if (tmp.info.cmd_type == CMD_SELECT && PGSM_QUERY_PLAN && planid == 0) continue; Minor nit: ```suggestion /* In case that query plan is enabled, there is no need to show 0 planid query */ ``` pg_stat_monitor_internal(FunctionCallInfo fcinfo, SpinLockRelease(&e->mutex); } + /* In case that query plan is enabled, there is no need to show 0 planid query */ if (tmp.info.cmd_type == CMD_SELECT && PGSM_QUERY_PLAN && planid == 0) continue;
codereview_new_cpp_data_4001
static int vine_manager_transfer_capacity_available(struct vine_manager *q, stru /* Provide a substitute file object to describe the peer. */ if(m->file->type != VINE_MINI_TASK) { - vine_file_delete(m->substitute); if((peer = vine_file_replica_table_find_worker(q, m->file->cached_name))) { char *peer_source = string_format("worker://%s:%d/%s", peer->transfer_addr, peer->transfer_port, m->file->cached_name); This might go away with the separate bug fix, but it looks dangerous to delete without setting m->substitute to null. static int vine_manager_transfer_capacity_available(struct vine_manager *q, stru /* Provide a substitute file object to describe the peer. */ if(m->file->type != VINE_MINI_TASK) { if((peer = vine_file_replica_table_find_worker(q, m->file->cached_name))) { char *peer_source = string_format("worker://%s:%d/%s", peer->transfer_addr, peer->transfer_port, m->file->cached_name);
codereview_new_cpp_data_4006
int main(int argc, char *argv[]) for(i=0;i<36;i++) { char filename[256]; sprintf(filename,"%d.cat.jpg",i); - vine_task_add_input(t,temp_file[i],filename,VINE_CACHE); } vine_task_add_input_file(t,"montage.sfx","montage.sfx",VINE_NOCACHE); vine_task_add_output_file(t,"mosaic.jpg","mosaic.jpg",VINE_NOCACHE); `vine_file_clone` here as above? Should we do the `vine_file_clone` inside `vine_task_add_input` anyway? int main(int argc, char *argv[]) for(i=0;i<36;i++) { char filename[256]; sprintf(filename,"%d.cat.jpg",i); + vine_task_add_input(t,vine_file_clone(temp_file[i]),filename,VINE_CACHE); } vine_task_add_input_file(t,"montage.sfx","montage.sfx",VINE_NOCACHE); vine_task_add_output_file(t,"mosaic.jpg","mosaic.jpg",VINE_NOCACHE);
codereview_new_cpp_data_4007
struct vine_file * vine_file_substitute_url( struct vine_file *f, const char *so return vine_file_create(source,0,f->cached_name,0,f->length,VINE_URL,0,0); } -struct vine_file * vine_file_temp() { - return vine_file_create("temp",0,0,0,0,VINE_TEMP,0,0); } struct vine_file * vine_file_buffer( const char *buffer_name,const char *data, int length ) As above, suggest adding a single argument as a cache name, or the basis of a cache name? struct vine_file * vine_file_substitute_url( struct vine_file *f, const char *so return vine_file_create(source,0,f->cached_name,0,f->length,VINE_URL,0,0); } +struct vine_file * vine_file_temp( const char *unique_name ) { + return vine_file_create("temp",0,unique_name,0,0,VINE_TEMP,0,0); } struct vine_file * vine_file_buffer( const char *buffer_name,const char *data, int length )
codereview_new_cpp_data_4008
Return true if this task can run with the resources currently available. static int task_resources_fit_now( struct vine_task *t ) { return (cores_allocated + t->resources_requested->cores <= local_resources->cores.total) && (memory_allocated + t->resources_requested->memory <= local_resources->memory.total) && If this is a temporary hack, remove it. But if it is fixing a bug, add a big explanation here. Return true if this task can run with the resources currently available. static int task_resources_fit_now( struct vine_task *t ) { + /* XXX removed disk space check due to problems running workers locally or multiple workers on a single node + * since default tasks request the entire reported disk space. questionable if this check useful in practice.*/ return (cores_allocated + t->resources_requested->cores <= local_resources->cores.total) && (memory_allocated + t->resources_requested->memory <= local_resources->memory.total) &&
codereview_new_cpp_data_4009
static void bucketing_cursor_w_pos_delete(bucketing_cursor_w_pos_t* cursor_pos) list_cursor_destroy(cursor_pos->lc); free(cursor_pos); } - else - warn(D_BUCKETING, "ignoring command to delete null pointer to bucketing_cursor_w_pos\n"); } /* Create a bucketing_bucket_range_t structure Remove these warnings. static void bucketing_cursor_w_pos_delete(bucketing_cursor_w_pos_t* cursor_pos) list_cursor_destroy(cursor_pos->lc); free(cursor_pos); } } /* Create a bucketing_bucket_range_t structure
codereview_new_cpp_data_4010
void bucketing_state_delete(bucketing_state_t* s) void bucketing_state_tune(bucketing_state_t* s, const char* field, void* val) { - if (!s){ fatal("No bucketing state to tune\n"); return; } - if (!field){ fatal("No field in bucketing state to tune\n"); return; } - if (!val){ fatal("No value to tune field %s in bucketing state to\n", field); return; } Add space after ), e.g.: `if(!s) {` void bucketing_state_delete(bucketing_state_t* s) void bucketing_state_tune(bucketing_state_t* s, const char* field, void* val) { + if (!s) { fatal("No bucketing state to tune\n"); return; } + if (!field) { fatal("No field in bucketing state to tune\n"); return; } + if (!val) { fatal("No value to tune field %s in bucketing state to\n", field); return; }
codereview_new_cpp_data_4011
/* -Copyright (C) 2022 The University of Notre Dame This software is distributed under the GNU General Public License. See the file COPYING for details. */ We do want the hyphen. 2022- /* +Copyright (C) 2022- The University of Notre Dame This software is distributed under the GNU General Public License. See the file COPYING for details. */
codereview_new_cpp_data_4548
namespace fheroes2 Blit( _staticImage, 0, 0, output, offset.x, offset.y, _staticImage.width(), _staticImage.height() ); } - const Sprite & animationImage = AGG::GetICN( _animationIcnId, ICN::AnimationFrame( _animationIcnId, _animationIndexOffset, _currentIndex++ ) ); Blit( animationImage, 0, 0, output, offset.x + _animationPosition.x, offset.y + _animationPosition.y, animationImage.width(), animationImage.height() ); } Please do not combine multiple expressions into one line. Increment **_currentIndex** on a separate line. namespace fheroes2 Blit( _staticImage, 0, 0, output, offset.x, offset.y, _staticImage.width(), _staticImage.height() ); } + const uint32_t animationFrameId = ICN::AnimationFrame( _animationIcnId, _animationIndexOffset, _currentIndex ); + ++_currentIndex; + + const Sprite & animationImage = AGG::GetICN( _animationIcnId, animationFrameId); + Blit( animationImage, 0, 0, output, offset.x + _animationPosition.x, offset.y + _animationPosition.y, animationImage.width(), animationImage.height() ); }
codereview_new_cpp_data_4549
void Maps::Tiles::QuantityUpdate( bool isFirstLoad ) static_assert( std::is_same_v<decltype( quantity1 ), uint8_t> && std::is_same_v<decltype( quantity2 ), uint8_t>, "Type of quantity1 or quantity2 has been changed, check the logic below" ); - int spell = ( 1 + ( quantity2 << 5 ) + ( quantity1 >> 3 ) ) & 0xFF; QuantitySetVariant( 15 ); QuantitySetSpell( spell ); :warning: **misc\-redundant\-expression** :warning: both sides of operator are equivalent void Maps::Tiles::QuantityUpdate( bool isFirstLoad ) static_assert( std::is_same_v<decltype( quantity1 ), uint8_t> && std::is_same_v<decltype( quantity2 ), uint8_t>, "Type of quantity1 or quantity2 has been changed, check the logic below" ); + const int spell = ( 1 + ( quantity2 << 5 ) + ( quantity1 >> 3 ) ) & 0xFF; QuantitySetVariant( 15 ); QuantitySetSpell( spell );
codereview_new_cpp_data_4550
#include "serialize.h" #include "system.h" -namespace -{ - constexpr uint8_t spriteBackground = 0; -} - int main( int argc, char ** argv ) { if ( argc < 3 ) { :warning: **clang\-diagnostic\-unused\-const\-variable** :warning: unused variable `` spriteBackground `` #include "serialize.h" #include "system.h" int main( int argc, char ** argv ) { if ( argc < 3 ) {
codereview_new_cpp_data_4551
int main( int argc, char ** argv ) std::string baseName = System::GetBasename( argv[0] ); std::cerr << baseName << " generates an image with colors based on a provided palette file." << std::endl - << "Syntax: " << baseName << " palette_file.pal output.bmp" << std::endl; return EXIT_FAILURE; } I replaced imperative mood by the indicative one to match other tools. int main( int argc, char ** argv ) std::string baseName = System::GetBasename( argv[0] ); std::cerr << baseName << " generates an image with colors based on a provided palette file." << std::endl + << "Syntax: " << baseName << " palette_file.pal output.[bmp|png]" << std::endl; return EXIT_FAILURE; }
codereview_new_cpp_data_4552
int main( int argc, char ** argv ) std::string baseName = System::GetBasename( argv[0] ); std::cerr << baseName << " generates an image with colors based on a provided palette file." << std::endl - << "Syntax: " << baseName << " palette_file.pal output.bmp" << std::endl; return EXIT_FAILURE; } This tool may (and will, if built with `FHEROES2_WITH_IMAGE` and I pass the `output.png` as the second parameter) also generate PNG files. You can add this to the description, for example: ```suggestion << "Syntax: " << baseName << " palette_file.pal output.[bmp|png]" << std::endl; ``` or you can not add it - it's up to you. int main( int argc, char ** argv ) std::string baseName = System::GetBasename( argv[0] ); std::cerr << baseName << " generates an image with colors based on a provided palette file." << std::endl + << "Syntax: " << baseName << " palette_file.pal output.[bmp|png]" << std::endl; return EXIT_FAILURE; }
codereview_new_cpp_data_4553
namespace fheroes2 { assert( data != nullptr && imageCount > 0 && width > 0 && height > 0 ); - output.clear(); output.resize( imageCount ); const size_t imageSize = static_cast<size_t>( width * height ); :warning: **bugprone\-misplaced\-widening\-cast** :warning: either cast from `` int `` to `` size_t `` \(aka `` unsigned long ``\) is ineffective, or there is loss of precision before the conversion namespace fheroes2 { assert( data != nullptr && imageCount > 0 && width > 0 && height > 0 ); output.resize( imageCount ); const size_t imageSize = static_cast<size_t>( width * height );
codereview_new_cpp_data_4554
namespace fheroes2 output.resize( imageCount ); - const size_t imageSize = static_cast<size_t>( width * height ); for ( size_t i = 0; i < imageCount; ++i ) { Image & tilImage = output[i]; We can avoid this warning this way: ```suggestion const size_t imageSize = static_cast<size_t>( width ) * height; ``` namespace fheroes2 output.resize( imageCount ); + const size_t imageSize = static_cast<size_t>( width ) * height; for ( size_t i = 0; i < imageCount; ++i ) { Image & tilImage = output[i];
codereview_new_cpp_data_4555
namespace { const int32_t borderSize{ BORDERWIDTH }; - // Offset from border edges (size of evil interface corners is 43 pixels) - this edges (corners) will not be copied to fill the border. const int32_t borderEdgeOffset{ 43 }; // Size in pixels of dithered transition from one image to another. ```suggestion // Offset from border edges (size of evil interface corners is 43 pixels) - these edges (corners) will not be copied to fill the border. ``` namespace { const int32_t borderSize{ BORDERWIDTH }; + // Offset from border edges (size of evil interface corners is 43 pixels) - these edges (corners) will not be copied to fill the border. const int32_t borderEdgeOffset{ 43 }; // Size in pixels of dithered transition from one image to another.
codereview_new_cpp_data_4556
namespace AI double cellThreatLevel = 0.0; for ( const Unit * enemy : enemies ) { - // Archers and Flyers are always threating, skip if ( enemy->isFlying() || ( enemy->isArchers() && !enemy->isHandFighting() ) ) { continue; } See comment in different part. ```suggestion // Archers and Flyers are always threatening, skip ``` namespace AI double cellThreatLevel = 0.0; for ( const Unit * enemy : enemies ) { + // Archers and Flyers are always threatening, skip if ( enemy->isFlying() || ( enemy->isArchers() && !enemy->isHandFighting() ) ) { continue; }
codereview_new_cpp_data_4557
void ActionToArtifact( Heroes & hero, int32_t dst_index ) } } else - // 4,5 - need have skill wizard or leadership, if ( 3 < cond && cond < 6 ) { const Skill::Secondary & skill = tile.QuantitySkill(); Also should this be "wisdom" and not "wizard"? ```suggestion // 4,5 - need to have skill wizard or leadership, ``` void ActionToArtifact( Heroes & hero, int32_t dst_index ) } } else + // 4,5 - need to have skill wisdom or leadership if ( 3 < cond && cond < 6 ) { const Skill::Secondary & skill = tile.QuantitySkill();
codereview_new_cpp_data_4558
void Maps::Tiles::QuantityUpdate( bool isFirstLoad ) else { // 0: 70% none // 1,2,3 - 2000g, 2500g+3res, 3000g+5res, - // 4,5 - need have skill wizard or leadership, // 6 - 50 rogues, 7 - 1 gin, 8,9,10,11,12,13 - 1 monster level4, // 15 - spell int cond = Rand::Get( 1, 10 ) < 4 ? Rand::Get( 1, 13 ) : 0; Should this be "wisdom"? ```suggestion // 4,5 - need to have skill wizard or leadership, ``` void Maps::Tiles::QuantityUpdate( bool isFirstLoad ) else { // 0: 70% none // 1,2,3 - 2000g, 2500g+3res, 3000g+5res, + // 4,5 - need to have skill wisdom or leadership, // 6 - 50 rogues, 7 - 1 gin, 8,9,10,11,12,13 - 1 monster level4, // 15 - spell int cond = Rand::Get( 1, 10 ) < 4 ? Rand::Get( 1, 13 ) : 0;
codereview_new_cpp_data_4559
void Interface::GameArea::Redraw( fheroes2::Image & dst, int flag, bool isPuzzle --greenColorSteps; } - // Not all arrows and their shadows fit in 1 tile. We need to consider an area of 1 tile bigger area to properly render everything. const fheroes2::Rect extendedVisibleRoi{ tileROI.x - 1, tileROI.y - 1, tileROI.width + 2, tileROI.height + 2 }; for ( ; currentStep != path.end(); ++currentStep ) { ```suggestion // Not all arrows and their shadows fit in 1 tile. We need to consider an area of 1 tile bigger to properly render everything. ``` void Interface::GameArea::Redraw( fheroes2::Image & dst, int flag, bool isPuzzle --greenColorSteps; } + // Not all arrows and their shadows fit in 1 tile. We need to consider an area of 1 tile bigger to properly render everything. const fheroes2::Rect extendedVisibleRoi{ tileROI.x - 1, tileROI.y - 1, tileROI.width + 2, tileROI.height + 2 }; for ( ; currentStep != path.end(); ++currentStep ) {
codereview_new_cpp_data_4560
int main( int argc, char ** argv ) const size_t inputStreamSize = inputStream.size(); const uint16_t itemsCount = inputStream.getLE16(); - StreamBuf itemsStream = inputStream.toStreamBuf( itemsCount * 4 * 3 /* hash, offset, size */ ); inputStream.seek( inputStreamSize - AGGItemNameLen * itemsCount ); StreamBuf namesStream = inputStream.toStreamBuf( AGGItemNameLen * itemsCount ); :warning: **bugprone\-implicit\-widening\-of\-multiplication\-result** :warning: performing an implicit widening conversion to type `` size_t `` \(aka `` unsigned long ``\) of a multiplication performed in type `` int `` int main( int argc, char ** argv ) const size_t inputStreamSize = inputStream.size(); const uint16_t itemsCount = inputStream.getLE16(); + StreamBuf itemsStream = inputStream.toStreamBuf( static_cast<size_t>( itemsCount ) * 4 * 3 /* hash, offset, size */ ); inputStream.seek( inputStreamSize - AGGItemNameLen * itemsCount ); StreamBuf namesStream = inputStream.toStreamBuf( AGGItemNameLen * itemsCount );
codereview_new_cpp_data_4561
namespace fheroes2 const CustomImageDialogElement lighthouseImageElement( combined ); - std::string lighthouseControlledString = _( "%{count}" ); - StringReplace( lighthouseControlledString, "%{count}", std::to_string( lighthouseCount ) ); - const Text lighthouseControlledText( lighthouseControlledString, FontType::normalWhite() ); const TextDialogElement lighthouseControlledElement( std::make_shared<Text>( lighthouseControlledText ) ); showMessage( Text( header, FontType::normalYellow() ), Text( body, FontType::normalWhite() ), buttons, There is no need to translate a number. **std::to_string()** would be sufficient. namespace fheroes2 const CustomImageDialogElement lighthouseImageElement( combined ); + const Text lighthouseControlledText( std::to_string( lighthouseCount ), FontType::normalWhite() ); const TextDialogElement lighthouseControlledElement( std::make_shared<Text>( lighthouseControlledText ) ); showMessage( Text( header, FontType::normalYellow() ), Text( body, FontType::normalWhite() ), buttons,
codereview_new_cpp_data_4562
void Kingdom::openOverviewDialog() Dialog::Message( _( "Exit" ), _( "Exit this menu." ), Font::BIG ); } else if ( le.MousePressRight( rectIncome ) ) { - fheroes2::showKingdomIncome( *this, 0 ); } else if ( le.MousePressRight( rectLighthouse ) ) { - fheroes2::showLighthouseInfo( *this, 0 ); } // Exit this dialog. Please use **Dialog::ZERO** instead of **0**. void Kingdom::openOverviewDialog() Dialog::Message( _( "Exit" ), _( "Exit this menu." ), Font::BIG ); } else if ( le.MousePressRight( rectIncome ) ) { + fheroes2::showKingdomIncome( *this, Dialog::ZERO ); } else if ( le.MousePressRight( rectLighthouse ) ) { + fheroes2::showLighthouseInfo( *this, Dialog::ZERO ); } // Exit this dialog.
codereview_new_cpp_data_4563
namespace AI return target; } - Actions BattlePlanner::berserkTurn( Arena & arena, const Unit & currentUnit ) const { assert( currentUnit.Modes( SP_BERSERKER ) ); :warning: **readability\-convert\-member\-functions\-to\-static** :warning: method `` berserkTurn `` can be made static ```suggestion Actions BattlePlanner::berserkTurn( Arena & arena, const Unit & currentUnit ) ``` namespace AI return target; } + Actions BattlePlanner::berserkTurn( Arena & arena, const Unit & currentUnit ) { assert( currentUnit.Modes( SP_BERSERKER ) );
codereview_new_cpp_data_4564
namespace if ( hero != nullptr ) { hero->PickupArtifact( Artifact( awards[i]._subType ) ); - } - // Some artifacts increase the Spell Power of the hero we have to set spell points to maximum. - hero->SetSpellPoints( std::max( hero->GetSpellPoints(), hero->GetMaxSpellPoints() ) ); break; } Hi @ihhub please move this under the `if ( hero != nullptr )` condition after the `hero->PickupArtifact()` call. namespace if ( hero != nullptr ) { hero->PickupArtifact( Artifact( awards[i]._subType ) ); + // Some artifacts increase the Spell Power of the hero we have to set spell points to maximum. + hero->SetSpellPoints( std::max( hero->GetSpellPoints(), hero->GetMaxSpellPoints() ) ); + } break; }
codereview_new_cpp_data_4565
void ActionToMagellanMaps( Heroes & hero, const MP2::MapObjectType objectType, i hero.setVisitedForAllies( dst_index ); Interface::Basic & I = Interface::Basic::Get(); - I.GetRadar().SetRenderWholeMap(); I.SetRedraw( Interface::REDRAW_GAMEAREA | Interface::REDRAW_RADAR ); } } Do we need this call to be present since we reset ROI after each render? void ActionToMagellanMaps( Heroes & hero, const MP2::MapObjectType objectType, i hero.setVisitedForAllies( dst_index ); Interface::Basic & I = Interface::Basic::Get(); + I.GetRadar().SetRenderMap(); I.SetRedraw( Interface::REDRAW_GAMEAREA | Interface::REDRAW_RADAR ); } }
codereview_new_cpp_data_4566
void Heroes::MeetingDialog( Heroes & otherHero ) ScoutRadar(); } if ( hero2ScoutAreaBonus < otherHero.GetBagArtifacts().getTotalArtifactEffectValue( fheroes2::ArtifactBonusType::AREA_REVEAL_DISTANCE ) ) { - Scoute( otherHero.GetIndex() ); otherHero.ScoutRadar(); } IMHO this looks wrong. This call will scout tiles **_as-if_** the current hero is scouting, but while standing on the other hero's position, which is wrong, because the other hero may have different scouting radius. void Heroes::MeetingDialog( Heroes & otherHero ) ScoutRadar(); } if ( hero2ScoutAreaBonus < otherHero.GetBagArtifacts().getTotalArtifactEffectValue( fheroes2::ArtifactBonusType::AREA_REVEAL_DISTANCE ) ) { + otherHero.Scoute( otherHero.GetIndex() ); otherHero.ScoutRadar(); }
codereview_new_cpp_data_4567
fheroes2::Rect Heroes::GetScoutRoi( const bool ignoreDirection /* = false */ ) c } return { heroPosition.x - ( ( direction == Direction::RIGHT ) ? 1 : scoutRange ), heroPosition.y - ( ( direction == Direction::BOTTOM ) ? 1 : scoutRange ), - ( ( direction == Direction::LEFT || direction == Direction::RIGHT ) ? 0 : scoutRange ) + scoutRange + 1, - ( ( direction == Direction::TOP || direction == Direction::BOTTOM ) ? 0 : scoutRange ) + scoutRange + 1 }; } uint32_t Heroes::UpdateMovementPoints( const uint32_t movePoints, const int skill ) const ```suggestion ( ( direction == Direction::LEFT || direction == Direction::RIGHT ) ? 1 : scoutRange ) + scoutRange + 1, ( ( direction == Direction::TOP || direction == Direction::BOTTOM ) ? 1 : scoutRange ) + scoutRange + 1 }; ``` fheroes2::Rect Heroes::GetScoutRoi( const bool ignoreDirection /* = false */ ) c } return { heroPosition.x - ( ( direction == Direction::RIGHT ) ? 1 : scoutRange ), heroPosition.y - ( ( direction == Direction::BOTTOM ) ? 1 : scoutRange ), + ( ( direction == Direction::LEFT || direction == Direction::RIGHT ) ? 1 : scoutRange ) + scoutRange + 1, + ( ( direction == Direction::TOP || direction == Direction::BOTTOM ) ? 1 : scoutRange ) + scoutRange + 1 }; } uint32_t Heroes::UpdateMovementPoints( const uint32_t movePoints, const int skill ) const
codereview_new_cpp_data_4568
void Interface::Radar::SetZoom() void Interface::Radar::SetRedraw( const uint32_t redrawMode ) const { // Only radar redraws are allowed here. - assert( redrawMode & ( REDRAW_RADAR_CURSOR | REDRAW_RADAR ) ); _interface.SetRedraw( redrawMode ); } Hi @Districh-ru The whole point of this check is to verify that ONLY `REDRAW_RADAR_CURSOR` and/or `REDRAW_RADAR` can be passed as `redrawMode` (or zero which is acceptable too because it changes nothing). What if `redrawMode` will be equal to, say, `REDRAW_RADAR_CURSOR | REDRAW_BUTTONS`? In this case this `assert()` will not fail, while this one: ```cpp assert( ( redrawMode & ~( REDRAW_RADAR_CURSOR | REDRAW_RADAR ) ) == 0 ); ``` will fail, right? void Interface::Radar::SetZoom() void Interface::Radar::SetRedraw( const uint32_t redrawMode ) const { // Only radar redraws are allowed here. + assert( ( redrawMode & ~( REDRAW_RADAR_CURSOR | REDRAW_RADAR ) ) == 0 ); _interface.SetRedraw( redrawMode ); }
codereview_new_cpp_data_4569
namespace fheroes2 basicInterface.Reset(); // We need to redraw radar first due to the nature of restorers. Only then we can redraw everything. - basicInterface.Redraw( Interface::REDRAW_RADAR_CURSOR ); - basicInterface.Redraw( Interface::REDRAW_ALL ); action = DialogAction::Open; break; I suggest to exclude radar rendering from this line since we render it just at the line above. namespace fheroes2 basicInterface.Reset(); // We need to redraw radar first due to the nature of restorers. Only then we can redraw everything. + // And we do a full radar redraw as it could be hidden in "Hide Interface" mode so it was not updated. + basicInterface.Redraw( Interface::REDRAW_RADAR ); + basicInterface.Redraw( Interface::REDRAW_ALL & ~( Interface::REDRAW_RADAR_CURSOR | Interface::REDRAW_RADAR ) ); action = DialogAction::Open; break;
codereview_new_cpp_data_4570
void Heroes::MeetingDialog( Heroes & otherHero ) // If the scout area bonus is increased with the new artifact we reveal the fog and update the radar. if ( hero1ScoutAreaBonus < bag_artifacts.getTotalArtifactEffectValue( fheroes2::ArtifactBonusType::AREA_REVEAL_DISTANCE ) ) { - Scoute( this->GetIndex() ); ScoutRadar(); } if ( hero2ScoutAreaBonus < otherHero.GetBagArtifacts().getTotalArtifactEffectValue( fheroes2::ArtifactBonusType::AREA_REVEAL_DISTANCE ) ) { Please remove `this->`: ```cpp Scoute( GetIndex() ); ``` void Heroes::MeetingDialog( Heroes & otherHero ) // If the scout area bonus is increased with the new artifact we reveal the fog and update the radar. if ( hero1ScoutAreaBonus < bag_artifacts.getTotalArtifactEffectValue( fheroes2::ArtifactBonusType::AREA_REVEAL_DISTANCE ) ) { + Scoute( GetIndex() ); ScoutRadar(); } if ( hero2ScoutAreaBonus < otherHero.GetBagArtifacts().getTotalArtifactEffectValue( fheroes2::ArtifactBonusType::AREA_REVEAL_DISTANCE ) ) {
codereview_new_cpp_data_4571
bool World::LoadMapMP2( const std::string & filename, const bool isOriginalMp2Fi case MP2::OBJ_EXPANSION_DWELLING: case MP2::OBJ_EXPANSION_OBJECT: case MP2::OBJ_JAIL: - DEBUG_LOG( DBG_GAME, DBG_INFO, "Failed to load The Price of Loyalty '" << filename << "' map which is not supported by this version of the game." ) // You are trying to load a PoL map named as a MP2 file. return false; default: Don't you think that "Failed to load The Price of Loyalty map MAP.MP2 which is not supported by this version of the game" looks better than "Failed to load The Price of Loyalty MAP.MP2 map which is not supported by this version of the game"? bool World::LoadMapMP2( const std::string & filename, const bool isOriginalMp2Fi case MP2::OBJ_EXPANSION_DWELLING: case MP2::OBJ_EXPANSION_OBJECT: case MP2::OBJ_JAIL: + DEBUG_LOG( DBG_GAME, DBG_INFO, "Failed to load The Price of Loyalty map '" << filename << "' which is not supported by this version of the game." ) // You are trying to load a PoL map named as a MP2 file. return false; default:
codereview_new_cpp_data_4572
namespace AI // Then consider the stacks from the graveyard for ( const int32_t idx : arena.GraveyardOccupiedCells() ) { - const Unit * unit = arena.GraveyardLastTroop( idx ); - assert( unit != nullptr && !unit->isValid() ); - if ( !arena.GraveyardAllowResurrect( idx, spell ) ) { continue; } updateBestOutcome( unit ); } Should we allow to resurrect any unit on a cell, not only the last one? namespace AI // Then consider the stacks from the graveyard for ( const int32_t idx : arena.GraveyardOccupiedCells() ) { if ( !arena.GraveyardAllowResurrect( idx, spell ) ) { continue; } + const Unit * unit = arena.GraveyardLastTroop( idx ); + assert( unit != nullptr && !unit->isValid() ); + updateBestOutcome( unit ); }
codereview_new_cpp_data_4573
void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit } const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; - const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t) spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage; :warning: **bugprone\-narrowing\-conversions** :warning: narrowing conversion from `` uint32_t `` \(aka `` unsigned int ``\) to signed type `` int `` is implementation\-defined void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit } const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; + const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t)spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage;
codereview_new_cpp_data_4574
void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit } const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; - const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t) spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage; :warning: **bugprone\-narrowing\-conversions** :warning: narrowing conversion from `` uint32_t `` \(aka `` unsigned int ``\) to signed type `` int `` is implementation\-defined void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit } const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; + const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t)spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage;
codereview_new_cpp_data_4575
void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit } const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; - const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t)spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage; :warning: **bugprone\-narrowing\-conversions** :warning: narrowing conversion from `` uint32_t `` \(aka `` unsigned int ``\) to signed type `` int `` is implementation\-defined void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit } const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; + const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t)spellPoints, hero, (uint32_t)0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage;
codereview_new_cpp_data_4576
void Battle::PopupDamageInfo::SetAttackInfo( const Cell * cell, const Unit * att void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const HeroBase * hero, const Unit * defender, const Spell spell ) { - if ( hero == nullptr || !SetDamageInfoBase( cell, defender ) ) { return; } - // Only show popup for single target damage spells such as bolt, arrow, or cold ray - if ( !spell.isSingleTarget() || !spell.isDamage() ) { return; } I see no big reason not to show for mass spells like Chain Lighting or Cold Ring. We should add such support in the future. Therefore I suggest to at least add a TODO comment explaining what is missing. void Battle::PopupDamageInfo::SetAttackInfo( const Cell * cell, const Unit * att void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const HeroBase * hero, const Unit * defender, const Spell spell ) { + assert( hero != nullptr ); + + // TODO: Currently, this functionality only supports a simple single-target spell case + // We should refactor this to apply to all cases + if ( !spell.isSingleTarget() || !spell.isDamage() ) { return; } + if ( !SetDamageInfoBase( cell, defender ) ) { return; }
codereview_new_cpp_data_4577
void Battle::PopupDamageInfo::SetAttackInfo( const Cell * cell, const Unit * att void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const HeroBase * hero, const Unit * defender, const Spell spell ) { - if ( hero == nullptr || !SetDamageInfoBase( cell, defender ) ) { return; } - // Only show popup for single target damage spells such as bolt, arrow, or cold ray - if ( !spell.isSingleTarget() || !spell.isDamage() ) { return; } These checks should go before the first if where we call **!SetDamageInfoBase()** method. This method is computational heavy. void Battle::PopupDamageInfo::SetAttackInfo( const Cell * cell, const Unit * att void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const HeroBase * hero, const Unit * defender, const Spell spell ) { + assert( hero != nullptr ); + + // TODO: Currently, this functionality only supports a simple single-target spell case + // We should refactor this to apply to all cases + if ( !spell.isSingleTarget() || !spell.isDamage() ) { return; } + if ( !SetDamageInfoBase( cell, defender ) ) { return; }
codereview_new_cpp_data_4578
void Battle::PopupDamageInfo::SetAttackInfo( const Cell * cell, const Unit * att void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const HeroBase * hero, const Unit * defender, const Spell spell ) { - if ( hero == nullptr || !SetDamageInfoBase( cell, defender ) ) { return; } - // Only show popup for single target damage spells such as bolt, arrow, or cold ray - if ( !spell.isSingleTarget() || !spell.isDamage() ) { return; } If there a possibility that a hero who suppose to cast a spell is absent? If not we should just add an assertion for nullptr check for **hero** input argument. void Battle::PopupDamageInfo::SetAttackInfo( const Cell * cell, const Unit * att void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const HeroBase * hero, const Unit * defender, const Spell spell ) { + assert( hero != nullptr ); + + // TODO: Currently, this functionality only supports a simple single-target spell case + // We should refactor this to apply to all cases + if ( !spell.isSingleTarget() || !spell.isDamage() ) { return; } + if ( !SetDamageInfoBase( cell, defender ) ) { return; }
codereview_new_cpp_data_4579
void Battle::Interface::RedrawActionWincesKills( const TargetsInfo & targets, Un // There sould not be more Lich cloud animation frames than in corresponding ICN. assert( lichCloudFrame <= lichCloudMaxFrame ); - // Important: 'lichCloudFrame' can be more than 'lichCloudMaxFrame' when performing some long 'KILL' animations. if ( ( animatingTargets == finishedAnimationCount ) && ( !drawLichCloud || ( lichCloudFrame == lichCloudMaxFrame ) ) ) { // All unit animation frames are rendered and if it was a Lich attack then also its cloud frames are rendered too. break; Hi @Districh-ru please remove this comment. void Battle::Interface::RedrawActionWincesKills( const TargetsInfo & targets, Un // There sould not be more Lich cloud animation frames than in corresponding ICN. assert( lichCloudFrame <= lichCloudMaxFrame ); if ( ( animatingTargets == finishedAnimationCount ) && ( !drawLichCloud || ( lichCloudFrame == lichCloudMaxFrame ) ) ) { // All unit animation frames are rendered and if it was a Lich attack then also its cloud frames are rendered too. break;
codereview_new_cpp_data_4580
Battle::Indexes Battle::Arena::GetPath( const Position & position ) const return result; } -Battle::Indexes Battle::Arena::CalculateTwoMoveOverlap( int32_t /* indexTo */, uint32_t /* movementRange = 0 */ ) const -{ - // TODO: Not implemented yet - return {}; -} - uint32_t Battle::Arena::CalculateMoveDistance( const Position & position ) const { return _battlePathfinder.getDistance( position ); :warning: **readability\-convert\-member\-functions\-to\-static** :warning: method `` CalculateTwoMoveOverlap `` can be made static ```suggestion Battle::Indexes Battle::Arena::CalculateTwoMoveOverlap( int32_t /* indexTo */, uint32_t /* movementRange = 0 */ ) ``` Battle::Indexes Battle::Arena::GetPath( const Position & position ) const return result; } uint32_t Battle::Arena::CalculateMoveDistance( const Position & position ) const { return _battlePathfinder.getDistance( position );
codereview_new_cpp_data_4581
Battle::Position Battle::Position::GetReachable( const Unit & currentUnit, const return {}; }; - Position result = tryHead(); - if ( result.GetHead() == nullptr || result.GetTail() == nullptr ) { - result = tryTail(); } - return result; } Cell * headCell = Board::GetCell( dst ); We can directly return from here without extra assignment. Battle::Position Battle::Position::GetReachable( const Unit & currentUnit, const return {}; }; + Position headPos = tryHead(); + if ( headPos.GetHead() != nullptr && headPos.GetTail() != nullptr ) { + return headPos; } + return tryTail(); } Cell * headCell = Board::GetCell( dst );
codereview_new_cpp_data_4582
void Battle::Interface::RedrawActionHolyShoutSpell( const uint8_t strength ) const uint8_t alphaStep = 25; fheroes2::Display & display = fheroes2::Display::instance(); - const fheroes2::Rect renderArea( _interfacePosition.x + area.y, _interfacePosition.y + area.y, area.width, area.height ); // Immediately indicate that the delay has passed to render first frame immediately. Game::passCustomAnimationDelay( spellcastDelay ); Is it supposed to be `_interfacePosition.x + area.y` and not `area.x`? void Battle::Interface::RedrawActionHolyShoutSpell( const uint8_t strength ) const uint8_t alphaStep = 25; fheroes2::Display & display = fheroes2::Display::instance(); + const fheroes2::Rect renderArea( _interfacePosition.x + area.x, _interfacePosition.y + area.y, area.width, area.height ); // Immediately indicate that the delay has passed to render first frame immediately. Game::passCustomAnimationDelay( spellcastDelay );
codereview_new_cpp_data_4583
Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) - return Artifact( Rand( ART_LEVEL_ALL_NORMAL ) ); else if ( 0xA4 == index ) - return Artifact( Rand( ART_ULTIMATE ) ); else if ( 0xA7 == index ) - return Artifact( Rand( ART_LEVEL_TREASURE ) ); else if ( 0xA9 == index ) - return Artifact( Rand( ART_LEVEL_MINOR ) ); else if ( 0xAB == index ) - return Rand( ART_LEVEL_MAJOR ); DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) ) :warning: **modernize\-return\-braced\-init\-list** :warning: avoid repeating the return type from the declaration; use a braced initializer list instead ```suggestion return { Rand( ART_LEVEL_ALL_NORMAL ) ); ``` Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) + return { Rand( ART_LEVEL_ALL_NORMAL ) }; else if ( 0xA4 == index ) + return { Rand( ART_ULTIMATE ) }; else if ( 0xA7 == index ) + return { Rand( ART_LEVEL_TREASURE ) }; else if ( 0xA9 == index ) + return { Rand( ART_LEVEL_MINOR ) }; else if ( 0xAB == index ) + return { ART_LEVEL_MAJOR }; DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) )
codereview_new_cpp_data_4584
Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) - return Artifact( Rand( ART_LEVEL_ALL_NORMAL ) ); else if ( 0xA4 == index ) - return Artifact( Rand( ART_ULTIMATE ) ); else if ( 0xA7 == index ) - return Artifact( Rand( ART_LEVEL_TREASURE ) ); else if ( 0xA9 == index ) - return Artifact( Rand( ART_LEVEL_MINOR ) ); else if ( 0xAB == index ) - return Rand( ART_LEVEL_MAJOR ); DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) ) :warning: **modernize\-return\-braced\-init\-list** :warning: avoid repeating the return type from the declaration; use a braced initializer list instead ```suggestion return Artifact( Rand( ART_LEVEL_ALL_NORMAL ) }; ``` Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) + return { Rand( ART_LEVEL_ALL_NORMAL ) }; else if ( 0xA4 == index ) + return { Rand( ART_ULTIMATE ) }; else if ( 0xA7 == index ) + return { Rand( ART_LEVEL_TREASURE ) }; else if ( 0xA9 == index ) + return { Rand( ART_LEVEL_MINOR ) }; else if ( 0xAB == index ) + return { ART_LEVEL_MAJOR }; DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) )
codereview_new_cpp_data_4585
Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) - return Artifact( Rand( ART_LEVEL_ALL_NORMAL ) ); else if ( 0xA4 == index ) - return Artifact( Rand( ART_ULTIMATE ) ); else if ( 0xA7 == index ) - return Artifact( Rand( ART_LEVEL_TREASURE ) ); else if ( 0xA9 == index ) - return Artifact( Rand( ART_LEVEL_MINOR ) ); else if ( 0xAB == index ) - return Rand( ART_LEVEL_MAJOR ); DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) ) :warning: **modernize\-return\-braced\-init\-list** :warning: avoid repeating the return type from the declaration; use a braced initializer list instead ```suggestion return { Rand( ART_LEVEL_TREASURE ) ); ``` Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) + return { Rand( ART_LEVEL_ALL_NORMAL ) }; else if ( 0xA4 == index ) + return { Rand( ART_ULTIMATE ) }; else if ( 0xA7 == index ) + return { Rand( ART_LEVEL_TREASURE ) }; else if ( 0xA9 == index ) + return { Rand( ART_LEVEL_MINOR ) }; else if ( 0xAB == index ) + return { ART_LEVEL_MAJOR }; DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) )
codereview_new_cpp_data_4586
Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) - return Artifact( Rand( ART_LEVEL_ALL_NORMAL ) ); else if ( 0xA4 == index ) - return Artifact( Rand( ART_ULTIMATE ) ); else if ( 0xA7 == index ) - return Artifact( Rand( ART_LEVEL_TREASURE ) ); else if ( 0xA9 == index ) - return Artifact( Rand( ART_LEVEL_MINOR ) ); else if ( 0xAB == index ) - return Rand( ART_LEVEL_MAJOR ); DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) ) :warning: **modernize\-return\-braced\-init\-list** :warning: avoid repeating the return type from the declaration; use a braced initializer list instead ```suggestion return { Rand( ART_LEVEL_MINOR ) ); ``` Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) + return { Rand( ART_LEVEL_ALL_NORMAL ) }; else if ( 0xA4 == index ) + return { Rand( ART_ULTIMATE ) }; else if ( 0xA7 == index ) + return { Rand( ART_LEVEL_TREASURE ) }; else if ( 0xA9 == index ) + return { Rand( ART_LEVEL_MINOR ) }; else if ( 0xAB == index ) + return { ART_LEVEL_MAJOR }; DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) )
codereview_new_cpp_data_4587
Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) - return Artifact( Rand( ART_LEVEL_ALL_NORMAL ) ); else if ( 0xA4 == index ) - return Artifact( Rand( ART_ULTIMATE ) ); else if ( 0xA7 == index ) - return Artifact( Rand( ART_LEVEL_TREASURE ) ); else if ( 0xA9 == index ) - return Artifact( Rand( ART_LEVEL_MINOR ) ); else if ( 0xAB == index ) - return Rand( ART_LEVEL_MAJOR ); DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) ) :warning: **modernize\-return\-braced\-init\-list** :warning: avoid repeating the return type from the declaration; use a braced initializer list instead ```suggestion return Artifact( Rand( ART_LEVEL_MINOR ) }; ``` Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) + return { Rand( ART_LEVEL_ALL_NORMAL ) }; else if ( 0xA4 == index ) + return { Rand( ART_ULTIMATE ) }; else if ( 0xA7 == index ) + return { Rand( ART_LEVEL_TREASURE ) }; else if ( 0xA9 == index ) + return { Rand( ART_LEVEL_MINOR ) }; else if ( 0xAB == index ) + return { ART_LEVEL_MAJOR }; DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) )
codereview_new_cpp_data_4589
namespace int returnCode = SDL_SetRenderDrawColor( _renderer, 0, 0, 0, SDL_ALPHA_OPAQUE ); if ( returnCode < 0 ) { - ERROR_LOG( "Failed to set default color for rendered. The error value: " << returnCode << ", description: " << SDL_GetError() ) } returnCode = SDL_SetRenderTarget( _renderer, nullptr ); Hi @ihhub it seems that there is a typo: `default color for rendered` -> `default color for renderer` (?) namespace int returnCode = SDL_SetRenderDrawColor( _renderer, 0, 0, 0, SDL_ALPHA_OPAQUE ); if ( returnCode < 0 ) { + ERROR_LOG( "Failed to set default color for renderer. The error value: " << returnCode << ", description: " << SDL_GetError() ) } returnCode = SDL_SetRenderTarget( _renderer, nullptr );
codereview_new_cpp_data_4591
void Battle::Interface::RedrawActionWincesKills( const TargetsInfo & targets, Un } const int animationState = info.defender->GetAnimationState(); - if ( animationState == ( Monster_Info::WNCE || Monster_Info::WNCE_UP || Monster_Info::WNCE_DOWN ) ) { return false; } :warning: **clang\-diagnostic\-int\-in\-bool\-context** :warning: converting the enum constant to a boolean void Battle::Interface::RedrawActionWincesKills( const TargetsInfo & targets, Un } const int animationState = info.defender->GetAnimationState(); + if ( animationState == Monster_Info::WNCE || animationState == Monster_Info::WNCE_UP || animationState == Monster_Info::WNCE_DOWN ) { return false; }
codereview_new_cpp_data_4592
void Battle::Interface::RedrawActionWincesKills( const TargetsInfo & targets, Un } const int animationState = info.defender->GetAnimationState(); - if ( animationState == ( Monster_Info::WNCE || Monster_Info::WNCE_UP || Monster_Info::WNCE_DOWN ) ) { return false; } :warning: **clang\-diagnostic\-int\-in\-bool\-context** :warning: converting the enum constant to a boolean void Battle::Interface::RedrawActionWincesKills( const TargetsInfo & targets, Un } const int animationState = info.defender->GetAnimationState(); + if ( animationState == Monster_Info::WNCE || animationState == Monster_Info::WNCE_UP || animationState == Monster_Info::WNCE_DOWN ) { return false; }
codereview_new_cpp_data_4593
namespace fheroes2 Image CreateDeathWaveEffect( const Image & in, const int32_t x, const std::vector<int32_t> & deathWaveCurve ) { if ( in.empty() ) { - return Image(); } const int32_t inWidth = in.width(); const int32_t waveWidth = static_cast<int32_t>( deathWaveCurve.size() ); // If the death wave curve is outside of the battlefield - return an empty image. if ( x < 0 || ( x - waveWidth ) >= inWidth || deathWaveCurve.empty() ) { - return Image(); } const int32_t height = in.height(); :warning: **modernize\-return\-braced\-init\-list** :warning: avoid repeating the return type from the declaration; use a braced initializer list instead ```suggestion return {}; ``` namespace fheroes2 Image CreateDeathWaveEffect( const Image & in, const int32_t x, const std::vector<int32_t> & deathWaveCurve ) { if ( in.empty() ) { + return {}; } const int32_t inWidth = in.width(); const int32_t waveWidth = static_cast<int32_t>( deathWaveCurve.size() ); // If the death wave curve is outside of the battlefield - return an empty image. if ( x < 0 || ( x - waveWidth ) >= inWidth || deathWaveCurve.empty() ) { + return {}; } const int32_t height = in.height();
codereview_new_cpp_data_4594
bool LocalEvent::HandleEvents( const bool sleepAfterEventProcessing, const bool case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED: case SDL_CONTROLLERDEVICEREMAPPED: - // All these joystick and controller events aren't handled. break; case SDL_CONTROLLERAXISMOTION: HandleControllerAxisEvent( event.caxis ); Hi @ihhub So we should enable them only to not handle them? :) Are they handled somewhere inside the SDL itself? bool LocalEvent::HandleEvents( const bool sleepAfterEventProcessing, const bool case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED: case SDL_CONTROLLERDEVICEREMAPPED: + // SDL requires joystick events to be enabled in order to handle controller events. + // This is because the controller related code depends on the joystick related code. + // See SDL_gamecontroller.c within SDL source code for implementation details. break; case SDL_CONTROLLERAXISMOTION: HandleControllerAxisEvent( event.caxis );
codereview_new_cpp_data_4595
int32_t AnimationState::getCurrentFrameXOffset() const if ( currentFrame < offset.size() ) { return offset[currentFrame]; } - else { - // If there is no horizontal offset data, return 0 as offset. - return 0; - } } double AnimationState::movementProgress() const :warning: **readability\-else\-after\-return** :warning: do not use `` else `` after `` return `` ```suggestion else // If there is no horizontal offset data, return 0 as offset. return 0; ``` int32_t AnimationState::getCurrentFrameXOffset() const if ( currentFrame < offset.size() ) { return offset[currentFrame]; } + + // If there is no horizontal offset data for currentFrame, return 0 as offset. + return 0; } double AnimationState::movementProgress() const
codereview_new_cpp_data_4596
namespace fheroes2 // 'MOVE_MAIN' has 7 frames and we copy only first 6. const int32_t copyFramesNum = 6; // 'MOVE_MAIN' frames starts from the 6th frame in Golem ICN sprites. - const std::_Vector_iterator firstFrameToCopy = _icnVsSprite[id].begin() + 6; _icnVsSprite[id].insert( _icnVsSprite[id].end(), firstFrameToCopy, firstFrameToCopy + copyFramesNum ); for ( int32_t i = 0; i < copyFramesNum; ++i ) { const size_t frameID = golemICNSize + i; :warning: **clang\-diagnostic\-error** :warning: no type named `` _Vector_iterator `` in namespace `` std ``; did you mean `` _Bit_iterator ``? ```suggestion const std::_Bit_iterator firstFrameToCopy = _icnVsSprite[id].begin() + 6; ``` namespace fheroes2 // 'MOVE_MAIN' has 7 frames and we copy only first 6. const int32_t copyFramesNum = 6; // 'MOVE_MAIN' frames starts from the 6th frame in Golem ICN sprites. + const std::vector<fheroes2::Sprite>::const_iterator firstFrameToCopy = _icnVsSprite[id].begin() + 6; _icnVsSprite[id].insert( _icnVsSprite[id].end(), firstFrameToCopy, firstFrameToCopy + copyFramesNum ); for ( int32_t i = 0; i < copyFramesNum; ++i ) { const size_t frameID = golemICNSize + i;
codereview_new_cpp_data_4597
namespace void AIToXanadu( Heroes & hero, int32_t dst_index ) { const Maps::Tiles & tile = world.GetTiles( dst_index ); - const uint32_t level1 = hero.GetLevelSkill( Skill::Secondary::DIPLOMACY ); - const uint32_t level2 = hero.GetLevel(); if ( !hero.isVisited( tile ) && GameStatic::isHeroWorthyToVisitXanadu( hero ) ) { hero.IncreasePrimarySkill( Skill::Primary::ATTACK ); :warning: **clang\-diagnostic\-unused\-variable** :warning: unused variable `` level1 `` namespace void AIToXanadu( Heroes & hero, int32_t dst_index ) { const Maps::Tiles & tile = world.GetTiles( dst_index ); if ( !hero.isVisited( tile ) && GameStatic::isHeroWorthyToVisitXanadu( hero ) ) { hero.IncreasePrimarySkill( Skill::Primary::ATTACK );
codereview_new_cpp_data_4598
namespace void AIToXanadu( Heroes & hero, int32_t dst_index ) { const Maps::Tiles & tile = world.GetTiles( dst_index ); - const uint32_t level1 = hero.GetLevelSkill( Skill::Secondary::DIPLOMACY ); - const uint32_t level2 = hero.GetLevel(); if ( !hero.isVisited( tile ) && GameStatic::isHeroWorthyToVisitXanadu( hero ) ) { hero.IncreasePrimarySkill( Skill::Primary::ATTACK ); :warning: **clang\-diagnostic\-unused\-variable** :warning: unused variable `` level2 `` namespace void AIToXanadu( Heroes & hero, int32_t dst_index ) { const Maps::Tiles & tile = world.GetTiles( dst_index ); if ( !hero.isVisited( tile ) && GameStatic::isHeroWorthyToVisitXanadu( hero ) ) { hero.IncreasePrimarySkill( Skill::Primary::ATTACK );
codereview_new_cpp_data_4599
void Dialog::NonFixedFrameBox::redraw() Dialog::NonFixedFrameBox::~NonFixedFrameBox() { - const fheroes2::Rect restoredArea{ _restorer->x(), _restorer->y(), _restorer->width(), _restorer->height() }; _restorer->restore(); - fheroes2::Display::instance().render( restoredArea ); } Dialog::FrameBox::FrameBox( int height, bool buttons ) JFYI: after #6382 you will be able to use just `_restorer->rect()` here. void Dialog::NonFixedFrameBox::redraw() Dialog::NonFixedFrameBox::~NonFixedFrameBox() { _restorer->restore(); + fheroes2::Display::instance().render( _restorer->rect() ); } Dialog::FrameBox::FrameBox( int height, bool buttons )
codereview_new_cpp_data_4600
bool Battle::Bridge::AllowUp() const return isValid() && isDown() && !isOccupied(); } -bool Battle::Bridge::isOccupied() const { const Battle::Graveyard * graveyard = Arena::GetGraveyard(); :warning: **readability\-convert\-member\-functions\-to\-static** :warning: method `` isOccupied `` can be made static ```suggestion bool Battle::Bridge::isOccupied() ``` bool Battle::Bridge::AllowUp() const return isValid() && isDown() && !isOccupied(); } +bool Battle::Bridge::isOccupied() { const Battle::Graveyard * graveyard = Arena::GetGraveyard();
codereview_new_cpp_data_4601
bool Maps::FileInfo::ReadMP2( const std::string & filename ) void Maps::FileInfo::FillUnions( const int side1Colors, const int side2Colors ) { - static_assert( std::is_same_v<decltype( unions ), uint8_t[KINGDOMMAX]>, "The type of the unions[] member has been changed, check the logic below" ); - - assert( side1Colors >= 0 && side1Colors <= std::numeric_limits<uint8_t>::max() ); - assert( side2Colors >= 0 && side2Colors <= std::numeric_limits<uint8_t>::max() ); - for ( uint32_t i = 0; i < KINGDOMMAX; ++i ) { const uint8_t color = ByteToColor( i ); :warning: **cppcoreguidelines\-avoid\-c\-arrays** :warning: do not declare C\-style arrays, use std::array\<\> instead bool Maps::FileInfo::ReadMP2( const std::string & filename ) void Maps::FileInfo::FillUnions( const int side1Colors, const int side2Colors ) { for ( uint32_t i = 0; i < KINGDOMMAX; ++i ) { const uint8_t color = ByteToColor( i );
codereview_new_cpp_data_4602
Spell Maps::Tiles::QuantitySpell() const { switch ( GetObject( false ) ) { case MP2::OBJ_ARTIFACT: - return Spell( QuantityVariant() == 15 ? quantity1 : Spell::NONE ); case MP2::OBJ_SHRINE1: case MP2::OBJ_SHRINE2: case MP2::OBJ_SHRINE3: case MP2::OBJ_PYRAMID: - return Spell( quantity1 ); default: break; } - return Spell( Spell::NONE ); } void Maps::Tiles::QuantitySetSpell( int spell ) :warning: **modernize\-return\-braced\-init\-list** :warning: avoid repeating the return type from the declaration; use a braced initializer list instead Spell Maps::Tiles::QuantitySpell() const { switch ( GetObject( false ) ) { case MP2::OBJ_ARTIFACT: + return { QuantityVariant() == 15 ? quantity1 : Spell::NONE }; case MP2::OBJ_SHRINE1: case MP2::OBJ_SHRINE2: case MP2::OBJ_SHRINE3: case MP2::OBJ_PYRAMID: + return { quantity1 }; default: break; } + return { Spell::NONE }; } void Maps::Tiles::QuantitySetSpell( int spell )
codereview_new_cpp_data_4603
void Battle::Bridge::Action( const Unit & b, int32_t dst ) ForceAction( NeedDown( b, dst ) ); } -void Battle::Bridge::ForceAction( const bool action_down ) { if ( Arena::GetInterface() ) - Arena::GetInterface()->RedrawBridgeAnimation( action_down ); - SetDown( action_down ); } Since you are rewriting a piece of old code anyway, it would be good to modernize its style at the same time, in this case in terms of the style of variable names. `action_down` may be renamed to `actionDown` respectively. void Battle::Bridge::Action( const Unit & b, int32_t dst ) ForceAction( NeedDown( b, dst ) ); } +void Battle::Bridge::ForceAction( const bool actionDown ) { if ( Arena::GetInterface() ) + Arena::GetInterface()->RedrawBridgeAnimation( actionDown ); + SetDown( actionDown ); }
codereview_new_cpp_data_4604
namespace fheroes2 const std::vector<int32_t>::const_iterator endX = deathWaveCurve.end() - ( x > width ? x - width : 0 ); for ( ; pntX != endX; ++pntX, ++outImageX, ++inImageX ) { - const uint8_t * outImageYEnd = outImageX + ( height + *pntX ) * width; - const uint8_t * inImageY = inImageX - ( *pntX + 1 ) * width; // A loop to shift all horizontal pixels vertically. uint8_t * outImageY = outImageX; :warning: **bugprone\-implicit\-widening\-of\-multiplication\-result** :warning: result of multiplication in type `` int `` is used as a pointer offset after an implicit widening conversion to type `` ptrdiff_t `` namespace fheroes2 const std::vector<int32_t>::const_iterator endX = deathWaveCurve.end() - ( x > width ? x - width : 0 ); for ( ; pntX != endX; ++pntX, ++outImageX, ++inImageX ) { + const uint8_t * outImageYEnd = outImageX + static_cast<int64_t>( height + *pntX ) * width; + const uint8_t * inImageY = inImageX - static_cast<int64_t>( *pntX + 1 ) * width; // A loop to shift all horizontal pixels vertically. uint8_t * outImageY = outImageX;
codereview_new_cpp_data_4605
namespace fheroes2 const std::vector<int32_t>::const_iterator endX = deathWaveCurve.end() - ( x > width ? x - width : 0 ); for ( ; pntX != endX; ++pntX, ++outImageX, ++inImageX ) { - const uint8_t * outImageYEnd = outImageX + ( height + *pntX ) * width; - const uint8_t * inImageY = inImageX - ( *pntX + 1 ) * width; // A loop to shift all horizontal pixels vertically. uint8_t * outImageY = outImageX; :warning: **bugprone\-implicit\-widening\-of\-multiplication\-result** :warning: result of multiplication in type `` int `` is used as a pointer offset after an implicit widening conversion to type `` ptrdiff_t `` namespace fheroes2 const std::vector<int32_t>::const_iterator endX = deathWaveCurve.end() - ( x > width ? x - width : 0 ); for ( ; pntX != endX; ++pntX, ++outImageX, ++inImageX ) { + const uint8_t * outImageYEnd = outImageX + static_cast<int64_t>( height + *pntX ) * width; + const uint8_t * inImageY = inImageX - static_cast<int64_t>( *pntX + 1 ) * width; // A loop to shift all horizontal pixels vertically. uint8_t * outImageY = outImageX;
codereview_new_cpp_data_4606
namespace fheroes2 const std::vector<int32_t>::const_iterator endX = deathWaveCurve.end() - ( x > width ? x - width : 0 ); for ( ; pntX != endX; ++pntX, ++outImageX, ++inImageX ) { - const uint8_t * outImageYEnd = outImageX + static_cast<int64_t>( height + *pntX ) * width; - const uint8_t * inImageY = inImageX - static_cast<int64_t>( *pntX + 1 ) * width; // A loop to shift all horizontal pixels vertically. uint8_t * outImageY = outImageX; It's highly unlikely that the result of this multiplication will overflow `int` on 32+bit. However if you want to silence the clang-tidy, it would probably be better to convert to `std::ptrdiff_t` instead (here and on the following line), because currently on 32-bit machines there is one extra conversion performed - first to `int64_t` and then, when adding the multiplication result to pointer, it will be converted once again to `std::ptrdiff_t` which is 32-bit on these machines. namespace fheroes2 const std::vector<int32_t>::const_iterator endX = deathWaveCurve.end() - ( x > width ? x - width : 0 ); for ( ; pntX != endX; ++pntX, ++outImageX, ++inImageX ) { + const uint8_t * outImageYEnd = outImageX + static_cast<ptrdiff_t>( height + *pntX ) * width; + const uint8_t * inImageY = inImageX - static_cast<ptrdiff_t>( *pntX + 1 ) * width; // A loop to shift all horizontal pixels vertically. uint8_t * outImageY = outImageX;
codereview_new_cpp_data_4607
namespace fheroes2 const bool isEvilInterface = ( id == ICN::BUTTON_SMALL_OKAY_EVIL ); - if ( isPolishLanguageAndResources() ) { _icnVsSprite[id][0] = GetICN( isEvilInterface ? ICN::SYSTEME : ICN::SYSTEM, 1 ); _icnVsSprite[id][1] = GetICN( isEvilInterface ? ICN::SYSTEME : ICN::SYSTEM, 2 ); break; :warning: **clang\-diagnostic\-error** :warning: use of undeclared identifier `` isPolishLanguageAndResources `` namespace fheroes2 const bool isEvilInterface = ( id == ICN::BUTTON_SMALL_OKAY_EVIL ); + if ( useOriginalResources() ) { _icnVsSprite[id][0] = GetICN( isEvilInterface ? ICN::SYSTEME : ICN::SYSTEM, 1 ); _icnVsSprite[id][1] = GetICN( isEvilInterface ? ICN::SYSTEME : ICN::SYSTEM, 2 ); break;
codereview_new_cpp_data_4608
Castle::CastleDialogReturnValue Castle::OpenDialog( const bool openConstructionW fheroes2::drawCastleName( *this, display, cur_pt ); fheroes2::drawResourcePanel( GetKingdom().GetFunds(), display, cur_pt ); display.render(); } Is this logic not needed anymore? Castle::CastleDialogReturnValue Castle::OpenDialog( const bool openConstructionW fheroes2::drawCastleName( *this, display, cur_pt ); fheroes2::drawResourcePanel( GetKingdom().GetFunds(), display, cur_pt ); + if ( buttonExit.isPressed() ) { + buttonExit.draw(); + } + display.render(); }
codereview_new_cpp_data_4609
void Interface::StatusWindow::TimerEventProcessing() void Interface::StatusWindow::RedrawStatusIfNeeded( const uint32_t progressValue ) { turn_progress = progressValue; interface.Redraw( REDRAW_STATUS ); if ( Game::validateAnimationDelay( Game::MAPS_DELAY ) ) { - // Process events if any before rendering a frame. For instance, updating a mouse cursor position. - LocalEvent::Get().HandleEvents( false ); - uint32_t & frame = Game::MapsAnimationFrame(); ++frame; - interface.GetGameArea().SetRedraw(); - - interface.Redraw(); fheroes2::Display::instance().render(); } } I'm not sure about that, but, since we handle the events here, why wait for `MAPS_DELAY` for this? We can just handle events each time when this function is called. void Interface::StatusWindow::TimerEventProcessing() void Interface::StatusWindow::RedrawStatusIfNeeded( const uint32_t progressValue ) { + // Process events if any before rendering a frame. For instance, updating a mouse cursor position. + LocalEvent::Get().HandleEvents( false ); + turn_progress = progressValue; interface.Redraw( REDRAW_STATUS ); if ( Game::validateAnimationDelay( Game::MAPS_DELAY ) ) { uint32_t & frame = Game::MapsAnimationFrame(); ++frame; + interface.Redraw( REDRAW_GAMEAREA ); fheroes2::Display::instance().render(); } }
codereview_new_cpp_data_4610
void Interface::StatusWindow::TimerEventProcessing() void Interface::StatusWindow::RedrawStatusIfNeeded( const uint32_t progressValue ) { turn_progress = progressValue; interface.Redraw( REDRAW_STATUS ); if ( Game::validateAnimationDelay( Game::MAPS_DELAY ) ) { - // Process events if any before rendering a frame. For instance, updating a mouse cursor position. - LocalEvent::Get().HandleEvents( false ); - uint32_t & frame = Game::MapsAnimationFrame(); ++frame; - interface.GetGameArea().SetRedraw(); - - interface.Redraw(); fheroes2::Display::instance().render(); } } This can be simplified to `interface.Redraw( REDRAW_GAMEAREA );`, there is not need for separate `SetRedraw()` call. Or we can do the following: ```cpp interface.SetRedraw( REDRAW_STATUS ); if ( Game::validateAnimationDelay( Game::MAPS_DELAY ) ) { [...] interface.SetRedraw( REDRAW_GAMEAREA ); // Or interface.GetGameArea().SetRedraw(), which is effectively the same } interface.Redraw(); fheroes2::Display::instance().render(); ``` What do you think? void Interface::StatusWindow::TimerEventProcessing() void Interface::StatusWindow::RedrawStatusIfNeeded( const uint32_t progressValue ) { + // Process events if any before rendering a frame. For instance, updating a mouse cursor position. + LocalEvent::Get().HandleEvents( false ); + turn_progress = progressValue; interface.Redraw( REDRAW_STATUS ); if ( Game::validateAnimationDelay( Game::MAPS_DELAY ) ) { uint32_t & frame = Game::MapsAnimationFrame(); ++frame; + interface.Redraw( REDRAW_GAMEAREA ); fheroes2::Display::instance().render(); } }
codereview_new_cpp_data_4611
void Maps::Tiles::redrawBottomLayerObjects( fheroes2::Image & dst, bool isPuzzle // Some addons must be rendered after the main object on the tile. This applies for flags. // Since this method is called intensively during rendering we have to avoid memory allocation on heap. const size_t maxPostRenderAddons = 16; - std::array<const TilesAddon *, maxPostRenderAddons> postRenderingAddon; size_t postRenderAddonCount = 0; for ( const TilesAddon & addon : addons_level1 ) { :warning: **cppcoreguidelines\-pro\-type\-member\-init** :warning: uninitialized record type: `` postRenderingAddon `` ```suggestion std::array<const TilesAddon *, maxPostRenderAddons> postRenderingAddon{}; ``` void Maps::Tiles::redrawBottomLayerObjects( fheroes2::Image & dst, bool isPuzzle // Some addons must be rendered after the main object on the tile. This applies for flags. // Since this method is called intensively during rendering we have to avoid memory allocation on heap. const size_t maxPostRenderAddons = 16; + std::array<const TilesAddon *, maxPostRenderAddons> postRenderingAddon{ nullptr }; size_t postRenderAddonCount = 0; for ( const TilesAddon & addon : addons_level1 ) {
codereview_new_cpp_data_4612
void Battle::Arena::SetCastleTargetValue( int target, uint32_t value ) case CAT_BRIDGE: if ( _bridge->isValid() ) { - if ( !_bridge->isDown() ) { - _bridge->SetDown( true ); - } - _bridge->SetDestroy(); } break; So the code after the changes is: ```cpp if ( !_bridge->isDown() ) { _bridge->SetDown( true ); } ``` which can be translated into ` _bridge->SetDown( true );` as we don't need the check anymore. void Battle::Arena::SetCastleTargetValue( int target, uint32_t value ) case CAT_BRIDGE: if ( _bridge->isValid() ) { + _bridge->SetDown( true ); _bridge->SetDestroy(); } break;
codereview_new_cpp_data_4613
std::string Army::SizeString( uint32_t size ) Troops::Troops( const Troops & troops ) : std::vector<Troop *>() { - *this = troops; -} - -Troops & Troops::operator=( const Troops & rhs ) -{ - clear(); - reserve( rhs.size() ); - for ( const_iterator it = rhs.begin(); it != rhs.end(); ++it ) push_back( new Troop( **it ) ); - return *this; } Troops::~Troops() Hi @ihhub this is not quite right - since raw pointers are stored here, and not smart pointers, we should call `delete` for them first, and only after that we can call `clear()`, otherwise we will get a memory leak. std::string Army::SizeString( uint32_t size ) Troops::Troops( const Troops & troops ) : std::vector<Troop *>() { + reserve( troops.size() ); + for ( const_iterator it = troops.begin(); it != troops.end(); ++it ) push_back( new Troop( **it ) ); } Troops::~Troops()
codereview_new_cpp_data_4614
Troops::Troops( const Troops & troops ) : std::vector<Troop *>() { reserve( troops.size() ); - for ( const_iterator it = troops.begin(); it != troops.end(); ++it ) - push_back( new Troop( **it ) ); } Troops::~Troops() :warning: **modernize\-loop\-convert** :warning: use range\-based for loop instead ```suggestion push_back( new Troop( *troop ) ); ``` Troops::Troops( const Troops & troops ) : std::vector<Troop *>() { reserve( troops.size() ); + for ( const auto & troop : troops ) { + push_back( new Troop( *troop ) ); + } } Troops::~Troops()
codereview_new_cpp_data_4615
namespace fheroes2 case SupportedLanguage::Hungarian: return _( "Hungarian" ); case SupportedLanguage::Danish: - return _( "Hungarian" ); default: // Did you add a new language? Please add the code to handle it. assert( 0 ); :warning: **bugprone\-branch\-clone** :warning: switch has 2 consecutive identical branches namespace fheroes2 case SupportedLanguage::Hungarian: return _( "Hungarian" ); case SupportedLanguage::Danish: + return _( "Danish" ); default: // Did you add a new language? Please add the code to handle it. assert( 0 );
codereview_new_cpp_data_4616
bool LocalEvent::HandleWindowEvent( const SDL_WindowEvent & event ) return true; } - if ( event.event == SDL_WINDOWEVENT_RESIZED ) { - return true; - } - - return false; } void LocalEvent::HandleRenderDeviceResetEvent() :warning: **readability\-simplify\-boolean\-expr** :warning: redundant boolean literal in conditional return statement ```suggestion return event.event == SDL_WINDOWEVENT_RESIZED ``` bool LocalEvent::HandleWindowEvent( const SDL_WindowEvent & event ) return true; } + return ( event.event == SDL_WINDOWEVENT_RESIZED ); } void LocalEvent::HandleRenderDeviceResetEvent()
codereview_new_cpp_data_4617
namespace const fheroes2::Image & getDebugFogImage() { - static fheroes2::Image fog; - if ( fog.empty() ) { - fog.resize( 32, 32 ); - fheroes2::FillTransform( fog, 0, 0, fog.width(), fog.height(), 2 ); - } return fog; } Hi @ihhub I propose to initialize the static variable in such cases by using a lambda. First of all, such initializations are truly atomic, which can be useful (maybe not in this particular case, but in general). Second, you will not need to check a flag (such as `empty()` here) each time. Third, you will be able to declare `fog` as `const`. namespace const fheroes2::Image & getDebugFogImage() { + static const fheroes2::Image fog = []() { + fheroes2::Image temp( 32, 32 ); + fheroes2::FillTransform( temp, 0, 0, temp.width(), temp.height(), 2 ); + return temp; + }(); return fog; }
codereview_new_cpp_data_4618
int Mixer::setVolume( const int channelId, const int volumePercentage ) const int logvol = volumePercentage / 10; - const int arr[] = {0, 2, 3, 5, 8, 12, 20, 32, 50, 80, 128}; if ( !isInitialized ) { return 0; :warning: **cppcoreguidelines\-avoid\-c\-arrays** :warning: do not declare C\-style arrays, use std::array\<\> instead int Mixer::setVolume( const int channelId, const int volumePercentage ) const int logvol = volumePercentage / 10; + const int arr[] = { 0, 2, 3, 5, 8, 12, 20, 32, 50, 80, 128 }; if ( !isInitialized ) { return 0;
codereview_new_cpp_data_4619
namespace std::array<int, maxVolume + 1> result{ 0 }; result[maxVolume] = MIX_MAX_VOLUME; for ( int i = 1; i < maxVolume; i++ ) - result[i] = round( a * std::pow( 10.0, i * b ) * MIX_MAX_VOLUME ); return result; } (); :warning: **bugprone\-narrowing\-conversions** :warning: narrowing conversion from `` double `` to `` std::array<int, 11>::value_type `` \(aka `` int ``\) namespace std::array<int, maxVolume + 1> result{ 0 }; result[maxVolume] = MIX_MAX_VOLUME; for ( int i = 1; i < maxVolume; i++ ) + result[i] = static_cast<int>( round( a * std::pow( 10.0, i * b ) * MIX_MAX_VOLUME ) ); return result; } ();
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
2