text
stringlengths 558
4.54k
| prefix
stringlengths 100
2k
| middle
stringlengths 10
500
| suffix
stringlengths 100
2k
| type
stringclasses 2
values |
|---|---|---|---|---|
<|fim_prefix|>#include <grpcpp/impl/sync.h>
#include <grpcpp/support/client_interceptor.h>
#include <grpcpp/support/config.h>
#include <memory>
struct grpc_channel;
namespace grpc {
namespace testing {
class ChannelTestPeer;
} // namespace testing
std::shared_ptr<Channel> CreateChannelInternal(
const std::string& host, grpc_channel* c_channel,
std::vector<
std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
namespace experimental {
/// Resets the channel's connection backoff.
/// TODO(roth): Once we see whether this proves useful, either create a gRFC
/// and change this to be a method of the Channel class, or remove it.
void ChannelResetConnectionBackoff(Channel* channel);
/// Retrieves a channel's channelz uuid
/// TODO(ctiller): Once we see whether this proves useful, either create a gRFC
/// and change this to be a method of the Channel class, or remove it.
int64_t ChannelGetChannelzUuid(Channel* channel);
} // namespace experimental
/// Channels represent a connection to an endpoint. Created by \a CreateChannel.
class Channel final : public grpc::ChannelInterface,
public grpc::internal::CallHook,
public std::enable_shared_from_this<Channel>,
private grpc::internal::GrpcLibrary {
public:
~Channel() override;
/// Get the current channel state. If the channel is in IDLE and
/// \a try_to_connect is set to true, try to connect.
grpc_connectivity_state GetState(bool try_to_connect) override;
/// Returns the LB policy name, or the empty string if not yet available.
std::string GetLoadBalancingPolicyName() const;
/// Returns the service config in JSON form, or the empty string if
/// not available.
std::string GetServiceConfigJSON() const;
private:
template <class InputMessage, class OutputMessage>
friend class grpc::internal::BlockingUnaryCallImpl;
friend class grpc::testing::ChannelTestPeer;<|fim_suffix|> friend int64_t experimental::ChannelGetChannelzUuid(Channel* channel);
friend std::shared_ptr<Channel> grpc::CreateChannelInternal(
const std::string& host, grpc_channel* c_channel,
std::vector<std::unique_ptr<
grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
friend class grpc::internal::InterceptedChannel;
Channel(const std::string& host, grpc_channel* c_channel,
std::vector<std::unique_ptr<
grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
grpc::internal::Call CreateCall(const grpc::internal::RpcMethod& method,
grpc::ClientContext* context,
grpc::CompletionQueue* cq) override;
void PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
grpc::internal::Call* call) override;
void* RegisterMethod(const char* method) override;
void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline, grpc::CompletionQueue* cq,
void* tag) override;
bool WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) override;
grpc::CompletionQueue* CallbackCQ() override;
grpc::internal::Call CreateCallInternal(
const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
grpc::CompletionQueue* cq, size_t interceptor_pos) override;
const std::string host_;
grpc_channel* const c_channel_; // owned
// mu_ protects callback_cq_ (the per-channel callbackable completion queue)
grpc::internal::Mutex mu_;
// callback_cq_ references the callbackable completion queue associated
// with this channel (if any). It is set on the first call to CallbackCQ().
// It is _not owned_ by the channel; ownership belongs with its internal<|fim_middle|> friend void experimental::ChannelResetConnectionBackoff(Channel* channel);
|
#include <grpcpp/impl/sync.h>
#include <grpcpp/support/client_interceptor.h>
#include <grpcpp/support/config.h>
#include <memory>
struct grpc_channel;
namespace grpc {
namespace testing {
class ChannelTestPeer;
} // namespace testing
std::shared_ptr<Channel> CreateChannelInternal(
const std::string& host, grpc_channel* c_channel,
std::vector<
std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
namespace experimental {
/// Resets the channel's connection backoff.
/// TODO(roth): Once we see whether this proves useful, either create a gRFC
/// and change this to be a method of the Channel class, or remove it.
void ChannelResetConnectionBackoff(Channel* channel);
/// Retrieves a channel's channelz uuid
/// TODO(ctiller): Once we see whether this proves useful, either create a gRFC
/// and change this to be a method of the Channel class, or remove it.
int64_t ChannelGetChannelzUuid(Channel* channel);
} // namespace experimental
/// Channels represent a connection to an endpoint. Created by \a CreateChannel.
class Channel final : public grpc::ChannelInterface,
public grpc::internal::CallHook,
public std::enable_shared_from_this<Channel>,
private grpc::internal::GrpcLibrary {
public:
~Channel() override;
/// Get the current channel state. If the channel is in IDLE and
/// \a try_to_connect is set to true, try to connect.
grpc_connectivity_state GetState(bool try_to_connect) override;
/// Returns the LB policy name, or the empty string if not yet available.
std::string GetLoadBalancingPolicyName() const;
/// Returns the service config in JSON form, or the empty string if
/// not available.
std::string GetServiceConfigJSON() const;
private:
template <class InputMessage, class OutputMessage>
friend class grpc::internal::BlockingUnaryCallImpl;
friend class grpc::testing::ChannelTestPeer;
|
friend void experimental::ChannelResetConnectionBackoff(Channel* channel);
|
friend int64_t experimental::ChannelGetChannelzUuid(Channel* channel);
friend std::shared_ptr<Channel> grpc::CreateChannelInternal(
const std::string& host, grpc_channel* c_channel,
std::vector<std::unique_ptr<
grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
friend class grpc::internal::InterceptedChannel;
Channel(const std::string& host, grpc_channel* c_channel,
std::vector<std::unique_ptr<
grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
grpc::internal::Call CreateCall(const grpc::internal::RpcMethod& method,
grpc::ClientContext* context,
grpc::CompletionQueue* cq) override;
void PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
grpc::internal::Call* call) override;
void* RegisterMethod(const char* method) override;
void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline, grpc::CompletionQueue* cq,
void* tag) override;
bool WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) override;
grpc::CompletionQueue* CallbackCQ() override;
grpc::internal::Call CreateCallInternal(
const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
grpc::CompletionQueue* cq, size_t interceptor_pos) override;
const std::string host_;
grpc_channel* const c_channel_; // owned
// mu_ protects callback_cq_ (the per-channel callbackable completion queue)
grpc::internal::Mutex mu_;
// callback_cq_ references the callbackable completion queue associated
// with this channel (if any). It is set on the first call to CallbackCQ().
// It is _not owned_ by the channel; ownership belongs with its internal
|
random
|
<|fim_prefix|> LOG_INF("%s: Assuming llama2.c vocabulary since %s is not a gguf file\n", __func__, filename);
my_llama_file file(filename, "rb");
if (!file.fp) {
die_fmt("%s: %s", strerror(errno), filename);
}
const int n_vocab = config->vocab_size;
/* uint32_t max_token_length = */ file.read_u32(); // unused
vocab->id_to_token.resize(n_vocab);
for (my_llama_vocab::id id=0; id<n_vocab; ++id) {
float_t score = file.read_f32();
uint32_t len = file.read_u32();
std::string text = file.read_string(len);
unsigned char byte_val;
my_llama_vocab::ttype type = LLAMA_TOKEN_TYPE_NORMAL;
if (id == UNKNOWN_TOKEN_ID) {
text = "<unk>";
type = LLAMA_TOKEN_TYPE_UNKNOWN;
} else if (id == BOS_TOKEN_ID) {
text = "<s>";
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (id == EOS_TOKEN_ID) {
text = "</s>";
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (text.empty()) {
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (sscanf(text.c_str(), "<0x%02hhX>", &byte_val) == 1) {
// Text of byte tokens is already in the expected format.
type = LLAMA_TOKEN_TYPE_BYTE;
} else {
type = LLAMA_TOKEN_TYPE_NORMAL;
}
text = llama_escape_whitespaces(text);
vocab->id_to_token[id].text = text;
vocab->id_to_token[id].score = score;
vocab->id_to_token[id].type = type;
vocab->token_to_id.emplace(text, id);
}
}
}
static void convert_weights_ak_to_gg(struct ggml_tensor * gg_weights, const float * karpathy_weights) {
int size = 1;
for (int dim = 0; dim < ggml_n_dims(gg_weights); ++dim) {
size *= gg_weights->ne[dim];
}
for (int ct = 0; ct < size; ++ct) {
int64_t i0 = 0; <|fim_suffix|>
ggml_set_f32_nd(gg_weights, i0, i1, i2, i3, karpathy_weights[ct]);
}
}
static void save_as_llama_model(
struct my_llama_vocab * vocab, struct my_llama_model * model, TransformerWeights* w, const char * filename
) {
// convert AK weights into GG weights one by one.
// w->token_embedding_table -> model->tok_embeddings
// float* -> struct ggml_tensor
convert_weights_ak_to_gg(model->tok_embeddings, w->token_embedding_table.data());
convert_weights_ak_to_gg(model->output, !w->wcls.empty() ? w->wcls.data() : w->token_embedding_table.data());
convert_weights_ak_to_gg(model->norm, w->rms_final_weight.data());
//print_row(model->norm, 0);
// for rms-att-weight
int row_length = model->hparams.n_embd;
int n_ff = model->hparams.n_ff;
const uint32_t n_multiqueries = model->hparams.n_head_kv <= 0 || model->hparams.n_head_kv >= model->hparams.n_head ? 1 : model->hparams.n_head / model->hparams.n_head_kv;
for (uint32_t i = 0; i < model->hparams.n_layer; ++i){
auto & layer = model->layers[i];
// 1d
convert_weights_ak_to_gg(layer.attention_norm, &w->rms_att_weight[i*row_length]);
convert_weights_ak_to_gg(layer.ffn_norm , &w->rms_ffn_weight[i*row_length]);
// from 3d matrix layer x dim x dim to 2d matrix dim x dim
convert_weights_ak_to_gg(layer.wq , &w->wq[i*row_length*row_length]);
convert_weights_ak_to_gg(layer.wo , &w->wo[i*row_length*row_length]);
// from 3d matrix layer x dim x dim to 2d matrix dim x dim / n_multiqueries
convert_weights_ak_to_gg(layer.wk , &w->wk[i*row_length*row_length/n_multiqueries]);
convert_weights_ak_to_gg(layer.wv , &w->wv[i*row_length*row_length/n_multiqueries]);
convert_weights_ak_to_gg(layer.w1 , &w->w1[i*row_length*n_ff]);
convert_weights_ak_to_gg(layer.w2 , &w->w2[i*n_ff*row_length]);
conver<|fim_middle|>int64_t i1 = 0;
int64_t i2 = 0; int64_t i3 = 0;
ggml_unravel_index(gg_weights, ct, &i0, &i1, &i2, &i3);
|
LOG_INF("%s: Assuming llama2.c vocabulary since %s is not a gguf file\n", __func__, filename);
my_llama_file file(filename, "rb");
if (!file.fp) {
die_fmt("%s: %s", strerror(errno), filename);
}
const int n_vocab = config->vocab_size;
/* uint32_t max_token_length = */ file.read_u32(); // unused
vocab->id_to_token.resize(n_vocab);
for (my_llama_vocab::id id=0; id<n_vocab; ++id) {
float_t score = file.read_f32();
uint32_t len = file.read_u32();
std::string text = file.read_string(len);
unsigned char byte_val;
my_llama_vocab::ttype type = LLAMA_TOKEN_TYPE_NORMAL;
if (id == UNKNOWN_TOKEN_ID) {
text = "<unk>";
type = LLAMA_TOKEN_TYPE_UNKNOWN;
} else if (id == BOS_TOKEN_ID) {
text = "<s>";
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (id == EOS_TOKEN_ID) {
text = "</s>";
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (text.empty()) {
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (sscanf(text.c_str(), "<0x%02hhX>", &byte_val) == 1) {
// Text of byte tokens is already in the expected format.
type = LLAMA_TOKEN_TYPE_BYTE;
} else {
type = LLAMA_TOKEN_TYPE_NORMAL;
}
text = llama_escape_whitespaces(text);
vocab->id_to_token[id].text = text;
vocab->id_to_token[id].score = score;
vocab->id_to_token[id].type = type;
vocab->token_to_id.emplace(text, id);
}
}
}
static void convert_weights_ak_to_gg(struct ggml_tensor * gg_weights, const float * karpathy_weights) {
int size = 1;
for (int dim = 0; dim < ggml_n_dims(gg_weights); ++dim) {
size *= gg_weights->ne[dim];
}
for (int ct = 0; ct < size; ++ct) {
int64_t i0 = 0;
|
int64_t i1 = 0;
int64_t i2 = 0; int64_t i3 = 0;
ggml_unravel_index(gg_weights, ct, &i0, &i1, &i2, &i3);
|
ggml_set_f32_nd(gg_weights, i0, i1, i2, i3, karpathy_weights[ct]);
}
}
static void save_as_llama_model(
struct my_llama_vocab * vocab, struct my_llama_model * model, TransformerWeights* w, const char * filename
) {
// convert AK weights into GG weights one by one.
// w->token_embedding_table -> model->tok_embeddings
// float* -> struct ggml_tensor
convert_weights_ak_to_gg(model->tok_embeddings, w->token_embedding_table.data());
convert_weights_ak_to_gg(model->output, !w->wcls.empty() ? w->wcls.data() : w->token_embedding_table.data());
convert_weights_ak_to_gg(model->norm, w->rms_final_weight.data());
//print_row(model->norm, 0);
// for rms-att-weight
int row_length = model->hparams.n_embd;
int n_ff = model->hparams.n_ff;
const uint32_t n_multiqueries = model->hparams.n_head_kv <= 0 || model->hparams.n_head_kv >= model->hparams.n_head ? 1 : model->hparams.n_head / model->hparams.n_head_kv;
for (uint32_t i = 0; i < model->hparams.n_layer; ++i){
auto & layer = model->layers[i];
// 1d
convert_weights_ak_to_gg(layer.attention_norm, &w->rms_att_weight[i*row_length]);
convert_weights_ak_to_gg(layer.ffn_norm , &w->rms_ffn_weight[i*row_length]);
// from 3d matrix layer x dim x dim to 2d matrix dim x dim
convert_weights_ak_to_gg(layer.wq , &w->wq[i*row_length*row_length]);
convert_weights_ak_to_gg(layer.wo , &w->wo[i*row_length*row_length]);
// from 3d matrix layer x dim x dim to 2d matrix dim x dim / n_multiqueries
convert_weights_ak_to_gg(layer.wk , &w->wk[i*row_length*row_length/n_multiqueries]);
convert_weights_ak_to_gg(layer.wv , &w->wv[i*row_length*row_length/n_multiqueries]);
convert_weights_ak_to_gg(layer.w1 , &w->w1[i*row_length*n_ff]);
convert_weights_ak_to_gg(layer.w2 , &w->w2[i*n_ff*row_length]);
conver
|
ast_based
|
<|fim_prefix|> key[0] = h;
undo_redo->add_do_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
newpos,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second));
}
// 4 - (undo) Remove inserted keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second);
newpos += -scaling_selection_offset.x + (newpos - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newpos);
}
// 5 - (undo) Reinsert keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
Array key = animation->track_get_key_value(E->get().first, E->get().second);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
oldpos,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second));
}
// 6 - (undo) Reinsert overlapped keys.
List<AnimMoveRestore>::ConstIterator restore_itr = to_restore.begin();
List<Animation::HandleMode>::ConstIterator handle_itr = to_restore_handle_modes.begin();
for (; restore_itr != to_restore.end() && handle_itr != to_restore_handle_modes.end(); ++restore_itr, ++handle_itr) {
const AnimMoveRestore &amr = *restore_itr;
Array key = amr.key;
undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, 1);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",<|fim_suffix|>
undo_redo->add_do_method(this, "_clear_selection_for_anim", animation);
undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation);
// 7 - Reselect.
int i = 0;
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second);
newpos += -scaling_selection_offset.x + (newpos - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
undo_redo->add_do_method(this, "_select_at_anim", animation, E->get().first, newpos, i == 0);
undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, oldpos, i == 0);
i++;
}
AnimationPlayerEditor *ape = AnimationPlayerEditor::get_singleton();
if (ape) {
undo_redo->add_do_method(ape, "_animation_update_key_frame");
undo_redo->add_undo_method(ape, "_animation_update_key_frame");
}
undo_redo->commit_action();
}
scaling_selection = false;
scaling_selection_scale = Vector2(1, 1);
scaling_selection_offset = Vector2();
queue_redraw();
}
Ref<InputEventMouseMotion> mm = p_event;
if (moving_selection_attempt && mm.is_valid()) {
Point2 new_pos = mm->get_position();
if (mm->is_alt_pressed()) { // Axis snap key move when alt is pressed
if (Math::abs(new_pos.x - moving_selection_mouse_begin.x) > Math::abs(new_pos.y - moving_selection_mouse_begin.y)) {
new_pos.y = moving_selection_mouse_begin.y;
} else {
new_pos.x = moving_selection_mouse_begin.x;
}
}
if (!moving_selection) {
moving_selection = true;
select_single_attempt = IntPair(-1, -1);
}
if (!read_only) {
float y = (get_size().height / 2.0 - new_pos.y) * timeline_v_zoom + timeline_v_scroll;
float moving_selection_begin_time = ((moving_selection_mouse_begin.x - limit) / timeline->get_zoom_scale()) + timeline->get_value();<|fim_middle|> animation,
amr.track,
amr.time,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
*handle_itr);
}
|
key[0] = h;
undo_redo->add_do_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
newpos,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second));
}
// 4 - (undo) Remove inserted keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second);
newpos += -scaling_selection_offset.x + (newpos - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newpos);
}
// 5 - (undo) Reinsert keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
Array key = animation->track_get_key_value(E->get().first, E->get().second);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
oldpos,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second));
}
// 6 - (undo) Reinsert overlapped keys.
List<AnimMoveRestore>::ConstIterator restore_itr = to_restore.begin();
List<Animation::HandleMode>::ConstIterator handle_itr = to_restore_handle_modes.begin();
for (; restore_itr != to_restore.end() && handle_itr != to_restore_handle_modes.end(); ++restore_itr, ++handle_itr) {
const AnimMoveRestore &amr = *restore_itr;
Array key = amr.key;
undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, 1);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
|
animation,
amr.track,
amr.time,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
*handle_itr);
}
|
undo_redo->add_do_method(this, "_clear_selection_for_anim", animation);
undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation);
// 7 - Reselect.
int i = 0;
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second);
newpos += -scaling_selection_offset.x + (newpos - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
undo_redo->add_do_method(this, "_select_at_anim", animation, E->get().first, newpos, i == 0);
undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, oldpos, i == 0);
i++;
}
AnimationPlayerEditor *ape = AnimationPlayerEditor::get_singleton();
if (ape) {
undo_redo->add_do_method(ape, "_animation_update_key_frame");
undo_redo->add_undo_method(ape, "_animation_update_key_frame");
}
undo_redo->commit_action();
}
scaling_selection = false;
scaling_selection_scale = Vector2(1, 1);
scaling_selection_offset = Vector2();
queue_redraw();
}
Ref<InputEventMouseMotion> mm = p_event;
if (moving_selection_attempt && mm.is_valid()) {
Point2 new_pos = mm->get_position();
if (mm->is_alt_pressed()) { // Axis snap key move when alt is pressed
if (Math::abs(new_pos.x - moving_selection_mouse_begin.x) > Math::abs(new_pos.y - moving_selection_mouse_begin.y)) {
new_pos.y = moving_selection_mouse_begin.y;
} else {
new_pos.x = moving_selection_mouse_begin.x;
}
}
if (!moving_selection) {
moving_selection = true;
select_single_attempt = IntPair(-1, -1);
}
if (!read_only) {
float y = (get_size().height / 2.0 - new_pos.y) * timeline_v_zoom + timeline_v_scroll;
float moving_selection_begin_time = ((moving_selection_mouse_begin.x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
|
random
|
<|fim_prefix|> };
status = astcenc_compress_image(context, &image, &swizzle, dest_mip_write, comp_len, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: ASTC image compression failed: %s.", astcenc_get_error_string(status)));
astcenc_compress_reset(context);
}
astcenc_context_free(context);
// Replace original image with compressed one.
r_img->set_data(width, height, has_mipmaps, target_format, dest_data);
print_verbose(vformat("astcenc: Encoding took %d ms.", OS::get_singleton()->get_ticks_msec() - start_time));
}
#endif // TOOLS_ENABLED
void _decompress_astc(Image *r_img) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
// Determine decompression parameters from image format.
const Image::Format src_format = r_img->get_format();
bool is_hdr = false;
unsigned int block_x = 0;
unsigned int block_y = 0;
switch (src_format) {
case Image::FORMAT_ASTC_4x4: {
block_x = 4;
block_y = 4;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_4x4_HDR: {
block_x = 4;
block_y = 4;
is_hdr = true;
} break;
case Image::FORMAT_ASTC_8x8: {
block_x = 8;
block_y = 8;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_8x8_HDR: {
block_x = 8;
block_y = 8;
is_hdr = true;
} break;
default: {
ERR_FAIL_MSG(vformat("astcenc: Cannot decompress Image with a non-ASTC format: %s.", Image::get_format_name(src_format)));
} break;
}
// Initialize astcenc.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
astcenc_config config;
const float quality = ASTCENC_PRE_MEDIUM;
const uint32_t flags = ASTCENC_FLG_DECOMPRESS_ONLY;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, flags, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context = nullptr;
const unsigned int thread_count = 1;
<|fim_suffix|> const Image::Format target_format = is_hdr ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
// Decompress image.
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
const int64_t src_ofs = Image::get_image_mipmap_offset(width, height, src_format, i);
const uint8_t *mip_data = &src_data[src_ofs];
int64_t src_size;
if (i == mip_count) {
src_size = r_img->get_data_size() - src_ofs;
} else {
src_size = Image::get_image_mipmap_offset(width, height, src_format, i + 1) - src_ofs;
}
int dst_mip_w, dst_mip_h;
const int64_t dst_ofs = Image::get_image_mipmap_offset_and_dimensions(width, height, target_format, i, dst_mip_w, dst_mip_h);
// Ensure that mip offset is a multiple of 8 (etcpak expects uint64_t pointer).
ERR_FAIL_COND(dst_ofs % 8 != 0);
uint8_t *dest_mip_write = &dest_write[dst_ofs];
astcenc_image image;
image.dim_x = dst_mip_w;
image.dim_y = dst_mip_h;
image.dim_z = 1;
image.data_type = is_hdr ? ASTCENC_TYPE_F16 : ASTCENC_TYPE_U8;
image.data = (void **)(&dest_mip_write);
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_decompress_image(context, mip_data, src_size, &image, &swizzle, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS, vformat("astcenc: ASTC decompression failed: %s.", astcenc_get_error_string(status)));
ERR_BREAK_MSG(image.dim_z > 1, "astcenc: ASTC decompression failed because this is a 3D texture, which is not supported.");
astcenc_compress_reset(context);
}
<|fim_middle|> status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
|
};
status = astcenc_compress_image(context, &image, &swizzle, dest_mip_write, comp_len, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: ASTC image compression failed: %s.", astcenc_get_error_string(status)));
astcenc_compress_reset(context);
}
astcenc_context_free(context);
// Replace original image with compressed one.
r_img->set_data(width, height, has_mipmaps, target_format, dest_data);
print_verbose(vformat("astcenc: Encoding took %d ms.", OS::get_singleton()->get_ticks_msec() - start_time));
}
#endif // TOOLS_ENABLED
void _decompress_astc(Image *r_img) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
// Determine decompression parameters from image format.
const Image::Format src_format = r_img->get_format();
bool is_hdr = false;
unsigned int block_x = 0;
unsigned int block_y = 0;
switch (src_format) {
case Image::FORMAT_ASTC_4x4: {
block_x = 4;
block_y = 4;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_4x4_HDR: {
block_x = 4;
block_y = 4;
is_hdr = true;
} break;
case Image::FORMAT_ASTC_8x8: {
block_x = 8;
block_y = 8;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_8x8_HDR: {
block_x = 8;
block_y = 8;
is_hdr = true;
} break;
default: {
ERR_FAIL_MSG(vformat("astcenc: Cannot decompress Image with a non-ASTC format: %s.", Image::get_format_name(src_format)));
} break;
}
// Initialize astcenc.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
astcenc_config config;
const float quality = ASTCENC_PRE_MEDIUM;
const uint32_t flags = ASTCENC_FLG_DECOMPRESS_ONLY;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, flags, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context = nullptr;
const unsigned int thread_count = 1;
|
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
|
const Image::Format target_format = is_hdr ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
// Decompress image.
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
const int64_t src_ofs = Image::get_image_mipmap_offset(width, height, src_format, i);
const uint8_t *mip_data = &src_data[src_ofs];
int64_t src_size;
if (i == mip_count) {
src_size = r_img->get_data_size() - src_ofs;
} else {
src_size = Image::get_image_mipmap_offset(width, height, src_format, i + 1) - src_ofs;
}
int dst_mip_w, dst_mip_h;
const int64_t dst_ofs = Image::get_image_mipmap_offset_and_dimensions(width, height, target_format, i, dst_mip_w, dst_mip_h);
// Ensure that mip offset is a multiple of 8 (etcpak expects uint64_t pointer).
ERR_FAIL_COND(dst_ofs % 8 != 0);
uint8_t *dest_mip_write = &dest_write[dst_ofs];
astcenc_image image;
image.dim_x = dst_mip_w;
image.dim_y = dst_mip_h;
image.dim_z = 1;
image.data_type = is_hdr ? ASTCENC_TYPE_F16 : ASTCENC_TYPE_U8;
image.data = (void **)(&dest_mip_write);
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_decompress_image(context, mip_data, src_size, &image, &swizzle, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS, vformat("astcenc: ASTC decompression failed: %s.", astcenc_get_error_string(status)));
ERR_BREAK_MSG(image.dim_z > 1, "astcenc: ASTC decompression failed because this is a 3D texture, which is not supported.");
astcenc_compress_reset(context);
}
|
random
|
<|fim_prefix|>/**************************************************************************/
/* audio_driver_dummy.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */<|fim_suffix|>/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "audio_driver_dummy.h"
#include "core/os/os.h"
AudioDriverDummy *AudioDriverDummy::singleton = nullptr;
Error AudioDriverDummy::init() {
active.clear();
exit_thread.clear();
samples_in = nullptr;
if (mix_rate == -1) {
mix_rate = _get_configured_mix_rate();
}
channels = get_channels();
samples_in = memnew_arr(int32_t, size_t(buffer_frames) * channels);
if (use_threads) {
thread.start(AudioDriverDummy::thread_func, this);
}
return OK;
}
void AudioDriverDummy::thread_func(void *p_udata) {
AudioDriverDummy *ad = static_cast<AudioDriverDummy *>(p_udata);
uint64_t usdelay = (ad->buffer_frames / float(ad->mix_rate)) * 1000000;
while (!ad->exit_thread.is_set()) {
if (ad->active.is_set()) {
ad->lock();
ad->start_counting_ticks();
ad->audio_server_process(ad->buffer_frames, ad->samples_in);
ad->stop_counting_ticks();
ad->unlock();
}
OS::get_singleton()->delay_usec(usdelay);
}
}
void AudioDriverDummy::start() {
active.set();
}
int AudioDriverDummy::get_mix_rate() const {
return mix_rate;
}
<|fim_middle|>/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
|
/**************************************************************************/
/* audio_driver_dummy.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
|
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
|
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "audio_driver_dummy.h"
#include "core/os/os.h"
AudioDriverDummy *AudioDriverDummy::singleton = nullptr;
Error AudioDriverDummy::init() {
active.clear();
exit_thread.clear();
samples_in = nullptr;
if (mix_rate == -1) {
mix_rate = _get_configured_mix_rate();
}
channels = get_channels();
samples_in = memnew_arr(int32_t, size_t(buffer_frames) * channels);
if (use_threads) {
thread.start(AudioDriverDummy::thread_func, this);
}
return OK;
}
void AudioDriverDummy::thread_func(void *p_udata) {
AudioDriverDummy *ad = static_cast<AudioDriverDummy *>(p_udata);
uint64_t usdelay = (ad->buffer_frames / float(ad->mix_rate)) * 1000000;
while (!ad->exit_thread.is_set()) {
if (ad->active.is_set()) {
ad->lock();
ad->start_counting_ticks();
ad->audio_server_process(ad->buffer_frames, ad->samples_in);
ad->stop_counting_ticks();
ad->unlock();
}
OS::get_singleton()->delay_usec(usdelay);
}
}
void AudioDriverDummy::start() {
active.set();
}
int AudioDriverDummy::get_mix_rate() const {
return mix_rate;
}
|
random
|
<|fim_prefix|>d int block_y = 0;
switch (src_format) {
case Image::FORMAT_ASTC_4x4: {
block_x = 4;
block_y = 4;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_4x4_HDR: {
block_x = 4;
block_y = 4;
is_hdr = true;
} break;
case Image::FORMAT_ASTC_8x8: {
block_x = 8;
block_y = 8;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_8x8_HDR: {
block_x = 8;
block_y = 8;
is_hdr = true;
} break;
default: {
ERR_FAIL_MSG(vformat("astcenc: Cannot decompress Image with a non-ASTC format: %s.", Image::get_format_name(src_format)));
} break;
}
// Initialize astcenc.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
astcenc_config config;
const float quality = ASTCENC_PRE_MEDIUM;
const uint32_t flags = ASTCENC_FLG_DECOMPRESS_ONLY;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, flags, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context = nullptr;
const unsigned int thread_count = 1;
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const Image::Format target_format = is_hdr ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
// Decompress image.
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
const int64_t src_ofs = <|fim_suffix|>;
const uint8_t *mip_data = &src_data[src_ofs];
int64_t src_size;
if (i == mip_count) {
src_size = r_img->get_data_size() - src_ofs;
} else {
src_size = Image::get_image_mipmap_offset(width, height, src_format, i + 1) - src_ofs;
}
int dst_mip_w, dst_mip_h;
const int64_t dst_ofs = Image::get_image_mipmap_offset_and_dimensions(width, height, target_format, i, dst_mip_w, dst_mip_h);
// Ensure that mip offset is a multiple of 8 (etcpak expects uint64_t pointer).
ERR_FAIL_COND(dst_ofs % 8 != 0);
uint8_t *dest_mip_write = &dest_write[dst_ofs];
astcenc_image image;
image.dim_x = dst_mip_w;
image.dim_y = dst_mip_h;
image.dim_z = 1;
image.data_type = is_hdr ? ASTCENC_TYPE_F16 : ASTCENC_TYPE_U8;
image.data = (void **)(&dest_mip_write);
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_decompress_image(context, mip_data, src_size, &image, &swizzle, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS, vformat("astcenc: ASTC decompression failed: %s.", astcenc_get_error_string(status)));
ERR_BREAK_MSG(image.dim_z > 1, "astcenc: ASTC decompression failed because this is a 3D texture, which is not supported.");
astcenc_compress_reset(context);
}
astcenc_context_free(context);
// Replace original image with compressed one.
r_img->set_data(width, height, has_mipmaps, target_format, dest_data);
print_verbose(vformat("astcenc: Decompression took %d ms.", OS::get_singleton()->get_ticks_msec() - start_time));
}
<|fim_middle|>Image::get_image_mipmap_offset(width, height, src_format, i)
|
d int block_y = 0;
switch (src_format) {
case Image::FORMAT_ASTC_4x4: {
block_x = 4;
block_y = 4;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_4x4_HDR: {
block_x = 4;
block_y = 4;
is_hdr = true;
} break;
case Image::FORMAT_ASTC_8x8: {
block_x = 8;
block_y = 8;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_8x8_HDR: {
block_x = 8;
block_y = 8;
is_hdr = true;
} break;
default: {
ERR_FAIL_MSG(vformat("astcenc: Cannot decompress Image with a non-ASTC format: %s.", Image::get_format_name(src_format)));
} break;
}
// Initialize astcenc.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
astcenc_config config;
const float quality = ASTCENC_PRE_MEDIUM;
const uint32_t flags = ASTCENC_FLG_DECOMPRESS_ONLY;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, flags, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context = nullptr;
const unsigned int thread_count = 1;
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const Image::Format target_format = is_hdr ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
// Decompress image.
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
const int64_t src_ofs =
|
Image::get_image_mipmap_offset(width, height, src_format, i)
|
;
const uint8_t *mip_data = &src_data[src_ofs];
int64_t src_size;
if (i == mip_count) {
src_size = r_img->get_data_size() - src_ofs;
} else {
src_size = Image::get_image_mipmap_offset(width, height, src_format, i + 1) - src_ofs;
}
int dst_mip_w, dst_mip_h;
const int64_t dst_ofs = Image::get_image_mipmap_offset_and_dimensions(width, height, target_format, i, dst_mip_w, dst_mip_h);
// Ensure that mip offset is a multiple of 8 (etcpak expects uint64_t pointer).
ERR_FAIL_COND(dst_ofs % 8 != 0);
uint8_t *dest_mip_write = &dest_write[dst_ofs];
astcenc_image image;
image.dim_x = dst_mip_w;
image.dim_y = dst_mip_h;
image.dim_z = 1;
image.data_type = is_hdr ? ASTCENC_TYPE_F16 : ASTCENC_TYPE_U8;
image.data = (void **)(&dest_mip_write);
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_decompress_image(context, mip_data, src_size, &image, &swizzle, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS, vformat("astcenc: ASTC decompression failed: %s.", astcenc_get_error_string(status)));
ERR_BREAK_MSG(image.dim_z > 1, "astcenc: ASTC decompression failed because this is a 3D texture, which is not supported.");
astcenc_compress_reset(context);
}
astcenc_context_free(context);
// Replace original image with compressed one.
r_img->set_data(width, height, has_mipmaps, target_format, dest_data);
print_verbose(vformat("astcenc: Decompression took %d ms.", OS::get_singleton()->get_ticks_msec() - start_time));
}
|
ast_based
|
<|fim_prefix|>#include <tesseract/resultiterator.h>
#include <string>
#include "boxread.h"
#include "rect.h"
#include "include_gunit.h"
namespace tesseract {
const char *kTruthTextWords = "To simple burn running of goods lately.\n";
const char *kTruthTextLine = "Tosimpleburnrunningofgoodslately.\n";
// The fixture for testing Tesseract.
class ApplyBoxTest : public testing::Test {
protected:
std::string TestDataNameToPath(const std::string &name) {
return file::JoinPath(TESTING_DIR, name);
}
std::string TessdataPath() {
return TESSDATA_DIR;
}
ApplyBoxTest() {
src_pix_ = nullptr;
}
~ApplyBoxTest() override {
src_pix_.destroy();
}
bool SetImage(const char *filename) {
bool found = false;
src_pix_.destroy();
src_pix_ = pixRead(TestDataNameToPath(filename).c_str());
if (api_.Init(TessdataPath().c_str(), "eng", tesseract::OEM_TESSERACT_ONLY) != -1) {
api_.SetPageSegMode(tesseract::PSM_SINGLE_BLOCK);
api_.SetImage(src_pix_);
api_.SetVariable("tessedit_make_boxes_from_boxes", "1");
api_.SetInputName(TestDataNameToPath(filename).c_str());
found = true;
}
return found;
}
// Runs ApplyBoxes (via setting the appropriate variables and Recognize)
// and checks that the output ocr text matches the truth_str, and that
// the boxes match the given box file well enough.
// If line_mode is true, ApplyBoxes is run in line segmentation mode,
// otherwise the input box file is assumed to have character-level boxes.
void VerifyBoxesAndText(const char *imagefile, const char *truth_str, const char *target_box_file,
bool line_mode) {
if (!SetImage(imagefile)) {
// eng.traineddata not found or other problem during Init.
GTEST_SKIP();
}
if (line_mode) {
api_.SetVariable("tessedit_resegment_from_line_boxes", "1");
} else {
api_.SetVariable("tessedit_resegment_from_boxes", "1");
}
api_.Recognize(nullptr);<|fim_suffix|> ResultIterator *it = api_.GetIterator();
do {
int left, top, right, bottom;
EXPECT_TRUE(it->BoundingBox(tesseract::RIL_SYMBOL, &left, &top, &right, &bottom));
TBOX ocr_box(ICOORD(left, height - bottom), ICOORD(right, height - top));
int line_number = 0;
TBOX truth_box;
std::string box_text;
EXPECT_TRUE(ReadNextBox(0, &line_number, box_file, box_text, &truth_box));
// Testing for major overlap is a bit weak, but if they all
// major overlap successfully, then it has to be fairly close.
EXPECT_TRUE(ocr_box.major_overlap(truth_box));
// Also check that the symbol text matches the box text.
char *symbol_text = it->GetUTF8Text(tesseract::RIL_SYMBOL);
EXPECT_STREQ(box_text.c_str(), symbol_text);
delete[] symbol_text;
} while (it->Next(tesseract::RIL_SYMBOL));
delete it;
}
Image src_pix_;
std::string ocr_text_;
tesseract::TessBaseAPI api_;
};
// Tests character-level applyboxes on normal Times New Roman.
TEST_F(ApplyBoxTest, TimesCharLevel) {
VerifyBoxesAndText("trainingtimes.tif", kTruthTextWords, "trainingtimes.box", false);
}
// Tests character-level applyboxes on italic Times New Roman.
TEST_F(ApplyBoxTest, ItalicCharLevel) {
VerifyBoxesAndText("trainingital.tif", kTruthTextWords, "trainingital.box", false);
}
// Tests line-level applyboxes on normal Times New Roman.
TEST_F(ApplyBoxTest, TimesLineLevel) {
VerifyBoxesAndText("trainingtimesline.tif", kTruthTextLine, "trainingtimes.box", true);
}
// Tests line-level applyboxes on italic Times New Roman.
TEST_F(ApplyBoxTest, ItalLineLevel) {
VerifyBoxesAndText("trainingitalline.tif", kTruthTextLine, "trainingital.box", true);
}
} // namespace tesseract
<|fim_middle|> char *ocr_text = api_.GetUTF8Text();
EXPECT_STREQ(truth_str, ocr_text);
delete[] ocr_text;
// Test the boxes by reading the target box file in parallel with the
// bounding boxes in the ocr output.
std::string box_filename = TestDataNameToPath(target_box_file);
FILE *box_file = OpenBoxFile(box_filename.c_str());
ASSERT_TRUE(box_file != nullptr);
int height = pixGetHeight(src_pix_);
|
#include <tesseract/resultiterator.h>
#include <string>
#include "boxread.h"
#include "rect.h"
#include "include_gunit.h"
namespace tesseract {
const char *kTruthTextWords = "To simple burn running of goods lately.\n";
const char *kTruthTextLine = "Tosimpleburnrunningofgoodslately.\n";
// The fixture for testing Tesseract.
class ApplyBoxTest : public testing::Test {
protected:
std::string TestDataNameToPath(const std::string &name) {
return file::JoinPath(TESTING_DIR, name);
}
std::string TessdataPath() {
return TESSDATA_DIR;
}
ApplyBoxTest() {
src_pix_ = nullptr;
}
~ApplyBoxTest() override {
src_pix_.destroy();
}
bool SetImage(const char *filename) {
bool found = false;
src_pix_.destroy();
src_pix_ = pixRead(TestDataNameToPath(filename).c_str());
if (api_.Init(TessdataPath().c_str(), "eng", tesseract::OEM_TESSERACT_ONLY) != -1) {
api_.SetPageSegMode(tesseract::PSM_SINGLE_BLOCK);
api_.SetImage(src_pix_);
api_.SetVariable("tessedit_make_boxes_from_boxes", "1");
api_.SetInputName(TestDataNameToPath(filename).c_str());
found = true;
}
return found;
}
// Runs ApplyBoxes (via setting the appropriate variables and Recognize)
// and checks that the output ocr text matches the truth_str, and that
// the boxes match the given box file well enough.
// If line_mode is true, ApplyBoxes is run in line segmentation mode,
// otherwise the input box file is assumed to have character-level boxes.
void VerifyBoxesAndText(const char *imagefile, const char *truth_str, const char *target_box_file,
bool line_mode) {
if (!SetImage(imagefile)) {
// eng.traineddata not found or other problem during Init.
GTEST_SKIP();
}
if (line_mode) {
api_.SetVariable("tessedit_resegment_from_line_boxes", "1");
} else {
api_.SetVariable("tessedit_resegment_from_boxes", "1");
}
api_.Recognize(nullptr);
|
char *ocr_text = api_.GetUTF8Text();
EXPECT_STREQ(truth_str, ocr_text);
delete[] ocr_text;
// Test the boxes by reading the target box file in parallel with the
// bounding boxes in the ocr output.
std::string box_filename = TestDataNameToPath(target_box_file);
FILE *box_file = OpenBoxFile(box_filename.c_str());
ASSERT_TRUE(box_file != nullptr);
int height = pixGetHeight(src_pix_);
|
ResultIterator *it = api_.GetIterator();
do {
int left, top, right, bottom;
EXPECT_TRUE(it->BoundingBox(tesseract::RIL_SYMBOL, &left, &top, &right, &bottom));
TBOX ocr_box(ICOORD(left, height - bottom), ICOORD(right, height - top));
int line_number = 0;
TBOX truth_box;
std::string box_text;
EXPECT_TRUE(ReadNextBox(0, &line_number, box_file, box_text, &truth_box));
// Testing for major overlap is a bit weak, but if they all
// major overlap successfully, then it has to be fairly close.
EXPECT_TRUE(ocr_box.major_overlap(truth_box));
// Also check that the symbol text matches the box text.
char *symbol_text = it->GetUTF8Text(tesseract::RIL_SYMBOL);
EXPECT_STREQ(box_text.c_str(), symbol_text);
delete[] symbol_text;
} while (it->Next(tesseract::RIL_SYMBOL));
delete it;
}
Image src_pix_;
std::string ocr_text_;
tesseract::TessBaseAPI api_;
};
// Tests character-level applyboxes on normal Times New Roman.
TEST_F(ApplyBoxTest, TimesCharLevel) {
VerifyBoxesAndText("trainingtimes.tif", kTruthTextWords, "trainingtimes.box", false);
}
// Tests character-level applyboxes on italic Times New Roman.
TEST_F(ApplyBoxTest, ItalicCharLevel) {
VerifyBoxesAndText("trainingital.tif", kTruthTextWords, "trainingital.box", false);
}
// Tests line-level applyboxes on normal Times New Roman.
TEST_F(ApplyBoxTest, TimesLineLevel) {
VerifyBoxesAndText("trainingtimesline.tif", kTruthTextLine, "trainingtimes.box", true);
}
// Tests line-level applyboxes on italic Times New Roman.
TEST_F(ApplyBoxTest, ItalLineLevel) {
VerifyBoxesAndText("trainingitalline.tif", kTruthTextLine, "trainingital.box", true);
}
} // namespace tesseract
|
random
|
<|fim_prefix|>aste_keys(-1.0, false);
}
accept_event();
}
if (ED_IS_SHORTCUT("animation_editor/delete_selection", p_event)) {
if (!read_only) {
delete_selection();
}
accept_event();
}
}
Ref<InputEventKey> key_press = p_event;
if (key_press.is_valid() && key_press->is_pressed()) {
if (ED_IS_SHORTCUT("animation_bezier_editor/focus", p_event)) {
SelectionSet focused_keys;
if (selection.is_empty()) {
for (int i = 0; i < edit_points.size(); ++i) {
IntPair key_pair = IntPair(edit_points[i].track, edit_points[i].key);
focused_keys.insert(key_pair);
}
} else {
for (const IntPair &E : selection) {
focused_keys.insert(E);
if (E.second > 0) {
IntPair previous_key = IntPair(E.first, E.second - 1);
focused_keys.insert(previous_key);
}
if (E.second < animation->track_get_key_count(E.first) - 1) {
IntPair next_key = IntPair(E.first, E.second + 1);
focused_keys.insert(next_key);
}
}
}
if (focused_keys.is_empty()) {
accept_event();
return;
}
real_t minimum_time = Math::INF;
real_t maximum_time = -Math::INF;
real_t minimum_value = Math::INF;
real_t maximum_value = -Math::INF;
for (const IntPair &E : focused_keys) {
IntPair key_pair = E;
real_t time = animation->track_get_key_time(key_pair.first, key_pair.second);
real_t value = animation->bezier_track_get_key_value(key_pair.first, key_pair.second);
minimum_time = MIN(time, minimum_time);
maximum_time = MAX(time, maximum_time);
minimum_value = MIN(value, minimum_value);
maximum_value = MAX(value, maximum_value);
}
float width = get_size().width - timeline->get_name_limit() - timeline->get_buttons_width();
float padding = width * 0.1;
float desired_scale = (width - padding / 2.0) / (maximum_time - minimum_time);
minimum_time = MAX(0, minimum_time - (padding / 2.0) / desired_scale);
float zv = Math::pow(100 / desired_scale, 0.125f);
if (zv < 1) {
<|fim_suffix|>
}
float zoom_value = timeline->get_zoom()->get_max() - zv;
if (Math::is_finite(minimum_time) && Math::is_finite(maximum_time) && maximum_time - minimum_time > CMP_EPSILON) {
timeline->get_zoom()->set_value(zoom_value);
callable_mp((Range *)timeline, &Range::set_value).call_deferred(minimum_time);
}
if (Math::is_finite(minimum_value) && Math::is_finite(maximum_value)) {
_zoom_vertically(minimum_value, maximum_value);
}
queue_redraw();
accept_event();
return;
} else if (ED_IS_SHORTCUT("animation_bezier_editor/select_all_keys", p_event)) {
for (int i = 0; i < edit_points.size(); ++i) {
_select_at_anim(animation, edit_points[i].track, animation->track_get_key_time(edit_points[i].track, edit_points[i].key), i == 0);
}
queue_redraw();
accept_event();
return;
} else if (ED_IS_SHORTCUT("animation_bezier_editor/deselect_all_keys", p_event)) {
selection.clear();
emit_signal(SNAME("clear_selection"));
queue_redraw();
accept_event();
return;
}
}
Ref<InputEventMouseButton> mb = p_event;
int limit = timeline->get_name_limit();
if (mb.is_valid() && mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed()) {
menu_insert_key = mb->get_position();
if (menu_insert_key.x >= limit && menu_insert_key.x <= get_size().width) {
if (!read_only) {
Vector2 popup_pos = get_screen_position() + mb->get_position();
bool selected = _try_select_at_ui_pos(mb->get_position(), mb->is_shift_pressed(), false);
menu->clear();
menu->add_icon_item(bezier_icon, TTR("Insert Key Here"), MENU_KEY_INSERT);
if (selected || selection.size()) {
menu->add_separator();
menu->add_icon_item(get_editor_theme_icon(SNAME("Duplicate")), TTR("Duplicate Selected Key(s)"), MENU_KEY_DUPLICATE);
menu->add_icon_item(get_editor_theme_icon(SNAME("ActionCut")), TTR("Cut Selected Key(s)"), MENU_KEY_CUT);
menu->add_icon_item(get_editor_theme_icon(SNAME("ActionCopy")), TTR("Copy Selected Ke<|fim_middle|>zv = Math::pow(desired_scale / 100, 0.125f) - 1;
zv = 1 - zv;
|
aste_keys(-1.0, false);
}
accept_event();
}
if (ED_IS_SHORTCUT("animation_editor/delete_selection", p_event)) {
if (!read_only) {
delete_selection();
}
accept_event();
}
}
Ref<InputEventKey> key_press = p_event;
if (key_press.is_valid() && key_press->is_pressed()) {
if (ED_IS_SHORTCUT("animation_bezier_editor/focus", p_event)) {
SelectionSet focused_keys;
if (selection.is_empty()) {
for (int i = 0; i < edit_points.size(); ++i) {
IntPair key_pair = IntPair(edit_points[i].track, edit_points[i].key);
focused_keys.insert(key_pair);
}
} else {
for (const IntPair &E : selection) {
focused_keys.insert(E);
if (E.second > 0) {
IntPair previous_key = IntPair(E.first, E.second - 1);
focused_keys.insert(previous_key);
}
if (E.second < animation->track_get_key_count(E.first) - 1) {
IntPair next_key = IntPair(E.first, E.second + 1);
focused_keys.insert(next_key);
}
}
}
if (focused_keys.is_empty()) {
accept_event();
return;
}
real_t minimum_time = Math::INF;
real_t maximum_time = -Math::INF;
real_t minimum_value = Math::INF;
real_t maximum_value = -Math::INF;
for (const IntPair &E : focused_keys) {
IntPair key_pair = E;
real_t time = animation->track_get_key_time(key_pair.first, key_pair.second);
real_t value = animation->bezier_track_get_key_value(key_pair.first, key_pair.second);
minimum_time = MIN(time, minimum_time);
maximum_time = MAX(time, maximum_time);
minimum_value = MIN(value, minimum_value);
maximum_value = MAX(value, maximum_value);
}
float width = get_size().width - timeline->get_name_limit() - timeline->get_buttons_width();
float padding = width * 0.1;
float desired_scale = (width - padding / 2.0) / (maximum_time - minimum_time);
minimum_time = MAX(0, minimum_time - (padding / 2.0) / desired_scale);
float zv = Math::pow(100 / desired_scale, 0.125f);
if (zv < 1) {
|
zv = Math::pow(desired_scale / 100, 0.125f) - 1;
zv = 1 - zv;
|
}
float zoom_value = timeline->get_zoom()->get_max() - zv;
if (Math::is_finite(minimum_time) && Math::is_finite(maximum_time) && maximum_time - minimum_time > CMP_EPSILON) {
timeline->get_zoom()->set_value(zoom_value);
callable_mp((Range *)timeline, &Range::set_value).call_deferred(minimum_time);
}
if (Math::is_finite(minimum_value) && Math::is_finite(maximum_value)) {
_zoom_vertically(minimum_value, maximum_value);
}
queue_redraw();
accept_event();
return;
} else if (ED_IS_SHORTCUT("animation_bezier_editor/select_all_keys", p_event)) {
for (int i = 0; i < edit_points.size(); ++i) {
_select_at_anim(animation, edit_points[i].track, animation->track_get_key_time(edit_points[i].track, edit_points[i].key), i == 0);
}
queue_redraw();
accept_event();
return;
} else if (ED_IS_SHORTCUT("animation_bezier_editor/deselect_all_keys", p_event)) {
selection.clear();
emit_signal(SNAME("clear_selection"));
queue_redraw();
accept_event();
return;
}
}
Ref<InputEventMouseButton> mb = p_event;
int limit = timeline->get_name_limit();
if (mb.is_valid() && mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed()) {
menu_insert_key = mb->get_position();
if (menu_insert_key.x >= limit && menu_insert_key.x <= get_size().width) {
if (!read_only) {
Vector2 popup_pos = get_screen_position() + mb->get_position();
bool selected = _try_select_at_ui_pos(mb->get_position(), mb->is_shift_pressed(), false);
menu->clear();
menu->add_icon_item(bezier_icon, TTR("Insert Key Here"), MENU_KEY_INSERT);
if (selected || selection.size()) {
menu->add_separator();
menu->add_icon_item(get_editor_theme_icon(SNAME("Duplicate")), TTR("Duplicate Selected Key(s)"), MENU_KEY_DUPLICATE);
menu->add_icon_item(get_editor_theme_icon(SNAME("ActionCut")), TTR("Cut Selected Key(s)"), MENU_KEY_CUT);
menu->add_icon_item(get_editor_theme_icon(SNAME("ActionCopy")), TTR("Copy Selected Ke
|
ast_based
|
<|fim_prefix|>
if (src_format >= Image::FORMAT_RH && src_format <= Image::FORMAT_RGBAH) {
r_img->convert(Image::FORMAT_RGBAH);
} else if (src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995) {
r_img->convert(Image::FORMAT_RGBAF);
} else {
r_img->convert(Image::FORMAT_RGBA8);
}
// Determine encoder output format from our enum.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
Image::Format target_format = Image::FORMAT_MAX;
unsigned int block_x = 4;
unsigned int block_y = 4;
if (p_format == Image::ASTCFormat::ASTC_FORMAT_4x4) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_4x4_HDR;
} else {
target_format = Image::FORMAT_ASTC_4x4;
}
} else if (p_format == Image::ASTCFormat::ASTC_FORMAT_8x8) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_8x8_HDR;
} else {
target_format = Image::FORMAT_ASTC_8x8;
}
block_x = 8;
block_y = 8;
}
// Compress image data and (if required) mipmaps.
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
int required_width = (width % block_x) != 0 ? width + (block_x - (width % block_x)) : width;
int required_height = (height % block_y) != 0 ? height + (block_y - (height % block_y)) : height;
if (width != required_width || height != required_height) {
// Resize texture to fit block size.
r_img->resize(required_width, required_height);
width = required_width;
height = required_height;
}
print_verbose(vformat("astcenc: Encoding image size %dx%d to format %s%s.", width, height, Image::get_format_name(target_format), has_mipmaps ? ", with mipmaps" : ""));
// Initialize astcenc.
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
astcenc_config config;
config.block_x = block_x;
config.block_y = block_y;
config.profile = profile;
<|fim_suffix|> status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
int src_mip_w, src_mip_h;
const int64_t src_ofs = Image::get_image_mipmap_offset_and_dimensions(width, height, r_img->get_format(), i, src_mip_w, src_mip_h);
const uint8_t *mip_data = &src_data[src_ofs];
const int64_t dst_ofs = Image::get_image_mipmap_offset(width, height, target_format, i);
uint8_t *dest_mip_write = &dest_write[dst_ofs];
// Ensure that mip offset is a multiple of 8 (etcpak expects uint64_t pointer).
if (unlikely(dst_ofs % 8 != 0)) {
astcenc_context_free(context);
ERR_FAIL_MSG("astcenc: Mip offset is not a multiple of 8.");
}
// Compress image.
astcenc_image image;
image.dim_x = src_mip_w;
image.dim_y = src_mip_h;
image.dim_z = 1;
if (r_img->get_format() == Image::FORMAT_RGBA8) {
image.data_type = ASTCENC_TYPE_U8;
} else if (r_img->get_format() == Image::FORMAT_RGBAH) {
image.data_type = ASTCENC_TYPE_F16;
} else {
image.data_type = ASTCENC_TYPE_F32;
}
image.data = (void **)(&mip_data);
// Compute the number of ASTC blocks in each dimension.
unsigned int block_count_x = (src_mip_w + block_x - 1) / block_x;
unsigned int block_count_y = (src_mip_h + block_y - 1) / block_y;
size_t comp_len = block_count_x * block_count_y * 16;
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_compress_image(context, &image, &swizzle, dest_mip_write, comp_len, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: ASTC image compression failed: %s.", astcenc_get_error_string(status)));
astcenc_compress_reset(context);
}
<|fim_middle|> const float quality = ASTCENC_PRE_MEDIUM;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, 0, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context;
const unsigned int thread_count = 1; // Godot compresses multiple images each on a thread, which is more efficient for large amount of images imported.
|
if (src_format >= Image::FORMAT_RH && src_format <= Image::FORMAT_RGBAH) {
r_img->convert(Image::FORMAT_RGBAH);
} else if (src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995) {
r_img->convert(Image::FORMAT_RGBAF);
} else {
r_img->convert(Image::FORMAT_RGBA8);
}
// Determine encoder output format from our enum.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
Image::Format target_format = Image::FORMAT_MAX;
unsigned int block_x = 4;
unsigned int block_y = 4;
if (p_format == Image::ASTCFormat::ASTC_FORMAT_4x4) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_4x4_HDR;
} else {
target_format = Image::FORMAT_ASTC_4x4;
}
} else if (p_format == Image::ASTCFormat::ASTC_FORMAT_8x8) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_8x8_HDR;
} else {
target_format = Image::FORMAT_ASTC_8x8;
}
block_x = 8;
block_y = 8;
}
// Compress image data and (if required) mipmaps.
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
int required_width = (width % block_x) != 0 ? width + (block_x - (width % block_x)) : width;
int required_height = (height % block_y) != 0 ? height + (block_y - (height % block_y)) : height;
if (width != required_width || height != required_height) {
// Resize texture to fit block size.
r_img->resize(required_width, required_height);
width = required_width;
height = required_height;
}
print_verbose(vformat("astcenc: Encoding image size %dx%d to format %s%s.", width, height, Image::get_format_name(target_format), has_mipmaps ? ", with mipmaps" : ""));
// Initialize astcenc.
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
astcenc_config config;
config.block_x = block_x;
config.block_y = block_y;
config.profile = profile;
|
const float quality = ASTCENC_PRE_MEDIUM;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, 0, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context;
const unsigned int thread_count = 1; // Godot compresses multiple images each on a thread, which is more efficient for large amount of images imported.
|
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
int src_mip_w, src_mip_h;
const int64_t src_ofs = Image::get_image_mipmap_offset_and_dimensions(width, height, r_img->get_format(), i, src_mip_w, src_mip_h);
const uint8_t *mip_data = &src_data[src_ofs];
const int64_t dst_ofs = Image::get_image_mipmap_offset(width, height, target_format, i);
uint8_t *dest_mip_write = &dest_write[dst_ofs];
// Ensure that mip offset is a multiple of 8 (etcpak expects uint64_t pointer).
if (unlikely(dst_ofs % 8 != 0)) {
astcenc_context_free(context);
ERR_FAIL_MSG("astcenc: Mip offset is not a multiple of 8.");
}
// Compress image.
astcenc_image image;
image.dim_x = src_mip_w;
image.dim_y = src_mip_h;
image.dim_z = 1;
if (r_img->get_format() == Image::FORMAT_RGBA8) {
image.data_type = ASTCENC_TYPE_U8;
} else if (r_img->get_format() == Image::FORMAT_RGBAH) {
image.data_type = ASTCENC_TYPE_F16;
} else {
image.data_type = ASTCENC_TYPE_F32;
}
image.data = (void **)(&mip_data);
// Compute the number of ASTC blocks in each dimension.
unsigned int block_count_x = (src_mip_w + block_x - 1) / block_x;
unsigned int block_count_y = (src_mip_h + block_y - 1) / block_y;
size_t comp_len = block_count_x * block_count_y * 16;
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_compress_image(context, &image, &swizzle, dest_mip_write, comp_len, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: ASTC image compression failed: %s.", astcenc_get_error_string(status)));
astcenc_compress_reset(context);
}
|
random
|
<|fim_prefix|>anted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "engine.h"
#include "core/authors.gen.h"
#include "core/config/project_settings.h"
#include "core/donors.gen.h"
#include "core/license.gen.h"
#include "core/variant/typed_array.h"
#include "core/version.h"
#include "servers/rendering/rendering_device.h"
void Engine::set_physics_ticks_per_second(int p_ips) {
ERR_FAIL_COND_MSG(p_ips <= 0, "Engine iterations per second must be greater than 0.");
ips = p_ips;
}
int Engine::get_physics_ticks_per_second() const {
return ips;
}
void Engine::set_max_physics_steps_per_frame(int p_max_physics_steps) <|fim_suffix|>
max_physics_steps_per_frame = p_max_physics_steps;
}
int Engine::get_max_physics_steps_per_frame() const {
return max_physics_steps_per_frame;
}
void Engine::set_physics_jitter_fix(double p_threshold) {
if (p_threshold < 0) {
p_threshold = 0;
}
physics_jitter_fix = p_threshold;
}
double Engine::get_physics_jitter_fix() const {
return physics_jitter_fix;
}
void Engine::set_max_fps(int p_fps) {
_max_fps = p_fps > 0 ? p_fps : 0;
RenderingDevice *rd = RenderingDevice::get_singleton();
if (rd) {
rd->_set_max_fps(_max_fps);
}
}
int Engine::get_max_fps() const {
return _max_fps;
}
void Engine::set_audio_output_latency(int p_msec) {
_audio_output_latency = p_msec > 1 ? p_msec : 1;
}
int Engine::get_audio_output_latency() const {
return _audio_output_latency;
}
void Engine::increment_frames_drawn() {
if (frame_server_synced) {
server_syncs++;
} else {
server_syncs = 0;
}
frame_server_synced = false;
frames_drawn++;
}
uint64_t Engine::get_frames_drawn() {
return frames_drawn;
}
void Engine::set_frame_delay(uint32_t p_msec) {
_frame_delay = p_msec;
}
uint32_t Engine::get_frame_delay() const {
return _frame_delay;
}
void Engine::set_time_scale(double p_scale) {
_time_scale = p_scale;
}
double Engine::get_time_scale() const {
return freeze_time_scale ? 0 : _time_scale;
}
double Engine::get_unfrozen_time_scale() const {
return _time_scale;
}
Dictionary Engine::get_version_info() const {
Dictionary dict;
dict["major"] = GODOT_VERSION_MAJOR;
dict["minor"] = GODOT_VERSION_MINOR;
dict["patch"] = GODOT_VERSION_PATCH;
dict["hex"] = GODOT_VERSION_HEX;
dict["status"] = GODOT_VERSION_STATUS;
dict["build"] = GODOT_VERSION_BUILD;
String hash = String(GODOT_VERSION_HASH);
dict["hash"] = hash.is_empty() ? String("unknown") : hash;
dict["timestamp"] = GODOT_VERSION_TIMESTAMP;
String stringver = String(dict["major"]) + "." + String(dict["minor"]);
if ((int)dict["patch"] != 0) {
stringver += "." + String(dict["patch"]);
}
strin<|fim_middle|>{
ERR_FAIL_COND_MSG(p_max_physics_steps <= 0, "Maximum number of physics steps per frame must be greater than 0.");
|
anted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "engine.h"
#include "core/authors.gen.h"
#include "core/config/project_settings.h"
#include "core/donors.gen.h"
#include "core/license.gen.h"
#include "core/variant/typed_array.h"
#include "core/version.h"
#include "servers/rendering/rendering_device.h"
void Engine::set_physics_ticks_per_second(int p_ips) {
ERR_FAIL_COND_MSG(p_ips <= 0, "Engine iterations per second must be greater than 0.");
ips = p_ips;
}
int Engine::get_physics_ticks_per_second() const {
return ips;
}
void Engine::set_max_physics_steps_per_frame(int p_max_physics_steps)
|
{
ERR_FAIL_COND_MSG(p_max_physics_steps <= 0, "Maximum number of physics steps per frame must be greater than 0.");
|
max_physics_steps_per_frame = p_max_physics_steps;
}
int Engine::get_max_physics_steps_per_frame() const {
return max_physics_steps_per_frame;
}
void Engine::set_physics_jitter_fix(double p_threshold) {
if (p_threshold < 0) {
p_threshold = 0;
}
physics_jitter_fix = p_threshold;
}
double Engine::get_physics_jitter_fix() const {
return physics_jitter_fix;
}
void Engine::set_max_fps(int p_fps) {
_max_fps = p_fps > 0 ? p_fps : 0;
RenderingDevice *rd = RenderingDevice::get_singleton();
if (rd) {
rd->_set_max_fps(_max_fps);
}
}
int Engine::get_max_fps() const {
return _max_fps;
}
void Engine::set_audio_output_latency(int p_msec) {
_audio_output_latency = p_msec > 1 ? p_msec : 1;
}
int Engine::get_audio_output_latency() const {
return _audio_output_latency;
}
void Engine::increment_frames_drawn() {
if (frame_server_synced) {
server_syncs++;
} else {
server_syncs = 0;
}
frame_server_synced = false;
frames_drawn++;
}
uint64_t Engine::get_frames_drawn() {
return frames_drawn;
}
void Engine::set_frame_delay(uint32_t p_msec) {
_frame_delay = p_msec;
}
uint32_t Engine::get_frame_delay() const {
return _frame_delay;
}
void Engine::set_time_scale(double p_scale) {
_time_scale = p_scale;
}
double Engine::get_time_scale() const {
return freeze_time_scale ? 0 : _time_scale;
}
double Engine::get_unfrozen_time_scale() const {
return _time_scale;
}
Dictionary Engine::get_version_info() const {
Dictionary dict;
dict["major"] = GODOT_VERSION_MAJOR;
dict["minor"] = GODOT_VERSION_MINOR;
dict["patch"] = GODOT_VERSION_PATCH;
dict["hex"] = GODOT_VERSION_HEX;
dict["status"] = GODOT_VERSION_STATUS;
dict["build"] = GODOT_VERSION_BUILD;
String hash = String(GODOT_VERSION_HASH);
dict["hash"] = hash.is_empty() ? String("unknown") : hash;
dict["timestamp"] = GODOT_VERSION_TIMESTAMP;
String stringver = String(dict["major"]) + "." + String(dict["minor"]);
if ((int)dict["patch"] != 0) {
stringver += "." + String(dict["patch"]);
}
strin
|
ast_based
|
<|fim_prefix|> ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
ae->meta = p_meta;
}
Variant AccessibilityDriverAccessKit::accessibility_element_get_meta(const RID &p_id) const {
const AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL_V(ae, Variant());
return ae->meta;
}
void AccessibilityDriverAccessKit::accessibility_update_set_focus(const RID &p_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
if (p_id.is_valid() && rid_owner.owns(p_id)) {
focus = p_id;
} else {
focus = RID();
}
}
RID AccessibilityDriverAccessKit::accessibility_get_window_root(DisplayServer::WindowID p_window_id) const {
const WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL_V(wd, RID());
return wd->root_id;
}
accesskit_tree_update *AccessibilityDriverAccessKit::_accessibility_build_tree_update(void *p_user_data) {
DisplayServer::WindowID window_id = (DisplayServer::WindowID)(size_t)p_user_data;
ERR_FAIL_COND_V(!singleton->windows.has(window_id), nullptr);
WindowData &wd = singleton->windows[window_id];
singleton->in_accessibility_update = true;
if (singleton->update_cb.is_valid()) {
singleton->update_cb.call(window_id);
}
singleton->in_accessibility_update = false;
AccessibilityElement *focus_ae = singleton->rid_owner.get_or_null(singleton->focus);
uint32_t update_size = wd.update.size();
accesskit_node_id ac_focus = (accesskit_node_id)wd.root_id.get_id();
if (focus_ae && focus_ae->window_id == window_id) {
ac_focus = (accesskit_node_id)singleton->focus.get_id();
}
accesskit_tree_update *tree_update = (update_size > 0) ? accesskit_tree_update_with_capacity_and_focus(update_size, ac_focus) : accesskit_tree_update_with_focus(ac_focus);<|fim_suffix|> AccessibilityElement *ae = singleton->rid_owner.get_or_null(rid);
if (ae && ae->node) {
for (const RID &child_rid : ae->children) {
accesskit_node_push_child(ae->node, (accesskit_node_id)child_rid.get_id());
}
accesskit_tree_update_push_node(tree_update, (accesskit_node_id)rid.get_id(), ae->node);
ae->node = nullptr;
}
}
wd.update.clear();
return tree_update;
}
void AccessibilityDriverAccessKit::accessibility_update_if_active(const Callable &p_callable) {
ERR_FAIL_COND(!p_callable.is_valid());
update_cb = p_callable;
for (KeyValue<DisplayServer::WindowID, WindowData> &window : windows) {
#ifdef WINDOWS_ENABLED
accesskit_windows_queued_events *events = accesskit_windows_subclassing_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
if (events) {
accesskit_windows_queued_events_raise(events);
}
#endif
#ifdef MACOS_ENABLED
accesskit_macos_queued_events *events = accesskit_macos_subclassing_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
if (events) {
accesskit_macos_queued_events_raise(events);
}
#endif
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
#endif
}
update_cb = Callable();
}
_FORCE_INLINE_ void AccessibilityDriverAccessKit::_ensure_node(const RID &p_id, AccessibilityElement *p_ae) {
if (unlikely(!p_ae->node)) {
WindowData *wd = windows.getptr(p_ae->window_id);
ERR_FAIL_NULL(wd);
wd->update.insert(p_id);
p_ae->node = accesskit_node_new(p_ae->role);
}
}
void AccessibilityDriverAccessKit::accessibility_set_window_rect(DisplayServer::WindowID p_window_id, const Rect2 &p_rect_out, const Rect2 &p_rect_in) {
#ifdef LINUXBSD_ENABLED
const WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL(wd);
<|fim_middle|> for (const RID &rid : wd.update) {
|
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
ae->meta = p_meta;
}
Variant AccessibilityDriverAccessKit::accessibility_element_get_meta(const RID &p_id) const {
const AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL_V(ae, Variant());
return ae->meta;
}
void AccessibilityDriverAccessKit::accessibility_update_set_focus(const RID &p_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
if (p_id.is_valid() && rid_owner.owns(p_id)) {
focus = p_id;
} else {
focus = RID();
}
}
RID AccessibilityDriverAccessKit::accessibility_get_window_root(DisplayServer::WindowID p_window_id) const {
const WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL_V(wd, RID());
return wd->root_id;
}
accesskit_tree_update *AccessibilityDriverAccessKit::_accessibility_build_tree_update(void *p_user_data) {
DisplayServer::WindowID window_id = (DisplayServer::WindowID)(size_t)p_user_data;
ERR_FAIL_COND_V(!singleton->windows.has(window_id), nullptr);
WindowData &wd = singleton->windows[window_id];
singleton->in_accessibility_update = true;
if (singleton->update_cb.is_valid()) {
singleton->update_cb.call(window_id);
}
singleton->in_accessibility_update = false;
AccessibilityElement *focus_ae = singleton->rid_owner.get_or_null(singleton->focus);
uint32_t update_size = wd.update.size();
accesskit_node_id ac_focus = (accesskit_node_id)wd.root_id.get_id();
if (focus_ae && focus_ae->window_id == window_id) {
ac_focus = (accesskit_node_id)singleton->focus.get_id();
}
accesskit_tree_update *tree_update = (update_size > 0) ? accesskit_tree_update_with_capacity_and_focus(update_size, ac_focus) : accesskit_tree_update_with_focus(ac_focus);
|
for (const RID &rid : wd.update) {
|
AccessibilityElement *ae = singleton->rid_owner.get_or_null(rid);
if (ae && ae->node) {
for (const RID &child_rid : ae->children) {
accesskit_node_push_child(ae->node, (accesskit_node_id)child_rid.get_id());
}
accesskit_tree_update_push_node(tree_update, (accesskit_node_id)rid.get_id(), ae->node);
ae->node = nullptr;
}
}
wd.update.clear();
return tree_update;
}
void AccessibilityDriverAccessKit::accessibility_update_if_active(const Callable &p_callable) {
ERR_FAIL_COND(!p_callable.is_valid());
update_cb = p_callable;
for (KeyValue<DisplayServer::WindowID, WindowData> &window : windows) {
#ifdef WINDOWS_ENABLED
accesskit_windows_queued_events *events = accesskit_windows_subclassing_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
if (events) {
accesskit_windows_queued_events_raise(events);
}
#endif
#ifdef MACOS_ENABLED
accesskit_macos_queued_events *events = accesskit_macos_subclassing_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
if (events) {
accesskit_macos_queued_events_raise(events);
}
#endif
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
#endif
}
update_cb = Callable();
}
_FORCE_INLINE_ void AccessibilityDriverAccessKit::_ensure_node(const RID &p_id, AccessibilityElement *p_ae) {
if (unlikely(!p_ae->node)) {
WindowData *wd = windows.getptr(p_ae->window_id);
ERR_FAIL_NULL(wd);
wd->update.insert(p_id);
p_ae->node = accesskit_node_new(p_ae->role);
}
}
void AccessibilityDriverAccessKit::accessibility_set_window_rect(DisplayServer::WindowID p_window_id, const Rect2 &p_rect_out, const Rect2 &p_rect_in) {
#ifdef LINUXBSD_ENABLED
const WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL(wd);
|
random
|
<|fim_prefix|>
// Context allocation.
astcenc_context *context = nullptr;
const unsigned int thread_count = 1;
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const Image::Format target_format = is_hdr ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
// Decompress image.
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
const int64_t src_ofs = Image::get_image_mipmap_offset(width, height, src_format, i);
const uint8_t *mip_data = &src_data[src_ofs];
int64_t src_size;
if (i == mip_count) {
src_size = r_img->get_data_size() - src_ofs;
} else {
src_size = Image::get_image_mipmap_offset(width, height, src_format, i + 1) - src_ofs;
}
int dst_mip_w, dst_mip_h;
const int64_t dst_ofs = Image::get_image_mipmap_offset_and_dimensions(width, height, target_format, i, dst_mip_w, dst_mip_h);
// Ensure that mip offset is a multiple of 8 (etcpak expects uint64_t pointer).
ERR_FAIL_COND(dst_ofs % 8 != 0);
uint8_t *dest_mip_write = &dest_write[dst_ofs];
astcenc_image image;
image.dim_x = dst_mip_w;
image.dim_y = dst_mip_h;
image.dim_z = 1;
image.data_type = is_hdr ? ASTCENC_TYPE_F16 : ASTCENC_TYPE_U8;
image.data = (void **)(&dest_mip_write);
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_decompress_image(context, mip_data, src_size, &image, &swizzle, 0);<|fim_suffix|> r_img->set_data(width, height, has_mipmaps, target_format, dest_data);
print_verbose(vformat("astcenc: Decompression took %d ms.", OS::get_singleton()->get_ticks_msec() - start_time));
}
<|fim_middle|> ERR_BREAK_MSG(status != ASTCENC_SUCCESS, vformat("astcenc: ASTC decompression failed: %s.", astcenc_get_error_string(status)));
ERR_BREAK_MSG(image.dim_z > 1, "astcenc: ASTC decompression failed because this is a 3D texture, which is not supported.");
astcenc_compress_reset(context);
}
astcenc_context_free(context);
// Replace original image with compressed one.
|
// Context allocation.
astcenc_context *context = nullptr;
const unsigned int thread_count = 1;
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const Image::Format target_format = is_hdr ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
// Decompress image.
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
const int64_t src_ofs = Image::get_image_mipmap_offset(width, height, src_format, i);
const uint8_t *mip_data = &src_data[src_ofs];
int64_t src_size;
if (i == mip_count) {
src_size = r_img->get_data_size() - src_ofs;
} else {
src_size = Image::get_image_mipmap_offset(width, height, src_format, i + 1) - src_ofs;
}
int dst_mip_w, dst_mip_h;
const int64_t dst_ofs = Image::get_image_mipmap_offset_and_dimensions(width, height, target_format, i, dst_mip_w, dst_mip_h);
// Ensure that mip offset is a multiple of 8 (etcpak expects uint64_t pointer).
ERR_FAIL_COND(dst_ofs % 8 != 0);
uint8_t *dest_mip_write = &dest_write[dst_ofs];
astcenc_image image;
image.dim_x = dst_mip_w;
image.dim_y = dst_mip_h;
image.dim_z = 1;
image.data_type = is_hdr ? ASTCENC_TYPE_F16 : ASTCENC_TYPE_U8;
image.data = (void **)(&dest_mip_write);
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_decompress_image(context, mip_data, src_size, &image, &swizzle, 0);
|
ERR_BREAK_MSG(status != ASTCENC_SUCCESS, vformat("astcenc: ASTC decompression failed: %s.", astcenc_get_error_string(status)));
ERR_BREAK_MSG(image.dim_z > 1, "astcenc: ASTC decompression failed because this is a 3D texture, which is not supported.");
astcenc_compress_reset(context);
}
astcenc_context_free(context);
// Replace original image with compressed one.
|
r_img->set_data(width, height, has_mipmaps, target_format, dest_data);
print_verbose(vformat("astcenc: Decompression took %d ms.", OS::get_singleton()->get_ticks_msec() - start_time));
}
|
random
|
<|fim_prefix|>
// Create text element for each run.
Vector<AccessibilityElement *> text_elements;
for (int64_t i = 0; i < run_count; i++) {
const Vector2i range = TS->shaped_get_run_range(p_shaped_text, i);
String t = TS->shaped_get_run_text(p_shaped_text, i);
if (t.is_empty()) {
continue;
}
AccessibilityElement *ae = memnew(AccessibilityElement);
ae->role = ACCESSKIT_ROLE_TEXT_RUN;
ae->window_id = parent_ae->window_id;
ae->parent = root_rid;
ae->run = Vector3i(range.x, range.y, i);
ae->node = accesskit_node_new(ae->role);
text_elements.push_back(ae);
// UTF-8 text and char lengths.
Vector<uint8_t> char_lengths;
CharString text = t.utf8(&char_lengths);
accesskit_node_set_value(ae->node, text.ptr());
accesskit_node_set_character_lengths(ae->node, char_lengths.size(), char_lengths.ptr());
// Word sizes.
Vector<uint8_t> word_lengths;
int32_t prev = ae->run.x;
int32_t total = 0;
for (int j = 0; j < words.size(); j += 2) {
if (words[j] < ae->run.x) {
continue;
}
if (words[j] >= ae->run.y) {
break;
}
int32_t wlen = words[j] - prev;
while (wlen > 255) {
word_lengths.push_back(255);
wlen -= 255;
total += 255;
}
if (wlen > 0) {
word_lengths.push_back(wlen);
total += wlen;
}
prev = words[j];
}
if (total < t.length()) {
word_lengths.push_back(t.length() - total);
}
accesskit_node_set_word_lengths(ae->node, word_lengths.size(), word_lengths.ptr());
// Char widths and positions.
Vector<float> char_positions;
Vector<float> char_widths;
char_positions.resize_initialized(t.length());
float *positions_ptr = char_positions.ptrw();
char_widths.resize_initialized(t.length());
float *widths_ptr = char_widths.ptrw();
float size_x = 0.0;
for (int j = gl_index; j < gl_count; j += gl[j].count) {
if (gl[j].start >= ae->run.y) {
gl_index = j;
break;
}
float advance = 0.0; // Graphame advance.
for (int k = 0; k < gl[j].count; k++) {<|fim_suffix|>
for (int k = 0; k < chars; k++) {
int index = gl[j].start + k - ae->run.x;
ERR_CONTINUE(index < 0 || index >= t.length());
positions_ptr[index] = size_x + adv_per_char * k;
widths_ptr[index] = adv_per_char;
}
size_x += advance * gl[j].repeat;
}
positions_ptr[t.length() - 1] = size_x;
widths_ptr[t.length() - 1] = 1.0;
accesskit_node_set_character_positions(ae->node, char_positions.size(), char_positions.ptr());
accesskit_node_set_character_widths(ae->node, char_widths.size(), char_widths.ptr());
RID font_rid = TS->shaped_get_run_font_rid(p_shaped_text, i);
if (font_rid != RID()) {
CharString font_name = TS->font_get_name(font_rid).utf8();
if (font_name.length() > 0) {
accesskit_node_set_font_family(ae->node, font_name.ptr());
}
if (TS->font_get_style(font_rid).has_flag(TextServer::FONT_BOLD)) {
accesskit_node_set_bold(ae->node);
}
if (TS->font_get_style(font_rid).has_flag(TextServer::FONT_ITALIC)) {
accesskit_node_set_italic(ae->node);
}
accesskit_node_set_font_weight(ae->node, TS->font_get_weight(font_rid));
}
accesskit_node_set_font_size(ae->node, TS->shaped_get_run_font_size(p_shaped_text, i));
CharString language = TS->shaped_get_run_language(p_shaped_text, i).utf8();
if (language.length() > 0) {
accesskit_node_set_language(ae->node, language.ptr());
}
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
accesskit_rect rect;
rect.x0 = run_off_x;
rect.y0 = 0;
rect.x1 = run_off_x + size_x;
rect.y1 = text_height;
accesskit_node_set_bounds(ae->node, rect);
accesskit_node_add_action(ae->node, ACCESSKIT_ACTION_SCROLL_INTO_VIEW);
run_off_x += size_x;
}
{
// Add "\n" at the end.
AccessibilityElement *ae = memnew(AccessibilityElement);
ae->role = ACCESSKIT_ROLE_TEXT_RUN;
ae->window_id = parent_ae->window_id;
ae->parent = root_rid;
ae->run = Vector3i(full_range.y, full_range.y, run_count);<|fim_middle|> advance += gl[j + k].advance;
}
int chars = gl[j].end - gl[j].start;
float adv_per_char = advance / (float)chars;
|
// Create text element for each run.
Vector<AccessibilityElement *> text_elements;
for (int64_t i = 0; i < run_count; i++) {
const Vector2i range = TS->shaped_get_run_range(p_shaped_text, i);
String t = TS->shaped_get_run_text(p_shaped_text, i);
if (t.is_empty()) {
continue;
}
AccessibilityElement *ae = memnew(AccessibilityElement);
ae->role = ACCESSKIT_ROLE_TEXT_RUN;
ae->window_id = parent_ae->window_id;
ae->parent = root_rid;
ae->run = Vector3i(range.x, range.y, i);
ae->node = accesskit_node_new(ae->role);
text_elements.push_back(ae);
// UTF-8 text and char lengths.
Vector<uint8_t> char_lengths;
CharString text = t.utf8(&char_lengths);
accesskit_node_set_value(ae->node, text.ptr());
accesskit_node_set_character_lengths(ae->node, char_lengths.size(), char_lengths.ptr());
// Word sizes.
Vector<uint8_t> word_lengths;
int32_t prev = ae->run.x;
int32_t total = 0;
for (int j = 0; j < words.size(); j += 2) {
if (words[j] < ae->run.x) {
continue;
}
if (words[j] >= ae->run.y) {
break;
}
int32_t wlen = words[j] - prev;
while (wlen > 255) {
word_lengths.push_back(255);
wlen -= 255;
total += 255;
}
if (wlen > 0) {
word_lengths.push_back(wlen);
total += wlen;
}
prev = words[j];
}
if (total < t.length()) {
word_lengths.push_back(t.length() - total);
}
accesskit_node_set_word_lengths(ae->node, word_lengths.size(), word_lengths.ptr());
// Char widths and positions.
Vector<float> char_positions;
Vector<float> char_widths;
char_positions.resize_initialized(t.length());
float *positions_ptr = char_positions.ptrw();
char_widths.resize_initialized(t.length());
float *widths_ptr = char_widths.ptrw();
float size_x = 0.0;
for (int j = gl_index; j < gl_count; j += gl[j].count) {
if (gl[j].start >= ae->run.y) {
gl_index = j;
break;
}
float advance = 0.0; // Graphame advance.
for (int k = 0; k < gl[j].count; k++) {
|
advance += gl[j + k].advance;
}
int chars = gl[j].end - gl[j].start;
float adv_per_char = advance / (float)chars;
|
for (int k = 0; k < chars; k++) {
int index = gl[j].start + k - ae->run.x;
ERR_CONTINUE(index < 0 || index >= t.length());
positions_ptr[index] = size_x + adv_per_char * k;
widths_ptr[index] = adv_per_char;
}
size_x += advance * gl[j].repeat;
}
positions_ptr[t.length() - 1] = size_x;
widths_ptr[t.length() - 1] = 1.0;
accesskit_node_set_character_positions(ae->node, char_positions.size(), char_positions.ptr());
accesskit_node_set_character_widths(ae->node, char_widths.size(), char_widths.ptr());
RID font_rid = TS->shaped_get_run_font_rid(p_shaped_text, i);
if (font_rid != RID()) {
CharString font_name = TS->font_get_name(font_rid).utf8();
if (font_name.length() > 0) {
accesskit_node_set_font_family(ae->node, font_name.ptr());
}
if (TS->font_get_style(font_rid).has_flag(TextServer::FONT_BOLD)) {
accesskit_node_set_bold(ae->node);
}
if (TS->font_get_style(font_rid).has_flag(TextServer::FONT_ITALIC)) {
accesskit_node_set_italic(ae->node);
}
accesskit_node_set_font_weight(ae->node, TS->font_get_weight(font_rid));
}
accesskit_node_set_font_size(ae->node, TS->shaped_get_run_font_size(p_shaped_text, i));
CharString language = TS->shaped_get_run_language(p_shaped_text, i).utf8();
if (language.length() > 0) {
accesskit_node_set_language(ae->node, language.ptr());
}
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
accesskit_rect rect;
rect.x0 = run_off_x;
rect.y0 = 0;
rect.x1 = run_off_x + size_x;
rect.y1 = text_height;
accesskit_node_set_bounds(ae->node, rect);
accesskit_node_add_action(ae->node, ACCESSKIT_ACTION_SCROLL_INTO_VIEW);
run_off_x += size_x;
}
{
// Add "\n" at the end.
AccessibilityElement *ae = memnew(AccessibilityElement);
ae->role = ACCESSKIT_ROLE_TEXT_RUN;
ae->window_id = parent_ae->window_id;
ae->parent = root_rid;
ae->run = Vector3i(full_range.y, full_range.y, run_count);
|
random
|
<|fim_prefix|>rrors = newErrorsVec;
}
}
void calib::calibDataController::setParametersFileName(const std::string &name)
{
mParamsFileName = name;
}
void calib::calibDataController::deleteLastFrame()
{
if(!mCalibData->allFrames.empty())
{
mCalibData->allFrames.pop_back();
}
if( !mCalibData->imagePoints.empty()) {
mCalibData->imagePoints.pop_back();
mCalibData->objectPoints.pop_back();
}
if (!mCalibData->allCharucoCorners.empty()) {
mCalibData->allCharucoCorners.pop_back();
mCalibData->allCharucoIds.pop_back();
}
if(!mParamsStack.empty()) {
mCalibData->cameraMatrix = (mParamsStack.top()).cameraMatrix;
mCalibData->distCoeffs = (mParamsStack.top()).distCoeffs;
mCalibData->stdDeviations = (mParamsStack.top()).stdDeviations;
mCalibData->totalAvgErr = (mParamsStack.top()).avgError;
mParamsStack.pop();
}
}
void calib::calibDataController::rememberCurrentParameters()
{
cv::Mat oldCameraMat, oldDistcoeefs, oldStdDevs;
mCalibData->cameraMatrix.copyTo(oldCameraMat);
mCalibData->distCoeffs.copyTo(oldDistcoeefs);
mCalibData->stdDeviations.copyTo(oldStdDevs);
mParamsStack.push(cameraParameters(oldCameraMat, oldDistcoeefs, oldStdDevs, mCalibData->totalAvgErr));
}
void calib::calibDataController::deleteAllData()
{
mCalibData->allFrames.clear();
mCalibData->imagePoints.clear();
mCalibData->objectPoints.clear();
mCalibData->allCharucoCorners.clear();
mCalibData->allCharucoIds.clear();
mCalibData->cameraMatrix = mCalibData->distCoeffs = cv::Mat();
mParamsStack = std::stack<cameraParameters>();
rememberCurrentParameters();
}
bool calib::calibDataController::saveCurrentCameraParameters() const
{
for(size_t i = 0; i < mCalibData->allFrames.size(); i++)
cv::imwrite(cv::format("calibration_%zu.png", i), mCalibData->allFrames[i]);
bool success = false;
if(mCalibData->cameraMatrix.total()) {
<|fim_suffix|>
if(parametersWriter.isOpened()) {
time_t rawtime;
time(&rawtime);
char buf[256];
strftime(buf, sizeof(buf)-1, "%c", localtime(&rawtime));
parametersWriter << "calibrationDate" << buf;
parametersWriter << "framesCount" << std::max((int)mCalibData->objectPoints.size(), (int)mCalibData->allCharucoCorners.size());
parametersWriter << "cameraResolution" << mCalibData->imageSize;
parametersWriter << "camera_matrix" << mCalibData->cameraMatrix;
parametersWriter << "camera_matrix_std_dev" << mCalibData->stdDeviations.rowRange(cv::Range(0, 4));
parametersWriter << "distortion_coefficients" << mCalibData->distCoeffs;
parametersWriter << "distortion_coefficients_std_dev" << mCalibData->stdDeviations.rowRange(cv::Range(4, 9));
parametersWriter << "avg_reprojection_error" << mCalibData->totalAvgErr;
parametersWriter.release();
success = true;
}
}
return success;
}
void calib::calibDataController::printParametersToConsole(std::ostream &output) const
{
const char* border = "---------------------------------------------------";
output << border << std::endl;
output << "Frames used for calibration: " << std::max(mCalibData->objectPoints.size(), mCalibData->allCharucoCorners.size())
<< " \t RMS = " << mCalibData->totalAvgErr << std::endl;
if(mCalibData->cameraMatrix.at<double>(0,0) == mCalibData->cameraMatrix.at<double>(1,1))
output << "F = " << mCalibData->cameraMatrix.at<double>(1,1) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(1) << std::endl;
else
output << "Fx = " << mCalibData->cameraMatrix.at<double>(0,0) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(0) << " \t "
<< "Fy = " << mCalibData->cameraMatrix.at<double>(1,1) << " +- " << sigmaM<|fim_middle|>cv::FileStorage parametersWriter(mParamsFileName, cv::FileStorage::WRITE);
|
rrors = newErrorsVec;
}
}
void calib::calibDataController::setParametersFileName(const std::string &name)
{
mParamsFileName = name;
}
void calib::calibDataController::deleteLastFrame()
{
if(!mCalibData->allFrames.empty())
{
mCalibData->allFrames.pop_back();
}
if( !mCalibData->imagePoints.empty()) {
mCalibData->imagePoints.pop_back();
mCalibData->objectPoints.pop_back();
}
if (!mCalibData->allCharucoCorners.empty()) {
mCalibData->allCharucoCorners.pop_back();
mCalibData->allCharucoIds.pop_back();
}
if(!mParamsStack.empty()) {
mCalibData->cameraMatrix = (mParamsStack.top()).cameraMatrix;
mCalibData->distCoeffs = (mParamsStack.top()).distCoeffs;
mCalibData->stdDeviations = (mParamsStack.top()).stdDeviations;
mCalibData->totalAvgErr = (mParamsStack.top()).avgError;
mParamsStack.pop();
}
}
void calib::calibDataController::rememberCurrentParameters()
{
cv::Mat oldCameraMat, oldDistcoeefs, oldStdDevs;
mCalibData->cameraMatrix.copyTo(oldCameraMat);
mCalibData->distCoeffs.copyTo(oldDistcoeefs);
mCalibData->stdDeviations.copyTo(oldStdDevs);
mParamsStack.push(cameraParameters(oldCameraMat, oldDistcoeefs, oldStdDevs, mCalibData->totalAvgErr));
}
void calib::calibDataController::deleteAllData()
{
mCalibData->allFrames.clear();
mCalibData->imagePoints.clear();
mCalibData->objectPoints.clear();
mCalibData->allCharucoCorners.clear();
mCalibData->allCharucoIds.clear();
mCalibData->cameraMatrix = mCalibData->distCoeffs = cv::Mat();
mParamsStack = std::stack<cameraParameters>();
rememberCurrentParameters();
}
bool calib::calibDataController::saveCurrentCameraParameters() const
{
for(size_t i = 0; i < mCalibData->allFrames.size(); i++)
cv::imwrite(cv::format("calibration_%zu.png", i), mCalibData->allFrames[i]);
bool success = false;
if(mCalibData->cameraMatrix.total()) {
|
cv::FileStorage parametersWriter(mParamsFileName, cv::FileStorage::WRITE);
|
if(parametersWriter.isOpened()) {
time_t rawtime;
time(&rawtime);
char buf[256];
strftime(buf, sizeof(buf)-1, "%c", localtime(&rawtime));
parametersWriter << "calibrationDate" << buf;
parametersWriter << "framesCount" << std::max((int)mCalibData->objectPoints.size(), (int)mCalibData->allCharucoCorners.size());
parametersWriter << "cameraResolution" << mCalibData->imageSize;
parametersWriter << "camera_matrix" << mCalibData->cameraMatrix;
parametersWriter << "camera_matrix_std_dev" << mCalibData->stdDeviations.rowRange(cv::Range(0, 4));
parametersWriter << "distortion_coefficients" << mCalibData->distCoeffs;
parametersWriter << "distortion_coefficients_std_dev" << mCalibData->stdDeviations.rowRange(cv::Range(4, 9));
parametersWriter << "avg_reprojection_error" << mCalibData->totalAvgErr;
parametersWriter.release();
success = true;
}
}
return success;
}
void calib::calibDataController::printParametersToConsole(std::ostream &output) const
{
const char* border = "---------------------------------------------------";
output << border << std::endl;
output << "Frames used for calibration: " << std::max(mCalibData->objectPoints.size(), mCalibData->allCharucoCorners.size())
<< " \t RMS = " << mCalibData->totalAvgErr << std::endl;
if(mCalibData->cameraMatrix.at<double>(0,0) == mCalibData->cameraMatrix.at<double>(1,1))
output << "F = " << mCalibData->cameraMatrix.at<double>(1,1) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(1) << std::endl;
else
output << "Fx = " << mCalibData->cameraMatrix.at<double>(0,0) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(0) << " \t "
<< "Fy = " << mCalibData->cameraMatrix.at<double>(1,1) << " +- " << sigmaM
|
ast_based
|
<|fim_prefix|> fclose(file);
} else {
fprintf(stderr, "Error, cannot read input file %s: %s\n", filename, strerror(errno));
return false;
}
}
// Here is our autodetection
int format;
int r =
(data != nullptr) ? findFileFormatBuffer(data, &format) : findFileFormat(filename, &format);
// Maybe we have a filelist
if (r != 0 || format == IFF_UNKNOWN) {
std::string s;
if (data != nullptr) {
s = buf.c_str();
} else {
std::ifstream t(filename);
std::string u((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
s = u.c_str();
}
return ProcessPagesFileList(nullptr, &s, retry_config, timeout_millisec, renderer,
tesseract_->tessedit_page_number);
}
// Maybe we have a TIFF which is potentially multipage
bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS || format == IFF_TIFF_RLE ||
format == IFF_TIFF_G3 || format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
#if LIBLEPT_MAJOR_VERSION > 1 || LIBLEPT_MINOR_VERSION > 76
format == IFF_TIFF_JPEG ||
#endif
format == IFF_TIFF_ZIP);
// Fail early if we can, before producing any output
Pix *pix = nullptr;
if (!tiff) {
pix = (data != nullptr) ? pixReadMem(data, buf.size()) : pixRead(filename);
if (pix == nullptr) {
return false;
}
}
// Begin the output
if (renderer && !renderer->BeginDocument(document_title.c_str())) {
pixDestroy(&pix);
return false;
}
// Produce output
r = (tiff) ? ProcessPagesMultipageTiff(data, buf.size(), filename, retry_config, timeout_millisec,
renderer, tesseract_->tessedit_page_number)
: ProcessPage(pix, 0, filename, retry_config, timeout_millisec, renderer);
// Clean up memory as needed
pixDestroy(&pix);
// End the output
if (!r || (renderer && !renderer->EndDocument())) {
return false;
}<|fim_suffix|>}
bool TessBaseAPI::ProcessPage(Pix *pix, int page_index, const char *filename,
const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer) {
SetInputName(filename);
SetImage(pix);
bool failed = false;
if (tesseract_->tessedit_pageseg_mode == PSM_AUTO_ONLY) {
// Disabled character recognition
if (! std::unique_ptr<const PageIterator>(AnalyseLayout())) {
failed = true;
}
} else if (tesseract_->tessedit_pageseg_mode == PSM_OSD_ONLY) {
failed = FindLines() != 0;
} else if (timeout_millisec > 0) {
// Running with a timeout.
ETEXT_DESC monitor;
monitor.cancel = nullptr;
monitor.cancel_this = nullptr;
monitor.set_deadline_msecs(timeout_millisec);
// Now run the main recognition.
failed = Recognize(&monitor) < 0;
} else {
// Normal layout and character recognition with no timeout.
failed = Recognize(nullptr) < 0;
}
if (tesseract_->tessedit_write_images) {
Pix *page_pix = GetThresholdedImage();
std::string output_filename = output_file_ + ".processed";
if (page_index > 0) {
output_filename += std::to_string(page_index);
}
output_filename += ".tif";
pixWrite(output_filename.c_str(), page_pix, IFF_TIFF_G4);
pixDestroy(&page_pix);
}
if (failed && retry_config != nullptr && retry_config[0] != '\0') {
// Save current config variables before switching modes.
FILE *fp = fopen(kOldVarsFile, "wb");
if (fp == nullptr) {
tprintf("Error, failed to open file \"%s\"\n", kOldVarsFile);
} else {
PrintVariables(fp);
fclose(fp);
}
// Switch to alternate mode for retry.
ReadConfigFile(retry_config);
SetImage(pix);
Recognize(nullptr);
// Restore saved config variables.
ReadConfigFile(kOldVarsFile);
}
if (renderer && !failed) {
failed = !renderer->AddImage(this);
}
return !failed;
}
/**<|fim_middle|> return true;
|
fclose(file);
} else {
fprintf(stderr, "Error, cannot read input file %s: %s\n", filename, strerror(errno));
return false;
}
}
// Here is our autodetection
int format;
int r =
(data != nullptr) ? findFileFormatBuffer(data, &format) : findFileFormat(filename, &format);
// Maybe we have a filelist
if (r != 0 || format == IFF_UNKNOWN) {
std::string s;
if (data != nullptr) {
s = buf.c_str();
} else {
std::ifstream t(filename);
std::string u((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
s = u.c_str();
}
return ProcessPagesFileList(nullptr, &s, retry_config, timeout_millisec, renderer,
tesseract_->tessedit_page_number);
}
// Maybe we have a TIFF which is potentially multipage
bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS || format == IFF_TIFF_RLE ||
format == IFF_TIFF_G3 || format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
#if LIBLEPT_MAJOR_VERSION > 1 || LIBLEPT_MINOR_VERSION > 76
format == IFF_TIFF_JPEG ||
#endif
format == IFF_TIFF_ZIP);
// Fail early if we can, before producing any output
Pix *pix = nullptr;
if (!tiff) {
pix = (data != nullptr) ? pixReadMem(data, buf.size()) : pixRead(filename);
if (pix == nullptr) {
return false;
}
}
// Begin the output
if (renderer && !renderer->BeginDocument(document_title.c_str())) {
pixDestroy(&pix);
return false;
}
// Produce output
r = (tiff) ? ProcessPagesMultipageTiff(data, buf.size(), filename, retry_config, timeout_millisec,
renderer, tesseract_->tessedit_page_number)
: ProcessPage(pix, 0, filename, retry_config, timeout_millisec, renderer);
// Clean up memory as needed
pixDestroy(&pix);
// End the output
if (!r || (renderer && !renderer->EndDocument())) {
return false;
}
|
return true;
|
}
bool TessBaseAPI::ProcessPage(Pix *pix, int page_index, const char *filename,
const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer) {
SetInputName(filename);
SetImage(pix);
bool failed = false;
if (tesseract_->tessedit_pageseg_mode == PSM_AUTO_ONLY) {
// Disabled character recognition
if (! std::unique_ptr<const PageIterator>(AnalyseLayout())) {
failed = true;
}
} else if (tesseract_->tessedit_pageseg_mode == PSM_OSD_ONLY) {
failed = FindLines() != 0;
} else if (timeout_millisec > 0) {
// Running with a timeout.
ETEXT_DESC monitor;
monitor.cancel = nullptr;
monitor.cancel_this = nullptr;
monitor.set_deadline_msecs(timeout_millisec);
// Now run the main recognition.
failed = Recognize(&monitor) < 0;
} else {
// Normal layout and character recognition with no timeout.
failed = Recognize(nullptr) < 0;
}
if (tesseract_->tessedit_write_images) {
Pix *page_pix = GetThresholdedImage();
std::string output_filename = output_file_ + ".processed";
if (page_index > 0) {
output_filename += std::to_string(page_index);
}
output_filename += ".tif";
pixWrite(output_filename.c_str(), page_pix, IFF_TIFF_G4);
pixDestroy(&page_pix);
}
if (failed && retry_config != nullptr && retry_config[0] != '\0') {
// Save current config variables before switching modes.
FILE *fp = fopen(kOldVarsFile, "wb");
if (fp == nullptr) {
tprintf("Error, failed to open file \"%s\"\n", kOldVarsFile);
} else {
PrintVariables(fp);
fclose(fp);
}
// Switch to alternate mode for retry.
ReadConfigFile(retry_config);
SetImage(pix);
Recognize(nullptr);
// Restore saved config variables.
ReadConfigFile(kOldVarsFile);
}
if (renderer && !failed) {
failed = !renderer->AddImage(this);
}
return !failed;
}
/**
|
random
|
<|fim_prefix|> // Add last line without terminating LF.
lines.push_back(line);
}
if (lines.empty()) {
return false;
}
}
// Skip to the requested page number.
for (unsigned i = 0; i < page; i++) {
if (flist) {
if (fgets(pagename, sizeof(pagename), flist) == nullptr) {
break;
}
}
}
// Begin producing output
if (renderer && !renderer->BeginDocument(document_title.c_str())) {
return false;
}
// Loop over all pages - or just the requested one
while (true) {
if (flist) {
if (fgets(pagename, sizeof(pagename), flist) == nullptr) {
break;
}
} else {
if (page >= lines.size()) {
break;
}
snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str());
}
chomp_string(pagename);
Pix *pix = pixRead(pagename);
if (pix == nullptr) {
tprintf("Image file %s cannot be read!\n", pagename);
return false;
}
tprintf("Page %u : %s\n", page, pagename);
bool r = ProcessPage(pix, page, pagename, retry_config, timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) {
return false;
}
if (tessedit_page_number >= 0) {
break;
}
++page;
}
// Finish producing output
if (renderer && !renderer->EndDocument()) {
return false;
}
return true;
}
bool TessBaseAPI::ProcessPagesMultipageTiff(const l_uint8 *data, size_t size, const char *filename,
const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer,
int tessedit_page_number) {
Pix *pix = nullptr;
int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
size_t offset = 0;
for (;; ++page) {
if (tessedit_page_number >= 0) {
page = tessedit_page_number;
pix = (data) ? pixReadMemTiff(data, size, page) : pixReadTiff(filename, page);
} else {<|fim_suffix|> }
if (offset || page > 0) {
// Only print page number for multipage TIFF file.
tprintf("Page %d\n", page + 1);
}
auto page_string = std::to_string(page);
SetVariable("applybox_page", page_string.c_str());
bool r = ProcessPage(pix, page, filename, retry_config, timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) {
return false;
}
if (tessedit_page_number >= 0) {
break;
}
if (!offset) {
break;
}
}
return true;
}
// Master ProcessPages calls ProcessPagesInternal and then does any post-
// processing required due to being in a training mode.
bool TessBaseAPI::ProcessPages(const char *filename, const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer) {
bool result = ProcessPagesInternal(filename, retry_config, timeout_millisec, renderer);
#ifndef DISABLED_LEGACY_ENGINE
if (result) {
if (tesseract_->tessedit_train_from_boxes && !tesseract_->WriteTRFile(output_file_.c_str())) {
tprintf("Write of TR file failed: %s\n", output_file_.c_str());
return false;
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
return result;
}
#ifdef HAVE_LIBCURL
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size = size * nmemb;
auto *buf = reinterpret_cast<std::string *>(userp);
buf->append(reinterpret_cast<const char *>(contents), size);
return size;
}
#endif
// In the ideal scenario, Tesseract will start working on data as soon
// as it can. For example, if you stream a filelist through stdin, we
// should start the OCR process as soon as the first filename is
// available. This is particularly useful when hooking Tesseract up to
// slow hardware such as a book scanning machine.
//
// Unfortunately there are tradeoffs. You can't seek on stdin. That
// makes automatic detection of datatype (TIFF? filelist? PNG?)
// impractical. So we support a command line flag to explicitly<|fim_middle|> pix = (data) ? pixReadMemFromMultipageTiff(data, size, &offset)
: pixReadFromMultipageTiff(filename, &offset);
}
if (pix == nullptr) {
break;
|
// Add last line without terminating LF.
lines.push_back(line);
}
if (lines.empty()) {
return false;
}
}
// Skip to the requested page number.
for (unsigned i = 0; i < page; i++) {
if (flist) {
if (fgets(pagename, sizeof(pagename), flist) == nullptr) {
break;
}
}
}
// Begin producing output
if (renderer && !renderer->BeginDocument(document_title.c_str())) {
return false;
}
// Loop over all pages - or just the requested one
while (true) {
if (flist) {
if (fgets(pagename, sizeof(pagename), flist) == nullptr) {
break;
}
} else {
if (page >= lines.size()) {
break;
}
snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str());
}
chomp_string(pagename);
Pix *pix = pixRead(pagename);
if (pix == nullptr) {
tprintf("Image file %s cannot be read!\n", pagename);
return false;
}
tprintf("Page %u : %s\n", page, pagename);
bool r = ProcessPage(pix, page, pagename, retry_config, timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) {
return false;
}
if (tessedit_page_number >= 0) {
break;
}
++page;
}
// Finish producing output
if (renderer && !renderer->EndDocument()) {
return false;
}
return true;
}
bool TessBaseAPI::ProcessPagesMultipageTiff(const l_uint8 *data, size_t size, const char *filename,
const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer,
int tessedit_page_number) {
Pix *pix = nullptr;
int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
size_t offset = 0;
for (;; ++page) {
if (tessedit_page_number >= 0) {
page = tessedit_page_number;
pix = (data) ? pixReadMemTiff(data, size, page) : pixReadTiff(filename, page);
} else {
|
pix = (data) ? pixReadMemFromMultipageTiff(data, size, &offset)
: pixReadFromMultipageTiff(filename, &offset);
}
if (pix == nullptr) {
break;
|
}
if (offset || page > 0) {
// Only print page number for multipage TIFF file.
tprintf("Page %d\n", page + 1);
}
auto page_string = std::to_string(page);
SetVariable("applybox_page", page_string.c_str());
bool r = ProcessPage(pix, page, filename, retry_config, timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) {
return false;
}
if (tessedit_page_number >= 0) {
break;
}
if (!offset) {
break;
}
}
return true;
}
// Master ProcessPages calls ProcessPagesInternal and then does any post-
// processing required due to being in a training mode.
bool TessBaseAPI::ProcessPages(const char *filename, const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer) {
bool result = ProcessPagesInternal(filename, retry_config, timeout_millisec, renderer);
#ifndef DISABLED_LEGACY_ENGINE
if (result) {
if (tesseract_->tessedit_train_from_boxes && !tesseract_->WriteTRFile(output_file_.c_str())) {
tprintf("Write of TR file failed: %s\n", output_file_.c_str());
return false;
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
return result;
}
#ifdef HAVE_LIBCURL
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size = size * nmemb;
auto *buf = reinterpret_cast<std::string *>(userp);
buf->append(reinterpret_cast<const char *>(contents), size);
return size;
}
#endif
// In the ideal scenario, Tesseract will start working on data as soon
// as it can. For example, if you stream a filelist through stdin, we
// should start the OCR process as soon as the first filename is
// available. This is particularly useful when hooking Tesseract up to
// slow hardware such as a book scanning machine.
//
// Unfortunately there are tradeoffs. You can't seek on stdin. That
// makes automatic detection of datatype (TIFF? filelist? PNG?)
// impractical. So we support a command line flag to explicitly
|
random
|
<|fim_prefix|> return false; // Skip track due to not selected.
}
}
}
return true;
}
// Check if the curves for a track are displayed in the editor (not hidden). Includes the check on the track visibility.
bool AnimationBezierTrackEdit::_is_track_curves_displayed(int p_track_index) {
// Is the track is visible in the editor?
if (!_is_track_displayed(p_track_index)) {
return false;
}
// And curves visible?
if (hidden_tracks.has(p_track_index)) {
return false;
}
return true;
}
Ref<Animation> AnimationBezierTrackEdit::get_animation() const {
return animation;
}
void AnimationBezierTrackEdit::set_animation_and_track(const Ref<Animation> &p_animation, int p_track, bool p_read_only) {
animation = p_animation;
read_only = p_read_only;
selected_track = p_track;
queue_redraw();
}
Size2 AnimationBezierTrackEdit::get_minimum_size() const {
return Vector2(1, 1);
}
Control::CursorShape AnimationBezierTrackEdit::get_cursor_shape(const Point2 &p_pos) const {
// Box selecting or moving a handle
if (box_selecting || Math::abs(moving_handle) == 1) {
return get_default_cursor_shape();
}
// Hovering a handle
if (!read_only) {
for (const EditPoint &edit_point : edit_points) {
if (edit_point.in_rect.has_point(p_pos) || edit_point.out_rect.has_point(p_pos)) {
return get_default_cursor_shape();
}
}
}
// Currently box scaling
if (scaling_selection) {
if (scaling_selection_handles == Vector2i(1, 1) || scaling_selection_handles == Vector2i(-1, -1)) {
return CURSOR_FDIAGSIZE;
} else if (scaling_selection_handles == Vector2i(1, -1) || scaling_selection_handles == Vector2i(-1, 1)) {
return CURSOR_BDIAGSIZE;
} else if (abs(scaling_selection_handles.x) == 1) {
return CURSOR_HSIZE;
} else if (abs(scaling_selection_handles.y) == 1) {
return CURSOR_VSIZE;
}
}
// Hovering the scaling box
const Vector2i rel_pos = p_pos - selection_rect.position;
if (selection_handles_rect.has_point(p_pos)) {<|fim_suffix|> return CURSOR_VSIZE;
}
return CURSOR_MOVE;
}
return get_default_cursor_shape();
}
void AnimationBezierTrackEdit::set_timeline(AnimationTimelineEdit *p_timeline) {
timeline = p_timeline;
timeline->connect("zoom_changed", callable_mp(this, &AnimationBezierTrackEdit::_zoom_changed));
timeline->connect("name_limit_changed", callable_mp(this, &AnimationBezierTrackEdit::_zoom_changed));
}
void AnimationBezierTrackEdit::set_editor(AnimationTrackEditor *p_editor) {
editor = p_editor;
connect("clear_selection", callable_mp(editor, &AnimationTrackEditor::_clear_selection).bind(false));
connect("select_key", callable_mp(editor, &AnimationTrackEditor::_key_selected), CONNECT_DEFERRED);
connect("deselect_key", callable_mp(editor, &AnimationTrackEditor::_key_deselected), CONNECT_DEFERRED);
}
void AnimationBezierTrackEdit::_play_position_draw() {
if (animation.is_null() || play_position_pos < 0) {
return;
}
float scale = timeline->get_zoom_scale();
int h = get_size().height;
int limit = timeline->get_name_limit();
int px = (-timeline->get_value() + play_position_pos) * scale + limit;
if (px >= limit && px < (get_size().width)) {
const Color color = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
play_position->draw_line(Point2(px, 0), Point2(px, h), color, Math::round(2 * EDSCALE));
}
}
void AnimationBezierTrackEdit::set_play_position(real_t p_pos) {
play_position_pos = p_pos;
play_position->queue_redraw();
}
void AnimationBezierTrackEdit::update_play_position() {
play_position->queue_redraw();
}
void AnimationBezierTrackEdit::set_root(Node *p_root) {
root = p_root;
}
void AnimationBezierTrackEdit::set_filtered(bool p_filtered) {
is_filtered = p_filtered;
if (animation.is_null()) {
return;
}
String base_path = String(animation->track_get_path(selected_track));
if (is_filtered) {
if (root && root->has_node(base_path)) {
Node *node = root->get_node(base_path);<|fim_middle|> if ((rel_pos.x < 0 && rel_pos.y < 0) || (rel_pos.x > selection_rect.size.width && rel_pos.y > selection_rect.size.height)) {
return CURSOR_FDIAGSIZE;
} else if ((rel_pos.x < 0 && rel_pos.y > selection_rect.size.height) || (rel_pos.x > selection_rect.size.width && rel_pos.y < 0)) {
return CURSOR_BDIAGSIZE;
} else if (rel_pos.x < 0 || rel_pos.x > selection_rect.size.width) {
return CURSOR_HSIZE;
} else if (rel_pos.y < 0 || rel_pos.y > selection_rect.size.height) {
|
return false; // Skip track due to not selected.
}
}
}
return true;
}
// Check if the curves for a track are displayed in the editor (not hidden). Includes the check on the track visibility.
bool AnimationBezierTrackEdit::_is_track_curves_displayed(int p_track_index) {
// Is the track is visible in the editor?
if (!_is_track_displayed(p_track_index)) {
return false;
}
// And curves visible?
if (hidden_tracks.has(p_track_index)) {
return false;
}
return true;
}
Ref<Animation> AnimationBezierTrackEdit::get_animation() const {
return animation;
}
void AnimationBezierTrackEdit::set_animation_and_track(const Ref<Animation> &p_animation, int p_track, bool p_read_only) {
animation = p_animation;
read_only = p_read_only;
selected_track = p_track;
queue_redraw();
}
Size2 AnimationBezierTrackEdit::get_minimum_size() const {
return Vector2(1, 1);
}
Control::CursorShape AnimationBezierTrackEdit::get_cursor_shape(const Point2 &p_pos) const {
// Box selecting or moving a handle
if (box_selecting || Math::abs(moving_handle) == 1) {
return get_default_cursor_shape();
}
// Hovering a handle
if (!read_only) {
for (const EditPoint &edit_point : edit_points) {
if (edit_point.in_rect.has_point(p_pos) || edit_point.out_rect.has_point(p_pos)) {
return get_default_cursor_shape();
}
}
}
// Currently box scaling
if (scaling_selection) {
if (scaling_selection_handles == Vector2i(1, 1) || scaling_selection_handles == Vector2i(-1, -1)) {
return CURSOR_FDIAGSIZE;
} else if (scaling_selection_handles == Vector2i(1, -1) || scaling_selection_handles == Vector2i(-1, 1)) {
return CURSOR_BDIAGSIZE;
} else if (abs(scaling_selection_handles.x) == 1) {
return CURSOR_HSIZE;
} else if (abs(scaling_selection_handles.y) == 1) {
return CURSOR_VSIZE;
}
}
// Hovering the scaling box
const Vector2i rel_pos = p_pos - selection_rect.position;
if (selection_handles_rect.has_point(p_pos)) {
|
if ((rel_pos.x < 0 && rel_pos.y < 0) || (rel_pos.x > selection_rect.size.width && rel_pos.y > selection_rect.size.height)) {
return CURSOR_FDIAGSIZE;
} else if ((rel_pos.x < 0 && rel_pos.y > selection_rect.size.height) || (rel_pos.x > selection_rect.size.width && rel_pos.y < 0)) {
return CURSOR_BDIAGSIZE;
} else if (rel_pos.x < 0 || rel_pos.x > selection_rect.size.width) {
return CURSOR_HSIZE;
} else if (rel_pos.y < 0 || rel_pos.y > selection_rect.size.height) {
|
return CURSOR_VSIZE;
}
return CURSOR_MOVE;
}
return get_default_cursor_shape();
}
void AnimationBezierTrackEdit::set_timeline(AnimationTimelineEdit *p_timeline) {
timeline = p_timeline;
timeline->connect("zoom_changed", callable_mp(this, &AnimationBezierTrackEdit::_zoom_changed));
timeline->connect("name_limit_changed", callable_mp(this, &AnimationBezierTrackEdit::_zoom_changed));
}
void AnimationBezierTrackEdit::set_editor(AnimationTrackEditor *p_editor) {
editor = p_editor;
connect("clear_selection", callable_mp(editor, &AnimationTrackEditor::_clear_selection).bind(false));
connect("select_key", callable_mp(editor, &AnimationTrackEditor::_key_selected), CONNECT_DEFERRED);
connect("deselect_key", callable_mp(editor, &AnimationTrackEditor::_key_deselected), CONNECT_DEFERRED);
}
void AnimationBezierTrackEdit::_play_position_draw() {
if (animation.is_null() || play_position_pos < 0) {
return;
}
float scale = timeline->get_zoom_scale();
int h = get_size().height;
int limit = timeline->get_name_limit();
int px = (-timeline->get_value() + play_position_pos) * scale + limit;
if (px >= limit && px < (get_size().width)) {
const Color color = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
play_position->draw_line(Point2(px, 0), Point2(px, h), color, Math::round(2 * EDSCALE));
}
}
void AnimationBezierTrackEdit::set_play_position(real_t p_pos) {
play_position_pos = p_pos;
play_position->queue_redraw();
}
void AnimationBezierTrackEdit::update_play_position() {
play_position->queue_redraw();
}
void AnimationBezierTrackEdit::set_root(Node *p_root) {
root = p_root;
}
void AnimationBezierTrackEdit::set_filtered(bool p_filtered) {
is_filtered = p_filtered;
if (animation.is_null()) {
return;
}
String base_path = String(animation->track_get_path(selected_track));
if (is_filtered) {
if (root && root->has_node(base_path)) {
Node *node = root->get_node(base_path);
|
random
|
<|fim_prefix|>t)mCalibData->objectPoints.size(), (int)mCalibData->allCharucoCorners.size());
parametersWriter << "cameraResolution" << mCalibData->imageSize;
parametersWriter << "camera_matrix" << mCalibData->cameraMatrix;
parametersWriter << "camera_matrix_std_dev" << mCalibData->stdDeviations.rowRange(cv::Range(0, 4));
parametersWriter << "distortion_coefficients" << mCalibData->distCoeffs;
parametersWriter << "distortion_coefficients_std_dev" << mCalibData->stdDeviations.rowRange(cv::Range(4, 9));
parametersWriter << "avg_reprojection_error" << mCalibData->totalAvgErr;
parametersWriter.release();
success = true;
}
}
return success;
}
void calib::calibDataController::printParametersToConsole(std::ostream &output) const
{
const char* border = "---------------------------------------------------";
output << border << std::endl;
output << "Frames used for calibration: " << std::max(mCalibData->objectPoints.size(), mCalibData->allCharucoCorners.size())
<< " \t RMS = " << mCalibData->totalAvgErr << std::endl;
if(mCalibData->cameraMatrix.at<double>(0,0) == mCalibData->cameraMatrix.at<double>(1,1))
output << "F = " << mCalibData->cameraMatrix.at<double>(1,1) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(1) << std::endl;
else
output << "Fx = " << mCalibData->cameraMatrix.at<double>(0,0) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(0) << " \t "
<< "Fy = " << mCalibData->cameraMatrix.at<double>(1,1) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(1) << std::endl;
output << "Cx = " << mCalibData->cameraMatrix.at<double>(0,2) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(2) << " \t"
<< "Cy = " << mCalibData->cameraMatrix.at<double>(1,2) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(3) << std::endl;
<|fim_suffix|>
output << "K2 = " << mCalibData->distCoeffs.at<double>(1) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(5) << std::endl;
output << "K3 = " << mCalibData->distCoeffs.at<double>(4) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(8) << std::endl;
output << "TD1 = " << mCalibData->distCoeffs.at<double>(2) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(6) << std::endl;
output << "TD2 = " << mCalibData->distCoeffs.at<double>(3) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(7) << std::endl;
}
void calib::calibDataController::updateUndistortMap()
{
cv::initUndistortRectifyMap(mCalibData->cameraMatrix, mCalibData->distCoeffs, cv::noArray(),
cv::getOptimalNewCameraMatrix(mCalibData->cameraMatrix, mCalibData->distCoeffs, mCalibData->imageSize, 0.0, mCalibData->imageSize),
mCalibData->imageSize, CV_16SC2, mCalibData->undistMap1, mCalibData->undistMap2);
}
<|fim_middle|>output << "K1 = " << mCalibData->distCoeffs.at<double>(0) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(4) << std::endl;
|
t)mCalibData->objectPoints.size(), (int)mCalibData->allCharucoCorners.size());
parametersWriter << "cameraResolution" << mCalibData->imageSize;
parametersWriter << "camera_matrix" << mCalibData->cameraMatrix;
parametersWriter << "camera_matrix_std_dev" << mCalibData->stdDeviations.rowRange(cv::Range(0, 4));
parametersWriter << "distortion_coefficients" << mCalibData->distCoeffs;
parametersWriter << "distortion_coefficients_std_dev" << mCalibData->stdDeviations.rowRange(cv::Range(4, 9));
parametersWriter << "avg_reprojection_error" << mCalibData->totalAvgErr;
parametersWriter.release();
success = true;
}
}
return success;
}
void calib::calibDataController::printParametersToConsole(std::ostream &output) const
{
const char* border = "---------------------------------------------------";
output << border << std::endl;
output << "Frames used for calibration: " << std::max(mCalibData->objectPoints.size(), mCalibData->allCharucoCorners.size())
<< " \t RMS = " << mCalibData->totalAvgErr << std::endl;
if(mCalibData->cameraMatrix.at<double>(0,0) == mCalibData->cameraMatrix.at<double>(1,1))
output << "F = " << mCalibData->cameraMatrix.at<double>(1,1) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(1) << std::endl;
else
output << "Fx = " << mCalibData->cameraMatrix.at<double>(0,0) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(0) << " \t "
<< "Fy = " << mCalibData->cameraMatrix.at<double>(1,1) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(1) << std::endl;
output << "Cx = " << mCalibData->cameraMatrix.at<double>(0,2) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(2) << " \t"
<< "Cy = " << mCalibData->cameraMatrix.at<double>(1,2) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(3) << std::endl;
|
output << "K1 = " << mCalibData->distCoeffs.at<double>(0) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(4) << std::endl;
|
output << "K2 = " << mCalibData->distCoeffs.at<double>(1) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(5) << std::endl;
output << "K3 = " << mCalibData->distCoeffs.at<double>(4) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(8) << std::endl;
output << "TD1 = " << mCalibData->distCoeffs.at<double>(2) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(6) << std::endl;
output << "TD2 = " << mCalibData->distCoeffs.at<double>(3) << " +- " << sigmaMult*mCalibData->stdDeviations.at<double>(7) << std::endl;
}
void calib::calibDataController::updateUndistortMap()
{
cv::initUndistortRectifyMap(mCalibData->cameraMatrix, mCalibData->distCoeffs, cv::noArray(),
cv::getOptimalNewCameraMatrix(mCalibData->cameraMatrix, mCalibData->distCoeffs, mCalibData->imageSize, 0.0, mCalibData->imageSize),
mCalibData->imageSize, CV_16SC2, mCalibData->undistMap1, mCalibData->undistMap2);
}
|
ast_based
|
<|fim_prefix|>// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bitcoin-build-config.h> // IWYU pragma: keep
#include <addrdb.h>
#include <addrman.h>
#include <chainparams.h>
#include <clientversion.h>
#include <common/args.h>
#include <common/settings.h>
#include <cstdint>
#include <hash.h>
#include <logging.h>
#include <logging/timer.h>
#include <netbase.h>
#include <netgroup.h>
#include <random.h>
#include <streams.h>
#include <tinyformat.h>
#include <univalue.h>
#include <util/fs.h>
#include <util/fs_helpers.h>
#include <util/syserror.h>
#include <util/translation.h>
namespace {
class DbNotFoundError : public std::exception
{
using std::exception::exception;
};
template <typename Stream, typename Data>
bool SerializeDB(Stream& stream, const Data& data)
{
// Write and commit header, data
try {
HashedSourceWriter hashwriter{stream};
hashwriter << Params().MessageStart() << data;
stream << hashwriter.GetHash();
} catch (const std::exception& e) {
LogError("%s: Serialize or I/O error - %s\n", __func__, e.what());
return false;
}
return true;
}
template <typename Data>
bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data)
{
// Generate random temporary filename
const uint16_t randv{FastRandomContext().rand<uint16_t>()};
std::string tmpfn = strprintf("%s.%04x", prefix, randv);
// open temp output file
fs::path pathTmp = gArgs.GetDataDirNet() / fs::u8path(tmpfn);
FILE *file = fsbridge::fopen(pathTmp, "wb");
AutoFile fileout{file};
if (fileout.IsNull()) {
remove(pathTmp);
LogError("%s: Failed to open file %s\n", __func__, fs::PathToString(pathTmp));
return false;
}
// Serialize
if (!SerializeDB(fileout, data)) {
(void)fileout.fclose();
remove(pathTmp);
return false;
}
if (!fileout.Commit()) {
(void)fileout.fclose();<|fim_suffix|> if (fileout.fclose() != 0) {
const int errno_save{errno};
remove(pathTmp);
LogError("Failed to close file %s after commit: %s", fs::PathToString(pathTmp), SysErrorString(errno_save));
return false;
}
// replace existing file, if any, with new file
if (!RenameOver(pathTmp, path)) {
remove(pathTmp);
LogError("%s: Rename-into-place failed\n", __func__);
return false;
}
return true;
}
template <typename Stream, typename Data>
void DeserializeDB(Stream& stream, Data&& data, bool fCheckSum = true)
{
HashVerifier verifier{stream};
// de-serialize file header (network specific magic number) and ..
MessageStartChars pchMsgTmp;
verifier >> pchMsgTmp;
// ... verify the network matches ours
if (pchMsgTmp != Params().MessageStart()) {
throw std::runtime_error{"Invalid network magic number"};
}
// de-serialize data
verifier >> data;
// verify checksum
if (fCheckSum) {
uint256 hashTmp;
stream >> hashTmp;
if (hashTmp != verifier.GetHash()) {
throw std::runtime_error{"Checksum mismatch, data corrupted"};
}
}
}
template <typename Data>
void DeserializeFileDB(const fs::path& path, Data&& data)
{
FILE* file = fsbridge::fopen(path, "rb");
AutoFile filein{file};
if (filein.IsNull()) {
throw DbNotFoundError{};
}
DeserializeDB(filein, data);
}
} // namespace
CBanDB::CBanDB(fs::path ban_list_path)
: m_banlist_dat(ban_list_path + ".dat"),
m_banlist_json(ban_list_path + ".json")
{
}
bool CBanDB::Write(const banmap_t& banSet)
{
std::vector<std::string> errors;
if (common::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) {
return true;
}
for (const auto& err : errors) {
LogError("%s\n", err);
}
return false;
}
bool CBanDB::Read(banmap_t& banSet)
{
if (fs::exists(m_banlist_dat)) {<|fim_middle|> remove(pathTmp);
LogError("%s: Failed to flush file %s\n", __func__, fs::PathToString(pathTmp));
return false;
}
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bitcoin-build-config.h> // IWYU pragma: keep
#include <addrdb.h>
#include <addrman.h>
#include <chainparams.h>
#include <clientversion.h>
#include <common/args.h>
#include <common/settings.h>
#include <cstdint>
#include <hash.h>
#include <logging.h>
#include <logging/timer.h>
#include <netbase.h>
#include <netgroup.h>
#include <random.h>
#include <streams.h>
#include <tinyformat.h>
#include <univalue.h>
#include <util/fs.h>
#include <util/fs_helpers.h>
#include <util/syserror.h>
#include <util/translation.h>
namespace {
class DbNotFoundError : public std::exception
{
using std::exception::exception;
};
template <typename Stream, typename Data>
bool SerializeDB(Stream& stream, const Data& data)
{
// Write and commit header, data
try {
HashedSourceWriter hashwriter{stream};
hashwriter << Params().MessageStart() << data;
stream << hashwriter.GetHash();
} catch (const std::exception& e) {
LogError("%s: Serialize or I/O error - %s\n", __func__, e.what());
return false;
}
return true;
}
template <typename Data>
bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data)
{
// Generate random temporary filename
const uint16_t randv{FastRandomContext().rand<uint16_t>()};
std::string tmpfn = strprintf("%s.%04x", prefix, randv);
// open temp output file
fs::path pathTmp = gArgs.GetDataDirNet() / fs::u8path(tmpfn);
FILE *file = fsbridge::fopen(pathTmp, "wb");
AutoFile fileout{file};
if (fileout.IsNull()) {
remove(pathTmp);
LogError("%s: Failed to open file %s\n", __func__, fs::PathToString(pathTmp));
return false;
}
// Serialize
if (!SerializeDB(fileout, data)) {
(void)fileout.fclose();
remove(pathTmp);
return false;
}
if (!fileout.Commit()) {
(void)fileout.fclose();
|
remove(pathTmp);
LogError("%s: Failed to flush file %s\n", __func__, fs::PathToString(pathTmp));
return false;
}
|
if (fileout.fclose() != 0) {
const int errno_save{errno};
remove(pathTmp);
LogError("Failed to close file %s after commit: %s", fs::PathToString(pathTmp), SysErrorString(errno_save));
return false;
}
// replace existing file, if any, with new file
if (!RenameOver(pathTmp, path)) {
remove(pathTmp);
LogError("%s: Rename-into-place failed\n", __func__);
return false;
}
return true;
}
template <typename Stream, typename Data>
void DeserializeDB(Stream& stream, Data&& data, bool fCheckSum = true)
{
HashVerifier verifier{stream};
// de-serialize file header (network specific magic number) and ..
MessageStartChars pchMsgTmp;
verifier >> pchMsgTmp;
// ... verify the network matches ours
if (pchMsgTmp != Params().MessageStart()) {
throw std::runtime_error{"Invalid network magic number"};
}
// de-serialize data
verifier >> data;
// verify checksum
if (fCheckSum) {
uint256 hashTmp;
stream >> hashTmp;
if (hashTmp != verifier.GetHash()) {
throw std::runtime_error{"Checksum mismatch, data corrupted"};
}
}
}
template <typename Data>
void DeserializeFileDB(const fs::path& path, Data&& data)
{
FILE* file = fsbridge::fopen(path, "rb");
AutoFile filein{file};
if (filein.IsNull()) {
throw DbNotFoundError{};
}
DeserializeDB(filein, data);
}
} // namespace
CBanDB::CBanDB(fs::path ban_list_path)
: m_banlist_dat(ban_list_path + ".dat"),
m_banlist_json(ban_list_path + ".json")
{
}
bool CBanDB::Write(const banmap_t& banSet)
{
std::vector<std::string> errors;
if (common::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) {
return true;
}
for (const auto& err : errors) {
LogError("%s\n", err);
}
return false;
}
bool CBanDB::Read(banmap_t& banSet)
{
if (fs::exists(m_banlist_dat)) {
|
random
|
<|fim_prefix|>ringName(font_color), SNAME("Label"));
const Color h_line_color = get_theme_color(SNAME("h_line_color"), SNAME("AnimationBezierTrackEdit"));
const Color v_line_color = get_theme_color(SNAME("v_line_color"), SNAME("AnimationBezierTrackEdit"));
const Color focus_color = get_theme_color(SNAME("focus_color"), SNAME("AnimationBezierTrackEdit"));
const Color track_focus_color = get_theme_color(SNAME("track_focus_color"), SNAME("AnimationBezierTrackEdit"));
const int h_separation = get_theme_constant(SNAME("h_separation"), SNAME("AnimationBezierTrackEdit"));
const int v_separation = get_theme_constant(SNAME("h_separation"), SNAME("AnimationBezierTrackEdit"));
if (has_focus()) {
draw_rect(Rect2(Point2(), get_size()), focus_color, false, Math::round(EDSCALE));
}
draw_line(Point2(limit, 0), Point2(limit, get_size().height), v_line_color, Math::round(EDSCALE));
int right_limit = get_size().width;
track_v_scroll_max = v_separation;
int vofs = v_separation + track_v_scroll;
int margin = 0;
RBMap<int, Color> subtrack_colors;
Color selected_track_color;
subtracks.clear();
subtrack_icons.clear();
RBMap<String, Vector<int>> track_indices;
int track_count = animation->get_track_count();
for (int i = 0; i < track_count; ++i) {
if (!_is_track_displayed(i)) {
continue;
}
String base_path = String(animation->track_get_path(i));
int end = base_path.find_char(':');
if (end != -1) {
base_path = base_path.substr(0, end + 1);
}
Vector<int> indices = track_indices.has(base_path) ? track_indices[base_path] : Vector<int>();
indices.push_back(i);
track_indices[base_path] = indices;
}
for (const KeyValue<String, Vector<int>> &E : track_indices) {
String base_path = E.key;
Vector<int> tracks = E.value;
// Names and icon.
{
NodePath path = animation->track_get_path(tracks[0]);
Node *node = nullptr;
if (root && root->has_node(path)) {
<|fim_suffix|>
}
String text;
if (node) {
int ofs = 0;
Ref<Texture2D> icon = EditorNode::get_singleton()->get_object_icon(node, "Node");
text = node->get_name();
ofs += h_separation;
TextLine text_buf = TextLine(text, font, font_size);
text_buf.set_width(limit - ofs - icon->get_width() - h_separation);
int h = MAX(text_buf.get_size().y, icon->get_height());
draw_texture(icon, Point2(ofs, vofs + int(h - icon->get_height()) / 2.0));
ofs += icon->get_width() + h_separation;
margin = icon->get_width();
Vector2 string_pos = Point2(ofs, vofs);
string_pos = string_pos.floor();
text_buf.draw(get_canvas_item(), string_pos, color);
vofs += h + v_separation;
track_v_scroll_max += h + v_separation;
}
}
const Color dc = get_theme_color(SNAME("font_disabled_color"), EditorStringName(Editor));
Ref<Texture2D> remove = get_editor_theme_icon(SNAME("Remove"));
float remove_hpos = limit - h_separation - remove->get_width();
Ref<Texture2D> lock = get_editor_theme_icon(SNAME("Lock"));
Ref<Texture2D> unlock = get_editor_theme_icon(SNAME("Unlock"));
float lock_hpos = remove_hpos - h_separation - lock->get_width();
Ref<Texture2D> visibility_visible = get_editor_theme_icon(SNAME("GuiVisibilityVisible"));
Ref<Texture2D> visibility_hidden = get_editor_theme_icon(SNAME("GuiVisibilityHidden"));
float visibility_hpos = lock_hpos - h_separation - visibility_visible->get_width();
Ref<Texture2D> solo = get_editor_theme_icon(SNAME("AudioBusSolo"));
float solo_hpos = visibility_hpos - h_separation - solo->get_width();
float buttons_width = remove->get_width() + lock->get_width() + visibility_visible->get_width() + solo->get_width() + h_separation * 3;
for (int i = 0; i < tracks.size(); ++i) {
// Related track titles.
int current_track = tracks[i];
String path = String(animation->track_get_path(current_track));
pat<|fim_middle|>node = root->get_node(path);
|
ringName(font_color), SNAME("Label"));
const Color h_line_color = get_theme_color(SNAME("h_line_color"), SNAME("AnimationBezierTrackEdit"));
const Color v_line_color = get_theme_color(SNAME("v_line_color"), SNAME("AnimationBezierTrackEdit"));
const Color focus_color = get_theme_color(SNAME("focus_color"), SNAME("AnimationBezierTrackEdit"));
const Color track_focus_color = get_theme_color(SNAME("track_focus_color"), SNAME("AnimationBezierTrackEdit"));
const int h_separation = get_theme_constant(SNAME("h_separation"), SNAME("AnimationBezierTrackEdit"));
const int v_separation = get_theme_constant(SNAME("h_separation"), SNAME("AnimationBezierTrackEdit"));
if (has_focus()) {
draw_rect(Rect2(Point2(), get_size()), focus_color, false, Math::round(EDSCALE));
}
draw_line(Point2(limit, 0), Point2(limit, get_size().height), v_line_color, Math::round(EDSCALE));
int right_limit = get_size().width;
track_v_scroll_max = v_separation;
int vofs = v_separation + track_v_scroll;
int margin = 0;
RBMap<int, Color> subtrack_colors;
Color selected_track_color;
subtracks.clear();
subtrack_icons.clear();
RBMap<String, Vector<int>> track_indices;
int track_count = animation->get_track_count();
for (int i = 0; i < track_count; ++i) {
if (!_is_track_displayed(i)) {
continue;
}
String base_path = String(animation->track_get_path(i));
int end = base_path.find_char(':');
if (end != -1) {
base_path = base_path.substr(0, end + 1);
}
Vector<int> indices = track_indices.has(base_path) ? track_indices[base_path] : Vector<int>();
indices.push_back(i);
track_indices[base_path] = indices;
}
for (const KeyValue<String, Vector<int>> &E : track_indices) {
String base_path = E.key;
Vector<int> tracks = E.value;
// Names and icon.
{
NodePath path = animation->track_get_path(tracks[0]);
Node *node = nullptr;
if (root && root->has_node(path)) {
|
node = root->get_node(path);
|
}
String text;
if (node) {
int ofs = 0;
Ref<Texture2D> icon = EditorNode::get_singleton()->get_object_icon(node, "Node");
text = node->get_name();
ofs += h_separation;
TextLine text_buf = TextLine(text, font, font_size);
text_buf.set_width(limit - ofs - icon->get_width() - h_separation);
int h = MAX(text_buf.get_size().y, icon->get_height());
draw_texture(icon, Point2(ofs, vofs + int(h - icon->get_height()) / 2.0));
ofs += icon->get_width() + h_separation;
margin = icon->get_width();
Vector2 string_pos = Point2(ofs, vofs);
string_pos = string_pos.floor();
text_buf.draw(get_canvas_item(), string_pos, color);
vofs += h + v_separation;
track_v_scroll_max += h + v_separation;
}
}
const Color dc = get_theme_color(SNAME("font_disabled_color"), EditorStringName(Editor));
Ref<Texture2D> remove = get_editor_theme_icon(SNAME("Remove"));
float remove_hpos = limit - h_separation - remove->get_width();
Ref<Texture2D> lock = get_editor_theme_icon(SNAME("Lock"));
Ref<Texture2D> unlock = get_editor_theme_icon(SNAME("Unlock"));
float lock_hpos = remove_hpos - h_separation - lock->get_width();
Ref<Texture2D> visibility_visible = get_editor_theme_icon(SNAME("GuiVisibilityVisible"));
Ref<Texture2D> visibility_hidden = get_editor_theme_icon(SNAME("GuiVisibilityHidden"));
float visibility_hpos = lock_hpos - h_separation - visibility_visible->get_width();
Ref<Texture2D> solo = get_editor_theme_icon(SNAME("AudioBusSolo"));
float solo_hpos = visibility_hpos - h_separation - solo->get_width();
float buttons_width = remove->get_width() + lock->get_width() + visibility_visible->get_width() + solo->get_width() + h_separation * 3;
for (int i = 0; i < tracks.size(); ++i) {
// Related track titles.
int current_track = tracks[i];
String path = String(animation->track_get_path(current_track));
pat
|
ast_based
|
<|fim_prefix|> struct ggml_context * ctx_data = NULL;
struct gguf_init_params params = {
/*.no_alloc = */ false,
/*.ctx = */ &ctx_data,
};
struct gguf_context * ctx = gguf_init_from_file(filename, params);
GGML_ASSERT(ctx != NULL);
const int model_idx = gguf_find_key(ctx, KV_TOKENIZER_MODEL);
GGML_ASSERT(model_idx >= 0);
std::string tokenizer_name = gguf_get_val_str(ctx, model_idx);
GGML_ASSERT(tokenizer_name == TOKENIZER_NAME);
const int token_idx = gguf_find_key(ctx, KV_TOKENIZER_LIST);
GGML_ASSERT(token_idx >= 0);
const int score_idx = gguf_find_key(ctx, KV_TOKENIZER_SCORES);
GGML_ASSERT(score_idx >= 0);
const float * scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
const int toktype_idx = gguf_find_key(ctx, KV_TOKENIZER_TOKEN_TYPE);
GGML_ASSERT(toktype_idx >= 0);
const int * toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
if (n_vocab != static_cast<uint32_t>(config->vocab_size)) {
die_fmt("vocab size mismatch: (gguf) %u != (llama2c) %d", n_vocab, config->vocab_size);
}
vocab->id_to_token.resize(n_vocab);
for (uint32_t i = 0; i < n_vocab; i++) {
std::string word = gguf_get_arr_str(ctx, token_idx, i);
vocab->token_to_id[word] = i;
auto & token_data = vocab->id_to_token[i];
token_data.text = std::move(word);
token_data.score = scores[i];
token_data.type = (llama_token_type) toktypes[i];
}
ggml_free(ctx_data);
gguf_free(ctx);
} else {
// assume llama2.c vocabulary
LOG_INF("%s: Assuming llama2.c vocabulary since %s is not a gguf file\n", __func__, filename);
my_llama_file file(filename, "rb");<|fim_suffix|>
unsigned char byte_val;
my_llama_vocab::ttype type = LLAMA_TOKEN_TYPE_NORMAL;
if (id == UNKNOWN_TOKEN_ID) {
text = "<unk>";
type = LLAMA_TOKEN_TYPE_UNKNOWN;
} else if (id == BOS_TOKEN_ID) {
text = "<s>";
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (id == EOS_TOKEN_ID) {
text = "</s>";
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (text.empty()) {
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (sscanf(text.c_str(), "<0x%02hhX>", &byte_val) == 1) {
// Text of byte tokens is already in the expected format.
type = LLAMA_TOKEN_TYPE_BYTE;
} else {
type = LLAMA_TOKEN_TYPE_NORMAL;
}
text = llama_escape_whitespaces(text);
vocab->id_to_token[id].text = text;
vocab->id_to_token[id].score = score;
vocab->id_to_token[id].type = type;
vocab->token_to_id.emplace(text, id);
}
}
}
static void convert_weights_ak_to_gg(struct ggml_tensor * gg_weights, const float * karpathy_weights) {
int size = 1;
for (int dim = 0; dim < ggml_n_dims(gg_weights); ++dim) {
size *= gg_weights->ne[dim];
}
for (int ct = 0; ct < size; ++ct) {
int64_t i0 = 0; int64_t i1 = 0;
int64_t i2 = 0; int64_t i3 = 0;
ggml_unravel_index(gg_weights, ct, &i0, &i1, &i2, &i3);
ggml_set_f32_nd(gg_weights, i0, i1, i2, i3, karpathy_weights[ct]);
}
}
static void save_as_llama_model(
struct my_llama_vocab * vocab, struct my_llama_model * model, TransformerWeights* w, const char * filename
) {
// convert AK weights into GG weights one by one.
// w->token_embedding_table -> model->tok_embeddings
// float* -> struct ggml_tensor<|fim_middle|> if (!file.fp) {
die_fmt("%s: %s", strerror(errno), filename);
}
const int n_vocab = config->vocab_size;
/* uint32_t max_token_length = */ file.read_u32(); // unused
vocab->id_to_token.resize(n_vocab);
for (my_llama_vocab::id id=0; id<n_vocab; ++id) {
float_t score = file.read_f32();
uint32_t len = file.read_u32();
std::string text = file.read_string(len);
|
struct ggml_context * ctx_data = NULL;
struct gguf_init_params params = {
/*.no_alloc = */ false,
/*.ctx = */ &ctx_data,
};
struct gguf_context * ctx = gguf_init_from_file(filename, params);
GGML_ASSERT(ctx != NULL);
const int model_idx = gguf_find_key(ctx, KV_TOKENIZER_MODEL);
GGML_ASSERT(model_idx >= 0);
std::string tokenizer_name = gguf_get_val_str(ctx, model_idx);
GGML_ASSERT(tokenizer_name == TOKENIZER_NAME);
const int token_idx = gguf_find_key(ctx, KV_TOKENIZER_LIST);
GGML_ASSERT(token_idx >= 0);
const int score_idx = gguf_find_key(ctx, KV_TOKENIZER_SCORES);
GGML_ASSERT(score_idx >= 0);
const float * scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
const int toktype_idx = gguf_find_key(ctx, KV_TOKENIZER_TOKEN_TYPE);
GGML_ASSERT(toktype_idx >= 0);
const int * toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
if (n_vocab != static_cast<uint32_t>(config->vocab_size)) {
die_fmt("vocab size mismatch: (gguf) %u != (llama2c) %d", n_vocab, config->vocab_size);
}
vocab->id_to_token.resize(n_vocab);
for (uint32_t i = 0; i < n_vocab; i++) {
std::string word = gguf_get_arr_str(ctx, token_idx, i);
vocab->token_to_id[word] = i;
auto & token_data = vocab->id_to_token[i];
token_data.text = std::move(word);
token_data.score = scores[i];
token_data.type = (llama_token_type) toktypes[i];
}
ggml_free(ctx_data);
gguf_free(ctx);
} else {
// assume llama2.c vocabulary
LOG_INF("%s: Assuming llama2.c vocabulary since %s is not a gguf file\n", __func__, filename);
my_llama_file file(filename, "rb");
|
if (!file.fp) {
die_fmt("%s: %s", strerror(errno), filename);
}
const int n_vocab = config->vocab_size;
/* uint32_t max_token_length = */ file.read_u32(); // unused
vocab->id_to_token.resize(n_vocab);
for (my_llama_vocab::id id=0; id<n_vocab; ++id) {
float_t score = file.read_f32();
uint32_t len = file.read_u32();
std::string text = file.read_string(len);
|
unsigned char byte_val;
my_llama_vocab::ttype type = LLAMA_TOKEN_TYPE_NORMAL;
if (id == UNKNOWN_TOKEN_ID) {
text = "<unk>";
type = LLAMA_TOKEN_TYPE_UNKNOWN;
} else if (id == BOS_TOKEN_ID) {
text = "<s>";
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (id == EOS_TOKEN_ID) {
text = "</s>";
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (text.empty()) {
type = LLAMA_TOKEN_TYPE_CONTROL;
} else if (sscanf(text.c_str(), "<0x%02hhX>", &byte_val) == 1) {
// Text of byte tokens is already in the expected format.
type = LLAMA_TOKEN_TYPE_BYTE;
} else {
type = LLAMA_TOKEN_TYPE_NORMAL;
}
text = llama_escape_whitespaces(text);
vocab->id_to_token[id].text = text;
vocab->id_to_token[id].score = score;
vocab->id_to_token[id].type = type;
vocab->token_to_id.emplace(text, id);
}
}
}
static void convert_weights_ak_to_gg(struct ggml_tensor * gg_weights, const float * karpathy_weights) {
int size = 1;
for (int dim = 0; dim < ggml_n_dims(gg_weights); ++dim) {
size *= gg_weights->ne[dim];
}
for (int ct = 0; ct < size; ++ct) {
int64_t i0 = 0; int64_t i1 = 0;
int64_t i2 = 0; int64_t i3 = 0;
ggml_unravel_index(gg_weights, ct, &i0, &i1, &i2, &i3);
ggml_set_f32_nd(gg_weights, i0, i1, i2, i3, karpathy_weights[ct]);
}
}
static void save_as_llama_model(
struct my_llama_vocab * vocab, struct my_llama_model * model, TransformerWeights* w, const char * filename
) {
// convert AK weights into GG weights one by one.
// w->token_embedding_table -> model->tok_embeddings
// float* -> struct ggml_tensor
|
random
|
<|fim_prefix|>
if (tesseract_->SegmentPage(input_file_.c_str(), block_list_, osd_tess, &osr) < 0) {
return -1;
}
// If Devanagari is being recognized, we use different images for page seg
// and for OCR.
tesseract_->PrepareForTessOCR(block_list_, osd_tess, &osr);
return 0;
}
/**
* Return average gradient of lines on page.
*/
float TessBaseAPI::GetGradient() {
return tesseract_->gradient();
}
/** Delete the pageres and clear the block list ready for a new page. */
void TessBaseAPI::ClearResults() {
if (tesseract_ != nullptr) {
tesseract_->Clear();
}
delete page_res_;
page_res_ = nullptr;
recognition_done_ = false;
if (block_list_ == nullptr) {
block_list_ = new BLOCK_LIST;
} else {
block_list_->clear();
}
if (paragraph_models_ != nullptr) {
for (auto model : *paragraph_models_) {
delete model;
}
delete paragraph_models_;
paragraph_models_ = nullptr;
}
}
/**
* Return the length of the output text string, as UTF8, assuming
* liberally two spacing marks after each word (as paragraphs end with two
* newlines), and assuming a single character reject marker for each rejected
* character.
* Also return the number of recognized blobs in blob_count.
*/
int TessBaseAPI::TextLength(int *blob_count) const {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return 0;
}
PAGE_RES_IT page_res_it(page_res_);
int total_length = 2;
int total_blobs = 0;
// Iterate over the data structures to extract the recognition result.
for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
WERD_CHOICE *choice = word->best_choice;
if (choice != nullptr) {
total_blobs += choice->length() + 2;
total_length += choice->unichar_string().length() + 2;
for (int i = 0; i < word->reject_map.length(); ++i) {
if (word->reject_map[i].rejected()) {
++total_length;
}
}<|fim_suffix|> * Estimates the Orientation And Script of the image.
* Returns true if the image was processed successfully.
*/
bool TessBaseAPI::DetectOS(OSResults *osr) {
if (tesseract_ == nullptr) {
return false;
}
ClearResults();
if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
return false;
}
if (input_file_.empty()) {
input_file_ = kInputFile;
}
return orientation_and_script_detection(input_file_.c_str(), osr, tesseract_) > 0;
}
#endif // #ifndef DISABLED_LEGACY_ENGINE
void TessBaseAPI::set_min_orientation_margin(double margin) {
tesseract_->min_orientation_margin.set_value(margin);
}
/**
* Return text orientation of each block as determined in an earlier page layout
* analysis operation. Orientation is returned as the number of ccw 90-degree
* rotations (in [0..3]) required to make the text in the block upright
* (readable). Note that this may not necessary be the block orientation
* preferred for recognition (such as the case of vertical CJK text).
*
* Also returns whether the text in the block is believed to have vertical
* writing direction (when in an upright page orientation).
*
* The returned array is of length equal to the number of text blocks, which may
* be less than the total number of blocks. The ordering is intended to be
* consistent with GetTextLines().
*/
void TessBaseAPI::GetBlockTextOrientations(int **block_orientation, bool **vertical_writing) {
delete[] * block_orientation;
*block_orientation = nullptr;
delete[] * vertical_writing;
*vertical_writing = nullptr;
BLOCK_IT block_it(block_list_);
block_it.move_to_first();
int num_blocks = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
++num_blocks;
}
if (!num_blocks) {
tprintf("WARNING: Found no blocks\n");
return;
}
*block_orientation = new int[num_blocks];<|fim_middle|> }
}
if (blob_count != nullptr) {
*blob_count = total_blobs;
}
return total_length;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
|
if (tesseract_->SegmentPage(input_file_.c_str(), block_list_, osd_tess, &osr) < 0) {
return -1;
}
// If Devanagari is being recognized, we use different images for page seg
// and for OCR.
tesseract_->PrepareForTessOCR(block_list_, osd_tess, &osr);
return 0;
}
/**
* Return average gradient of lines on page.
*/
float TessBaseAPI::GetGradient() {
return tesseract_->gradient();
}
/** Delete the pageres and clear the block list ready for a new page. */
void TessBaseAPI::ClearResults() {
if (tesseract_ != nullptr) {
tesseract_->Clear();
}
delete page_res_;
page_res_ = nullptr;
recognition_done_ = false;
if (block_list_ == nullptr) {
block_list_ = new BLOCK_LIST;
} else {
block_list_->clear();
}
if (paragraph_models_ != nullptr) {
for (auto model : *paragraph_models_) {
delete model;
}
delete paragraph_models_;
paragraph_models_ = nullptr;
}
}
/**
* Return the length of the output text string, as UTF8, assuming
* liberally two spacing marks after each word (as paragraphs end with two
* newlines), and assuming a single character reject marker for each rejected
* character.
* Also return the number of recognized blobs in blob_count.
*/
int TessBaseAPI::TextLength(int *blob_count) const {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return 0;
}
PAGE_RES_IT page_res_it(page_res_);
int total_length = 2;
int total_blobs = 0;
// Iterate over the data structures to extract the recognition result.
for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
WERD_CHOICE *choice = word->best_choice;
if (choice != nullptr) {
total_blobs += choice->length() + 2;
total_length += choice->unichar_string().length() + 2;
for (int i = 0; i < word->reject_map.length(); ++i) {
if (word->reject_map[i].rejected()) {
++total_length;
}
}
|
}
}
if (blob_count != nullptr) {
*blob_count = total_blobs;
}
return total_length;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
|
* Estimates the Orientation And Script of the image.
* Returns true if the image was processed successfully.
*/
bool TessBaseAPI::DetectOS(OSResults *osr) {
if (tesseract_ == nullptr) {
return false;
}
ClearResults();
if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
return false;
}
if (input_file_.empty()) {
input_file_ = kInputFile;
}
return orientation_and_script_detection(input_file_.c_str(), osr, tesseract_) > 0;
}
#endif // #ifndef DISABLED_LEGACY_ENGINE
void TessBaseAPI::set_min_orientation_margin(double margin) {
tesseract_->min_orientation_margin.set_value(margin);
}
/**
* Return text orientation of each block as determined in an earlier page layout
* analysis operation. Orientation is returned as the number of ccw 90-degree
* rotations (in [0..3]) required to make the text in the block upright
* (readable). Note that this may not necessary be the block orientation
* preferred for recognition (such as the case of vertical CJK text).
*
* Also returns whether the text in the block is believed to have vertical
* writing direction (when in an upright page orientation).
*
* The returned array is of length equal to the number of text blocks, which may
* be less than the total number of blocks. The ordering is intended to be
* consistent with GetTextLines().
*/
void TessBaseAPI::GetBlockTextOrientations(int **block_orientation, bool **vertical_writing) {
delete[] * block_orientation;
*block_orientation = nullptr;
delete[] * vertical_writing;
*vertical_writing = nullptr;
BLOCK_IT block_it(block_list_);
block_it.move_to_first();
int num_blocks = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
++num_blocks;
}
if (!num_blocks) {
tprintf("WARNING: Found no blocks\n");
return;
}
*block_orientation = new int[num_blocks];
|
random
|
<|fim_prefix|>in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#include <grpc/grpc.h>
#include <grpc/impl/connectivity_state.h>
#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/time.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/completion_queue.h>
#include <grpcpp/impl/call.h>
#include <grpcpp/impl/call_op_set_interface.h>
#include <grpcpp/impl/completion_queue_tag.h>
#include <grpcpp/impl/rpc_method.h>
#include <grpcpp/impl/sync.h>
#include <grpcpp/support/client_interceptor.h>
#include <grpcpp/support/slice.h>
#include <atomic>
#include <cstring>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/util/grpc_check.h"
namespace grpc {
Channel::Channel(
const std::string& host, grpc_channel* channel,
std::vector<
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators)
: host_(host), c_channel_(channel) {
interceptor_creators_ = std::move(interceptor_creators);
}
Channel::~Channel() {
grpc_channel_destroy(c_channel_);
CompletionQueue* callback_cq = callback_cq_.load(std::memory_order_relaxed);
if (callback_cq != nullptr) {
if (grpc_iomgr_run_in_background()) {
// gRPC-core provides the backing needed for the preferred CQ type
callback_cq->Shutdown();
} else {
CompletionQueue::ReleaseCallbackAlternativeCQ(callback_cq);
}
}
}
namespace {
inline grpc_slice SliceFromArray(const char* arr, <|fim_suffix|>) {
return grpc_slice_from_copied_buffer(arr, len);
}
std::string GetChannelInfoField(grpc_channel* channel,
grpc_channel_info* channel_info,
char*** channel_info_field) {
char* value = nullptr;
memset(channel_info, 0, sizeof(*channel_info));
*channel_info_field = &value;
grpc_channel_get_info(channel, channel_info);
if (value == nullptr) return "";
std::string result = value;
gpr_free(value);
return result;
}
} // namespace
std::string Channel::GetLoadBalancingPolicyName() const {
grpc_channel_info channel_info;
return GetChannelInfoField(c_channel_, &channel_info,
&channel_info.lb_policy_name);
}
std::string Channel::GetServiceConfigJSON() const {
grpc_channel_info channel_info;
return GetChannelInfoField(c_channel_, &channel_info,
&channel_info.service_config_json);
}
namespace experimental {
void ChannelResetConnectionBackoff(Channel* channel) {
grpc_channel_reset_connect_backoff(channel->c_channel_);
}
int64_t ChannelGetChannelzUuid(Channel* channel) {
auto* node = grpc_channel_get_channelz_node(channel->c_channel_);
if (node == nullptr) return 0;
return node->uuid();
}
} // namespace experimental
grpc::internal::Call Channel::CreateCallInternal(
const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
grpc::CompletionQueue* cq, size_t interceptor_pos) {
const bool kRegistered = method.channel_tag() && context->authority().empty();
grpc_call* c_call = nullptr;
if (kRegistered) {
c_call = grpc_channel_create_registered_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(),
method.channel_tag(), context->raw_deadline(), nullptr);
} else {
const ::std::string* host_str = nullptr;
if (!context->authority_.empty()) {
host_str = &context->authority_;
} else if (!host_.empty()) {
<|fim_middle|>size_t len
|
in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#include <grpc/grpc.h>
#include <grpc/impl/connectivity_state.h>
#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/time.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/completion_queue.h>
#include <grpcpp/impl/call.h>
#include <grpcpp/impl/call_op_set_interface.h>
#include <grpcpp/impl/completion_queue_tag.h>
#include <grpcpp/impl/rpc_method.h>
#include <grpcpp/impl/sync.h>
#include <grpcpp/support/client_interceptor.h>
#include <grpcpp/support/slice.h>
#include <atomic>
#include <cstring>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/util/grpc_check.h"
namespace grpc {
Channel::Channel(
const std::string& host, grpc_channel* channel,
std::vector<
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators)
: host_(host), c_channel_(channel) {
interceptor_creators_ = std::move(interceptor_creators);
}
Channel::~Channel() {
grpc_channel_destroy(c_channel_);
CompletionQueue* callback_cq = callback_cq_.load(std::memory_order_relaxed);
if (callback_cq != nullptr) {
if (grpc_iomgr_run_in_background()) {
// gRPC-core provides the backing needed for the preferred CQ type
callback_cq->Shutdown();
} else {
CompletionQueue::ReleaseCallbackAlternativeCQ(callback_cq);
}
}
}
namespace {
inline grpc_slice SliceFromArray(const char* arr,
|
size_t len
|
) {
return grpc_slice_from_copied_buffer(arr, len);
}
std::string GetChannelInfoField(grpc_channel* channel,
grpc_channel_info* channel_info,
char*** channel_info_field) {
char* value = nullptr;
memset(channel_info, 0, sizeof(*channel_info));
*channel_info_field = &value;
grpc_channel_get_info(channel, channel_info);
if (value == nullptr) return "";
std::string result = value;
gpr_free(value);
return result;
}
} // namespace
std::string Channel::GetLoadBalancingPolicyName() const {
grpc_channel_info channel_info;
return GetChannelInfoField(c_channel_, &channel_info,
&channel_info.lb_policy_name);
}
std::string Channel::GetServiceConfigJSON() const {
grpc_channel_info channel_info;
return GetChannelInfoField(c_channel_, &channel_info,
&channel_info.service_config_json);
}
namespace experimental {
void ChannelResetConnectionBackoff(Channel* channel) {
grpc_channel_reset_connect_backoff(channel->c_channel_);
}
int64_t ChannelGetChannelzUuid(Channel* channel) {
auto* node = grpc_channel_get_channelz_node(channel->c_channel_);
if (node == nullptr) return 0;
return node->uuid();
}
} // namespace experimental
grpc::internal::Call Channel::CreateCallInternal(
const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
grpc::CompletionQueue* cq, size_t interceptor_pos) {
const bool kRegistered = method.channel_tag() && context->authority().empty();
grpc_call* c_call = nullptr;
if (kRegistered) {
c_call = grpc_channel_create_registered_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(),
method.channel_tag(), context->raw_deadline(), nullptr);
} else {
const ::std::string* host_str = nullptr;
if (!context->authority_.empty()) {
host_str = &context->authority_;
} else if (!host_.empty()) {
|
ast_based
|
<|fim_prefix|>tringList( const string& filename, vector<string>& l )
{
l.resize(0);
FileStorage fs(filename, FileStorage::READ);
if( !fs.isOpened() )
return false;
FileNode n = fs.getFirstTopLevelNode();
if( n.type() != FileNode::SEQ )
return false;
FileNodeIterator it = n.begin(), it_end = n.end();
for( ; it != it_end; ++it )
l.push_back((string)*it);
return true;
}
int main( int argc, char** argv )
{
int i, k;
int flags = 0;
Size boardSize, imageSize;
float squareSize, aspectRatio;
string outputFilename;
string inputFilename = "";
vector<vector<Point2f> > imgpt[3];
vector<string> imageList;
cv::CommandLineParser parser(argc, argv,
"{help ||}{w||}{h||}{s|1|}{o|out_camera_data.yml|}"
"{zt||}{a|1|}{p||}{@input||}");
if (parser.has("help"))
{
help(argv);
return 0;
}
boardSize.width = parser.get<int>("w");
boardSize.height = parser.get<int>("h");
squareSize = parser.get<float>("s");
aspectRatio = parser.get<float>("a");
if (parser.has("a"))
flags |= CALIB_FIX_ASPECT_RATIO;
if (parser.has("zt"))
flags |= CALIB_ZERO_TANGENT_DIST;
if (parser.has("p"))
flags |= CALIB_FIX_PRINCIPAL_POINT;
outputFilename = parser.get<string>("o");
inputFilename = parser.get<string>("@input");
if (!parser.check())
{
help(argv);
parser.printErrors();
return -1;
}
if (boardSize.width <= 0)
return fprintf( stderr, "Invalid board width\n" ), -1;
if (boardSize.height <= 0)
return fprintf( stderr, "Invalid board height\n" ), -1;
if (squareSize <= 0)
return fprintf( stderr, "Invalid board square width\n" ), -1;
if (aspectRatio <= 0)
return printf("Invalid aspect ratio\n" ), -1;
if( inputFilename.empty() ||
!readStringList(inputFilename, imageList) ||
imageList.size() == 0 || imageList.size() % 3 != 0 )
{
<|fim_suffix|>;
return -1;
}
Mat view, viewGray;
Mat cameraMatrix[3], distCoeffs[3], R[3], P[3], R12, T12;
for( k = 0; k < 3; k++ )
{
cameraMatrix[k] = Mat_<double>::eye(3,3);
cameraMatrix[k].at<double>(0,0) = aspectRatio;
cameraMatrix[k].at<double>(1,1) = 1;
distCoeffs[k] = Mat_<double>::zeros(5,1);
}
Mat R13=Mat_<double>::eye(3,3), T13=Mat_<double>::zeros(3,1);
FileStorage fs;
namedWindow( "Image View", 0 );
for( k = 0; k < 3; k++ )
imgpt[k].resize(imageList.size()/3);
for( i = 0; i < (int)(imageList.size()/3); i++ )
{
for( k = 0; k < 3; k++ )
{
int k1 = k == 0 ? 2 : k == 1 ? 0 : 1;
printf("%s\n", imageList[i*3+k].c_str());
view = imread(imageList[i*3+k], IMREAD_COLOR);
if(!view.empty())
{
vector<Point2f> ptvec;
imageSize = view.size();
cvtColor(view, viewGray, COLOR_BGR2GRAY);
bool found = findChessboardCorners( view, boardSize, ptvec, CALIB_CB_ADAPTIVE_THRESH );
drawChessboardCorners( view, boardSize, Mat(ptvec), found );
if( found )
{
imgpt[k1][i].resize(ptvec.size());
std::copy(ptvec.begin(), ptvec.end(), imgpt[k1][i].begin());
}
//imshow("view", view);
//int c = waitKey(0) & 255;
//if( c == 27 || c == 'q' || c == 'Q' )
// return -1;
}
}
}
printf("Running calibration ...\n");
run3Calibration(imgpt[0], imgpt[1], imgpt[2], imageSize,
boardSize, squareSize, aspectRatio, flags|CALIB_FIX_K4|CALIB_FIX_K5,
cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
cameraMatrix[2], distCoeffs[2],
R12, T12, R13, T13);
fs.open(outputFile<|fim_middle|>printf("Error: the input image list is not specified, or can not be read, or the number of files is not divisible by 3\n")
|
tringList( const string& filename, vector<string>& l )
{
l.resize(0);
FileStorage fs(filename, FileStorage::READ);
if( !fs.isOpened() )
return false;
FileNode n = fs.getFirstTopLevelNode();
if( n.type() != FileNode::SEQ )
return false;
FileNodeIterator it = n.begin(), it_end = n.end();
for( ; it != it_end; ++it )
l.push_back((string)*it);
return true;
}
int main( int argc, char** argv )
{
int i, k;
int flags = 0;
Size boardSize, imageSize;
float squareSize, aspectRatio;
string outputFilename;
string inputFilename = "";
vector<vector<Point2f> > imgpt[3];
vector<string> imageList;
cv::CommandLineParser parser(argc, argv,
"{help ||}{w||}{h||}{s|1|}{o|out_camera_data.yml|}"
"{zt||}{a|1|}{p||}{@input||}");
if (parser.has("help"))
{
help(argv);
return 0;
}
boardSize.width = parser.get<int>("w");
boardSize.height = parser.get<int>("h");
squareSize = parser.get<float>("s");
aspectRatio = parser.get<float>("a");
if (parser.has("a"))
flags |= CALIB_FIX_ASPECT_RATIO;
if (parser.has("zt"))
flags |= CALIB_ZERO_TANGENT_DIST;
if (parser.has("p"))
flags |= CALIB_FIX_PRINCIPAL_POINT;
outputFilename = parser.get<string>("o");
inputFilename = parser.get<string>("@input");
if (!parser.check())
{
help(argv);
parser.printErrors();
return -1;
}
if (boardSize.width <= 0)
return fprintf( stderr, "Invalid board width\n" ), -1;
if (boardSize.height <= 0)
return fprintf( stderr, "Invalid board height\n" ), -1;
if (squareSize <= 0)
return fprintf( stderr, "Invalid board square width\n" ), -1;
if (aspectRatio <= 0)
return printf("Invalid aspect ratio\n" ), -1;
if( inputFilename.empty() ||
!readStringList(inputFilename, imageList) ||
imageList.size() == 0 || imageList.size() % 3 != 0 )
{
|
printf("Error: the input image list is not specified, or can not be read, or the number of files is not divisible by 3\n")
|
;
return -1;
}
Mat view, viewGray;
Mat cameraMatrix[3], distCoeffs[3], R[3], P[3], R12, T12;
for( k = 0; k < 3; k++ )
{
cameraMatrix[k] = Mat_<double>::eye(3,3);
cameraMatrix[k].at<double>(0,0) = aspectRatio;
cameraMatrix[k].at<double>(1,1) = 1;
distCoeffs[k] = Mat_<double>::zeros(5,1);
}
Mat R13=Mat_<double>::eye(3,3), T13=Mat_<double>::zeros(3,1);
FileStorage fs;
namedWindow( "Image View", 0 );
for( k = 0; k < 3; k++ )
imgpt[k].resize(imageList.size()/3);
for( i = 0; i < (int)(imageList.size()/3); i++ )
{
for( k = 0; k < 3; k++ )
{
int k1 = k == 0 ? 2 : k == 1 ? 0 : 1;
printf("%s\n", imageList[i*3+k].c_str());
view = imread(imageList[i*3+k], IMREAD_COLOR);
if(!view.empty())
{
vector<Point2f> ptvec;
imageSize = view.size();
cvtColor(view, viewGray, COLOR_BGR2GRAY);
bool found = findChessboardCorners( view, boardSize, ptvec, CALIB_CB_ADAPTIVE_THRESH );
drawChessboardCorners( view, boardSize, Mat(ptvec), found );
if( found )
{
imgpt[k1][i].resize(ptvec.size());
std::copy(ptvec.begin(), ptvec.end(), imgpt[k1][i].begin());
}
//imshow("view", view);
//int c = waitKey(0) & 255;
//if( c == 27 || c == 'q' || c == 'Q' )
// return -1;
}
}
}
printf("Running calibration ...\n");
run3Calibration(imgpt[0], imgpt[1], imgpt[2], imageSize,
boardSize, squareSize, aspectRatio, flags|CALIB_FIX_K4|CALIB_FIX_K5,
cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
cameraMatrix[2], distCoeffs[2],
R12, T12, R13, T13);
fs.open(outputFile
|
ast_based
|
<|fim_prefix|> struct llama_context * ctx,
const char * path_session,
llama_token * tokens_out,
size_t n_token_capacity,
size_t * n_token_count_out);
LLAMA_API DEPRECATED(bool llama_load_session_file(
struct llama_context * ctx,
const char * path_session,
llama_token * tokens_out,
size_t n_token_capacity,
size_t * n_token_count_out),
"use llama_state_load_file instead");
LLAMA_API bool llama_state_save_file(
struct llama_context * ctx,
const char * path_session,
const llama_token * tokens,
size_t n_token_count);
LLAMA_API DEPRECATED(bool llama_save_session_file(
struct llama_context * ctx,
const char * path_session,
const llama_token * tokens,
size_t n_token_count),
"use llama_state_save_file instead");
// Get the exact size needed to copy the state of a single sequence
LLAMA_API size_t llama_state_seq_get_size(
struct llama_context * ctx,
llama_seq_id seq_id);
// Copy the state of a single sequence into the specified buffer
LLAMA_API size_t llama_state_seq_get_data(
struct llama_context * ctx,
uint8_t * dst,
size_t size,
llama_seq_id seq_id);
// Copy the sequence data (originally copied with `llama_state_seq_get_data`) into the specified sequence
// Returns:
// - Positive: Ok
// - Zero: Failed to load
LLAMA_API size_t llama_state_seq_set_data(
struct llama_context * ctx,
const uint8_t * src,
size_t size,
llama_seq_id dest_seq_id);
<|fim_suffix|> LLAMA_API size_t llama_state_seq_load_file(
struct llama_context * ctx,
const char * filepath,
llama_seq_id dest_seq_id,
llama_token * tokens_out,
size_t n_token_capacity,
size_t * n_token_count_out);
// for backwards-compat
#define LLAMA_STATE_SEQ_FLAGS_SWA_ONLY 1
// work only with partial states, such as SWA KV cache or recurrent cache (e.g. Mamba)
#define LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY 1
typedef uint32_t llama_state_seq_flags;
LLAMA_API size_t llama_state_seq_get_size_ext(
struct llama_context * ctx,
llama_seq_id seq_id,
llama_state_seq_flags flags);
LLAMA_API size_t llama_state_seq_get_data_ext(
struct llama_context * ctx,
uint8_t * dst,
size_t size,
llama_seq_id seq_id,
llama_state_seq_flags flags);
LLAMA_API size_t llama_state_seq_set_data_ext(
struct llama_context * ctx,
const uint8_t * src,
size_t size,
llama_seq_id dest_seq_id,
llama_state_seq_flags flags);
//
// Decoding
//
// Return batch for single sequence of tokens
// The sequence ID will be fixed to 0
// The position of the tokens will be tracked automatically by llama_decode
//
// NOTE: this is a helper function to facilitate transition to the new batch API - avoid using it
//
LLAMA_API struct llama_batch llama_batch_get_one(
llama_token * tokens,
int32_t n_tokens);
// Allocates a batch of tokens on the heap that can hold a maximum of n_tokens
// Each token can be assigned up to n_seq_max sequence ids
// The batch has to be freed with llama_batch_free()<|fim_middle|> LLAMA_API size_t llama_state_seq_save_file(
struct llama_context * ctx,
const char * filepath,
llama_seq_id seq_id,
const llama_token * tokens,
size_t n_token_count);
|
struct llama_context * ctx,
const char * path_session,
llama_token * tokens_out,
size_t n_token_capacity,
size_t * n_token_count_out);
LLAMA_API DEPRECATED(bool llama_load_session_file(
struct llama_context * ctx,
const char * path_session,
llama_token * tokens_out,
size_t n_token_capacity,
size_t * n_token_count_out),
"use llama_state_load_file instead");
LLAMA_API bool llama_state_save_file(
struct llama_context * ctx,
const char * path_session,
const llama_token * tokens,
size_t n_token_count);
LLAMA_API DEPRECATED(bool llama_save_session_file(
struct llama_context * ctx,
const char * path_session,
const llama_token * tokens,
size_t n_token_count),
"use llama_state_save_file instead");
// Get the exact size needed to copy the state of a single sequence
LLAMA_API size_t llama_state_seq_get_size(
struct llama_context * ctx,
llama_seq_id seq_id);
// Copy the state of a single sequence into the specified buffer
LLAMA_API size_t llama_state_seq_get_data(
struct llama_context * ctx,
uint8_t * dst,
size_t size,
llama_seq_id seq_id);
// Copy the sequence data (originally copied with `llama_state_seq_get_data`) into the specified sequence
// Returns:
// - Positive: Ok
// - Zero: Failed to load
LLAMA_API size_t llama_state_seq_set_data(
struct llama_context * ctx,
const uint8_t * src,
size_t size,
llama_seq_id dest_seq_id);
|
LLAMA_API size_t llama_state_seq_save_file(
struct llama_context * ctx,
const char * filepath,
llama_seq_id seq_id,
const llama_token * tokens,
size_t n_token_count);
|
LLAMA_API size_t llama_state_seq_load_file(
struct llama_context * ctx,
const char * filepath,
llama_seq_id dest_seq_id,
llama_token * tokens_out,
size_t n_token_capacity,
size_t * n_token_count_out);
// for backwards-compat
#define LLAMA_STATE_SEQ_FLAGS_SWA_ONLY 1
// work only with partial states, such as SWA KV cache or recurrent cache (e.g. Mamba)
#define LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY 1
typedef uint32_t llama_state_seq_flags;
LLAMA_API size_t llama_state_seq_get_size_ext(
struct llama_context * ctx,
llama_seq_id seq_id,
llama_state_seq_flags flags);
LLAMA_API size_t llama_state_seq_get_data_ext(
struct llama_context * ctx,
uint8_t * dst,
size_t size,
llama_seq_id seq_id,
llama_state_seq_flags flags);
LLAMA_API size_t llama_state_seq_set_data_ext(
struct llama_context * ctx,
const uint8_t * src,
size_t size,
llama_seq_id dest_seq_id,
llama_state_seq_flags flags);
//
// Decoding
//
// Return batch for single sequence of tokens
// The sequence ID will be fixed to 0
// The position of the tokens will be tracked automatically by llama_decode
//
// NOTE: this is a helper function to facilitate transition to the new batch API - avoid using it
//
LLAMA_API struct llama_batch llama_batch_get_one(
llama_token * tokens,
int32_t n_tokens);
// Allocates a batch of tokens on the heap that can hold a maximum of n_tokens
// Each token can be assigned up to n_seq_max sequence ids
// The batch has to be freed with llama_batch_free()
|
random
|
<|fim_prefix|> float c = (p_clip_left - from.x) / (to.x - from.x);
from = from.lerp(to, c);
}
draw_line(from, to, p_color, Math::round(EDSCALE), true);
}
void AnimationBezierTrackEdit::_notification(int p_what) {
switch (p_what) {
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
if (EditorSettings::get_singleton()->check_changed_settings_in_group("editors/panning")) {
panner->setup((ViewPanner::ControlScheme)EDITOR_GET("editors/panning/animation_editors_panning_scheme").operator int(), ED_GET_SHORTCUT("canvas_item_editor/pan_view"), bool(EDITOR_GET("editors/panning/simple_panning")));
panner->setup_warped_panning(get_viewport(), EDITOR_GET("editors/panning/warped_mouse_panning"));
}
} break;
case NOTIFICATION_ENTER_TREE: {
panner->setup((ViewPanner::ControlScheme)EDITOR_GET("editors/panning/animation_editors_panning_scheme").operator int(), ED_GET_SHORTCUT("canvas_item_editor/pan_view"), bool(EDITOR_GET("editors/panning/simple_panning")));
panner->setup_warped_panning(get_viewport(), EDITOR_GET("editors/panning/warped_mouse_panning"));
} break;
case NOTIFICATION_THEME_CHANGED: {
bezier_icon = get_editor_theme_icon(SNAME("KeyBezierPoint"));
bezier_handle_icon = get_editor_theme_icon(SNAME("KeyBezierHandle"));
selected_icon = get_editor_theme_icon(SNAME("KeyBezierSelected"));
} break;
case NOTIFICATION_ACCESSIBILITY_UPDATE: {
RID ae = get_accessibility_element();
ERR_FAIL_COND(ae.is_null());
//TODO
DisplayServer::get_singleton()->accessibility_update_set_role(ae, DisplayServer::AccessibilityRole::ROLE_STATIC_TEXT);
DisplayServer::get_singleton()->accessibility_update_set_value(ae, TTR(vformat("The %s is not accessible at this time.", "Animation bezier track editor")));
} break;
case NOTIFICATION_DRAW: {
if (animation.is_null()) {
return;
}
int limit = timeline->get_name_limit();
const Ref<Font> font = get_theme_font(SceneStringName(font), SNAME("Label"));
const int font_size = <|fim_suffix|>;
const Color color = get_theme_color(SceneStringName(font_color), SNAME("Label"));
const Color h_line_color = get_theme_color(SNAME("h_line_color"), SNAME("AnimationBezierTrackEdit"));
const Color v_line_color = get_theme_color(SNAME("v_line_color"), SNAME("AnimationBezierTrackEdit"));
const Color focus_color = get_theme_color(SNAME("focus_color"), SNAME("AnimationBezierTrackEdit"));
const Color track_focus_color = get_theme_color(SNAME("track_focus_color"), SNAME("AnimationBezierTrackEdit"));
const int h_separation = get_theme_constant(SNAME("h_separation"), SNAME("AnimationBezierTrackEdit"));
const int v_separation = get_theme_constant(SNAME("h_separation"), SNAME("AnimationBezierTrackEdit"));
if (has_focus()) {
draw_rect(Rect2(Point2(), get_size()), focus_color, false, Math::round(EDSCALE));
}
draw_line(Point2(limit, 0), Point2(limit, get_size().height), v_line_color, Math::round(EDSCALE));
int right_limit = get_size().width;
track_v_scroll_max = v_separation;
int vofs = v_separation + track_v_scroll;
int margin = 0;
RBMap<int, Color> subtrack_colors;
Color selected_track_color;
subtracks.clear();
subtrack_icons.clear();
RBMap<String, Vector<int>> track_indices;
int track_count = animation->get_track_count();
for (int i = 0; i < track_count; ++i) {
if (!_is_track_displayed(i)) {
continue;
}
String base_path = String(animation->track_get_path(i));
int end = base_path.find_char(':');
if (end != -1) {
base_path = base_path.substr(0, end + 1);
}
Vector<int> indices = track_indices.has(base_path) ? track_indices[base_path] : Vector<int>();
indices.push_back(i);
track_indices[base_path] = indices;
}
for (const KeyValue<String, Vector<int>> &E : track_indices) {
String base_path = E.key;
Vector<int> tracks = E.value;
// Names and icon.
{
NodePath path = animation->track_get_path(tracks[0]);
Node *node = nullptr;
<|fim_middle|>get_theme_font_size(SceneStringName(font_size), SNAME("Label"))
|
float c = (p_clip_left - from.x) / (to.x - from.x);
from = from.lerp(to, c);
}
draw_line(from, to, p_color, Math::round(EDSCALE), true);
}
void AnimationBezierTrackEdit::_notification(int p_what) {
switch (p_what) {
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
if (EditorSettings::get_singleton()->check_changed_settings_in_group("editors/panning")) {
panner->setup((ViewPanner::ControlScheme)EDITOR_GET("editors/panning/animation_editors_panning_scheme").operator int(), ED_GET_SHORTCUT("canvas_item_editor/pan_view"), bool(EDITOR_GET("editors/panning/simple_panning")));
panner->setup_warped_panning(get_viewport(), EDITOR_GET("editors/panning/warped_mouse_panning"));
}
} break;
case NOTIFICATION_ENTER_TREE: {
panner->setup((ViewPanner::ControlScheme)EDITOR_GET("editors/panning/animation_editors_panning_scheme").operator int(), ED_GET_SHORTCUT("canvas_item_editor/pan_view"), bool(EDITOR_GET("editors/panning/simple_panning")));
panner->setup_warped_panning(get_viewport(), EDITOR_GET("editors/panning/warped_mouse_panning"));
} break;
case NOTIFICATION_THEME_CHANGED: {
bezier_icon = get_editor_theme_icon(SNAME("KeyBezierPoint"));
bezier_handle_icon = get_editor_theme_icon(SNAME("KeyBezierHandle"));
selected_icon = get_editor_theme_icon(SNAME("KeyBezierSelected"));
} break;
case NOTIFICATION_ACCESSIBILITY_UPDATE: {
RID ae = get_accessibility_element();
ERR_FAIL_COND(ae.is_null());
//TODO
DisplayServer::get_singleton()->accessibility_update_set_role(ae, DisplayServer::AccessibilityRole::ROLE_STATIC_TEXT);
DisplayServer::get_singleton()->accessibility_update_set_value(ae, TTR(vformat("The %s is not accessible at this time.", "Animation bezier track editor")));
} break;
case NOTIFICATION_DRAW: {
if (animation.is_null()) {
return;
}
int limit = timeline->get_name_limit();
const Ref<Font> font = get_theme_font(SceneStringName(font), SNAME("Label"));
const int font_size =
|
get_theme_font_size(SceneStringName(font_size), SNAME("Label"))
|
;
const Color color = get_theme_color(SceneStringName(font_color), SNAME("Label"));
const Color h_line_color = get_theme_color(SNAME("h_line_color"), SNAME("AnimationBezierTrackEdit"));
const Color v_line_color = get_theme_color(SNAME("v_line_color"), SNAME("AnimationBezierTrackEdit"));
const Color focus_color = get_theme_color(SNAME("focus_color"), SNAME("AnimationBezierTrackEdit"));
const Color track_focus_color = get_theme_color(SNAME("track_focus_color"), SNAME("AnimationBezierTrackEdit"));
const int h_separation = get_theme_constant(SNAME("h_separation"), SNAME("AnimationBezierTrackEdit"));
const int v_separation = get_theme_constant(SNAME("h_separation"), SNAME("AnimationBezierTrackEdit"));
if (has_focus()) {
draw_rect(Rect2(Point2(), get_size()), focus_color, false, Math::round(EDSCALE));
}
draw_line(Point2(limit, 0), Point2(limit, get_size().height), v_line_color, Math::round(EDSCALE));
int right_limit = get_size().width;
track_v_scroll_max = v_separation;
int vofs = v_separation + track_v_scroll;
int margin = 0;
RBMap<int, Color> subtrack_colors;
Color selected_track_color;
subtracks.clear();
subtrack_icons.clear();
RBMap<String, Vector<int>> track_indices;
int track_count = animation->get_track_count();
for (int i = 0; i < track_count; ++i) {
if (!_is_track_displayed(i)) {
continue;
}
String base_path = String(animation->track_get_path(i));
int end = base_path.find_char(':');
if (end != -1) {
base_path = base_path.substr(0, end + 1);
}
Vector<int> indices = track_indices.has(base_path) ? track_indices[base_path] : Vector<int>();
indices.push_back(i);
track_indices[base_path] = indices;
}
for (const KeyValue<String, Vector<int>> &E : track_indices) {
String base_path = E.key;
Vector<int> tracks = E.value;
// Names and icon.
{
NodePath path = animation->track_get_path(tracks[0]);
Node *node = nullptr;
|
ast_based
|
<|fim_prefix|>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_ADDRDB_H
#define BITCOIN_ADDRDB_H
#include <net_types.h>
#include <util/fs.h>
#include <util/result.h>
#include <memory>
#include <vector>
class ArgsManager;
class AddrMan;
class CAddress;
class DataStream;
class NetGroupManager;
/** Only used by tests. */
void ReadFromStream(AddrMan& addr, DataStream& ssPeers);
bool DumpPeerAddresses(<|fim_suffix|>, const AddrMan& addr);
/** Access to the banlist database (banlist.json) */
class CBanDB
{
private:
/**
* JSON key under which the data is stored in the json database.
*/
static constexpr const char* JSON_KEY = "banned_nets";
const fs::path m_banlist_dat;
const fs::path m_banlist_json;
public:
explicit CBanDB(fs::path ban_list_path);
bool Write(const banmap_t& banSet);
/**
* Read the banlist from disk.
* @param[out] banSet The loaded list. Set if `true` is returned, otherwise it is left
* in an undefined state.
* @return true on success
*/
bool Read(banmap_t& banSet);
};
/** Returns an error string on failure */
util::Result<std::unique_ptr<AddrMan>> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args);
/**
* Dump the anchor IP address database (anchors.dat)
*
* Anchors are last known outgoing block-relay-only peers that are
* tried to re-connect to on startup.
*/
void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors);
/**
* Read the anchor IP address database (anchors.dat)
*
* Deleting anchors.dat is intentional as it avoids renewed peering to anchors after
* an unclean shutdown and thus potential exploitation of the anchor peer policy.
*/
std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path);
#endif // BITCOIN_ADDRDB_H
<|fim_middle|>const ArgsManager& args
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_ADDRDB_H
#define BITCOIN_ADDRDB_H
#include <net_types.h>
#include <util/fs.h>
#include <util/result.h>
#include <memory>
#include <vector>
class ArgsManager;
class AddrMan;
class CAddress;
class DataStream;
class NetGroupManager;
/** Only used by tests. */
void ReadFromStream(AddrMan& addr, DataStream& ssPeers);
bool DumpPeerAddresses(
|
const ArgsManager& args
|
, const AddrMan& addr);
/** Access to the banlist database (banlist.json) */
class CBanDB
{
private:
/**
* JSON key under which the data is stored in the json database.
*/
static constexpr const char* JSON_KEY = "banned_nets";
const fs::path m_banlist_dat;
const fs::path m_banlist_json;
public:
explicit CBanDB(fs::path ban_list_path);
bool Write(const banmap_t& banSet);
/**
* Read the banlist from disk.
* @param[out] banSet The loaded list. Set if `true` is returned, otherwise it is left
* in an undefined state.
* @return true on success
*/
bool Read(banmap_t& banSet);
};
/** Returns an error string on failure */
util::Result<std::unique_ptr<AddrMan>> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args);
/**
* Dump the anchor IP address database (anchors.dat)
*
* Anchors are last known outgoing block-relay-only peers that are
* tried to re-connect to on startup.
*/
void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors);
/**
* Read the anchor IP address database (anchors.dat)
*
* Deleting anchors.dat is intentional as it avoids renewed peering to anchors after
* an unclean shutdown and thus potential exploitation of the anchor peer policy.
*/
std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path);
#endif // BITCOIN_ADDRDB_H
|
ast_based
|
<|fim_prefix|>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_DTENSOR_CC_CONSTANTS_H_
#define TENSORFLOW_DTENSOR_CC_CONSTANTS_H_
namespace tensorflow {
namespace dtensor {
// Constants used within dtensor scope.
// Qualified attribute without `_` prefix.
// Used in Ops attribute registration.
static constexpr char kQualifiedLayoutAttr[] = "layout";
// Internal attribute to DTensor MLIR passes and Graph nodes.
// Prefixed with `_` so that it doesn't require op attribute registration.
static constexpr char kLayoutAttr[] = "_layout";
// Indicates a non-binding layout hint provided by the user.
// `tf` prefix attached in MLIR importer for dialect requirements.
static constexpr char kCustomDefaultLayoutAttr[] = "tf._default_layout";
<|fim_suffix|>// propagation. `tf` prefix attached in MLIR importer for dialect requirements.
static constexpr char kCustomDefaultMeshAttr[] = "tf._default_mesh";
// Attribute attached on _Arg node for the mesh config.
static constexpr char kMeshAttr[] = "_mesh";
// Attribute carries mesh information from Custom Device Arguments.
// `tf` prefix attached in MLIR importer for dialect requirements.
static constexpr char kCustomDeviceMeshAttr[] = "tf._mesh";
// Attribute carries argument indices for newly inferred layout of resource
// handle.
static constexpr char kNewResourceLayoutIndices[] =
"_inferred_resource_indices";
// Attribute carries layout for newly inferred layout of resource handle.
static constexpr char kNewResourceArgLayouts[] = "_inferred_resource_layouts";
static constexpr char kNumLocalOutputsAttr[] = "_num_local_outputs";
// Attribute carries input layout information for shape op.
static constexpr char kShapeOpInputLayout[] = "_shape_input_layout";
// Attribute carries input layout index for shape op. This forms a 1 -> 1
// mapping for kShapeOpInputLayout above.
static constexpr char kShapeOpInputLayoutIndices[] = "_shape_input_indices";
// Attribute that carries global shape of operation. Used to preserve global
// shape to be used during SPMD expansion.
static constexpr char kGlobalShape[] = "_global_shape";
// Global shape attribute with `tf.` dialect to be used for annotating func op
// arguments/return values.
static constexpr char kGlobalShapeDialectAttr[] = "tf._global_shape";
// Attribute attached to resource-type function arguments containing the local
// shape of the tensor that is being assigned to it.
static constexpr char kAssignedResourceLocalShape[] =
"tf._assigned_resource_local_shape";
// Tensor handles smaller than this is considered as small tensor. We perform
// some optimizations around it. For example, will be transformed into constant
// values during graph building, instead of being passed as inputs. In addition,<|fim_middle|>// Indicates a non-binding layout hint provided by the user.
static constexpr char kDefaultLayoutAttr[] = "_default_layout";
// Attribute carries layout information from Custom Device Arguments.
// `tf` prefix attached in MLIR importer for dialect requirements.
static constexpr char kCustomDeviceAttr[] = "tf._layout";
// Indicates a default mesh provided by the user as fallback during mesh
|
/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_DTENSOR_CC_CONSTANTS_H_
#define TENSORFLOW_DTENSOR_CC_CONSTANTS_H_
namespace tensorflow {
namespace dtensor {
// Constants used within dtensor scope.
// Qualified attribute without `_` prefix.
// Used in Ops attribute registration.
static constexpr char kQualifiedLayoutAttr[] = "layout";
// Internal attribute to DTensor MLIR passes and Graph nodes.
// Prefixed with `_` so that it doesn't require op attribute registration.
static constexpr char kLayoutAttr[] = "_layout";
// Indicates a non-binding layout hint provided by the user.
// `tf` prefix attached in MLIR importer for dialect requirements.
static constexpr char kCustomDefaultLayoutAttr[] = "tf._default_layout";
|
// Indicates a non-binding layout hint provided by the user.
static constexpr char kDefaultLayoutAttr[] = "_default_layout";
// Attribute carries layout information from Custom Device Arguments.
// `tf` prefix attached in MLIR importer for dialect requirements.
static constexpr char kCustomDeviceAttr[] = "tf._layout";
// Indicates a default mesh provided by the user as fallback during mesh
|
// propagation. `tf` prefix attached in MLIR importer for dialect requirements.
static constexpr char kCustomDefaultMeshAttr[] = "tf._default_mesh";
// Attribute attached on _Arg node for the mesh config.
static constexpr char kMeshAttr[] = "_mesh";
// Attribute carries mesh information from Custom Device Arguments.
// `tf` prefix attached in MLIR importer for dialect requirements.
static constexpr char kCustomDeviceMeshAttr[] = "tf._mesh";
// Attribute carries argument indices for newly inferred layout of resource
// handle.
static constexpr char kNewResourceLayoutIndices[] =
"_inferred_resource_indices";
// Attribute carries layout for newly inferred layout of resource handle.
static constexpr char kNewResourceArgLayouts[] = "_inferred_resource_layouts";
static constexpr char kNumLocalOutputsAttr[] = "_num_local_outputs";
// Attribute carries input layout information for shape op.
static constexpr char kShapeOpInputLayout[] = "_shape_input_layout";
// Attribute carries input layout index for shape op. This forms a 1 -> 1
// mapping for kShapeOpInputLayout above.
static constexpr char kShapeOpInputLayoutIndices[] = "_shape_input_indices";
// Attribute that carries global shape of operation. Used to preserve global
// shape to be used during SPMD expansion.
static constexpr char kGlobalShape[] = "_global_shape";
// Global shape attribute with `tf.` dialect to be used for annotating func op
// arguments/return values.
static constexpr char kGlobalShapeDialectAttr[] = "tf._global_shape";
// Attribute attached to resource-type function arguments containing the local
// shape of the tensor that is being assigned to it.
static constexpr char kAssignedResourceLocalShape[] =
"tf._assigned_resource_local_shape";
// Tensor handles smaller than this is considered as small tensor. We perform
// some optimizations around it. For example, will be transformed into constant
// values during graph building, instead of being passed as inputs. In addition,
|
random
|
<|fim_prefix|> {
CAROTENE_NS::gaussianBlur5x5(sz, cn, (int16_t*)src_data, src_step,
(int16_t*)dst_data, dst_step, border, 0, mg);
return CV_HAL_ERROR_OK;
}
}
return CV_HAL_ERROR_NOT_IMPLEMENTED;
}
#undef cv_hal_gaussianBlurBinomial
#define cv_hal_gaussianBlurBinomial TEGRA_GaussianBlurBinomial
#endif // __ARM_ARCH=7
#endif // OPENCV_IMGPROC_HAL_INTERFACE_H
// The optimized branch was developed for old armv7 processors
#if defined(__ARM_ARCH) && (__ARM_ARCH == 7)
inline int TEGRA_LKOpticalFlowLevel(const uchar *prev_data, size_t prev_data_step,
const short* prev_deriv_data, size_t prev_deriv_step,
const uchar* next_data, size_t next_step,
int width, int height, int cn,
const float *prev_points, float *next_points, size_t point_count,
uchar *status, float *err,
const int win_width, const int win_height,
int termination_count, double termination_epsilon,
bool get_min_eigen_vals,
float min_eigen_vals_threshold)
{
if (!CAROTENE_NS::isSupportedConfiguration())
return CV_HAL_ERROR_NOT_IMPLEMENTED;
CAROTENE_NS::pyrLKOptFlowLevel(CAROTENE_NS::Size2D(width, height), cn,
prev_data, prev_data_step, prev_deriv_data, prev_deriv_step,
next_data, next_step,
point_count, prev_points, next_points,
status, err, CAROTENE_NS::Size2D(win_width, win_height),
termination_count, termination_epsilon,
get_min_eigen_vals, min_eigen_vals_threshold);
return CV_HAL_ERROR_OK;
}
#undef cv_hal_LKOpticalFlowLevel
#define cv_hal_LKOpticalFlowLevel TEGRA_LKOpticalFlowLevel
#endif // __ARM_ARCH=7
#if 0 // OpenCV provides fater parallel implementation
inline int TEGRA_ScharrDeriv(const uchar* src_data, size_t src_step,
short* dst_data, <|fim_suffix|>,
int width, int height, int cn)
{
if (!CAROTENE_NS::isSupportedConfiguration())
return CV_HAL_ERROR_NOT_IMPLEMENTED;
CAROTENE_NS::ScharrDeriv(CAROTENE_NS::Size2D(width, height), cn, src_data, src_step, dst_data, dst_step);
return CV_HAL_ERROR_OK;
}
#undef cv_hal_ScharrDeriv
#define cv_hal_ScharrDeriv TEGRA_ScharrDeriv
#endif
#endif
<|fim_middle|>size_t dst_step
|
{
CAROTENE_NS::gaussianBlur5x5(sz, cn, (int16_t*)src_data, src_step,
(int16_t*)dst_data, dst_step, border, 0, mg);
return CV_HAL_ERROR_OK;
}
}
return CV_HAL_ERROR_NOT_IMPLEMENTED;
}
#undef cv_hal_gaussianBlurBinomial
#define cv_hal_gaussianBlurBinomial TEGRA_GaussianBlurBinomial
#endif // __ARM_ARCH=7
#endif // OPENCV_IMGPROC_HAL_INTERFACE_H
// The optimized branch was developed for old armv7 processors
#if defined(__ARM_ARCH) && (__ARM_ARCH == 7)
inline int TEGRA_LKOpticalFlowLevel(const uchar *prev_data, size_t prev_data_step,
const short* prev_deriv_data, size_t prev_deriv_step,
const uchar* next_data, size_t next_step,
int width, int height, int cn,
const float *prev_points, float *next_points, size_t point_count,
uchar *status, float *err,
const int win_width, const int win_height,
int termination_count, double termination_epsilon,
bool get_min_eigen_vals,
float min_eigen_vals_threshold)
{
if (!CAROTENE_NS::isSupportedConfiguration())
return CV_HAL_ERROR_NOT_IMPLEMENTED;
CAROTENE_NS::pyrLKOptFlowLevel(CAROTENE_NS::Size2D(width, height), cn,
prev_data, prev_data_step, prev_deriv_data, prev_deriv_step,
next_data, next_step,
point_count, prev_points, next_points,
status, err, CAROTENE_NS::Size2D(win_width, win_height),
termination_count, termination_epsilon,
get_min_eigen_vals, min_eigen_vals_threshold);
return CV_HAL_ERROR_OK;
}
#undef cv_hal_LKOpticalFlowLevel
#define cv_hal_LKOpticalFlowLevel TEGRA_LKOpticalFlowLevel
#endif // __ARM_ARCH=7
#if 0 // OpenCV provides fater parallel implementation
inline int TEGRA_ScharrDeriv(const uchar* src_data, size_t src_step,
short* dst_data,
|
size_t dst_step
|
,
int width, int height, int cn)
{
if (!CAROTENE_NS::isSupportedConfiguration())
return CV_HAL_ERROR_NOT_IMPLEMENTED;
CAROTENE_NS::ScharrDeriv(CAROTENE_NS::Size2D(width, height), cn, src_data, src_step, dst_data, dst_step);
return CV_HAL_ERROR_OK;
}
#undef cv_hal_ScharrDeriv
#define cv_hal_ScharrDeriv TEGRA_ScharrDeriv
#endif
#endif
|
ast_based
|
<|fim_prefix|> }
if (tessedit_page_number >= 0) {
break;
}
if (!offset) {
break;
}
}
return true;
}
// Master ProcessPages calls ProcessPagesInternal and then does any post-
// processing required due to being in a training mode.
bool TessBaseAPI::ProcessPages(const char *filename, const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer) {
bool result = ProcessPagesInternal(filename, retry_config, timeout_millisec, renderer);
#ifndef DISABLED_LEGACY_ENGINE
if (result) {
if (tesseract_->tessedit_train_from_boxes && !tesseract_->WriteTRFile(output_file_.c_str())) {
tprintf("Write of TR file failed: %s\n", output_file_.c_str());
return false;
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
return result;
}
#ifdef HAVE_LIBCURL
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size = size * nmemb;
auto *buf = reinterpret_cast<std::string *>(userp);
buf->append(reinterpret_cast<const char *>(contents), size);
return size;
}
#endif
// In the ideal scenario, Tesseract will start working on data as soon
// as it can. For example, if you stream a filelist through stdin, we
// should start the OCR process as soon as the first filename is
// available. This is particularly useful when hooking Tesseract up to
// slow hardware such as a book scanning machine.
//
// Unfortunately there are tradeoffs. You can't seek on stdin. That
// makes automatic detection of datatype (TIFF? filelist? PNG?)
// impractical. So we support a command line flag to explicitly
// identify the scenario that really matters: filelists on
// stdin. We'll still do our best if the user likes pipes.
bool TessBaseAPI::ProcessPagesInternal(const char *filename, const char *retry_config,
int timeout_millisec, TessResultRenderer *renderer) {
bool stdInput = !strcmp(filename, "stdin") || !strcmp(filename, "-");
if (stdInput) {
<|fim_suffix|> // WIN32
}
if (stream_filelist) {
return ProcessPagesFileList(stdin, nullptr, retry_config, timeout_millisec, renderer,
tesseract_->tessedit_page_number);
}
// At this point we are officially in autodection territory.
// That means any data in stdin must be buffered, to make it
// seekable.
std::string buf;
const l_uint8 *data = nullptr;
if (stdInput) {
buf.assign((std::istreambuf_iterator<char>(std::cin)), (std::istreambuf_iterator<char>()));
data = reinterpret_cast<const l_uint8 *>(buf.data());
} else if (strstr(filename, "://") != nullptr) {
// Get image or image list by URL.
#ifdef HAVE_LIBCURL
CURL *curl = curl_easy_init();
if (curl == nullptr) {
fprintf(stderr, "Error, curl_easy_init failed\n");
return false;
} else {
CURLcode curlcode;
auto error = [curl, &curlcode](const char *function) {
fprintf(stderr, "Error, %s failed with error %s\n", function, curl_easy_strerror(curlcode));
curl_easy_cleanup(curl);
return false;
};
curlcode = curl_easy_setopt(curl, CURLOPT_URL, filename);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
// Follow HTTP, HTTPS, FTP and FTPS redirects.
curlcode = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
// Allow no more than 8 redirections to prevent endless loops.
curlcode = curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 8);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
int timeout = curl_timeout;
if (timeout > 0) {
curlcode = curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt"<|fim_middle|>#ifdef WIN32
if (_setmode(_fileno(stdin), _O_BINARY) == -1)
tprintf("ERROR: cin to binary: %s", strerror(errno));
#endif
|
}
if (tessedit_page_number >= 0) {
break;
}
if (!offset) {
break;
}
}
return true;
}
// Master ProcessPages calls ProcessPagesInternal and then does any post-
// processing required due to being in a training mode.
bool TessBaseAPI::ProcessPages(const char *filename, const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer) {
bool result = ProcessPagesInternal(filename, retry_config, timeout_millisec, renderer);
#ifndef DISABLED_LEGACY_ENGINE
if (result) {
if (tesseract_->tessedit_train_from_boxes && !tesseract_->WriteTRFile(output_file_.c_str())) {
tprintf("Write of TR file failed: %s\n", output_file_.c_str());
return false;
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
return result;
}
#ifdef HAVE_LIBCURL
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size = size * nmemb;
auto *buf = reinterpret_cast<std::string *>(userp);
buf->append(reinterpret_cast<const char *>(contents), size);
return size;
}
#endif
// In the ideal scenario, Tesseract will start working on data as soon
// as it can. For example, if you stream a filelist through stdin, we
// should start the OCR process as soon as the first filename is
// available. This is particularly useful when hooking Tesseract up to
// slow hardware such as a book scanning machine.
//
// Unfortunately there are tradeoffs. You can't seek on stdin. That
// makes automatic detection of datatype (TIFF? filelist? PNG?)
// impractical. So we support a command line flag to explicitly
// identify the scenario that really matters: filelists on
// stdin. We'll still do our best if the user likes pipes.
bool TessBaseAPI::ProcessPagesInternal(const char *filename, const char *retry_config,
int timeout_millisec, TessResultRenderer *renderer) {
bool stdInput = !strcmp(filename, "stdin") || !strcmp(filename, "-");
if (stdInput) {
|
#ifdef WIN32
if (_setmode(_fileno(stdin), _O_BINARY) == -1)
tprintf("ERROR: cin to binary: %s", strerror(errno));
#endif
|
// WIN32
}
if (stream_filelist) {
return ProcessPagesFileList(stdin, nullptr, retry_config, timeout_millisec, renderer,
tesseract_->tessedit_page_number);
}
// At this point we are officially in autodection territory.
// That means any data in stdin must be buffered, to make it
// seekable.
std::string buf;
const l_uint8 *data = nullptr;
if (stdInput) {
buf.assign((std::istreambuf_iterator<char>(std::cin)), (std::istreambuf_iterator<char>()));
data = reinterpret_cast<const l_uint8 *>(buf.data());
} else if (strstr(filename, "://") != nullptr) {
// Get image or image list by URL.
#ifdef HAVE_LIBCURL
CURL *curl = curl_easy_init();
if (curl == nullptr) {
fprintf(stderr, "Error, curl_easy_init failed\n");
return false;
} else {
CURLcode curlcode;
auto error = [curl, &curlcode](const char *function) {
fprintf(stderr, "Error, %s failed with error %s\n", function, curl_easy_strerror(curlcode));
curl_easy_cleanup(curl);
return false;
};
curlcode = curl_easy_setopt(curl, CURLOPT_URL, filename);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
// Follow HTTP, HTTPS, FTP and FTPS redirects.
curlcode = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
// Allow no more than 8 redirections to prevent endless loops.
curlcode = curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 8);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
int timeout = curl_timeout;
if (timeout > 0) {
curlcode = curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt"
|
ast_based
|
<|fim_prefix|>t_or_null(singleton->focus);
uint32_t update_size = wd.update.size();
accesskit_node_id ac_focus = (accesskit_node_id)wd.root_id.get_id();
if (focus_ae && focus_ae->window_id == window_id) {
ac_focus = (accesskit_node_id)singleton->focus.get_id();
}
accesskit_tree_update *tree_update = (update_size > 0) ? accesskit_tree_update_with_capacity_and_focus(update_size, ac_focus) : accesskit_tree_update_with_focus(ac_focus);
for (const RID &rid : wd.update) {
AccessibilityElement *ae = singleton->rid_owner.get_or_null(rid);
if (ae && ae->node) {
for (const RID &child_rid : ae->children) {
accesskit_node_push_child(ae->node, (accesskit_node_id)child_rid.get_id());
}
accesskit_tree_update_push_node(tree_update, (accesskit_node_id)rid.get_id(), ae->node);
ae->node = nullptr;
}
}
wd.update.clear();
return tree_update;
}
void AccessibilityDriverAccessKit::accessibility_update_if_active(const Callable &p_callable) {
ERR_FAIL_COND(!p_callable.is_valid());
update_cb = p_callable;
for (KeyValue<DisplayServer::WindowID, WindowData> &window : windows) {
#ifdef WINDOWS_ENABLED
accesskit_windows_queued_events *events = accesskit_windows_subclassing_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
if (events) {
accesskit_windows_queued_events_raise(events);
}
#endif
#ifdef MACOS_ENABLED
accesskit_macos_queued_events *events = accesskit_macos_subclassing_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
if (events) {
accesskit_macos_queued_events_raise(events);
}
#endif
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
#endif
}
update_cb = Callable();
}
_FORCE_INLINE_ void AccessibilityDriverAccessKit::_ensure_node(const RID &p_id, AccessibilityElement *p_ae) {
if (unlikely(!p_ae->node)) {
WindowData *wd = <|fim_suffix|>;
ERR_FAIL_NULL(wd);
wd->update.insert(p_id);
p_ae->node = accesskit_node_new(p_ae->role);
}
}
void AccessibilityDriverAccessKit::accessibility_set_window_rect(DisplayServer::WindowID p_window_id, const Rect2 &p_rect_out, const Rect2 &p_rect_in) {
#ifdef LINUXBSD_ENABLED
const WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL(wd);
accesskit_rect outer_bounds = { p_rect_out.position.x, p_rect_out.position.y, p_rect_out.position.x + p_rect_out.size.width, p_rect_out.position.y + p_rect_out.size.height };
accesskit_rect inner_bounds = { p_rect_in.position.x, p_rect_in.position.y, p_rect_in.position.x + p_rect_in.size.width, p_rect_in.position.y + p_rect_in.size.height };
accesskit_unix_adapter_set_root_window_bounds(wd->adapter, outer_bounds, inner_bounds);
#endif
}
void AccessibilityDriverAccessKit::accessibility_set_window_focused(DisplayServer::WindowID p_window_id, bool p_focused) {
const WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL(wd);
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter_update_window_focus_state(wd->adapter, p_focused);
#endif
#ifdef MACOS_ENABLED
accesskit_macos_queued_events *events = accesskit_macos_subclassing_adapter_update_view_focus_state(wd->adapter, p_focused);
if (events != nullptr) {
accesskit_macos_queued_events_raise(events);
}
#endif
// Note: On Windows, the subclassing adapter takes care of this.
}
void AccessibilityDriverAccessKit::accessibility_update_set_role(const RID &p_id, DisplayServer::AccessibilityRole p_role) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
if (ae->role == _accessibility_role(p_role)) {
return;
}
ae->role = _accessibility_role(p_role);
_ensure_node(p_id, ae);
accesskit_node_set_role(ae->node, ae->role);
}
void AccessibilityDriverAccessKit::accessibility_update_set_name(const <|fim_middle|>windows.getptr(p_ae->window_id)
|
t_or_null(singleton->focus);
uint32_t update_size = wd.update.size();
accesskit_node_id ac_focus = (accesskit_node_id)wd.root_id.get_id();
if (focus_ae && focus_ae->window_id == window_id) {
ac_focus = (accesskit_node_id)singleton->focus.get_id();
}
accesskit_tree_update *tree_update = (update_size > 0) ? accesskit_tree_update_with_capacity_and_focus(update_size, ac_focus) : accesskit_tree_update_with_focus(ac_focus);
for (const RID &rid : wd.update) {
AccessibilityElement *ae = singleton->rid_owner.get_or_null(rid);
if (ae && ae->node) {
for (const RID &child_rid : ae->children) {
accesskit_node_push_child(ae->node, (accesskit_node_id)child_rid.get_id());
}
accesskit_tree_update_push_node(tree_update, (accesskit_node_id)rid.get_id(), ae->node);
ae->node = nullptr;
}
}
wd.update.clear();
return tree_update;
}
void AccessibilityDriverAccessKit::accessibility_update_if_active(const Callable &p_callable) {
ERR_FAIL_COND(!p_callable.is_valid());
update_cb = p_callable;
for (KeyValue<DisplayServer::WindowID, WindowData> &window : windows) {
#ifdef WINDOWS_ENABLED
accesskit_windows_queued_events *events = accesskit_windows_subclassing_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
if (events) {
accesskit_windows_queued_events_raise(events);
}
#endif
#ifdef MACOS_ENABLED
accesskit_macos_queued_events *events = accesskit_macos_subclassing_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
if (events) {
accesskit_macos_queued_events_raise(events);
}
#endif
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter_update_if_active(window.value.adapter, _accessibility_build_tree_update, (void *)(size_t)window.key);
#endif
}
update_cb = Callable();
}
_FORCE_INLINE_ void AccessibilityDriverAccessKit::_ensure_node(const RID &p_id, AccessibilityElement *p_ae) {
if (unlikely(!p_ae->node)) {
WindowData *wd =
|
windows.getptr(p_ae->window_id)
|
;
ERR_FAIL_NULL(wd);
wd->update.insert(p_id);
p_ae->node = accesskit_node_new(p_ae->role);
}
}
void AccessibilityDriverAccessKit::accessibility_set_window_rect(DisplayServer::WindowID p_window_id, const Rect2 &p_rect_out, const Rect2 &p_rect_in) {
#ifdef LINUXBSD_ENABLED
const WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL(wd);
accesskit_rect outer_bounds = { p_rect_out.position.x, p_rect_out.position.y, p_rect_out.position.x + p_rect_out.size.width, p_rect_out.position.y + p_rect_out.size.height };
accesskit_rect inner_bounds = { p_rect_in.position.x, p_rect_in.position.y, p_rect_in.position.x + p_rect_in.size.width, p_rect_in.position.y + p_rect_in.size.height };
accesskit_unix_adapter_set_root_window_bounds(wd->adapter, outer_bounds, inner_bounds);
#endif
}
void AccessibilityDriverAccessKit::accessibility_set_window_focused(DisplayServer::WindowID p_window_id, bool p_focused) {
const WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL(wd);
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter_update_window_focus_state(wd->adapter, p_focused);
#endif
#ifdef MACOS_ENABLED
accesskit_macos_queued_events *events = accesskit_macos_subclassing_adapter_update_view_focus_state(wd->adapter, p_focused);
if (events != nullptr) {
accesskit_macos_queued_events_raise(events);
}
#endif
// Note: On Windows, the subclassing adapter takes care of this.
}
void AccessibilityDriverAccessKit::accessibility_update_set_role(const RID &p_id, DisplayServer::AccessibilityRole p_role) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
if (ae->role == _accessibility_role(p_role)) {
return;
}
ae->role = _accessibility_role(p_role);
_ensure_node(p_id, ae);
accesskit_node_set_role(ae->node, ae->role);
}
void AccessibilityDriverAccessKit::accessibility_update_set_name(const
|
ast_based
|
<|fim_prefix|>while ignoring keyframes before scaling/moving.
bool inside_selection_handles_rect = !read_only && selection_handles_rect.has_point(mb->get_position());
// First, check keyframe.
// Command/Control makes it ignore the keyframe, so control point editors can be force-edited.
if (!inside_selection_handles_rect && !mb->is_command_or_control_pressed()) {
if (_try_select_at_ui_pos(mb->get_position(), mb->is_shift_pressed(), true)) {
return;
}
}
// Second, check key handles.
for (int i = 0; i < edit_points.size(); i++) {
if (!read_only) {
if (edit_points[i].in_rect.has_point(mb->get_position())) {
moving_handle = -1;
moving_handle_key = edit_points[i].key;
moving_handle_track = edit_points[i].track;
moving_handle_left = animation->bezier_track_get_key_in_handle(edit_points[i].track, edit_points[i].key);
moving_handle_right = animation->bezier_track_get_key_out_handle(edit_points[i].track, edit_points[i].key);
queue_redraw();
return;
}
if (edit_points[i].out_rect.has_point(mb->get_position())) {
moving_handle = 1;
moving_handle_key = edit_points[i].key;
moving_handle_track = edit_points[i].track;
moving_handle_left = animation->bezier_track_get_key_in_handle(edit_points[i].track, edit_points[i].key);
moving_handle_right = animation->bezier_track_get_key_out_handle(edit_points[i].track, edit_points[i].key);
queue_redraw();
return;
}
}
}
// Box scaling/movement.
if (inside_selection_handles_rect) {
const Vector2i rel_pos = mb->get_position() - selection_rect.position;
scaling_selection_handles = Vector2i();
// Check which scaling handles are available.
if (selection_rect.size.width > CMP_EPSILON) {
if (rel_pos.x <= 0) {
scaling_selection_handles.x = -1;
} else if (rel_pos.x >= selection_rect.size.width) {
scaling_selection_handles.x = 1;
}
}
if (selection_rect.size.height > CMP_EPSILON) {
if (rel_pos.y <= 0) <|fim_suffix|> else if (rel_pos.y >= selection_rect.size.height) {
scaling_selection_handles.y = 1;
}
}
if (scaling_selection_handles != Vector2i()) {
scaling_selection = true;
const float time = ((selection_rect.position.x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
const float h = (get_size().height / 2.0 - selection_rect.position.y) * timeline_v_zoom + timeline_v_scroll;
scaling_selection_pivot = Point2(time, h);
return;
}
// If not scaling, that means we're moving.
moving_selection_attempt = true;
moving_selection = false;
moving_selection_mouse_begin = mb->get_position();
// The pivot will be from the mouse click location, not a specific key.
moving_selection_from_key = -1;
moving_selection_from_track = selected_track;
moving_selection_offset = Vector2();
select_single_attempt = IntPair(-1, -1);
return;
}
// Insert new point.
if (mb->get_position().x >= limit && mb->get_position().x < get_size().width && mb->is_command_or_control_pressed()) {
float h = (get_size().height / 2.0 - mb->get_position().y) * timeline_v_zoom + timeline_v_scroll;
Array new_point = animation->make_default_bezier_key(h);
real_t time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
while (animation->track_find_key(selected_track, time, Animation::FIND_MODE_APPROX) != -1) {
time += 0.0001;
}
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Add Bezier Point"));
undo_redo->add_do_method(animation.ptr(), "bezier_track_insert_key", selected_track, time, new_point[0], Vector2(new_point[1], new_point[2]), Vector2(new_point[3], new_point[4]));
undo_redo->add_do_method(editor, "_bezier_track_set_key_handle_mode_at_time", animation.ptr(), selected_track, time, (Animation::HandleMode)editor->bezier_key_mode->get_selected_id(), Animation::HANDLE_SET_MODE_AUTO);
undo_redo->add_undo_metho<|fim_middle|>{
scaling_selection_handles.y = -1;
}
|
while ignoring keyframes before scaling/moving.
bool inside_selection_handles_rect = !read_only && selection_handles_rect.has_point(mb->get_position());
// First, check keyframe.
// Command/Control makes it ignore the keyframe, so control point editors can be force-edited.
if (!inside_selection_handles_rect && !mb->is_command_or_control_pressed()) {
if (_try_select_at_ui_pos(mb->get_position(), mb->is_shift_pressed(), true)) {
return;
}
}
// Second, check key handles.
for (int i = 0; i < edit_points.size(); i++) {
if (!read_only) {
if (edit_points[i].in_rect.has_point(mb->get_position())) {
moving_handle = -1;
moving_handle_key = edit_points[i].key;
moving_handle_track = edit_points[i].track;
moving_handle_left = animation->bezier_track_get_key_in_handle(edit_points[i].track, edit_points[i].key);
moving_handle_right = animation->bezier_track_get_key_out_handle(edit_points[i].track, edit_points[i].key);
queue_redraw();
return;
}
if (edit_points[i].out_rect.has_point(mb->get_position())) {
moving_handle = 1;
moving_handle_key = edit_points[i].key;
moving_handle_track = edit_points[i].track;
moving_handle_left = animation->bezier_track_get_key_in_handle(edit_points[i].track, edit_points[i].key);
moving_handle_right = animation->bezier_track_get_key_out_handle(edit_points[i].track, edit_points[i].key);
queue_redraw();
return;
}
}
}
// Box scaling/movement.
if (inside_selection_handles_rect) {
const Vector2i rel_pos = mb->get_position() - selection_rect.position;
scaling_selection_handles = Vector2i();
// Check which scaling handles are available.
if (selection_rect.size.width > CMP_EPSILON) {
if (rel_pos.x <= 0) {
scaling_selection_handles.x = -1;
} else if (rel_pos.x >= selection_rect.size.width) {
scaling_selection_handles.x = 1;
}
}
if (selection_rect.size.height > CMP_EPSILON) {
if (rel_pos.y <= 0)
|
{
scaling_selection_handles.y = -1;
}
|
else if (rel_pos.y >= selection_rect.size.height) {
scaling_selection_handles.y = 1;
}
}
if (scaling_selection_handles != Vector2i()) {
scaling_selection = true;
const float time = ((selection_rect.position.x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
const float h = (get_size().height / 2.0 - selection_rect.position.y) * timeline_v_zoom + timeline_v_scroll;
scaling_selection_pivot = Point2(time, h);
return;
}
// If not scaling, that means we're moving.
moving_selection_attempt = true;
moving_selection = false;
moving_selection_mouse_begin = mb->get_position();
// The pivot will be from the mouse click location, not a specific key.
moving_selection_from_key = -1;
moving_selection_from_track = selected_track;
moving_selection_offset = Vector2();
select_single_attempt = IntPair(-1, -1);
return;
}
// Insert new point.
if (mb->get_position().x >= limit && mb->get_position().x < get_size().width && mb->is_command_or_control_pressed()) {
float h = (get_size().height / 2.0 - mb->get_position().y) * timeline_v_zoom + timeline_v_scroll;
Array new_point = animation->make_default_bezier_key(h);
real_t time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
while (animation->track_find_key(selected_track, time, Animation::FIND_MODE_APPROX) != -1) {
time += 0.0001;
}
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Add Bezier Point"));
undo_redo->add_do_method(animation.ptr(), "bezier_track_insert_key", selected_track, time, new_point[0], Vector2(new_point[1], new_point[2]), Vector2(new_point[3], new_point[4]));
undo_redo->add_do_method(editor, "_bezier_track_set_key_handle_mode_at_time", animation.ptr(), selected_track, time, (Animation::HandleMode)editor->bezier_key_mode->get_selected_id(), Animation::HANDLE_SET_MODE_AUTO);
undo_redo->add_undo_metho
|
ast_based
|
<|fim_prefix|> // shape: [n_embd] (1-dimensional)
// returns NULL for invalid ids.
LLAMA_API float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i);
// Get the embeddings for a sequence id
// Returns NULL if pooling_type is LLAMA_POOLING_TYPE_NONE
// when pooling_type == LLAMA_POOLING_TYPE_RANK, returns float[n_cls_out] with the rank(s) of the sequence
// otherwise: float[n_embd] (1-dimensional)
LLAMA_API float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id);
//
// Vocab
//
LLAMA_API const char * llama_vocab_get_text(const struct llama_vocab * vocab, llama_token token);
LLAMA_API float llama_vocab_get_score(const struct llama_vocab * vocab, llama_token token);
LLAMA_API enum llama_token_attr llama_vocab_get_attr(const struct llama_vocab * vocab, llama_token token);
// Check if the token is supposed to end generation (end-of-generation, eg. EOS, EOT, etc.)
LLAMA_API bool llama_vocab_is_eog(const struct llama_vocab * vocab, llama_token token);
// Identify if Token Id is a control token or a render-able token
LLAMA_API bool llama_vocab_is_control(const struct llama_vocab * vocab, llama_token token);
// Special tokens
LLAMA_API llama_token llama_vocab_bos(const struct llama_vocab * vocab); // beginning-of-sentence
LLAMA_API llama_token llama_vocab_eos(const struct llama_vocab * vocab); // end-of-sentence
LLAMA_API llama_token llama_vocab_eot(const struct llama_vocab * vocab); // end-of-turn
LLAMA_API llama_token llama_vocab_sep(const struct llama_vocab * vocab); // sentence separator
LLAMA_API llama_token llama_vocab_nl (const struct llama_vocab * vocab); // next-line
LLAMA_API llama_token llama_vocab_pad(const struct llama_vocab * vocab); // padding
LLAMA_API llama_token llama_vocab_mask(const struct llama_vocab * vocab); // mask
<|fim_suffix|> LLAMA_API bool llama_vocab_get_add_eos(const struct llama_vocab * vocab);
LLAMA_API bool llama_vocab_get_add_sep(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_pre(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_suf(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_mid(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_pad(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_rep(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_sep(const struct llama_vocab * vocab);
DEPRECATED(LLAMA_API const char * llama_token_get_text(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_text instead");
DEPRECATED(LLAMA_API float llama_token_get_score(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_score instead");
DEPRECATED(LLAMA_API enum llama_token_attr llama_token_get_attr(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_attr instead");
DEPRECATED(LLAMA_API bool llama_token_is_eog(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_eog instead");
DEPRECATED(LLAMA_API bool llama_token_is_control(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_control instead");
DEPRECATED(LLAMA_API llama_token llama_token_bos(const struct llama_vocab * vocab), "use llama_vocab_bos instead");
DEPRECATED(LLAMA_API llama_token llama_token_eos(const struct llama_vocab * vocab), "use llama_vocab_eos instead");
DEPRECATED(LLAMA_API llama_token llama_token_eot(const struct llama_vocab * vocab), "use llama_vocab_eot instead");
DEPRECATED(LLAMA_API llama_token llama_token_cls(const struct llama_vocab * vocab), "use llama_vocab_cls instead");
DEPRECATED(LLAMA_API llama_token llama_token_sep(const struct llama_vocab * vocab), "use llama_vocab_sep instead");<|fim_middle|> LLAMA_API bool llama_vocab_get_add_bos(const struct llama_vocab * vocab);
|
// shape: [n_embd] (1-dimensional)
// returns NULL for invalid ids.
LLAMA_API float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i);
// Get the embeddings for a sequence id
// Returns NULL if pooling_type is LLAMA_POOLING_TYPE_NONE
// when pooling_type == LLAMA_POOLING_TYPE_RANK, returns float[n_cls_out] with the rank(s) of the sequence
// otherwise: float[n_embd] (1-dimensional)
LLAMA_API float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id);
//
// Vocab
//
LLAMA_API const char * llama_vocab_get_text(const struct llama_vocab * vocab, llama_token token);
LLAMA_API float llama_vocab_get_score(const struct llama_vocab * vocab, llama_token token);
LLAMA_API enum llama_token_attr llama_vocab_get_attr(const struct llama_vocab * vocab, llama_token token);
// Check if the token is supposed to end generation (end-of-generation, eg. EOS, EOT, etc.)
LLAMA_API bool llama_vocab_is_eog(const struct llama_vocab * vocab, llama_token token);
// Identify if Token Id is a control token or a render-able token
LLAMA_API bool llama_vocab_is_control(const struct llama_vocab * vocab, llama_token token);
// Special tokens
LLAMA_API llama_token llama_vocab_bos(const struct llama_vocab * vocab); // beginning-of-sentence
LLAMA_API llama_token llama_vocab_eos(const struct llama_vocab * vocab); // end-of-sentence
LLAMA_API llama_token llama_vocab_eot(const struct llama_vocab * vocab); // end-of-turn
LLAMA_API llama_token llama_vocab_sep(const struct llama_vocab * vocab); // sentence separator
LLAMA_API llama_token llama_vocab_nl (const struct llama_vocab * vocab); // next-line
LLAMA_API llama_token llama_vocab_pad(const struct llama_vocab * vocab); // padding
LLAMA_API llama_token llama_vocab_mask(const struct llama_vocab * vocab); // mask
|
LLAMA_API bool llama_vocab_get_add_bos(const struct llama_vocab * vocab);
|
LLAMA_API bool llama_vocab_get_add_eos(const struct llama_vocab * vocab);
LLAMA_API bool llama_vocab_get_add_sep(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_pre(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_suf(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_mid(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_pad(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_rep(const struct llama_vocab * vocab);
LLAMA_API llama_token llama_vocab_fim_sep(const struct llama_vocab * vocab);
DEPRECATED(LLAMA_API const char * llama_token_get_text(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_text instead");
DEPRECATED(LLAMA_API float llama_token_get_score(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_score instead");
DEPRECATED(LLAMA_API enum llama_token_attr llama_token_get_attr(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_attr instead");
DEPRECATED(LLAMA_API bool llama_token_is_eog(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_eog instead");
DEPRECATED(LLAMA_API bool llama_token_is_control(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_control instead");
DEPRECATED(LLAMA_API llama_token llama_token_bos(const struct llama_vocab * vocab), "use llama_vocab_bos instead");
DEPRECATED(LLAMA_API llama_token llama_token_eos(const struct llama_vocab * vocab), "use llama_vocab_eos instead");
DEPRECATED(LLAMA_API llama_token llama_token_eot(const struct llama_vocab * vocab), "use llama_vocab_eot instead");
DEPRECATED(LLAMA_API llama_token llama_token_cls(const struct llama_vocab * vocab), "use llama_vocab_cls instead");
DEPRECATED(LLAMA_API llama_token llama_token_sep(const struct llama_vocab * vocab), "use llama_vocab_sep instead");
|
random
|
<|fim_prefix|> draw_string(font, ep.point_rect.position + Vector2(8, -font->get_height(font_size) - 8), TTR("Time:") + " " + TS->format_number(rtos(Math::snapped(offset, 0.0001))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, accent);
draw_string(font, ep.point_rect.position + Vector2(8, -8), TTR("Value:") + " " + TS->format_number(rtos(Math::snapped(value, 0.001))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, accent);
} else {
Color track_color = Color(1, 1, 1, 1);
if (i != selected_track) {
track_color = subtrack_colors[i];
}
draw_texture(bezier_icon, ep.point_rect.position, track_color);
}
ep.point_rect = ep.point_rect.grow(ep.point_rect.size.width * 0.5);
}
ep.point_rect = ep.point_rect.grow(ep.point_rect.size.width * 0.5);
if (i == selected_track || is_selected) {
if (animation->bezier_track_get_key_handle_mode(i, j) != Animation::HANDLE_MODE_LINEAR) {
if (pos_in.x >= limit && pos_in.x <= right_limit) {
ep.in_rect.position = (pos_in - bezier_handle_icon->get_size() / 2.0).floor();
ep.in_rect.size = bezier_handle_icon->get_size();
draw_texture(bezier_handle_icon, ep.in_rect.position);
ep.in_rect = ep.in_rect.grow(ep.in_rect.size.width * 0.5);
}
if (pos_out.x >= limit && pos_out.x <= right_limit) {
ep.out_rect.position = (pos_out - bezier_handle_icon->get_size() / 2.0).floor();
ep.out_rect.size = bezier_handle_icon->get_size();
draw_texture(bezier_handle_icon, ep.out_rect.position);
ep.out_rect = ep.out_rect.grow(ep.out_rect.size.width * 0.5);
}
}
}
if (!locked_tracks.has(i)) {
edit_points.push_back(ep);
}
}
}
for (int i = 0; i < edit_points.size(); ++i) {
if (edit_points[i].track == selected_track) {
EditPoint ep = edit_points[i];
edit_points.remove_at(i);<|fim_suffix|> selection_handles_rect = Rect2();
// Draw scale handles.
if (draw_selection_handles) {
selection_rect.position = selected_pos[0];
selected_pos.remove_at(0);
for (const Point2 &pos : selected_pos) {
selection_rect = selection_rect.expand(pos);
}
const int outer_ofs = Math::round(12 * EDSCALE);
const int inner_ofs = Math::round(outer_ofs / 2.0);
// Draw horizontal handles.
if (selection_rect.size.height > CMP_EPSILON) {
_draw_line_clipped(selection_rect.position - Vector2(inner_ofs, inner_ofs), selection_rect.position + Vector2(selection_rect.size.width + inner_ofs, -inner_ofs), accent, limit, right_limit);
_draw_line_clipped(selection_rect.position + Vector2(-inner_ofs, selection_rect.size.height + inner_ofs), selection_rect.position + selection_rect.size + Vector2(inner_ofs, inner_ofs), accent, limit, right_limit);
}
// Draw vertical handles.
if (selection_rect.size.width > CMP_EPSILON) {
_draw_line_clipped(selection_rect.position - Vector2(inner_ofs, inner_ofs), selection_rect.position + Vector2(-inner_ofs, selection_rect.size.height + inner_ofs), accent, limit, right_limit);
_draw_line_clipped(selection_rect.position + Vector2(selection_rect.size.width + inner_ofs, -inner_ofs), selection_rect.position + selection_rect.size + Vector2(inner_ofs, inner_ofs), accent, limit, right_limit);
}
selection_handles_rect.position = selection_rect.position - Vector2(outer_ofs, outer_ofs);
selection_handles_rect.size = selection_rect.size + Vector2(outer_ofs, outer_ofs) * 2;
}
if (box_selecting) {
Vector2 bs_from = box_selection_from;
Vector2 bs_to = box_selection_to;
if (bs_from.x > bs_to.x) {
SWAP(bs_from.x, bs_to.x);
}
if (bs_from.y > bs_to.y) {
SWAP(bs_from.y, bs_to.y);
}
draw_rect(
Rect2(bs_from, bs_to - bs_from),
get_theme_color(SNAME("box_selection_fill_color"), EditorStringName(Editor)));
draw_rect(<|fim_middle|> edit_points.insert(0, ep);
}
}
}
selection_rect = Rect2();
|
draw_string(font, ep.point_rect.position + Vector2(8, -font->get_height(font_size) - 8), TTR("Time:") + " " + TS->format_number(rtos(Math::snapped(offset, 0.0001))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, accent);
draw_string(font, ep.point_rect.position + Vector2(8, -8), TTR("Value:") + " " + TS->format_number(rtos(Math::snapped(value, 0.001))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, accent);
} else {
Color track_color = Color(1, 1, 1, 1);
if (i != selected_track) {
track_color = subtrack_colors[i];
}
draw_texture(bezier_icon, ep.point_rect.position, track_color);
}
ep.point_rect = ep.point_rect.grow(ep.point_rect.size.width * 0.5);
}
ep.point_rect = ep.point_rect.grow(ep.point_rect.size.width * 0.5);
if (i == selected_track || is_selected) {
if (animation->bezier_track_get_key_handle_mode(i, j) != Animation::HANDLE_MODE_LINEAR) {
if (pos_in.x >= limit && pos_in.x <= right_limit) {
ep.in_rect.position = (pos_in - bezier_handle_icon->get_size() / 2.0).floor();
ep.in_rect.size = bezier_handle_icon->get_size();
draw_texture(bezier_handle_icon, ep.in_rect.position);
ep.in_rect = ep.in_rect.grow(ep.in_rect.size.width * 0.5);
}
if (pos_out.x >= limit && pos_out.x <= right_limit) {
ep.out_rect.position = (pos_out - bezier_handle_icon->get_size() / 2.0).floor();
ep.out_rect.size = bezier_handle_icon->get_size();
draw_texture(bezier_handle_icon, ep.out_rect.position);
ep.out_rect = ep.out_rect.grow(ep.out_rect.size.width * 0.5);
}
}
}
if (!locked_tracks.has(i)) {
edit_points.push_back(ep);
}
}
}
for (int i = 0; i < edit_points.size(); ++i) {
if (edit_points[i].track == selected_track) {
EditPoint ep = edit_points[i];
edit_points.remove_at(i);
|
edit_points.insert(0, ep);
}
}
}
selection_rect = Rect2();
|
selection_handles_rect = Rect2();
// Draw scale handles.
if (draw_selection_handles) {
selection_rect.position = selected_pos[0];
selected_pos.remove_at(0);
for (const Point2 &pos : selected_pos) {
selection_rect = selection_rect.expand(pos);
}
const int outer_ofs = Math::round(12 * EDSCALE);
const int inner_ofs = Math::round(outer_ofs / 2.0);
// Draw horizontal handles.
if (selection_rect.size.height > CMP_EPSILON) {
_draw_line_clipped(selection_rect.position - Vector2(inner_ofs, inner_ofs), selection_rect.position + Vector2(selection_rect.size.width + inner_ofs, -inner_ofs), accent, limit, right_limit);
_draw_line_clipped(selection_rect.position + Vector2(-inner_ofs, selection_rect.size.height + inner_ofs), selection_rect.position + selection_rect.size + Vector2(inner_ofs, inner_ofs), accent, limit, right_limit);
}
// Draw vertical handles.
if (selection_rect.size.width > CMP_EPSILON) {
_draw_line_clipped(selection_rect.position - Vector2(inner_ofs, inner_ofs), selection_rect.position + Vector2(-inner_ofs, selection_rect.size.height + inner_ofs), accent, limit, right_limit);
_draw_line_clipped(selection_rect.position + Vector2(selection_rect.size.width + inner_ofs, -inner_ofs), selection_rect.position + selection_rect.size + Vector2(inner_ofs, inner_ofs), accent, limit, right_limit);
}
selection_handles_rect.position = selection_rect.position - Vector2(outer_ofs, outer_ofs);
selection_handles_rect.size = selection_rect.size + Vector2(outer_ofs, outer_ofs) * 2;
}
if (box_selecting) {
Vector2 bs_from = box_selection_from;
Vector2 bs_to = box_selection_to;
if (bs_from.x > bs_to.x) {
SWAP(bs_from.x, bs_to.x);
}
if (bs_from.y > bs_to.y) {
SWAP(bs_from.y, bs_to.y);
}
draw_rect(
Rect2(bs_from, bs_to - bs_from),
get_theme_color(SNAME("box_selection_fill_color"), EditorStringName(Editor)));
draw_rect(
|
random
|
<|fim_prefix|> int32_t * ptr = (int32_t *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
return *ptr;
}
static void print_row(struct ggml_tensor * probs, int i) {
for (int k = 0; k < probs->ne[0]; ++k) {
float p = get_f32_2d(probs, k, i);
LOG(" %f", p);
}
LOG("\n");
}
static void print_matrix(struct ggml_tensor * probs) {
assert(ggml_is_matrix(probs));
for (int i = 0; i < probs->ne[1]; ++i) {
for (int k = 0; k < probs->ne[0]; ++k) {
float p = get_f32_2d(probs, k, i);
LOG(" %.2f", p);
}
LOG("\n");
}
}
struct my_llama_file {
// use FILE * so we don't have to re-open the file to mmap
FILE * fp;
size_t size;
my_llama_file(const char * fname, const char * mode) {
fp = std::fopen(fname, mode);
if (fp == NULL) {
size = 0;
} else {
seek(0, SEEK_END);
size = tell();
seek(0, SEEK_SET);
}
}
size_t tell() const {
#ifdef _WIN32
__int64 ret = _ftelli64(fp);
#else
long ret = std::ftell(fp);
#endif
GGML_ASSERT(ret != -1); // this really shouldn't fail
return (size_t) ret;
}
void seek(size_t offset, int whence) {
#ifdef _WIN32
int ret = _fseeki64(fp, (__int64) offset, whence);
#else
int ret = std::fseek(fp, (long) offset, whence);
#endif
GGML_ASSERT(ret == 0); // same
}
void read_raw(void * ptr, size_t size) {
if (size == 0) {
return;
}
errno = 0;
std::size_t ret = std::fread(ptr, size, 1, fp);
if (ferror(fp)) {
die_fmt("fread failed: %s", strerror(errno));
}
if (ret != 1) {
die("unexpectedly reached end of file");
}
}
std::uint32_t read_u32() {
std::uint32_t ret;
read_raw(&ret, sizeof(ret));
return ret;
}
std::float_t read_f32() {<|fim_suffix|> std::vector<char> chars(len);
read_raw(chars.data(), len);
return std::string(chars.data(), len);
}
~my_llama_file() {
if (fp) {
std::fclose(fp);
}
}
};
static bool is_ggml_file(const char * filename) {
my_llama_file file(filename, "rb");
if (file.size < 4) {
return false;
}
std::string magic = file.read_string(4);
return magic == GGUF_MAGIC;
}
static std::string llama_escape_whitespaces(const std::string & text) {
std::ostringstream out;
for (char c : text) {
if (c == ' ') out << "\xe2\x96\x81";
else out << c;
}
return out.str();
}
static void load_vocab(const char * filename, const Config * config, struct my_llama_vocab * vocab) {
if (is_ggml_file(filename)) {
LOG_INF("%s: Loading vocabulary from gguf file %s\n", __func__, filename);
struct ggml_context * ctx_data = NULL;
struct gguf_init_params params = {
/*.no_alloc = */ false,
/*.ctx = */ &ctx_data,
};
struct gguf_context * ctx = gguf_init_from_file(filename, params);
GGML_ASSERT(ctx != NULL);
const int model_idx = gguf_find_key(ctx, KV_TOKENIZER_MODEL);
GGML_ASSERT(model_idx >= 0);
std::string tokenizer_name = gguf_get_val_str(ctx, model_idx);
GGML_ASSERT(tokenizer_name == TOKENIZER_NAME);
const int token_idx = gguf_find_key(ctx, KV_TOKENIZER_LIST);
GGML_ASSERT(token_idx >= 0);
const int score_idx = gguf_find_key(ctx, KV_TOKENIZER_SCORES);
GGML_ASSERT(score_idx >= 0);
const float * scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
const int toktype_idx = gguf_find_key(ctx, KV_TOKENIZER_TOKEN_TYPE);
GGML_ASSERT(toktype_idx >= 0);
const int * toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);<|fim_middle|> std::float_t ret;
read_raw(&ret, sizeof(ret));
return ret;
}
std::string read_string(std::uint32_t len) {
|
int32_t * ptr = (int32_t *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
return *ptr;
}
static void print_row(struct ggml_tensor * probs, int i) {
for (int k = 0; k < probs->ne[0]; ++k) {
float p = get_f32_2d(probs, k, i);
LOG(" %f", p);
}
LOG("\n");
}
static void print_matrix(struct ggml_tensor * probs) {
assert(ggml_is_matrix(probs));
for (int i = 0; i < probs->ne[1]; ++i) {
for (int k = 0; k < probs->ne[0]; ++k) {
float p = get_f32_2d(probs, k, i);
LOG(" %.2f", p);
}
LOG("\n");
}
}
struct my_llama_file {
// use FILE * so we don't have to re-open the file to mmap
FILE * fp;
size_t size;
my_llama_file(const char * fname, const char * mode) {
fp = std::fopen(fname, mode);
if (fp == NULL) {
size = 0;
} else {
seek(0, SEEK_END);
size = tell();
seek(0, SEEK_SET);
}
}
size_t tell() const {
#ifdef _WIN32
__int64 ret = _ftelli64(fp);
#else
long ret = std::ftell(fp);
#endif
GGML_ASSERT(ret != -1); // this really shouldn't fail
return (size_t) ret;
}
void seek(size_t offset, int whence) {
#ifdef _WIN32
int ret = _fseeki64(fp, (__int64) offset, whence);
#else
int ret = std::fseek(fp, (long) offset, whence);
#endif
GGML_ASSERT(ret == 0); // same
}
void read_raw(void * ptr, size_t size) {
if (size == 0) {
return;
}
errno = 0;
std::size_t ret = std::fread(ptr, size, 1, fp);
if (ferror(fp)) {
die_fmt("fread failed: %s", strerror(errno));
}
if (ret != 1) {
die("unexpectedly reached end of file");
}
}
std::uint32_t read_u32() {
std::uint32_t ret;
read_raw(&ret, sizeof(ret));
return ret;
}
std::float_t read_f32() {
|
std::float_t ret;
read_raw(&ret, sizeof(ret));
return ret;
}
std::string read_string(std::uint32_t len) {
|
std::vector<char> chars(len);
read_raw(chars.data(), len);
return std::string(chars.data(), len);
}
~my_llama_file() {
if (fp) {
std::fclose(fp);
}
}
};
static bool is_ggml_file(const char * filename) {
my_llama_file file(filename, "rb");
if (file.size < 4) {
return false;
}
std::string magic = file.read_string(4);
return magic == GGUF_MAGIC;
}
static std::string llama_escape_whitespaces(const std::string & text) {
std::ostringstream out;
for (char c : text) {
if (c == ' ') out << "\xe2\x96\x81";
else out << c;
}
return out.str();
}
static void load_vocab(const char * filename, const Config * config, struct my_llama_vocab * vocab) {
if (is_ggml_file(filename)) {
LOG_INF("%s: Loading vocabulary from gguf file %s\n", __func__, filename);
struct ggml_context * ctx_data = NULL;
struct gguf_init_params params = {
/*.no_alloc = */ false,
/*.ctx = */ &ctx_data,
};
struct gguf_context * ctx = gguf_init_from_file(filename, params);
GGML_ASSERT(ctx != NULL);
const int model_idx = gguf_find_key(ctx, KV_TOKENIZER_MODEL);
GGML_ASSERT(model_idx >= 0);
std::string tokenizer_name = gguf_get_val_str(ctx, model_idx);
GGML_ASSERT(tokenizer_name == TOKENIZER_NAME);
const int token_idx = gguf_find_key(ctx, KV_TOKENIZER_LIST);
GGML_ASSERT(token_idx >= 0);
const int score_idx = gguf_find_key(ctx, KV_TOKENIZER_SCORES);
GGML_ASSERT(score_idx >= 0);
const float * scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
const int toktype_idx = gguf_find_key(ctx, KV_TOKENIZER_TOKEN_TYPE);
GGML_ASSERT(toktype_idx >= 0);
const int * toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
|
random
|
<|fim_prefix|> for(int l = 0; l < (*it).size[0]; l++) {
int i = (int)((*it).at<float>(l, 0) / xGridStep);
int j = (int)((*it).at<float>(l, 1) / yGridStep);
pointsInCell[i*gridSize + j]++;
}
cv::Mat mean, stdDev;
cv::meanStdDev(pointsInCell, mean, stdDev);
return mean.at<double>(0) / (stdDev.at<double>(0) + 1e-7);
}
calib::calibController::calibController()
{
mCalibFlags = 0;
}
calib::calibController::calibController(cv::Ptr<calib::calibrationData> data, int initialFlags, bool autoTuning, int minFramesNum) :
mCalibData(data)
{
mCalibFlags = initialFlags;
mNeedTuning = autoTuning;
mMinFramesNum = minFramesNum;
mConfIntervalsState = false;
mCoverageQualityState = false;
}
void calib::calibController::updateState()
{
if(mCalibData->cameraMatrix.total()) {
const double relErrEps = 0.05;
bool fConfState = false, cConfState = false, dConfState = true;
if(sigmaMult*mCalibData->stdDeviations.at<double>(0) / mCalibData->cameraMatrix.at<double>(0,0) < relErrEps &&
sigmaMult*mCalibData->stdDeviations.at<double>(1) / mCalibData->cameraMatrix.at<double>(1,1) < relErrEps)
fConfState = true;
if(sigmaMult*mCalibData->stdDeviations.at<double>(2) / mCalibData->cameraMatrix.at<double>(0,2) < relErrEps &&
sigmaMult*mCalibData->stdDeviations.at<double>(3) / mCalibData->cameraMatrix.at<double>(1,2) < relErrEps)
cConfState = true;
for(int i = 0; i < 5; i++)
if(mCalibData->stdDeviations.at<double>(4+i) / fabs(mCalibData->distCoeffs.at<double>(i)) > 1)
dConfState = false;
mConfIntervalsState = fConfState && cConfState && dConfState;
}
if(getFramesNumberState())
mCoverageQualityState = estimateCoverageQuality() > 1.8 ? true : false;
<|fim_suffix|> mCalibFlags |= cv::CALIB_FIX_ASPECT_RATIO;
mCalibData->cameraMatrix.at<double>(0,0) =
mCalibData->cameraMatrix.at<double>(1,1);
}
}
if(!(mCalibFlags & cv::CALIB_ZERO_TANGENT_DIST)) {
const double eps = 0.005;
if(fabs(mCalibData->distCoeffs.at<double>(2)) < eps &&
fabs(mCalibData->distCoeffs.at<double>(3)) < eps)
mCalibFlags |= cv::CALIB_ZERO_TANGENT_DIST;
}
if(!(mCalibFlags & cv::CALIB_FIX_K1)) {
const double eps = 0.005;
if(fabs(mCalibData->distCoeffs.at<double>(0)) < eps)
mCalibFlags |= cv::CALIB_FIX_K1;
}
if(!(mCalibFlags & cv::CALIB_FIX_K2)) {
const double eps = 0.005;
if(fabs(mCalibData->distCoeffs.at<double>(1)) < eps)
mCalibFlags |= cv::CALIB_FIX_K2;
}
if(!(mCalibFlags & cv::CALIB_FIX_K3)) {
const double eps = 0.005;
if(fabs(mCalibData->distCoeffs.at<double>(4)) < eps)
mCalibFlags |= cv::CALIB_FIX_K3;
}
}
}
bool calib::calibController::getCommonCalibrationState() const
{
int rating = (int)getFramesNumberState() + (int)getConfidenceIntrervalsState() +
(int)getRMSState() + (int)mCoverageQualityState;
return rating == 4;
}
bool calib::calibController::getFramesNumberState() const
{
return std::max(mCalibData->imagePoints.size(), mCalibData->allCharucoCorners.size()) > mMinFramesNum;
}
bool calib::calibController::getConfidenceIntrervalsState() const
{
return mConfIntervalsState;
}
bool calib::calibController::getRMSState() const
{
return mCalibData->totalAvgErr < 0.5;
}
int calib::calibController::getNewFlags() const
{
return mCalibFlags;
}
//////////////////// calibDataController
double calib::calibDataController::estimateGridSubsetQuality(size_t excludedIndex)
{
{<|fim_middle|> if (getFramesNumberState() && mNeedTuning) {
if( !(mCalibFlags & cv::CALIB_FIX_ASPECT_RATIO) &&
mCalibData->cameraMatrix.total()) {
double fDiff = fabs(mCalibData->cameraMatrix.at<double>(0,0) -
mCalibData->cameraMatrix.at<double>(1,1));
if (fDiff < 3*mCalibData->stdDeviations.at<double>(0) &&
fDiff < 3*mCalibData->stdDeviations.at<double>(1)) {
|
for(int l = 0; l < (*it).size[0]; l++) {
int i = (int)((*it).at<float>(l, 0) / xGridStep);
int j = (int)((*it).at<float>(l, 1) / yGridStep);
pointsInCell[i*gridSize + j]++;
}
cv::Mat mean, stdDev;
cv::meanStdDev(pointsInCell, mean, stdDev);
return mean.at<double>(0) / (stdDev.at<double>(0) + 1e-7);
}
calib::calibController::calibController()
{
mCalibFlags = 0;
}
calib::calibController::calibController(cv::Ptr<calib::calibrationData> data, int initialFlags, bool autoTuning, int minFramesNum) :
mCalibData(data)
{
mCalibFlags = initialFlags;
mNeedTuning = autoTuning;
mMinFramesNum = minFramesNum;
mConfIntervalsState = false;
mCoverageQualityState = false;
}
void calib::calibController::updateState()
{
if(mCalibData->cameraMatrix.total()) {
const double relErrEps = 0.05;
bool fConfState = false, cConfState = false, dConfState = true;
if(sigmaMult*mCalibData->stdDeviations.at<double>(0) / mCalibData->cameraMatrix.at<double>(0,0) < relErrEps &&
sigmaMult*mCalibData->stdDeviations.at<double>(1) / mCalibData->cameraMatrix.at<double>(1,1) < relErrEps)
fConfState = true;
if(sigmaMult*mCalibData->stdDeviations.at<double>(2) / mCalibData->cameraMatrix.at<double>(0,2) < relErrEps &&
sigmaMult*mCalibData->stdDeviations.at<double>(3) / mCalibData->cameraMatrix.at<double>(1,2) < relErrEps)
cConfState = true;
for(int i = 0; i < 5; i++)
if(mCalibData->stdDeviations.at<double>(4+i) / fabs(mCalibData->distCoeffs.at<double>(i)) > 1)
dConfState = false;
mConfIntervalsState = fConfState && cConfState && dConfState;
}
if(getFramesNumberState())
mCoverageQualityState = estimateCoverageQuality() > 1.8 ? true : false;
|
if (getFramesNumberState() && mNeedTuning) {
if( !(mCalibFlags & cv::CALIB_FIX_ASPECT_RATIO) &&
mCalibData->cameraMatrix.total()) {
double fDiff = fabs(mCalibData->cameraMatrix.at<double>(0,0) -
mCalibData->cameraMatrix.at<double>(1,1));
if (fDiff < 3*mCalibData->stdDeviations.at<double>(0) &&
fDiff < 3*mCalibData->stdDeviations.at<double>(1)) {
|
mCalibFlags |= cv::CALIB_FIX_ASPECT_RATIO;
mCalibData->cameraMatrix.at<double>(0,0) =
mCalibData->cameraMatrix.at<double>(1,1);
}
}
if(!(mCalibFlags & cv::CALIB_ZERO_TANGENT_DIST)) {
const double eps = 0.005;
if(fabs(mCalibData->distCoeffs.at<double>(2)) < eps &&
fabs(mCalibData->distCoeffs.at<double>(3)) < eps)
mCalibFlags |= cv::CALIB_ZERO_TANGENT_DIST;
}
if(!(mCalibFlags & cv::CALIB_FIX_K1)) {
const double eps = 0.005;
if(fabs(mCalibData->distCoeffs.at<double>(0)) < eps)
mCalibFlags |= cv::CALIB_FIX_K1;
}
if(!(mCalibFlags & cv::CALIB_FIX_K2)) {
const double eps = 0.005;
if(fabs(mCalibData->distCoeffs.at<double>(1)) < eps)
mCalibFlags |= cv::CALIB_FIX_K2;
}
if(!(mCalibFlags & cv::CALIB_FIX_K3)) {
const double eps = 0.005;
if(fabs(mCalibData->distCoeffs.at<double>(4)) < eps)
mCalibFlags |= cv::CALIB_FIX_K3;
}
}
}
bool calib::calibController::getCommonCalibrationState() const
{
int rating = (int)getFramesNumberState() + (int)getConfidenceIntrervalsState() +
(int)getRMSState() + (int)mCoverageQualityState;
return rating == 4;
}
bool calib::calibController::getFramesNumberState() const
{
return std::max(mCalibData->imagePoints.size(), mCalibData->allCharucoCorners.size()) > mMinFramesNum;
}
bool calib::calibController::getConfidenceIntrervalsState() const
{
return mConfIntervalsState;
}
bool calib::calibController::getRMSState() const
{
return mCalibData->totalAvgErr < 0.5;
}
int calib::calibController::getNewFlags() const
{
return mCalibFlags;
}
//////////////////// calibDataController
double calib::calibDataController::estimateGridSubsetQuality(size_t excludedIndex)
{
{
|
random
|
<|fim_prefix|> Point2 moving_selection_mouse_begin;
IntPair select_single_attempt;
bool moving_selection = false;
int moving_selection_from_key = 0;
int moving_selection_from_track = 0;
Vector2 moving_selection_offset;
bool box_selecting_attempt = false;
bool box_selecting = false;
bool box_selecting_add = false;
Vector2 box_selection_from;
Vector2 box_selection_to;
Rect2 selection_rect;
Rect2 selection_handles_rect;
bool scaling_selection = false;
Vector2i scaling_selection_handles;
Vector2 scaling_selection_scale = Vector2(1, 1);
Vector2 scaling_selection_offset;
Point2 scaling_selection_pivot;
int moving_handle = 0; //0 no move -1 or +1 out, 2 both (drawing only)
int moving_handle_key = 0;
int moving_handle_track = 0;
Vector2 moving_handle_left;
Vector2 moving_handle_right;
int moving_handle_mode = 0; // value from Animation::HandleMode
struct PairHasher {
static _FORCE_INLINE_ uint32_t hash(const Pair<int, int> &p_value) {
int32_t hash = 23;
hash = hash * 31 * hash_one_uint64(p_value.first);
hash = hash * 31 * hash_one_uint64(p_value.second);
return hash;
}
};
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_lefts;
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_rights;
void _clear_selection();
void _clear_selection_for_anim(const Ref<Animation> &p_anim);
void _select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single);
bool _try_select_at_ui_pos(const Point2 &p_pos, bool p_aggregate, bool p_deselectable);
void _change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto = false);
Vector2 menu_insert_key;
struct AnimMoveRestore {
int track = 0;
double time = 0;
Variant key;
real_t transition = 0;
};
AnimationTrackEditor *editor = nullptr;
struct EditPoint {
Rect2 point_rect;
Rect2 in_rect;
Rect2 out_rect;
int track = 0;
int key = 0;
};
Vector<EditPoint> edit_points;
struct PairCompare {
bool operator()(<|fim_suffix|>, const IntPair &rh) {
if (lh.first == rh.first) {
return lh.second < rh.second;
} else {
return lh.first < rh.first;
}
}
};
typedef RBSet<IntPair, PairCompare> SelectionSet;
SelectionSet selection;
Ref<ViewPanner> panner;
void _pan_callback(Vector2 p_scroll_vec, Ref<InputEvent> p_event);
void _zoom_callback(float p_zoom_factor, Vector2 p_origin, Ref<InputEvent> p_event);
void _draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right);
void _draw_track(int p_track, const Color &p_color);
float _bezier_h_to_pixel(float p_h);
void _zoom_vertically(real_t p_minimum_value, real_t p_maximum_value);
protected:
static void _bind_methods();
void _notification(int p_what);
public:
static float get_bezier_key_value(Array p_bezier_key_array);
virtual String get_tooltip(const Point2 &p_pos) const override;
Ref<Animation> get_animation() const;
void set_animation_and_track(const Ref<Animation> &p_animation, int p_track, bool p_read_only);
virtual Size2 get_minimum_size() const override;
virtual CursorShape get_cursor_shape(const Point2 &p_pos) const override;
void set_timeline(AnimationTimelineEdit *p_timeline);
void set_editor(AnimationTrackEditor *p_editor);
void set_root(Node *p_root);
void set_filtered(bool p_filtered);
void auto_fit_vertically();
void set_play_position(real_t p_pos);
void update_play_position();
void duplicate_selected_keys(real_t p_ofs, bool p_ofs_valid);
void copy_selected_keys(bool p_cut);
void paste_keys(real_t p_ofs, bool p_ofs_valid);
void delete_selection();
void _bezier_track_insert_key_at_anim(const Ref<Animation> &p_anim, int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const Animation::HandleMode p_handle_mode, Animation::HandleSetMode p_handle_set_mode = Animation::HANDLE_SET_MODE_NONE);
AnimationBezierTrackEdit();
};
<|fim_middle|>const IntPair &lh
|
Point2 moving_selection_mouse_begin;
IntPair select_single_attempt;
bool moving_selection = false;
int moving_selection_from_key = 0;
int moving_selection_from_track = 0;
Vector2 moving_selection_offset;
bool box_selecting_attempt = false;
bool box_selecting = false;
bool box_selecting_add = false;
Vector2 box_selection_from;
Vector2 box_selection_to;
Rect2 selection_rect;
Rect2 selection_handles_rect;
bool scaling_selection = false;
Vector2i scaling_selection_handles;
Vector2 scaling_selection_scale = Vector2(1, 1);
Vector2 scaling_selection_offset;
Point2 scaling_selection_pivot;
int moving_handle = 0; //0 no move -1 or +1 out, 2 both (drawing only)
int moving_handle_key = 0;
int moving_handle_track = 0;
Vector2 moving_handle_left;
Vector2 moving_handle_right;
int moving_handle_mode = 0; // value from Animation::HandleMode
struct PairHasher {
static _FORCE_INLINE_ uint32_t hash(const Pair<int, int> &p_value) {
int32_t hash = 23;
hash = hash * 31 * hash_one_uint64(p_value.first);
hash = hash * 31 * hash_one_uint64(p_value.second);
return hash;
}
};
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_lefts;
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_rights;
void _clear_selection();
void _clear_selection_for_anim(const Ref<Animation> &p_anim);
void _select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single);
bool _try_select_at_ui_pos(const Point2 &p_pos, bool p_aggregate, bool p_deselectable);
void _change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto = false);
Vector2 menu_insert_key;
struct AnimMoveRestore {
int track = 0;
double time = 0;
Variant key;
real_t transition = 0;
};
AnimationTrackEditor *editor = nullptr;
struct EditPoint {
Rect2 point_rect;
Rect2 in_rect;
Rect2 out_rect;
int track = 0;
int key = 0;
};
Vector<EditPoint> edit_points;
struct PairCompare {
bool operator()(
|
const IntPair &lh
|
, const IntPair &rh) {
if (lh.first == rh.first) {
return lh.second < rh.second;
} else {
return lh.first < rh.first;
}
}
};
typedef RBSet<IntPair, PairCompare> SelectionSet;
SelectionSet selection;
Ref<ViewPanner> panner;
void _pan_callback(Vector2 p_scroll_vec, Ref<InputEvent> p_event);
void _zoom_callback(float p_zoom_factor, Vector2 p_origin, Ref<InputEvent> p_event);
void _draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right);
void _draw_track(int p_track, const Color &p_color);
float _bezier_h_to_pixel(float p_h);
void _zoom_vertically(real_t p_minimum_value, real_t p_maximum_value);
protected:
static void _bind_methods();
void _notification(int p_what);
public:
static float get_bezier_key_value(Array p_bezier_key_array);
virtual String get_tooltip(const Point2 &p_pos) const override;
Ref<Animation> get_animation() const;
void set_animation_and_track(const Ref<Animation> &p_animation, int p_track, bool p_read_only);
virtual Size2 get_minimum_size() const override;
virtual CursorShape get_cursor_shape(const Point2 &p_pos) const override;
void set_timeline(AnimationTimelineEdit *p_timeline);
void set_editor(AnimationTrackEditor *p_editor);
void set_root(Node *p_root);
void set_filtered(bool p_filtered);
void auto_fit_vertically();
void set_play_position(real_t p_pos);
void update_play_position();
void duplicate_selected_keys(real_t p_ofs, bool p_ofs_valid);
void copy_selected_keys(bool p_cut);
void paste_keys(real_t p_ofs, bool p_ofs_valid);
void delete_selection();
void _bezier_track_insert_key_at_anim(const Ref<Animation> &p_anim, int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const Animation::HandleMode p_handle_mode, Animation::HandleSetMode p_handle_set_mode = Animation::HANDLE_SET_MODE_NONE);
AnimationBezierTrackEdit();
};
|
ast_based
|
<|fim_prefix|>#include "ggml.h"
#include "gguf.h"
#include "arg.h"
#include "common.h"
#include "llama.h"
#include "pca.hpp"
#include "mean.hpp"
#ifdef GGML_USE_CUDA
#include "ggml-cuda.h"
#endif
#ifdef GGML_USE_METAL
#include "ggml-metal.h"
#endif
#include <algorithm>
#include <climits>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
//////////////////////////////////////////////////
// utils
template <class Iter>
static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
std::string ret;
for (; begin != end; ++begin) {
ret += common_token_to_piece(ctx, *begin);
}
return ret;
}
static void print_usage(int, char ** argv) {
printf("\nexample usage:\n");
printf("\n CPU only: %s -m ./llama-3.Q4_K_M.gguf\n", argv[0]);
printf("\n with GPU: %s -m ./llama-3.Q4_K_M.gguf -ngl 99\n", argv[0]);
printf("\n advanced: %s -m ./llama-3.Q4_K_M.gguf -ngl 99 --pca-iter 2000 --pca-batch 100\n", argv[0]);
printf("\n using mean: %s -m ./llama-3.Q4_K_M.gguf --method mean\n", argv[0]);
printf("\n");
}
<|fim_suffix|>struct callback_data {
ggml_context * ctx_ggml = nullptr; // holds v_pos, v_neg, v_diff_filtered
int n_layers = 0;
int n_tokens = 0;
bool is_eval_pos = true;
// each element of the vector correspond to one layer
std::vector<struct ggml_tensor *> v_pos; // vector of matrices of size [n_embd, n_tokens]
std::vector<struct ggml_tensor *> v_neg; // vector of matrices of size [n_embd, n_tokens]
std::vector<struct ggml_tensor *> v_diff_filtered; // vector of matrices of size [n_embd, n_nonzero_rows]. NOTE: n_nonzero_rows maybe different for each layer
// save a tensor into either v_pos or v_neg (decided by is_eval_pos)
void save_tensor_for_layer(struct ggml_tensor * t) {
GGML_ASSERT(t->type == GGML_TYPE_F32);
if (ctx_ggml == nullptr) {
// alloc a new ctx_ggml if needed
struct ggml_init_params params_ggml = {
/*.mem_size =*/ ggml_tensor_overhead() * n_layers * 3u,
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ctx_ggml = ggml_init(params_ggml);
}
// copy tensor data
auto n_bytes = ggml_nbytes(t);
struct ggml_tensor * t_layer = ggml_new_tensor_2d(ctx_ggml, t->type, t->ne[0], t->ne[1]);
t_layer->data = malloc(n_bytes); // TODO @ngxson : get rid of this malloc somehow
ggml_backend_tensor_get(t, t_layer->data, 0, n_bytes);
ggml_set_name(t_layer, ggml_get_name(t));
//print_debug_tensor(t_layer);
if (is_eval_pos) {
v_pos.push_back(t_layer);
} else {
v_neg.push_back(t_layer);
}
}
// calculate diff (v_pos - v_neg) and place the result back to v_pos
// all zero rows in the diff tensor will also be removed
// NOTE: final layer is ignored. we only have (n_layers - 1) to process
std::vector<struct ggml_tensor *> calc_diff() {
for (float il = 0; il < v_pos.size(); il++) {<|fim_middle|>//////////////////////////////////////////////////
// cb_eval is reused for each pair of positive - negative prompt
|
#include "ggml.h"
#include "gguf.h"
#include "arg.h"
#include "common.h"
#include "llama.h"
#include "pca.hpp"
#include "mean.hpp"
#ifdef GGML_USE_CUDA
#include "ggml-cuda.h"
#endif
#ifdef GGML_USE_METAL
#include "ggml-metal.h"
#endif
#include <algorithm>
#include <climits>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
//////////////////////////////////////////////////
// utils
template <class Iter>
static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
std::string ret;
for (; begin != end; ++begin) {
ret += common_token_to_piece(ctx, *begin);
}
return ret;
}
static void print_usage(int, char ** argv) {
printf("\nexample usage:\n");
printf("\n CPU only: %s -m ./llama-3.Q4_K_M.gguf\n", argv[0]);
printf("\n with GPU: %s -m ./llama-3.Q4_K_M.gguf -ngl 99\n", argv[0]);
printf("\n advanced: %s -m ./llama-3.Q4_K_M.gguf -ngl 99 --pca-iter 2000 --pca-batch 100\n", argv[0]);
printf("\n using mean: %s -m ./llama-3.Q4_K_M.gguf --method mean\n", argv[0]);
printf("\n");
}
|
//////////////////////////////////////////////////
// cb_eval is reused for each pair of positive - negative prompt
|
struct callback_data {
ggml_context * ctx_ggml = nullptr; // holds v_pos, v_neg, v_diff_filtered
int n_layers = 0;
int n_tokens = 0;
bool is_eval_pos = true;
// each element of the vector correspond to one layer
std::vector<struct ggml_tensor *> v_pos; // vector of matrices of size [n_embd, n_tokens]
std::vector<struct ggml_tensor *> v_neg; // vector of matrices of size [n_embd, n_tokens]
std::vector<struct ggml_tensor *> v_diff_filtered; // vector of matrices of size [n_embd, n_nonzero_rows]. NOTE: n_nonzero_rows maybe different for each layer
// save a tensor into either v_pos or v_neg (decided by is_eval_pos)
void save_tensor_for_layer(struct ggml_tensor * t) {
GGML_ASSERT(t->type == GGML_TYPE_F32);
if (ctx_ggml == nullptr) {
// alloc a new ctx_ggml if needed
struct ggml_init_params params_ggml = {
/*.mem_size =*/ ggml_tensor_overhead() * n_layers * 3u,
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ctx_ggml = ggml_init(params_ggml);
}
// copy tensor data
auto n_bytes = ggml_nbytes(t);
struct ggml_tensor * t_layer = ggml_new_tensor_2d(ctx_ggml, t->type, t->ne[0], t->ne[1]);
t_layer->data = malloc(n_bytes); // TODO @ngxson : get rid of this malloc somehow
ggml_backend_tensor_get(t, t_layer->data, 0, n_bytes);
ggml_set_name(t_layer, ggml_get_name(t));
//print_debug_tensor(t_layer);
if (is_eval_pos) {
v_pos.push_back(t_layer);
} else {
v_neg.push_back(t_layer);
}
}
// calculate diff (v_pos - v_neg) and place the result back to v_pos
// all zero rows in the diff tensor will also be removed
// NOTE: final layer is ignored. we only have (n_layers - 1) to process
std::vector<struct ggml_tensor *> calc_diff() {
for (float il = 0; il < v_pos.size(); il++) {
|
random
|
<|fim_prefix|>/**************************************************************************/
/* image_compress_astcenc.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */<|fim_suffix|>/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "image_compress_astcenc.h"
#include "core/os/os.h"
#include "core/string/print_string.h"
#include <astcenc.h>
#ifdef TOOLS_ENABLED
void _compress_astc(Image *r_img, Image::ASTCFormat p_format) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
if (r_img->is_compressed()) {
return; // Do not compress, already compressed.
}
const Image::Format src_format = r_img->get_format();
const bool is_hdr = src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995;
if (src_format >= Image::FORMAT_RH && src_format <= Image::FORMAT_RGBAH) {
r_img->convert(Image::FORMAT_RGBAH);
} else if (src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995) {
r_img->convert(Image::FORMAT_RGBAF);
} else {
r_img->convert(Image::FORMAT_RGBA8);
}
// Determine encoder output format from our enum.<|fim_middle|>/* distribute, sublicense, and/or sell copies of the Software, and to */
|
/**************************************************************************/
/* image_compress_astcenc.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
|
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "image_compress_astcenc.h"
#include "core/os/os.h"
#include "core/string/print_string.h"
#include <astcenc.h>
#ifdef TOOLS_ENABLED
void _compress_astc(Image *r_img, Image::ASTCFormat p_format) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
if (r_img->is_compressed()) {
return; // Do not compress, already compressed.
}
const Image::Format src_format = r_img->get_format();
const bool is_hdr = src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995;
if (src_format >= Image::FORMAT_RH && src_format <= Image::FORMAT_RGBAH) {
r_img->convert(Image::FORMAT_RGBAH);
} else if (src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995) {
r_img->convert(Image::FORMAT_RGBAF);
} else {
r_img->convert(Image::FORMAT_RGBA8);
}
// Determine encoder output format from our enum.
|
random
|
<|fim_prefix|>ltiple of 8.");
}
// Compress image.
astcenc_image image;
image.dim_x = src_mip_w;
image.dim_y = src_mip_h;
image.dim_z = 1;
if (r_img->get_format() == Image::FORMAT_RGBA8) {
image.data_type = ASTCENC_TYPE_U8;
} else if (r_img->get_format() == Image::FORMAT_RGBAH) {
image.data_type = ASTCENC_TYPE_F16;
} else {
image.data_type = ASTCENC_TYPE_F32;
}
image.data = (void **)(&mip_data);
// Compute the number of ASTC blocks in each dimension.
unsigned int block_count_x = (src_mip_w + block_x - 1) / block_x;
unsigned int block_count_y = (src_mip_h + block_y - 1) / block_y;
size_t comp_len = block_count_x * block_count_y * 16;
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_compress_image(context, &image, &swizzle, dest_mip_write, comp_len, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: ASTC image compression failed: %s.", astcenc_get_error_string(status)));
astcenc_compress_reset(context);
}
astcenc_context_free(context);
// Replace original image with compressed one.
r_img->set_data(width, height, has_mipmaps, target_format, dest_data);
print_verbose(vformat("astcenc: Encoding took %d ms.", OS::get_singleton()->get_ticks_msec() - start_time));
}
#endif // TOOLS_ENABLED
void _decompress_astc(Image *r_img) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
// Determine decompression parameters from image format.
const Image::Format src_format = r_img->get_format();
bool is_hdr = false;
unsigned int block_x = 0;
unsigned int block_y = 0;
switch (src_format) {
case Image::FORMAT_ASTC_4x4: {
block_x = 4;
block_y = 4;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_4x4_HDR: {
block_x = 4;
block_y = 4;
is_hdr = true;
} break;
case Image::FORMAT_ASTC_8x8: {
block_x = 8;
block_y = 8;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_8x8_HDR: {
block_x = 8;
<|fim_suffix|>
} break;
default: {
ERR_FAIL_MSG(vformat("astcenc: Cannot decompress Image with a non-ASTC format: %s.", Image::get_format_name(src_format)));
} break;
}
// Initialize astcenc.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
astcenc_config config;
const float quality = ASTCENC_PRE_MEDIUM;
const uint32_t flags = ASTCENC_FLG_DECOMPRESS_ONLY;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, flags, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context = nullptr;
const unsigned int thread_count = 1;
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const Image::Format target_format = is_hdr ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
// Decompress image.
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
const int64_t src_ofs = Image::get_image_mipmap_offset(width, height, src_format, i);
const uint8_t *mip_data = &src_data[src_ofs];
int64_t src_size;
if (i == mip_count) {
src_size = r_img->get_data_size() - src_ofs;
} else {
src_size = Image::get_image_mipmap_offset(width, height, src_format, i + 1) - src_ofs;
}
int dst_mip_w, dst_mip_h;
const int64_t dst_ofs = Image::get_image_mipmap_offset_and_dimensions(width, h<|fim_middle|>block_y = 8;
is_hdr = true;
|
ltiple of 8.");
}
// Compress image.
astcenc_image image;
image.dim_x = src_mip_w;
image.dim_y = src_mip_h;
image.dim_z = 1;
if (r_img->get_format() == Image::FORMAT_RGBA8) {
image.data_type = ASTCENC_TYPE_U8;
} else if (r_img->get_format() == Image::FORMAT_RGBAH) {
image.data_type = ASTCENC_TYPE_F16;
} else {
image.data_type = ASTCENC_TYPE_F32;
}
image.data = (void **)(&mip_data);
// Compute the number of ASTC blocks in each dimension.
unsigned int block_count_x = (src_mip_w + block_x - 1) / block_x;
unsigned int block_count_y = (src_mip_h + block_y - 1) / block_y;
size_t comp_len = block_count_x * block_count_y * 16;
const astcenc_swizzle swizzle = {
ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A
};
status = astcenc_compress_image(context, &image, &swizzle, dest_mip_write, comp_len, 0);
ERR_BREAK_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: ASTC image compression failed: %s.", astcenc_get_error_string(status)));
astcenc_compress_reset(context);
}
astcenc_context_free(context);
// Replace original image with compressed one.
r_img->set_data(width, height, has_mipmaps, target_format, dest_data);
print_verbose(vformat("astcenc: Encoding took %d ms.", OS::get_singleton()->get_ticks_msec() - start_time));
}
#endif // TOOLS_ENABLED
void _decompress_astc(Image *r_img) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
// Determine decompression parameters from image format.
const Image::Format src_format = r_img->get_format();
bool is_hdr = false;
unsigned int block_x = 0;
unsigned int block_y = 0;
switch (src_format) {
case Image::FORMAT_ASTC_4x4: {
block_x = 4;
block_y = 4;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_4x4_HDR: {
block_x = 4;
block_y = 4;
is_hdr = true;
} break;
case Image::FORMAT_ASTC_8x8: {
block_x = 8;
block_y = 8;
is_hdr = false;
} break;
case Image::FORMAT_ASTC_8x8_HDR: {
block_x = 8;
|
block_y = 8;
is_hdr = true;
|
} break;
default: {
ERR_FAIL_MSG(vformat("astcenc: Cannot decompress Image with a non-ASTC format: %s.", Image::get_format_name(src_format)));
} break;
}
// Initialize astcenc.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
astcenc_config config;
const float quality = ASTCENC_PRE_MEDIUM;
const uint32_t flags = ASTCENC_FLG_DECOMPRESS_ONLY;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, flags, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context = nullptr;
const unsigned int thread_count = 1;
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const Image::Format target_format = is_hdr ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
// Decompress image.
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
for (int i = 0; i < mip_count + 1; i++) {
const int64_t src_ofs = Image::get_image_mipmap_offset(width, height, src_format, i);
const uint8_t *mip_data = &src_data[src_ofs];
int64_t src_size;
if (i == mip_count) {
src_size = r_img->get_data_size() - src_ofs;
} else {
src_size = Image::get_image_mipmap_offset(width, height, src_format, i + 1) - src_ofs;
}
int dst_mip_w, dst_mip_h;
const int64_t dst_ofs = Image::get_image_mipmap_offset_and_dimensions(width, h
|
ast_based
|
<|fim_prefix|> for (auto & ex : buft_extra) {
if (ex == buft) {
LLAMA_LOG_WARN("%s: lora for '%s' cannot use buft '%s', fallback to CPU\n", __func__, model_tensor->name, ggml_backend_buft_name(buft));
auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
if (!cpu_dev) {
throw std::runtime_error(format("%s: no CPU backend found", __func__));
}
buft = ggml_backend_dev_buffer_type(cpu_dev);
break;
}
}
LLAMA_LOG_DEBUG("%s: lora for '%s' -> '%s'\n", __func__, model_tensor->name, ggml_backend_buft_name(buft));
ggml_context * dev_ctx = ctx_for_buft(buft);
// validate tensor shape
if (is_token_embd) {
// expect B to be non-transposed, A and B are flipped; see llm_build_inp_embd()
if (model_tensor->ne[0] != w.b->ne[1] || model_tensor->ne[1] != w.a->ne[1]) {
throw std::runtime_error("tensor '" + name + "' has incorrect shape (hint: maybe wrong base model?)");
}
} else {
if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
throw std::runtime_error("tensor '" + name + "' has incorrect shape (hint: maybe wrong base model?)");
}
if (w.a->ne[1] != w.b->ne[0]) {
throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
}
}
// save tensor to adapter
ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
ggml_set_name(tensor_a, w.a->name);
ggml_set_name(tensor_b, w.b->name);
adapter.ab_map[name] = llama_adapter_lora_weight(tensor_a, tensor_b);
}
// allocate tensors / buffers and zero
{
adapter.ctxs.reserve(ctx_map.size());
<|fim_suffix|>
for (auto & it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx_dev = it.second;
ggml_backend_buffer_ptr buf { ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft) };
if (!buf) {
throw std::runtime_error("failed to allocate buffer for lora adapter\n");
}
LLAMA_LOG_INFO("%s: %10s LoRA buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf.get()), ggml_backend_buffer_get_size(buf.get())/1024.0/1024.0);
adapter.bufs.emplace_back(std::move(buf));
}
}
// set tensor data
{
llama_file gguf_file(path_lora, "rb");
std::vector<uint8_t> read_buf;
auto set_tensor = [&](ggml_tensor * orig, ggml_tensor * dev) {
size_t offs = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), gguf_find_tensor(ctx_gguf.get(), orig->name));
size_t size = ggml_nbytes(orig);
read_buf.resize(size);
gguf_file.seek(offs, SEEK_SET);
gguf_file.read_raw(read_buf.data(), size);
ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
};
for (auto & it : adapter.ab_map) {
auto orig = ab_map[it.first];
auto dev = it.second;
set_tensor(orig.a, dev.a);
set_tensor(orig.b, dev.b);
}
}
LLAMA_LOG_INFO("%s: loaded %zu tensors from lora file\n", __func__, adapter.ab_map.size()*2);
}
llama_adapter_lora * llama_adapter_lora_init(llama_model * model, const char * path_lora) {
llama_adapter_lora * adapter = new llama_adapter_lora();
try {
llama_adapter_lora_init_impl(*model, path_lora, *adapter);
return adapter;
} catch (const std::exception & err) {
LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
delete adapter;
}
return nullptr;
}
int32_t llama_adapter_meta_val_s<|fim_middle|>adapter.bufs.reserve(ctx_map.size());
|
for (auto & ex : buft_extra) {
if (ex == buft) {
LLAMA_LOG_WARN("%s: lora for '%s' cannot use buft '%s', fallback to CPU\n", __func__, model_tensor->name, ggml_backend_buft_name(buft));
auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
if (!cpu_dev) {
throw std::runtime_error(format("%s: no CPU backend found", __func__));
}
buft = ggml_backend_dev_buffer_type(cpu_dev);
break;
}
}
LLAMA_LOG_DEBUG("%s: lora for '%s' -> '%s'\n", __func__, model_tensor->name, ggml_backend_buft_name(buft));
ggml_context * dev_ctx = ctx_for_buft(buft);
// validate tensor shape
if (is_token_embd) {
// expect B to be non-transposed, A and B are flipped; see llm_build_inp_embd()
if (model_tensor->ne[0] != w.b->ne[1] || model_tensor->ne[1] != w.a->ne[1]) {
throw std::runtime_error("tensor '" + name + "' has incorrect shape (hint: maybe wrong base model?)");
}
} else {
if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
throw std::runtime_error("tensor '" + name + "' has incorrect shape (hint: maybe wrong base model?)");
}
if (w.a->ne[1] != w.b->ne[0]) {
throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
}
}
// save tensor to adapter
ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
ggml_set_name(tensor_a, w.a->name);
ggml_set_name(tensor_b, w.b->name);
adapter.ab_map[name] = llama_adapter_lora_weight(tensor_a, tensor_b);
}
// allocate tensors / buffers and zero
{
adapter.ctxs.reserve(ctx_map.size());
|
adapter.bufs.reserve(ctx_map.size());
|
for (auto & it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx_dev = it.second;
ggml_backend_buffer_ptr buf { ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft) };
if (!buf) {
throw std::runtime_error("failed to allocate buffer for lora adapter\n");
}
LLAMA_LOG_INFO("%s: %10s LoRA buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf.get()), ggml_backend_buffer_get_size(buf.get())/1024.0/1024.0);
adapter.bufs.emplace_back(std::move(buf));
}
}
// set tensor data
{
llama_file gguf_file(path_lora, "rb");
std::vector<uint8_t> read_buf;
auto set_tensor = [&](ggml_tensor * orig, ggml_tensor * dev) {
size_t offs = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), gguf_find_tensor(ctx_gguf.get(), orig->name));
size_t size = ggml_nbytes(orig);
read_buf.resize(size);
gguf_file.seek(offs, SEEK_SET);
gguf_file.read_raw(read_buf.data(), size);
ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
};
for (auto & it : adapter.ab_map) {
auto orig = ab_map[it.first];
auto dev = it.second;
set_tensor(orig.a, dev.a);
set_tensor(orig.b, dev.b);
}
}
LLAMA_LOG_INFO("%s: loaded %zu tensors from lora file\n", __func__, adapter.ab_map.size()*2);
}
llama_adapter_lora * llama_adapter_lora_init(llama_model * model, const char * path_lora) {
llama_adapter_lora * adapter = new llama_adapter_lora();
try {
llama_adapter_lora_init_impl(*model, path_lora, *adapter);
return adapter;
} catch (const std::exception & err) {
LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
delete adapter;
}
return nullptr;
}
int32_t llama_adapter_meta_val_s
|
ast_based
|
<|fim_prefix|>();
Vector2 string_pos = Point2(ofs, vofs);
string_pos = string_pos.floor();
text_buf.draw(get_canvas_item(), string_pos, color);
vofs += h + v_separation;
track_v_scroll_max += h + v_separation;
}
}
const Color dc = get_theme_color(SNAME("font_disabled_color"), EditorStringName(Editor));
Ref<Texture2D> remove = get_editor_theme_icon(SNAME("Remove"));
float remove_hpos = limit - h_separation - remove->get_width();
Ref<Texture2D> lock = get_editor_theme_icon(SNAME("Lock"));
Ref<Texture2D> unlock = get_editor_theme_icon(SNAME("Unlock"));
float lock_hpos = remove_hpos - h_separation - lock->get_width();
Ref<Texture2D> visibility_visible = get_editor_theme_icon(SNAME("GuiVisibilityVisible"));
Ref<Texture2D> visibility_hidden = get_editor_theme_icon(SNAME("GuiVisibilityHidden"));
float visibility_hpos = lock_hpos - h_separation - visibility_visible->get_width();
Ref<Texture2D> solo = get_editor_theme_icon(SNAME("AudioBusSolo"));
float solo_hpos = visibility_hpos - h_separation - solo->get_width();
float buttons_width = remove->get_width() + lock->get_width() + visibility_visible->get_width() + solo->get_width() + h_separation * 3;
for (int i = 0; i < tracks.size(); ++i) {
// Related track titles.
int current_track = tracks[i];
String path = String(animation->track_get_path(current_track));
path = path.replace_first(base_path, "");
Color cc = color;
TextLine text_buf = TextLine(path, font, font_size);
text_buf.set_width(limit - margin - buttons_width - h_separation * 2);
Rect2 rect = Rect2(margin, vofs, solo_hpos - h_separation - solo->get_width(), text_buf.get_size().y + v_separation);
cc.a *= 0.7;
float h;
if (path.ends_with(":x")) {
h = 0;
} else if (path.ends_with(":y")) {
h = 0.33f;
} else if (path.ends_with(":z")) {
h = 0.66f;
} else {
uint32_t hash = path.hash();
<|fim_suffix|>;
hash = ((hash >> 16) ^ hash) * 0x45d9f3b;
hash = (hash >> 16) ^ hash;
h = (hash % 65535) / 65536.0;
}
if (current_track != selected_track) {
Color track_color;
if (locked_tracks.has(current_track)) {
track_color.set_hsv(h, 0, 0.4);
} else {
track_color.set_hsv(h, 0.2, 0.8);
}
track_color.a = 0.5;
draw_rect(Rect2(0, vofs, margin - h_separation, text_buf.get_size().y * 0.8), track_color);
subtrack_colors[current_track] = track_color;
subtracks[current_track] = rect;
} else {
draw_rect(rect, track_focus_color);
if (locked_tracks.has(selected_track)) {
selected_track_color.set_hsv(h, 0.0, 0.4);
} else {
selected_track_color.set_hsv(h, 0.8, 0.8);
}
}
Vector2 string_pos = Point2(margin + h_separation, vofs);
text_buf.draw(get_canvas_item(), string_pos, cc);
float icon_start_height = vofs + rect.size.y / 2.0;
Rect2 remove_rect = Rect2(remove_hpos, icon_start_height - remove->get_height() / 2.0, remove->get_width(), remove->get_height());
if (read_only) {
draw_texture(remove, remove_rect.position, dc);
} else {
draw_texture(remove, remove_rect.position);
}
Rect2 lock_rect = Rect2(lock_hpos, icon_start_height - lock->get_height() / 2.0, lock->get_width(), lock->get_height());
if (locked_tracks.has(current_track)) {
draw_texture(lock, lock_rect.position);
} else {
draw_texture(unlock, lock_rect.position);
}
Rect2 visible_rect = Rect2(visibility_hpos, icon_start_height - visibility_visible->get_height() / 2.0, visibility_visible->get_width(), visibility_visible->get_height());
if (hidden_tracks.has(current_track)) {
draw_texture(visibility_hidden, visible_rect.position);
} else {
draw_texture(visibility_visible, visible_rect.position);
}
Rect2 solo_rect = Rect2(solo_hpos, icon_start_height - solo->get_height() / 2.0, s<|fim_middle|>hash = ((hash >> 16) ^ hash) * 0x45d9f3b
|
();
Vector2 string_pos = Point2(ofs, vofs);
string_pos = string_pos.floor();
text_buf.draw(get_canvas_item(), string_pos, color);
vofs += h + v_separation;
track_v_scroll_max += h + v_separation;
}
}
const Color dc = get_theme_color(SNAME("font_disabled_color"), EditorStringName(Editor));
Ref<Texture2D> remove = get_editor_theme_icon(SNAME("Remove"));
float remove_hpos = limit - h_separation - remove->get_width();
Ref<Texture2D> lock = get_editor_theme_icon(SNAME("Lock"));
Ref<Texture2D> unlock = get_editor_theme_icon(SNAME("Unlock"));
float lock_hpos = remove_hpos - h_separation - lock->get_width();
Ref<Texture2D> visibility_visible = get_editor_theme_icon(SNAME("GuiVisibilityVisible"));
Ref<Texture2D> visibility_hidden = get_editor_theme_icon(SNAME("GuiVisibilityHidden"));
float visibility_hpos = lock_hpos - h_separation - visibility_visible->get_width();
Ref<Texture2D> solo = get_editor_theme_icon(SNAME("AudioBusSolo"));
float solo_hpos = visibility_hpos - h_separation - solo->get_width();
float buttons_width = remove->get_width() + lock->get_width() + visibility_visible->get_width() + solo->get_width() + h_separation * 3;
for (int i = 0; i < tracks.size(); ++i) {
// Related track titles.
int current_track = tracks[i];
String path = String(animation->track_get_path(current_track));
path = path.replace_first(base_path, "");
Color cc = color;
TextLine text_buf = TextLine(path, font, font_size);
text_buf.set_width(limit - margin - buttons_width - h_separation * 2);
Rect2 rect = Rect2(margin, vofs, solo_hpos - h_separation - solo->get_width(), text_buf.get_size().y + v_separation);
cc.a *= 0.7;
float h;
if (path.ends_with(":x")) {
h = 0;
} else if (path.ends_with(":y")) {
h = 0.33f;
} else if (path.ends_with(":z")) {
h = 0.66f;
} else {
uint32_t hash = path.hash();
|
hash = ((hash >> 16) ^ hash) * 0x45d9f3b
|
;
hash = ((hash >> 16) ^ hash) * 0x45d9f3b;
hash = (hash >> 16) ^ hash;
h = (hash % 65535) / 65536.0;
}
if (current_track != selected_track) {
Color track_color;
if (locked_tracks.has(current_track)) {
track_color.set_hsv(h, 0, 0.4);
} else {
track_color.set_hsv(h, 0.2, 0.8);
}
track_color.a = 0.5;
draw_rect(Rect2(0, vofs, margin - h_separation, text_buf.get_size().y * 0.8), track_color);
subtrack_colors[current_track] = track_color;
subtracks[current_track] = rect;
} else {
draw_rect(rect, track_focus_color);
if (locked_tracks.has(selected_track)) {
selected_track_color.set_hsv(h, 0.0, 0.4);
} else {
selected_track_color.set_hsv(h, 0.8, 0.8);
}
}
Vector2 string_pos = Point2(margin + h_separation, vofs);
text_buf.draw(get_canvas_item(), string_pos, cc);
float icon_start_height = vofs + rect.size.y / 2.0;
Rect2 remove_rect = Rect2(remove_hpos, icon_start_height - remove->get_height() / 2.0, remove->get_width(), remove->get_height());
if (read_only) {
draw_texture(remove, remove_rect.position, dc);
} else {
draw_texture(remove, remove_rect.position);
}
Rect2 lock_rect = Rect2(lock_hpos, icon_start_height - lock->get_height() / 2.0, lock->get_width(), lock->get_height());
if (locked_tracks.has(current_track)) {
draw_texture(lock, lock_rect.position);
} else {
draw_texture(unlock, lock_rect.position);
}
Rect2 visible_rect = Rect2(visibility_hpos, icon_start_height - visibility_visible->get_height() / 2.0, visibility_visible->get_width(), visibility_visible->get_height());
if (hidden_tracks.has(current_track)) {
draw_texture(visibility_hidden, visible_rect.position);
} else {
draw_texture(visibility_visible, visible_rect.position);
}
Rect2 solo_rect = Rect2(solo_hpos, icon_start_height - solo->get_height() / 2.0, s
|
ast_based
|
<|fim_prefix|>creenTouch> ev;
ev.instantiate();
ev->set_index(touch[i].id);
ev->set_pressed(p_pressed);
ev->set_canceled(p_canceled);
ev->set_position(touch[i].pos);
ev->set_double_tap(p_double_tap);
Input::get_singleton()->parse_input_event(ev);
}
}
}
void AndroidInputHandler::_release_all_touch() {
_parse_all_touch(false, false);
touch.clear();
}
void AndroidInputHandler::process_touch_event(int p_event, int p_pointer, const Vector<TouchPos> &p_points, bool p_double_tap) {
switch (p_event) {
case AMOTION_EVENT_ACTION_DOWN: { //gesture begin
// Release any remaining touches or mouse event
_release_mouse_event_info();
_release_all_touch();
touch.resize(p_points.size());
for (int i = 0; i < p_points.size(); i++) {
touch.write[i].id = p_points[i].id;
touch.write[i].pos = p_points[i].pos;
touch.write[i].pressure = p_points[i].pressure;
touch.write[i].tilt = p_points[i].tilt;
}
//send touch
_parse_all_touch(true, false, p_double_tap);
} break;
case AMOTION_EVENT_ACTION_MOVE: { //motion
if (touch.size() != p_points.size()) {
return;
}
for (int i = 0; i < touch.size(); i++) {
int idx = -1;
for (int j = 0; j < p_points.size(); j++) {
if (touch[i].id == p_points[j].id) {
idx = j;
break;
}
}
ERR_CONTINUE(idx == -1);
if (touch[i].pos == p_points[idx].pos) {
continue; // Don't move unnecessarily.
}
Ref<InputEventScreenDrag> ev;
ev.instantiate();
ev->set_index(touch[i].id);
ev->set_position(p_points[idx].pos);
ev->set_relative(p_points[idx].pos - touch[i].pos);
ev->set_relative_screen_position(ev->get_relative());
ev->set_pressure(p_points[idx].pressure);
ev->set_tilt(p_points[idx].tilt);
Input::get_singleton()->parse_input_event(ev);
touch.write[i].pos = p_points[idx].pos;
}
} break;
case AMOTION_EVENT_ACTION_CANCEL: {
_cancel_all_touch();
} break;
case AMOTION_EVENT_ACTION_UP: { //release
<|fim_suffix|>
} break;
case AMOTION_EVENT_ACTION_POINTER_DOWN: { // add touch
for (int i = 0; i < p_points.size(); i++) {
if (p_points[i].id == p_pointer) {
TouchPos tp = p_points[i];
touch.push_back(tp);
Ref<InputEventScreenTouch> ev;
ev.instantiate();
ev->set_index(tp.id);
ev->set_pressed(true);
ev->set_position(tp.pos);
Input::get_singleton()->parse_input_event(ev);
break;
}
}
} break;
case AMOTION_EVENT_ACTION_POINTER_UP: { // remove touch
for (int i = 0; i < touch.size(); i++) {
if (touch[i].id == p_pointer) {
Ref<InputEventScreenTouch> ev;
ev.instantiate();
ev->set_index(touch[i].id);
ev->set_pressed(false);
ev->set_position(touch[i].pos);
Input::get_singleton()->parse_input_event(ev);
touch.remove_at(i);
break;
}
}
} break;
}
}
void AndroidInputHandler::_cancel_mouse_event_info(bool p_source_mouse_relative) {
buttons_state = BitField<MouseButtonMask>();
_parse_mouse_event_info(BitField<MouseButtonMask>(), false, true, false, p_source_mouse_relative);
mouse_event_info.valid = false;
}
void AndroidInputHandler::_parse_mouse_event_info(BitField<MouseButtonMask> event_buttons_mask, bool p_pressed, bool p_canceled, bool p_double_click, bool p_source_mouse_relative) {
if (!mouse_event_info.valid) {
return;
}
Ref<InputEventMouseButton> ev;
ev.instantiate();
_set_key_modifier_state(ev, Key::NONE);
if (p_source_mouse_relative) {
ev->set_position(hover_prev_pos);
ev->set_global_position(hover_prev_pos);
} else {
ev->set_position(mouse_event_info.pos);
ev->set_global_position(mouse_event_info.pos);
hover_prev_pos = mouse_event_info.pos;
}
ev->set_pressed(p_pressed);
ev->set_canceled(p_canceled);
BitField<MouseButtonMask> changed_button_mask = buttons_state.get_different(event_buttons_mask);
buttons_state = event_buttons_mask;
ev->set_button_index(_button_index_from_mask(changed_button_mask));
ev->set_button_mask(event_butto<|fim_middle|>_release_all_touch();
|
creenTouch> ev;
ev.instantiate();
ev->set_index(touch[i].id);
ev->set_pressed(p_pressed);
ev->set_canceled(p_canceled);
ev->set_position(touch[i].pos);
ev->set_double_tap(p_double_tap);
Input::get_singleton()->parse_input_event(ev);
}
}
}
void AndroidInputHandler::_release_all_touch() {
_parse_all_touch(false, false);
touch.clear();
}
void AndroidInputHandler::process_touch_event(int p_event, int p_pointer, const Vector<TouchPos> &p_points, bool p_double_tap) {
switch (p_event) {
case AMOTION_EVENT_ACTION_DOWN: { //gesture begin
// Release any remaining touches or mouse event
_release_mouse_event_info();
_release_all_touch();
touch.resize(p_points.size());
for (int i = 0; i < p_points.size(); i++) {
touch.write[i].id = p_points[i].id;
touch.write[i].pos = p_points[i].pos;
touch.write[i].pressure = p_points[i].pressure;
touch.write[i].tilt = p_points[i].tilt;
}
//send touch
_parse_all_touch(true, false, p_double_tap);
} break;
case AMOTION_EVENT_ACTION_MOVE: { //motion
if (touch.size() != p_points.size()) {
return;
}
for (int i = 0; i < touch.size(); i++) {
int idx = -1;
for (int j = 0; j < p_points.size(); j++) {
if (touch[i].id == p_points[j].id) {
idx = j;
break;
}
}
ERR_CONTINUE(idx == -1);
if (touch[i].pos == p_points[idx].pos) {
continue; // Don't move unnecessarily.
}
Ref<InputEventScreenDrag> ev;
ev.instantiate();
ev->set_index(touch[i].id);
ev->set_position(p_points[idx].pos);
ev->set_relative(p_points[idx].pos - touch[i].pos);
ev->set_relative_screen_position(ev->get_relative());
ev->set_pressure(p_points[idx].pressure);
ev->set_tilt(p_points[idx].tilt);
Input::get_singleton()->parse_input_event(ev);
touch.write[i].pos = p_points[idx].pos;
}
} break;
case AMOTION_EVENT_ACTION_CANCEL: {
_cancel_all_touch();
} break;
case AMOTION_EVENT_ACTION_UP: { //release
|
_release_all_touch();
|
} break;
case AMOTION_EVENT_ACTION_POINTER_DOWN: { // add touch
for (int i = 0; i < p_points.size(); i++) {
if (p_points[i].id == p_pointer) {
TouchPos tp = p_points[i];
touch.push_back(tp);
Ref<InputEventScreenTouch> ev;
ev.instantiate();
ev->set_index(tp.id);
ev->set_pressed(true);
ev->set_position(tp.pos);
Input::get_singleton()->parse_input_event(ev);
break;
}
}
} break;
case AMOTION_EVENT_ACTION_POINTER_UP: { // remove touch
for (int i = 0; i < touch.size(); i++) {
if (touch[i].id == p_pointer) {
Ref<InputEventScreenTouch> ev;
ev.instantiate();
ev->set_index(touch[i].id);
ev->set_pressed(false);
ev->set_position(touch[i].pos);
Input::get_singleton()->parse_input_event(ev);
touch.remove_at(i);
break;
}
}
} break;
}
}
void AndroidInputHandler::_cancel_mouse_event_info(bool p_source_mouse_relative) {
buttons_state = BitField<MouseButtonMask>();
_parse_mouse_event_info(BitField<MouseButtonMask>(), false, true, false, p_source_mouse_relative);
mouse_event_info.valid = false;
}
void AndroidInputHandler::_parse_mouse_event_info(BitField<MouseButtonMask> event_buttons_mask, bool p_pressed, bool p_canceled, bool p_double_click, bool p_source_mouse_relative) {
if (!mouse_event_info.valid) {
return;
}
Ref<InputEventMouseButton> ev;
ev.instantiate();
_set_key_modifier_state(ev, Key::NONE);
if (p_source_mouse_relative) {
ev->set_position(hover_prev_pos);
ev->set_global_position(hover_prev_pos);
} else {
ev->set_position(mouse_event_info.pos);
ev->set_global_position(mouse_event_info.pos);
hover_prev_pos = mouse_event_info.pos;
}
ev->set_pressed(p_pressed);
ev->set_canceled(p_canceled);
BitField<MouseButtonMask> changed_button_mask = buttons_state.get_different(event_buttons_mask);
buttons_state = event_buttons_mask;
ev->set_button_index(_button_index_from_mask(changed_button_mask));
ev->set_button_mask(event_butto
|
ast_based
|
<|fim_prefix|>ID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_active_descendant(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_next_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_next_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_previous_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_previous_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_member_of(const RID &p_id, const RID &p_group_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
<|fim_suffix|>
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_group_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_member_of(ae->node, (accesskit_node_id)p_group_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_in_page_link_target(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_in_page_link_target(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_error_message(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_error_message(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_live(const RID &p_id, DisplayServer::AccessibilityLiveMode p_live) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_live) {
case DisplayServer::AccessibilityLiveMode::LIVE_OFF: {
accesskit_node_set_live(ae->node, ACCESSK<|fim_middle|>AccessibilityElement *ae = rid_owner.get_or_null(p_id);
|
ID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_active_descendant(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_next_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_next_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_previous_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_previous_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_member_of(const RID &p_id, const RID &p_group_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
|
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
|
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_group_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_member_of(ae->node, (accesskit_node_id)p_group_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_in_page_link_target(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_in_page_link_target(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_error_message(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_error_message(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_live(const RID &p_id, DisplayServer::AccessibilityLiveMode p_live) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_live) {
case DisplayServer::AccessibilityLiveMode::LIVE_OFF: {
accesskit_node_set_live(ae->node, ACCESSK
|
ast_based
|
<|fim_prefix|>stom_action(const RID &p_id, int p_action_id, const String &p_action_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_action_description.is_empty()) {
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, p_action_description.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
} else {
String cs_name = vformat("Custom Action %d", p_action_id);
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, cs_name.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_index(ae->node, p_index);
}
<|fim_suffix|>
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_position(const RID &p_id, int p_row_index, int p_column_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_index(ae->node, p_row_index);
accesskit_node_set_column_index(ae->node, p_column_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_span(const RID &p_id, int p_row_span, int p_column_span) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_span(ae->node, p_row_span);
accesskit_node_set_column_span(ae->node, p_column_span);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_count(const RID &p_id, int p_size) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_size_of_set(ae->node, p_size);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_position_in_set(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_level(const RID &p_id, int p_level) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility up<|fim_middle|>void AccessibilityDriverAccessKit::accessibility_update_set_table_column_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_index(ae->node, p_index);
}
|
stom_action(const RID &p_id, int p_action_id, const String &p_action_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_action_description.is_empty()) {
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, p_action_description.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
} else {
String cs_name = vformat("Custom Action %d", p_action_id);
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, cs_name.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_index(ae->node, p_index);
}
|
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_index(ae->node, p_index);
}
|
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_position(const RID &p_id, int p_row_index, int p_column_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_index(ae->node, p_row_index);
accesskit_node_set_column_index(ae->node, p_column_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_span(const RID &p_id, int p_row_span, int p_column_span) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_span(ae->node, p_row_span);
accesskit_node_set_column_span(ae->node, p_column_span);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_count(const RID &p_id, int p_size) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_size_of_set(ae->node, p_size);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_position_in_set(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_level(const RID &p_id, int p_level) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility up
|
ast_based
|
<|fim_prefix|>t_step)
TegraCvtColor_Invoker(bgrx2gray, bgrx2gray, CAROTENE_NS::COLOR_SPACE_BT601, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
#define TEGRA_CVTBGRTOGRAY(src_data, src_step, dst_data, dst_step, width, height, depth, scn, swapBlue) \
( \
depth == CV_8U && CAROTENE_NS::isSupportedConfiguration() ? \
scn == 3 ? \
(swapBlue ? \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_rgb2gray_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)) : \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_bgr2gray_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)) ), \
CV_HAL_ERROR_OK : \
scn == 4 ? \
(swapBlue ? \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_rgbx2gray_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)) : \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_bgrx2gray_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)) ), \
CV_HAL_ERROR_OK : \
CV_HAL_ERROR_NOT_IMPLEMENTED \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
TegraCvtColor_Invoker(gray2rgb, gray2rgb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
TegraCvtColor_Invoker(gray2rgbx, gray2rgbx, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + <|fim_suffix|> * dst_step, dst_step)
#define TEGRA_CVTGRAYTOBGR(src_data, src_step, dst_data, dst_step, width, height, depth, dcn) \
( \
depth == CV_8U && CAROTENE_NS::isSupportedConfiguration() ? \
dcn == 3 ? \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_gray2rgb_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)), \
CV_HAL_ERROR_OK : \
dcn == 4 ? \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_gray2rgbx_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)), \
CV_HAL_ERROR_OK : \
CV_HAL_ERROR_NOT_IMPLEMENTED \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
TegraCvtColor_Invoker(rgb2ycrcb, rgb2ycrcb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
TegraCvtColor_Invoker(bgr2ycrcb, bgr2ycrcb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
TegraCvtColor_Invoker(rgbx2ycrcb, rgbx2ycrcb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
TegraCvtColor_Invoker(bgrx2ycrcb, bgrx2ycrcb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
#define TEGRA_CVTBGRTOYUV(src_data, src_step, dst_data, dst_step, width, height, depth, scn, swapBlue, isCbCr) \
( \
isCbCr && depth == CV_8U && CAROTENE_NS::isSupportedConfiguration() ? \
scn == 3 ? \
(swapBlue ? \
parallel_for_(cv::Range(0, height), \
<|fim_middle|>static_cast<size_t>(range.start)
|
t_step)
TegraCvtColor_Invoker(bgrx2gray, bgrx2gray, CAROTENE_NS::COLOR_SPACE_BT601, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
#define TEGRA_CVTBGRTOGRAY(src_data, src_step, dst_data, dst_step, width, height, depth, scn, swapBlue) \
( \
depth == CV_8U && CAROTENE_NS::isSupportedConfiguration() ? \
scn == 3 ? \
(swapBlue ? \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_rgb2gray_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)) : \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_bgr2gray_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)) ), \
CV_HAL_ERROR_OK : \
scn == 4 ? \
(swapBlue ? \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_rgbx2gray_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)) : \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_bgrx2gray_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)) ), \
CV_HAL_ERROR_OK : \
CV_HAL_ERROR_NOT_IMPLEMENTED \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
TegraCvtColor_Invoker(gray2rgb, gray2rgb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
TegraCvtColor_Invoker(gray2rgbx, gray2rgbx, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data +
|
static_cast<size_t>(range.start)
|
* dst_step, dst_step)
#define TEGRA_CVTGRAYTOBGR(src_data, src_step, dst_data, dst_step, width, height, depth, dcn) \
( \
depth == CV_8U && CAROTENE_NS::isSupportedConfiguration() ? \
dcn == 3 ? \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_gray2rgb_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)), \
CV_HAL_ERROR_OK : \
dcn == 4 ? \
parallel_for_(cv::Range(0, height), \
TegraCvtColor_gray2rgbx_Invoker(src_data, src_step, dst_data, dst_step, width, height), \
(width * height) / static_cast<double>(1<<16)), \
CV_HAL_ERROR_OK : \
CV_HAL_ERROR_NOT_IMPLEMENTED \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
TegraCvtColor_Invoker(rgb2ycrcb, rgb2ycrcb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
TegraCvtColor_Invoker(bgr2ycrcb, bgr2ycrcb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
TegraCvtColor_Invoker(rgbx2ycrcb, rgbx2ycrcb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
TegraCvtColor_Invoker(bgrx2ycrcb, bgrx2ycrcb, src_data + static_cast<size_t>(range.start) * src_step, src_step, \
dst_data + static_cast<size_t>(range.start) * dst_step, dst_step)
#define TEGRA_CVTBGRTOYUV(src_data, src_step, dst_data, dst_step, width, height, depth, scn, swapBlue, isCbCr) \
( \
isCbCr && depth == CV_8U && CAROTENE_NS::isSupportedConfiguration() ? \
scn == 3 ? \
(swapBlue ? \
parallel_for_(cv::Range(0, height), \
|
ast_based
|
<|fim_prefix|>id, ae);
accesskit_node_set_row_index(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_index(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_position(const RID &p_id, int p_row_index, int p_column_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_index(ae->node, p_row_index);
accesskit_node_set_column_index(ae->node, p_column_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_span(const RID &p_id, int p_row_span, int p_column_span) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_span(ae->node, p_row_span);
accesskit_node_set_column_span(ae->node, p_column_span);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_count(const RID &p_id, int p_size) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_size_of_set(ae->node, p_size);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_index(const RID &p_id, int p_index) {
<|fim_suffix|>;
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_position_in_set(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_level(const RID &p_id, int p_level) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_level(ae->node, p_level);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_selected(const RID &p_id, bool p_selected) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_selected(ae->node, p_selected);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_expanded(const RID &p_id, bool p_expanded) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_expanded(ae->node, p_expanded);
}
void AccessibilityDriverAccessKit::accessibility_update_set_popup_type(const RID &p_id, DisplayServer::AccessibilityPopupType p_popup) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_popup) {
case DisplayServer::AccessibilityPopupType::POPUP_MENU: {
accesskit_node_set_has_popup(ae->node, ACCESSKIT_HAS_POPUP_MENU);
} break;
case DisplayServer::AccessibilityPo<|fim_middle|>ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.")
|
id, ae);
accesskit_node_set_row_index(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_index(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_position(const RID &p_id, int p_row_index, int p_column_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_index(ae->node, p_row_index);
accesskit_node_set_column_index(ae->node, p_column_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_span(const RID &p_id, int p_row_span, int p_column_span) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_span(ae->node, p_row_span);
accesskit_node_set_column_span(ae->node, p_column_span);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_count(const RID &p_id, int p_size) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_size_of_set(ae->node, p_size);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_index(const RID &p_id, int p_index) {
|
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.")
|
;
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_position_in_set(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_level(const RID &p_id, int p_level) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_level(ae->node, p_level);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_selected(const RID &p_id, bool p_selected) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_selected(ae->node, p_selected);
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_item_expanded(const RID &p_id, bool p_expanded) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_expanded(ae->node, p_expanded);
}
void AccessibilityDriverAccessKit::accessibility_update_set_popup_type(const RID &p_id, DisplayServer::AccessibilityPopupType p_popup) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_popup) {
case DisplayServer::AccessibilityPopupType::POPUP_MENU: {
accesskit_node_set_has_popup(ae->node, ACCESSKIT_HAS_POPUP_MENU);
} break;
case DisplayServer::AccessibilityPo
|
ast_based
|
<|fim_prefix|>ass MissingImplementationError: public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
class UnsupportedModelError: public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
struct GPUDevice {
const char *backend;
int index;
int type;
size_t heapSize;
std::string name;
std::string vendor;
GPUDevice(const char *backend, int index, int type, size_t heapSize, std::string name, std::string vendor):
backend(backend), index(index), type(type), heapSize(heapSize), name(std::move(name)),
vendor(std::move(vendor)) {}
std::string selectionName() const
{
assert(backend == "cuda"s || backend == "kompute"s);
return backendName() + ": " + name;
}
std::string backendName() const { return backendIdToName(backend); }
static std::string backendIdToName(const std::string &backend) { return s_backendNames.at(backend); }
static std::string updateSelectionName(const std::string &name) {
if (name == "Auto" || name == "CPU" || name == "Metal")
return name;
auto it = std::find_if(s_backendNames.begin(), s_backendNames.end(), [&name](const auto &entry) {
return name.starts_with(entry.second + ": ");
});
if (it != s_backendNames.end())
return name;
return "Vulkan: " + name; // previously, there were only Vulkan devices
}
private:
static inline const std::unordered_map<std::string, std::string> s_backendNames {
{"cpu", "CPU"}, {"metal", "Metal"}, {"cuda", "CUDA"}, {"kompute", "Vulkan"},
};
};
class Implementation {
public:
Implementation(const Implementation &) = delete;
Implementation(Implementation &&);
~Implementation();
std::string_view modelType() const { <|fim_suffix|> }
std::string_view buildVariant() const { return m_buildVariant; }
static LLModel *construct(const std::string &modelPath, const std::string &backend = "auto", int n_ctx = 2048);
static std::vector<GPUDevice> availableGPUDevices(size_t memoryRequired = 0);
static int32_t maxContextLength(const std::string &modelPath);
static int32_t layerCount(const std::string &modelPath);
static bool isEmbeddingModel(const std::string &modelPath);
static auto chatTemplate(const char *modelPath) -> std::expected<std::string, std::string>;
static void setImplementationsSearchPath(const std::string &path);
static const std::string &implementationsSearchPath();
static bool hasSupportedCPU();
// 0 for no, 1 for yes, -1 for non-x86_64
static int cpuSupportsAVX2();
private:
Implementation(Dlhandle &&);
static const std::vector<Implementation> &implementationList();
static const Implementation *implementation(const char *fname, const std::string &buildVariant);
static LLModel *constructGlobalLlama(const std::optional<std::string> &backend = std::nullopt);
char *(*m_getFileArch)(const char *fname);
bool (*m_isArchSupported)(const char *arch);
LLModel *(*m_construct)();
std::string_view m_modelType;
std::string_view m_buildVariant;
Dlhandle *m_dlhandle;
};
struct PromptContext {
int32_t n_predict = 200;
int32_t top_k = 40;
float top_p = 0.9f;
float min_p = 0.0f;
float temp = 0.9f;
int32_t n_batch = 9;
float repeat_penalty = 1.10f;
int32_t repeat_last_n = 64; // last n tokens to penalize
float contextErase = 0.5f; // percent of context to erase if we exceed the context window
};
explicit LLModel() {}
virtual ~LLModel() {}
virtual bool supportsEmbedding() const = 0;
virtual bool supportsCompl<|fim_middle|>return m_modelType;
|
ass MissingImplementationError: public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
class UnsupportedModelError: public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
struct GPUDevice {
const char *backend;
int index;
int type;
size_t heapSize;
std::string name;
std::string vendor;
GPUDevice(const char *backend, int index, int type, size_t heapSize, std::string name, std::string vendor):
backend(backend), index(index), type(type), heapSize(heapSize), name(std::move(name)),
vendor(std::move(vendor)) {}
std::string selectionName() const
{
assert(backend == "cuda"s || backend == "kompute"s);
return backendName() + ": " + name;
}
std::string backendName() const { return backendIdToName(backend); }
static std::string backendIdToName(const std::string &backend) { return s_backendNames.at(backend); }
static std::string updateSelectionName(const std::string &name) {
if (name == "Auto" || name == "CPU" || name == "Metal")
return name;
auto it = std::find_if(s_backendNames.begin(), s_backendNames.end(), [&name](const auto &entry) {
return name.starts_with(entry.second + ": ");
});
if (it != s_backendNames.end())
return name;
return "Vulkan: " + name; // previously, there were only Vulkan devices
}
private:
static inline const std::unordered_map<std::string, std::string> s_backendNames {
{"cpu", "CPU"}, {"metal", "Metal"}, {"cuda", "CUDA"}, {"kompute", "Vulkan"},
};
};
class Implementation {
public:
Implementation(const Implementation &) = delete;
Implementation(Implementation &&);
~Implementation();
std::string_view modelType() const {
|
return m_modelType;
|
}
std::string_view buildVariant() const { return m_buildVariant; }
static LLModel *construct(const std::string &modelPath, const std::string &backend = "auto", int n_ctx = 2048);
static std::vector<GPUDevice> availableGPUDevices(size_t memoryRequired = 0);
static int32_t maxContextLength(const std::string &modelPath);
static int32_t layerCount(const std::string &modelPath);
static bool isEmbeddingModel(const std::string &modelPath);
static auto chatTemplate(const char *modelPath) -> std::expected<std::string, std::string>;
static void setImplementationsSearchPath(const std::string &path);
static const std::string &implementationsSearchPath();
static bool hasSupportedCPU();
// 0 for no, 1 for yes, -1 for non-x86_64
static int cpuSupportsAVX2();
private:
Implementation(Dlhandle &&);
static const std::vector<Implementation> &implementationList();
static const Implementation *implementation(const char *fname, const std::string &buildVariant);
static LLModel *constructGlobalLlama(const std::optional<std::string> &backend = std::nullopt);
char *(*m_getFileArch)(const char *fname);
bool (*m_isArchSupported)(const char *arch);
LLModel *(*m_construct)();
std::string_view m_modelType;
std::string_view m_buildVariant;
Dlhandle *m_dlhandle;
};
struct PromptContext {
int32_t n_predict = 200;
int32_t top_k = 40;
float top_p = 0.9f;
float min_p = 0.0f;
float temp = 0.9f;
int32_t n_batch = 9;
float repeat_penalty = 1.10f;
int32_t repeat_last_n = 64; // last n tokens to penalize
float contextErase = 0.5f; // percent of context to erase if we exceed the context window
};
explicit LLModel() {}
virtual ~LLModel() {}
virtual bool supportsEmbedding() const = 0;
virtual bool supportsCompl
|
ast_based
|
<|fim_prefix|> if (hConsole != INVALID_HANDLE_VALUE) {
DWORD mode = 0;
if (::GetConsoleMode(hConsole, &mode) == TRUE) {
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT;
::SetConsoleMode(hConsole, mode);
}
}
// Set the __IMHEX_FORWARD_CONSOLE__ environment variable,
// to let ImHex know that it was launched from the forwarder
// and that it should forward it's console output to us
::SetEnvironmentVariableA("__IMHEX_FORWARD_CONSOLE__", "1");
}
}
int launchExecutable() {
// Get the path of the main ImHex executable
auto executablePath = wolv::io::fs::getExecutablePath();
auto executableFullPath = executablePath->parent_path() / "imhex-gui.exe";
// Handles for the pipes
HANDLE hChildStdoutRead, hChildStdoutWrite;
// Security attributes to allow the pipes to be inherited
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.lpSecurityDescriptor = nullptr;
saAttr.bInheritHandle = TRUE;
// Create pipes for stdout redirection
if (!::CreatePipe(&hChildStdoutRead, &hChildStdoutWrite, &saAttr, 0)) {
return EXIT_FAILURE;
}
// Set up the STARTUPINFO structure for the child process
STARTUPINFO si;
::ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.hStdOutput = hChildStdoutWrite; // Redirect stdout to the parent process
si.dwFlags |= STARTF_USESTDHANDLES; // Enable redirection of stdin, stdout, stderr
PROCESS_INFORMATION pi;
::ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
// Create the child process
if (!::CreateProcessW(
executableFullPath.c_str(),
::GetCommandLineW(), // Command line
nullptr, // Process security attributes
nullptr, // Thread security attributes
TRUE, // Inherit handles<|fim_suffix|> nullptr, // Environment
nullptr, // Current directory
&si, // STARTUPINFO
&pi // PROCESS_INFORMATION
)) {
return EXIT_FAILURE;
}
// Close unnecessary pipe handles in the parent process
::CloseHandle(hChildStdoutWrite);
// Read the child process's stdout and stderr and redirect them to the parent's stdout
DWORD bytesRead;
std::array<char, 4096> buffer;
while (true) {
// Read from stdout
if (::ReadFile(hChildStdoutRead, buffer.data(), buffer.size(), &bytesRead, nullptr)) {
// Write to the parent's stdout
if (bytesRead > 0)
::WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buffer.data(), bytesRead, &bytesRead, nullptr);
} else {
break;
}
}
// Wait for the child process to exit
::WaitForSingleObject(pi.hProcess, INFINITE);
// Clean up
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
::CloseHandle(hChildStdoutRead);
return EXIT_SUCCESS;
}
int main() {
setupConsoleWindow();
return launchExecutable();
}<|fim_middle|> 0, // Creation flags
|
if (hConsole != INVALID_HANDLE_VALUE) {
DWORD mode = 0;
if (::GetConsoleMode(hConsole, &mode) == TRUE) {
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT;
::SetConsoleMode(hConsole, mode);
}
}
// Set the __IMHEX_FORWARD_CONSOLE__ environment variable,
// to let ImHex know that it was launched from the forwarder
// and that it should forward it's console output to us
::SetEnvironmentVariableA("__IMHEX_FORWARD_CONSOLE__", "1");
}
}
int launchExecutable() {
// Get the path of the main ImHex executable
auto executablePath = wolv::io::fs::getExecutablePath();
auto executableFullPath = executablePath->parent_path() / "imhex-gui.exe";
// Handles for the pipes
HANDLE hChildStdoutRead, hChildStdoutWrite;
// Security attributes to allow the pipes to be inherited
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.lpSecurityDescriptor = nullptr;
saAttr.bInheritHandle = TRUE;
// Create pipes for stdout redirection
if (!::CreatePipe(&hChildStdoutRead, &hChildStdoutWrite, &saAttr, 0)) {
return EXIT_FAILURE;
}
// Set up the STARTUPINFO structure for the child process
STARTUPINFO si;
::ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.hStdOutput = hChildStdoutWrite; // Redirect stdout to the parent process
si.dwFlags |= STARTF_USESTDHANDLES; // Enable redirection of stdin, stdout, stderr
PROCESS_INFORMATION pi;
::ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
// Create the child process
if (!::CreateProcessW(
executableFullPath.c_str(),
::GetCommandLineW(), // Command line
nullptr, // Process security attributes
nullptr, // Thread security attributes
TRUE, // Inherit handles
|
0, // Creation flags
|
nullptr, // Environment
nullptr, // Current directory
&si, // STARTUPINFO
&pi // PROCESS_INFORMATION
)) {
return EXIT_FAILURE;
}
// Close unnecessary pipe handles in the parent process
::CloseHandle(hChildStdoutWrite);
// Read the child process's stdout and stderr and redirect them to the parent's stdout
DWORD bytesRead;
std::array<char, 4096> buffer;
while (true) {
// Read from stdout
if (::ReadFile(hChildStdoutRead, buffer.data(), buffer.size(), &bytesRead, nullptr)) {
// Write to the parent's stdout
if (bytesRead > 0)
::WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buffer.data(), bytesRead, &bytesRead, nullptr);
} else {
break;
}
}
// Wait for the child process to exit
::WaitForSingleObject(pi.hProcess, INFINITE);
// Clean up
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
::CloseHandle(hChildStdoutRead);
return EXIT_SUCCESS;
}
int main() {
setupConsoleWindow();
return launchExecutable();
}
|
random
|
<|fim_prefix|>skit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_flow_to(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_flow_to(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_labeled_by(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_labelled_by(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_radio_group(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_to_radio_group(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_active_descendant(const RID &p_id, const RID &p_other_id) {
<|fim_suffix|>
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_active_descendant(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_next_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_next_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_previous_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_previous_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_member_of(const RID &p_id, const RID &p_group_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_group_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_<|fim_middle|>ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
|
skit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_flow_to(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_flow_to(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_labeled_by(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_labelled_by(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_radio_group(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_to_radio_group(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_active_descendant(const RID &p_id, const RID &p_other_id) {
|
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
|
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_active_descendant(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_next_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_next_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_previous_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_previous_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_member_of(const RID &p_id, const RID &p_group_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_group_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_
|
ast_based
|
<|fim_prefix|> }
}
if (scaling_selection_handles.y != 0) {
if (scaling_selection_handles.y == 1) { // Bottom Handle
const int handle_adjust = Math::round(mp.y - (scaling_selection_scale.y >= 0 ? selection_rect.position.y : (selection_rect.position.y + selection_rect.size.height)));
mp.y -= MIN(Math::abs(handle_adjust), handle_length) * scaling_selection_handles.y * SIGN(handle_adjust);
if (scaling_selection_scale.y >= 0) {
rel_pos.y = mp.y - selection_rect.position.y;
} else {
rel_pos.y = selection_rect.position.y + selection_rect.size.height - mp.y;
}
} else { // Top Handle
const int handle_adjust = Math::round((scaling_selection_scale.y >= 0 ? (selection_rect.position.y + selection_rect.size.height) : selection_rect.position.y) - mp.y);
mp.y -= MIN(Math::abs(handle_adjust), handle_length) * scaling_selection_handles.y * SIGN(handle_adjust);
if (scaling_selection_scale.y >= 0) {
rel_pos.y = selection_rect.position.y + selection_rect.size.height - mp.y;
} else {
rel_pos.y = mp.y - selection_rect.position.y;
}
const float h = (get_size().height / 2.0 - mp.y) * timeline_v_zoom + timeline_v_scroll;
scaling_selection_offset.y = scaling_selection_pivot.y - h;
}
scaling_selection_scale.y *= rel_pos.y / selection_rect.size.height;
if (scaling_selection_scale.y == 0) {
scaling_selection_scale.y = CMP_EPSILON;
}
}
queue_redraw();
}
if ((moving_handle == 1 || moving_handle == -1) && mm.is_valid()) {
float y = (get_size().height / 2.0 - mm->get_position().y) * timeline_v_zoom + timeline_v_scroll;
float x = editor->snap_time((mm->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
Vector2 key_pos = Vector2(animation->track_get_key_time(moving_handle_track, moving_handle_key), animation->bezier_track_get_key_value(moving_handle_track, moving_handle_key));
Vector2 moving_handle_value = Vector2(x, y) - key_pos;
<|fim_suffix|> moving_handle_right = animation->bezier_track_get_key_out_handle(moving_handle_track, moving_handle_key);
if (moving_handle == -1) {
moving_handle_left = moving_handle_value;
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(moving_handle_track, moving_handle_key);
if (handle_mode == Animation::HANDLE_MODE_BALANCED) {
real_t ratio = timeline->get_zoom_scale() * timeline_v_zoom;
Transform2D xform;
xform.set_scale(Vector2(1.0, 1.0 / ratio));
Vector2 vec_out = xform.xform(moving_handle_right);
Vector2 vec_in = xform.xform(moving_handle_left);
moving_handle_right = xform.affine_inverse().xform(-vec_in.normalized() * vec_out.length());
} else if (handle_mode == Animation::HANDLE_MODE_MIRRORED) {
moving_handle_right = -moving_handle_left;
}
} else if (moving_handle == 1) {
moving_handle_right = moving_handle_value;
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(moving_handle_track, moving_handle_key);
if (handle_mode == Animation::HANDLE_MODE_BALANCED) {
real_t ratio = timeline->get_zoom_scale() * timeline_v_zoom;
Transform2D xform;
xform.set_scale(Vector2(1.0, 1.0 / ratio));
Vector2 vec_in = xform.xform(moving_handle_left);
Vector2 vec_out = xform.xform(moving_handle_right);
moving_handle_left = xform.affine_inverse().xform(-vec_out.normalized() * vec_in.length());
} else if (handle_mode == Animation::HANDLE_MODE_MIRRORED) {
moving_handle_left = -moving_handle_right;
}
}
queue_redraw();
}
if ((moving_handle == -1 || moving_handle == 1) && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
if (!read_only) {
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Move Bezier Points"));
if (moving_handle == -1) {
real_t ratio = timeline->get_zoom_scale() * timeline_v_zoom;<|fim_middle|> moving_handle_left = animation->bezier_track_get_key_in_handle(moving_handle_track, moving_handle_key);
|
}
}
if (scaling_selection_handles.y != 0) {
if (scaling_selection_handles.y == 1) { // Bottom Handle
const int handle_adjust = Math::round(mp.y - (scaling_selection_scale.y >= 0 ? selection_rect.position.y : (selection_rect.position.y + selection_rect.size.height)));
mp.y -= MIN(Math::abs(handle_adjust), handle_length) * scaling_selection_handles.y * SIGN(handle_adjust);
if (scaling_selection_scale.y >= 0) {
rel_pos.y = mp.y - selection_rect.position.y;
} else {
rel_pos.y = selection_rect.position.y + selection_rect.size.height - mp.y;
}
} else { // Top Handle
const int handle_adjust = Math::round((scaling_selection_scale.y >= 0 ? (selection_rect.position.y + selection_rect.size.height) : selection_rect.position.y) - mp.y);
mp.y -= MIN(Math::abs(handle_adjust), handle_length) * scaling_selection_handles.y * SIGN(handle_adjust);
if (scaling_selection_scale.y >= 0) {
rel_pos.y = selection_rect.position.y + selection_rect.size.height - mp.y;
} else {
rel_pos.y = mp.y - selection_rect.position.y;
}
const float h = (get_size().height / 2.0 - mp.y) * timeline_v_zoom + timeline_v_scroll;
scaling_selection_offset.y = scaling_selection_pivot.y - h;
}
scaling_selection_scale.y *= rel_pos.y / selection_rect.size.height;
if (scaling_selection_scale.y == 0) {
scaling_selection_scale.y = CMP_EPSILON;
}
}
queue_redraw();
}
if ((moving_handle == 1 || moving_handle == -1) && mm.is_valid()) {
float y = (get_size().height / 2.0 - mm->get_position().y) * timeline_v_zoom + timeline_v_scroll;
float x = editor->snap_time((mm->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
Vector2 key_pos = Vector2(animation->track_get_key_time(moving_handle_track, moving_handle_key), animation->bezier_track_get_key_value(moving_handle_track, moving_handle_key));
Vector2 moving_handle_value = Vector2(x, y) - key_pos;
|
moving_handle_left = animation->bezier_track_get_key_in_handle(moving_handle_track, moving_handle_key);
|
moving_handle_right = animation->bezier_track_get_key_out_handle(moving_handle_track, moving_handle_key);
if (moving_handle == -1) {
moving_handle_left = moving_handle_value;
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(moving_handle_track, moving_handle_key);
if (handle_mode == Animation::HANDLE_MODE_BALANCED) {
real_t ratio = timeline->get_zoom_scale() * timeline_v_zoom;
Transform2D xform;
xform.set_scale(Vector2(1.0, 1.0 / ratio));
Vector2 vec_out = xform.xform(moving_handle_right);
Vector2 vec_in = xform.xform(moving_handle_left);
moving_handle_right = xform.affine_inverse().xform(-vec_in.normalized() * vec_out.length());
} else if (handle_mode == Animation::HANDLE_MODE_MIRRORED) {
moving_handle_right = -moving_handle_left;
}
} else if (moving_handle == 1) {
moving_handle_right = moving_handle_value;
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(moving_handle_track, moving_handle_key);
if (handle_mode == Animation::HANDLE_MODE_BALANCED) {
real_t ratio = timeline->get_zoom_scale() * timeline_v_zoom;
Transform2D xform;
xform.set_scale(Vector2(1.0, 1.0 / ratio));
Vector2 vec_in = xform.xform(moving_handle_left);
Vector2 vec_out = xform.xform(moving_handle_right);
moving_handle_left = xform.affine_inverse().xform(-vec_out.normalized() * vec_in.length());
} else if (handle_mode == Animation::HANDLE_MODE_MIRRORED) {
moving_handle_left = -moving_handle_right;
}
}
queue_redraw();
}
if ((moving_handle == -1 || moving_handle == 1) && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
if (!read_only) {
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Move Bezier Points"));
if (moving_handle == -1) {
real_t ratio = timeline->get_zoom_scale() * timeline_v_zoom;
|
random
|
<|fim_prefix|> Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "animation_bezier_editor.h"
#include "editor/animation/animation_player_editor_plugin.h"
#include "editor/editor_node.h"
#include "editor/editor_string_names.h"
#include "editor/editor_undo_redo_manager.h"
#include "editor/gui/editor_spin_slider.h"
#include "editor/settings/editor_settings.h"
#include "editor/themes/editor_scale.h"
#include "scene/gui/option_button.h"
#include "scene/gui/view_panner.h"
#include "scene/resources/text_line.h"
#include <climits>
float AnimationBezierTrackEdit::_bezier_h_to_pixel(float p_h) <|fim_suffix|>
return h;
}
void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
float scale = timeline->get_zoom_scale();
int limit = timeline->get_name_limit();
int right_limit = get_size().width;
// Selection may have altered the order of keys.
RBMap<real_t, int> key_order;
for (int i = 0; i < animation->track_get_key_count(p_track); i++) {
real_t ofs = animation->track_get_key_time(p_track, i);
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
ofs += moving_selection_offset.x;
} else if (scaling_selection) {
ofs += -scaling_selection_offset.x + (ofs - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
}
}
key_order[ofs] = i;
}
for (RBMap<real_t, int>::Element *E = key_order.front(); E; E = E->next()) {
int i = E->get();
if (!E->next()) {
break;
}
int i_n = E->next()->get();
float offset = animation->track_get_key_time(p_track, i);
float height = animation->bezier_track_get_key_value(p_track, i);
Vector2 out_handle = animation->bezier_track_get_key_out_handle(p_track, i);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i) {
out_handle = moving_handle_right;
}
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
offset += moving_selection_offset.x;
height += moving_selection_offset.y;
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
height += -scaling_selection_offset.y + (height - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
float offset_n = animation->track_get_key_time(p_track, i_n);
float height_n = animation->bezier_track_get_key_value(p_track, i_n);
Vector2 in_handle = animation->bezier_track_get_key_in_handle(p_track, i_n);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i_n<|fim_middle|>{
float h = p_h;
h = (h - timeline_v_scroll) / timeline_v_zoom;
h = (get_size().height / 2.0) - h;
|
Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "animation_bezier_editor.h"
#include "editor/animation/animation_player_editor_plugin.h"
#include "editor/editor_node.h"
#include "editor/editor_string_names.h"
#include "editor/editor_undo_redo_manager.h"
#include "editor/gui/editor_spin_slider.h"
#include "editor/settings/editor_settings.h"
#include "editor/themes/editor_scale.h"
#include "scene/gui/option_button.h"
#include "scene/gui/view_panner.h"
#include "scene/resources/text_line.h"
#include <climits>
float AnimationBezierTrackEdit::_bezier_h_to_pixel(float p_h)
|
{
float h = p_h;
h = (h - timeline_v_scroll) / timeline_v_zoom;
h = (get_size().height / 2.0) - h;
|
return h;
}
void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
float scale = timeline->get_zoom_scale();
int limit = timeline->get_name_limit();
int right_limit = get_size().width;
// Selection may have altered the order of keys.
RBMap<real_t, int> key_order;
for (int i = 0; i < animation->track_get_key_count(p_track); i++) {
real_t ofs = animation->track_get_key_time(p_track, i);
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
ofs += moving_selection_offset.x;
} else if (scaling_selection) {
ofs += -scaling_selection_offset.x + (ofs - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
}
}
key_order[ofs] = i;
}
for (RBMap<real_t, int>::Element *E = key_order.front(); E; E = E->next()) {
int i = E->get();
if (!E->next()) {
break;
}
int i_n = E->next()->get();
float offset = animation->track_get_key_time(p_track, i);
float height = animation->bezier_track_get_key_value(p_track, i);
Vector2 out_handle = animation->bezier_track_get_key_out_handle(p_track, i);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i) {
out_handle = moving_handle_right;
}
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
offset += moving_selection_offset.x;
height += moving_selection_offset.y;
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
height += -scaling_selection_offset.y + (height - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
float offset_n = animation->track_get_key_time(p_track, i_n);
float height_n = animation->bezier_track_get_key_value(p_track, i_n);
Vector2 in_handle = animation->bezier_track_get_key_in_handle(p_track, i_n);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i_n
|
ast_based
|
<|fim_prefix|>Texture(ImTextureData* tex)
{
if (tex->Status == ImTextureStatus_WantCreate)
{
// Create and upload new texture to graphics system
//IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
// Create texture
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
const int new_bitmap_flags = al_get_new_bitmap_flags();
int new_bitmap_format = al_get_new_bitmap_format();
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR);
al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE);
ALLEGRO_BITMAP* cpu_bitmap = al_create_bitmap(tex->Width, tex->Height);
IM_ASSERT(cpu_bitmap != nullptr && "Backend failed to create texture!");
// Upload pixels
ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap(cpu_bitmap, al_get_bitmap_format(cpu_bitmap), ALLEGRO_LOCK_WRITEONLY);
IM_ASSERT(locked_region != nullptr && "Backend failed to create texture!");
memcpy(locked_region->data, tex->GetPixels(), tex->GetSizeInBytes());
al_unlock_bitmap(cpu_bitmap);
// Convert software texture to hardware texture.
al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);
al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_32_WITH_ALPHA);
ALLEGRO_BITMAP* gpu_bitmap = al_clone_bitmap(cpu_bitmap);
al_destroy_bitmap(cpu_bitmap);
IM_ASSERT(gpu_bitmap != nullptr && "Backend failed to create texture!");
al_set_new_bitmap_flags(new_bitmap_flags);
al_set_new_bitmap_format(new_bitmap_format);
// Store identifiers
tex->SetTexID((ImTextureID)(intptr_t)gpu_bitmap);
<|fim_suffix|>
}
else if (tex->Status == ImTextureStatus_WantUpdates)
{
// Update selected blocks. We only ever write to textures regions which have never been used before!
// This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
ImTextureRect r = tex->UpdateRect; // Bounding box encompassing all individual updates
ALLEGRO_BITMAP* gpu_bitmap = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID;
ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap_region(gpu_bitmap, r.x, r.y, r.w, r.h, al_get_bitmap_format(gpu_bitmap), ALLEGRO_LOCK_WRITEONLY);
IM_ASSERT(locked_region && "Backend failed to update texture!");
for (int y = 0; y < r.h; y++)
memcpy((unsigned char*)locked_region->data + locked_region->pitch * y, tex->GetPixelsAt(r.x, r.y + y), r.w * tex->BytesPerPixel); // dst, src, block pitch
al_unlock_bitmap(gpu_bitmap);
tex->SetStatus(ImTextureStatus_OK);
}
else if (tex->Status == ImTextureStatus_WantDestroy)
{
ALLEGRO_BITMAP* backend_tex = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID;
if (backend_tex)
al_destroy_bitmap(backend_tex);
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
tex->SetTexID(ImTextureID_Invalid);
tex->SetStatus(ImTextureStatus_Destroyed);
}
}
void ImGui_ImplAllegro5_InvalidateDeviceObjects()
{
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
// Destroy all textures
for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
if (tex->RefCount == 1)
{
tex->SetStatus(ImTextureStatus_WantDestroy);
ImGui_ImplAllegro5_UpdateTexture(tex);
}
// Destroy mouse cursor
if (bd->MouseCursorInvisible)
{
al_destroy_mouse_cursor(bd->MouseCursorInvisible);
bd->MouseCursorInvisible = nullptr;
}
}
#if ALLEGRO_HAS_CLIP<|fim_middle|>tex->SetStatus(ImTextureStatus_OK);
|
Texture(ImTextureData* tex)
{
if (tex->Status == ImTextureStatus_WantCreate)
{
// Create and upload new texture to graphics system
//IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
// Create texture
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
const int new_bitmap_flags = al_get_new_bitmap_flags();
int new_bitmap_format = al_get_new_bitmap_format();
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR);
al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE);
ALLEGRO_BITMAP* cpu_bitmap = al_create_bitmap(tex->Width, tex->Height);
IM_ASSERT(cpu_bitmap != nullptr && "Backend failed to create texture!");
// Upload pixels
ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap(cpu_bitmap, al_get_bitmap_format(cpu_bitmap), ALLEGRO_LOCK_WRITEONLY);
IM_ASSERT(locked_region != nullptr && "Backend failed to create texture!");
memcpy(locked_region->data, tex->GetPixels(), tex->GetSizeInBytes());
al_unlock_bitmap(cpu_bitmap);
// Convert software texture to hardware texture.
al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);
al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_32_WITH_ALPHA);
ALLEGRO_BITMAP* gpu_bitmap = al_clone_bitmap(cpu_bitmap);
al_destroy_bitmap(cpu_bitmap);
IM_ASSERT(gpu_bitmap != nullptr && "Backend failed to create texture!");
al_set_new_bitmap_flags(new_bitmap_flags);
al_set_new_bitmap_format(new_bitmap_format);
// Store identifiers
tex->SetTexID((ImTextureID)(intptr_t)gpu_bitmap);
|
tex->SetStatus(ImTextureStatus_OK);
|
}
else if (tex->Status == ImTextureStatus_WantUpdates)
{
// Update selected blocks. We only ever write to textures regions which have never been used before!
// This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
ImTextureRect r = tex->UpdateRect; // Bounding box encompassing all individual updates
ALLEGRO_BITMAP* gpu_bitmap = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID;
ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap_region(gpu_bitmap, r.x, r.y, r.w, r.h, al_get_bitmap_format(gpu_bitmap), ALLEGRO_LOCK_WRITEONLY);
IM_ASSERT(locked_region && "Backend failed to update texture!");
for (int y = 0; y < r.h; y++)
memcpy((unsigned char*)locked_region->data + locked_region->pitch * y, tex->GetPixelsAt(r.x, r.y + y), r.w * tex->BytesPerPixel); // dst, src, block pitch
al_unlock_bitmap(gpu_bitmap);
tex->SetStatus(ImTextureStatus_OK);
}
else if (tex->Status == ImTextureStatus_WantDestroy)
{
ALLEGRO_BITMAP* backend_tex = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID;
if (backend_tex)
al_destroy_bitmap(backend_tex);
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
tex->SetTexID(ImTextureID_Invalid);
tex->SetStatus(ImTextureStatus_Destroyed);
}
}
void ImGui_ImplAllegro5_InvalidateDeviceObjects()
{
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
// Destroy all textures
for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
if (tex->RefCount == 1)
{
tex->SetStatus(ImTextureStatus_WantDestroy);
ImGui_ImplAllegro5_UpdateTexture(tex);
}
// Destroy mouse cursor
if (bd->MouseCursorInvisible)
{
al_destroy_mouse_cursor(bd->MouseCursorInvisible);
bd->MouseCursorInvisible = nullptr;
}
}
#if ALLEGRO_HAS_CLIP
|
ast_based
|
<|fim_prefix|> : CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_MAX(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::max(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_MIN(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::min(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_ABSDIFF(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::absDiff(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_AND(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::bitwiseAnd(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_OR(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::bitwiseOr(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_XOR(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::bitwiseXor(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
<|fim_suffix|> CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::bitwiseNot(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#undef cv_hal_add8u
#define cv_hal_add8u TEGRA_ADD
#undef cv_hal_add8s
#define cv_hal_add8s TEGRA_ADD
#undef cv_hal_add16u
#define cv_hal_add16u TEGRA_ADD
#undef cv_hal_add16s
#define cv_hal_add16s TEGRA_ADD
#undef cv_hal_add32s
#define cv_hal_add32s TEGRA_ADD
#undef cv_hal_add32f
#define cv_hal_add32f TEGRA_ADDF
//#undef cv_hal_add64f
//#define cv_hal_add64f TEGRA_ADDF
#undef cv_hal_sub8u
#define cv_hal_sub8u TEGRA_SUB
#undef cv_hal_sub8s
#define cv_hal_sub8s TEGRA_SUB
#undef cv_hal_sub16u
#define cv_hal_sub16u TEGRA_SUB
#undef cv_hal_sub16s
#define cv_hal_sub16s TEGRA_SUB
#undef cv_hal_sub32s
#define cv_hal_sub32s TEGRA_SUB
#undef cv_hal_sub32f
#define cv_hal_sub32f TEGRA_SUBF
//#undef cv_hal_sub64f
//#define cv_hal_sub64f TEGRA_SUBF
#undef cv_hal_max8u
#define cv_hal_max8u TEGRA_MAX
#undef cv_hal_max8s
#define cv_hal_max8s TEGRA_MAX
#undef cv_hal_max16u
#define cv_hal_max16u TEGRA_MAX
#undef cv_hal_max16s
#define cv_hal_max16s TEGRA_MAX
#undef cv_hal_max32s
#define cv_hal_max32s TEGRA_MAX
#undef cv_hal_max32f
#define cv_hal_max32f TEGRA_MAX
//#undef cv_hal_max64f
//#define cv_hal_max64f TEGRA_MAX
#undef cv_hal_min8u
#define cv_hal_min8u TEGRA_MIN
#undef cv_hal_min8s
#define cv_hal_min8s TEGRA_MIN
#undef cv_hal_min16u
#define cv_hal_min16u TEGRA_MIN
#undef cv_hal_min16s
#define cv_hal_min16s TEGRA_MIN
#undef cv_hal_min32s
#define cv_hal_min32s TEGRA_MIN
#undef cv_hal_min32f
#define cv_hal_min32f TEGRA_MIN
//#undef cv_hal_min64f
//#define cv_hal_min64f TEGRA_MIN
#undef cv_hal_absdiff8u
#define cv_hal_absdiff8u TEGRA_ABSDIFF
#undef cv_hal_absdiff8s
#define cv_hal_absdiff8s TEGRA_ABSDIFF
#undef cv_hal_absdiff16u
#define cv_hal_absdiff16u TEGRA_ABSDIFF
#undef cv_hal_absdiff16s
#define cv_hal_absdiff16s TEGRA_ABSDIFF<|fim_middle|>#define TEGRA_NOT(src1, sz1, dst, sz, w, h) \
( \
|
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_MAX(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::max(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_MIN(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::min(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_ABSDIFF(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::absDiff(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_AND(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::bitwiseAnd(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_OR(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::bitwiseOr(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#define TEGRA_XOR(src1, sz1, src2, sz2, dst, sz, w, h) \
( \
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::bitwiseXor(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
src2, sz2, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
|
#define TEGRA_NOT(src1, sz1, dst, sz, w, h) \
( \
|
CAROTENE_NS::isSupportedConfiguration() ? \
CAROTENE_NS::bitwiseNot(CAROTENE_NS::Size2D(w, h), \
src1, sz1, \
dst, sz), \
CV_HAL_ERROR_OK \
: CV_HAL_ERROR_NOT_IMPLEMENTED \
)
#undef cv_hal_add8u
#define cv_hal_add8u TEGRA_ADD
#undef cv_hal_add8s
#define cv_hal_add8s TEGRA_ADD
#undef cv_hal_add16u
#define cv_hal_add16u TEGRA_ADD
#undef cv_hal_add16s
#define cv_hal_add16s TEGRA_ADD
#undef cv_hal_add32s
#define cv_hal_add32s TEGRA_ADD
#undef cv_hal_add32f
#define cv_hal_add32f TEGRA_ADDF
//#undef cv_hal_add64f
//#define cv_hal_add64f TEGRA_ADDF
#undef cv_hal_sub8u
#define cv_hal_sub8u TEGRA_SUB
#undef cv_hal_sub8s
#define cv_hal_sub8s TEGRA_SUB
#undef cv_hal_sub16u
#define cv_hal_sub16u TEGRA_SUB
#undef cv_hal_sub16s
#define cv_hal_sub16s TEGRA_SUB
#undef cv_hal_sub32s
#define cv_hal_sub32s TEGRA_SUB
#undef cv_hal_sub32f
#define cv_hal_sub32f TEGRA_SUBF
//#undef cv_hal_sub64f
//#define cv_hal_sub64f TEGRA_SUBF
#undef cv_hal_max8u
#define cv_hal_max8u TEGRA_MAX
#undef cv_hal_max8s
#define cv_hal_max8s TEGRA_MAX
#undef cv_hal_max16u
#define cv_hal_max16u TEGRA_MAX
#undef cv_hal_max16s
#define cv_hal_max16s TEGRA_MAX
#undef cv_hal_max32s
#define cv_hal_max32s TEGRA_MAX
#undef cv_hal_max32f
#define cv_hal_max32f TEGRA_MAX
//#undef cv_hal_max64f
//#define cv_hal_max64f TEGRA_MAX
#undef cv_hal_min8u
#define cv_hal_min8u TEGRA_MIN
#undef cv_hal_min8s
#define cv_hal_min8s TEGRA_MIN
#undef cv_hal_min16u
#define cv_hal_min16u TEGRA_MIN
#undef cv_hal_min16s
#define cv_hal_min16s TEGRA_MIN
#undef cv_hal_min32s
#define cv_hal_min32s TEGRA_MIN
#undef cv_hal_min32f
#define cv_hal_min32f TEGRA_MIN
//#undef cv_hal_min64f
//#define cv_hal_min64f TEGRA_MIN
#undef cv_hal_absdiff8u
#define cv_hal_absdiff8u TEGRA_ABSDIFF
#undef cv_hal_absdiff8s
#define cv_hal_absdiff8s TEGRA_ABSDIFF
#undef cv_hal_absdiff16u
#define cv_hal_absdiff16u TEGRA_ABSDIFF
#undef cv_hal_absdiff16s
#define cv_hal_absdiff16s TEGRA_ABSDIFF
|
random
|
<|fim_prefix|> ** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#define _USE_MATH_DEFINES // for M_PI
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
# include "config_auto.h"
#endif
#include "boxword.h" // for BoxWord
#include "coutln.h" // for C_OUTLINE_IT, C_OUTLINE_LIST
#include "dawg_cache.h" // for DawgCache
#include "dict.h" // for Dict
#include "elst.h" // for ELIST_ITERATOR, ELISTIZE, ELISTIZEH
#include "environ.h" // for l_uint8
#ifndef DISABLED_LEGACY_ENGINE
#include "equationdetect.h" // for EquationDetect, destructor of equ_detect_
#endif // ndef DISABLED_LEGACY_ENGINE
#include "errcode.h" // for ASSERT_HOST
#include "helpers.h" // for IntCastRounded, chomp_string, copy_string
#include "host.h" // for MAX_PATH
#include "imageio.h" // for IFF_TIFF_G4, IFF_TIFF, IFF_TIFF_G3, ...
#ifndef DISABLED_LEGACY_ENGINE
# include "intfx.h" // for INT_FX_RESULT_STRUCT
#endif
#include "mutableiterator.h" // for MutableIterator
#include "normalis.h" // for kBlnBaselineOffset, kBlnXHeight
#include "pageres.h" // for PAGE_RES_IT, WERD_RES, PAGE_RES, CR_DE...
#include "paragraphs.h" // for DetectParagraphs
#include "params.h" // for BoolParam, IntParam, DoubleParam, Stri...
#include "pdblock.h" // for PDBLK
#include "points.h" // for FCOORD
#include "polyblk.h" // for POLY_BLOCK
#include "rect.h" // for TBOX<|fim_suffix|>#include "tessdatamanager.h" // for TessdataManager, kTrainedDataSuffix
#include "tesseractclass.h" // for Tesseract
#include "tprintf.h" // for tprintf
#include "werd.h" // for WERD, WERD_IT, W_FUZZY_NON, W_FUZZY_SP
#include "thresholder.h" // for ImageThresholder
#include <tesseract/baseapi.h>
#include <tesseract/ocrclass.h> // for ETEXT_DESC
#include <tesseract/osdetect.h> // for OSResults, OSBestResult, OrientationId...
#include <tesseract/renderer.h> // for TessResultRenderer
#include <tesseract/resultiterator.h> // for ResultIterator
#include <cmath> // for round, M_PI
#include <cstdint> // for int32_t
#include <cstring> // for strcmp, strcpy
#include <filesystem> // for std::filesystem
#include <fstream> // for size_t
#include <iostream> // for std::cin
#include <locale> // for std::locale::classic
#include <memory> // for std::unique_ptr
#include <set> // for std::pair
#include <sstream> // for std::stringstream
#include <vector> // for std::vector
#include <allheaders.h> // for pixDestroy, boxCreate, boxaAddBox, box...
#ifdef HAVE_LIBCURL
# include <curl/curl.h>
#endif
#ifdef __linux__
# include <csignal> // for sigaction, SA_RESETHAND, SIGBUS, SIGFPE
#endif
#if defined(_WIN32)
# include <fcntl.h> // for _O_BINARY
# include <io.h> // for _setmode
#endif
namespace tesseract {
static BOOL_VAR(stream_filelist, false, "Stream a filelist from stdin");
static STRING_VAR(document_title, "", "Title of output document (used for hOCR and PDF output)");
#ifdef HAVE_LIBCURL
static INT_VAR(curl_timeout, 0, "Timeout for curl in seconds");
static STRING_VAR(curl_cookiefile, "", "File with cookie data for curl");
#endif
/** Minimum sensible image size to be worth running Tesseract. */
const int kMinRectSize = 10;
/** Character returned when Tesseract couldn't recognize as anything. */
const char kTesseractReject = '~';
/** Character used by UNLV error counter as a reject. */<|fim_middle|>#include "stepblob.h" // for C_BLOB_IT, C_BLOB, C_BLOB_LIST
|
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#define _USE_MATH_DEFINES // for M_PI
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
# include "config_auto.h"
#endif
#include "boxword.h" // for BoxWord
#include "coutln.h" // for C_OUTLINE_IT, C_OUTLINE_LIST
#include "dawg_cache.h" // for DawgCache
#include "dict.h" // for Dict
#include "elst.h" // for ELIST_ITERATOR, ELISTIZE, ELISTIZEH
#include "environ.h" // for l_uint8
#ifndef DISABLED_LEGACY_ENGINE
#include "equationdetect.h" // for EquationDetect, destructor of equ_detect_
#endif // ndef DISABLED_LEGACY_ENGINE
#include "errcode.h" // for ASSERT_HOST
#include "helpers.h" // for IntCastRounded, chomp_string, copy_string
#include "host.h" // for MAX_PATH
#include "imageio.h" // for IFF_TIFF_G4, IFF_TIFF, IFF_TIFF_G3, ...
#ifndef DISABLED_LEGACY_ENGINE
# include "intfx.h" // for INT_FX_RESULT_STRUCT
#endif
#include "mutableiterator.h" // for MutableIterator
#include "normalis.h" // for kBlnBaselineOffset, kBlnXHeight
#include "pageres.h" // for PAGE_RES_IT, WERD_RES, PAGE_RES, CR_DE...
#include "paragraphs.h" // for DetectParagraphs
#include "params.h" // for BoolParam, IntParam, DoubleParam, Stri...
#include "pdblock.h" // for PDBLK
#include "points.h" // for FCOORD
#include "polyblk.h" // for POLY_BLOCK
#include "rect.h" // for TBOX
|
#include "stepblob.h" // for C_BLOB_IT, C_BLOB, C_BLOB_LIST
|
#include "tessdatamanager.h" // for TessdataManager, kTrainedDataSuffix
#include "tesseractclass.h" // for Tesseract
#include "tprintf.h" // for tprintf
#include "werd.h" // for WERD, WERD_IT, W_FUZZY_NON, W_FUZZY_SP
#include "thresholder.h" // for ImageThresholder
#include <tesseract/baseapi.h>
#include <tesseract/ocrclass.h> // for ETEXT_DESC
#include <tesseract/osdetect.h> // for OSResults, OSBestResult, OrientationId...
#include <tesseract/renderer.h> // for TessResultRenderer
#include <tesseract/resultiterator.h> // for ResultIterator
#include <cmath> // for round, M_PI
#include <cstdint> // for int32_t
#include <cstring> // for strcmp, strcpy
#include <filesystem> // for std::filesystem
#include <fstream> // for size_t
#include <iostream> // for std::cin
#include <locale> // for std::locale::classic
#include <memory> // for std::unique_ptr
#include <set> // for std::pair
#include <sstream> // for std::stringstream
#include <vector> // for std::vector
#include <allheaders.h> // for pixDestroy, boxCreate, boxaAddBox, box...
#ifdef HAVE_LIBCURL
# include <curl/curl.h>
#endif
#ifdef __linux__
# include <csignal> // for sigaction, SA_RESETHAND, SIGBUS, SIGFPE
#endif
#if defined(_WIN32)
# include <fcntl.h> // for _O_BINARY
# include <io.h> // for _setmode
#endif
namespace tesseract {
static BOOL_VAR(stream_filelist, false, "Stream a filelist from stdin");
static STRING_VAR(document_title, "", "Title of output document (used for hOCR and PDF output)");
#ifdef HAVE_LIBCURL
static INT_VAR(curl_timeout, 0, "Timeout for curl in seconds");
static STRING_VAR(curl_cookiefile, "", "File with cookie data for curl");
#endif
/** Minimum sensible image size to be worth running Tesseract. */
const int kMinRectSize = 10;
/** Character returned when Tesseract couldn't recognize as anything. */
const char kTesseractReject = '~';
/** Character used by UNLV error counter as a reject. */
|
random
|
<|fim_prefix|>de_set_hidden(ae->node);
} else {
accesskit_node_clear_hidden(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_MULTISELECTABLE: {
if (p_value) {
accesskit_node_set_multiselectable(ae->node);
} else {
accesskit_node_clear_multiselectable(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_REQUIRED: {
if (p_value) {
accesskit_node_set_required(ae->node);
} else {
accesskit_node_clear_required(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_VISITED: {
if (p_value) {
accesskit_node_set_visited(ae->node);
} else {
accesskit_node_clear_visited(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_BUSY: {
if (p_value) {
accesskit_node_set_busy(ae->node);
} else {
accesskit_node_clear_busy(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_MODAL: {
if (p_value) {
accesskit_node_set_modal(ae->node);
} else {
accesskit_node_clear_modal(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_TOUCH_PASSTHROUGH: {
if (p_value) {
accesskit_node_set_touch_transparent(ae->node);
} else {
accesskit_node_clear_touch_transparent(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_READONLY: {
if (p_value) {
accesskit_node_set_read_only(ae->node);
} else {
accesskit_node_clear_read_only(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_DISABLED: {
if (p_value) {
accesskit_node_set_disabled(ae->node);
} else {
accesskit_node_clear_disabled(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_CLIPS_CHILDREN: {
if (p_value) {
accesskit_node_set_clips_children(ae->node);
} else {
accesskit_node_clear_clips_children(ae->node);
}
} break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_classname(const RID &p_id, const String &p_classname) {
<|fim_suffix|>
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_classname.is_empty()) {
accesskit_node_set_class_name(ae->node, p_classname.utf8().ptr());
} else {
accesskit_node_clear_class_name(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_placeholder(const RID &p_id, const String &p_placeholder) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_placeholder.is_empty()) {
accesskit_node_set_placeholder(ae->node, p_placeholder.utf8().ptr());
} else {
accesskit_node_clear_placeholder(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_language(const RID &p_id, const String &p_language) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_language(ae->node, p_language.utf8().ptr());
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_orientation(const RID &p_id, bool p_vertical) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (p_vertical) {
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_TOP_TO_BOTTOM);
} else {
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_orientation(const RID &p_id, bool p_vertical) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE not<|fim_middle|>ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
|
de_set_hidden(ae->node);
} else {
accesskit_node_clear_hidden(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_MULTISELECTABLE: {
if (p_value) {
accesskit_node_set_multiselectable(ae->node);
} else {
accesskit_node_clear_multiselectable(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_REQUIRED: {
if (p_value) {
accesskit_node_set_required(ae->node);
} else {
accesskit_node_clear_required(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_VISITED: {
if (p_value) {
accesskit_node_set_visited(ae->node);
} else {
accesskit_node_clear_visited(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_BUSY: {
if (p_value) {
accesskit_node_set_busy(ae->node);
} else {
accesskit_node_clear_busy(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_MODAL: {
if (p_value) {
accesskit_node_set_modal(ae->node);
} else {
accesskit_node_clear_modal(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_TOUCH_PASSTHROUGH: {
if (p_value) {
accesskit_node_set_touch_transparent(ae->node);
} else {
accesskit_node_clear_touch_transparent(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_READONLY: {
if (p_value) {
accesskit_node_set_read_only(ae->node);
} else {
accesskit_node_clear_read_only(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_DISABLED: {
if (p_value) {
accesskit_node_set_disabled(ae->node);
} else {
accesskit_node_clear_disabled(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_CLIPS_CHILDREN: {
if (p_value) {
accesskit_node_set_clips_children(ae->node);
} else {
accesskit_node_clear_clips_children(ae->node);
}
} break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_classname(const RID &p_id, const String &p_classname) {
|
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
|
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_classname.is_empty()) {
accesskit_node_set_class_name(ae->node, p_classname.utf8().ptr());
} else {
accesskit_node_clear_class_name(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_placeholder(const RID &p_id, const String &p_placeholder) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_placeholder.is_empty()) {
accesskit_node_set_placeholder(ae->node, p_placeholder.utf8().ptr());
} else {
accesskit_node_clear_placeholder(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_language(const RID &p_id, const String &p_language) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_language(ae->node, p_language.utf8().ptr());
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_orientation(const RID &p_id, bool p_vertical) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (p_vertical) {
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_TOP_TO_BOTTOM);
} else {
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_orientation(const RID &p_id, bool p_vertical) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE not
|
ast_based
|
<|fim_prefix|> } else {
// Avoid an error, `hint_string` is required for `PROPERTY_HINT_RANGE`.
p_property.hint_string = "0,0,1";
}
p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
}
void AnimatedSprite2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ACCESSIBILITY_UPDATE: {
RID ae = get_accessibility_element();
ERR_FAIL_COND(ae.is_null());
Rect2 dst_rect = _get_rect();
DisplayServer::get_singleton()->accessibility_update_set_role(ae, DisplayServer::AccessibilityRole::ROLE_IMAGE);
DisplayServer::get_singleton()->accessibility_update_set_transform(ae, get_transform());
DisplayServer::get_singleton()->accessibility_update_set_bounds(ae, dst_rect);
} break;
case NOTIFICATION_READY: {
if (!Engine::get_singleton()->is_editor_hint() && frames.is_valid() && frames->has_animation(autoplay)) {
play(autoplay);
}
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
}
double remaining = get_process_delta_time();
int i = 0;
while (remaining) {
// Animation speed may be changed by animation_finished or frame_changed signals.
double speed = frames->get_animation_speed(animation) * speed_scale * custom_speed_scale * frame_speed_scale;
double abs_speed = Math::abs(speed);
if (speed == 0) {
return; // Do nothing.
}
// Frame count may be changed by animation_finished or frame_changed signals.
int fc = frames->get_frame_count(animation);
int last_frame = fc - 1;
if (!std::signbit(speed)) {
// Forwards.
if (frame_progress >= 1.0) {
if (frame >= last_frame) {
if (frames->get_animation_loop(animation)) {
frame = 0;
emit_signal("animation_looped");
} else {
frame = last_frame;
pause();
emit_signal(SceneStringName(animation_finished));
return;<|fim_suffix|> }
_calc_frame_speed_scale();
frame_progress = 0.0;
queue_redraw();
emit_signal(SceneStringName(frame_changed));
}
double to_process = MIN((1.0 - frame_progress) / abs_speed, remaining);
frame_progress += to_process * abs_speed;
remaining -= to_process;
} else {
// Backwards.
if (frame_progress <= 0) {
if (frame <= 0) {
if (frames->get_animation_loop(animation)) {
frame = last_frame;
emit_signal("animation_looped");
} else {
frame = 0;
pause();
emit_signal(SceneStringName(animation_finished));
return;
}
} else {
frame--;
}
_calc_frame_speed_scale();
frame_progress = 1.0;
queue_redraw();
emit_signal(SceneStringName(frame_changed));
}
double to_process = MIN(frame_progress / abs_speed, remaining);
frame_progress -= to_process * abs_speed;
remaining -= to_process;
}
i++;
if (i > fc) {
return; // Prevents freezing if to_process is each time much less than remaining.
}
}
} break;
case NOTIFICATION_DRAW: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
}
Ref<Texture2D> texture = frames->get_frame_texture(animation, frame);
if (texture.is_null()) {
return;
}
RID ci = get_canvas_item();
Size2 s = texture->get_size();
Point2 ofs = offset;
if (centered) {
ofs -= s / 2;
}
if (get_viewport() && get_viewport()->is_snap_2d_transforms_to_pixel_enabled()) {
ofs = (ofs + Point2(0.5, 0.5)).floor();
}
Rect2 dst_rect(ofs, s);
if (hflip) {
dst_rect.size.x = -dst_rect.size.x;
}
if (vflip) {
dst_rect.size.y = -dst_rect.size.y;
}
texture->draw_rect_region(ci, dst_rect, Rect2(Vector2(), texture->get_size()), Color(1, 1, 1), false);
} break;
}
}
void AnimatedSprite2D::set_sprite_frames(const Ref<SpriteFrames> &p_frames) {
if (frames == p_frames) {<|fim_middle|> }
} else {
frame++;
|
} else {
// Avoid an error, `hint_string` is required for `PROPERTY_HINT_RANGE`.
p_property.hint_string = "0,0,1";
}
p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
}
void AnimatedSprite2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ACCESSIBILITY_UPDATE: {
RID ae = get_accessibility_element();
ERR_FAIL_COND(ae.is_null());
Rect2 dst_rect = _get_rect();
DisplayServer::get_singleton()->accessibility_update_set_role(ae, DisplayServer::AccessibilityRole::ROLE_IMAGE);
DisplayServer::get_singleton()->accessibility_update_set_transform(ae, get_transform());
DisplayServer::get_singleton()->accessibility_update_set_bounds(ae, dst_rect);
} break;
case NOTIFICATION_READY: {
if (!Engine::get_singleton()->is_editor_hint() && frames.is_valid() && frames->has_animation(autoplay)) {
play(autoplay);
}
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
}
double remaining = get_process_delta_time();
int i = 0;
while (remaining) {
// Animation speed may be changed by animation_finished or frame_changed signals.
double speed = frames->get_animation_speed(animation) * speed_scale * custom_speed_scale * frame_speed_scale;
double abs_speed = Math::abs(speed);
if (speed == 0) {
return; // Do nothing.
}
// Frame count may be changed by animation_finished or frame_changed signals.
int fc = frames->get_frame_count(animation);
int last_frame = fc - 1;
if (!std::signbit(speed)) {
// Forwards.
if (frame_progress >= 1.0) {
if (frame >= last_frame) {
if (frames->get_animation_loop(animation)) {
frame = 0;
emit_signal("animation_looped");
} else {
frame = last_frame;
pause();
emit_signal(SceneStringName(animation_finished));
return;
|
}
} else {
frame++;
|
}
_calc_frame_speed_scale();
frame_progress = 0.0;
queue_redraw();
emit_signal(SceneStringName(frame_changed));
}
double to_process = MIN((1.0 - frame_progress) / abs_speed, remaining);
frame_progress += to_process * abs_speed;
remaining -= to_process;
} else {
// Backwards.
if (frame_progress <= 0) {
if (frame <= 0) {
if (frames->get_animation_loop(animation)) {
frame = last_frame;
emit_signal("animation_looped");
} else {
frame = 0;
pause();
emit_signal(SceneStringName(animation_finished));
return;
}
} else {
frame--;
}
_calc_frame_speed_scale();
frame_progress = 1.0;
queue_redraw();
emit_signal(SceneStringName(frame_changed));
}
double to_process = MIN(frame_progress / abs_speed, remaining);
frame_progress -= to_process * abs_speed;
remaining -= to_process;
}
i++;
if (i > fc) {
return; // Prevents freezing if to_process is each time much less than remaining.
}
}
} break;
case NOTIFICATION_DRAW: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
}
Ref<Texture2D> texture = frames->get_frame_texture(animation, frame);
if (texture.is_null()) {
return;
}
RID ci = get_canvas_item();
Size2 s = texture->get_size();
Point2 ofs = offset;
if (centered) {
ofs -= s / 2;
}
if (get_viewport() && get_viewport()->is_snap_2d_transforms_to_pixel_enabled()) {
ofs = (ofs + Point2(0.5, 0.5)).floor();
}
Rect2 dst_rect(ofs, s);
if (hflip) {
dst_rect.size.x = -dst_rect.size.x;
}
if (vflip) {
dst_rect.size.y = -dst_rect.size.y;
}
texture->draw_rect_region(ci, dst_rect, Rect2(Vector2(), texture->get_size()), Color(1, 1, 1), false);
} break;
}
}
void AnimatedSprite2D::set_sprite_frames(const Ref<SpriteFrames> &p_frames) {
if (frames == p_frames) {
|
random
|
<|fim_prefix|>/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#include "core/os/main_loop.h"
#include "core/string/ustring.h"
#include "core/templates/list.h"
template <typename T>
class TypedArray;
class Engine {
public:
struct Singleton {
StringName name;
Object *ptr = nullptr;
StringName class_name; // Used for binding generation hinting.<|fim_suffix|> bool user_created = false;
bool editor_only = false;
Singleton(const StringName &p_name = StringName(), Object *p_ptr = nullptr, const StringName &p_class_name = StringName());
};
private:
friend class Main;
uint64_t frames_drawn = 0;
uint32_t _frame_delay = 0;
uint64_t _frame_ticks = 0;
double _process_step = 0;
int ips = 60;
double physics_jitter_fix = 0.5;
double _fps = 1;
int _max_fps = 0;
int _audio_output_latency = 0;
double _time_scale = 1.0;
uint64_t _physics_frames = 0;
int max_physics_steps_per_frame = 8;
double _physics_interpolation_fraction = 0.0f;
bool abort_on_gpu_errors = false;
bool use_validation_layers = false;
bool generate_spirv_debug_info = false;
bool extra_gpu_memory_tracking = false;
#if defined(DEBUG_ENABLED) || defined(DEV_ENABLED)
bool accurate_breadcrumbs = false;
#endif
int32_t gpu_idx = -1;
uint64_t _process_frames = 0;
bool _in_physics = false;
List<Singleton> singletons;
HashMap<StringName, Object *> singleton_ptrs;
bool editor_hint = false;
bool project_manager_hint = false;
bool extension_reloading = false;
bool embedded_in_editor = false;
bool recovery_mode_hint = false;
bool _print_header = true;
static inline Engine *singleton = nullptr;
String write_movie_path;
String shader_cache_path;
static constexpr int SERVER_SYNC_FRAME_COUNT_WARNING = 5;
int server_syncs = 0;
bool frame_server_synced = false;
bool freeze_time_scale = false;
public:
static Engine *get_singleton();
virtual void set_physics_ticks_per_second(int p_ips);
virtual int get_physics_ticks_per_second() const;
virtual void set_max_physics_steps_per_frame(int p_max_physics_steps);
virtual int get_max_physics_steps_per_frame() const;
void set_physics_jitter_fix(double p_threshold);
double get_physics_jitter_fix() const;
virtual void set_max_fps(int p_fps);
virtual int get_max_fps() const;
virtual void set_audio_output_latency(int p_msec);
virtual int get_audio_output_latency() const;
<|fim_middle|> // Singleton scope flags.
|
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#include "core/os/main_loop.h"
#include "core/string/ustring.h"
#include "core/templates/list.h"
template <typename T>
class TypedArray;
class Engine {
public:
struct Singleton {
StringName name;
Object *ptr = nullptr;
StringName class_name; // Used for binding generation hinting.
|
// Singleton scope flags.
|
bool user_created = false;
bool editor_only = false;
Singleton(const StringName &p_name = StringName(), Object *p_ptr = nullptr, const StringName &p_class_name = StringName());
};
private:
friend class Main;
uint64_t frames_drawn = 0;
uint32_t _frame_delay = 0;
uint64_t _frame_ticks = 0;
double _process_step = 0;
int ips = 60;
double physics_jitter_fix = 0.5;
double _fps = 1;
int _max_fps = 0;
int _audio_output_latency = 0;
double _time_scale = 1.0;
uint64_t _physics_frames = 0;
int max_physics_steps_per_frame = 8;
double _physics_interpolation_fraction = 0.0f;
bool abort_on_gpu_errors = false;
bool use_validation_layers = false;
bool generate_spirv_debug_info = false;
bool extra_gpu_memory_tracking = false;
#if defined(DEBUG_ENABLED) || defined(DEV_ENABLED)
bool accurate_breadcrumbs = false;
#endif
int32_t gpu_idx = -1;
uint64_t _process_frames = 0;
bool _in_physics = false;
List<Singleton> singletons;
HashMap<StringName, Object *> singleton_ptrs;
bool editor_hint = false;
bool project_manager_hint = false;
bool extension_reloading = false;
bool embedded_in_editor = false;
bool recovery_mode_hint = false;
bool _print_header = true;
static inline Engine *singleton = nullptr;
String write_movie_path;
String shader_cache_path;
static constexpr int SERVER_SYNC_FRAME_COUNT_WARNING = 5;
int server_syncs = 0;
bool frame_server_synced = false;
bool freeze_time_scale = false;
public:
static Engine *get_singleton();
virtual void set_physics_ticks_per_second(int p_ips);
virtual int get_physics_ticks_per_second() const;
virtual void set_max_physics_steps_per_frame(int p_max_physics_steps);
virtual int get_max_physics_steps_per_frame() const;
void set_physics_jitter_fix(double p_threshold);
double get_physics_jitter_fix() const;
virtual void set_max_fps(int p_fps);
virtual int get_max_fps() const;
virtual void set_audio_output_latency(int p_msec);
virtual int get_audio_output_latency() const;
|
random
|
<|fim_prefix|> char *result = new char[total_length];
char *ptr = result;
for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
// Process the current word.
if (word->unlv_crunch_mode != CR_NONE) {
if (word->unlv_crunch_mode != CR_DELETE &&
(!tilde_crunch_written ||
(word->unlv_crunch_mode == CR_KEEP_SPACE && word->word->space() > 0 &&
!word->word->flag(W_FUZZY_NON) && !word->word->flag(W_FUZZY_SP)))) {
if (!word->word->flag(W_BOL) && word->word->space() > 0 && !word->word->flag(W_FUZZY_NON) &&
!word->word->flag(W_FUZZY_SP)) {
/* Write a space to separate from preceding good text */
*ptr++ = ' ';
last_char_was_tilde = false;
}
if (!last_char_was_tilde) {
// Write a reject char.
last_char_was_tilde = true;
*ptr++ = kUNLVReject;
tilde_crunch_written = true;
last_char_was_newline = false;
}
}
} else {
// NORMAL PROCESSING of non tilde crunched words.
tilde_crunch_written = false;
tesseract_->set_unlv_suspects(word);
const char *wordstr = word->best_choice->unichar_string().c_str();
const auto &lengths = word->best_choice->unichar_lengths();
int length = lengths.length();
int i = 0;
int offset = 0;
if (last_char_was_tilde && word->word->space() == 0 && wordstr[offset] == ' ') {
// Prevent adjacent tilde across words - we know that adjacent tildes
// within words have been removed.
// Skip the first character.
offset = lengths[i++];
}
if (i < length && wordstr[offset] != 0) {
if (!last_char_was_newline) {
*ptr++ = ' ';
} else {
last_char_was_newline = false;
}
for (; i < length; offset += lengths[i++]) {
if (wordstr[offset] == ' ' || wordstr[offset] == kTesseractReject) <|fim_suffix|> else {
if (word->reject_map[i].rejected()) {
*ptr++ = kUNLVSuspect;
}
UNICHAR ch(wordstr + offset, lengths[i]);
int uni_ch = ch.first_uni();
for (int j = 0; kUniChs[j] != 0; ++j) {
if (kUniChs[j] == uni_ch) {
uni_ch = kLatinChs[j];
break;
}
}
if (uni_ch <= 0xff) {
*ptr++ = static_cast<char>(uni_ch);
last_char_was_tilde = false;
} else {
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
}
}
}
}
}
if (word->word->flag(W_EOL) && !last_char_was_newline) {
/* Add a new line output */
*ptr++ = '\n';
tilde_crunch_written = false;
last_char_was_newline = true;
last_char_was_tilde = false;
}
}
*ptr++ = '\n';
*ptr = '\0';
return result;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
* Detect the orientation of the input image and apparent script (alphabet).
* orient_deg is the detected clockwise rotation of the input image in degrees
* (0, 90, 180, 270)
* orient_conf is the confidence (15.0 is reasonably confident)
* script_name is an ASCII string, the name of the script, e.g. "Latin"
* script_conf is confidence level in the script
* Returns true on success and writes values to each parameter as an output
*/
bool TessBaseAPI::DetectOrientationScript(int *orient_deg, float *orient_conf,
const char **script_name, float *script_conf) {
OSResults osr;
bool osd = DetectOS(&osr);
if (!osd) {
return false;
}
int orient_id = osr.best_result.orientation_id;
int script_id = osr.get_best_script(orient_id);
if (orient_conf) {
*orient_conf = osr.best_result.oconfidence;
}
if (orient_deg) {
*orient_deg = orient_id * 90; // convert quadrant to degrees
}
if (script_name) {
const char *script = osr.unich<|fim_middle|>{
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
}
|
char *result = new char[total_length];
char *ptr = result;
for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
// Process the current word.
if (word->unlv_crunch_mode != CR_NONE) {
if (word->unlv_crunch_mode != CR_DELETE &&
(!tilde_crunch_written ||
(word->unlv_crunch_mode == CR_KEEP_SPACE && word->word->space() > 0 &&
!word->word->flag(W_FUZZY_NON) && !word->word->flag(W_FUZZY_SP)))) {
if (!word->word->flag(W_BOL) && word->word->space() > 0 && !word->word->flag(W_FUZZY_NON) &&
!word->word->flag(W_FUZZY_SP)) {
/* Write a space to separate from preceding good text */
*ptr++ = ' ';
last_char_was_tilde = false;
}
if (!last_char_was_tilde) {
// Write a reject char.
last_char_was_tilde = true;
*ptr++ = kUNLVReject;
tilde_crunch_written = true;
last_char_was_newline = false;
}
}
} else {
// NORMAL PROCESSING of non tilde crunched words.
tilde_crunch_written = false;
tesseract_->set_unlv_suspects(word);
const char *wordstr = word->best_choice->unichar_string().c_str();
const auto &lengths = word->best_choice->unichar_lengths();
int length = lengths.length();
int i = 0;
int offset = 0;
if (last_char_was_tilde && word->word->space() == 0 && wordstr[offset] == ' ') {
// Prevent adjacent tilde across words - we know that adjacent tildes
// within words have been removed.
// Skip the first character.
offset = lengths[i++];
}
if (i < length && wordstr[offset] != 0) {
if (!last_char_was_newline) {
*ptr++ = ' ';
} else {
last_char_was_newline = false;
}
for (; i < length; offset += lengths[i++]) {
if (wordstr[offset] == ' ' || wordstr[offset] == kTesseractReject)
|
{
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
}
|
else {
if (word->reject_map[i].rejected()) {
*ptr++ = kUNLVSuspect;
}
UNICHAR ch(wordstr + offset, lengths[i]);
int uni_ch = ch.first_uni();
for (int j = 0; kUniChs[j] != 0; ++j) {
if (kUniChs[j] == uni_ch) {
uni_ch = kLatinChs[j];
break;
}
}
if (uni_ch <= 0xff) {
*ptr++ = static_cast<char>(uni_ch);
last_char_was_tilde = false;
} else {
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
}
}
}
}
}
if (word->word->flag(W_EOL) && !last_char_was_newline) {
/* Add a new line output */
*ptr++ = '\n';
tilde_crunch_written = false;
last_char_was_newline = true;
last_char_was_tilde = false;
}
}
*ptr++ = '\n';
*ptr = '\0';
return result;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
* Detect the orientation of the input image and apparent script (alphabet).
* orient_deg is the detected clockwise rotation of the input image in degrees
* (0, 90, 180, 270)
* orient_conf is the confidence (15.0 is reasonably confident)
* script_name is an ASCII string, the name of the script, e.g. "Latin"
* script_conf is confidence level in the script
* Returns true on success and writes values to each parameter as an output
*/
bool TessBaseAPI::DetectOrientationScript(int *orient_deg, float *orient_conf,
const char **script_name, float *script_conf) {
OSResults osr;
bool osd = DetectOS(&osr);
if (!osd) {
return false;
}
int orient_id = osr.best_result.orientation_id;
int script_id = osr.get_best_script(orient_id);
if (orient_conf) {
*orient_conf = osr.best_result.oconfidence;
}
if (orient_deg) {
*orient_deg = orient_id * 90; // convert quadrant to degrees
}
if (script_name) {
const char *script = osr.unich
|
ast_based
|
<|fim_prefix|>
// load and prepare entries for training
prepare_entries(params, ctx_train);
// we have to pretokenize everything because otherwise we don't know how much overhead to allocate ctx_diffs_wrapped
std::vector<tokenized_prompt> tokenized_prompts;
size_t n_total_tokens = 0;
for (size_t i = 0; i < ctx_train.positive_entries.size(); ++i) {
tokenized_prompt t(ctx, ctx_train.positive_entries[i], ctx_train.negative_entries[i]);
n_total_tokens += 2 * t.max_seq_len;
tokenized_prompts.push_back(std::move(t));
}
std::cout << "n_total_tokens: " << n_total_tokens << std::endl;
for(size_t i = 0; i < ctx_train.positive_entries.size(); ++i) {
bool success = false;
tokenized_prompt t = tokenized_prompts[i];
cb_data.n_layers = n_layers;
cb_data.n_tokens = t.max_seq_len;
printf("Evaluating prompt[%d/%d]: \"%s\" - \"%s\" (%d tokens)\n",
(int) i+1, (int) ctx_train.positive_entries.size(),
tokens_to_str(ctx, t.tokens_pos.cbegin(), t.tokens_pos.cend()).c_str(),
tokens_to_str(ctx, t.tokens_neg.cbegin(), t.tokens_neg.cend()).c_str(),
(int) t.max_seq_len);
cb_data.is_eval_pos = true;
success = get_hidden_layers(ctx, t.tokens_pos);
if (!success) break;
cb_data.is_eval_pos = false;
success = get_hidden_layers(ctx, t.tokens_neg);
if (!success) break;
// calculate diff and remove all zero rows
auto v_diff_filtered = cb_data.calc_diff();
// save & concat the filtered v_diff to ctx_train
ctx_train.concat_diff_tmp(v_diff_filtered);
// reset for next iteration
cb_data.reset();
}
// done with the model, we can now free it to make gain some memory
printf("Done evaluate prompts, unload model...\n");
bool use_pca = params.cvector_dimre_method == DIMRE_METHOD_PCA;
// prepare ctx_train for PCA
ctx_train.build_v_diff(use_pca);
<|fim_suffix|> else {
// run mean
mean::run(ctx_train.v_diff, ctx_train.v_final);
}
// write output vectors to gguf
export_gguf(ctx_train.v_final, params.out_file, model_hint);
llama_backend_free();
return 0;
}
<|fim_middle|>if (use_pca) {
// run PCA
PCA::pca_params pca_params;
pca_params.n_threads = params.cpuparams.n_threads;
pca_params.n_batch = params.n_pca_batch;
pca_params.n_iterations = params.n_pca_iterations;
PCA::run_pca(pca_params, ctx_train.v_diff, ctx_train.v_final);
}
|
// load and prepare entries for training
prepare_entries(params, ctx_train);
// we have to pretokenize everything because otherwise we don't know how much overhead to allocate ctx_diffs_wrapped
std::vector<tokenized_prompt> tokenized_prompts;
size_t n_total_tokens = 0;
for (size_t i = 0; i < ctx_train.positive_entries.size(); ++i) {
tokenized_prompt t(ctx, ctx_train.positive_entries[i], ctx_train.negative_entries[i]);
n_total_tokens += 2 * t.max_seq_len;
tokenized_prompts.push_back(std::move(t));
}
std::cout << "n_total_tokens: " << n_total_tokens << std::endl;
for(size_t i = 0; i < ctx_train.positive_entries.size(); ++i) {
bool success = false;
tokenized_prompt t = tokenized_prompts[i];
cb_data.n_layers = n_layers;
cb_data.n_tokens = t.max_seq_len;
printf("Evaluating prompt[%d/%d]: \"%s\" - \"%s\" (%d tokens)\n",
(int) i+1, (int) ctx_train.positive_entries.size(),
tokens_to_str(ctx, t.tokens_pos.cbegin(), t.tokens_pos.cend()).c_str(),
tokens_to_str(ctx, t.tokens_neg.cbegin(), t.tokens_neg.cend()).c_str(),
(int) t.max_seq_len);
cb_data.is_eval_pos = true;
success = get_hidden_layers(ctx, t.tokens_pos);
if (!success) break;
cb_data.is_eval_pos = false;
success = get_hidden_layers(ctx, t.tokens_neg);
if (!success) break;
// calculate diff and remove all zero rows
auto v_diff_filtered = cb_data.calc_diff();
// save & concat the filtered v_diff to ctx_train
ctx_train.concat_diff_tmp(v_diff_filtered);
// reset for next iteration
cb_data.reset();
}
// done with the model, we can now free it to make gain some memory
printf("Done evaluate prompts, unload model...\n");
bool use_pca = params.cvector_dimre_method == DIMRE_METHOD_PCA;
// prepare ctx_train for PCA
ctx_train.build_v_diff(use_pca);
|
if (use_pca) {
// run PCA
PCA::pca_params pca_params;
pca_params.n_threads = params.cpuparams.n_threads;
pca_params.n_batch = params.n_pca_batch;
pca_params.n_iterations = params.n_pca_iterations;
PCA::run_pca(pca_params, ctx_train.v_diff, ctx_train.v_final);
}
|
else {
// run mean
mean::run(ctx_train.v_diff, ctx_train.v_final);
}
// write output vectors to gguf
export_gguf(ctx_train.v_final, params.out_file, model_hint);
llama_backend_free();
return 0;
}
|
ast_based
|
<|fim_prefix|>rd = page_res_it.word();
WERD_CHOICE *choice = word->best_choice;
if (choice != nullptr) {
total_blobs += choice->length() + 2;
total_length += choice->unichar_string().length() + 2;
for (int i = 0; i < word->reject_map.length(); ++i) {
if (word->reject_map[i].rejected()) {
++total_length;
}
}
}
}
if (blob_count != nullptr) {
*blob_count = total_blobs;
}
return total_length;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
* Estimates the Orientation And Script of the image.
* Returns true if the image was processed successfully.
*/
bool TessBaseAPI::DetectOS(OSResults *osr) {
if (tesseract_ == nullptr) {
return false;
}
ClearResults();
if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
return false;
}
if (input_file_.empty()) {
input_file_ = kInputFile;
}
return orientation_and_script_detection(input_file_.c_str(), osr, tesseract_) > 0;
}
#endif // #ifndef DISABLED_LEGACY_ENGINE
void TessBaseAPI::set_min_orientation_margin(double margin) {
tesseract_->min_orientation_margin.set_value(margin);
}
/**
* Return text orientation of each block as determined in an earlier page layout
* analysis operation. Orientation is returned as the number of ccw 90-degree
* rotations (in [0..3]) required to make the text in the block upright
* (readable). Note that this may not necessary be the block orientation
* preferred for recognition (such as the case of vertical CJK text).
*
* Also returns whether the text in the block is believed to have vertical
* writing direction (when in an upright page orientation).
*
* The returned array is of length equal to the number of text blocks, which may
* be less than the total number of blocks. The ordering is intended to be
* consistent with GetTextLines().
*/
void TessBaseAPI::GetBlockTextOrientations(int **block_orientation, bool **vertical_writing) {
delete[] * block_orientation;
<|fim_suffix|>;
delete[] * vertical_writing;
*vertical_writing = nullptr;
BLOCK_IT block_it(block_list_);
block_it.move_to_first();
int num_blocks = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
++num_blocks;
}
if (!num_blocks) {
tprintf("WARNING: Found no blocks\n");
return;
}
*block_orientation = new int[num_blocks];
*vertical_writing = new bool[num_blocks];
block_it.move_to_first();
int i = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
FCOORD re_rotation = block_it.data()->re_rotation();
float re_theta = re_rotation.angle();
FCOORD classify_rotation = block_it.data()->classify_rotation();
float classify_theta = classify_rotation.angle();
double rot_theta = -(re_theta - classify_theta) * 2.0 / M_PI;
if (rot_theta < 0) {
rot_theta += 4;
}
int num_rotations = static_cast<int>(rot_theta + 0.5);
(*block_orientation)[i] = num_rotations;
// The classify_rotation is non-zero only if the text has vertical
// writing direction.
(*vertical_writing)[i] = classify_rotation.y() != 0.0f;
++i;
}
}
void TessBaseAPI::DetectParagraphs(bool after_text_recognition) {
int debug_level = 0;
GetIntVariable("paragraph_debug_level", &debug_level);
if (paragraph_models_ == nullptr) {
paragraph_models_ = new std::vector<ParagraphModel *>;
}
MutableIterator *result_it = GetMutableIterator();
do { // Detect paragraphs for this block
std::vector<ParagraphModel *> models;
::tesseract::DetectParagraphs(debug_level, after_text_recognition, result_it, &models);
paragraph_models_->insert(paragraph_models_->end(), models.begin(), models.end());
} while (result_it->Next(RIL_BLOCK));
delete result_it;
}
/** This method returns the string form of the specifie<|fim_middle|>*block_orientation = nullptr
|
rd = page_res_it.word();
WERD_CHOICE *choice = word->best_choice;
if (choice != nullptr) {
total_blobs += choice->length() + 2;
total_length += choice->unichar_string().length() + 2;
for (int i = 0; i < word->reject_map.length(); ++i) {
if (word->reject_map[i].rejected()) {
++total_length;
}
}
}
}
if (blob_count != nullptr) {
*blob_count = total_blobs;
}
return total_length;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
* Estimates the Orientation And Script of the image.
* Returns true if the image was processed successfully.
*/
bool TessBaseAPI::DetectOS(OSResults *osr) {
if (tesseract_ == nullptr) {
return false;
}
ClearResults();
if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
return false;
}
if (input_file_.empty()) {
input_file_ = kInputFile;
}
return orientation_and_script_detection(input_file_.c_str(), osr, tesseract_) > 0;
}
#endif // #ifndef DISABLED_LEGACY_ENGINE
void TessBaseAPI::set_min_orientation_margin(double margin) {
tesseract_->min_orientation_margin.set_value(margin);
}
/**
* Return text orientation of each block as determined in an earlier page layout
* analysis operation. Orientation is returned as the number of ccw 90-degree
* rotations (in [0..3]) required to make the text in the block upright
* (readable). Note that this may not necessary be the block orientation
* preferred for recognition (such as the case of vertical CJK text).
*
* Also returns whether the text in the block is believed to have vertical
* writing direction (when in an upright page orientation).
*
* The returned array is of length equal to the number of text blocks, which may
* be less than the total number of blocks. The ordering is intended to be
* consistent with GetTextLines().
*/
void TessBaseAPI::GetBlockTextOrientations(int **block_orientation, bool **vertical_writing) {
delete[] * block_orientation;
|
*block_orientation = nullptr
|
;
delete[] * vertical_writing;
*vertical_writing = nullptr;
BLOCK_IT block_it(block_list_);
block_it.move_to_first();
int num_blocks = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
++num_blocks;
}
if (!num_blocks) {
tprintf("WARNING: Found no blocks\n");
return;
}
*block_orientation = new int[num_blocks];
*vertical_writing = new bool[num_blocks];
block_it.move_to_first();
int i = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
FCOORD re_rotation = block_it.data()->re_rotation();
float re_theta = re_rotation.angle();
FCOORD classify_rotation = block_it.data()->classify_rotation();
float classify_theta = classify_rotation.angle();
double rot_theta = -(re_theta - classify_theta) * 2.0 / M_PI;
if (rot_theta < 0) {
rot_theta += 4;
}
int num_rotations = static_cast<int>(rot_theta + 0.5);
(*block_orientation)[i] = num_rotations;
// The classify_rotation is non-zero only if the text has vertical
// writing direction.
(*vertical_writing)[i] = classify_rotation.y() != 0.0f;
++i;
}
}
void TessBaseAPI::DetectParagraphs(bool after_text_recognition) {
int debug_level = 0;
GetIntVariable("paragraph_debug_level", &debug_level);
if (paragraph_models_ == nullptr) {
paragraph_models_ = new std::vector<ParagraphModel *>;
}
MutableIterator *result_it = GetMutableIterator();
do { // Detect paragraphs for this block
std::vector<ParagraphModel *> models;
::tesseract::DetectParagraphs(debug_level, after_text_recognition, result_it, &models);
paragraph_models_->insert(paragraph_models_->end(), models.begin(), models.end());
} while (result_it->Next(RIL_BLOCK));
delete result_it;
}
/** This method returns the string form of the specifie
|
ast_based
|
<|fim_prefix|>ility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_description.is_empty()) {
accesskit_node_set_description(ae->node, p_description.utf8().ptr());
} else {
accesskit_node_clear_description(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_value(const RID &p_id, const String &p_value) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_value.is_empty()) {
Vector<uint8_t> ch_length;
accesskit_node_set_value(ae->node, p_value.utf8(&ch_length).ptr());
accesskit_node_set_character_lengths(ae->node, ch_length.size(), ch_length.ptr());
} else {
accesskit_node_clear_value(ae->node);
accesskit_node_clear_character_lengths(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_tooltip(const RID &p_id, const String &p_tooltip) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_tooltip.is_empty()) {
accesskit_node_set_tooltip(ae->node, p_tooltip.utf8().ptr());
} else {
accesskit_node_clear_tooltip(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_bounds(const RID &p_id, const Rect2 &p_rect) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_rect rect;
rect.x0 = p_rect.position.x;
rect.y0 = p_rect.position.y;
<|fim_suffix|>
}
void AccessibilityDriverAccessKit::accessibility_update_set_transform(const RID &p_id, const Transform2D &p_transform) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_affine transform = { p_transform.columns[0][0], p_transform.columns[0][1], p_transform.columns[1][0], p_transform.columns[1][1], p_transform.columns[2][0], p_transform.columns[2][1] };
accesskit_node_set_transform(ae->node, transform);
}
void AccessibilityDriverAccessKit::accessibility_update_add_child(const RID &p_id, const RID &p_child_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_child_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_child(ae->node, (accesskit_node_id)p_child_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_controls(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_controlled(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_details(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessi<|fim_middle|>rect.x1 = p_rect.position.x + p_rect.size.x;
rect.y1 = p_rect.position.y + p_rect.size.y;
accesskit_node_set_bounds(ae->node, rect);
|
ility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_description.is_empty()) {
accesskit_node_set_description(ae->node, p_description.utf8().ptr());
} else {
accesskit_node_clear_description(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_value(const RID &p_id, const String &p_value) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_value.is_empty()) {
Vector<uint8_t> ch_length;
accesskit_node_set_value(ae->node, p_value.utf8(&ch_length).ptr());
accesskit_node_set_character_lengths(ae->node, ch_length.size(), ch_length.ptr());
} else {
accesskit_node_clear_value(ae->node);
accesskit_node_clear_character_lengths(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_tooltip(const RID &p_id, const String &p_tooltip) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_tooltip.is_empty()) {
accesskit_node_set_tooltip(ae->node, p_tooltip.utf8().ptr());
} else {
accesskit_node_clear_tooltip(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_bounds(const RID &p_id, const Rect2 &p_rect) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_rect rect;
rect.x0 = p_rect.position.x;
rect.y0 = p_rect.position.y;
|
rect.x1 = p_rect.position.x + p_rect.size.x;
rect.y1 = p_rect.position.y + p_rect.size.y;
accesskit_node_set_bounds(ae->node, rect);
|
}
void AccessibilityDriverAccessKit::accessibility_update_set_transform(const RID &p_id, const Transform2D &p_transform) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_affine transform = { p_transform.columns[0][0], p_transform.columns[0][1], p_transform.columns[1][0], p_transform.columns[1][1], p_transform.columns[2][0], p_transform.columns[2][1] };
accesskit_node_set_transform(ae->node, transform);
}
void AccessibilityDriverAccessKit::accessibility_update_add_child(const RID &p_id, const RID &p_child_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_child_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_child(ae->node, (accesskit_node_id)p_child_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_controls(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_controlled(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_add_related_details(const RID &p_id, const RID &p_related_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessi
|
ast_based
|
<|fim_prefix|>
int moving_handle = 0; //0 no move -1 or +1 out, 2 both (drawing only)
int moving_handle_key = 0;
int moving_handle_track = 0;
Vector2 moving_handle_left;
Vector2 moving_handle_right;
int moving_handle_mode = 0; // value from Animation::HandleMode
struct PairHasher {
static _FORCE_INLINE_ uint32_t hash(const Pair<int, int> &p_value) {
int32_t hash = 23;
hash = hash * 31 * hash_one_uint64(p_value.first);
hash = hash * 31 * hash_one_uint64(p_value.second);
return hash;
}
};
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_lefts;
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_rights;
void _clear_selection();
void _clear_selection_for_anim(const Ref<Animation> &p_anim);
void _select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single);
bool _try_select_at_ui_pos(const Point2 &p_pos, bool p_aggregate, bool p_deselectable);
void _change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto = false);
Vector2 menu_insert_key;
struct AnimMoveRestore {
int track = 0;
double time = 0;
Variant key;
real_t transition = 0;
};
AnimationTrackEditor *editor = nullptr;
struct EditPoint {
Rect2 point_rect;
Rect2 in_rect;
Rect2 out_rect;
int track = 0;
int key = 0;
};
Vector<EditPoint> edit_points;
struct PairCompare {
bool operator()(const IntPair &lh, const IntPair &rh) {
if (lh.first == rh.first) {
return lh.second < rh.second;
} else {
return lh.first < rh.first;
}
}
};
typedef RBSet<IntPair, PairCompare> SelectionSet;
SelectionSet selection;
Ref<ViewPanner> panner;
void _pan_callback(Vector2 p_scroll_vec, Ref<InputEvent> p_event);
void _zoom_callback(float p_zoom_factor, Vector2 p_origin, Ref<InputEvent> p_event);
void _draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right);
void _draw_track(int p_track, const Color &p_color);
<|fim_suffix|> void _notification(int p_what);
public:
static float get_bezier_key_value(Array p_bezier_key_array);
virtual String get_tooltip(const Point2 &p_pos) const override;
Ref<Animation> get_animation() const;
void set_animation_and_track(const Ref<Animation> &p_animation, int p_track, bool p_read_only);
virtual Size2 get_minimum_size() const override;
virtual CursorShape get_cursor_shape(const Point2 &p_pos) const override;
void set_timeline(AnimationTimelineEdit *p_timeline);
void set_editor(AnimationTrackEditor *p_editor);
void set_root(Node *p_root);
void set_filtered(bool p_filtered);
void auto_fit_vertically();
void set_play_position(real_t p_pos);
void update_play_position();
void duplicate_selected_keys(real_t p_ofs, bool p_ofs_valid);
void copy_selected_keys(bool p_cut);
void paste_keys(real_t p_ofs, bool p_ofs_valid);
void delete_selection();
void _bezier_track_insert_key_at_anim(const Ref<Animation> &p_anim, int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const Animation::HandleMode p_handle_mode, Animation::HandleSetMode p_handle_set_mode = Animation::HANDLE_SET_MODE_NONE);
AnimationBezierTrackEdit();
};
<|fim_middle|> float _bezier_h_to_pixel(float p_h);
void _zoom_vertically(real_t p_minimum_value, real_t p_maximum_value);
protected:
static void _bind_methods();
|
int moving_handle = 0; //0 no move -1 or +1 out, 2 both (drawing only)
int moving_handle_key = 0;
int moving_handle_track = 0;
Vector2 moving_handle_left;
Vector2 moving_handle_right;
int moving_handle_mode = 0; // value from Animation::HandleMode
struct PairHasher {
static _FORCE_INLINE_ uint32_t hash(const Pair<int, int> &p_value) {
int32_t hash = 23;
hash = hash * 31 * hash_one_uint64(p_value.first);
hash = hash * 31 * hash_one_uint64(p_value.second);
return hash;
}
};
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_lefts;
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_rights;
void _clear_selection();
void _clear_selection_for_anim(const Ref<Animation> &p_anim);
void _select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single);
bool _try_select_at_ui_pos(const Point2 &p_pos, bool p_aggregate, bool p_deselectable);
void _change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto = false);
Vector2 menu_insert_key;
struct AnimMoveRestore {
int track = 0;
double time = 0;
Variant key;
real_t transition = 0;
};
AnimationTrackEditor *editor = nullptr;
struct EditPoint {
Rect2 point_rect;
Rect2 in_rect;
Rect2 out_rect;
int track = 0;
int key = 0;
};
Vector<EditPoint> edit_points;
struct PairCompare {
bool operator()(const IntPair &lh, const IntPair &rh) {
if (lh.first == rh.first) {
return lh.second < rh.second;
} else {
return lh.first < rh.first;
}
}
};
typedef RBSet<IntPair, PairCompare> SelectionSet;
SelectionSet selection;
Ref<ViewPanner> panner;
void _pan_callback(Vector2 p_scroll_vec, Ref<InputEvent> p_event);
void _zoom_callback(float p_zoom_factor, Vector2 p_origin, Ref<InputEvent> p_event);
void _draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right);
void _draw_track(int p_track, const Color &p_color);
|
float _bezier_h_to_pixel(float p_h);
void _zoom_vertically(real_t p_minimum_value, real_t p_maximum_value);
protected:
static void _bind_methods();
|
void _notification(int p_what);
public:
static float get_bezier_key_value(Array p_bezier_key_array);
virtual String get_tooltip(const Point2 &p_pos) const override;
Ref<Animation> get_animation() const;
void set_animation_and_track(const Ref<Animation> &p_animation, int p_track, bool p_read_only);
virtual Size2 get_minimum_size() const override;
virtual CursorShape get_cursor_shape(const Point2 &p_pos) const override;
void set_timeline(AnimationTimelineEdit *p_timeline);
void set_editor(AnimationTrackEditor *p_editor);
void set_root(Node *p_root);
void set_filtered(bool p_filtered);
void auto_fit_vertically();
void set_play_position(real_t p_pos);
void update_play_position();
void duplicate_selected_keys(real_t p_ofs, bool p_ofs_valid);
void copy_selected_keys(bool p_cut);
void paste_keys(real_t p_ofs, bool p_ofs_valid);
void delete_selection();
void _bezier_track_insert_key_at_anim(const Ref<Animation> &p_anim, int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const Animation::HandleMode p_handle_mode, Animation::HandleSetMode p_handle_set_mode = Animation::HANDLE_SET_MODE_NONE);
AnimationBezierTrackEdit();
};
|
random
|
<|fim_prefix|>].out_rect.has_point(mb->get_position())) {
moving_handle = 1;
moving_handle_key = edit_points[i].key;
moving_handle_track = edit_points[i].track;
moving_handle_left = animation->bezier_track_get_key_in_handle(edit_points[i].track, edit_points[i].key);
moving_handle_right = animation->bezier_track_get_key_out_handle(edit_points[i].track, edit_points[i].key);
queue_redraw();
return;
}
}
}
// Box scaling/movement.
if (inside_selection_handles_rect) {
const Vector2i rel_pos = mb->get_position() - selection_rect.position;
scaling_selection_handles = Vector2i();
// Check which scaling handles are available.
if (selection_rect.size.width > CMP_EPSILON) {
if (rel_pos.x <= 0) {
scaling_selection_handles.x = -1;
} else if (rel_pos.x >= selection_rect.size.width) {
scaling_selection_handles.x = 1;
}
}
if (selection_rect.size.height > CMP_EPSILON) {
if (rel_pos.y <= 0) {
scaling_selection_handles.y = -1;
} else if (rel_pos.y >= selection_rect.size.height) {
scaling_selection_handles.y = 1;
}
}
if (scaling_selection_handles != Vector2i()) {
scaling_selection = true;
const float time = ((selection_rect.position.x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
const float h = (get_size().height / 2.0 - selection_rect.position.y) * timeline_v_zoom + timeline_v_scroll;
scaling_selection_pivot = Point2(time, h);
return;
}
// If not scaling, that means we're moving.
moving_selection_attempt = true;
moving_selection = false;
moving_selection_mouse_begin = mb->get_position();
// The pivot will be from the mouse click location, not a specific key.
moving_selection_from_key = -1;
moving_selection_from_track = selected_track;
moving_selection_offset = Vector2();
select_single_attempt = IntPair(-1, -1);
return;
}
// Insert new point.
if (mb->get_position().x >= limit && mb->get_position().x < <|fim_suffix|>.width && mb->is_command_or_control_pressed()) {
float h = (get_size().height / 2.0 - mb->get_position().y) * timeline_v_zoom + timeline_v_scroll;
Array new_point = animation->make_default_bezier_key(h);
real_t time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
while (animation->track_find_key(selected_track, time, Animation::FIND_MODE_APPROX) != -1) {
time += 0.0001;
}
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Add Bezier Point"));
undo_redo->add_do_method(animation.ptr(), "bezier_track_insert_key", selected_track, time, new_point[0], Vector2(new_point[1], new_point[2]), Vector2(new_point[3], new_point[4]));
undo_redo->add_do_method(editor, "_bezier_track_set_key_handle_mode_at_time", animation.ptr(), selected_track, time, (Animation::HandleMode)editor->bezier_key_mode->get_selected_id(), Animation::HANDLE_SET_MODE_AUTO);
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", selected_track, time);
undo_redo->commit_action();
// Then attempt to move.
int index = animation->track_find_key(selected_track, time, Animation::FIND_MODE_APPROX);
ERR_FAIL_COND(index == -1);
_clear_selection();
_select_at_anim(animation, selected_track, animation->track_get_key_time(selected_track, index), true);
moving_selection_attempt = true;
moving_inserted_key = true;
moving_selection = false;
moving_selection_mouse_begin = mb->get_position();
moving_selection_from_key = index;
moving_selection_from_track = selected_track;
moving_selection_offset = Vector2();
select_single_attempt = IntPair(-1, -1);
queue_redraw();
return;
}
// Box select.
if (mb->get_position().x >= limit && mb->get_position().x < get_size().width) {
box_selecting_attempt = true;
box_selecting = false;
box_selecting_add = false;
box_selection_from = mb->get_position();
return;
}
}
if (b<|fim_middle|>get_size()
|
].out_rect.has_point(mb->get_position())) {
moving_handle = 1;
moving_handle_key = edit_points[i].key;
moving_handle_track = edit_points[i].track;
moving_handle_left = animation->bezier_track_get_key_in_handle(edit_points[i].track, edit_points[i].key);
moving_handle_right = animation->bezier_track_get_key_out_handle(edit_points[i].track, edit_points[i].key);
queue_redraw();
return;
}
}
}
// Box scaling/movement.
if (inside_selection_handles_rect) {
const Vector2i rel_pos = mb->get_position() - selection_rect.position;
scaling_selection_handles = Vector2i();
// Check which scaling handles are available.
if (selection_rect.size.width > CMP_EPSILON) {
if (rel_pos.x <= 0) {
scaling_selection_handles.x = -1;
} else if (rel_pos.x >= selection_rect.size.width) {
scaling_selection_handles.x = 1;
}
}
if (selection_rect.size.height > CMP_EPSILON) {
if (rel_pos.y <= 0) {
scaling_selection_handles.y = -1;
} else if (rel_pos.y >= selection_rect.size.height) {
scaling_selection_handles.y = 1;
}
}
if (scaling_selection_handles != Vector2i()) {
scaling_selection = true;
const float time = ((selection_rect.position.x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
const float h = (get_size().height / 2.0 - selection_rect.position.y) * timeline_v_zoom + timeline_v_scroll;
scaling_selection_pivot = Point2(time, h);
return;
}
// If not scaling, that means we're moving.
moving_selection_attempt = true;
moving_selection = false;
moving_selection_mouse_begin = mb->get_position();
// The pivot will be from the mouse click location, not a specific key.
moving_selection_from_key = -1;
moving_selection_from_track = selected_track;
moving_selection_offset = Vector2();
select_single_attempt = IntPair(-1, -1);
return;
}
// Insert new point.
if (mb->get_position().x >= limit && mb->get_position().x <
|
get_size()
|
.width && mb->is_command_or_control_pressed()) {
float h = (get_size().height / 2.0 - mb->get_position().y) * timeline_v_zoom + timeline_v_scroll;
Array new_point = animation->make_default_bezier_key(h);
real_t time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value();
while (animation->track_find_key(selected_track, time, Animation::FIND_MODE_APPROX) != -1) {
time += 0.0001;
}
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Add Bezier Point"));
undo_redo->add_do_method(animation.ptr(), "bezier_track_insert_key", selected_track, time, new_point[0], Vector2(new_point[1], new_point[2]), Vector2(new_point[3], new_point[4]));
undo_redo->add_do_method(editor, "_bezier_track_set_key_handle_mode_at_time", animation.ptr(), selected_track, time, (Animation::HandleMode)editor->bezier_key_mode->get_selected_id(), Animation::HANDLE_SET_MODE_AUTO);
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", selected_track, time);
undo_redo->commit_action();
// Then attempt to move.
int index = animation->track_find_key(selected_track, time, Animation::FIND_MODE_APPROX);
ERR_FAIL_COND(index == -1);
_clear_selection();
_select_at_anim(animation, selected_track, animation->track_get_key_time(selected_track, index), true);
moving_selection_attempt = true;
moving_inserted_key = true;
moving_selection = false;
moving_selection_mouse_begin = mb->get_position();
moving_selection_from_key = index;
moving_selection_from_track = selected_track;
moving_selection_offset = Vector2();
select_single_attempt = IntPair(-1, -1);
queue_redraw();
return;
}
// Box select.
if (mb->get_position().x >= limit && mb->get_position().x < get_size().width) {
box_selecting_attempt = true;
box_selecting = false;
box_selecting_add = false;
box_selection_from = mb->get_position();
return;
}
}
if (b
|
ast_based
|
<|fim_prefix|> ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_scroll_y(ae->node, p_position);
}
void AccessibilityDriverAccessKit::accessibility_update_set_scroll_y_range(const RID &p_id, double p_min, double p_max) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_scroll_y_min(ae->node, p_min);
accesskit_node_set_scroll_y_max(ae->node, p_max);
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_decorations(const RID &p_id, bool p_underline, bool p_strikethrough, bool p_overline) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (p_underline) {
accesskit_node_set_underline(ae->node, ACCESSKIT_TEXT_DECORATION_SOLID);
} else {
accesskit_node_clear_underline(ae->node);
}
if (p_overline) {
accesskit_node_set_overline(ae->node, ACCESSKIT_TEXT_DECORATION_SOLID);
} else {
accesskit_node_clear_overline(ae->node);
}
if (p_strikethrough) {
accesskit_node_set_strikethrough(ae->node, ACCESSKIT_TEXT_DECORATION_SOLID);
} else {
accesskit_node_clear_strikethrough(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_align(const RID &p_id, HorizontalAlignment p_align) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_align) {
case HORIZONTAL_ALIGNMENT_LEFT: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_LEFT);
} break;
case HORIZONTAL_ALIGNMENT_CENTER: {
<|fim_suffix|>
} break;
case HORIZONTAL_ALIGNMENT_RIGHT: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_CENTER);
} break;
case HORIZONTAL_ALIGNMENT_FILL: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_JUSTIFY);
} break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_selection(const RID &p_id, const RID &p_text_start_id, int p_start_char, const RID &p_text_end_id, int p_end_char) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *start_ae = rid_owner.get_or_null(p_text_start_id);
ERR_FAIL_NULL(start_ae);
ERR_FAIL_COND(start_ae->window_id != ae->window_id);
AccessibilityElement *end_ae = rid_owner.get_or_null(p_text_end_id);
ERR_FAIL_NULL(end_ae);
ERR_FAIL_COND(end_ae->window_id != ae->window_id);
int start_pos = p_start_char;
int end_pos = p_end_char;
RID start_rid;
RID end_rid;
for (const RID &rid : start_ae->children) {
const AccessibilityElement *child_ae = rid_owner.get_or_null(rid);
if (child_ae && child_ae->role == ACCESSKIT_ROLE_TEXT_RUN) {
if (p_start_char >= child_ae->run.x && p_start_char <= child_ae->run.y) {
start_rid = rid;
start_pos = p_start_char - child_ae->run.x;
break;
}
}
}
for (const RID &rid : end_ae->children) {
const AccessibilityElement *child_ae = rid_owner.get_or_null(rid);
if (child_ae && child_ae->role == ACCESSKIT_ROLE_TEXT_RUN) {
if (p_end_char >= child_ae->run.x && p_end_char <= child_ae->run.y) {
end_rid = rid;
end_pos = p_end_char - child_ae->run.x;
break;
}
}
}
ERR_FAIL_COND(start_rid.is_null() && end_rid.is_null());
_ensure_node(p_id, ae);
accesskit_text_selection sel;
sel.anchor.node = (accesskit_node_id)start_rid.get_id();
sel.anchor.character_index = start_pos;
sel.focus.node = (accesskit_node_id)end_rid.get_i<|fim_middle|>accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_RIGHT);
|
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_scroll_y(ae->node, p_position);
}
void AccessibilityDriverAccessKit::accessibility_update_set_scroll_y_range(const RID &p_id, double p_min, double p_max) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_scroll_y_min(ae->node, p_min);
accesskit_node_set_scroll_y_max(ae->node, p_max);
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_decorations(const RID &p_id, bool p_underline, bool p_strikethrough, bool p_overline) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (p_underline) {
accesskit_node_set_underline(ae->node, ACCESSKIT_TEXT_DECORATION_SOLID);
} else {
accesskit_node_clear_underline(ae->node);
}
if (p_overline) {
accesskit_node_set_overline(ae->node, ACCESSKIT_TEXT_DECORATION_SOLID);
} else {
accesskit_node_clear_overline(ae->node);
}
if (p_strikethrough) {
accesskit_node_set_strikethrough(ae->node, ACCESSKIT_TEXT_DECORATION_SOLID);
} else {
accesskit_node_clear_strikethrough(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_align(const RID &p_id, HorizontalAlignment p_align) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_align) {
case HORIZONTAL_ALIGNMENT_LEFT: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_LEFT);
} break;
case HORIZONTAL_ALIGNMENT_CENTER: {
|
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_RIGHT);
|
} break;
case HORIZONTAL_ALIGNMENT_RIGHT: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_CENTER);
} break;
case HORIZONTAL_ALIGNMENT_FILL: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_JUSTIFY);
} break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_selection(const RID &p_id, const RID &p_text_start_id, int p_start_char, const RID &p_text_end_id, int p_end_char) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *start_ae = rid_owner.get_or_null(p_text_start_id);
ERR_FAIL_NULL(start_ae);
ERR_FAIL_COND(start_ae->window_id != ae->window_id);
AccessibilityElement *end_ae = rid_owner.get_or_null(p_text_end_id);
ERR_FAIL_NULL(end_ae);
ERR_FAIL_COND(end_ae->window_id != ae->window_id);
int start_pos = p_start_char;
int end_pos = p_end_char;
RID start_rid;
RID end_rid;
for (const RID &rid : start_ae->children) {
const AccessibilityElement *child_ae = rid_owner.get_or_null(rid);
if (child_ae && child_ae->role == ACCESSKIT_ROLE_TEXT_RUN) {
if (p_start_char >= child_ae->run.x && p_start_char <= child_ae->run.y) {
start_rid = rid;
start_pos = p_start_char - child_ae->run.x;
break;
}
}
}
for (const RID &rid : end_ae->children) {
const AccessibilityElement *child_ae = rid_owner.get_or_null(rid);
if (child_ae && child_ae->role == ACCESSKIT_ROLE_TEXT_RUN) {
if (p_end_char >= child_ae->run.x && p_end_char <= child_ae->run.y) {
end_rid = rid;
end_pos = p_end_char - child_ae->run.x;
break;
}
}
}
ERR_FAIL_COND(start_rid.is_null() && end_rid.is_null());
_ensure_node(p_id, ae);
accesskit_text_selection sel;
sel.anchor.node = (accesskit_node_id)start_rid.get_id();
sel.anchor.character_index = start_pos;
sel.focus.node = (accesskit_node_id)end_rid.get_i
|
ast_based
|
<|fim_prefix|> CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, String());
}
TEST_CASE("[ProjectSettings] Non existing setting is null") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
}
TEST_CASE("[ProjectSettings] Non existing setting should return default value") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting", "my_nice_default_value");
CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, "my_nice_default_value");
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
}
TEST_CASE("[ProjectSettings] Set value should be returned when retrieved") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("my_custom_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
ProjectSettings::get_singleton()->set_setting("my_custom_setting", true);
CHECK(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
variant = ProjectSettings::get_singleton()->get_setting("my_custom_setting");
CHECK_EQ(variant.get_type(), Variant::BOOL);
bool value = variant;
CHECK_EQ(true, value);
CHECK(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
}
TEST_CASE("[ProjectSettings] localize_path") {
String old_resource_path = TestProjectSettingsInternalsAccessor::resource_path();
TestProjectSettingsInternalsAccessor::resource_path() = DirAccess::create(DirAccess::ACCESS_FILESYSTEM)->get_current_dir();<|fim_suffix|>#ifdef WINDOWS_ENABLED
String root_path_win = ProjectSettings::get_singleton()->get_resource_path().replace_char('/', '\\');
#endif
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("filename"), "res://filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/something/../filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/./filename"), "res://path/filename");
#ifdef WINDOWS_ENABLED
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\something\\..\\filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\.\\filename"), "res://path/filename");
#endif
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("../filename"), "../filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("../path/filename"), "../path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("..\\path\\filename"), "../path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/filename"), "/testroot/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/path/filename"), "/testroot/path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/path/something/../filename"), "/testroot/path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/path/./filename"), "/testroot/path/filename");
#ifdef WINDOWS_ENABLED
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:/testroot/filename"), "C:/testroot/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:/testroot/path/filename"), "C:/testroot/path/filename");<|fim_middle|> String root_path = ProjectSettings::get_singleton()->get_resource_path();
|
CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, String());
}
TEST_CASE("[ProjectSettings] Non existing setting is null") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
}
TEST_CASE("[ProjectSettings] Non existing setting should return default value") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting", "my_nice_default_value");
CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, "my_nice_default_value");
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
}
TEST_CASE("[ProjectSettings] Set value should be returned when retrieved") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("my_custom_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
ProjectSettings::get_singleton()->set_setting("my_custom_setting", true);
CHECK(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
variant = ProjectSettings::get_singleton()->get_setting("my_custom_setting");
CHECK_EQ(variant.get_type(), Variant::BOOL);
bool value = variant;
CHECK_EQ(true, value);
CHECK(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
}
TEST_CASE("[ProjectSettings] localize_path") {
String old_resource_path = TestProjectSettingsInternalsAccessor::resource_path();
TestProjectSettingsInternalsAccessor::resource_path() = DirAccess::create(DirAccess::ACCESS_FILESYSTEM)->get_current_dir();
|
String root_path = ProjectSettings::get_singleton()->get_resource_path();
|
#ifdef WINDOWS_ENABLED
String root_path_win = ProjectSettings::get_singleton()->get_resource_path().replace_char('/', '\\');
#endif
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("filename"), "res://filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/something/../filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/./filename"), "res://path/filename");
#ifdef WINDOWS_ENABLED
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\something\\..\\filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\.\\filename"), "res://path/filename");
#endif
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("../filename"), "../filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("../path/filename"), "../path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("..\\path\\filename"), "../path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/filename"), "/testroot/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/path/filename"), "/testroot/path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/path/something/../filename"), "/testroot/path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/path/./filename"), "/testroot/path/filename");
#ifdef WINDOWS_ENABLED
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:/testroot/filename"), "C:/testroot/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:/testroot/path/filename"), "C:/testroot/path/filename");
|
random
|
<|fim_prefix|>
#include "animation_bezier_editor.h"
#include "editor/animation/animation_player_editor_plugin.h"
#include "editor/editor_node.h"
#include "editor/editor_string_names.h"
#include "editor/editor_undo_redo_manager.h"
#include "editor/gui/editor_spin_slider.h"
#include "editor/settings/editor_settings.h"
#include "editor/themes/editor_scale.h"
#include "scene/gui/option_button.h"
#include "scene/gui/view_panner.h"
#include "scene/resources/text_line.h"
#include <climits>
float AnimationBezierTrackEdit::_bezier_h_to_pixel(float p_h) {
float h = p_h;
h = (h - timeline_v_scroll) / timeline_v_zoom;
h = (get_size().height / 2.0) - h;
return h;
}
void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
float scale = timeline->get_zoom_scale();
int limit = timeline->get_name_limit();
int right_limit = get_size().width;
// Selection may have altered the order of keys.
RBMap<real_t, int> key_order;
for (int i = 0; i < animation->track_get_key_count(p_track); i++) {
real_t ofs = animation->track_get_key_time(p_track, i);
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
ofs += moving_selection_offset.x;
} else if (scaling_selection) {
ofs += -scaling_selection_offset.x + (ofs - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
}
}
key_order[ofs] = i;
}
for (RBMap<real_t, int>::Element *E = key_order.front(); E; E = E->next()) {
int i = E->get();
if (!E->next()) {
break;
}
int i_n = E->next()->get();
float offset = animation->track_get_key_time(p_track, i);
float height = animation->bezier_track_get_key_value(p_track, i);
Vector2 out_handle = animation->bezier_track_get_key_out_handle(p_track, i);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i) {
out_handle = moving_handle_right;
}
if (selection.has(IntPair(p_track, i))) {<|fim_suffix|> }
float offset_n = animation->track_get_key_time(p_track, i_n);
float height_n = animation->bezier_track_get_key_value(p_track, i_n);
Vector2 in_handle = animation->bezier_track_get_key_in_handle(p_track, i_n);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i_n) {
in_handle = moving_handle_left;
}
if (selection.has(IntPair(p_track, i_n))) {
if (moving_selection) {
offset_n += moving_selection_offset.x;
height_n += moving_selection_offset.y;
} else if (scaling_selection) {
offset_n += -scaling_selection_offset.x + (offset_n - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
height_n += -scaling_selection_offset.y + (height_n - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
if (moving_inserted_key && moving_selection_from_track == p_track) {
if (moving_selection_from_key == i) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(p_track, i);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
float offset_p = offset;
float height_p = height;
if (E->prev()) {
int i_p = E->prev()->get();
offset_p = animation->track_get_key_time(p_track, i_p);
height_p = animation->bezier_track_get_key_value(p_track, i_p);
}
animation->bezier_track_calculate_handles(offset, offset_p, height_p, offset_n, height_n, handle_mode, Animation::HANDLE_SET_MODE_AUTO, nullptr, &out_handle);
}
} else if (moving_selection_from_key == i_n) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(p_track, i_n);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
float offset_nn = offset_n;
float height_nn = height_n;
if (E->next()->next()) {
int i_nn = E->next()->next()->get();
offset_nn = animation->track_get_key_time(p_track, i_nn);
height_nn = animation->bezier_track_get_key_value(p_track, i_nn);
}
<|fim_middle|> if (moving_selection) {
offset += moving_selection_offset.x;
height += moving_selection_offset.y;
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
height += -scaling_selection_offset.y + (height - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
|
#include "animation_bezier_editor.h"
#include "editor/animation/animation_player_editor_plugin.h"
#include "editor/editor_node.h"
#include "editor/editor_string_names.h"
#include "editor/editor_undo_redo_manager.h"
#include "editor/gui/editor_spin_slider.h"
#include "editor/settings/editor_settings.h"
#include "editor/themes/editor_scale.h"
#include "scene/gui/option_button.h"
#include "scene/gui/view_panner.h"
#include "scene/resources/text_line.h"
#include <climits>
float AnimationBezierTrackEdit::_bezier_h_to_pixel(float p_h) {
float h = p_h;
h = (h - timeline_v_scroll) / timeline_v_zoom;
h = (get_size().height / 2.0) - h;
return h;
}
void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
float scale = timeline->get_zoom_scale();
int limit = timeline->get_name_limit();
int right_limit = get_size().width;
// Selection may have altered the order of keys.
RBMap<real_t, int> key_order;
for (int i = 0; i < animation->track_get_key_count(p_track); i++) {
real_t ofs = animation->track_get_key_time(p_track, i);
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
ofs += moving_selection_offset.x;
} else if (scaling_selection) {
ofs += -scaling_selection_offset.x + (ofs - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
}
}
key_order[ofs] = i;
}
for (RBMap<real_t, int>::Element *E = key_order.front(); E; E = E->next()) {
int i = E->get();
if (!E->next()) {
break;
}
int i_n = E->next()->get();
float offset = animation->track_get_key_time(p_track, i);
float height = animation->bezier_track_get_key_value(p_track, i);
Vector2 out_handle = animation->bezier_track_get_key_out_handle(p_track, i);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i) {
out_handle = moving_handle_right;
}
if (selection.has(IntPair(p_track, i))) {
|
if (moving_selection) {
offset += moving_selection_offset.x;
height += moving_selection_offset.y;
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
height += -scaling_selection_offset.y + (height - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
|
}
float offset_n = animation->track_get_key_time(p_track, i_n);
float height_n = animation->bezier_track_get_key_value(p_track, i_n);
Vector2 in_handle = animation->bezier_track_get_key_in_handle(p_track, i_n);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i_n) {
in_handle = moving_handle_left;
}
if (selection.has(IntPair(p_track, i_n))) {
if (moving_selection) {
offset_n += moving_selection_offset.x;
height_n += moving_selection_offset.y;
} else if (scaling_selection) {
offset_n += -scaling_selection_offset.x + (offset_n - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
height_n += -scaling_selection_offset.y + (height_n - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
if (moving_inserted_key && moving_selection_from_track == p_track) {
if (moving_selection_from_key == i) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(p_track, i);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
float offset_p = offset;
float height_p = height;
if (E->prev()) {
int i_p = E->prev()->get();
offset_p = animation->track_get_key_time(p_track, i_p);
height_p = animation->bezier_track_get_key_value(p_track, i_p);
}
animation->bezier_track_calculate_handles(offset, offset_p, height_p, offset_n, height_n, handle_mode, Animation::HANDLE_SET_MODE_AUTO, nullptr, &out_handle);
}
} else if (moving_selection_from_key == i_n) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(p_track, i_n);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
float offset_nn = offset_n;
float height_nn = height_n;
if (E->next()->next()) {
int i_nn = E->next()->next()->get();
offset_nn = animation->track_get_key_time(p_track, i_nn);
height_nn = animation->bezier_track_get_key_value(p_track, i_nn);
}
|
random
|
<|fim_prefix|>// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef CARBON_TOOLCHAIN_BASE_CANONICAL_VALUE_STORE_H_
#define CARBON_TOOLCHAIN_BASE_CANONICAL_VALUE_STORE_H_
#include "common/hashtable_key_context.h"
#include "common/set.h"
#include "toolchain/base/mem_usage.h"
#include "toolchain/base/value_store.h"
#include "toolchain/base/value_store_types.h"
#include "toolchain/base/yaml.h"
namespace Carbon {
// A wrapper for accumulating immutable values with deduplication, providing IDs
// to later retrieve the value.
//
// `ValueT` represents the type being stored.
//
// `KeyT` can optionally be different from `ValueT`, and if so is used for the
// argument to `Lookup`. It must be valid to use both `KeyT` and `ValueT` as
// lookup types in the underlying `Set`.
template <typename IdT, typename KeyT, typename ValueT = KeyT>
class CanonicalValueStore {
public:
using KeyType = std::remove_cvref_t<KeyT>;
using ValueType = ValueStoreTypes<ValueT>::ValueType;
using RefType = ValueStoreTypes<ValueT>::RefType;
using ConstRefType = ValueStoreTypes<ValueT>::ConstRefType;
// Stores a canonical copy of the value and returns an ID to reference it.
auto Add(ValueType value) -> IdT;
// Returns the value for an ID.
auto Get(IdT id) const -> ConstRefType { return values_.Get(id); }
// Looks up the canonical ID for a value, or returns `None` if not in the
// store.
auto Lookup(KeyType key) const -> IdT;
// Reserves space.
auto Reserve(size_t size) -> void;
// These are to support printable structures, and are not guaranteed.
auto OutputYaml() const -> Yaml::OutputMapping {
<|fim_suffix|>
}
auto values() const [[clang::lifetimebound]]
-> ValueStore<IdT, ValueType>::Range {
return values_.values();
}
auto size() const -> size_t { return values_.size(); }
// Collects memory usage of the values and deduplication set.
auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
-> void {
mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
auto bytes = set_.ComputeMetrics(KeyContext(&values_)).storage_bytes;
mem_usage.Add(MemUsage::ConcatLabel(label, "set_"), bytes, bytes);
}
private:
class KeyContext;
ValueStore<IdT, ValueType> values_;
Set<IdT, /*SmallSize=*/0, KeyContext> set_;
};
template <typename IdT, typename KeyT, typename ValueT>
class CanonicalValueStore<IdT, KeyT, ValueT>::KeyContext
: public TranslatingKeyContext<KeyContext> {
public:
explicit KeyContext(const ValueStore<IdT, ValueType>* values)
: values_(values) {}
// Note that it is safe to return a `const` reference here as the underlying
// object's lifetime is provided by the `ValueStore`.
auto TranslateKey(IdT id) const -> ConstRefType { return values_->Get(id); }
private:
const ValueStore<IdT, ValueType>* values_;
};
template <typename IdT, typename KeyT, typename ValueT>
auto CanonicalValueStore<IdT, KeyT, ValueT>::Add(ValueType value) -> IdT {
auto make_key = [&] { return IdT(values_.Add(std::move(value))); };
return set_.Insert(value, make_key, KeyContext(&values_)).key();
}
template <typename IdT, typename KeyT, typename ValueT>
auto CanonicalValueStore<IdT, KeyT, ValueT>::Lookup(KeyType key) const -> IdT {
if (auto result = set_.Lookup(key, KeyContext(&values_))) {
return result.key();
}
return IdT::None;
}
template <typename IdT, typename KeyT, typename ValueT>
auto CanonicalValueStore<IdT, KeyT, ValueT>::Reserve(size_t size) -> void {
// Compute the resulting new insert count using the size of values -- the
// set doesn't have a fast to compute current size.
<|fim_middle|>return values_.OutputYaml();
|
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef CARBON_TOOLCHAIN_BASE_CANONICAL_VALUE_STORE_H_
#define CARBON_TOOLCHAIN_BASE_CANONICAL_VALUE_STORE_H_
#include "common/hashtable_key_context.h"
#include "common/set.h"
#include "toolchain/base/mem_usage.h"
#include "toolchain/base/value_store.h"
#include "toolchain/base/value_store_types.h"
#include "toolchain/base/yaml.h"
namespace Carbon {
// A wrapper for accumulating immutable values with deduplication, providing IDs
// to later retrieve the value.
//
// `ValueT` represents the type being stored.
//
// `KeyT` can optionally be different from `ValueT`, and if so is used for the
// argument to `Lookup`. It must be valid to use both `KeyT` and `ValueT` as
// lookup types in the underlying `Set`.
template <typename IdT, typename KeyT, typename ValueT = KeyT>
class CanonicalValueStore {
public:
using KeyType = std::remove_cvref_t<KeyT>;
using ValueType = ValueStoreTypes<ValueT>::ValueType;
using RefType = ValueStoreTypes<ValueT>::RefType;
using ConstRefType = ValueStoreTypes<ValueT>::ConstRefType;
// Stores a canonical copy of the value and returns an ID to reference it.
auto Add(ValueType value) -> IdT;
// Returns the value for an ID.
auto Get(IdT id) const -> ConstRefType { return values_.Get(id); }
// Looks up the canonical ID for a value, or returns `None` if not in the
// store.
auto Lookup(KeyType key) const -> IdT;
// Reserves space.
auto Reserve(size_t size) -> void;
// These are to support printable structures, and are not guaranteed.
auto OutputYaml() const -> Yaml::OutputMapping {
|
return values_.OutputYaml();
|
}
auto values() const [[clang::lifetimebound]]
-> ValueStore<IdT, ValueType>::Range {
return values_.values();
}
auto size() const -> size_t { return values_.size(); }
// Collects memory usage of the values and deduplication set.
auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
-> void {
mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
auto bytes = set_.ComputeMetrics(KeyContext(&values_)).storage_bytes;
mem_usage.Add(MemUsage::ConcatLabel(label, "set_"), bytes, bytes);
}
private:
class KeyContext;
ValueStore<IdT, ValueType> values_;
Set<IdT, /*SmallSize=*/0, KeyContext> set_;
};
template <typename IdT, typename KeyT, typename ValueT>
class CanonicalValueStore<IdT, KeyT, ValueT>::KeyContext
: public TranslatingKeyContext<KeyContext> {
public:
explicit KeyContext(const ValueStore<IdT, ValueType>* values)
: values_(values) {}
// Note that it is safe to return a `const` reference here as the underlying
// object's lifetime is provided by the `ValueStore`.
auto TranslateKey(IdT id) const -> ConstRefType { return values_->Get(id); }
private:
const ValueStore<IdT, ValueType>* values_;
};
template <typename IdT, typename KeyT, typename ValueT>
auto CanonicalValueStore<IdT, KeyT, ValueT>::Add(ValueType value) -> IdT {
auto make_key = [&] { return IdT(values_.Add(std::move(value))); };
return set_.Insert(value, make_key, KeyContext(&values_)).key();
}
template <typename IdT, typename KeyT, typename ValueT>
auto CanonicalValueStore<IdT, KeyT, ValueT>::Lookup(KeyType key) const -> IdT {
if (auto result = set_.Lookup(key, KeyContext(&values_))) {
return result.key();
}
return IdT::None;
}
template <typename IdT, typename KeyT, typename ValueT>
auto CanonicalValueStore<IdT, KeyT, ValueT>::Reserve(size_t size) -> void {
// Compute the resulting new insert count using the size of values -- the
// set doesn't have a fast to compute current size.
|
ast_based
|
<|fim_prefix|>/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/<|fim_suffix|>#include "editor/animation/animation_player_editor_plugin.h"
#include "editor/editor_node.h"
#include "editor/editor_string_names.h"
#include "editor/editor_undo_redo_manager.h"
#include "editor/gui/editor_spin_slider.h"
#include "editor/settings/editor_settings.h"
#include "editor/themes/editor_scale.h"
#include "scene/gui/option_button.h"
#include "scene/gui/view_panner.h"
#include "scene/resources/text_line.h"
#include <climits>
float AnimationBezierTrackEdit::_bezier_h_to_pixel(float p_h) {
float h = p_h;
h = (h - timeline_v_scroll) / timeline_v_zoom;
h = (get_size().height / 2.0) - h;
return h;
}
void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
float scale = timeline->get_zoom_scale();
int limit = timeline->get_name_limit();
int right_limit = get_size().width;
// Selection may have altered the order of keys.
RBMap<real_t, int> key_order;
for (int i = 0; i < animation->track_get_key_count(p_track); i++) {
real_t ofs = animation->track_get_key_time(p_track, i);
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
ofs += moving_selection_offset.x;
} else if (scaling_selection) {
ofs += -scaling_selection_offset.x + (ofs - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
}
}
key_order[ofs] = i;
}
for (RBMap<real_t, int>::Element *E = key_order.front(); E; E = E->next()) {
int i = E->get();
if (!E->next()) {
break;
}
int i_n = E->next()->get();
float offset = animation->track_get_key_time(p_track, i);
float height = animation->bezier_track_get_key_value(p_track, i);
Vector2 out_handle = animation->bezier_track_get_key_out_handle(p_track, i);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i) {
out_handle = moving_handle_right;
}
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
offset += moving_selection_offset.x;
height += moving_selection_offset.y;<|fim_middle|>
#include "animation_bezier_editor.h"
|
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
|
#include "animation_bezier_editor.h"
|
#include "editor/animation/animation_player_editor_plugin.h"
#include "editor/editor_node.h"
#include "editor/editor_string_names.h"
#include "editor/editor_undo_redo_manager.h"
#include "editor/gui/editor_spin_slider.h"
#include "editor/settings/editor_settings.h"
#include "editor/themes/editor_scale.h"
#include "scene/gui/option_button.h"
#include "scene/gui/view_panner.h"
#include "scene/resources/text_line.h"
#include <climits>
float AnimationBezierTrackEdit::_bezier_h_to_pixel(float p_h) {
float h = p_h;
h = (h - timeline_v_scroll) / timeline_v_zoom;
h = (get_size().height / 2.0) - h;
return h;
}
void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) {
float scale = timeline->get_zoom_scale();
int limit = timeline->get_name_limit();
int right_limit = get_size().width;
// Selection may have altered the order of keys.
RBMap<real_t, int> key_order;
for (int i = 0; i < animation->track_get_key_count(p_track); i++) {
real_t ofs = animation->track_get_key_time(p_track, i);
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
ofs += moving_selection_offset.x;
} else if (scaling_selection) {
ofs += -scaling_selection_offset.x + (ofs - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
}
}
key_order[ofs] = i;
}
for (RBMap<real_t, int>::Element *E = key_order.front(); E; E = E->next()) {
int i = E->get();
if (!E->next()) {
break;
}
int i_n = E->next()->get();
float offset = animation->track_get_key_time(p_track, i);
float height = animation->bezier_track_get_key_value(p_track, i);
Vector2 out_handle = animation->bezier_track_get_key_out_handle(p_track, i);
if (p_track == moving_handle_track && (moving_handle == -1 || moving_handle == 1) && moving_handle_key == i) {
out_handle = moving_handle_right;
}
if (selection.has(IntPair(p_track, i))) {
if (moving_selection) {
offset += moving_selection_offset.x;
height += moving_selection_offset.y;
|
random
|
<|fim_prefix|> } else {
accesskit_node_clear_state_description(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_color_value(const RID &p_id, const Color &p_color) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_color_value(ae->node, p_color.to_rgba32());
}
void AccessibilityDriverAccessKit::accessibility_update_set_background_color(const RID &p_id, const Color &p_color) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_background_color(ae->node, p_color.to_rgba32());
}
void AccessibilityDriverAccessKit::accessibility_update_set_foreground_color(const RID &p_id, const Color &p_color) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_foreground_color(ae->node, p_color.to_rgba32());
}
Error AccessibilityDriverAccessKit::init() {
#ifdef ACCESSKIT_DYNAMIC
#ifdef DEBUG_ENABLED
int dylibloader_verbose = 1;
#else
int dylibloader_verbose = 0;
#endif
void *library_handle = nullptr;
String path;
String arch = Engine::get_singleton()->get_architecture_name();
#ifdef LINUXBSD_ENABLED
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("libaccesskit." + arch + ".so");
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("../lib").path_join("libaccesskit." + arch + ".so");
}<|fim_suffix|> return ERR_CANT_CREATE;
}
#endif
#ifdef MACOS_ENABLED
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("libaccesskit." + arch + ".dylib");
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("../Frameworks").path_join("libaccesskit." + arch + ".dylib");
}
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("libaccesskit.dylib");
}
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("../Frameworks").path_join("libaccesskit.dylib");
}
if (!FileAccess::exists(path)) {
return ERR_CANT_CREATE;
}
#endif
#ifdef WINDOWS_ENABLED
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("accesskit." + arch + ".dll");
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("accesskit.dll");
}
if (!FileAccess::exists(path)) {
return ERR_CANT_CREATE;
}
#endif
Error err = OS::get_singleton()->open_dynamic_library(path, library_handle);
if (err == OK && initialize_libaccesskit(dylibloader_verbose, library_handle) == 0) {
print_verbose("AccessKit loaded.");
} else {
return ERR_CANT_CREATE;
}
#endif
#ifdef MACOS_ENABLED
//accesskit_macos_add_focus_forwarder_to_window_class("GodotWindow");
#endif
return OK;
}
AccessibilityDriverAccessKit::AccessibilityDriverAccessKit() {
singleton = this;
role_map[DisplayServer::AccessibilityRole::ROLE_UNKNOWN] = ACCESSKIT_ROLE_UNKNOWN;
role_map[DisplayServer::AccessibilityRole::ROLE_DEFAULT_BUTTON] = ACCESSKIT_ROLE_DEFAULT_BUTTON;
role_map[DisplayServer::AccessibilityRole::ROLE_AUDIO] = ACCESSKIT_ROLE_AUDIO;
role_map[DisplayServer::AccessibilityRole::ROLE_VIDEO] = ACCESSKIT_ROLE_VIDEO;
role_map[DisplayServer::AccessibilityRole::ROLE_STATIC_TEXT] = ACCESSKIT_ROLE_LABEL;<|fim_middle|> if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("libaccesskit.so");
}
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("../lib").path_join("libaccesskit.so");
}
if (!FileAccess::exists(path)) {
|
} else {
accesskit_node_clear_state_description(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_color_value(const RID &p_id, const Color &p_color) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_color_value(ae->node, p_color.to_rgba32());
}
void AccessibilityDriverAccessKit::accessibility_update_set_background_color(const RID &p_id, const Color &p_color) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_background_color(ae->node, p_color.to_rgba32());
}
void AccessibilityDriverAccessKit::accessibility_update_set_foreground_color(const RID &p_id, const Color &p_color) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_foreground_color(ae->node, p_color.to_rgba32());
}
Error AccessibilityDriverAccessKit::init() {
#ifdef ACCESSKIT_DYNAMIC
#ifdef DEBUG_ENABLED
int dylibloader_verbose = 1;
#else
int dylibloader_verbose = 0;
#endif
void *library_handle = nullptr;
String path;
String arch = Engine::get_singleton()->get_architecture_name();
#ifdef LINUXBSD_ENABLED
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("libaccesskit." + arch + ".so");
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("../lib").path_join("libaccesskit." + arch + ".so");
}
|
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("libaccesskit.so");
}
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("../lib").path_join("libaccesskit.so");
}
if (!FileAccess::exists(path)) {
|
return ERR_CANT_CREATE;
}
#endif
#ifdef MACOS_ENABLED
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("libaccesskit." + arch + ".dylib");
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("../Frameworks").path_join("libaccesskit." + arch + ".dylib");
}
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("libaccesskit.dylib");
}
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("../Frameworks").path_join("libaccesskit.dylib");
}
if (!FileAccess::exists(path)) {
return ERR_CANT_CREATE;
}
#endif
#ifdef WINDOWS_ENABLED
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("accesskit." + arch + ".dll");
if (!FileAccess::exists(path)) {
path = OS::get_singleton()->get_executable_path().get_base_dir().path_join("accesskit.dll");
}
if (!FileAccess::exists(path)) {
return ERR_CANT_CREATE;
}
#endif
Error err = OS::get_singleton()->open_dynamic_library(path, library_handle);
if (err == OK && initialize_libaccesskit(dylibloader_verbose, library_handle) == 0) {
print_verbose("AccessKit loaded.");
} else {
return ERR_CANT_CREATE;
}
#endif
#ifdef MACOS_ENABLED
//accesskit_macos_add_focus_forwarder_to_window_class("GodotWindow");
#endif
return OK;
}
AccessibilityDriverAccessKit::AccessibilityDriverAccessKit() {
singleton = this;
role_map[DisplayServer::AccessibilityRole::ROLE_UNKNOWN] = ACCESSKIT_ROLE_UNKNOWN;
role_map[DisplayServer::AccessibilityRole::ROLE_DEFAULT_BUTTON] = ACCESSKIT_ROLE_DEFAULT_BUTTON;
role_map[DisplayServer::AccessibilityRole::ROLE_AUDIO] = ACCESSKIT_ROLE_AUDIO;
role_map[DisplayServer::AccessibilityRole::ROLE_VIDEO] = ACCESSKIT_ROLE_VIDEO;
role_map[DisplayServer::AccessibilityRole::ROLE_STATIC_TEXT] = ACCESSKIT_ROLE_LABEL;
|
random
|
<|fim_prefix|> IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
ImGuiIO& io = ImGui::GetIO();
switch (ev->type)
{
case ALLEGRO_EVENT_MOUSE_AXES:
if (ev->mouse.display == bd->Display)
{
io.AddMousePosEvent(ev->mouse.x, ev->mouse.y);
io.AddMouseWheelEvent(-ev->mouse.dw, ev->mouse.dz);
}
return true;
case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
if (ev->mouse.display == bd->Display && ev->mouse.button > 0 && ev->mouse.button <= 5)
io.AddMouseButtonEvent(ev->mouse.button - 1, ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN);
return true;
case ALLEGRO_EVENT_TOUCH_MOVE:
if (ev->touch.display == bd->Display)
io.AddMousePosEvent(ev->touch.x, ev->touch.y);
return true;
case ALLEGRO_EVENT_TOUCH_BEGIN:
case ALLEGRO_EVENT_TOUCH_END:
case ALLEGRO_EVENT_TOUCH_CANCEL:
if (ev->touch.display == bd->Display && ev->touch.primary)
io.AddMouseButtonEvent(0, ev->type == ALLEGRO_EVENT_TOUCH_BEGIN);
return true;
case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
if (ev->mouse.display == bd->Display)
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
return true;
case ALLEGRO_EVENT_KEY_CHAR:
if (ev->keyboard.display == bd->Display)
if (ev->keyboard.unichar != 0)
io.AddInputCharacter((unsigned int)ev->keyboard.unichar);
return true;
case ALLEGRO_EVENT_KEY_DOWN:
case ALLEGRO_EVENT_KEY_UP:
if (ev->keyboard.display == bd->Display)
{
ImGui_ImplAllegro5_UpdateKeyModifiers();
ImGuiKey key = ImGui_ImplAllegro5_KeyCodeToImGuiKey(ev->keyboard.keycode);
io.AddKeyEvent(key, (ev->type == ALLEGRO_EVENT_KEY_DOWN));
io.SetKeyEventNativeData(key, ev->keyboard.keycode, -1); // To support legacy indexing (<1.87 user code)<|fim_suffix|> case ALLEGRO_EVENT_DISPLAY_SWITCH_IN:
if (ev->display.source == bd->Display)
{
io.AddFocusEvent(true);
#if defined(ALLEGRO_UNSTABLE)
al_clear_keyboard_state(bd->Display);
#endif
}
return true;
}
return false;
}
static void ImGui_ImplAllegro5_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
return;
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
// Hide OS mouse cursor if imgui is drawing it
if (io.MouseDrawCursor)
imgui_cursor = ImGuiMouseCursor_None;
if (bd->LastCursor == imgui_cursor)
return;
bd->LastCursor = imgui_cursor;
if (imgui_cursor == ImGuiMouseCursor_None)
{
al_set_mouse_cursor(bd->Display, bd->MouseCursorInvisible);
}
else
{
ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT;
switch (imgui_cursor)
{
case ImGuiMouseCursor_TextInput: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT; break;
case ImGuiMouseCursor_ResizeAll: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE; break;
case ImGuiMouseCursor_ResizeNS: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N; break;
case ImGuiMouseCursor_ResizeEW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break;
case ImGuiMouseCursor_ResizeNESW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break;
case ImGuiMouseCursor_ResizeNWSE: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break;
case ImGuiMouseCursor_Wait: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_BUSY; break;
case ImGuiMouseCursor_Progress: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_PROGRESS; break;
case ImGuiMouseCursor_NotAllowed: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE; break;
}<|fim_middle|> }
return true;
case ALLEGRO_EVENT_DISPLAY_SWITCH_OUT:
if (ev->display.source == bd->Display)
io.AddFocusEvent(false);
return true;
|
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
ImGuiIO& io = ImGui::GetIO();
switch (ev->type)
{
case ALLEGRO_EVENT_MOUSE_AXES:
if (ev->mouse.display == bd->Display)
{
io.AddMousePosEvent(ev->mouse.x, ev->mouse.y);
io.AddMouseWheelEvent(-ev->mouse.dw, ev->mouse.dz);
}
return true;
case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
if (ev->mouse.display == bd->Display && ev->mouse.button > 0 && ev->mouse.button <= 5)
io.AddMouseButtonEvent(ev->mouse.button - 1, ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN);
return true;
case ALLEGRO_EVENT_TOUCH_MOVE:
if (ev->touch.display == bd->Display)
io.AddMousePosEvent(ev->touch.x, ev->touch.y);
return true;
case ALLEGRO_EVENT_TOUCH_BEGIN:
case ALLEGRO_EVENT_TOUCH_END:
case ALLEGRO_EVENT_TOUCH_CANCEL:
if (ev->touch.display == bd->Display && ev->touch.primary)
io.AddMouseButtonEvent(0, ev->type == ALLEGRO_EVENT_TOUCH_BEGIN);
return true;
case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
if (ev->mouse.display == bd->Display)
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
return true;
case ALLEGRO_EVENT_KEY_CHAR:
if (ev->keyboard.display == bd->Display)
if (ev->keyboard.unichar != 0)
io.AddInputCharacter((unsigned int)ev->keyboard.unichar);
return true;
case ALLEGRO_EVENT_KEY_DOWN:
case ALLEGRO_EVENT_KEY_UP:
if (ev->keyboard.display == bd->Display)
{
ImGui_ImplAllegro5_UpdateKeyModifiers();
ImGuiKey key = ImGui_ImplAllegro5_KeyCodeToImGuiKey(ev->keyboard.keycode);
io.AddKeyEvent(key, (ev->type == ALLEGRO_EVENT_KEY_DOWN));
io.SetKeyEventNativeData(key, ev->keyboard.keycode, -1); // To support legacy indexing (<1.87 user code)
|
}
return true;
case ALLEGRO_EVENT_DISPLAY_SWITCH_OUT:
if (ev->display.source == bd->Display)
io.AddFocusEvent(false);
return true;
|
case ALLEGRO_EVENT_DISPLAY_SWITCH_IN:
if (ev->display.source == bd->Display)
{
io.AddFocusEvent(true);
#if defined(ALLEGRO_UNSTABLE)
al_clear_keyboard_state(bd->Display);
#endif
}
return true;
}
return false;
}
static void ImGui_ImplAllegro5_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
return;
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
// Hide OS mouse cursor if imgui is drawing it
if (io.MouseDrawCursor)
imgui_cursor = ImGuiMouseCursor_None;
if (bd->LastCursor == imgui_cursor)
return;
bd->LastCursor = imgui_cursor;
if (imgui_cursor == ImGuiMouseCursor_None)
{
al_set_mouse_cursor(bd->Display, bd->MouseCursorInvisible);
}
else
{
ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT;
switch (imgui_cursor)
{
case ImGuiMouseCursor_TextInput: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT; break;
case ImGuiMouseCursor_ResizeAll: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE; break;
case ImGuiMouseCursor_ResizeNS: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N; break;
case ImGuiMouseCursor_ResizeEW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break;
case ImGuiMouseCursor_ResizeNESW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break;
case ImGuiMouseCursor_ResizeNWSE: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break;
case ImGuiMouseCursor_Wait: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_BUSY; break;
case ImGuiMouseCursor_Progress: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_PROGRESS; break;
case ImGuiMouseCursor_NotAllowed: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE; break;
}
|
random
|
<|fim_prefix|>j] - prev;
while (wlen > 255) {
word_lengths.push_back(255);
wlen -= 255;
total += 255;
}
if (wlen > 0) {
word_lengths.push_back(wlen);
total += wlen;
}
prev = words[j];
}
if (total < t.length()) {
word_lengths.push_back(t.length() - total);
}
accesskit_node_set_word_lengths(ae->node, word_lengths.size(), word_lengths.ptr());
// Char widths and positions.
Vector<float> char_positions;
Vector<float> char_widths;
char_positions.resize_initialized(t.length());
float *positions_ptr = char_positions.ptrw();
char_widths.resize_initialized(t.length());
float *widths_ptr = char_widths.ptrw();
float size_x = 0.0;
for (int j = gl_index; j < gl_count; j += gl[j].count) {
if (gl[j].start >= ae->run.y) {
gl_index = j;
break;
}
float advance = 0.0; // Graphame advance.
for (int k = 0; k < gl[j].count; k++) {
advance += gl[j + k].advance;
}
int chars = gl[j].end - gl[j].start;
float adv_per_char = advance / (float)chars;
for (int k = 0; k < chars; k++) {
int index = gl[j].start + k - ae->run.x;
ERR_CONTINUE(index < 0 || index >= t.length());
positions_ptr[index] = size_x + adv_per_char * k;
widths_ptr[index] = adv_per_char;
}
size_x += advance * gl[j].repeat;
}
positions_ptr[t.length() - 1] = size_x;
widths_ptr[t.length() - 1] = 1.0;
accesskit_node_set_character_positions(ae->node, char_positions.size(), char_positions.ptr());
accesskit_node_set_character_widths(ae->node, char_widths.size(), char_widths.ptr());
RID font_rid = TS->shaped_get_run_font_rid(p_shaped_text, i);
if (font_rid != RID()) {
CharString font_name = TS->font_get_name(font_rid).utf8();
if (font_name.length() > 0) {
accesskit_node_set_font_family(ae->node, font_name.ptr());
}
if (TS->font_get_style(font_rid).has_flag(TextServer::FONT_BOLD)) {
accesskit_node_set_bold(ae->node);
}
if (TS->font_get_style(font_rid).has_flag(TextServer::FONT_ITALIC)) <|fim_suffix|>
accesskit_node_set_font_weight(ae->node, TS->font_get_weight(font_rid));
}
accesskit_node_set_font_size(ae->node, TS->shaped_get_run_font_size(p_shaped_text, i));
CharString language = TS->shaped_get_run_language(p_shaped_text, i).utf8();
if (language.length() > 0) {
accesskit_node_set_language(ae->node, language.ptr());
}
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
accesskit_rect rect;
rect.x0 = run_off_x;
rect.y0 = 0;
rect.x1 = run_off_x + size_x;
rect.y1 = text_height;
accesskit_node_set_bounds(ae->node, rect);
accesskit_node_add_action(ae->node, ACCESSKIT_ACTION_SCROLL_INTO_VIEW);
run_off_x += size_x;
}
{
// Add "\n" at the end.
AccessibilityElement *ae = memnew(AccessibilityElement);
ae->role = ACCESSKIT_ROLE_TEXT_RUN;
ae->window_id = parent_ae->window_id;
ae->parent = root_rid;
ae->run = Vector3i(full_range.y, full_range.y, run_count);
ae->node = accesskit_node_new(ae->role);
text_elements.push_back(ae);
Vector<uint8_t> char_lengths;
char_lengths.push_back(1);
accesskit_node_set_value(ae->node, "\n");
accesskit_node_set_character_lengths(ae->node, char_lengths.size(), char_lengths.ptr());
Vector<float> char_positions;
Vector<float> char_widths;
char_positions.push_back(0.0);
char_widths.push_back(1.0);
accesskit_node_set_character_positions(ae->node, char_positions.size(), char_positions.ptr());
accesskit_node_set_character_widths(ae->node, char_widths.size(), char_widths.ptr());
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
accesskit_rect rect;
rect.x0 = run_off_x;
rect.y0 = 0;
rect.x1 = run_off_x + 1;
rect.y1 = text_height;
accesskit_node_set_bounds(ae->node, rect);
}
// Sort runs in logical order.
struct RunCompare {
_FORCE_INLINE_ bool operator()(const AccessibilityElement *l, const AccessibilityElement *r) const {
return l->run.x < r->run.x;
}
};
text_elements.sort_custom<|fim_middle|>{
accesskit_node_set_italic(ae->node);
}
|
j] - prev;
while (wlen > 255) {
word_lengths.push_back(255);
wlen -= 255;
total += 255;
}
if (wlen > 0) {
word_lengths.push_back(wlen);
total += wlen;
}
prev = words[j];
}
if (total < t.length()) {
word_lengths.push_back(t.length() - total);
}
accesskit_node_set_word_lengths(ae->node, word_lengths.size(), word_lengths.ptr());
// Char widths and positions.
Vector<float> char_positions;
Vector<float> char_widths;
char_positions.resize_initialized(t.length());
float *positions_ptr = char_positions.ptrw();
char_widths.resize_initialized(t.length());
float *widths_ptr = char_widths.ptrw();
float size_x = 0.0;
for (int j = gl_index; j < gl_count; j += gl[j].count) {
if (gl[j].start >= ae->run.y) {
gl_index = j;
break;
}
float advance = 0.0; // Graphame advance.
for (int k = 0; k < gl[j].count; k++) {
advance += gl[j + k].advance;
}
int chars = gl[j].end - gl[j].start;
float adv_per_char = advance / (float)chars;
for (int k = 0; k < chars; k++) {
int index = gl[j].start + k - ae->run.x;
ERR_CONTINUE(index < 0 || index >= t.length());
positions_ptr[index] = size_x + adv_per_char * k;
widths_ptr[index] = adv_per_char;
}
size_x += advance * gl[j].repeat;
}
positions_ptr[t.length() - 1] = size_x;
widths_ptr[t.length() - 1] = 1.0;
accesskit_node_set_character_positions(ae->node, char_positions.size(), char_positions.ptr());
accesskit_node_set_character_widths(ae->node, char_widths.size(), char_widths.ptr());
RID font_rid = TS->shaped_get_run_font_rid(p_shaped_text, i);
if (font_rid != RID()) {
CharString font_name = TS->font_get_name(font_rid).utf8();
if (font_name.length() > 0) {
accesskit_node_set_font_family(ae->node, font_name.ptr());
}
if (TS->font_get_style(font_rid).has_flag(TextServer::FONT_BOLD)) {
accesskit_node_set_bold(ae->node);
}
if (TS->font_get_style(font_rid).has_flag(TextServer::FONT_ITALIC))
|
{
accesskit_node_set_italic(ae->node);
}
|
accesskit_node_set_font_weight(ae->node, TS->font_get_weight(font_rid));
}
accesskit_node_set_font_size(ae->node, TS->shaped_get_run_font_size(p_shaped_text, i));
CharString language = TS->shaped_get_run_language(p_shaped_text, i).utf8();
if (language.length() > 0) {
accesskit_node_set_language(ae->node, language.ptr());
}
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
accesskit_rect rect;
rect.x0 = run_off_x;
rect.y0 = 0;
rect.x1 = run_off_x + size_x;
rect.y1 = text_height;
accesskit_node_set_bounds(ae->node, rect);
accesskit_node_add_action(ae->node, ACCESSKIT_ACTION_SCROLL_INTO_VIEW);
run_off_x += size_x;
}
{
// Add "\n" at the end.
AccessibilityElement *ae = memnew(AccessibilityElement);
ae->role = ACCESSKIT_ROLE_TEXT_RUN;
ae->window_id = parent_ae->window_id;
ae->parent = root_rid;
ae->run = Vector3i(full_range.y, full_range.y, run_count);
ae->node = accesskit_node_new(ae->role);
text_elements.push_back(ae);
Vector<uint8_t> char_lengths;
char_lengths.push_back(1);
accesskit_node_set_value(ae->node, "\n");
accesskit_node_set_character_lengths(ae->node, char_lengths.size(), char_lengths.ptr());
Vector<float> char_positions;
Vector<float> char_widths;
char_positions.push_back(0.0);
char_widths.push_back(1.0);
accesskit_node_set_character_positions(ae->node, char_positions.size(), char_positions.ptr());
accesskit_node_set_character_widths(ae->node, char_widths.size(), char_widths.ptr());
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
accesskit_rect rect;
rect.x0 = run_off_x;
rect.y0 = 0;
rect.x1 = run_off_x + 1;
rect.y1 = text_height;
accesskit_node_set_bounds(ae->node, rect);
}
// Sort runs in logical order.
struct RunCompare {
_FORCE_INLINE_ bool operator()(const AccessibilityElement *l, const AccessibilityElement *r) const {
return l->run.x < r->run.x;
}
};
text_elements.sort_custom
|
ast_based
|
<|fim_prefix|>ggml_context * dev_ctx = ctx_for_buft(buft);
// validate tensor shape
if (is_token_embd) {
// expect B to be non-transposed, A and B are flipped; see llm_build_inp_embd()
if (model_tensor->ne[0] != w.b->ne[1] || model_tensor->ne[1] != w.a->ne[1]) {
throw std::runtime_error("tensor '" + name + "' has incorrect shape (hint: maybe wrong base model?)");
}
} else {
if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
throw std::runtime_error("tensor '" + name + "' has incorrect shape (hint: maybe wrong base model?)");
}
if (w.a->ne[1] != w.b->ne[0]) {
throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
}
}
// save tensor to adapter
ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
ggml_set_name(tensor_a, w.a->name);
ggml_set_name(tensor_b, w.b->name);
adapter.ab_map[name] = llama_adapter_lora_weight(tensor_a, tensor_b);
}
// allocate tensors / buffers and zero
{
adapter.ctxs.reserve(ctx_map.size());
adapter.bufs.reserve(ctx_map.size());
for (auto & it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx_dev = it.second;
ggml_backend_buffer_ptr buf { ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft) };
if (!buf) {
throw std::runtime_error("failed to allocate buffer for lora adapter\n");
}
LLAMA_LOG_INFO("%s: %10s LoRA buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf.get()), ggml_backend_buffer_get_size(buf.get())/1024.0/1024.0);
adapter.bufs.emplace_back(std::move(buf));
}
}
// set tensor data
{
<|fim_suffix|>
std::vector<uint8_t> read_buf;
auto set_tensor = [&](ggml_tensor * orig, ggml_tensor * dev) {
size_t offs = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), gguf_find_tensor(ctx_gguf.get(), orig->name));
size_t size = ggml_nbytes(orig);
read_buf.resize(size);
gguf_file.seek(offs, SEEK_SET);
gguf_file.read_raw(read_buf.data(), size);
ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
};
for (auto & it : adapter.ab_map) {
auto orig = ab_map[it.first];
auto dev = it.second;
set_tensor(orig.a, dev.a);
set_tensor(orig.b, dev.b);
}
}
LLAMA_LOG_INFO("%s: loaded %zu tensors from lora file\n", __func__, adapter.ab_map.size()*2);
}
llama_adapter_lora * llama_adapter_lora_init(llama_model * model, const char * path_lora) {
llama_adapter_lora * adapter = new llama_adapter_lora();
try {
llama_adapter_lora_init_impl(*model, path_lora, *adapter);
return adapter;
} catch (const std::exception & err) {
LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
delete adapter;
}
return nullptr;
}
int32_t llama_adapter_meta_val_str(const llama_adapter_lora * adapter, const char * key, char * buf, size_t buf_size) {
const auto & it = adapter->gguf_kv.find(key);
if (it == adapter->gguf_kv.end()) {
if (buf_size > 0) {
buf[0] = '\0';
}
return -1;
}
return snprintf(buf, buf_size, "%s", it->second.c_str());
}
int32_t llama_adapter_meta_count(const llama_adapter_lora * adapter) {
return (int)adapter->gguf_kv.size();
}
int32_t llama_adapter_meta_key_by_index(const llama_adapter_lora * adapter, int i, char * buf, size_t buf_size) {
if (i < 0 || i >= (int)adapter->gguf_kv.size()) {
if (buf_size > 0) {
buf[0] = '\0';
}
r<|fim_middle|>llama_file gguf_file(path_lora, "rb");
|
ggml_context * dev_ctx = ctx_for_buft(buft);
// validate tensor shape
if (is_token_embd) {
// expect B to be non-transposed, A and B are flipped; see llm_build_inp_embd()
if (model_tensor->ne[0] != w.b->ne[1] || model_tensor->ne[1] != w.a->ne[1]) {
throw std::runtime_error("tensor '" + name + "' has incorrect shape (hint: maybe wrong base model?)");
}
} else {
if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
throw std::runtime_error("tensor '" + name + "' has incorrect shape (hint: maybe wrong base model?)");
}
if (w.a->ne[1] != w.b->ne[0]) {
throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
}
}
// save tensor to adapter
ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
ggml_set_name(tensor_a, w.a->name);
ggml_set_name(tensor_b, w.b->name);
adapter.ab_map[name] = llama_adapter_lora_weight(tensor_a, tensor_b);
}
// allocate tensors / buffers and zero
{
adapter.ctxs.reserve(ctx_map.size());
adapter.bufs.reserve(ctx_map.size());
for (auto & it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx_dev = it.second;
ggml_backend_buffer_ptr buf { ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft) };
if (!buf) {
throw std::runtime_error("failed to allocate buffer for lora adapter\n");
}
LLAMA_LOG_INFO("%s: %10s LoRA buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf.get()), ggml_backend_buffer_get_size(buf.get())/1024.0/1024.0);
adapter.bufs.emplace_back(std::move(buf));
}
}
// set tensor data
{
|
llama_file gguf_file(path_lora, "rb");
|
std::vector<uint8_t> read_buf;
auto set_tensor = [&](ggml_tensor * orig, ggml_tensor * dev) {
size_t offs = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), gguf_find_tensor(ctx_gguf.get(), orig->name));
size_t size = ggml_nbytes(orig);
read_buf.resize(size);
gguf_file.seek(offs, SEEK_SET);
gguf_file.read_raw(read_buf.data(), size);
ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
};
for (auto & it : adapter.ab_map) {
auto orig = ab_map[it.first];
auto dev = it.second;
set_tensor(orig.a, dev.a);
set_tensor(orig.b, dev.b);
}
}
LLAMA_LOG_INFO("%s: loaded %zu tensors from lora file\n", __func__, adapter.ab_map.size()*2);
}
llama_adapter_lora * llama_adapter_lora_init(llama_model * model, const char * path_lora) {
llama_adapter_lora * adapter = new llama_adapter_lora();
try {
llama_adapter_lora_init_impl(*model, path_lora, *adapter);
return adapter;
} catch (const std::exception & err) {
LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
delete adapter;
}
return nullptr;
}
int32_t llama_adapter_meta_val_str(const llama_adapter_lora * adapter, const char * key, char * buf, size_t buf_size) {
const auto & it = adapter->gguf_kv.find(key);
if (it == adapter->gguf_kv.end()) {
if (buf_size > 0) {
buf[0] = '\0';
}
return -1;
}
return snprintf(buf, buf_size, "%s", it->second.c_str());
}
int32_t llama_adapter_meta_count(const llama_adapter_lora * adapter) {
return (int)adapter->gguf_kv.size();
}
int32_t llama_adapter_meta_key_by_index(const llama_adapter_lora * adapter, int i, char * buf, size_t buf_size) {
if (i < 0 || i >= (int)adapter->gguf_kv.size()) {
if (buf_size > 0) {
buf[0] = '\0';
}
r
|
ast_based
|
<|fim_prefix|>l draw_track = _is_track_curves_displayed(i) && !locked_tracks.has(i);
if (!draw_selection_handles && !draw_track) {
continue;
}
int key_count = animation->track_get_key_count(i);
for (int j = 0; j < key_count; ++j) {
float offset = animation->track_get_key_time(i, j);
float value = animation->bezier_track_get_key_value(i, j);
bool is_selected = selection.has(IntPair(i, j));
if (is_selected) {
if (moving_selection) {
offset += moving_selection_offset.x;
value += moving_selection_offset.y;
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
value += -scaling_selection_offset.y + (value - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (draw_selection_handles && is_selected) {
selected_pos.push_back(pos);
}
if (!draw_track) {
continue;
}
Vector2 in_vec = animation->bezier_track_get_key_in_handle(i, j);
Vector2 out_vec = animation->bezier_track_get_key_out_handle(i, j);
if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
in_vec = moving_handle_left;
}
if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
out_vec = moving_handle_right;
}
if (moving_inserted_key && moving_selection_from_key == j) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(i, j);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
int key_prev = 0;
int key_next = moving_selection_from_key;
for (int k = 0; k < key_count; k++) {
if (k == moving_selection_from_key) {
continue;
}
if <|fim_suffix|> else {
key_next = k;
break;
}
}
float prev_time = offset;
float prev_value = value;
if (key_prev != moving_selection_from_key) {
prev_time = animation->track_get_key_time(i, key_prev);
prev_value = animation->bezier_track_get_key_value(i, key_prev);
}
float next_time = offset;
float next_value = value;
if (key_next != moving_selection_from_key) {
next_time = animation->track_get_key_time(i, key_next);
next_value = animation->bezier_track_get_key_value(i, key_next);
}
animation->bezier_track_calculate_handles(offset, prev_time, prev_value, next_time, next_value, handle_mode, Animation::HANDLE_SET_MODE_AUTO, &in_vec, &out_vec);
}
}
Vector2 pos_in(((offset + in_vec.x) - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value + in_vec.y));
Vector2 pos_out(((offset + out_vec.x) - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value + out_vec.y));
if (i == selected_track || is_selected) {
_draw_line_clipped(pos, pos_in, accent, limit, right_limit);
_draw_line_clipped(pos, pos_out, accent, limit, right_limit);
}
EditPoint ep;
ep.track = i;
ep.key = j;
if (pos.x >= limit && pos.x <= right_limit) {
ep.point_rect.position = (pos - bezier_icon->get_size() / 2.0).floor();
ep.point_rect.size = bezier_icon->get_size();
if (is_selected) {
draw_texture(selected_icon, ep.point_rect.position);
draw_string(font, ep.point_rect.position + Vector2(8, -font->get_height(font_size) - 8), TTR("Time:") + " " + TS->format_number(rtos(Math::snapped(offset, 0.0001))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, accent);
draw_string(font, ep.point_rect.position + Vector2(8, -8), TTR("Value:") + " " + TS->format_number(rtos(Math::snapped(value, 0.001))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, accent);
<|fim_middle|>(animation->track_get_key_time(i, k) < offset) {
key_prev = k;
}
|
l draw_track = _is_track_curves_displayed(i) && !locked_tracks.has(i);
if (!draw_selection_handles && !draw_track) {
continue;
}
int key_count = animation->track_get_key_count(i);
for (int j = 0; j < key_count; ++j) {
float offset = animation->track_get_key_time(i, j);
float value = animation->bezier_track_get_key_value(i, j);
bool is_selected = selection.has(IntPair(i, j));
if (is_selected) {
if (moving_selection) {
offset += moving_selection_offset.x;
value += moving_selection_offset.y;
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
value += -scaling_selection_offset.y + (value - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (draw_selection_handles && is_selected) {
selected_pos.push_back(pos);
}
if (!draw_track) {
continue;
}
Vector2 in_vec = animation->bezier_track_get_key_in_handle(i, j);
Vector2 out_vec = animation->bezier_track_get_key_out_handle(i, j);
if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
in_vec = moving_handle_left;
}
if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
out_vec = moving_handle_right;
}
if (moving_inserted_key && moving_selection_from_key == j) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(i, j);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
int key_prev = 0;
int key_next = moving_selection_from_key;
for (int k = 0; k < key_count; k++) {
if (k == moving_selection_from_key) {
continue;
}
if
|
(animation->track_get_key_time(i, k) < offset) {
key_prev = k;
}
|
else {
key_next = k;
break;
}
}
float prev_time = offset;
float prev_value = value;
if (key_prev != moving_selection_from_key) {
prev_time = animation->track_get_key_time(i, key_prev);
prev_value = animation->bezier_track_get_key_value(i, key_prev);
}
float next_time = offset;
float next_value = value;
if (key_next != moving_selection_from_key) {
next_time = animation->track_get_key_time(i, key_next);
next_value = animation->bezier_track_get_key_value(i, key_next);
}
animation->bezier_track_calculate_handles(offset, prev_time, prev_value, next_time, next_value, handle_mode, Animation::HANDLE_SET_MODE_AUTO, &in_vec, &out_vec);
}
}
Vector2 pos_in(((offset + in_vec.x) - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value + in_vec.y));
Vector2 pos_out(((offset + out_vec.x) - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value + out_vec.y));
if (i == selected_track || is_selected) {
_draw_line_clipped(pos, pos_in, accent, limit, right_limit);
_draw_line_clipped(pos, pos_out, accent, limit, right_limit);
}
EditPoint ep;
ep.track = i;
ep.key = j;
if (pos.x >= limit && pos.x <= right_limit) {
ep.point_rect.position = (pos - bezier_icon->get_size() / 2.0).floor();
ep.point_rect.size = bezier_icon->get_size();
if (is_selected) {
draw_texture(selected_icon, ep.point_rect.position);
draw_string(font, ep.point_rect.position + Vector2(8, -font->get_height(font_size) - 8), TTR("Time:") + " " + TS->format_number(rtos(Math::snapped(offset, 0.0001))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, accent);
draw_string(font, ep.point_rect.position + Vector2(8, -8), TTR("Value:") + " " + TS->format_number(rtos(Math::snapped(value, 0.001))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, accent);
|
ast_based
|
<|fim_prefix|>void TessBaseAPI::ClearResults() {
if (tesseract_ != nullptr) {
tesseract_->Clear();
}
delete page_res_;
page_res_ = nullptr;
recognition_done_ = false;
if (block_list_ == nullptr) {
block_list_ = new BLOCK_LIST;
} else {
block_list_->clear();
}
if (paragraph_models_ != nullptr) {
for (auto model : *paragraph_models_) {
delete model;
}
delete paragraph_models_;
paragraph_models_ = nullptr;
}
}
/**
* Return the length of the output text string, as UTF8, assuming
* liberally two spacing marks after each word (as paragraphs end with two
* newlines), and assuming a single character reject marker for each rejected
* character.
* Also return the number of recognized blobs in blob_count.
*/
int TessBaseAPI::TextLength(int *blob_count) const {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return 0;
}
PAGE_RES_IT page_res_it(page_res_);
int total_length = 2;
int total_blobs = 0;
// Iterate over the data structures to extract the recognition result.
for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
WERD_CHOICE *choice = word->best_choice;
if (choice != nullptr) {
total_blobs += choice->length() + 2;
total_length += choice->unichar_string().length() + 2;
for (int i = 0; i < word->reject_map.length(); ++i) {
if (word->reject_map[i].rejected()) {
++total_length;
}
}
}
}
if (blob_count != nullptr) {
*blob_count = total_blobs;
}
return total_length;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
* Estimates the Orientation And Script of the image.
* Returns true if the image was processed successfully.
*/
bool TessBaseAPI::DetectOS(OSResults *osr) {
if (tesseract_ == nullptr) {
return false;
}
ClearResults();
if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
return false;<|fim_suffix|>#endif // #ifndef DISABLED_LEGACY_ENGINE
void TessBaseAPI::set_min_orientation_margin(double margin) {
tesseract_->min_orientation_margin.set_value(margin);
}
/**
* Return text orientation of each block as determined in an earlier page layout
* analysis operation. Orientation is returned as the number of ccw 90-degree
* rotations (in [0..3]) required to make the text in the block upright
* (readable). Note that this may not necessary be the block orientation
* preferred for recognition (such as the case of vertical CJK text).
*
* Also returns whether the text in the block is believed to have vertical
* writing direction (when in an upright page orientation).
*
* The returned array is of length equal to the number of text blocks, which may
* be less than the total number of blocks. The ordering is intended to be
* consistent with GetTextLines().
*/
void TessBaseAPI::GetBlockTextOrientations(int **block_orientation, bool **vertical_writing) {
delete[] * block_orientation;
*block_orientation = nullptr;
delete[] * vertical_writing;
*vertical_writing = nullptr;
BLOCK_IT block_it(block_list_);
block_it.move_to_first();
int num_blocks = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
++num_blocks;
}
if (!num_blocks) {
tprintf("WARNING: Found no blocks\n");
return;
}
*block_orientation = new int[num_blocks];
*vertical_writing = new bool[num_blocks];
block_it.move_to_first();
int i = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
FCOORD re_rotation = block_it.data()->re_rotation();
float re_theta = re_rotation.angle();
FCOORD classify_rotation = block_it.data()->classify_rotation();
float classify_theta = classify_rotation.angle();<|fim_middle|> }
if (input_file_.empty()) {
input_file_ = kInputFile;
}
return orientation_and_script_detection(input_file_.c_str(), osr, tesseract_) > 0;
}
|
void TessBaseAPI::ClearResults() {
if (tesseract_ != nullptr) {
tesseract_->Clear();
}
delete page_res_;
page_res_ = nullptr;
recognition_done_ = false;
if (block_list_ == nullptr) {
block_list_ = new BLOCK_LIST;
} else {
block_list_->clear();
}
if (paragraph_models_ != nullptr) {
for (auto model : *paragraph_models_) {
delete model;
}
delete paragraph_models_;
paragraph_models_ = nullptr;
}
}
/**
* Return the length of the output text string, as UTF8, assuming
* liberally two spacing marks after each word (as paragraphs end with two
* newlines), and assuming a single character reject marker for each rejected
* character.
* Also return the number of recognized blobs in blob_count.
*/
int TessBaseAPI::TextLength(int *blob_count) const {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return 0;
}
PAGE_RES_IT page_res_it(page_res_);
int total_length = 2;
int total_blobs = 0;
// Iterate over the data structures to extract the recognition result.
for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
WERD_CHOICE *choice = word->best_choice;
if (choice != nullptr) {
total_blobs += choice->length() + 2;
total_length += choice->unichar_string().length() + 2;
for (int i = 0; i < word->reject_map.length(); ++i) {
if (word->reject_map[i].rejected()) {
++total_length;
}
}
}
}
if (blob_count != nullptr) {
*blob_count = total_blobs;
}
return total_length;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
* Estimates the Orientation And Script of the image.
* Returns true if the image was processed successfully.
*/
bool TessBaseAPI::DetectOS(OSResults *osr) {
if (tesseract_ == nullptr) {
return false;
}
ClearResults();
if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
return false;
|
}
if (input_file_.empty()) {
input_file_ = kInputFile;
}
return orientation_and_script_detection(input_file_.c_str(), osr, tesseract_) > 0;
}
|
#endif // #ifndef DISABLED_LEGACY_ENGINE
void TessBaseAPI::set_min_orientation_margin(double margin) {
tesseract_->min_orientation_margin.set_value(margin);
}
/**
* Return text orientation of each block as determined in an earlier page layout
* analysis operation. Orientation is returned as the number of ccw 90-degree
* rotations (in [0..3]) required to make the text in the block upright
* (readable). Note that this may not necessary be the block orientation
* preferred for recognition (such as the case of vertical CJK text).
*
* Also returns whether the text in the block is believed to have vertical
* writing direction (when in an upright page orientation).
*
* The returned array is of length equal to the number of text blocks, which may
* be less than the total number of blocks. The ordering is intended to be
* consistent with GetTextLines().
*/
void TessBaseAPI::GetBlockTextOrientations(int **block_orientation, bool **vertical_writing) {
delete[] * block_orientation;
*block_orientation = nullptr;
delete[] * vertical_writing;
*vertical_writing = nullptr;
BLOCK_IT block_it(block_list_);
block_it.move_to_first();
int num_blocks = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
++num_blocks;
}
if (!num_blocks) {
tprintf("WARNING: Found no blocks\n");
return;
}
*block_orientation = new int[num_blocks];
*vertical_writing = new bool[num_blocks];
block_it.move_to_first();
int i = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->pdblk.poly_block()->IsText()) {
continue;
}
FCOORD re_rotation = block_it.data()->re_rotation();
float re_theta = re_rotation.angle();
FCOORD classify_rotation = block_it.data()->classify_rotation();
float classify_theta = classify_rotation.angle();
|
random
|
<|fim_prefix|>
#pragma once
#include "core/config/project_settings.h"
#include "core/io/dir_access.h"
#include "core/variant/variant.h"
#include "tests/test_macros.h"
class TestProjectSettingsInternalsAccessor {
public:
static String &resource_path() {
return ProjectSettings::get_singleton()->resource_path;
}
};
namespace TestProjectSettings {
TEST_CASE("[ProjectSettings] Get existing setting") {
CHECK(ProjectSettings::get_singleton()->has_setting("application/run/main_scene"));
Variant variant = ProjectSettings::get_singleton()->get_setting("application/run/main_scene");
CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, String());
}
TEST_CASE("[ProjectSettings] Default value is ignored if setting exists") {
CHECK(ProjectSettings::get_singleton()->has_setting("application/run/main_scene"));
Variant variant = ProjectSettings::get_singleton()->get_setting("application/run/main_scene", "SomeDefaultValue");
CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, String());
}
TEST_CASE("[ProjectSettings] Non existing setting is null") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
}
TEST_CASE("[ProjectSettings] Non existing setting should return default value") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting", "my_nice_default_value");
CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, "my_nice_default_value");
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
}
<|fim_suffix|> CHECK(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
variant = ProjectSettings::get_singleton()->get_setting("my_custom_setting");
CHECK_EQ(variant.get_type(), Variant::BOOL);
bool value = variant;
CHECK_EQ(true, value);
CHECK(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
}
TEST_CASE("[ProjectSettings] localize_path") {
String old_resource_path = TestProjectSettingsInternalsAccessor::resource_path();
TestProjectSettingsInternalsAccessor::resource_path() = DirAccess::create(DirAccess::ACCESS_FILESYSTEM)->get_current_dir();
String root_path = ProjectSettings::get_singleton()->get_resource_path();
#ifdef WINDOWS_ENABLED
String root_path_win = ProjectSettings::get_singleton()->get_resource_path().replace_char('/', '\\');
#endif
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("filename"), "res://filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/something/../filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/./filename"), "res://path/filename");
#ifdef WINDOWS_ENABLED
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\something\\..\\filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\.\\filename"), "res://path/filename");
#endif
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("../filename"), "../filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("../path/filename"), "../path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("..\\path\\filename"), "../path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/filename"), "/testroot/filename");<|fim_middle|>TEST_CASE("[ProjectSettings] Set value should be returned when retrieved") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("my_custom_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
ProjectSettings::get_singleton()->set_setting("my_custom_setting", true);
|
#pragma once
#include "core/config/project_settings.h"
#include "core/io/dir_access.h"
#include "core/variant/variant.h"
#include "tests/test_macros.h"
class TestProjectSettingsInternalsAccessor {
public:
static String &resource_path() {
return ProjectSettings::get_singleton()->resource_path;
}
};
namespace TestProjectSettings {
TEST_CASE("[ProjectSettings] Get existing setting") {
CHECK(ProjectSettings::get_singleton()->has_setting("application/run/main_scene"));
Variant variant = ProjectSettings::get_singleton()->get_setting("application/run/main_scene");
CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, String());
}
TEST_CASE("[ProjectSettings] Default value is ignored if setting exists") {
CHECK(ProjectSettings::get_singleton()->has_setting("application/run/main_scene"));
Variant variant = ProjectSettings::get_singleton()->get_setting("application/run/main_scene", "SomeDefaultValue");
CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, String());
}
TEST_CASE("[ProjectSettings] Non existing setting is null") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
}
TEST_CASE("[ProjectSettings] Non existing setting should return default value") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting", "my_nice_default_value");
CHECK_EQ(variant.get_type(), Variant::STRING);
String name = variant;
CHECK_EQ(name, "my_nice_default_value");
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting"));
}
|
TEST_CASE("[ProjectSettings] Set value should be returned when retrieved") {
CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
Variant variant = ProjectSettings::get_singleton()->get_setting("my_custom_setting");
CHECK_EQ(variant.get_type(), Variant::NIL);
ProjectSettings::get_singleton()->set_setting("my_custom_setting", true);
|
CHECK(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
variant = ProjectSettings::get_singleton()->get_setting("my_custom_setting");
CHECK_EQ(variant.get_type(), Variant::BOOL);
bool value = variant;
CHECK_EQ(true, value);
CHECK(ProjectSettings::get_singleton()->has_setting("my_custom_setting"));
}
TEST_CASE("[ProjectSettings] localize_path") {
String old_resource_path = TestProjectSettingsInternalsAccessor::resource_path();
TestProjectSettingsInternalsAccessor::resource_path() = DirAccess::create(DirAccess::ACCESS_FILESYSTEM)->get_current_dir();
String root_path = ProjectSettings::get_singleton()->get_resource_path();
#ifdef WINDOWS_ENABLED
String root_path_win = ProjectSettings::get_singleton()->get_resource_path().replace_char('/', '\\');
#endif
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("filename"), "res://filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/something/../filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path/./filename"), "res://path/filename");
#ifdef WINDOWS_ENABLED
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\something\\..\\filename"), "res://path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("path\\.\\filename"), "res://path/filename");
#endif
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("../filename"), "../filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("../path/filename"), "../path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("..\\path\\filename"), "../path/filename");
CHECK_EQ(ProjectSettings::get_singleton()->localize_path("/testroot/filename"), "/testroot/filename");
|
random
|
<|fim_prefix|>#endif
if (wd.adapter == nullptr) {
memdelete(ae);
rid_owner.free(wd.root_id);
windows.erase(p_window_id);
return false;
} else {
return true;
}
}
void AccessibilityDriverAccessKit::window_destroy(DisplayServer::WindowID p_window_id) {
WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL(wd);
#ifdef WINDOWS_ENABLED
accesskit_windows_subclassing_adapter_free(wd->adapter);
#endif
#ifdef MACOS_ENABLED
accesskit_macos_subclassing_adapter_free(wd->adapter);
#endif
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter_free(wd->adapter);
#endif
accessibility_free_element(wd->root_id);
windows.erase(p_window_id);
}
void AccessibilityDriverAccessKit::_accessibility_deactivation_callback(void *p_user_data) {
// NOP
}
void AccessibilityDriverAccessKit::_accessibility_action_callback(struct accesskit_action_request *p_request, void *p_user_data) {
DisplayServer::WindowID window_id = (DisplayServer::WindowID)(size_t)p_user_data;
ERR_FAIL_COND(!singleton->windows.has(window_id));
RID rid = RID::from_uint64(p_request->target);
AccessibilityElement *ae = singleton->rid_owner.get_or_null(rid);
ERR_FAIL_NULL(ae);
Variant rq_data;
if (!ae->actions.has(p_request->action) && ae->role == ACCESSKIT_ROLE_TEXT_RUN && p_request->action == ACCESSKIT_ACTION_SCROLL_INTO_VIEW) {
AccessibilityElement *root_ae = singleton->rid_owner.get_or_null(ae->parent);
ERR_FAIL_NULL(root_ae);
ae = root_ae;
rq_data = ae->run;
}
if (ae->actions.has(p_request->action)) {
Callable &cb = ae->actions[p_request->action];
if (cb.is_valid()) {
if (p_request->data.has_value) {
switch (p_request->data.value.tag) {
case ACCESSKIT_ACTION_DATA_CUSTOM_ACTION: {
rq_data = p_request->data.value.custom_action;
} break;<|fim_suffix|> case ACCESSKIT_ACTION_DATA_SCROLL_HINT: {
switch (p_request->data.value.scroll_hint) {
case ACCESSKIT_SCROLL_HINT_TOP_LEFT: {
rq_data = DisplayServer::SCROLL_HINT_TOP_LEFT;
} break;
case ACCESSKIT_SCROLL_HINT_BOTTOM_RIGHT: {
rq_data = DisplayServer::SCROLL_HINT_BOTTOM_RIGHT;
} break;
case ACCESSKIT_SCROLL_HINT_TOP_EDGE: {
rq_data = DisplayServer::SCROLL_HINT_TOP_EDGE;
} break;
case ACCESSKIT_SCROLL_HINT_BOTTOM_EDGE: {
rq_data = DisplayServer::SCROLL_HINT_BOTTOM_EDGE;
} break;
case ACCESSKIT_SCROLL_HINT_LEFT_EDGE: {
rq_data = DisplayServer::SCROLL_HINT_LEFT_EDGE;
} break;
case ACCESSKIT_SCROLL_HINT_RIGHT_EDGE: {
rq_data = DisplayServer::SCROLL_HINT_RIGHT_EDGE;
} break;
default:
break;
}
} break;
case ACCESSKIT_ACTION_DATA_SCROLL_UNIT: {
if (p_request->data.value.scroll_unit == ACCESSKIT_SCROLL_UNIT_ITEM) {
rq_data = DisplayServer::SCROLL_UNIT_ITEM;
} else if (p_request->data.value.scroll_unit == ACCESSKIT_SCROLL_UNIT_PAGE) {
rq_data = DisplayServer::SCROLL_UNIT_PAGE;
}
} break;
case ACCESSKIT_ACTION_DATA_SCROLL_TO_POINT: {
rq_data = Point2(p_request->data.value.scroll_to_point.x, p_request->data.value.scroll_to_point.y);
} break;
case ACCESSKIT_ACTION_DATA_SET_SCROLL_OFFSET: {
rq_data = Point2(p_request->data.value.set_scroll_offset.x, p_request->data.value.set_scroll_offset.y);
} break;
case ACCESSKIT_ACTION_DATA_SET_TEXT_SELECTION: {
Dictionary sel;
RID start_rid = RID::from_uint64(p_request->data.value.set_text_selection.anchor.node);
AccessibilityElement *start_ae = singleton->rid_owner.get_or_null(start_rid);
ERR_FAIL_NULL(start_ae);
RID end_rid = RID::from_uint64(p_request->data.value.set_text_selection.focus.node);<|fim_middle|> case ACCESSKIT_ACTION_DATA_VALUE: {
rq_data = String::utf8(p_request->data.value.value);
} break;
case ACCESSKIT_ACTION_DATA_NUMERIC_VALUE: {
rq_data = p_request->data.value.numeric_value;
} break;
|
#endif
if (wd.adapter == nullptr) {
memdelete(ae);
rid_owner.free(wd.root_id);
windows.erase(p_window_id);
return false;
} else {
return true;
}
}
void AccessibilityDriverAccessKit::window_destroy(DisplayServer::WindowID p_window_id) {
WindowData *wd = windows.getptr(p_window_id);
ERR_FAIL_NULL(wd);
#ifdef WINDOWS_ENABLED
accesskit_windows_subclassing_adapter_free(wd->adapter);
#endif
#ifdef MACOS_ENABLED
accesskit_macos_subclassing_adapter_free(wd->adapter);
#endif
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter_free(wd->adapter);
#endif
accessibility_free_element(wd->root_id);
windows.erase(p_window_id);
}
void AccessibilityDriverAccessKit::_accessibility_deactivation_callback(void *p_user_data) {
// NOP
}
void AccessibilityDriverAccessKit::_accessibility_action_callback(struct accesskit_action_request *p_request, void *p_user_data) {
DisplayServer::WindowID window_id = (DisplayServer::WindowID)(size_t)p_user_data;
ERR_FAIL_COND(!singleton->windows.has(window_id));
RID rid = RID::from_uint64(p_request->target);
AccessibilityElement *ae = singleton->rid_owner.get_or_null(rid);
ERR_FAIL_NULL(ae);
Variant rq_data;
if (!ae->actions.has(p_request->action) && ae->role == ACCESSKIT_ROLE_TEXT_RUN && p_request->action == ACCESSKIT_ACTION_SCROLL_INTO_VIEW) {
AccessibilityElement *root_ae = singleton->rid_owner.get_or_null(ae->parent);
ERR_FAIL_NULL(root_ae);
ae = root_ae;
rq_data = ae->run;
}
if (ae->actions.has(p_request->action)) {
Callable &cb = ae->actions[p_request->action];
if (cb.is_valid()) {
if (p_request->data.has_value) {
switch (p_request->data.value.tag) {
case ACCESSKIT_ACTION_DATA_CUSTOM_ACTION: {
rq_data = p_request->data.value.custom_action;
} break;
|
case ACCESSKIT_ACTION_DATA_VALUE: {
rq_data = String::utf8(p_request->data.value.value);
} break;
case ACCESSKIT_ACTION_DATA_NUMERIC_VALUE: {
rq_data = p_request->data.value.numeric_value;
} break;
|
case ACCESSKIT_ACTION_DATA_SCROLL_HINT: {
switch (p_request->data.value.scroll_hint) {
case ACCESSKIT_SCROLL_HINT_TOP_LEFT: {
rq_data = DisplayServer::SCROLL_HINT_TOP_LEFT;
} break;
case ACCESSKIT_SCROLL_HINT_BOTTOM_RIGHT: {
rq_data = DisplayServer::SCROLL_HINT_BOTTOM_RIGHT;
} break;
case ACCESSKIT_SCROLL_HINT_TOP_EDGE: {
rq_data = DisplayServer::SCROLL_HINT_TOP_EDGE;
} break;
case ACCESSKIT_SCROLL_HINT_BOTTOM_EDGE: {
rq_data = DisplayServer::SCROLL_HINT_BOTTOM_EDGE;
} break;
case ACCESSKIT_SCROLL_HINT_LEFT_EDGE: {
rq_data = DisplayServer::SCROLL_HINT_LEFT_EDGE;
} break;
case ACCESSKIT_SCROLL_HINT_RIGHT_EDGE: {
rq_data = DisplayServer::SCROLL_HINT_RIGHT_EDGE;
} break;
default:
break;
}
} break;
case ACCESSKIT_ACTION_DATA_SCROLL_UNIT: {
if (p_request->data.value.scroll_unit == ACCESSKIT_SCROLL_UNIT_ITEM) {
rq_data = DisplayServer::SCROLL_UNIT_ITEM;
} else if (p_request->data.value.scroll_unit == ACCESSKIT_SCROLL_UNIT_PAGE) {
rq_data = DisplayServer::SCROLL_UNIT_PAGE;
}
} break;
case ACCESSKIT_ACTION_DATA_SCROLL_TO_POINT: {
rq_data = Point2(p_request->data.value.scroll_to_point.x, p_request->data.value.scroll_to_point.y);
} break;
case ACCESSKIT_ACTION_DATA_SET_SCROLL_OFFSET: {
rq_data = Point2(p_request->data.value.set_scroll_offset.x, p_request->data.value.set_scroll_offset.y);
} break;
case ACCESSKIT_ACTION_DATA_SET_TEXT_SELECTION: {
Dictionary sel;
RID start_rid = RID::from_uint64(p_request->data.value.set_text_selection.anchor.node);
AccessibilityElement *start_ae = singleton->rid_owner.get_or_null(start_rid);
ERR_FAIL_NULL(start_ae);
RID end_rid = RID::from_uint64(p_request->data.value.set_text_selection.focus.node);
|
random
|
<|fim_prefix|>/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "image_compress_astcenc.h"
#include "core/os/os.h"
#include "core/string/print_string.h"
#include <astcenc.h>
#ifdef TOOLS_ENABLED
void _compress_astc(Image *r_img, Image::ASTCFormat p_format) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
if (r_img->is_compressed()) {
return; // Do not compress, already compressed.
}
const Image::Format src_format = r_img->get_format();
const bool is_hdr = src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995;
if (src_format >= Image::FORMAT_RH && src_format <= Image::FORMAT_RGBAH) {
r_img->convert(Image::FORMAT_RGBAH);
} else if (src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995) {<|fim_suffix|> } else {
r_img->convert(Image::FORMAT_RGBA8);
}
// Determine encoder output format from our enum.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
Image::Format target_format = Image::FORMAT_MAX;
unsigned int block_x = 4;
unsigned int block_y = 4;
if (p_format == Image::ASTCFormat::ASTC_FORMAT_4x4) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_4x4_HDR;
} else {
target_format = Image::FORMAT_ASTC_4x4;
}
} else if (p_format == Image::ASTCFormat::ASTC_FORMAT_8x8) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_8x8_HDR;
} else {
target_format = Image::FORMAT_ASTC_8x8;
}
block_x = 8;
block_y = 8;
}
// Compress image data and (if required) mipmaps.
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
int required_width = (width % block_x) != 0 ? width + (block_x - (width % block_x)) : width;
int required_height = (height % block_y) != 0 ? height + (block_y - (height % block_y)) : height;
if (width != required_width || height != required_height) {
// Resize texture to fit block size.
r_img->resize(required_width, required_height);
width = required_width;
height = required_height;
}
print_verbose(vformat("astcenc: Encoding image size %dx%d to format %s%s.", width, height, Image::get_format_name(target_format), has_mipmaps ? ", with mipmaps" : ""));
// Initialize astcenc.
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
astcenc_config config;
config.block_x = block_x;
config.block_y = block_y;
config.profile = profile;
const float quality = ASTCENC_PRE_MEDIUM;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, 0, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,<|fim_middle|> r_img->convert(Image::FORMAT_RGBAF);
|
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "image_compress_astcenc.h"
#include "core/os/os.h"
#include "core/string/print_string.h"
#include <astcenc.h>
#ifdef TOOLS_ENABLED
void _compress_astc(Image *r_img, Image::ASTCFormat p_format) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
if (r_img->is_compressed()) {
return; // Do not compress, already compressed.
}
const Image::Format src_format = r_img->get_format();
const bool is_hdr = src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995;
if (src_format >= Image::FORMAT_RH && src_format <= Image::FORMAT_RGBAH) {
r_img->convert(Image::FORMAT_RGBAH);
} else if (src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995) {
|
r_img->convert(Image::FORMAT_RGBAF);
|
} else {
r_img->convert(Image::FORMAT_RGBA8);
}
// Determine encoder output format from our enum.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
Image::Format target_format = Image::FORMAT_MAX;
unsigned int block_x = 4;
unsigned int block_y = 4;
if (p_format == Image::ASTCFormat::ASTC_FORMAT_4x4) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_4x4_HDR;
} else {
target_format = Image::FORMAT_ASTC_4x4;
}
} else if (p_format == Image::ASTCFormat::ASTC_FORMAT_8x8) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_8x8_HDR;
} else {
target_format = Image::FORMAT_ASTC_8x8;
}
block_x = 8;
block_y = 8;
}
// Compress image data and (if required) mipmaps.
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
int required_width = (width % block_x) != 0 ? width + (block_x - (width % block_x)) : width;
int required_height = (height % block_y) != 0 ? height + (block_y - (height % block_y)) : height;
if (width != required_width || height != required_height) {
// Resize texture to fit block size.
r_img->resize(required_width, required_height);
width = required_width;
height = required_height;
}
print_verbose(vformat("astcenc: Encoding image size %dx%d to format %s%s.", width, height, Image::get_format_name(target_format), has_mipmaps ? ", with mipmaps" : ""));
// Initialize astcenc.
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
astcenc_config config;
config.block_x = block_x;
config.block_y = block_y;
config.profile = profile;
const float quality = ASTCENC_PRE_MEDIUM;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, 0, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
|
random
|
<|fim_prefix|>id, ae);
if (!p_placeholder.is_empty()) {
accesskit_node_set_placeholder(ae->node, p_placeholder.utf8().ptr());
} else {
accesskit_node_clear_placeholder(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_language(const RID &p_id, const String &p_language) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_language(ae->node, p_language.utf8().ptr());
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_orientation(const RID &p_id, bool p_vertical) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (p_vertical) {
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_TOP_TO_BOTTOM);
} else {
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_orientation(const RID &p_id, bool p_vertical) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (p_vertical) {
accesskit_node_set_orientation(ae->node, ACCESSKIT_ORIENTATION_VERTICAL);
} else {
accesskit_node_set_orientation(ae->node, ACCESSKIT_ORIENTATION_HORIZONTAL);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_shortcut(const RID &p_id, const String &p_shortcut) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
<|fim_suffix|>
_ensure_node(p_id, ae);
if (!p_shortcut.is_empty()) {
accesskit_node_set_keyboard_shortcut(ae->node, p_shortcut.utf8().ptr());
} else {
accesskit_node_clear_keyboard_shortcut(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_url(const RID &p_id, const String &p_url) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_url.is_empty()) {
accesskit_node_set_url(ae->node, p_url.utf8().ptr());
} else {
accesskit_node_clear_url(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_role_description(const RID &p_id, const String &p_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_description.is_empty()) {
accesskit_node_set_role_description(ae->node, p_description.utf8().ptr());
} else {
accesskit_node_clear_role_description(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_state_description(const RID &p_id, const String &p_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_description.is_empty()) {
accesskit_node_set_state_description(ae->node, p_description.utf8().ptr());
} else {
accesskit_node_clear_state_description(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_color_value(const RID &p_id, const Color &p_color) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed<|fim_middle|>AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
|
id, ae);
if (!p_placeholder.is_empty()) {
accesskit_node_set_placeholder(ae->node, p_placeholder.utf8().ptr());
} else {
accesskit_node_clear_placeholder(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_language(const RID &p_id, const String &p_language) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_language(ae->node, p_language.utf8().ptr());
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_orientation(const RID &p_id, bool p_vertical) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (p_vertical) {
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_TOP_TO_BOTTOM);
} else {
accesskit_node_set_text_direction(ae->node, ACCESSKIT_TEXT_DIRECTION_LEFT_TO_RIGHT);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_list_orientation(const RID &p_id, bool p_vertical) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (p_vertical) {
accesskit_node_set_orientation(ae->node, ACCESSKIT_ORIENTATION_VERTICAL);
} else {
accesskit_node_set_orientation(ae->node, ACCESSKIT_ORIENTATION_HORIZONTAL);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_shortcut(const RID &p_id, const String &p_shortcut) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
|
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
|
_ensure_node(p_id, ae);
if (!p_shortcut.is_empty()) {
accesskit_node_set_keyboard_shortcut(ae->node, p_shortcut.utf8().ptr());
} else {
accesskit_node_clear_keyboard_shortcut(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_url(const RID &p_id, const String &p_url) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_url.is_empty()) {
accesskit_node_set_url(ae->node, p_url.utf8().ptr());
} else {
accesskit_node_clear_url(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_role_description(const RID &p_id, const String &p_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_description.is_empty()) {
accesskit_node_set_role_description(ae->node, p_description.utf8().ptr());
} else {
accesskit_node_clear_role_description(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_state_description(const RID &p_id, const String &p_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_description.is_empty()) {
accesskit_node_set_state_description(ae->node, p_description.utf8().ptr());
} else {
accesskit_node_clear_state_description(ae->node);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_color_value(const RID &p_id, const Color &p_color) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed
|
ast_based
|
<|fim_prefix|> CrcCheck { "CRC-8-RANDOM-9", 8, 0x000000000000002c, 0x0000000000000094, 0x0000000000000001, false, false, 0x0000000000000095, { 52, 156, 20, 14, 1, 178, 132, 57, 220, 251, 1, 215, 195, 236, 197, 102, 193, 157, 140, 196, 132, 204, 155, 140, 185, 73, 13, 252, 175, 141, 171, 139, 221, 14, 156, 253, 107, 24, 153, 166, 217, 181, 203, 39, 172, 114, 160, 88, 197, 221, 51, 241, 70, 152, 181, 31, 88, 165, 30, 123, 231, 163, 75, 107, 55, 95, 2, 13, 70, 128, 165, 27, 224, 105, 51, 97, 76, 160, 100, 245, 174, 32, 109, 251, 43, 55, 139, 88, 89, 122, 194, 92, 245, 188, 236, 38, 211, 19, 252, 17, 209, 60, 133, 227, 36, 69, 213, 161, 162, 187, 161, 202, 3, 71, 32, 29, 131, 167, 43, 99, 175, 141, 70, 62, 3, 56, 100, 107, 165, 123, 239, 252, 219, 111, 11, 31, 216, 22, 111, 27, 7, 44, 168, 68, 216, 58, 207, 231, 94, 58, 178, 210, 149 } },
};
TEST_ASSERT(!checkCrcAgainstGondenSamples(hex::crypt::crc8, golden_samples));
TEST_SUCCESS();<|fim_suffix|>};
struct HashCheck {
std::string data;
std::string result;
};
template<typename Ret, typename Range>
int checkHashProviderAgainstGondenSamples(Ret (*func)(hex::prv::Provider *&, u64, size_t), Range golden_samples) {
for (auto &i : golden_samples) {
std::vector<u8> data(i.data.data(), i.data.data() + i.data.size());
hex::test::TestProvider provider(&data);
hex::prv::Provider *provider2 = &provider;
auto res = func(provider2, 0, i.data.size());
TEST_ASSERT(std::equal(std::begin(res), std::end(res), hex::crypt::decode16(i.result).begin()),
"data: '{}' got: {} expected: {}",
i.data,
hex::crypt::encode16(std::vector(res.begin(), res.end())),
i.result);
}
TEST_SUCCESS();
}
template<typename Ret, typename Range>
int checkHashVectorAgainstGondenSamples(Ret (*func)(const std::vector<u8> &), Range golden_samples) {
for (auto &i : golden_samples) {
std::vector<u8> data(i.data.data(), i.data.data() + i.data.size());
auto res = func(data);
TEST_ASSERT(std::equal(std::begin(res), std::end(res), hex::crypt::decode16(i.result).begin()),
"data: '{}' got: {} expected: {}",
i.data,
hex::crypt::encode16(std::vector(res.begin(), res.end())),
i.result);
}
TEST_SUCCESS();
}
TEST_SEQUENCE("md5") {
std::array golden_samples = {
// source: RFC 1321: The MD5 Message-Digest Algorithm [https://datatracker.ietf.org/doc/html/rfc1321#appendix-A.5]
HashCheck {"",
"d41d8cd98f00b204e9800998ecf8427e"},
HashCheck { "a",
"0cc175b9c0f1b6a831c399e269772661"},
HashCheck { "abc",
"900150983cd24fb0d6963f7d28e17f72"},
HashCheck { "message digest",
"f96b697d7cb7938d525a2f31aaf161d0"},
HashCheck { "abcdefghijklmnopqrstuvwxyz",<|fim_middle|>};
TEST_SEQUENCE("CRC8Random") {
TEST_ASSERT(!checkCrcAgainstRandomData(hex::crypt::crc8, 8));
TEST_SUCCESS();
|
CrcCheck { "CRC-8-RANDOM-9", 8, 0x000000000000002c, 0x0000000000000094, 0x0000000000000001, false, false, 0x0000000000000095, { 52, 156, 20, 14, 1, 178, 132, 57, 220, 251, 1, 215, 195, 236, 197, 102, 193, 157, 140, 196, 132, 204, 155, 140, 185, 73, 13, 252, 175, 141, 171, 139, 221, 14, 156, 253, 107, 24, 153, 166, 217, 181, 203, 39, 172, 114, 160, 88, 197, 221, 51, 241, 70, 152, 181, 31, 88, 165, 30, 123, 231, 163, 75, 107, 55, 95, 2, 13, 70, 128, 165, 27, 224, 105, 51, 97, 76, 160, 100, 245, 174, 32, 109, 251, 43, 55, 139, 88, 89, 122, 194, 92, 245, 188, 236, 38, 211, 19, 252, 17, 209, 60, 133, 227, 36, 69, 213, 161, 162, 187, 161, 202, 3, 71, 32, 29, 131, 167, 43, 99, 175, 141, 70, 62, 3, 56, 100, 107, 165, 123, 239, 252, 219, 111, 11, 31, 216, 22, 111, 27, 7, 44, 168, 68, 216, 58, 207, 231, 94, 58, 178, 210, 149 } },
};
TEST_ASSERT(!checkCrcAgainstGondenSamples(hex::crypt::crc8, golden_samples));
TEST_SUCCESS();
|
};
TEST_SEQUENCE("CRC8Random") {
TEST_ASSERT(!checkCrcAgainstRandomData(hex::crypt::crc8, 8));
TEST_SUCCESS();
|
};
struct HashCheck {
std::string data;
std::string result;
};
template<typename Ret, typename Range>
int checkHashProviderAgainstGondenSamples(Ret (*func)(hex::prv::Provider *&, u64, size_t), Range golden_samples) {
for (auto &i : golden_samples) {
std::vector<u8> data(i.data.data(), i.data.data() + i.data.size());
hex::test::TestProvider provider(&data);
hex::prv::Provider *provider2 = &provider;
auto res = func(provider2, 0, i.data.size());
TEST_ASSERT(std::equal(std::begin(res), std::end(res), hex::crypt::decode16(i.result).begin()),
"data: '{}' got: {} expected: {}",
i.data,
hex::crypt::encode16(std::vector(res.begin(), res.end())),
i.result);
}
TEST_SUCCESS();
}
template<typename Ret, typename Range>
int checkHashVectorAgainstGondenSamples(Ret (*func)(const std::vector<u8> &), Range golden_samples) {
for (auto &i : golden_samples) {
std::vector<u8> data(i.data.data(), i.data.data() + i.data.size());
auto res = func(data);
TEST_ASSERT(std::equal(std::begin(res), std::end(res), hex::crypt::decode16(i.result).begin()),
"data: '{}' got: {} expected: {}",
i.data,
hex::crypt::encode16(std::vector(res.begin(), res.end())),
i.result);
}
TEST_SUCCESS();
}
TEST_SEQUENCE("md5") {
std::array golden_samples = {
// source: RFC 1321: The MD5 Message-Digest Algorithm [https://datatracker.ietf.org/doc/html/rfc1321#appendix-A.5]
HashCheck {"",
"d41d8cd98f00b204e9800998ecf8427e"},
HashCheck { "a",
"0cc175b9c0f1b6a831c399e269772661"},
HashCheck { "abc",
"900150983cd24fb0d6963f7d28e17f72"},
HashCheck { "message digest",
"f96b697d7cb7938d525a2f31aaf161d0"},
HashCheck { "abcdefghijklmnopqrstuvwxyz",
|
random
|
<|fim_prefix|>#include <hex/helpers/crypto.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/test/test_provider.hpp>
#include <hex/test/tests.hpp>
#include <random>
#include <vector>
#include <array>
#include <algorithm>
#include <fmt/ranges.h>
struct EncodeChek {
std::vector<u8> vec;
std::string string;
};
TEST_SEQUENCE("EncodeDecode16") {
std::array golden_samples = {
// source: created by hand
EncodeChek {{}, "" },
EncodeChek { { 0x2a }, "2A" },
EncodeChek { { 0x00, 0x2a }, "002A" },
EncodeChek { { 0x2a, 0x00 }, "2A00" },
EncodeChek { { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }, "DEADBEEF422A00FF"},
};
for (auto &i : golden_samples) {
std::string string;
TEST_ASSERT((string = hex::crypt::encode16(i.vec)) == i.string, "string: '{}' i.string: '{}' from: {}", string, i.string, i.vec);
std::vector<u8> vec;
TEST_ASSERT((vec = hex::crypt::decode16(i.string)) == i.vec, "vec: {} i.vec: {} from: '{}'", vec, i.vec, i.string);
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution dataLen(0, 1024);
std::uniform_int_distribution<u8> data;
for (int i = 0; i < 1000; i++) {
std::vector<u8> original(dataLen(gen));
std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
auto encoded = hex::crypt::encode16(original);
auto decoded = hex::crypt::decode16(encoded);
TEST_ASSERT(decoded == original, "decoded: {} encoded: '{}' original: {}", decoded, encoded, original);
}
if (<|fim_suffix|> == "2A") {
hex::log::error("Known bug: in function hex::crypt::encode16 mbedtls_mpi_read_binary ingores initial null bytes");
TEST_FAIL();
}
TEST_SUCCESS();
};
std::string vectorToString(std::vector<u8> in) {
return std::string(reinterpret_cast<char *>(in.data()), in.size());
}
std::vector<u8> stringToVector(std::string in) {
return std::vector<u8>(in.begin(), in.end());
}
TEST_SEQUENCE("EncodeDecode64") {
std::array golden_samples = {
// source: linux command base64 (from GNU coreutils)
EncodeChek {{}, "" },
EncodeChek { { 0x2a }, "Kg==" },
EncodeChek { { 0x00, 0x2a }, "ACo=" },
EncodeChek { { 0x2a, 0x00 }, "KgA=" },
EncodeChek { { 0x42, 0xff, 0x55 }, "Qv9V" },
EncodeChek { { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }, "3q2+70IqAP8="},
};
for (auto &i : golden_samples) {
std::string string;
TEST_ASSERT((string = vectorToString(hex::crypt::encode64(i.vec))) == i.string, "string: '{}' i.string: '{}' from: {}", string, i.string, i.vec);
std::vector<u8> vec;
TEST_ASSERT((vec = hex::crypt::decode64(stringToVector(i.string))) == i.vec, "vec: {} i.vec: {} from: '{}'", vec, i.vec, i.string);
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution dataLen(0, 1024);
std::uniform_int_distribution<u8> data;
for (int i = 0; i < 1000; i++) {
std::vector<u8> original(dataLen(gen));
std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
auto encoded = vectorToString(hex::crypt::encode64(original));
auto decoded = hex::crypt::decode64(stringToVector(encoded));
TEST_ASSERT(decoded == original, "decode<|fim_middle|>hex::crypt::encode16({ 0x00, 0x2a })
|
#include <hex/helpers/crypto.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/test/test_provider.hpp>
#include <hex/test/tests.hpp>
#include <random>
#include <vector>
#include <array>
#include <algorithm>
#include <fmt/ranges.h>
struct EncodeChek {
std::vector<u8> vec;
std::string string;
};
TEST_SEQUENCE("EncodeDecode16") {
std::array golden_samples = {
// source: created by hand
EncodeChek {{}, "" },
EncodeChek { { 0x2a }, "2A" },
EncodeChek { { 0x00, 0x2a }, "002A" },
EncodeChek { { 0x2a, 0x00 }, "2A00" },
EncodeChek { { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }, "DEADBEEF422A00FF"},
};
for (auto &i : golden_samples) {
std::string string;
TEST_ASSERT((string = hex::crypt::encode16(i.vec)) == i.string, "string: '{}' i.string: '{}' from: {}", string, i.string, i.vec);
std::vector<u8> vec;
TEST_ASSERT((vec = hex::crypt::decode16(i.string)) == i.vec, "vec: {} i.vec: {} from: '{}'", vec, i.vec, i.string);
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution dataLen(0, 1024);
std::uniform_int_distribution<u8> data;
for (int i = 0; i < 1000; i++) {
std::vector<u8> original(dataLen(gen));
std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
auto encoded = hex::crypt::encode16(original);
auto decoded = hex::crypt::decode16(encoded);
TEST_ASSERT(decoded == original, "decoded: {} encoded: '{}' original: {}", decoded, encoded, original);
}
if (
|
hex::crypt::encode16({ 0x00, 0x2a })
|
== "2A") {
hex::log::error("Known bug: in function hex::crypt::encode16 mbedtls_mpi_read_binary ingores initial null bytes");
TEST_FAIL();
}
TEST_SUCCESS();
};
std::string vectorToString(std::vector<u8> in) {
return std::string(reinterpret_cast<char *>(in.data()), in.size());
}
std::vector<u8> stringToVector(std::string in) {
return std::vector<u8>(in.begin(), in.end());
}
TEST_SEQUENCE("EncodeDecode64") {
std::array golden_samples = {
// source: linux command base64 (from GNU coreutils)
EncodeChek {{}, "" },
EncodeChek { { 0x2a }, "Kg==" },
EncodeChek { { 0x00, 0x2a }, "ACo=" },
EncodeChek { { 0x2a, 0x00 }, "KgA=" },
EncodeChek { { 0x42, 0xff, 0x55 }, "Qv9V" },
EncodeChek { { 0xde, 0xad, 0xbe, 0xef, 0x42, 0x2a, 0x00, 0xff }, "3q2+70IqAP8="},
};
for (auto &i : golden_samples) {
std::string string;
TEST_ASSERT((string = vectorToString(hex::crypt::encode64(i.vec))) == i.string, "string: '{}' i.string: '{}' from: {}", string, i.string, i.vec);
std::vector<u8> vec;
TEST_ASSERT((vec = hex::crypt::decode64(stringToVector(i.string))) == i.vec, "vec: {} i.vec: {} from: '{}'", vec, i.vec, i.string);
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution dataLen(0, 1024);
std::uniform_int_distribution<u8> data;
for (int i = 0; i < 1000; i++) {
std::vector<u8> original(dataLen(gen));
std::generate(std::begin(original), std::end(original), [&] { return data(gen); });
auto encoded = vectorToString(hex::crypt::encode64(original));
auto decoded = hex::crypt::decode64(stringToVector(encoded));
TEST_ASSERT(decoded == original, "decode
|
ast_based
|
<|fim_prefix|>
undo_redo->add_do_method(animation.ptr(), "remove_track", track);
undo_redo->add_undo_method(animation.ptr(), "add_track", Animation::TrackType::TYPE_BEZIER, track);
undo_redo->add_undo_method(animation.ptr(), "track_set_path", track, animation->track_get_path(track));
for (int i = 0; i < animation->track_get_key_count(track); ++i) {
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
track,
animation->track_get_key_time(track, i),
animation->bezier_track_get_key_value(track, i),
animation->bezier_track_get_key_in_handle(track, i),
animation->bezier_track_get_key_out_handle(track, i),
animation->bezier_track_get_key_handle_mode(track, i));
}
undo_redo->commit_action();
selected_track = CLAMP(selected_track, 0, animation->get_track_count() - 1);
}
return;
} else if (I.key == LOCK_ICON) {
if (locked_tracks.has(track)) {
locked_tracks.erase(track);
} else {
locked_tracks.insert(track);
if (selected_track == track) {
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!locked_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
set_animation_and_track(animation, i, read_only);
break;
}
}
}
}
queue_redraw();
return;
} else if (I.key == VISIBILITY_ICON) {
if (hidden_tracks.has(track)) {
hidden_tracks.erase(track);
} else {
hidden_tracks.insert(track);
if (selected_track == track) {
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!hidden_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
set_animation_and_track(animation, i, read_only);
break;
}<|fim_suffix|> Vector<int> visible_tracks;
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!hidden_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
visible_tracks.push_back(i);
}
}
if (visible_tracks.size() == 1) {
solo_track = visible_tracks[0];
} else {
solo_track = -1;
}
queue_redraw();
return;
} else if (I.key == SOLO_ICON) {
if (solo_track == track) {
solo_track = -1;
hidden_tracks.clear();
} else {
if (hidden_tracks.has(track)) {
hidden_tracks.erase(track);
}
for (int i = 0; i < animation->get_track_count(); ++i) {
if (animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
if (i != track && !hidden_tracks.has(i)) {
hidden_tracks.insert(i);
}
}
}
set_animation_and_track(animation, track, read_only);
solo_track = track;
}
queue_redraw();
return;
}
return;
}
}
}
// Check this first, to allow manipulating key handles while ignoring keyframes before scaling/moving.
bool inside_selection_handles_rect = !read_only && selection_handles_rect.has_point(mb->get_position());
// First, check keyframe.
// Command/Control makes it ignore the keyframe, so control point editors can be force-edited.
if (!inside_selection_handles_rect && !mb->is_command_or_control_pressed()) {
if (_try_select_at_ui_pos(mb->get_position(), mb->is_shift_pressed(), true)) {
return;
}
}
// Second, check key handles.
for (int i = 0; i < edit_points.size(); i++) {
if (!read_only) {
if (edit_points[i].in_rect.has_point(mb->get_position())) {
moving_handle = -1;
moving_handle_key = edit_points[i].key;
moving_handle_track = edit_points[i].track;
moving_handle_left = animation->bezier_track_get_key_in_handle(edit_points[i].track, edit_points[i].key);<|fim_middle|> }
}
}
|
undo_redo->add_do_method(animation.ptr(), "remove_track", track);
undo_redo->add_undo_method(animation.ptr(), "add_track", Animation::TrackType::TYPE_BEZIER, track);
undo_redo->add_undo_method(animation.ptr(), "track_set_path", track, animation->track_get_path(track));
for (int i = 0; i < animation->track_get_key_count(track); ++i) {
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
track,
animation->track_get_key_time(track, i),
animation->bezier_track_get_key_value(track, i),
animation->bezier_track_get_key_in_handle(track, i),
animation->bezier_track_get_key_out_handle(track, i),
animation->bezier_track_get_key_handle_mode(track, i));
}
undo_redo->commit_action();
selected_track = CLAMP(selected_track, 0, animation->get_track_count() - 1);
}
return;
} else if (I.key == LOCK_ICON) {
if (locked_tracks.has(track)) {
locked_tracks.erase(track);
} else {
locked_tracks.insert(track);
if (selected_track == track) {
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!locked_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
set_animation_and_track(animation, i, read_only);
break;
}
}
}
}
queue_redraw();
return;
} else if (I.key == VISIBILITY_ICON) {
if (hidden_tracks.has(track)) {
hidden_tracks.erase(track);
} else {
hidden_tracks.insert(track);
if (selected_track == track) {
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!hidden_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
set_animation_and_track(animation, i, read_only);
break;
}
|
}
}
}
|
Vector<int> visible_tracks;
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!hidden_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
visible_tracks.push_back(i);
}
}
if (visible_tracks.size() == 1) {
solo_track = visible_tracks[0];
} else {
solo_track = -1;
}
queue_redraw();
return;
} else if (I.key == SOLO_ICON) {
if (solo_track == track) {
solo_track = -1;
hidden_tracks.clear();
} else {
if (hidden_tracks.has(track)) {
hidden_tracks.erase(track);
}
for (int i = 0; i < animation->get_track_count(); ++i) {
if (animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
if (i != track && !hidden_tracks.has(i)) {
hidden_tracks.insert(i);
}
}
}
set_animation_and_track(animation, track, read_only);
solo_track = track;
}
queue_redraw();
return;
}
return;
}
}
}
// Check this first, to allow manipulating key handles while ignoring keyframes before scaling/moving.
bool inside_selection_handles_rect = !read_only && selection_handles_rect.has_point(mb->get_position());
// First, check keyframe.
// Command/Control makes it ignore the keyframe, so control point editors can be force-edited.
if (!inside_selection_handles_rect && !mb->is_command_or_control_pressed()) {
if (_try_select_at_ui_pos(mb->get_position(), mb->is_shift_pressed(), true)) {
return;
}
}
// Second, check key handles.
for (int i = 0; i < edit_points.size(); i++) {
if (!read_only) {
if (edit_points[i].in_rect.has_point(mb->get_position())) {
moving_handle = -1;
moving_handle_key = edit_points[i].key;
moving_handle_track = edit_points[i].track;
moving_handle_left = animation->bezier_track_get_key_in_handle(edit_points[i].track, edit_points[i].key);
|
random
|
<|fim_prefix|>;
menu->add_icon_item(get_editor_theme_icon(SNAME("BezierHandlesBalanced")), TTR("Make Handles Balanced"), MENU_KEY_SET_HANDLE_BALANCED);
menu->add_icon_item(get_editor_theme_icon(SNAME("BezierHandlesMirror")), TTR("Make Handles Mirrored"), MENU_KEY_SET_HANDLE_MIRRORED);
menu->add_separator();
menu->add_icon_item(get_editor_theme_icon(SNAME("BezierHandlesBalanced")), TTR("Make Handles Balanced (Auto Tangent)"), MENU_KEY_SET_HANDLE_AUTO_BALANCED);
menu->add_icon_item(get_editor_theme_icon(SNAME("BezierHandlesMirror")), TTR("Make Handles Mirrored (Auto Tangent)"), MENU_KEY_SET_HANDLE_AUTO_MIRRORED);
}
if (menu->get_item_count()) {
menu->reset_size();
menu->set_position(popup_pos);
menu->popup();
}
}
}
}
if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
Point2 pos = mb->get_position();
bool no_mod_key_pressed = !mb->is_alt_pressed() && !mb->is_shift_pressed() && !mb->is_command_or_control_pressed();
if (mb->is_double_click() && !moving_selection && no_mod_key_pressed) {
int x = pos.x - timeline->get_name_limit();
float ofs = x / timeline->get_zoom_scale() + timeline->get_value();
emit_signal(SNAME("timeline_changed"), ofs, false);
}
for (const KeyValue<int, Rect2> &E : subtracks) {
if (E.value.has_point(mb->get_position())) {
if (!locked_tracks.has(E.key) && !hidden_tracks.has(E.key)) {
set_animation_and_track(animation, E.key, read_only);
_clear_selection();
}
return;
}
}
for (const KeyValue<int, RBMap<int, Rect2>> &E : subtrack_icons) {
int track = E.key;
RBMap<int, Rect2> track_icons = E.value;
for (const KeyValue<int, Rect2> &I : track_icons) {
if (I.value.has_point(mb->get_position())) {
if (I.key == REMOVE_ICON) {
if (!read_only) {
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action("Remove Bezier Track", UndoRedo::MERGE_DISABLE, <|fim_suffix|>);
undo_redo->add_do_method(this, "_update_locked_tracks_after", track);
undo_redo->add_do_method(this, "_update_hidden_tracks_after", track);
undo_redo->add_do_method(animation.ptr(), "remove_track", track);
undo_redo->add_undo_method(animation.ptr(), "add_track", Animation::TrackType::TYPE_BEZIER, track);
undo_redo->add_undo_method(animation.ptr(), "track_set_path", track, animation->track_get_path(track));
for (int i = 0; i < animation->track_get_key_count(track); ++i) {
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
track,
animation->track_get_key_time(track, i),
animation->bezier_track_get_key_value(track, i),
animation->bezier_track_get_key_in_handle(track, i),
animation->bezier_track_get_key_out_handle(track, i),
animation->bezier_track_get_key_handle_mode(track, i));
}
undo_redo->commit_action();
selected_track = CLAMP(selected_track, 0, animation->get_track_count() - 1);
}
return;
} else if (I.key == LOCK_ICON) {
if (locked_tracks.has(track)) {
locked_tracks.erase(track);
} else {
locked_tracks.insert(track);
if (selected_track == track) {
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!locked_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
set_animation_and_track(animation, i, read_only);
break;
}
}
}
}
queue_redraw();
return;
} else if (I.key == VISIBILITY_ICON) {
if (hidden_tracks.has(track)) {
hidden_tracks.erase(track);
} else {
hidden_tracks.insert(track);
if (selected_track == track) {
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!hidden_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType<|fim_middle|>animation.ptr()
|
;
menu->add_icon_item(get_editor_theme_icon(SNAME("BezierHandlesBalanced")), TTR("Make Handles Balanced"), MENU_KEY_SET_HANDLE_BALANCED);
menu->add_icon_item(get_editor_theme_icon(SNAME("BezierHandlesMirror")), TTR("Make Handles Mirrored"), MENU_KEY_SET_HANDLE_MIRRORED);
menu->add_separator();
menu->add_icon_item(get_editor_theme_icon(SNAME("BezierHandlesBalanced")), TTR("Make Handles Balanced (Auto Tangent)"), MENU_KEY_SET_HANDLE_AUTO_BALANCED);
menu->add_icon_item(get_editor_theme_icon(SNAME("BezierHandlesMirror")), TTR("Make Handles Mirrored (Auto Tangent)"), MENU_KEY_SET_HANDLE_AUTO_MIRRORED);
}
if (menu->get_item_count()) {
menu->reset_size();
menu->set_position(popup_pos);
menu->popup();
}
}
}
}
if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
Point2 pos = mb->get_position();
bool no_mod_key_pressed = !mb->is_alt_pressed() && !mb->is_shift_pressed() && !mb->is_command_or_control_pressed();
if (mb->is_double_click() && !moving_selection && no_mod_key_pressed) {
int x = pos.x - timeline->get_name_limit();
float ofs = x / timeline->get_zoom_scale() + timeline->get_value();
emit_signal(SNAME("timeline_changed"), ofs, false);
}
for (const KeyValue<int, Rect2> &E : subtracks) {
if (E.value.has_point(mb->get_position())) {
if (!locked_tracks.has(E.key) && !hidden_tracks.has(E.key)) {
set_animation_and_track(animation, E.key, read_only);
_clear_selection();
}
return;
}
}
for (const KeyValue<int, RBMap<int, Rect2>> &E : subtrack_icons) {
int track = E.key;
RBMap<int, Rect2> track_icons = E.value;
for (const KeyValue<int, Rect2> &I : track_icons) {
if (I.value.has_point(mb->get_position())) {
if (I.key == REMOVE_ICON) {
if (!read_only) {
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action("Remove Bezier Track", UndoRedo::MERGE_DISABLE,
|
animation.ptr()
|
);
undo_redo->add_do_method(this, "_update_locked_tracks_after", track);
undo_redo->add_do_method(this, "_update_hidden_tracks_after", track);
undo_redo->add_do_method(animation.ptr(), "remove_track", track);
undo_redo->add_undo_method(animation.ptr(), "add_track", Animation::TrackType::TYPE_BEZIER, track);
undo_redo->add_undo_method(animation.ptr(), "track_set_path", track, animation->track_get_path(track));
for (int i = 0; i < animation->track_get_key_count(track); ++i) {
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
track,
animation->track_get_key_time(track, i),
animation->bezier_track_get_key_value(track, i),
animation->bezier_track_get_key_in_handle(track, i),
animation->bezier_track_get_key_out_handle(track, i),
animation->bezier_track_get_key_handle_mode(track, i));
}
undo_redo->commit_action();
selected_track = CLAMP(selected_track, 0, animation->get_track_count() - 1);
}
return;
} else if (I.key == LOCK_ICON) {
if (locked_tracks.has(track)) {
locked_tracks.erase(track);
} else {
locked_tracks.insert(track);
if (selected_track == track) {
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!locked_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) {
set_animation_and_track(animation, i, read_only);
break;
}
}
}
}
queue_redraw();
return;
} else if (I.key == VISIBILITY_ICON) {
if (hidden_tracks.has(track)) {
hidden_tracks.erase(track);
} else {
hidden_tracks.insert(track);
if (selected_track == track) {
for (int i = 0; i < animation->get_track_count(); ++i) {
if (!hidden_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType
|
ast_based
|
<|fim_prefix|> LOG("\n");
LOG("|%6s | %6s | %4s | %6s | %8s | %8s | %8s | %8s | %8s | %8s |\n", "PP", "TG", "B", "N_KV", "T_PP s", "S_PP t/s", "T_TG s", "S_TG t/s", "T s", "S t/s");
LOG("|%6s-|-%6s-|-%4s-|-%6s-|-%8s-|-%8s-|-%8s-|-%8s-|-%8s-|-%8s-|\n", "------", "------", "----", "------", "--------", "--------", "--------", "--------", "--------", "--------");
}
for ( int i_pp = 0; i_pp < (int) n_pp.size(); ++i_pp) {
for ( int i_tg = 0; i_tg < (int) n_tg.size(); ++i_tg) {
for (int i_pl = 0; i_pl < (int) n_pl.size(); ++i_pl) {
const int pp = n_pp[i_pp];
const int tg = n_tg[i_tg];
const int pl = n_pl[i_pl];
const int n_ctx_req = is_pp_shared ? (params.kv_unified ? pp : pl*pp) + pl*tg : pl*(pp + tg);
if (n_ctx_req > n_kv_max) {
continue;
}
common_batch_clear(batch);
for (int j = 0; j < (is_pp_shared ? 1 : pl); ++j) {
for (int i = 0; i < pp; ++i) {
common_batch_add(batch, get_token_rand(), i, { j }, i == pp - 1);
}
}
llama_memory_clear(mem, false);
const auto t_pp_start = ggml_time_us();
if (!decode_helper(ctx, batch, ctx_params.n_batch, false)) {
LOG_ERR("%s: llama_decode() failed\n", __func__);
return 1;
}
llama_synchronize(ctx);
const auto t_pp_end = ggml_time_us();
if (is_pp_shared) {
for (int32_t i = 1; i < pl; ++i) {
llama_memory_seq_cp(mem, 0, i, -1, -1);
}
if (!params.kv_unified) {
// run one dummy token to apply the memory copy
common_batch_clear(batch);<|fim_suffix|> const auto t_tg_start = ggml_time_us();
for (int i = 0; i < tg; ++i) {
common_batch_clear(batch);
for (int j = 0; j < pl; ++j) {
common_batch_add(batch, get_token_rand(), pp + i, { j }, true);
}
if (!decode_helper(ctx, batch, ctx_params.n_batch, true)) {
LOG_ERR("%s: llama_decode() failed\n", __func__);
return 1;
}
}
const auto t_tg_end = ggml_time_us();
const int32_t n_kv = n_ctx_req;
const float t_pp = (t_pp_end - t_pp_start) / 1000000.0f;
const float t_tg = (t_tg_end - t_tg_start) / 1000000.0f;
const float t = t_pp + t_tg;
const float speed_pp = is_pp_shared ? pp / t_pp : pl*pp / t_pp;
const float speed_tg = pl*tg / t_tg;
const float speed = ((is_pp_shared ? pp : pl*pp) + pl*tg) / t;
if(params.batched_bench_output_jsonl) {
LOG(
"{\"n_kv_max\": %d, \"n_batch\": %d, \"n_ubatch\": %d, \"flash_attn\": %d, \"is_pp_shared\": %d, \"n_gpu_layers\": %d, \"n_threads\": %u, \"n_threads_batch\": %u, "
"\"pp\": %d, \"tg\": %d, \"pl\": %d, \"n_kv\": %d, \"t_pp\": %f, \"speed_pp\": %f, \"t_tg\": %f, \"speed_tg\": %f, \"t\": %f, \"speed\": %f}\n",
n_kv_max, params.n_batch, params.n_ubatch, int(params.flash_attn_type), params.is_pp_shared, params.n_gpu_layers, ctx_params.n_threads, ctx_params.n_threads_batch,
pp, tg, pl, n_kv, t_pp, speed_pp, t_tg, speed_tg, t, speed
);
} else {
LOG("|%6d | %6d | %4d | %6d | %8.3f | %8.2f | %8.3f | %8.2f | %8.3f | %8.2f |\n", pp, tg, pl, n_kv, t_pp, speed_pp, t_tg, speed_tg, t, speed);
}<|fim_middle|> common_batch_add(batch, get_token_rand(), pp + 0, { 0 }, true);
if (!decode_helper(ctx, batch, ctx_params.n_batch, true)) {
LOG_ERR("%s: llama_decode() failed\n", __func__);
return 1;
}
llama_memory_seq_rm(mem, 0, pp, -1);
}
}
|
LOG("\n");
LOG("|%6s | %6s | %4s | %6s | %8s | %8s | %8s | %8s | %8s | %8s |\n", "PP", "TG", "B", "N_KV", "T_PP s", "S_PP t/s", "T_TG s", "S_TG t/s", "T s", "S t/s");
LOG("|%6s-|-%6s-|-%4s-|-%6s-|-%8s-|-%8s-|-%8s-|-%8s-|-%8s-|-%8s-|\n", "------", "------", "----", "------", "--------", "--------", "--------", "--------", "--------", "--------");
}
for ( int i_pp = 0; i_pp < (int) n_pp.size(); ++i_pp) {
for ( int i_tg = 0; i_tg < (int) n_tg.size(); ++i_tg) {
for (int i_pl = 0; i_pl < (int) n_pl.size(); ++i_pl) {
const int pp = n_pp[i_pp];
const int tg = n_tg[i_tg];
const int pl = n_pl[i_pl];
const int n_ctx_req = is_pp_shared ? (params.kv_unified ? pp : pl*pp) + pl*tg : pl*(pp + tg);
if (n_ctx_req > n_kv_max) {
continue;
}
common_batch_clear(batch);
for (int j = 0; j < (is_pp_shared ? 1 : pl); ++j) {
for (int i = 0; i < pp; ++i) {
common_batch_add(batch, get_token_rand(), i, { j }, i == pp - 1);
}
}
llama_memory_clear(mem, false);
const auto t_pp_start = ggml_time_us();
if (!decode_helper(ctx, batch, ctx_params.n_batch, false)) {
LOG_ERR("%s: llama_decode() failed\n", __func__);
return 1;
}
llama_synchronize(ctx);
const auto t_pp_end = ggml_time_us();
if (is_pp_shared) {
for (int32_t i = 1; i < pl; ++i) {
llama_memory_seq_cp(mem, 0, i, -1, -1);
}
if (!params.kv_unified) {
// run one dummy token to apply the memory copy
common_batch_clear(batch);
|
common_batch_add(batch, get_token_rand(), pp + 0, { 0 }, true);
if (!decode_helper(ctx, batch, ctx_params.n_batch, true)) {
LOG_ERR("%s: llama_decode() failed\n", __func__);
return 1;
}
llama_memory_seq_rm(mem, 0, pp, -1);
}
}
|
const auto t_tg_start = ggml_time_us();
for (int i = 0; i < tg; ++i) {
common_batch_clear(batch);
for (int j = 0; j < pl; ++j) {
common_batch_add(batch, get_token_rand(), pp + i, { j }, true);
}
if (!decode_helper(ctx, batch, ctx_params.n_batch, true)) {
LOG_ERR("%s: llama_decode() failed\n", __func__);
return 1;
}
}
const auto t_tg_end = ggml_time_us();
const int32_t n_kv = n_ctx_req;
const float t_pp = (t_pp_end - t_pp_start) / 1000000.0f;
const float t_tg = (t_tg_end - t_tg_start) / 1000000.0f;
const float t = t_pp + t_tg;
const float speed_pp = is_pp_shared ? pp / t_pp : pl*pp / t_pp;
const float speed_tg = pl*tg / t_tg;
const float speed = ((is_pp_shared ? pp : pl*pp) + pl*tg) / t;
if(params.batched_bench_output_jsonl) {
LOG(
"{\"n_kv_max\": %d, \"n_batch\": %d, \"n_ubatch\": %d, \"flash_attn\": %d, \"is_pp_shared\": %d, \"n_gpu_layers\": %d, \"n_threads\": %u, \"n_threads_batch\": %u, "
"\"pp\": %d, \"tg\": %d, \"pl\": %d, \"n_kv\": %d, \"t_pp\": %f, \"speed_pp\": %f, \"t_tg\": %f, \"speed_tg\": %f, \"t\": %f, \"speed\": %f}\n",
n_kv_max, params.n_batch, params.n_ubatch, int(params.flash_attn_type), params.is_pp_shared, params.n_gpu_layers, ctx_params.n_threads, ctx_params.n_threads_batch,
pp, tg, pl, n_kv, t_pp, speed_pp, t_tg, speed_tg, t, speed
);
} else {
LOG("|%6d | %6d | %4d | %6d | %8.3f | %8.2f | %8.3f | %8.2f | %8.3f | %8.2f |\n", pp, tg, pl, n_kv, t_pp, speed_pp, t_tg, speed_tg, t, speed);
}
|
random
|
<|fim_prefix|>table RID_PtrOwner<AccessibilityElement> rid_owner;
struct WindowData {
// Adapter.
#ifdef WINDOWS_ENABLED
accesskit_windows_subclassing_adapter *adapter = nullptr;
#endif
#ifdef MACOS_ENABLED
accesskit_macos_subclassing_adapter *adapter = nullptr;
#endif
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter *adapter = nullptr;
#endif
RID root_id;
HashSet<RID> update;
};
RID focus;
HashMap<DisplayServer::WindowID, WindowData> windows;
HashMap<DisplayServer::AccessibilityRole, accesskit_role> role_map;
HashMap<DisplayServer::AccessibilityAction, accesskit_action> action_map;
_FORCE_INLINE_ accesskit_role _accessibility_role(DisplayServer::AccessibilityRole p_role) const;
_FORCE_INLINE_ accesskit_action _accessibility_action(DisplayServer::AccessibilityAction p_action) const;
void _free_recursive(WindowData *p_wd, const RID &p_id);
_FORCE_INLINE_ void _ensure_node(const RID &p_id, AccessibilityElement *p_ae);
static void _accessibility_action_callback(struct accesskit_action_request *p_request, void *p_user_data);
static accesskit_tree_update *_accessibility_initial_tree_update_callback(void *p_user_data);
static void _accessibility_deactivation_callback(void *p_user_data);
static accesskit_tree_update *_accessibility_build_tree_update(void *p_user_data);
bool in_accessibility_update = false;
Callable update_cb;
public:
Error init() override;
bool window_create(DisplayServer::WindowID p_window_id, void *p_handle) override;
void window_destroy(DisplayServer::WindowID p_window_id) override;
RID accessibility_create_element(DisplayServer::WindowID p_window_id, DisplayServer::AccessibilityRole p_role) override;
RID accessibility_create_sub_element(const RID &p_parent_rid, DisplayServer::AccessibilityRole p_role, int p_insert_pos = -1) override;
virtual RID accessibility_create_sub_text_edit_elements(const RID &p_parent_rid, const RID &p_shaped_text, float p_min_height, int p_insert_pos = -1) override;
bool accessibility_has_element(<|fim_suffix|>) const override;
void accessibility_free_element(const RID &p_id) override;
void accessibility_element_set_meta(const RID &p_id, const Variant &p_meta) override;
Variant accessibility_element_get_meta(const RID &p_id) const override;
void accessibility_update_if_active(const Callable &p_callable) override;
void accessibility_update_set_focus(const RID &p_id) override;
RID accessibility_get_window_root(DisplayServer::WindowID p_window_id) const override;
void accessibility_set_window_rect(DisplayServer::WindowID p_window_id, const Rect2 &p_rect_out, const Rect2 &p_rect_in) override;
void accessibility_set_window_focused(DisplayServer::WindowID p_window_id, bool p_focused) override;
void accessibility_update_set_role(const RID &p_id, DisplayServer::AccessibilityRole p_role) override;
void accessibility_update_set_name(const RID &p_id, const String &p_name) override;
void accessibility_update_set_extra_info(const RID &p_id, const String &p_name_extra_info) override;
void accessibility_update_set_description(const RID &p_id, const String &p_description) override;
void accessibility_update_set_value(const RID &p_id, const String &p_value) override;
void accessibility_update_set_tooltip(const RID &p_id, const String &p_tooltip) override;
void accessibility_update_set_bounds(const RID &p_id, const Rect2 &p_rect) override;
void accessibility_update_set_transform(const RID &p_id, const Transform2D &p_transform) override;
void accessibility_update_add_child(const RID &p_id, const RID &p_child_id) override;
void accessibility_update_add_related_controls(const RID &p_id, const RID &p_related_id) override;
void accessibility_update_add_related_details(const RID &p_id, const RID &p_related_id) override;
void accessibility_update_add_related_described_by(const RID &p_id, const RID &p_related_id) override;
void accessibility_update_add_related_flow_to(const RID &p_id, const RID &p_related_id) override;
void accessibility_update_add_related_labeled_by(con<|fim_middle|>const RID &p_id
|
table RID_PtrOwner<AccessibilityElement> rid_owner;
struct WindowData {
// Adapter.
#ifdef WINDOWS_ENABLED
accesskit_windows_subclassing_adapter *adapter = nullptr;
#endif
#ifdef MACOS_ENABLED
accesskit_macos_subclassing_adapter *adapter = nullptr;
#endif
#ifdef LINUXBSD_ENABLED
accesskit_unix_adapter *adapter = nullptr;
#endif
RID root_id;
HashSet<RID> update;
};
RID focus;
HashMap<DisplayServer::WindowID, WindowData> windows;
HashMap<DisplayServer::AccessibilityRole, accesskit_role> role_map;
HashMap<DisplayServer::AccessibilityAction, accesskit_action> action_map;
_FORCE_INLINE_ accesskit_role _accessibility_role(DisplayServer::AccessibilityRole p_role) const;
_FORCE_INLINE_ accesskit_action _accessibility_action(DisplayServer::AccessibilityAction p_action) const;
void _free_recursive(WindowData *p_wd, const RID &p_id);
_FORCE_INLINE_ void _ensure_node(const RID &p_id, AccessibilityElement *p_ae);
static void _accessibility_action_callback(struct accesskit_action_request *p_request, void *p_user_data);
static accesskit_tree_update *_accessibility_initial_tree_update_callback(void *p_user_data);
static void _accessibility_deactivation_callback(void *p_user_data);
static accesskit_tree_update *_accessibility_build_tree_update(void *p_user_data);
bool in_accessibility_update = false;
Callable update_cb;
public:
Error init() override;
bool window_create(DisplayServer::WindowID p_window_id, void *p_handle) override;
void window_destroy(DisplayServer::WindowID p_window_id) override;
RID accessibility_create_element(DisplayServer::WindowID p_window_id, DisplayServer::AccessibilityRole p_role) override;
RID accessibility_create_sub_element(const RID &p_parent_rid, DisplayServer::AccessibilityRole p_role, int p_insert_pos = -1) override;
virtual RID accessibility_create_sub_text_edit_elements(const RID &p_parent_rid, const RID &p_shaped_text, float p_min_height, int p_insert_pos = -1) override;
bool accessibility_has_element(
|
const RID &p_id
|
) const override;
void accessibility_free_element(const RID &p_id) override;
void accessibility_element_set_meta(const RID &p_id, const Variant &p_meta) override;
Variant accessibility_element_get_meta(const RID &p_id) const override;
void accessibility_update_if_active(const Callable &p_callable) override;
void accessibility_update_set_focus(const RID &p_id) override;
RID accessibility_get_window_root(DisplayServer::WindowID p_window_id) const override;
void accessibility_set_window_rect(DisplayServer::WindowID p_window_id, const Rect2 &p_rect_out, const Rect2 &p_rect_in) override;
void accessibility_set_window_focused(DisplayServer::WindowID p_window_id, bool p_focused) override;
void accessibility_update_set_role(const RID &p_id, DisplayServer::AccessibilityRole p_role) override;
void accessibility_update_set_name(const RID &p_id, const String &p_name) override;
void accessibility_update_set_extra_info(const RID &p_id, const String &p_name_extra_info) override;
void accessibility_update_set_description(const RID &p_id, const String &p_description) override;
void accessibility_update_set_value(const RID &p_id, const String &p_value) override;
void accessibility_update_set_tooltip(const RID &p_id, const String &p_tooltip) override;
void accessibility_update_set_bounds(const RID &p_id, const Rect2 &p_rect) override;
void accessibility_update_set_transform(const RID &p_id, const Transform2D &p_transform) override;
void accessibility_update_add_child(const RID &p_id, const RID &p_child_id) override;
void accessibility_update_add_related_controls(const RID &p_id, const RID &p_related_id) override;
void accessibility_update_add_related_details(const RID &p_id, const RID &p_related_id) override;
void accessibility_update_add_related_described_by(const RID &p_id, const RID &p_related_id) override;
void accessibility_update_add_related_flow_to(const RID &p_id, const RID &p_related_id) override;
void accessibility_update_add_related_labeled_by(con
|
ast_based
|
<|fim_prefix|>:AccessibilityRole::ROLE_VIDEO] = ACCESSKIT_ROLE_VIDEO;
role_map[DisplayServer::AccessibilityRole::ROLE_STATIC_TEXT] = ACCESSKIT_ROLE_LABEL;
role_map[DisplayServer::AccessibilityRole::ROLE_CONTAINER] = ACCESSKIT_ROLE_GENERIC_CONTAINER;
role_map[DisplayServer::AccessibilityRole::ROLE_PANEL] = ACCESSKIT_ROLE_PANE;
role_map[DisplayServer::AccessibilityRole::ROLE_BUTTON] = ACCESSKIT_ROLE_BUTTON;
role_map[DisplayServer::AccessibilityRole::ROLE_LINK] = ACCESSKIT_ROLE_LINK;
role_map[DisplayServer::AccessibilityRole::ROLE_CHECK_BOX] = ACCESSKIT_ROLE_CHECK_BOX;
role_map[DisplayServer::AccessibilityRole::ROLE_RADIO_BUTTON] = ACCESSKIT_ROLE_RADIO_BUTTON;
role_map[DisplayServer::AccessibilityRole::ROLE_CHECK_BUTTON] = ACCESSKIT_ROLE_SWITCH;
role_map[DisplayServer::AccessibilityRole::ROLE_SCROLL_BAR] = ACCESSKIT_ROLE_SCROLL_BAR;
role_map[DisplayServer::AccessibilityRole::ROLE_SCROLL_VIEW] = ACCESSKIT_ROLE_SCROLL_VIEW;
role_map[DisplayServer::AccessibilityRole::ROLE_SPLITTER] = ACCESSKIT_ROLE_SPLITTER;
role_map[DisplayServer::AccessibilityRole::ROLE_SLIDER] = ACCESSKIT_ROLE_SLIDER;
role_map[DisplayServer::AccessibilityRole::ROLE_SPIN_BUTTON] = ACCESSKIT_ROLE_SPIN_BUTTON;
role_map[DisplayServer::AccessibilityRole::ROLE_PROGRESS_INDICATOR] = ACCESSKIT_ROLE_PROGRESS_INDICATOR;
role_map[DisplayServer::AccessibilityRole::ROLE_TEXT_FIELD] = ACCESSKIT_ROLE_TEXT_INPUT;
role_map[DisplayServer::AccessibilityRole::ROLE_MULTILINE_TEXT_FIELD] = ACCESSKIT_ROLE_MULTILINE_TEXT_INPUT;
role_map[DisplayServer::AccessibilityRole::ROLE_COLOR_PICKER] = ACCESSKIT_ROLE_COLOR_WELL;
role_map[DisplayServer::AccessibilityRole::ROLE_TABLE] = ACCESSKIT_ROLE_TABLE;
role_map[DisplayServer::AccessibilityRole::ROLE_CELL] = ACCESSKIT_ROLE_CELL;
role_map[DisplayServer::AccessibilityRole::ROLE_ROW] = ACCESSKIT_ROLE_ROW;
role_map[DisplayServer::AccessibilityRole::ROLE_ROW_GROUP] = ACCESSKIT_ROLE_ROW_GROUP;
role_map[DisplayServer::AccessibilityRole::ROLE_ROW_HEADER] = ACCESSKIT_ROLE_ROW_HEADER;
<|fim_suffix|>
role_map[DisplayServer::AccessibilityRole::ROLE_TREE] = ACCESSKIT_ROLE_TREE;
role_map[DisplayServer::AccessibilityRole::ROLE_TREE_ITEM] = ACCESSKIT_ROLE_TREE_ITEM;
role_map[DisplayServer::AccessibilityRole::ROLE_LIST] = ACCESSKIT_ROLE_LIST;
role_map[DisplayServer::AccessibilityRole::ROLE_LIST_ITEM] = ACCESSKIT_ROLE_LIST_ITEM;
role_map[DisplayServer::AccessibilityRole::ROLE_LIST_BOX] = ACCESSKIT_ROLE_LIST_BOX;
role_map[DisplayServer::AccessibilityRole::ROLE_LIST_BOX_OPTION] = ACCESSKIT_ROLE_LIST_BOX_OPTION;
role_map[DisplayServer::AccessibilityRole::ROLE_TAB_BAR] = ACCESSKIT_ROLE_TAB_LIST;
role_map[DisplayServer::AccessibilityRole::ROLE_TAB] = ACCESSKIT_ROLE_TAB;
role_map[DisplayServer::AccessibilityRole::ROLE_TAB_PANEL] = ACCESSKIT_ROLE_TAB_PANEL;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU_BAR] = ACCESSKIT_ROLE_MENU_BAR;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU] = ACCESSKIT_ROLE_MENU;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU_ITEM] = ACCESSKIT_ROLE_MENU_ITEM;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU_ITEM_CHECK_BOX] = ACCESSKIT_ROLE_MENU_ITEM_CHECK_BOX;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU_ITEM_RADIO] = ACCESSKIT_ROLE_MENU_ITEM_RADIO;
role_map[DisplayServer::AccessibilityRole::ROLE_IMAGE] = ACCESSKIT_ROLE_IMAGE;
role_map[DisplayServer::AccessibilityRole::ROLE_WINDOW] = ACCESSKIT_ROLE_WINDOW;
role_map[DisplayServer::AccessibilityRole::ROLE_TITLE_BAR] = ACCESSKIT_ROLE_TITLE_BAR;
role_map[DisplayServer::AccessibilityRole::ROLE_DIALOG] = ACCESSKIT_ROLE_DIALOG;
role_map[DisplayServer::AccessibilityRole::ROLE_TOOLTIP] = ACCESSKIT_ROLE_TOOLTIP;
action_map[DisplayServer::AccessibilityAction::ACTION_CLICK] = ACCESSKIT_ACTION_CLICK;
action_map[DisplayServer::AccessibilityAction::ACTION_FOCUS] = ACCESSKIT_ACTION_FOCUS;
action_map[DisplayServer::AccessibilityAction::ACTION_BLUR] = ACCESSKIT_ACTION_BLUR;
action_map[DisplayServer::AccessibilityAction::ACTION_COLLAPSE] = ACCESSKIT_ACTION_COLLAPSE;<|fim_middle|>role_map[DisplayServer::AccessibilityRole::ROLE_COLUMN_HEADER] = ACCESSKIT_ROLE_COLUMN_HEADER;
|
:AccessibilityRole::ROLE_VIDEO] = ACCESSKIT_ROLE_VIDEO;
role_map[DisplayServer::AccessibilityRole::ROLE_STATIC_TEXT] = ACCESSKIT_ROLE_LABEL;
role_map[DisplayServer::AccessibilityRole::ROLE_CONTAINER] = ACCESSKIT_ROLE_GENERIC_CONTAINER;
role_map[DisplayServer::AccessibilityRole::ROLE_PANEL] = ACCESSKIT_ROLE_PANE;
role_map[DisplayServer::AccessibilityRole::ROLE_BUTTON] = ACCESSKIT_ROLE_BUTTON;
role_map[DisplayServer::AccessibilityRole::ROLE_LINK] = ACCESSKIT_ROLE_LINK;
role_map[DisplayServer::AccessibilityRole::ROLE_CHECK_BOX] = ACCESSKIT_ROLE_CHECK_BOX;
role_map[DisplayServer::AccessibilityRole::ROLE_RADIO_BUTTON] = ACCESSKIT_ROLE_RADIO_BUTTON;
role_map[DisplayServer::AccessibilityRole::ROLE_CHECK_BUTTON] = ACCESSKIT_ROLE_SWITCH;
role_map[DisplayServer::AccessibilityRole::ROLE_SCROLL_BAR] = ACCESSKIT_ROLE_SCROLL_BAR;
role_map[DisplayServer::AccessibilityRole::ROLE_SCROLL_VIEW] = ACCESSKIT_ROLE_SCROLL_VIEW;
role_map[DisplayServer::AccessibilityRole::ROLE_SPLITTER] = ACCESSKIT_ROLE_SPLITTER;
role_map[DisplayServer::AccessibilityRole::ROLE_SLIDER] = ACCESSKIT_ROLE_SLIDER;
role_map[DisplayServer::AccessibilityRole::ROLE_SPIN_BUTTON] = ACCESSKIT_ROLE_SPIN_BUTTON;
role_map[DisplayServer::AccessibilityRole::ROLE_PROGRESS_INDICATOR] = ACCESSKIT_ROLE_PROGRESS_INDICATOR;
role_map[DisplayServer::AccessibilityRole::ROLE_TEXT_FIELD] = ACCESSKIT_ROLE_TEXT_INPUT;
role_map[DisplayServer::AccessibilityRole::ROLE_MULTILINE_TEXT_FIELD] = ACCESSKIT_ROLE_MULTILINE_TEXT_INPUT;
role_map[DisplayServer::AccessibilityRole::ROLE_COLOR_PICKER] = ACCESSKIT_ROLE_COLOR_WELL;
role_map[DisplayServer::AccessibilityRole::ROLE_TABLE] = ACCESSKIT_ROLE_TABLE;
role_map[DisplayServer::AccessibilityRole::ROLE_CELL] = ACCESSKIT_ROLE_CELL;
role_map[DisplayServer::AccessibilityRole::ROLE_ROW] = ACCESSKIT_ROLE_ROW;
role_map[DisplayServer::AccessibilityRole::ROLE_ROW_GROUP] = ACCESSKIT_ROLE_ROW_GROUP;
role_map[DisplayServer::AccessibilityRole::ROLE_ROW_HEADER] = ACCESSKIT_ROLE_ROW_HEADER;
|
role_map[DisplayServer::AccessibilityRole::ROLE_COLUMN_HEADER] = ACCESSKIT_ROLE_COLUMN_HEADER;
|
role_map[DisplayServer::AccessibilityRole::ROLE_TREE] = ACCESSKIT_ROLE_TREE;
role_map[DisplayServer::AccessibilityRole::ROLE_TREE_ITEM] = ACCESSKIT_ROLE_TREE_ITEM;
role_map[DisplayServer::AccessibilityRole::ROLE_LIST] = ACCESSKIT_ROLE_LIST;
role_map[DisplayServer::AccessibilityRole::ROLE_LIST_ITEM] = ACCESSKIT_ROLE_LIST_ITEM;
role_map[DisplayServer::AccessibilityRole::ROLE_LIST_BOX] = ACCESSKIT_ROLE_LIST_BOX;
role_map[DisplayServer::AccessibilityRole::ROLE_LIST_BOX_OPTION] = ACCESSKIT_ROLE_LIST_BOX_OPTION;
role_map[DisplayServer::AccessibilityRole::ROLE_TAB_BAR] = ACCESSKIT_ROLE_TAB_LIST;
role_map[DisplayServer::AccessibilityRole::ROLE_TAB] = ACCESSKIT_ROLE_TAB;
role_map[DisplayServer::AccessibilityRole::ROLE_TAB_PANEL] = ACCESSKIT_ROLE_TAB_PANEL;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU_BAR] = ACCESSKIT_ROLE_MENU_BAR;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU] = ACCESSKIT_ROLE_MENU;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU_ITEM] = ACCESSKIT_ROLE_MENU_ITEM;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU_ITEM_CHECK_BOX] = ACCESSKIT_ROLE_MENU_ITEM_CHECK_BOX;
role_map[DisplayServer::AccessibilityRole::ROLE_MENU_ITEM_RADIO] = ACCESSKIT_ROLE_MENU_ITEM_RADIO;
role_map[DisplayServer::AccessibilityRole::ROLE_IMAGE] = ACCESSKIT_ROLE_IMAGE;
role_map[DisplayServer::AccessibilityRole::ROLE_WINDOW] = ACCESSKIT_ROLE_WINDOW;
role_map[DisplayServer::AccessibilityRole::ROLE_TITLE_BAR] = ACCESSKIT_ROLE_TITLE_BAR;
role_map[DisplayServer::AccessibilityRole::ROLE_DIALOG] = ACCESSKIT_ROLE_DIALOG;
role_map[DisplayServer::AccessibilityRole::ROLE_TOOLTIP] = ACCESSKIT_ROLE_TOOLTIP;
action_map[DisplayServer::AccessibilityAction::ACTION_CLICK] = ACCESSKIT_ACTION_CLICK;
action_map[DisplayServer::AccessibilityAction::ACTION_FOCUS] = ACCESSKIT_ACTION_FOCUS;
action_map[DisplayServer::AccessibilityAction::ACTION_BLUR] = ACCESSKIT_ACTION_BLUR;
action_map[DisplayServer::AccessibilityAction::ACTION_COLLAPSE] = ACCESSKIT_ACTION_COLLAPSE;
|
ast_based
|
<|fim_prefix|>holder_ == nullptr || thresholder_->IsEmpty()) {
tprintf("Please call SetImage before attempting recognition.\n");
return -1;
}
if (recognition_done_) {
ClearResults();
}
if (!block_list_->empty()) {
return 0;
}
if (tesseract_ == nullptr) {
tesseract_ = new Tesseract;
#ifndef DISABLED_LEGACY_ENGINE
tesseract_->InitAdaptiveClassifier(nullptr);
#endif
}
if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
return -1;
}
tesseract_->PrepareForPageseg();
#ifndef DISABLED_LEGACY_ENGINE
if (tesseract_->textord_equation_detect) {
if (equ_detect_ == nullptr && !datapath_.empty()) {
equ_detect_ = new EquationDetect(datapath_.c_str(), nullptr);
}
if (equ_detect_ == nullptr) {
tprintf("Warning: Could not set equation detector\n");
} else {
tesseract_->SetEquationDetect(equ_detect_);
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
Tesseract *osd_tess = osd_tesseract_;
OSResults osr;
#ifndef DISABLED_LEGACY_ENGINE
if (PSM_OSD_ENABLED(tesseract_->tessedit_pageseg_mode) && osd_tess == nullptr) {
if (strcmp(language_.c_str(), "osd") == 0) {
osd_tess = tesseract_;
} else {
osd_tesseract_ = new Tesseract;
TessdataManager mgr(reader_);
if (datapath_.empty()) {
tprintf(
"Warning: Auto orientation and script detection requested,"
" but data path is undefined\n");
delete osd_tesseract_;
osd_tesseract_ = nullptr;
} else if (osd_tesseract_->init_tesseract(datapath_, "", "osd", OEM_TESSERACT_ONLY,
nullptr, 0, nullptr, nullptr, false, &mgr) == 0) {
osd_tess = osd_tesseract_;
osd_tesseract_->set_source_resolution(thresholder_->GetSourceYResolution());
} else {
tprintf(
"Warning: Auto orientation and script detection requested,"
" but osd language failed to load\n");
<|fim_suffix|>
}
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
if (tesseract_->SegmentPage(input_file_.c_str(), block_list_, osd_tess, &osr) < 0) {
return -1;
}
// If Devanagari is being recognized, we use different images for page seg
// and for OCR.
tesseract_->PrepareForTessOCR(block_list_, osd_tess, &osr);
return 0;
}
/**
* Return average gradient of lines on page.
*/
float TessBaseAPI::GetGradient() {
return tesseract_->gradient();
}
/** Delete the pageres and clear the block list ready for a new page. */
void TessBaseAPI::ClearResults() {
if (tesseract_ != nullptr) {
tesseract_->Clear();
}
delete page_res_;
page_res_ = nullptr;
recognition_done_ = false;
if (block_list_ == nullptr) {
block_list_ = new BLOCK_LIST;
} else {
block_list_->clear();
}
if (paragraph_models_ != nullptr) {
for (auto model : *paragraph_models_) {
delete model;
}
delete paragraph_models_;
paragraph_models_ = nullptr;
}
}
/**
* Return the length of the output text string, as UTF8, assuming
* liberally two spacing marks after each word (as paragraphs end with two
* newlines), and assuming a single character reject marker for each rejected
* character.
* Also return the number of recognized blobs in blob_count.
*/
int TessBaseAPI::TextLength(int *blob_count) const {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return 0;
}
PAGE_RES_IT page_res_it(page_res_);
int total_length = 2;
int total_blobs = 0;
// Iterate over the data structures to extract the recognition result.
for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
WERD_CHOICE *choice = word->best_choice;
if (choice != nullptr) {
total_blobs += choice->length() + 2;
total_length += choice->unichar_string().length() + 2;
for (int i = 0; i < word->reject_map.length(); ++i) {
if (word->reject_map[i].rejected()) {
+<|fim_middle|>delete osd_tesseract_;
osd_tesseract_ = nullptr;
|
holder_ == nullptr || thresholder_->IsEmpty()) {
tprintf("Please call SetImage before attempting recognition.\n");
return -1;
}
if (recognition_done_) {
ClearResults();
}
if (!block_list_->empty()) {
return 0;
}
if (tesseract_ == nullptr) {
tesseract_ = new Tesseract;
#ifndef DISABLED_LEGACY_ENGINE
tesseract_->InitAdaptiveClassifier(nullptr);
#endif
}
if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
return -1;
}
tesseract_->PrepareForPageseg();
#ifndef DISABLED_LEGACY_ENGINE
if (tesseract_->textord_equation_detect) {
if (equ_detect_ == nullptr && !datapath_.empty()) {
equ_detect_ = new EquationDetect(datapath_.c_str(), nullptr);
}
if (equ_detect_ == nullptr) {
tprintf("Warning: Could not set equation detector\n");
} else {
tesseract_->SetEquationDetect(equ_detect_);
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
Tesseract *osd_tess = osd_tesseract_;
OSResults osr;
#ifndef DISABLED_LEGACY_ENGINE
if (PSM_OSD_ENABLED(tesseract_->tessedit_pageseg_mode) && osd_tess == nullptr) {
if (strcmp(language_.c_str(), "osd") == 0) {
osd_tess = tesseract_;
} else {
osd_tesseract_ = new Tesseract;
TessdataManager mgr(reader_);
if (datapath_.empty()) {
tprintf(
"Warning: Auto orientation and script detection requested,"
" but data path is undefined\n");
delete osd_tesseract_;
osd_tesseract_ = nullptr;
} else if (osd_tesseract_->init_tesseract(datapath_, "", "osd", OEM_TESSERACT_ONLY,
nullptr, 0, nullptr, nullptr, false, &mgr) == 0) {
osd_tess = osd_tesseract_;
osd_tesseract_->set_source_resolution(thresholder_->GetSourceYResolution());
} else {
tprintf(
"Warning: Auto orientation and script detection requested,"
" but osd language failed to load\n");
|
delete osd_tesseract_;
osd_tesseract_ = nullptr;
|
}
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
if (tesseract_->SegmentPage(input_file_.c_str(), block_list_, osd_tess, &osr) < 0) {
return -1;
}
// If Devanagari is being recognized, we use different images for page seg
// and for OCR.
tesseract_->PrepareForTessOCR(block_list_, osd_tess, &osr);
return 0;
}
/**
* Return average gradient of lines on page.
*/
float TessBaseAPI::GetGradient() {
return tesseract_->gradient();
}
/** Delete the pageres and clear the block list ready for a new page. */
void TessBaseAPI::ClearResults() {
if (tesseract_ != nullptr) {
tesseract_->Clear();
}
delete page_res_;
page_res_ = nullptr;
recognition_done_ = false;
if (block_list_ == nullptr) {
block_list_ = new BLOCK_LIST;
} else {
block_list_->clear();
}
if (paragraph_models_ != nullptr) {
for (auto model : *paragraph_models_) {
delete model;
}
delete paragraph_models_;
paragraph_models_ = nullptr;
}
}
/**
* Return the length of the output text string, as UTF8, assuming
* liberally two spacing marks after each word (as paragraphs end with two
* newlines), and assuming a single character reject marker for each rejected
* character.
* Also return the number of recognized blobs in blob_count.
*/
int TessBaseAPI::TextLength(int *blob_count) const {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return 0;
}
PAGE_RES_IT page_res_it(page_res_);
int total_length = 2;
int total_blobs = 0;
// Iterate over the data structures to extract the recognition result.
for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
WERD_CHOICE *choice = word->best_choice;
if (choice != nullptr) {
total_blobs += choice->length() + 2;
total_length += choice->unichar_string().length() + 2;
for (int i = 0; i < word->reject_map.length(); ++i) {
if (word->reject_map[i].rejected()) {
+
|
ast_based
|
<|fim_prefix|>
if (p_from_end) {
set_frame_and_progress(end_frame, 1.0);
} else {
set_frame_and_progress(0, 0.0);
}
emit_signal(SceneStringName(animation_changed));
} else {
int end_frame = MAX(0, frames->get_frame_count(animation) - 1);
bool is_backward = std::signbit(speed_scale * custom_speed_scale);
if (p_from_end && is_backward && frame == 0 && frame_progress <= 0.0) {
set_frame_and_progress(end_frame, 1.0);
} else if (!p_from_end && !is_backward && frame == end_frame && frame_progress >= 1.0) {
set_frame_and_progress(0, 0.0);
}
}
set_process_internal(true);
notify_property_list_changed();
queue_redraw();
}
void AnimatedSprite2D::play_backwards(const StringName &p_name) {
play(p_name, -1, true);
}
void AnimatedSprite2D::_stop_internal(bool p_reset) {
playing = false;
if (p_reset) {
custom_speed_scale = 1.0;
set_frame_and_progress(0, 0.0);
}
notify_property_list_changed();
set_process_internal(false);
}
void AnimatedSprite2D::pause() {
_stop_internal(false);
}
void AnimatedSprite2D::stop() {
_stop_internal(true);
}
double AnimatedSprite2D::_get_frame_duration() {
if (frames.is_valid() && frames->has_animation(animation)) {
return frames->get_frame_duration(animation, frame);
}
return 1.0;
}
void AnimatedSprite2D::_calc_frame_speed_scale() {
frame_speed_scale = 1.0 / _get_frame_duration();
}
void AnimatedSprite2D::set_animation(const StringName &p_name) {
if (animation == p_name) {
return;
}
animation = p_name;
emit_signal(SceneStringName(animation_changed));
if (frames.is_null()) {
animation = StringName();
stop();
ERR_FAIL_MSG(vformat("There is no animation with name '%s'.", p_name));
}
int frame_count = frames->get_frame_count(animation);
if (animation == StringName() || frame_count == 0) {
stop();
return;
} else if (!frames->get_animation_names().has(animation)) {
animation = StringName();
stop();
ERR_FAIL_MSG(vformat("There is no animation with name '%s'.", p_name));<|fim_suffix|>}
StringName AnimatedSprite2D::get_animation() const {
return animation;
}
PackedStringArray AnimatedSprite2D::get_configuration_warnings() const {
PackedStringArray warnings = Node2D::get_configuration_warnings();
if (frames.is_null()) {
warnings.push_back(RTR("A SpriteFrames resource must be created or set in the \"Sprite Frames\" property in order for AnimatedSprite2D to display frames."));
}
return warnings;
}
#ifdef TOOLS_ENABLED
void AnimatedSprite2D::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
const String pf = p_function;
if (p_idx == 0 && frames.is_valid()) {
if (pf == "play" || pf == "play_backwards" || pf == "set_animation" || pf == "set_autoplay") {
List<StringName> al;
frames->get_animation_list(&al);
for (const StringName &name : al) {
r_options->push_back(String(name).quote());
}
}
}
Node2D::get_argument_options(p_function, p_idx, r_options);
}
#endif // TOOLS_ENABLED
#ifndef DISABLE_DEPRECATED
bool AnimatedSprite2D::_set(const StringName &p_name, const Variant &p_value) {
if ((p_name == SNAME("frames"))) {
set_sprite_frames(p_value);
return true;
}
return false;
}
#endif
void AnimatedSprite2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_sprite_frames", "sprite_frames"), &AnimatedSprite2D::set_sprite_frames);
ClassDB::bind_method(D_METHOD("get_sprite_frames"), &AnimatedSprite2D::get_sprite_frames);
ClassDB::bind_method(D_METHOD("set_animation", "name"), &AnimatedSprite2D::set_animation);
ClassDB::bind_method(D_METHOD("get_animation"), &AnimatedSprite2D::get_animation);
ClassDB::bind_method(D_METHOD("set_autoplay", "name"), &AnimatedSprite2D::set_autoplay);
ClassDB::bind_method(D_METHOD("get_autoplay"), &AnimatedSprite2D::get_autoplay);
ClassDB::bind_method(D_METHOD("is_playing"), &AnimatedSprite2D::is_playing);
<|fim_middle|> }
if (std::signbit(get_playing_speed())) {
set_frame_and_progress(frame_count - 1, 1.0);
} else {
set_frame_and_progress(0, 0.0);
}
notify_property_list_changed();
queue_redraw();
|
if (p_from_end) {
set_frame_and_progress(end_frame, 1.0);
} else {
set_frame_and_progress(0, 0.0);
}
emit_signal(SceneStringName(animation_changed));
} else {
int end_frame = MAX(0, frames->get_frame_count(animation) - 1);
bool is_backward = std::signbit(speed_scale * custom_speed_scale);
if (p_from_end && is_backward && frame == 0 && frame_progress <= 0.0) {
set_frame_and_progress(end_frame, 1.0);
} else if (!p_from_end && !is_backward && frame == end_frame && frame_progress >= 1.0) {
set_frame_and_progress(0, 0.0);
}
}
set_process_internal(true);
notify_property_list_changed();
queue_redraw();
}
void AnimatedSprite2D::play_backwards(const StringName &p_name) {
play(p_name, -1, true);
}
void AnimatedSprite2D::_stop_internal(bool p_reset) {
playing = false;
if (p_reset) {
custom_speed_scale = 1.0;
set_frame_and_progress(0, 0.0);
}
notify_property_list_changed();
set_process_internal(false);
}
void AnimatedSprite2D::pause() {
_stop_internal(false);
}
void AnimatedSprite2D::stop() {
_stop_internal(true);
}
double AnimatedSprite2D::_get_frame_duration() {
if (frames.is_valid() && frames->has_animation(animation)) {
return frames->get_frame_duration(animation, frame);
}
return 1.0;
}
void AnimatedSprite2D::_calc_frame_speed_scale() {
frame_speed_scale = 1.0 / _get_frame_duration();
}
void AnimatedSprite2D::set_animation(const StringName &p_name) {
if (animation == p_name) {
return;
}
animation = p_name;
emit_signal(SceneStringName(animation_changed));
if (frames.is_null()) {
animation = StringName();
stop();
ERR_FAIL_MSG(vformat("There is no animation with name '%s'.", p_name));
}
int frame_count = frames->get_frame_count(animation);
if (animation == StringName() || frame_count == 0) {
stop();
return;
} else if (!frames->get_animation_names().has(animation)) {
animation = StringName();
stop();
ERR_FAIL_MSG(vformat("There is no animation with name '%s'.", p_name));
|
}
if (std::signbit(get_playing_speed())) {
set_frame_and_progress(frame_count - 1, 1.0);
} else {
set_frame_and_progress(0, 0.0);
}
notify_property_list_changed();
queue_redraw();
|
}
StringName AnimatedSprite2D::get_animation() const {
return animation;
}
PackedStringArray AnimatedSprite2D::get_configuration_warnings() const {
PackedStringArray warnings = Node2D::get_configuration_warnings();
if (frames.is_null()) {
warnings.push_back(RTR("A SpriteFrames resource must be created or set in the \"Sprite Frames\" property in order for AnimatedSprite2D to display frames."));
}
return warnings;
}
#ifdef TOOLS_ENABLED
void AnimatedSprite2D::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
const String pf = p_function;
if (p_idx == 0 && frames.is_valid()) {
if (pf == "play" || pf == "play_backwards" || pf == "set_animation" || pf == "set_autoplay") {
List<StringName> al;
frames->get_animation_list(&al);
for (const StringName &name : al) {
r_options->push_back(String(name).quote());
}
}
}
Node2D::get_argument_options(p_function, p_idx, r_options);
}
#endif // TOOLS_ENABLED
#ifndef DISABLE_DEPRECATED
bool AnimatedSprite2D::_set(const StringName &p_name, const Variant &p_value) {
if ((p_name == SNAME("frames"))) {
set_sprite_frames(p_value);
return true;
}
return false;
}
#endif
void AnimatedSprite2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_sprite_frames", "sprite_frames"), &AnimatedSprite2D::set_sprite_frames);
ClassDB::bind_method(D_METHOD("get_sprite_frames"), &AnimatedSprite2D::get_sprite_frames);
ClassDB::bind_method(D_METHOD("set_animation", "name"), &AnimatedSprite2D::set_animation);
ClassDB::bind_method(D_METHOD("get_animation"), &AnimatedSprite2D::get_animation);
ClassDB::bind_method(D_METHOD("set_autoplay", "name"), &AnimatedSprite2D::set_autoplay);
ClassDB::bind_method(D_METHOD("get_autoplay"), &AnimatedSprite2D::get_autoplay);
ClassDB::bind_method(D_METHOD("is_playing"), &AnimatedSprite2D::is_playing);
|
random
|
<|fim_prefix|>t_pivot() const {
return Vector2();
}
bool AnimatedSprite2D::_edit_use_pivot() const {
return true;
}
#endif // TOOLS_ENABLED
#ifdef DEBUG_ENABLED
Rect2 AnimatedSprite2D::_edit_get_rect() const {
return _get_rect();
}
bool AnimatedSprite2D::_edit_use_rect() const {
if (frames.is_null() || !frames->has_animation(animation)) {
return false;
}
if (frame < 0 || frame >= frames->get_frame_count(animation)) {
return false;
}
Ref<Texture2D> t;
if (animation) {
t = frames->get_frame_texture(animation, frame);
}
return t.is_valid();
}
#endif // DEBUG_ENABLED
Rect2 AnimatedSprite2D::get_anchorable_rect() const {
return _get_rect();
}
Rect2 AnimatedSprite2D::_get_rect() const {
if (frames.is_null() || !frames->has_animation(animation)) {
return Rect2();
}
if (frame < 0 || frame >= frames->get_frame_count(animation)) {
return Rect2();
}
Ref<Texture2D> t;
if (animation) {
t = frames->get_frame_texture(animation, frame);
}
if (t.is_null()) {
return Rect2();
}
Size2 s = t->get_size();
Point2 ofs = offset;
if (centered) {
ofs -= s / 2;
}
if (s == Size2(0, 0)) {
s = Size2(1, 1);
}
return Rect2(ofs, s);
}
void AnimatedSprite2D::_validate_property(PropertyInfo &p_property) const {
if (frames.is_null()) {
return;
}
if (!Engine::get_singleton()->is_editor_hint()) {
if (p_property.name == "frame" && playing) {
p_property.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_READ_ONLY;
}
return;
}
if (p_property.name == "animation") {
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
bool current_found = false;
bool is_first_element = true;
for (const StringName &E : names) {
if (!is_first_element) {
p_property.hint_string += ",";
} else {
is_first_element = false;
}
p_property.hint_string += String(E);
if (animation == E) {
current_found = true;
}
}
if (!current_found) {
if (p_property.hint_string.is_empty()) {
<|fim_suffix|>
} else {
p_property.hint_string = String(animation) + "," + p_property.hint_string;
}
}
return;
}
if (p_property.name == "frame") {
if (playing) {
p_property.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_READ_ONLY;
return;
}
p_property.hint = PROPERTY_HINT_RANGE;
if (frames->has_animation(animation) && frames->get_frame_count(animation) > 0) {
p_property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
} else {
// Avoid an error, `hint_string` is required for `PROPERTY_HINT_RANGE`.
p_property.hint_string = "0,0,1";
}
p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
}
void AnimatedSprite2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ACCESSIBILITY_UPDATE: {
RID ae = get_accessibility_element();
ERR_FAIL_COND(ae.is_null());
Rect2 dst_rect = _get_rect();
DisplayServer::get_singleton()->accessibility_update_set_role(ae, DisplayServer::AccessibilityRole::ROLE_IMAGE);
DisplayServer::get_singleton()->accessibility_update_set_transform(ae, get_transform());
DisplayServer::get_singleton()->accessibility_update_set_bounds(ae, dst_rect);
} break;
case NOTIFICATION_READY: {
if (!Engine::get_singleton()->is_editor_hint() && frames.is_valid() && frames->has_animation(autoplay)) {
play(autoplay);
}
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
}
double remaining = get_process_delta_time();
int i = 0;
while (remaining) {
// Animation speed may be changed by animation_finished or frame_changed signals.
double speed = frames->get_animation_speed(animation) * speed_scale * custom_speed_scale * frame_speed_scale;
double abs_speed = Math::abs(speed);
if (speed == 0) {
return; // Do nothing.
}
// Frame count may be changed by animation_finished or frame_changed signals.
int fc = frames->get_frame_count(animation);
in<|fim_middle|>p_property.hint_string = String(animation);
|
t_pivot() const {
return Vector2();
}
bool AnimatedSprite2D::_edit_use_pivot() const {
return true;
}
#endif // TOOLS_ENABLED
#ifdef DEBUG_ENABLED
Rect2 AnimatedSprite2D::_edit_get_rect() const {
return _get_rect();
}
bool AnimatedSprite2D::_edit_use_rect() const {
if (frames.is_null() || !frames->has_animation(animation)) {
return false;
}
if (frame < 0 || frame >= frames->get_frame_count(animation)) {
return false;
}
Ref<Texture2D> t;
if (animation) {
t = frames->get_frame_texture(animation, frame);
}
return t.is_valid();
}
#endif // DEBUG_ENABLED
Rect2 AnimatedSprite2D::get_anchorable_rect() const {
return _get_rect();
}
Rect2 AnimatedSprite2D::_get_rect() const {
if (frames.is_null() || !frames->has_animation(animation)) {
return Rect2();
}
if (frame < 0 || frame >= frames->get_frame_count(animation)) {
return Rect2();
}
Ref<Texture2D> t;
if (animation) {
t = frames->get_frame_texture(animation, frame);
}
if (t.is_null()) {
return Rect2();
}
Size2 s = t->get_size();
Point2 ofs = offset;
if (centered) {
ofs -= s / 2;
}
if (s == Size2(0, 0)) {
s = Size2(1, 1);
}
return Rect2(ofs, s);
}
void AnimatedSprite2D::_validate_property(PropertyInfo &p_property) const {
if (frames.is_null()) {
return;
}
if (!Engine::get_singleton()->is_editor_hint()) {
if (p_property.name == "frame" && playing) {
p_property.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_READ_ONLY;
}
return;
}
if (p_property.name == "animation") {
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
bool current_found = false;
bool is_first_element = true;
for (const StringName &E : names) {
if (!is_first_element) {
p_property.hint_string += ",";
} else {
is_first_element = false;
}
p_property.hint_string += String(E);
if (animation == E) {
current_found = true;
}
}
if (!current_found) {
if (p_property.hint_string.is_empty()) {
|
p_property.hint_string = String(animation);
|
} else {
p_property.hint_string = String(animation) + "," + p_property.hint_string;
}
}
return;
}
if (p_property.name == "frame") {
if (playing) {
p_property.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_READ_ONLY;
return;
}
p_property.hint = PROPERTY_HINT_RANGE;
if (frames->has_animation(animation) && frames->get_frame_count(animation) > 0) {
p_property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
} else {
// Avoid an error, `hint_string` is required for `PROPERTY_HINT_RANGE`.
p_property.hint_string = "0,0,1";
}
p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
}
void AnimatedSprite2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ACCESSIBILITY_UPDATE: {
RID ae = get_accessibility_element();
ERR_FAIL_COND(ae.is_null());
Rect2 dst_rect = _get_rect();
DisplayServer::get_singleton()->accessibility_update_set_role(ae, DisplayServer::AccessibilityRole::ROLE_IMAGE);
DisplayServer::get_singleton()->accessibility_update_set_transform(ae, get_transform());
DisplayServer::get_singleton()->accessibility_update_set_bounds(ae, dst_rect);
} break;
case NOTIFICATION_READY: {
if (!Engine::get_singleton()->is_editor_hint() && frames.is_valid() && frames->has_animation(autoplay)) {
play(autoplay);
}
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
}
double remaining = get_process_delta_time();
int i = 0;
while (remaining) {
// Animation speed may be changed by animation_finished or frame_changed signals.
double speed = frames->get_animation_speed(animation) * speed_scale * custom_speed_scale * frame_speed_scale;
double abs_speed = Math::abs(speed);
if (speed == 0) {
return; // Do nothing.
}
// Frame count may be changed by animation_finished or frame_changed signals.
int fc = frames->get_frame_count(animation);
in
|
ast_based
|
<|fim_prefix|>/**************************************************************************/
/* android_input_handler.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */<|fim_suffix|>/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "android_input_handler.h"
#include "android_keys_utils.h"
#include "display_server_android.h"
void AndroidInputHandler::process_joy_event(AndroidInputHandler::JoypadEvent p_event) {
switch (p_event.type) {
case JOY_EVENT_BUTTON:
Input::get_singleton()->joy_button(p_event.device, (JoyButton)p_event.index, p_event.pressed);
break;
case JOY_EVENT_AXIS:
Input::get_singleton()->joy_axis(p_event.device, (JoyAxis)p_event.index, p_event.value);
break;
case JOY_EVENT_HAT:
Input::get_singleton()->joy_hat(p_event.device, p_event.hat);
break;
default:
return;
}
}
void AndroidInputHandler::_set_key_modifier_state(Ref<InputEventWithModifiers> ev, Key p_keycode) {
if (p_keycode != Key::SHIFT) {
ev->set_shift_pressed(shift_mem);
}
if (p_keycode != Key::ALT) {
ev->set_alt_pressed(alt_mem);
}
if (p_keycode != Key::META) {
ev->set_meta_pressed(meta_mem);
}
if (p_keycode != Key::CTRL) {
ev->set_ctrl_pressed(control_mem);
}
}
void AndroidInputHandler::process_key_event(int p_physical_keycode, int p_unicode, int p_key_label, bool p_pressed, bool p_echo) {
static char32_t prev_wc = 0;
char32_t unicode = p_unicode;
if ((p_unicode & 0xfffffc00) == 0xd800) {
if (prev_wc != 0) {
ERR_PRINT("invalid utf16 surrogate input");
}
prev_wc = unicode;
return; // Skip surrogate.
} else if ((unicode & 0xfffffc00) == 0xdc00) {
if (prev_wc == 0) {
ERR_PRINT("invalid utf16 surrogate input");
return; // Skip invalid surrogate.
}
unicode = (prev_wc << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
prev_wc = 0;
} else {
prev_wc = 0;
}
Ref<InputEventKey> ev;
ev.instantiate();
<|fim_middle|>/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
/**************************************************************************/
/* android_input_handler.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "android_input_handler.h"
#include "android_keys_utils.h"
#include "display_server_android.h"
void AndroidInputHandler::process_joy_event(AndroidInputHandler::JoypadEvent p_event) {
switch (p_event.type) {
case JOY_EVENT_BUTTON:
Input::get_singleton()->joy_button(p_event.device, (JoyButton)p_event.index, p_event.pressed);
break;
case JOY_EVENT_AXIS:
Input::get_singleton()->joy_axis(p_event.device, (JoyAxis)p_event.index, p_event.value);
break;
case JOY_EVENT_HAT:
Input::get_singleton()->joy_hat(p_event.device, p_event.hat);
break;
default:
return;
}
}
void AndroidInputHandler::_set_key_modifier_state(Ref<InputEventWithModifiers> ev, Key p_keycode) {
if (p_keycode != Key::SHIFT) {
ev->set_shift_pressed(shift_mem);
}
if (p_keycode != Key::ALT) {
ev->set_alt_pressed(alt_mem);
}
if (p_keycode != Key::META) {
ev->set_meta_pressed(meta_mem);
}
if (p_keycode != Key::CTRL) {
ev->set_ctrl_pressed(control_mem);
}
}
void AndroidInputHandler::process_key_event(int p_physical_keycode, int p_unicode, int p_key_label, bool p_pressed, bool p_echo) {
static char32_t prev_wc = 0;
char32_t unicode = p_unicode;
if ((p_unicode & 0xfffffc00) == 0xd800) {
if (prev_wc != 0) {
ERR_PRINT("invalid utf16 surrogate input");
}
prev_wc = unicode;
return; // Skip surrogate.
} else if ((unicode & 0xfffffc00) == 0xdc00) {
if (prev_wc == 0) {
ERR_PRINT("invalid utf16 surrogate input");
return; // Skip invalid surrogate.
}
unicode = (prev_wc << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
prev_wc = 0;
} else {
prev_wc = 0;
}
Ref<InputEventKey> ev;
ev.instantiate();
|
random
|
<|fim_prefix|> (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_live(const RID &p_id, DisplayServer::AccessibilityLiveMode p_live) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_live) {
case DisplayServer::AccessibilityLiveMode::LIVE_OFF: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_OFF);
} break;
case DisplayServer::AccessibilityLiveMode::LIVE_POLITE: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_POLITE);
} break;
case DisplayServer::AccessibilityLiveMode::LIVE_ASSERTIVE: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_ASSERTIVE);
} break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_add_action(const RID &p_id, DisplayServer::AccessibilityAction p_action, const Callable &p_callable) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
ae->actions[_accessibility_action(p_action)] = p_callable;
accesskit_node_add_action(ae->node, _accessibility_action(p_action));
}
void AccessibilityDriverAccessKit::accessibility_update_add_custom_action(const RID &p_id, int p_action_id, const String &p_action_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_action_description.is_empty()) {
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, p_action_description.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
} else {
<|fim_suffix|>
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_index(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_index(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_position(const RID &p_id, int p_row_index, int p_column_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null<|fim_middle|>String cs_name = vformat("Custom Action %d", p_action_id);
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, cs_name.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
|
(accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_live(const RID &p_id, DisplayServer::AccessibilityLiveMode p_live) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_live) {
case DisplayServer::AccessibilityLiveMode::LIVE_OFF: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_OFF);
} break;
case DisplayServer::AccessibilityLiveMode::LIVE_POLITE: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_POLITE);
} break;
case DisplayServer::AccessibilityLiveMode::LIVE_ASSERTIVE: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_ASSERTIVE);
} break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_add_action(const RID &p_id, DisplayServer::AccessibilityAction p_action, const Callable &p_callable) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
ae->actions[_accessibility_action(p_action)] = p_callable;
accesskit_node_add_action(ae->node, _accessibility_action(p_action));
}
void AccessibilityDriverAccessKit::accessibility_update_add_custom_action(const RID &p_id, int p_action_id, const String &p_action_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_action_description.is_empty()) {
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, p_action_description.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
} else {
|
String cs_name = vformat("Custom Action %d", p_action_id);
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, cs_name.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
|
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_index(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_index(const RID &p_id, int p_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_column_index(ae->node, p_index);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_cell_position(const RID &p_id, int p_row_index, int p_column_index) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null
|
ast_based
|
<|fim_prefix|>ative prompt
struct callback_data {
ggml_context * ctx_ggml = nullptr; // holds v_pos, v_neg, v_diff_filtered
int n_layers = 0;
int n_tokens = 0;
bool is_eval_pos = true;
// each element of the vector correspond to one layer
std::vector<struct ggml_tensor *> v_pos; // vector of matrices of size [n_embd, n_tokens]
std::vector<struct ggml_tensor *> v_neg; // vector of matrices of size [n_embd, n_tokens]
std::vector<struct ggml_tensor *> v_diff_filtered; // vector of matrices of size [n_embd, n_nonzero_rows]. NOTE: n_nonzero_rows maybe different for each layer
// save a tensor into either v_pos or v_neg (decided by is_eval_pos)
void save_tensor_for_layer(struct ggml_tensor * t) {
GGML_ASSERT(t->type == GGML_TYPE_F32);
if (ctx_ggml == nullptr) {
// alloc a new ctx_ggml if needed
struct ggml_init_params params_ggml = {
/*.mem_size =*/ ggml_tensor_overhead() * n_layers * 3u,
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ctx_ggml = ggml_init(params_ggml);
}
// copy tensor data
auto n_bytes = ggml_nbytes(t);
struct ggml_tensor * t_layer = ggml_new_tensor_2d(ctx_ggml, t->type, t->ne[0], t->ne[1]);
t_layer->data = malloc(n_bytes); // TODO @ngxson : get rid of this malloc somehow
ggml_backend_tensor_get(t, t_layer->data, 0, n_bytes);
ggml_set_name(t_layer, ggml_get_name(t));
//print_debug_tensor(t_layer);
if (is_eval_pos) {
v_pos.push_back(t_layer);
} else {
v_neg.push_back(t_layer);
}
}
// calculate diff (v_pos - v_neg) and place the result back to v_pos
// all zero rows in the diff tensor will also be removed
// NOTE: final layer is ignored. we only have (n_layers - 1) to process
std::vector<struct ggml_tensor *> calc_diff() {
for (float il = 0; il < v_pos.size(); il++) <|fim_suffix|>
float * b = (float *) v_neg[il]->data;
size_t n_elem = ggml_nelements(v_pos[il]);
for (size_t j = 0; j < n_elem; j++) {
a[j] -= b[j];
}
//print_debug_tensor(v_pos[i]);
auto diff_filtered = filter_nonzero_rows(v_pos[il]);
v_diff_filtered.push_back(diff_filtered);
}
return v_diff_filtered; // for convinient, we return the result std::vector
}
// delete zero rows from a given 2D tensor
struct ggml_tensor * filter_nonzero_rows(struct ggml_tensor * a) {
//printf("filter_nonzero_rows\n");
auto is_row_all_zeros = [](struct ggml_tensor * t, int row, float eps) -> bool {
// check if given row containing all zero elements
int n_cols = t->ne[0]; // hint: should be equal to n_embd
for (int col = 0; col < n_cols; ++col) {
if (ggml_get_f32_nd(t, col, row, 0, 0) > eps) {
return false;
}
}
return true;
};
std::vector<int> rows_to_copy; // the idx of non-zero cols (to be copied to row of diff_filtered)
for (int i_row = 0; i_row < a->ne[1]; i_row++) {
if (!is_row_all_zeros(a, i_row, 1e-6)) {
rows_to_copy.push_back(i_row);
}
}
// get "n_nonzero_rows" for the output "diff_filtered"
int n_nonzero_rows = rows_to_copy.size();
//printf("n_nonzero_rows: %d\n", n_nonzero_rows);
int n_embd = a->ne[0];
GGML_ASSERT(n_nonzero_rows > 0);
// diff_filtered: [n_embd, n_nonzero_rows]
struct ggml_tensor * diff_filtered = ggml_new_tensor_2d(
ctx_ggml, GGML_TYPE_F32, n_embd, n_nonzero_rows);
ggml_format_name(diff_filtered, "diff_filtered_%s", a->name);
diff_filtered->data = malloc(ggml_nbytes(diff_filtered));
// copy non-zero rows
for (int dest_row = 0; dest_row < n_nonzero_rows<|fim_middle|>{
float * a = (float *) v_pos[il]->data;
|
ative prompt
struct callback_data {
ggml_context * ctx_ggml = nullptr; // holds v_pos, v_neg, v_diff_filtered
int n_layers = 0;
int n_tokens = 0;
bool is_eval_pos = true;
// each element of the vector correspond to one layer
std::vector<struct ggml_tensor *> v_pos; // vector of matrices of size [n_embd, n_tokens]
std::vector<struct ggml_tensor *> v_neg; // vector of matrices of size [n_embd, n_tokens]
std::vector<struct ggml_tensor *> v_diff_filtered; // vector of matrices of size [n_embd, n_nonzero_rows]. NOTE: n_nonzero_rows maybe different for each layer
// save a tensor into either v_pos or v_neg (decided by is_eval_pos)
void save_tensor_for_layer(struct ggml_tensor * t) {
GGML_ASSERT(t->type == GGML_TYPE_F32);
if (ctx_ggml == nullptr) {
// alloc a new ctx_ggml if needed
struct ggml_init_params params_ggml = {
/*.mem_size =*/ ggml_tensor_overhead() * n_layers * 3u,
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ctx_ggml = ggml_init(params_ggml);
}
// copy tensor data
auto n_bytes = ggml_nbytes(t);
struct ggml_tensor * t_layer = ggml_new_tensor_2d(ctx_ggml, t->type, t->ne[0], t->ne[1]);
t_layer->data = malloc(n_bytes); // TODO @ngxson : get rid of this malloc somehow
ggml_backend_tensor_get(t, t_layer->data, 0, n_bytes);
ggml_set_name(t_layer, ggml_get_name(t));
//print_debug_tensor(t_layer);
if (is_eval_pos) {
v_pos.push_back(t_layer);
} else {
v_neg.push_back(t_layer);
}
}
// calculate diff (v_pos - v_neg) and place the result back to v_pos
// all zero rows in the diff tensor will also be removed
// NOTE: final layer is ignored. we only have (n_layers - 1) to process
std::vector<struct ggml_tensor *> calc_diff() {
for (float il = 0; il < v_pos.size(); il++)
|
{
float * a = (float *) v_pos[il]->data;
|
float * b = (float *) v_neg[il]->data;
size_t n_elem = ggml_nelements(v_pos[il]);
for (size_t j = 0; j < n_elem; j++) {
a[j] -= b[j];
}
//print_debug_tensor(v_pos[i]);
auto diff_filtered = filter_nonzero_rows(v_pos[il]);
v_diff_filtered.push_back(diff_filtered);
}
return v_diff_filtered; // for convinient, we return the result std::vector
}
// delete zero rows from a given 2D tensor
struct ggml_tensor * filter_nonzero_rows(struct ggml_tensor * a) {
//printf("filter_nonzero_rows\n");
auto is_row_all_zeros = [](struct ggml_tensor * t, int row, float eps) -> bool {
// check if given row containing all zero elements
int n_cols = t->ne[0]; // hint: should be equal to n_embd
for (int col = 0; col < n_cols; ++col) {
if (ggml_get_f32_nd(t, col, row, 0, 0) > eps) {
return false;
}
}
return true;
};
std::vector<int> rows_to_copy; // the idx of non-zero cols (to be copied to row of diff_filtered)
for (int i_row = 0; i_row < a->ne[1]; i_row++) {
if (!is_row_all_zeros(a, i_row, 1e-6)) {
rows_to_copy.push_back(i_row);
}
}
// get "n_nonzero_rows" for the output "diff_filtered"
int n_nonzero_rows = rows_to_copy.size();
//printf("n_nonzero_rows: %d\n", n_nonzero_rows);
int n_embd = a->ne[0];
GGML_ASSERT(n_nonzero_rows > 0);
// diff_filtered: [n_embd, n_nonzero_rows]
struct ggml_tensor * diff_filtered = ggml_new_tensor_2d(
ctx_ggml, GGML_TYPE_F32, n_embd, n_nonzero_rows);
ggml_format_name(diff_filtered, "diff_filtered_%s", a->name);
diff_filtered->data = malloc(ggml_nbytes(diff_filtered));
// copy non-zero rows
for (int dest_row = 0; dest_row < n_nonzero_rows
|
ast_based
|
<|fim_prefix|>#include "llama-adapter.h"
#include "llama-impl.h"
#include "llama-mmap.h"
#include "llama-model.h"
#include <map>
#include <cassert>
#include <sstream>
#include <stdexcept>
// vec
ggml_tensor * llama_adapter_cvec::tensor_for(int il) const {
if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
return nullptr;
}
return tensors[il];
}
ggml_tensor * llama_adapter_cvec::apply_to(ggml_context * ctx, ggml_tensor * cur, int il) const {
ggml_tensor * layer_dir = tensor_for(il);
if (layer_dir != nullptr) {
cur = ggml_add(ctx, cur, layer_dir);
}
return cur;<|fim_suffix|> GGML_ASSERT(ctxs.empty());
GGML_ASSERT(bufs.empty());
// create a context for each buffer type
std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
auto it = ctx_map.find(buft);
if (it == ctx_map.end()) {
ggml_init_params params = {
/*.mem_size =*/ hparams.n_layer*ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context * ctx = ggml_init(params);
if (!ctx) {
return nullptr;
}
ctx_map[buft] = ctx;
ctxs.emplace_back(ctx);
return ctx;
}
return it->second;
};
// make tensors
tensors.reserve(hparams.n_layer);
tensors.push_back(nullptr); // there's never a tensor for layer 0
for (size_t il = 1; il < hparams.n_layer; il++) {
ggml_backend_buffer_type_t buft = model.select_buft(il);
ggml_context * ctx = ctx_for_buft(buft);
if (!ctx) {
LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
return false;
}
ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.n_embd);
tensors.push_back(tensor);
}
// allocate tensors / buffers and zero
bufs.reserve(ctx_map.size());
for (auto it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx = it.second;
ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
if (!buf) {
LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
return false;
}
ggml_backend_buffer_clear(buf, 0);
bufs.emplace_back(buf);
}
return true;
}
bool llama_adapter_cvec::apply(
const llama_model & model,<|fim_middle|>}
bool llama_adapter_cvec::init(const llama_model & model) {
const auto & hparams = model.hparams;
GGML_ASSERT(tensors.empty());
|
#include "llama-adapter.h"
#include "llama-impl.h"
#include "llama-mmap.h"
#include "llama-model.h"
#include <map>
#include <cassert>
#include <sstream>
#include <stdexcept>
// vec
ggml_tensor * llama_adapter_cvec::tensor_for(int il) const {
if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
return nullptr;
}
return tensors[il];
}
ggml_tensor * llama_adapter_cvec::apply_to(ggml_context * ctx, ggml_tensor * cur, int il) const {
ggml_tensor * layer_dir = tensor_for(il);
if (layer_dir != nullptr) {
cur = ggml_add(ctx, cur, layer_dir);
}
return cur;
|
}
bool llama_adapter_cvec::init(const llama_model & model) {
const auto & hparams = model.hparams;
GGML_ASSERT(tensors.empty());
|
GGML_ASSERT(ctxs.empty());
GGML_ASSERT(bufs.empty());
// create a context for each buffer type
std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
auto it = ctx_map.find(buft);
if (it == ctx_map.end()) {
ggml_init_params params = {
/*.mem_size =*/ hparams.n_layer*ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context * ctx = ggml_init(params);
if (!ctx) {
return nullptr;
}
ctx_map[buft] = ctx;
ctxs.emplace_back(ctx);
return ctx;
}
return it->second;
};
// make tensors
tensors.reserve(hparams.n_layer);
tensors.push_back(nullptr); // there's never a tensor for layer 0
for (size_t il = 1; il < hparams.n_layer; il++) {
ggml_backend_buffer_type_t buft = model.select_buft(il);
ggml_context * ctx = ctx_for_buft(buft);
if (!ctx) {
LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
return false;
}
ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.n_embd);
tensors.push_back(tensor);
}
// allocate tensors / buffers and zero
bufs.reserve(ctx_map.size());
for (auto it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx = it.second;
ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
if (!buf) {
LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
return false;
}
ggml_backend_buffer_clear(buf, 0);
bufs.emplace_back(buf);
}
return true;
}
bool llama_adapter_cvec::apply(
const llama_model & model,
|
random
|
<|fim_prefix|>#include "llama-adapter.h"
#include "llama-impl.h"
#include "llama-mmap.h"
#include "llama-model.h"
#include <map>
#include <cassert>
#include <sstream>
#include <stdexcept>
// vec
ggml_tensor * llama_adapter_cvec::tensor_for(int il) const {
if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
return nullptr;
}
return tensors[il];
}
ggml_tensor * llama_adapter_cvec::apply_to(ggml_context * ctx, ggml_tensor * cur, int il) const {
ggml_tensor * layer_dir = tensor_for(il);
if (layer_dir != nullptr) {
cur = ggml_add(ctx, cur, layer_dir);
}
return cur;
}
bool llama_adapter_cvec::init(const llama_model & model) {
const auto & hparams = model.hparams;
GGML_ASSERT(tensors.empty());
GGML_ASSERT(ctxs.empty());
GGML_ASSERT(bufs.empty());
// create a context for each buffer type
std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
auto it = ctx_map.find(buft);
if (it == ctx_map.end()) {
ggml_init_params params = {
/*.mem_size =*/ hparams.n_layer*ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context * ctx = ggml_init(params);
if (!ctx) {
return nullptr;
}
ctx_map[buft] = ctx;
ctxs.emplace_back(ctx);
return ctx;
}
return it->second;
};
// make tensors
tensors.reserve(hparams.n_layer);
tensors.push_back(nullptr); // there's never a tensor for layer 0
for (size_t il = 1; il < hparams.n_layer; il++) {
ggml_backend_buffer_type_t buft = model.select_buft(il);
ggml_context * ctx = ctx_for_buft(buft);
<|fim_suffix|>
ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.n_embd);
tensors.push_back(tensor);
}
// allocate tensors / buffers and zero
bufs.reserve(ctx_map.size());
for (auto it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx = it.second;
ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
if (!buf) {
LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
return false;
}
ggml_backend_buffer_clear(buf, 0);
bufs.emplace_back(buf);
}
return true;
}
bool llama_adapter_cvec::apply(
const llama_model & model,
const float * data,
size_t len,
int32_t n_embd,
int32_t il_start,
int32_t il_end) {
const auto & hparams = model.hparams;
if (data == nullptr) {
// disable the current control vector (but leave allocated for later)
layer_start = -1;
layer_end = -1;
return true;
}
if (n_embd != (int) hparams.n_embd) {
LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
return false;
}
if (tensors.empty()) {
if (!init(model)) {
return false;
}
}
layer_start = il_start;
layer_end = il_end;
for (size_t il = 1; il < hparams.n_layer; il++) {
assert(tensors[il] != nullptr);
const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
if (off + n_embd <= len) {
ggml_backend_tensor_set(tensors[il], data + off, 0, n_embd * ggml_element_size(tensors[il]));
}
}
return true;
}
// lora
llama_adapter_lora_weight * llama_adapter_lora::get_weight(ggml_tensor * w) {
const std::string name(w->name);
const auto pos = ab_map.find(name);
if (pos != ab_map.end()) {
return &pos-<|fim_middle|>if (!ctx) {
LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
return false;
}
|
#include "llama-adapter.h"
#include "llama-impl.h"
#include "llama-mmap.h"
#include "llama-model.h"
#include <map>
#include <cassert>
#include <sstream>
#include <stdexcept>
// vec
ggml_tensor * llama_adapter_cvec::tensor_for(int il) const {
if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
return nullptr;
}
return tensors[il];
}
ggml_tensor * llama_adapter_cvec::apply_to(ggml_context * ctx, ggml_tensor * cur, int il) const {
ggml_tensor * layer_dir = tensor_for(il);
if (layer_dir != nullptr) {
cur = ggml_add(ctx, cur, layer_dir);
}
return cur;
}
bool llama_adapter_cvec::init(const llama_model & model) {
const auto & hparams = model.hparams;
GGML_ASSERT(tensors.empty());
GGML_ASSERT(ctxs.empty());
GGML_ASSERT(bufs.empty());
// create a context for each buffer type
std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
auto it = ctx_map.find(buft);
if (it == ctx_map.end()) {
ggml_init_params params = {
/*.mem_size =*/ hparams.n_layer*ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context * ctx = ggml_init(params);
if (!ctx) {
return nullptr;
}
ctx_map[buft] = ctx;
ctxs.emplace_back(ctx);
return ctx;
}
return it->second;
};
// make tensors
tensors.reserve(hparams.n_layer);
tensors.push_back(nullptr); // there's never a tensor for layer 0
for (size_t il = 1; il < hparams.n_layer; il++) {
ggml_backend_buffer_type_t buft = model.select_buft(il);
ggml_context * ctx = ctx_for_buft(buft);
|
if (!ctx) {
LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
return false;
}
|
ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.n_embd);
tensors.push_back(tensor);
}
// allocate tensors / buffers and zero
bufs.reserve(ctx_map.size());
for (auto it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx = it.second;
ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
if (!buf) {
LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
return false;
}
ggml_backend_buffer_clear(buf, 0);
bufs.emplace_back(buf);
}
return true;
}
bool llama_adapter_cvec::apply(
const llama_model & model,
const float * data,
size_t len,
int32_t n_embd,
int32_t il_start,
int32_t il_end) {
const auto & hparams = model.hparams;
if (data == nullptr) {
// disable the current control vector (but leave allocated for later)
layer_start = -1;
layer_end = -1;
return true;
}
if (n_embd != (int) hparams.n_embd) {
LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
return false;
}
if (tensors.empty()) {
if (!init(model)) {
return false;
}
}
layer_start = il_start;
layer_end = il_end;
for (size_t il = 1; il < hparams.n_layer; il++) {
assert(tensors[il] != nullptr);
const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
if (off + n_embd <= len) {
ggml_backend_tensor_set(tensors[il], data + off, 0, n_embd * ggml_element_size(tensors[il]));
}
}
return true;
}
// lora
llama_adapter_lora_weight * llama_adapter_lora::get_weight(ggml_tensor * w) {
const std::string name(w->name);
const auto pos = ab_map.find(name);
if (pos != ab_map.end()) {
return &pos-
|
ast_based
|
<|fim_prefix|> * @param description Description of the achievement
* @return Reference to the achievement
*/
Achievement& setDescription(std::string description) {
m_unlocalizedDescription = std::move(description);
return *this;
}
/**
* @brief Adds a requirement to the achievement. The achievement will only be unlockable if all requirements are unlocked.
* @param requirement Unlocalized name of the requirement
* @return Reference to the achievement
*/
Achievement& addRequirement(std::string requirement) {
m_requirements.emplace_back(std::move(requirement));
return *this;
}
/**
* @brief Adds a visibility requirement to the achievement. The achievement will only be visible if all requirements are unlocked.
* @param requirement Unlocalized name of the requirement
* @return Reference to the achievement
*/
Achievement& addVisibilityRequirement(std::string requirement) {
m_visibilityRequirements.emplace_back(std::move(requirement));
return *this;
}
/**
* @brief Marks the achievement as blacked. Blacked achievements are visible but their name and description are hidden.
* @return Reference to the achievement
*/
Achievement& setBlacked() {
m_blacked = true;
return *this;
}
/**
* @brief Marks the achievement as invisible. Invisible achievements are not visible at all.
* @return Reference to the achievement
*/
Achievement& setInvisible() {
m_invisible = true;
return *this;
}
/**
* @brief Returns whether the achievement is blacked
* @return Whether the achievement is blacked
*/
[[nodiscard]] bool isBlacked() const {<|fim_suffix|> [[nodiscard]] bool isInvisible() const {
return m_invisible;
}
/**
* @brief Returns the list of requirements of the achievement
* @return List of requirements of the achievement
*/
[[nodiscard]] const std::vector<std::string> &getRequirements() const {
return m_requirements;
}
/**
* @brief Returns the list of visibility requirements of the achievement
* @return List of visibility requirements of the achievement
*/
[[nodiscard]] const std::vector<std::string> &getVisibilityRequirements() const {
return m_visibilityRequirements;
}
/**
* @brief Returns the unlocalized description of the achievement
* @return Unlocalized description of the achievement
*/
[[nodiscard]] const UnlocalizedString &getUnlocalizedDescription() const {
return m_unlocalizedDescription;
}
/**
* @brief Returns the icon of the achievement
* @return Icon of the achievement
*/
[[nodiscard]] const ImGuiExt::Texture &getIcon() const {
if (m_iconData.empty())
return m_icon;
if (m_icon.isValid())
return m_icon;
m_icon = ImGuiExt::Texture::fromImage(m_iconData.data(), m_iconData.size(), ImGuiExt::Texture::Filter::Linear);
return m_icon;
}
/**
* @brief Sets the icon of the achievement
* @param data Icon data
* @return Reference to the achievement
*/
Achievement& setIcon(std::span<const std::byte> data) {
m_iconData.reserve(data.size());
for (auto &byte : data)
m_iconData.emplace_back(static_cast<u8>(byte));
return *this;
}
/**
* @brief Sets the icon of the achievement
* @param data Icon data<|fim_middle|> return m_blacked;
}
/**
* @brief Returns whether the achievement is invisible
* @return Whether the achievement is invisible
*/
|
* @param description Description of the achievement
* @return Reference to the achievement
*/
Achievement& setDescription(std::string description) {
m_unlocalizedDescription = std::move(description);
return *this;
}
/**
* @brief Adds a requirement to the achievement. The achievement will only be unlockable if all requirements are unlocked.
* @param requirement Unlocalized name of the requirement
* @return Reference to the achievement
*/
Achievement& addRequirement(std::string requirement) {
m_requirements.emplace_back(std::move(requirement));
return *this;
}
/**
* @brief Adds a visibility requirement to the achievement. The achievement will only be visible if all requirements are unlocked.
* @param requirement Unlocalized name of the requirement
* @return Reference to the achievement
*/
Achievement& addVisibilityRequirement(std::string requirement) {
m_visibilityRequirements.emplace_back(std::move(requirement));
return *this;
}
/**
* @brief Marks the achievement as blacked. Blacked achievements are visible but their name and description are hidden.
* @return Reference to the achievement
*/
Achievement& setBlacked() {
m_blacked = true;
return *this;
}
/**
* @brief Marks the achievement as invisible. Invisible achievements are not visible at all.
* @return Reference to the achievement
*/
Achievement& setInvisible() {
m_invisible = true;
return *this;
}
/**
* @brief Returns whether the achievement is blacked
* @return Whether the achievement is blacked
*/
[[nodiscard]] bool isBlacked() const {
|
return m_blacked;
}
/**
* @brief Returns whether the achievement is invisible
* @return Whether the achievement is invisible
*/
|
[[nodiscard]] bool isInvisible() const {
return m_invisible;
}
/**
* @brief Returns the list of requirements of the achievement
* @return List of requirements of the achievement
*/
[[nodiscard]] const std::vector<std::string> &getRequirements() const {
return m_requirements;
}
/**
* @brief Returns the list of visibility requirements of the achievement
* @return List of visibility requirements of the achievement
*/
[[nodiscard]] const std::vector<std::string> &getVisibilityRequirements() const {
return m_visibilityRequirements;
}
/**
* @brief Returns the unlocalized description of the achievement
* @return Unlocalized description of the achievement
*/
[[nodiscard]] const UnlocalizedString &getUnlocalizedDescription() const {
return m_unlocalizedDescription;
}
/**
* @brief Returns the icon of the achievement
* @return Icon of the achievement
*/
[[nodiscard]] const ImGuiExt::Texture &getIcon() const {
if (m_iconData.empty())
return m_icon;
if (m_icon.isValid())
return m_icon;
m_icon = ImGuiExt::Texture::fromImage(m_iconData.data(), m_iconData.size(), ImGuiExt::Texture::Filter::Linear);
return m_icon;
}
/**
* @brief Sets the icon of the achievement
* @param data Icon data
* @return Reference to the achievement
*/
Achievement& setIcon(std::span<const std::byte> data) {
m_iconData.reserve(data.size());
for (auto &byte : data)
m_iconData.emplace_back(static_cast<u8>(byte));
return *this;
}
/**
* @brief Sets the icon of the achievement
* @param data Icon data
|
random
|
<|fim_prefix|>nt Engine::get_max_fps() const {
return _max_fps;
}
void Engine::set_audio_output_latency(int p_msec) {
_audio_output_latency = p_msec > 1 ? p_msec : 1;
}
int Engine::get_audio_output_latency() const {
return _audio_output_latency;
}
void Engine::increment_frames_drawn() {
if (frame_server_synced) {
server_syncs++;
} else {
server_syncs = 0;
}
frame_server_synced = false;
frames_drawn++;
}
uint64_t Engine::get_frames_drawn() {
return frames_drawn;
}
void Engine::set_frame_delay(uint32_t p_msec) {
_frame_delay = p_msec;
}
uint32_t Engine::get_frame_delay() const {
return _frame_delay;
}
void Engine::set_time_scale(double p_scale) {
_time_scale = p_scale;
}
double Engine::get_time_scale() const {
return freeze_time_scale ? 0 : _time_scale;
}
double Engine::get_unfrozen_time_scale() const {
return _time_scale;
}
Dictionary Engine::get_version_info() const {
Dictionary dict;
dict["major"] = GODOT_VERSION_MAJOR;
dict["minor"] = GODOT_VERSION_MINOR;
dict["patch"] = GODOT_VERSION_PATCH;
dict["hex"] = GODOT_VERSION_HEX;
dict["status"] = GODOT_VERSION_STATUS;
dict["build"] = GODOT_VERSION_BUILD;
String hash = String(GODOT_VERSION_HASH);
dict["hash"] = hash.is_empty() ? String("unknown") : hash;
dict["timestamp"] = GODOT_VERSION_TIMESTAMP;
String stringver = String(dict["major"]) + "." + String(dict["minor"]);
if ((int)dict["patch"] != 0) {
stringver += "." + String(dict["patch"]);
}
stringver += "-" + String(dict["status"]) + " (" + String(dict["build"]) + ")";
dict["string"] = stringver;
return dict;
}
static Array array_from_info(const char *const *info_list) {
Array arr;
for (int i = 0; info_list[i] != nullptr; i++) {
arr.push_back(String::utf8(info_list[i]));
}
return arr;
}
static Array array_from_info_count(const char *const *info_list, int info_count) {
Array arr;
for (int i = 0; i < info_count; i++) {
arr.push_back(String::utf8(info_list[i]));
}
return arr;
}
Dictionary Engine::get_author_info() const <|fim_suffix|>
TypedArray<Dictionary> Engine::get_copyright_info() const {
TypedArray<Dictionary> components;
for (int component_index = 0; component_index < COPYRIGHT_INFO_COUNT; component_index++) {
const ComponentCopyright &cp_info = COPYRIGHT_INFO[component_index];
Dictionary component_dict;
component_dict["name"] = String::utf8(cp_info.name);
Array parts;
for (int i = 0; i < cp_info.part_count; i++) {
const ComponentCopyrightPart &cp_part = cp_info.parts[i];
Dictionary part_dict;
part_dict["files"] = array_from_info_count(cp_part.files, cp_part.file_count);
part_dict["copyright"] = array_from_info_count(cp_part.copyright_statements, cp_part.copyright_count);
part_dict["license"] = String::utf8(cp_part.license);
parts.push_back(part_dict);
}
component_dict["parts"] = parts;
components.push_back(component_dict);
}
return components;
}
Dictionary Engine::get_donor_info() const {
Dictionary donors;
donors["patrons"] = array_from_info(DONORS_PATRONS);
donors["platinum_sponsors"] = array_from_info(DONORS_SPONSORS_PLATINUM);
donors["gold_sponsors"] = array_from_info(DONORS_SPONSORS_GOLD);
donors["silver_sponsors"] = array_from_info(DONORS_SPONSORS_SILVER);
donors["diamond_members"] = array_from_info(DONORS_MEMBERS_DIAMOND);
donors["titanium_members"] = array_from_info(DONORS_MEMBERS_TITANIUM);
donors["platinum_members"] = array_from_info(DONORS_MEMBERS_PLATINUM);
donors["gold_members"] = array_from_info(DONORS_MEMBERS_GOLD);
return donors;
}
Dictionary Engine::get_license_info() const {
Dictionary licenses;
for (int i = 0; i < LICENSE_COUNT; i++) {
licenses[LICENSE_NAMES[i]] = LICENSE_BODIES[i];
}
return licenses;
}
String Engine::get_license_text() const {
return String(GODOT_LICENSE_TEXT);
}
String Engine::get_architecture_name() const {
#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
return "x86_64";
#elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
return "x86_32";
<|fim_middle|>{
Dictionary dict;
dict["lead_developers"] = array_from_info(AUTHORS_LEAD_DEVELOPERS);
dict["project_managers"] = array_from_info(AUTHORS_PROJECT_MANAGERS);
dict["founders"] = array_from_info(AUTHORS_FOUNDERS);
dict["developers"] = array_from_info(AUTHORS_DEVELOPERS);
return dict;
}
|
nt Engine::get_max_fps() const {
return _max_fps;
}
void Engine::set_audio_output_latency(int p_msec) {
_audio_output_latency = p_msec > 1 ? p_msec : 1;
}
int Engine::get_audio_output_latency() const {
return _audio_output_latency;
}
void Engine::increment_frames_drawn() {
if (frame_server_synced) {
server_syncs++;
} else {
server_syncs = 0;
}
frame_server_synced = false;
frames_drawn++;
}
uint64_t Engine::get_frames_drawn() {
return frames_drawn;
}
void Engine::set_frame_delay(uint32_t p_msec) {
_frame_delay = p_msec;
}
uint32_t Engine::get_frame_delay() const {
return _frame_delay;
}
void Engine::set_time_scale(double p_scale) {
_time_scale = p_scale;
}
double Engine::get_time_scale() const {
return freeze_time_scale ? 0 : _time_scale;
}
double Engine::get_unfrozen_time_scale() const {
return _time_scale;
}
Dictionary Engine::get_version_info() const {
Dictionary dict;
dict["major"] = GODOT_VERSION_MAJOR;
dict["minor"] = GODOT_VERSION_MINOR;
dict["patch"] = GODOT_VERSION_PATCH;
dict["hex"] = GODOT_VERSION_HEX;
dict["status"] = GODOT_VERSION_STATUS;
dict["build"] = GODOT_VERSION_BUILD;
String hash = String(GODOT_VERSION_HASH);
dict["hash"] = hash.is_empty() ? String("unknown") : hash;
dict["timestamp"] = GODOT_VERSION_TIMESTAMP;
String stringver = String(dict["major"]) + "." + String(dict["minor"]);
if ((int)dict["patch"] != 0) {
stringver += "." + String(dict["patch"]);
}
stringver += "-" + String(dict["status"]) + " (" + String(dict["build"]) + ")";
dict["string"] = stringver;
return dict;
}
static Array array_from_info(const char *const *info_list) {
Array arr;
for (int i = 0; info_list[i] != nullptr; i++) {
arr.push_back(String::utf8(info_list[i]));
}
return arr;
}
static Array array_from_info_count(const char *const *info_list, int info_count) {
Array arr;
for (int i = 0; i < info_count; i++) {
arr.push_back(String::utf8(info_list[i]));
}
return arr;
}
Dictionary Engine::get_author_info() const
|
{
Dictionary dict;
dict["lead_developers"] = array_from_info(AUTHORS_LEAD_DEVELOPERS);
dict["project_managers"] = array_from_info(AUTHORS_PROJECT_MANAGERS);
dict["founders"] = array_from_info(AUTHORS_FOUNDERS);
dict["developers"] = array_from_info(AUTHORS_DEVELOPERS);
return dict;
}
|
TypedArray<Dictionary> Engine::get_copyright_info() const {
TypedArray<Dictionary> components;
for (int component_index = 0; component_index < COPYRIGHT_INFO_COUNT; component_index++) {
const ComponentCopyright &cp_info = COPYRIGHT_INFO[component_index];
Dictionary component_dict;
component_dict["name"] = String::utf8(cp_info.name);
Array parts;
for (int i = 0; i < cp_info.part_count; i++) {
const ComponentCopyrightPart &cp_part = cp_info.parts[i];
Dictionary part_dict;
part_dict["files"] = array_from_info_count(cp_part.files, cp_part.file_count);
part_dict["copyright"] = array_from_info_count(cp_part.copyright_statements, cp_part.copyright_count);
part_dict["license"] = String::utf8(cp_part.license);
parts.push_back(part_dict);
}
component_dict["parts"] = parts;
components.push_back(component_dict);
}
return components;
}
Dictionary Engine::get_donor_info() const {
Dictionary donors;
donors["patrons"] = array_from_info(DONORS_PATRONS);
donors["platinum_sponsors"] = array_from_info(DONORS_SPONSORS_PLATINUM);
donors["gold_sponsors"] = array_from_info(DONORS_SPONSORS_GOLD);
donors["silver_sponsors"] = array_from_info(DONORS_SPONSORS_SILVER);
donors["diamond_members"] = array_from_info(DONORS_MEMBERS_DIAMOND);
donors["titanium_members"] = array_from_info(DONORS_MEMBERS_TITANIUM);
donors["platinum_members"] = array_from_info(DONORS_MEMBERS_PLATINUM);
donors["gold_members"] = array_from_info(DONORS_MEMBERS_GOLD);
return donors;
}
Dictionary Engine::get_license_info() const {
Dictionary licenses;
for (int i = 0; i < LICENSE_COUNT; i++) {
licenses[LICENSE_NAMES[i]] = LICENSE_BODIES[i];
}
return licenses;
}
String Engine::get_license_text() const {
return String(GODOT_LICENSE_TEXT);
}
String Engine::get_architecture_name() const {
#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
return "x86_64";
#elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
return "x86_32";
|
ast_based
|
<|fim_prefix|> CV_WRAP virtual void setCols(int val) = 0;
CV_WRAP virtual int getWindowSize() const = 0;
CV_WRAP virtual void setWindowSize(int val) = 0;
CV_WRAP virtual int getDepth() const = 0;
CV_WRAP virtual void getK(OutputArray val) const = 0;
CV_WRAP virtual void setK(InputArray val) = 0;
CV_WRAP virtual RgbdNormals::RgbdNormalsMethod getMethod() const = 0;
};
/** Registers depth data to an external camera
* Registration is performed by creating a depth cloud, transforming the cloud by
* the rigid body transformation between the cameras, and then projecting the
* transformed points into the RGB camera.
*
* uv_rgb = K_rgb * [R | t] * z * inv(K_ir) * uv_ir
*
* Currently does not check for negative depth values.
*
* @param unregisteredCameraMatrix the camera matrix of the depth camera
* @param registeredCameraMatrix the camera matrix of the external camera
* @param registeredDistCoeffs the distortion coefficients of the external camera
* @param Rt the rigid body transform between the cameras. Transforms points from depth camera frame to external camera frame.
* @param unregisteredDepth the input depth data
* @param outputImagePlaneSize the image plane dimensions of the external camera (width, height)
* @param registeredDepth the result of transforming the depth into the external camera
* @param depthDilation whether or not the depth is dilated to avoid holes and occlusion errors (optional)
*/
CV_EXPORTS_W void registerDepth(InputArray unregisteredCameraMatrix, InputArray registeredCameraMatrix, InputArray registeredDistCoeffs,
InputArray Rt, InputArray unregisteredDepth, const Size& outputImagePlaneSize,
OutputArray registeredDepth, bool depthDilation=false);
/**
* @param depth the depth image
* @param in_K
* @param in_points the list of xy coordinates
* @param points3d the resulting 3d points (point is represented by 4 chanels value [x, y, z, 0])
*/<|fim_suffix|>
/** Converts a depth image to 3d points. If the mask is empty then the resulting array has the same dimensions as `depth`,
* otherwise it is 1d vector containing mask-enabled values only.
* The coordinate system is x pointing left, y down and z away from the camera
* @param depth the depth image (if given as short int CV_U, it is assumed to be the depth in millimeters
* (as done with the Microsoft Kinect), otherwise, if given as CV_32F or CV_64F, it is assumed in meters)
* @param K The calibration matrix
* @param points3d the resulting 3d points (point is represented by 4 channels value [x, y, z, 0]). They are of the same depth as `depth` if it is CV_32F or CV_64F, and the
* depth of `K` if `depth` is of depth CV_16U or CV_16S
* @param mask the mask of the points to consider (can be empty)
*/
CV_EXPORTS_W void depthTo3d(InputArray depth, InputArray K, OutputArray points3d, InputArray mask = noArray());
/** If the input image is of type CV_16UC1 (like the Kinect one), the image is converted to floats, divided
* by depth_factor to get a depth in meters, and the values 0 are converted to std::numeric_limits<float>::quiet_NaN()
* Otherwise, the image is simply converted to floats
* @param in the depth image (if given as short int CV_U, it is assumed to be the depth in millimeters
* (as done with the Microsoft Kinect), it is assumed in meters)
* @param type the desired output depth (CV_32F or CV_64F)
* @param out The rescaled float depth image
* @param depth_factor (optional) factor by which depth is converted to distance (by default = 1000.0 for Kinect sensor)
*/
CV_EXPORTS_W void rescaleDepth(InputArray in, int type, OutputArray out, double depth_factor = 1000.0);
/** Warps depth or RGB-D image by reprojecting it in 3d, applying Rt transformation
* and then projecting it back onto the image plane.
* This function can be used to visualize the results of the Odometry algorithm.<|fim_middle|>CV_EXPORTS_W void depthTo3dSparse(InputArray depth, InputArray in_K, InputArray in_points, OutputArray points3d);
|
CV_WRAP virtual void setCols(int val) = 0;
CV_WRAP virtual int getWindowSize() const = 0;
CV_WRAP virtual void setWindowSize(int val) = 0;
CV_WRAP virtual int getDepth() const = 0;
CV_WRAP virtual void getK(OutputArray val) const = 0;
CV_WRAP virtual void setK(InputArray val) = 0;
CV_WRAP virtual RgbdNormals::RgbdNormalsMethod getMethod() const = 0;
};
/** Registers depth data to an external camera
* Registration is performed by creating a depth cloud, transforming the cloud by
* the rigid body transformation between the cameras, and then projecting the
* transformed points into the RGB camera.
*
* uv_rgb = K_rgb * [R | t] * z * inv(K_ir) * uv_ir
*
* Currently does not check for negative depth values.
*
* @param unregisteredCameraMatrix the camera matrix of the depth camera
* @param registeredCameraMatrix the camera matrix of the external camera
* @param registeredDistCoeffs the distortion coefficients of the external camera
* @param Rt the rigid body transform between the cameras. Transforms points from depth camera frame to external camera frame.
* @param unregisteredDepth the input depth data
* @param outputImagePlaneSize the image plane dimensions of the external camera (width, height)
* @param registeredDepth the result of transforming the depth into the external camera
* @param depthDilation whether or not the depth is dilated to avoid holes and occlusion errors (optional)
*/
CV_EXPORTS_W void registerDepth(InputArray unregisteredCameraMatrix, InputArray registeredCameraMatrix, InputArray registeredDistCoeffs,
InputArray Rt, InputArray unregisteredDepth, const Size& outputImagePlaneSize,
OutputArray registeredDepth, bool depthDilation=false);
/**
* @param depth the depth image
* @param in_K
* @param in_points the list of xy coordinates
* @param points3d the resulting 3d points (point is represented by 4 chanels value [x, y, z, 0])
*/
|
CV_EXPORTS_W void depthTo3dSparse(InputArray depth, InputArray in_K, InputArray in_points, OutputArray points3d);
|
/** Converts a depth image to 3d points. If the mask is empty then the resulting array has the same dimensions as `depth`,
* otherwise it is 1d vector containing mask-enabled values only.
* The coordinate system is x pointing left, y down and z away from the camera
* @param depth the depth image (if given as short int CV_U, it is assumed to be the depth in millimeters
* (as done with the Microsoft Kinect), otherwise, if given as CV_32F or CV_64F, it is assumed in meters)
* @param K The calibration matrix
* @param points3d the resulting 3d points (point is represented by 4 channels value [x, y, z, 0]). They are of the same depth as `depth` if it is CV_32F or CV_64F, and the
* depth of `K` if `depth` is of depth CV_16U or CV_16S
* @param mask the mask of the points to consider (can be empty)
*/
CV_EXPORTS_W void depthTo3d(InputArray depth, InputArray K, OutputArray points3d, InputArray mask = noArray());
/** If the input image is of type CV_16UC1 (like the Kinect one), the image is converted to floats, divided
* by depth_factor to get a depth in meters, and the values 0 are converted to std::numeric_limits<float>::quiet_NaN()
* Otherwise, the image is simply converted to floats
* @param in the depth image (if given as short int CV_U, it is assumed to be the depth in millimeters
* (as done with the Microsoft Kinect), it is assumed in meters)
* @param type the desired output depth (CV_32F or CV_64F)
* @param out The rescaled float depth image
* @param depth_factor (optional) factor by which depth is converted to distance (by default = 1000.0 for Kinect sensor)
*/
CV_EXPORTS_W void rescaleDepth(InputArray in, int type, OutputArray out, double depth_factor = 1000.0);
/** Warps depth or RGB-D image by reprojecting it in 3d, applying Rt transformation
* and then projecting it back onto the image plane.
* This function can be used to visualize the results of the Odometry algorithm.
|
random
|
<|fim_prefix|> return name.starts_with(entry.second + ": ");
});
if (it != s_backendNames.end())
return name;
return "Vulkan: " + name; // previously, there were only Vulkan devices
}
private:
static inline const std::unordered_map<std::string, std::string> s_backendNames {
{"cpu", "CPU"}, {"metal", "Metal"}, {"cuda", "CUDA"}, {"kompute", "Vulkan"},
};
};
class Implementation {
public:
Implementation(const Implementation &) = delete;
Implementation(Implementation &&);
~Implementation();
std::string_view modelType() const { return m_modelType; }
std::string_view buildVariant() const { return m_buildVariant; }
static LLModel *construct(const std::string &modelPath, const std::string &backend = "auto", int n_ctx = 2048);
static std::vector<GPUDevice> availableGPUDevices(size_t memoryRequired = 0);
static int32_t maxContextLength(const std::string &modelPath);
static int32_t layerCount(const std::string &modelPath);
static bool isEmbeddingModel(const std::string &modelPath);
static auto chatTemplate(const char *modelPath) -> std::expected<std::string, std::string>;
static void setImplementationsSearchPath(const std::string &path);
static const std::string &implementationsSearchPath();
static bool hasSupportedCPU();
// 0 for no, 1 for yes, -1 for non-x86_64
static int cpuSupportsAVX2();
private:
Implementation(Dlhandle &&);
static const std::vector<Implementation> &implementationList();
static const Implementation *implementation(const char *fname, const std::string &buildVariant);
static LLModel *constructGlobalLlama(const std::optional<std::string> &backend = std::nullopt);
char *(*m_getFileArch)(const char *fname);
bool (*m_isArchSupported)(const char *arch);<|fim_suffix|> int32_t n_predict = 200;
int32_t top_k = 40;
float top_p = 0.9f;
float min_p = 0.0f;
float temp = 0.9f;
int32_t n_batch = 9;
float repeat_penalty = 1.10f;
int32_t repeat_last_n = 64; // last n tokens to penalize
float contextErase = 0.5f; // percent of context to erase if we exceed the context window
};
explicit LLModel() {}
virtual ~LLModel() {}
virtual bool supportsEmbedding() const = 0;
virtual bool supportsCompletion() const = 0;
virtual bool loadModel(const std::string &modelPath, int n_ctx, int ngl) = 0;
virtual bool isModelBlacklisted(const std::string &modelPath) const { (void)modelPath; return false; }
virtual bool isEmbeddingModel(const std::string &modelPath) const { (void)modelPath; return false; }
virtual bool isModelLoaded() const = 0;
virtual size_t requiredMem(const std::string &modelPath, int n_ctx, int ngl) = 0;
virtual size_t stateSize() const = 0;
virtual size_t saveState(std::span<uint8_t> stateOut, std::vector<Token> &inputTokensOut) const = 0;
virtual size_t restoreState(std::span<const uint8_t> state, std::span<const Token> inputTokens) = 0;
// This method requires the model to return true from supportsCompletion otherwise it will throw
// an error
virtual void prompt(std::string_view prompt,
const PromptCallback &promptCallback,
const ResponseCallback &responseCallback,
const PromptContext &ctx);
virtual int32_t countPromptTokens(std::string_view prompt) const;
virtual size_t embeddingSize() const {
throw std::logic_error(std::string(implementation().modelType()) + " does not support embeddings");
}
// user-specified prefix
virtual void embed(const std::vector<std::string> &texts, float *embeddings, std::optional<std::string> prefix,<|fim_middle|> LLModel *(*m_construct)();
std::string_view m_modelType;
std::string_view m_buildVariant;
Dlhandle *m_dlhandle;
};
struct PromptContext {
|
return name.starts_with(entry.second + ": ");
});
if (it != s_backendNames.end())
return name;
return "Vulkan: " + name; // previously, there were only Vulkan devices
}
private:
static inline const std::unordered_map<std::string, std::string> s_backendNames {
{"cpu", "CPU"}, {"metal", "Metal"}, {"cuda", "CUDA"}, {"kompute", "Vulkan"},
};
};
class Implementation {
public:
Implementation(const Implementation &) = delete;
Implementation(Implementation &&);
~Implementation();
std::string_view modelType() const { return m_modelType; }
std::string_view buildVariant() const { return m_buildVariant; }
static LLModel *construct(const std::string &modelPath, const std::string &backend = "auto", int n_ctx = 2048);
static std::vector<GPUDevice> availableGPUDevices(size_t memoryRequired = 0);
static int32_t maxContextLength(const std::string &modelPath);
static int32_t layerCount(const std::string &modelPath);
static bool isEmbeddingModel(const std::string &modelPath);
static auto chatTemplate(const char *modelPath) -> std::expected<std::string, std::string>;
static void setImplementationsSearchPath(const std::string &path);
static const std::string &implementationsSearchPath();
static bool hasSupportedCPU();
// 0 for no, 1 for yes, -1 for non-x86_64
static int cpuSupportsAVX2();
private:
Implementation(Dlhandle &&);
static const std::vector<Implementation> &implementationList();
static const Implementation *implementation(const char *fname, const std::string &buildVariant);
static LLModel *constructGlobalLlama(const std::optional<std::string> &backend = std::nullopt);
char *(*m_getFileArch)(const char *fname);
bool (*m_isArchSupported)(const char *arch);
|
LLModel *(*m_construct)();
std::string_view m_modelType;
std::string_view m_buildVariant;
Dlhandle *m_dlhandle;
};
struct PromptContext {
|
int32_t n_predict = 200;
int32_t top_k = 40;
float top_p = 0.9f;
float min_p = 0.0f;
float temp = 0.9f;
int32_t n_batch = 9;
float repeat_penalty = 1.10f;
int32_t repeat_last_n = 64; // last n tokens to penalize
float contextErase = 0.5f; // percent of context to erase if we exceed the context window
};
explicit LLModel() {}
virtual ~LLModel() {}
virtual bool supportsEmbedding() const = 0;
virtual bool supportsCompletion() const = 0;
virtual bool loadModel(const std::string &modelPath, int n_ctx, int ngl) = 0;
virtual bool isModelBlacklisted(const std::string &modelPath) const { (void)modelPath; return false; }
virtual bool isEmbeddingModel(const std::string &modelPath) const { (void)modelPath; return false; }
virtual bool isModelLoaded() const = 0;
virtual size_t requiredMem(const std::string &modelPath, int n_ctx, int ngl) = 0;
virtual size_t stateSize() const = 0;
virtual size_t saveState(std::span<uint8_t> stateOut, std::vector<Token> &inputTokensOut) const = 0;
virtual size_t restoreState(std::span<const uint8_t> state, std::span<const Token> inputTokens) = 0;
// This method requires the model to return true from supportsCompletion otherwise it will throw
// an error
virtual void prompt(std::string_view prompt,
const PromptCallback &promptCallback,
const ResponseCallback &responseCallback,
const PromptContext &ctx);
virtual int32_t countPromptTokens(std::string_view prompt) const;
virtual size_t embeddingSize() const {
throw std::logic_error(std::string(implementation().modelType()) + " does not support embeddings");
}
// user-specified prefix
virtual void embed(const std::vector<std::string> &texts, float *embeddings, std::optional<std::string> prefix,
|
random
|
<|fim_prefix|>olo_rect.position);
RBMap<int, Rect2> track_icons;
track_icons[REMOVE_ICON] = remove_rect;
track_icons[LOCK_ICON] = lock_rect;
track_icons[VISIBILITY_ICON] = visible_rect;
track_icons[SOLO_ICON] = solo_rect;
subtrack_icons[current_track] = track_icons;
vofs += text_buf.get_size().y + v_separation;
track_v_scroll_max += text_buf.get_size().y + v_separation;
}
}
const Color accent = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
// Guides.
{
float min_left_scale = font->get_height(font_size) + v_separation;
float scale = (min_left_scale * 2) * timeline_v_zoom;
float step = Math::pow(10.0, Math::round(Math::log(scale / 5.0) / Math::log(10.0))) * 5.0;
scale = Math::snapped(scale, step);
while (scale / timeline_v_zoom < min_left_scale * 2) {
scale += step;
}
bool first = true;
int prev_iv = 0;
for (int i = font->get_height(font_size); i < get_size().height; i++) {
float ofs = get_size().height / 2.0 - i;
ofs *= timeline_v_zoom;
ofs += timeline_v_scroll;
int iv = int(ofs / scale);
if (ofs < 0) {
iv -= 1;
}
if (!first && iv != prev_iv) {
Color lc = h_line_color;
lc.a *= 0.5;
draw_line(Point2(limit, i), Point2(right_limit, i), lc, Math::round(EDSCALE));
Color c = color;
c.a *= 0.5;
draw_string(font, Point2(limit + 8, i - 2), TS->format_number(rtos(Math::snapped((iv + 1) * scale, step))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, c);
}
first = false;
prev_iv = iv;
}
}
// Draw other curves.
{
float scale = timeline->get_zoom_scale();
Ref<Texture2D> point = get_editor_theme_icon(SNAME("KeyValue"));
for (const KeyValue<int, Color> &E : subtrack_colors) {
if (hidden_tracks.has(E.key)) {
continue;
}
_draw_track(E.key, E.value);
for (int i = 0; i < animation->track_get_key_count(E.key); i++) {
float offset = <|fim_suffix|>;
float value = animation->bezier_track_get_key_value(E.key, i);
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (pos.x >= limit && pos.x <= right_limit) {
draw_texture(point, pos - point->get_size() / 2.0, E.value);
}
}
}
if (track_count > 0 && !hidden_tracks.has(selected_track)) {
// Draw edited curve.
_draw_track(selected_track, selected_track_color);
}
}
const bool draw_selection_handles = selection.size() > 1;
LocalVector<Point2> selected_pos;
// Draw editor handles.
{
edit_points.clear();
float scale = timeline->get_zoom_scale();
for (int i = 0; i < track_count; ++i) {
bool draw_track = _is_track_curves_displayed(i) && !locked_tracks.has(i);
if (!draw_selection_handles && !draw_track) {
continue;
}
int key_count = animation->track_get_key_count(i);
for (int j = 0; j < key_count; ++j) {
float offset = animation->track_get_key_time(i, j);
float value = animation->bezier_track_get_key_value(i, j);
bool is_selected = selection.has(IntPair(i, j));
if (is_selected) {
if (moving_selection) {
offset += moving_selection_offset.x;
value += moving_selection_offset.y;
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
value += -scaling_selection_offset.y + (value - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (draw_selection_handles && is_selected) {
selected_pos.push_back(pos);
}
if (!draw_track) {
continue;
}
Vector2 in_vec = animation->bezier_track_get_key_in_handle(i, j);
Vector2 out_vec = animation->bezier_track_get_key_out_handle(i, j);
if ((moving_h<|fim_middle|>animation->track_get_key_time(E.key, i)
|
olo_rect.position);
RBMap<int, Rect2> track_icons;
track_icons[REMOVE_ICON] = remove_rect;
track_icons[LOCK_ICON] = lock_rect;
track_icons[VISIBILITY_ICON] = visible_rect;
track_icons[SOLO_ICON] = solo_rect;
subtrack_icons[current_track] = track_icons;
vofs += text_buf.get_size().y + v_separation;
track_v_scroll_max += text_buf.get_size().y + v_separation;
}
}
const Color accent = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
// Guides.
{
float min_left_scale = font->get_height(font_size) + v_separation;
float scale = (min_left_scale * 2) * timeline_v_zoom;
float step = Math::pow(10.0, Math::round(Math::log(scale / 5.0) / Math::log(10.0))) * 5.0;
scale = Math::snapped(scale, step);
while (scale / timeline_v_zoom < min_left_scale * 2) {
scale += step;
}
bool first = true;
int prev_iv = 0;
for (int i = font->get_height(font_size); i < get_size().height; i++) {
float ofs = get_size().height / 2.0 - i;
ofs *= timeline_v_zoom;
ofs += timeline_v_scroll;
int iv = int(ofs / scale);
if (ofs < 0) {
iv -= 1;
}
if (!first && iv != prev_iv) {
Color lc = h_line_color;
lc.a *= 0.5;
draw_line(Point2(limit, i), Point2(right_limit, i), lc, Math::round(EDSCALE));
Color c = color;
c.a *= 0.5;
draw_string(font, Point2(limit + 8, i - 2), TS->format_number(rtos(Math::snapped((iv + 1) * scale, step))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, c);
}
first = false;
prev_iv = iv;
}
}
// Draw other curves.
{
float scale = timeline->get_zoom_scale();
Ref<Texture2D> point = get_editor_theme_icon(SNAME("KeyValue"));
for (const KeyValue<int, Color> &E : subtrack_colors) {
if (hidden_tracks.has(E.key)) {
continue;
}
_draw_track(E.key, E.value);
for (int i = 0; i < animation->track_get_key_count(E.key); i++) {
float offset =
|
animation->track_get_key_time(E.key, i)
|
;
float value = animation->bezier_track_get_key_value(E.key, i);
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (pos.x >= limit && pos.x <= right_limit) {
draw_texture(point, pos - point->get_size() / 2.0, E.value);
}
}
}
if (track_count > 0 && !hidden_tracks.has(selected_track)) {
// Draw edited curve.
_draw_track(selected_track, selected_track_color);
}
}
const bool draw_selection_handles = selection.size() > 1;
LocalVector<Point2> selected_pos;
// Draw editor handles.
{
edit_points.clear();
float scale = timeline->get_zoom_scale();
for (int i = 0; i < track_count; ++i) {
bool draw_track = _is_track_curves_displayed(i) && !locked_tracks.has(i);
if (!draw_selection_handles && !draw_track) {
continue;
}
int key_count = animation->track_get_key_count(i);
for (int j = 0; j < key_count; ++j) {
float offset = animation->track_get_key_time(i, j);
float value = animation->bezier_track_get_key_value(i, j);
bool is_selected = selection.has(IntPair(i, j));
if (is_selected) {
if (moving_selection) {
offset += moving_selection_offset.x;
value += moving_selection_offset.y;
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
value += -scaling_selection_offset.y + (value - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (draw_selection_handles && is_selected) {
selected_pos.push_back(pos);
}
if (!draw_track) {
continue;
}
Vector2 in_vec = animation->bezier_track_get_key_in_handle(i, j);
Vector2 out_vec = animation->bezier_track_get_key_out_handle(i, j);
if ((moving_h
|
ast_based
|
<|fim_prefix|>text_align(const RID &p_id, HorizontalAlignment p_align) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_align) {
case HORIZONTAL_ALIGNMENT_LEFT: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_LEFT);
} break;
case HORIZONTAL_ALIGNMENT_CENTER: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_RIGHT);
} break;
case HORIZONTAL_ALIGNMENT_RIGHT: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_CENTER);
} break;
case HORIZONTAL_ALIGNMENT_FILL: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_JUSTIFY);
} break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_selection(const RID &p_id, const RID &p_text_start_id, int p_start_char, const RID &p_text_end_id, int p_end_char) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *start_ae = rid_owner.get_or_null(p_text_start_id);
ERR_FAIL_NULL(start_ae);
ERR_FAIL_COND(start_ae->window_id != ae->window_id);
AccessibilityElement *end_ae = rid_owner.get_or_null(p_text_end_id);
ERR_FAIL_NULL(end_ae);
ERR_FAIL_COND(end_ae->window_id != ae->window_id);
int start_pos = p_start_char;
int end_pos = p_end_char;
RID start_rid;
RID end_rid;
for (const RID &rid : start_ae->children) {
const AccessibilityElement *child_ae = rid_owner.get_or_null(rid);
if (child_ae && child_ae->role == ACCESSKIT_ROLE_TEXT_RUN) {
if (p_start_char >= child_ae->run.x && p_start_char <= child_ae->run.y) {
start_rid = rid;
start_pos = p_start_char - child_ae->run.x;
break;
}
}
}
for (const RID &rid : end_ae->children) <|fim_suffix|>
ERR_FAIL_COND(start_rid.is_null() && end_rid.is_null());
_ensure_node(p_id, ae);
accesskit_text_selection sel;
sel.anchor.node = (accesskit_node_id)start_rid.get_id();
sel.anchor.character_index = start_pos;
sel.focus.node = (accesskit_node_id)end_rid.get_id();
sel.focus.character_index = end_pos;
accesskit_node_set_text_selection(ae->node, sel);
}
void AccessibilityDriverAccessKit::accessibility_update_set_flag(const RID &p_id, DisplayServer::AccessibilityFlags p_flag, bool p_value) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_flag) {
case DisplayServer::AccessibilityFlags::FLAG_HIDDEN: {
if (p_value) {
accesskit_node_set_hidden(ae->node);
} else {
accesskit_node_clear_hidden(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_MULTISELECTABLE: {
if (p_value) {
accesskit_node_set_multiselectable(ae->node);
} else {
accesskit_node_clear_multiselectable(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_REQUIRED: {
if (p_value) {
accesskit_node_set_required(ae->node);
} else {
accesskit_node_clear_required(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_VISITED: {
if (p_value) {
accesskit_node_set_visited(ae->node);
} else {
accesskit_node_clear_visited(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_BUSY: {
if (p_value) {
accesskit_node_set_busy(ae->node);
} else {
accesskit_node_clear_busy(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_MODAL: {
if (p_value) {
accesskit_node_set_modal(ae->node);
} else {
accesskit_node_clear_modal(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_TOUCH_PASSTHROUGH: {
if (p_va<|fim_middle|>{
const AccessibilityElement *child_ae = rid_owner.get_or_null(rid);
if (child_ae && child_ae->role == ACCESSKIT_ROLE_TEXT_RUN) {
if (p_end_char >= child_ae->run.x && p_end_char <= child_ae->run.y) {
end_rid = rid;
end_pos = p_end_char - child_ae->run.x;
break;
}
}
}
|
text_align(const RID &p_id, HorizontalAlignment p_align) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_align) {
case HORIZONTAL_ALIGNMENT_LEFT: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_LEFT);
} break;
case HORIZONTAL_ALIGNMENT_CENTER: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_RIGHT);
} break;
case HORIZONTAL_ALIGNMENT_RIGHT: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_CENTER);
} break;
case HORIZONTAL_ALIGNMENT_FILL: {
accesskit_node_set_text_align(ae->node, ACCESSKIT_TEXT_ALIGN_JUSTIFY);
} break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_text_selection(const RID &p_id, const RID &p_text_start_id, int p_start_char, const RID &p_text_end_id, int p_end_char) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *start_ae = rid_owner.get_or_null(p_text_start_id);
ERR_FAIL_NULL(start_ae);
ERR_FAIL_COND(start_ae->window_id != ae->window_id);
AccessibilityElement *end_ae = rid_owner.get_or_null(p_text_end_id);
ERR_FAIL_NULL(end_ae);
ERR_FAIL_COND(end_ae->window_id != ae->window_id);
int start_pos = p_start_char;
int end_pos = p_end_char;
RID start_rid;
RID end_rid;
for (const RID &rid : start_ae->children) {
const AccessibilityElement *child_ae = rid_owner.get_or_null(rid);
if (child_ae && child_ae->role == ACCESSKIT_ROLE_TEXT_RUN) {
if (p_start_char >= child_ae->run.x && p_start_char <= child_ae->run.y) {
start_rid = rid;
start_pos = p_start_char - child_ae->run.x;
break;
}
}
}
for (const RID &rid : end_ae->children)
|
{
const AccessibilityElement *child_ae = rid_owner.get_or_null(rid);
if (child_ae && child_ae->role == ACCESSKIT_ROLE_TEXT_RUN) {
if (p_end_char >= child_ae->run.x && p_end_char <= child_ae->run.y) {
end_rid = rid;
end_pos = p_end_char - child_ae->run.x;
break;
}
}
}
|
ERR_FAIL_COND(start_rid.is_null() && end_rid.is_null());
_ensure_node(p_id, ae);
accesskit_text_selection sel;
sel.anchor.node = (accesskit_node_id)start_rid.get_id();
sel.anchor.character_index = start_pos;
sel.focus.node = (accesskit_node_id)end_rid.get_id();
sel.focus.character_index = end_pos;
accesskit_node_set_text_selection(ae->node, sel);
}
void AccessibilityDriverAccessKit::accessibility_update_set_flag(const RID &p_id, DisplayServer::AccessibilityFlags p_flag, bool p_value) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
switch (p_flag) {
case DisplayServer::AccessibilityFlags::FLAG_HIDDEN: {
if (p_value) {
accesskit_node_set_hidden(ae->node);
} else {
accesskit_node_clear_hidden(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_MULTISELECTABLE: {
if (p_value) {
accesskit_node_set_multiselectable(ae->node);
} else {
accesskit_node_clear_multiselectable(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_REQUIRED: {
if (p_value) {
accesskit_node_set_required(ae->node);
} else {
accesskit_node_clear_required(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_VISITED: {
if (p_value) {
accesskit_node_set_visited(ae->node);
} else {
accesskit_node_clear_visited(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_BUSY: {
if (p_value) {
accesskit_node_set_busy(ae->node);
} else {
accesskit_node_clear_busy(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_MODAL: {
if (p_value) {
accesskit_node_set_modal(ae->node);
} else {
accesskit_node_clear_modal(ae->node);
}
} break;
case DisplayServer::AccessibilityFlags::FLAG_TOUCH_PASSTHROUGH: {
if (p_va
|
ast_based
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.