text
stringlengths
558
4.54k
prefix
stringlengths
100
2k
middle
stringlengths
10
500
suffix
stringlengths
100
2k
type
stringclasses
2 values
<|fim_prefix|>P_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) { <|fim_suffix|> 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.unicharset->get_script_from_script_id(script_id); *script_name = script; } if (script_conf) { *script_conf = osr.best_result.sconfidence; } return true; } /** * The recognized text is returned as a char* which is coded * as UTF8 and must be freed with the delete [] operator. * page_number is a 0-based page index that<|fim_middle|>uni_ch = kLatinChs[j];
P_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.unicharset->get_script_from_script_id(script_id); *script_name = script; } if (script_conf) { *script_conf = osr.best_result.sconfidence; } return true; } /** * The recognized text is returned as a char* which is coded * as UTF8 and must be freed with the delete [] operator. * page_number is a 0-based page index that
ast_based
<|fim_prefix|>_key_frame"); undo_redo->add_undo_method(ape, "_animation_update_key_frame"); } undo_redo->commit_action(); //selection.clear(); } } void AnimationBezierTrackEdit::_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) { int idx = p_anim->bezier_track_insert_key(p_track, p_time, p_value, p_in_handle, p_out_handle); p_anim->bezier_track_set_key_handle_mode(p_track, idx, p_handle_mode, p_handle_set_mode); } void AnimationBezierTrackEdit::_bind_methods() { ClassDB::bind_method(D_METHOD("_clear_selection"), &AnimationBezierTrackEdit::_clear_selection); ClassDB::bind_method(D_METHOD("_clear_selection_for_anim"), &AnimationBezierTrackEdit::_clear_selection_for_anim); ClassDB::bind_method(D_METHOD("_select_at_anim"), &AnimationBezierTrackEdit::_select_at_anim); ClassDB::bind_method(D_METHOD("_update_hidden_tracks_after"), &AnimationBezierTrackEdit::_update_hidden_tracks_after); ClassDB::bind_method(D_METHOD("_update_locked_tracks_after"), &AnimationBezierTrackEdit::_update_locked_tracks_after); ClassDB::bind_method(D_METHOD("_bezier_track_insert_key_at_anim"), &AnimationBezierTrackEdit::_bezier_track_insert_key_at_anim, DEFVAL(Animation::HANDLE_SET_MODE_NONE)); ADD_SIGNAL(MethodInfo("select_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "single"), PropertyInfo(Variant::INT, "track"))); ADD_SIGNAL(MethodInfo("deselect_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::INT, "track"))); ADD_SIGNAL(MethodInfo("clear_selection")); ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::FLOAT, "position"), PropertyInfo(Variant::BOOL, "timeline_only"))); } AnimationBezierTrackEdit::AnimationBezierTrackEdit() { panner.instantiate(); panner->set_callbacks(callable_mp(this, &AnimationBezierTrackEdit::_pan_callback), <|fim_suffix|>); play_position = memnew(Control); play_position->set_mouse_filter(MOUSE_FILTER_PASS); add_child(play_position); play_position->set_anchors_and_offsets_preset(PRESET_FULL_RECT); play_position->connect(SceneStringName(draw), callable_mp(this, &AnimationBezierTrackEdit::_play_position_draw)); set_focus_mode(FOCUS_CLICK); set_clip_contents(true); ED_SHORTCUT("animation_bezier_editor/focus", TTRC("Focus"), Key::F); ED_SHORTCUT("animation_bezier_editor/select_all_keys", TTRC("Select All Keys"), KeyModifierMask::CMD_OR_CTRL | Key::A); ED_SHORTCUT("animation_bezier_editor/deselect_all_keys", TTRC("Deselect All Keys"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::A); menu = memnew(PopupMenu); add_child(menu); menu->connect(SceneStringName(id_pressed), callable_mp(this, &AnimationBezierTrackEdit::_menu_selected)); } <|fim_middle|>callable_mp(this, &AnimationBezierTrackEdit::_zoom_callback)
_key_frame"); undo_redo->add_undo_method(ape, "_animation_update_key_frame"); } undo_redo->commit_action(); //selection.clear(); } } void AnimationBezierTrackEdit::_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) { int idx = p_anim->bezier_track_insert_key(p_track, p_time, p_value, p_in_handle, p_out_handle); p_anim->bezier_track_set_key_handle_mode(p_track, idx, p_handle_mode, p_handle_set_mode); } void AnimationBezierTrackEdit::_bind_methods() { ClassDB::bind_method(D_METHOD("_clear_selection"), &AnimationBezierTrackEdit::_clear_selection); ClassDB::bind_method(D_METHOD("_clear_selection_for_anim"), &AnimationBezierTrackEdit::_clear_selection_for_anim); ClassDB::bind_method(D_METHOD("_select_at_anim"), &AnimationBezierTrackEdit::_select_at_anim); ClassDB::bind_method(D_METHOD("_update_hidden_tracks_after"), &AnimationBezierTrackEdit::_update_hidden_tracks_after); ClassDB::bind_method(D_METHOD("_update_locked_tracks_after"), &AnimationBezierTrackEdit::_update_locked_tracks_after); ClassDB::bind_method(D_METHOD("_bezier_track_insert_key_at_anim"), &AnimationBezierTrackEdit::_bezier_track_insert_key_at_anim, DEFVAL(Animation::HANDLE_SET_MODE_NONE)); ADD_SIGNAL(MethodInfo("select_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "single"), PropertyInfo(Variant::INT, "track"))); ADD_SIGNAL(MethodInfo("deselect_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::INT, "track"))); ADD_SIGNAL(MethodInfo("clear_selection")); ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::FLOAT, "position"), PropertyInfo(Variant::BOOL, "timeline_only"))); } AnimationBezierTrackEdit::AnimationBezierTrackEdit() { panner.instantiate(); panner->set_callbacks(callable_mp(this, &AnimationBezierTrackEdit::_pan_callback),
callable_mp(this, &AnimationBezierTrackEdit::_zoom_callback)
); play_position = memnew(Control); play_position->set_mouse_filter(MOUSE_FILTER_PASS); add_child(play_position); play_position->set_anchors_and_offsets_preset(PRESET_FULL_RECT); play_position->connect(SceneStringName(draw), callable_mp(this, &AnimationBezierTrackEdit::_play_position_draw)); set_focus_mode(FOCUS_CLICK); set_clip_contents(true); ED_SHORTCUT("animation_bezier_editor/focus", TTRC("Focus"), Key::F); ED_SHORTCUT("animation_bezier_editor/select_all_keys", TTRC("Select All Keys"), KeyModifierMask::CMD_OR_CTRL | Key::A); ED_SHORTCUT("animation_bezier_editor/deselect_all_keys", TTRC("Deselect All Keys"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::A); menu = memnew(PopupMenu); add_child(menu); menu->connect(SceneStringName(id_pressed), callable_mp(this, &AnimationBezierTrackEdit::_menu_selected)); }
ast_based
<|fim_prefix|>s 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) { <|fim_suffix|> 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(); f<|fim_middle|>if (is_hdr) { target_format = Image::FORMAT_ASTC_8x8_HDR; }
s 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, 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(); f
ast_based
<|fim_prefix|> 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);<|fim_suffix|> } 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) {<|fim_middle|> 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);
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, 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) {
random
<|fim_prefix|>>GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } /** * Get a reading-order iterator to the results of LayoutAnalysis and/or * Recognize. The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ ResultIterator *TessBaseAPI::GetIterator() { if (tesseract_ == nullptr || page_res_ == nullptr) { return nullptr; } return ResultIterator::StartOfParagraph(LTRResultIterator( page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_)); } /** * Get a mutable iterator to the results of LayoutAnalysis and/or Recognize. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ MutableIterator *TessBaseAPI::GetMutableIterator() { if (tesseract_ == nullptr || page_res_ == nullptr) { return nullptr; } return new MutableIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } /** Make a text string from the internal data structures. */ char *TessBaseAPI::GetUTF8Text() { if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) { return nullptr; } std::string text(""); const std::unique_ptr</*non-const*/ ResultIterator> it(GetIterator()); do { <|fim_suffix|> auto block_type = it->BlockType(); switch (block_type) { case PT_FLOWING_IMAGE: case PT_HEADING_IMAGE: case PT_PULLOUT_IMAGE: case PT_HORZ_LINE: case PT_VERT_LINE: // Ignore images and lines for text output. continue; case PT_NOISE: tprintf("TODO: Please report image which triggers the noise case.\n"); ASSERT_HOST(false); default: break; } const std::unique_ptr<const char[]> para_text(it->GetUTF8Text(RIL_PARA)); text += para_text.get(); } while (it->Next(RIL_PARA)); return copy_string(text); } static void AddBoxToTSV(const PageIterator *it, PageIteratorLevel level, std::string &text) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); text += "\t" + std::to_string(left); text += "\t" + std::to_string(top); text += "\t" + std::to_string(right - left); text += "\t" + std::to_string(bottom - top); } /** * Make a TSV-formatted string from the internal data structures. * page_number is 0-based but will appear in the output as 1-based. * Returned string must be freed with the delete [] operator. */ char *TessBaseAPI::GetTSVText(int page_number) { if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(nullptr) < 0)) { return nullptr; } #if !defined(NDEBUG) int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1; #endif int page_id = page_number + 1; // we use 1-based page numbers. int page_num = page_id; int block_num = 0; int par_num = 0; int line_num = 0; int word_num = 0; std::string tsv_str; tsv_str += "1\t" + std::to_string(page_num); // level 1 - page tsv_str += "\t" + std::to_string(block_num); tsv_str += "\t" + std::to_string(par_num); tsv_str += "\t" + std::to_string(line_num); tsv_str += "\t" + std::to_string(word_num); tsv_str += "\t" + std::to_string(rect_left_); tsv_str += "\t" + std::to_string(rect_top_); tsv_str += "\t" + std::to_string(rect_width_); tsv_str +=<|fim_middle|>if (it->Empty(RIL_PARA)) { continue; }
>GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } /** * Get a reading-order iterator to the results of LayoutAnalysis and/or * Recognize. The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ ResultIterator *TessBaseAPI::GetIterator() { if (tesseract_ == nullptr || page_res_ == nullptr) { return nullptr; } return ResultIterator::StartOfParagraph(LTRResultIterator( page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_)); } /** * Get a mutable iterator to the results of LayoutAnalysis and/or Recognize. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ MutableIterator *TessBaseAPI::GetMutableIterator() { if (tesseract_ == nullptr || page_res_ == nullptr) { return nullptr; } return new MutableIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } /** Make a text string from the internal data structures. */ char *TessBaseAPI::GetUTF8Text() { if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) { return nullptr; } std::string text(""); const std::unique_ptr</*non-const*/ ResultIterator> it(GetIterator()); do {
if (it->Empty(RIL_PARA)) { continue; }
auto block_type = it->BlockType(); switch (block_type) { case PT_FLOWING_IMAGE: case PT_HEADING_IMAGE: case PT_PULLOUT_IMAGE: case PT_HORZ_LINE: case PT_VERT_LINE: // Ignore images and lines for text output. continue; case PT_NOISE: tprintf("TODO: Please report image which triggers the noise case.\n"); ASSERT_HOST(false); default: break; } const std::unique_ptr<const char[]> para_text(it->GetUTF8Text(RIL_PARA)); text += para_text.get(); } while (it->Next(RIL_PARA)); return copy_string(text); } static void AddBoxToTSV(const PageIterator *it, PageIteratorLevel level, std::string &text) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); text += "\t" + std::to_string(left); text += "\t" + std::to_string(top); text += "\t" + std::to_string(right - left); text += "\t" + std::to_string(bottom - top); } /** * Make a TSV-formatted string from the internal data structures. * page_number is 0-based but will appear in the output as 1-based. * Returned string must be freed with the delete [] operator. */ char *TessBaseAPI::GetTSVText(int page_number) { if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(nullptr) < 0)) { return nullptr; } #if !defined(NDEBUG) int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1; #endif int page_id = page_number + 1; // we use 1-based page numbers. int page_num = page_id; int block_num = 0; int par_num = 0; int line_num = 0; int word_num = 0; std::string tsv_str; tsv_str += "1\t" + std::to_string(page_num); // level 1 - page tsv_str += "\t" + std::to_string(block_num); tsv_str += "\t" + std::to_string(par_num); tsv_str += "\t" + std::to_string(line_num); tsv_str += "\t" + std::to_string(word_num); tsv_str += "\t" + std::to_string(rect_left_); tsv_str += "\t" + std::to_string(rect_top_); tsv_str += "\t" + std::to_string(rect_width_); tsv_str +=
ast_based
<|fim_prefix|> (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; } <|fim_suffix|> 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) ==<|fim_middle|>if (tessedit_page_number >= 0) { break; }
(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 // 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) ==
ast_based
<|fim_prefix|> 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, solo->get_width(), solo->get_height()); draw_texture(solo, solo_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);<|fim_suffix|> 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);<|fim_middle|> while (scale / timeline_v_zoom < min_left_scale * 2) {
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, solo->get_width(), solo->get_height()); draw_texture(solo, solo_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);
random
<|fim_prefix|>R_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 = <|fim_suffix|>; 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_n<|fim_middle|>rid_owner.get_or_null(p_id)
R_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_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_n
ast_based
<|fim_prefix|> #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(); Key physical_keycode = godot_code_from_android_code(p_physical_keycode); Key keycode; if (unicode == '\b') { // 0x08 keycode = Key::BACKSPACE; } else if (unicode == '\t') { // 0x09 keycode = Key::TAB; } else if (unicode == '\n') { // 0x0A keycode = Key::ENTER; } else if (unicode == 0x1B) { keycode = Key::ESCAPE; } else if (unicode == 0x1F) {<|fim_suffix|> } else { keycode = fix_keycode(unicode, physical_keycode); } switch (physical_keycode) { case Key::SHIFT: { shift_mem = p_pressed; } break; case Key::ALT: { alt_mem = p_pressed; } break; case Key::CTRL: { control_mem = p_pressed; } break; case Key::META: { meta_mem = p_pressed; } break; default: break; } ev->set_keycode(keycode); ev->set_physical_keycode(physical_keycode); ev->set_key_label(fix_key_label(p_key_label, keycode)); ev->set_unicode(fix_unicode(unicode)); ev->set_location(godot_location_from_android_code(p_physical_keycode)); ev->set_pressed(p_pressed); ev->set_echo(p_echo); _set_key_modifier_state(ev, keycode); if (p_physical_keycode == AKEYCODE_BACK && p_pressed) { if (DisplayServerAndroid *dsa = Object::cast_to<DisplayServerAndroid>(DisplayServer::get_singleton())) { dsa->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST, true); } } Input::get_singleton()->parse_input_event(ev); } void AndroidInputHandler::_cancel_all_touch() { _parse_all_touch(false, true); touch.clear(); } void AndroidInputHandler::_parse_all_touch(bool p_pressed, bool p_canceled, bool p_double_tap) { if (touch.size()) { //end all if exist for (int i = 0; i < touch.size(); i++) { Ref<InputEventScreenTouch> 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());<|fim_middle|> keycode = Key::KEY_DELETE;
#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(); Key physical_keycode = godot_code_from_android_code(p_physical_keycode); Key keycode; if (unicode == '\b') { // 0x08 keycode = Key::BACKSPACE; } else if (unicode == '\t') { // 0x09 keycode = Key::TAB; } else if (unicode == '\n') { // 0x0A keycode = Key::ENTER; } else if (unicode == 0x1B) { keycode = Key::ESCAPE; } else if (unicode == 0x1F) {
keycode = Key::KEY_DELETE;
} else { keycode = fix_keycode(unicode, physical_keycode); } switch (physical_keycode) { case Key::SHIFT: { shift_mem = p_pressed; } break; case Key::ALT: { alt_mem = p_pressed; } break; case Key::CTRL: { control_mem = p_pressed; } break; case Key::META: { meta_mem = p_pressed; } break; default: break; } ev->set_keycode(keycode); ev->set_physical_keycode(physical_keycode); ev->set_key_label(fix_key_label(p_key_label, keycode)); ev->set_unicode(fix_unicode(unicode)); ev->set_location(godot_location_from_android_code(p_physical_keycode)); ev->set_pressed(p_pressed); ev->set_echo(p_echo); _set_key_modifier_state(ev, keycode); if (p_physical_keycode == AKEYCODE_BACK && p_pressed) { if (DisplayServerAndroid *dsa = Object::cast_to<DisplayServerAndroid>(DisplayServer::get_singleton())) { dsa->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST, true); } } Input::get_singleton()->parse_input_event(ev); } void AndroidInputHandler::_cancel_all_touch() { _parse_all_touch(false, true); touch.clear(); } void AndroidInputHandler::_parse_all_touch(bool p_pressed, bool p_canceled, bool p_double_tap) { if (touch.size()) { //end all if exist for (int i = 0; i < touch.size(); i++) { Ref<InputEventScreenTouch> 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());
random
<|fim_prefix|> for (int i = 0; i < track_count; ++i) { if (animation->track_get_type(i) != Animation::TrackType::TYPE_BEZIER || hidden_tracks.has(i) || locked_tracks.has(i)) { continue; } float track_h = animation->bezier_track_interpolate(i, time); float track_height = _bezier_h_to_pixel(track_h); if (std::abs(mb->get_position().y - track_height) < 10) { set_animation_and_track(animation, i, read_only); break; } } animation->set_length(animation_length); } box_selecting_attempt = false; box_selecting = false; queue_redraw(); } if (moving_selection_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) { if (!read_only) { if (moving_selection && (std::abs(moving_selection_offset.x) > CMP_EPSILON || std::abs(moving_selection_offset.y) > CMP_EPSILON)) { // Commit it. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Move Bezier Points")); List<AnimMoveRestore> to_restore; List<Animation::HandleMode> to_restore_handle_modes; // 1 - Remove the keys. for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->get().first, E->get().second); } // 2 - Remove overlapped keys. for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t newtime = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x; int idx = animation->track_find_key(E->get().first, newtime, Animation::FIND_MODE_APPROX); if (idx == -1) { continue; } if (selection.has(IntPair(E->get().first, idx))) { continue; // Already in selection, don't save. } undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newtime); AnimMoveRestore amr; amr.key = animation->track_get_key_value(E->get().first, idx);<|fim_suffix|> amr.time = newtime; to_restore.push_back(amr); to_restore_handle_modes.push_back(animation->bezier_track_get_key_handle_mode(E->get().first, idx)); } // 3 - Move the keys (re-insert them). for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t newpos = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x; Array key = animation->track_get_key_value(E->get().first, E->get().second); real_t h = key[0]; h += moving_selection_offset.y; key[0] = h; Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second); Animation::HandleSetMode handle_set_mode = Animation::HANDLE_SET_MODE_NONE; if (moving_inserted_key) { handle_mode = (Animation::HandleMode)editor->bezier_key_mode->get_selected_id(); handle_set_mode = Animation::HANDLE_SET_MODE_AUTO; } 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]), handle_mode, handle_set_mode); } // 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) + moving_selection_offset.x; 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],<|fim_middle|> amr.track = E->get().first;
for (int i = 0; i < track_count; ++i) { if (animation->track_get_type(i) != Animation::TrackType::TYPE_BEZIER || hidden_tracks.has(i) || locked_tracks.has(i)) { continue; } float track_h = animation->bezier_track_interpolate(i, time); float track_height = _bezier_h_to_pixel(track_h); if (std::abs(mb->get_position().y - track_height) < 10) { set_animation_and_track(animation, i, read_only); break; } } animation->set_length(animation_length); } box_selecting_attempt = false; box_selecting = false; queue_redraw(); } if (moving_selection_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) { if (!read_only) { if (moving_selection && (std::abs(moving_selection_offset.x) > CMP_EPSILON || std::abs(moving_selection_offset.y) > CMP_EPSILON)) { // Commit it. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Move Bezier Points")); List<AnimMoveRestore> to_restore; List<Animation::HandleMode> to_restore_handle_modes; // 1 - Remove the keys. for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->get().first, E->get().second); } // 2 - Remove overlapped keys. for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t newtime = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x; int idx = animation->track_find_key(E->get().first, newtime, Animation::FIND_MODE_APPROX); if (idx == -1) { continue; } if (selection.has(IntPair(E->get().first, idx))) { continue; // Already in selection, don't save. } undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newtime); AnimMoveRestore amr; amr.key = animation->track_get_key_value(E->get().first, idx);
amr.track = E->get().first;
amr.time = newtime; to_restore.push_back(amr); to_restore_handle_modes.push_back(animation->bezier_track_get_key_handle_mode(E->get().first, idx)); } // 3 - Move the keys (re-insert them). for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t newpos = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x; Array key = animation->track_get_key_value(E->get().first, E->get().second); real_t h = key[0]; h += moving_selection_offset.y; key[0] = h; Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second); Animation::HandleSetMode handle_set_mode = Animation::HANDLE_SET_MODE_NONE; if (moving_inserted_key) { handle_mode = (Animation::HandleMode)editor->bezier_key_mode->get_selected_id(); handle_set_mode = Animation::HANDLE_SET_MODE_AUTO; } 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]), handle_mode, handle_set_mode); } // 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) + moving_selection_offset.x; 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],
random
<|fim_prefix|> = [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"); } curlcode = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } std::string cookiefile = curl_cookiefile; if (!cookiefile.empty()) { curlcode = curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiefile.c_str()); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_USERAGENT, "Tesseract OCR"); if (curlcode != CURLE_OK) <|fim_suffix|> curlcode = curl_easy_perform(curl); if (curlcode != CURLE_OK) { return error("curl_easy_perform"); } curl_easy_cleanup(curl); data = reinterpret_cast<const l_uint8 *>(buf.data()); } #else fprintf(stderr, "Error, this tesseract has no URL support\n"); return false; #endif } else { // Check whether the input file can be read. if (FILE *file = fopen(filename, "rb")) { 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) ? Pro<|fim_middle|>{ return error("curl_easy_setopt"); }
= [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"); } curlcode = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } std::string cookiefile = curl_cookiefile; if (!cookiefile.empty()) { curlcode = curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiefile.c_str()); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_USERAGENT, "Tesseract OCR"); if (curlcode != CURLE_OK)
{ return error("curl_easy_setopt"); }
curlcode = curl_easy_perform(curl); if (curlcode != CURLE_OK) { return error("curl_easy_perform"); } curl_easy_cleanup(curl); data = reinterpret_cast<const l_uint8 *>(buf.data()); } #else fprintf(stderr, "Error, this tesseract has no URL support\n"); return false; #endif } else { // Check whether the input file can be read. if (FILE *file = fopen(filename, "rb")) { 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) ? Pro
ast_based
<|fim_prefix|> */ /* 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); } <|fim_suffix|> } 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(); Key physical_keycode = godot_code_from_android_code(p_physical_keycode); Key keycode; if (unicode == '\b') { // 0x08 keycode = Key::BACKSPACE; } else if (unicode == '\t') { // 0x09 keycode = Key::TAB; } else if (unicode == '\n') { // 0x0A keycode = Key::ENTER; } else if (unicode == 0x1B) { keycode = Key::ESCAPE; } else if (unicode == 0x1F) { keycode = Key::KEY_DELETE; } else { keycode = fix_keycode(unicode, physical_keycode); } switch (physical_keycode) { case Key::SHIFT: { shift_mem = p_pressed; } break; case Key::ALT: { alt_mem = p_pressed; } break; case Key::CTRL: { control_mem = p_pressed; } break; case Key::META: { meta_mem = p_pressed; } break; default: break; } ev->set_keycode(keycode); ev->set_physical_keycode(physical_keycode); ev->set_key_label(fix_key_label(p_key_label, keycode)); ev->set_unicode(fix_unicode(unicode)); ev->set_location(godot_location_from_android_code(p_physical_keycode)); ev->set_pressed(p_pressed); ev->set_echo(p_echo); _set_key_modifier_state(ev, keycode); if (p_physical_keycode == AKEYCODE_BACK && p_pressed) { if (DisplayServerAndroid *dsa = Object::cast_to<DisplayServerAndroid>(DisplayServer::get_singleton())) { dsa->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST, true)<|fim_middle|>if (p_keycode != Key::META) { ev->set_meta_pressed(meta_mem); } if (p_keycode != Key::CTRL) { ev->set_ctrl_pressed(control_mem); }
*/ /* 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(); Key physical_keycode = godot_code_from_android_code(p_physical_keycode); Key keycode; if (unicode == '\b') { // 0x08 keycode = Key::BACKSPACE; } else if (unicode == '\t') { // 0x09 keycode = Key::TAB; } else if (unicode == '\n') { // 0x0A keycode = Key::ENTER; } else if (unicode == 0x1B) { keycode = Key::ESCAPE; } else if (unicode == 0x1F) { keycode = Key::KEY_DELETE; } else { keycode = fix_keycode(unicode, physical_keycode); } switch (physical_keycode) { case Key::SHIFT: { shift_mem = p_pressed; } break; case Key::ALT: { alt_mem = p_pressed; } break; case Key::CTRL: { control_mem = p_pressed; } break; case Key::META: { meta_mem = p_pressed; } break; default: break; } ev->set_keycode(keycode); ev->set_physical_keycode(physical_keycode); ev->set_key_label(fix_key_label(p_key_label, keycode)); ev->set_unicode(fix_unicode(unicode)); ev->set_location(godot_location_from_android_code(p_physical_keycode)); ev->set_pressed(p_pressed); ev->set_echo(p_echo); _set_key_modifier_state(ev, keycode); if (p_physical_keycode == AKEYCODE_BACK && p_pressed) { if (DisplayServerAndroid *dsa = Object::cast_to<DisplayServerAndroid>(DisplayServer::get_singleton())) { dsa->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST, true)
ast_based
<|fim_prefix|> 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])); }<|fim_suffix|> // 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->second; } return nullptr; } static void llama_adapter_lora_init_impl(llama_model & model, const char * path_lora, llama_adapter_lora & adapter) { LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora); ggml_context * ctx_init; gguf_init_params meta_gguf_params = { /* .no_alloc = */ true, /* .ctx = */ &ctx_init, }; gguf_context_ptr ctx_gguf { gguf_init_from_file(path_lora, meta_gguf_params) }; if (!ctx_gguf) { throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora)); } ggml_context_ptr ctx { ctx_init }; // check metadata { const gguf_context * gguf_ctx = ctx_gguf.get(); LLAMA_LOG_INFO("%s: Dumping metadata keys/values.\n", __func__); // get metadata as string for (int i = 0; i < gguf_get_n_kv(gguf_ctx); i++) { gguf_type type = gguf_get_kv_type(gguf_ctx, i); const std::string type_name = type == GGUF_TYPE_ARRAY ? format("%s[%s,%zu]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(gguf_ctx, i)), gguf_get_arr_n(gguf_ctx, i)) : gguf_type_name(type); const char * name = gguf_get_key(gguf_ctx, i); const std::string value = gguf_kv_to_str(gguf_ctx, i); if (type != GGUF_TYPE_ARRAY) { adapter.gguf_kv.emplace(name, value); } const size_t MAX_VALUE_LEN = 40; std::string print_value = value.size() > MAX_VALUE_LEN ? format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str()) : value; replace_all(print_value, "\n", "\\n"); <|fim_middle|> } return true; }
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->second; } return nullptr; } static void llama_adapter_lora_init_impl(llama_model & model, const char * path_lora, llama_adapter_lora & adapter) { LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora); ggml_context * ctx_init; gguf_init_params meta_gguf_params = { /* .no_alloc = */ true, /* .ctx = */ &ctx_init, }; gguf_context_ptr ctx_gguf { gguf_init_from_file(path_lora, meta_gguf_params) }; if (!ctx_gguf) { throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora)); } ggml_context_ptr ctx { ctx_init }; // check metadata { const gguf_context * gguf_ctx = ctx_gguf.get(); LLAMA_LOG_INFO("%s: Dumping metadata keys/values.\n", __func__); // get metadata as string for (int i = 0; i < gguf_get_n_kv(gguf_ctx); i++) { gguf_type type = gguf_get_kv_type(gguf_ctx, i); const std::string type_name = type == GGUF_TYPE_ARRAY ? format("%s[%s,%zu]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(gguf_ctx, i)), gguf_get_arr_n(gguf_ctx, i)) : gguf_type_name(type); const char * name = gguf_get_key(gguf_ctx, i); const std::string value = gguf_kv_to_str(gguf_ctx, i); if (type != GGUF_TYPE_ARRAY) { adapter.gguf_kv.emplace(name, value); } const size_t MAX_VALUE_LEN = 40; std::string print_value = value.size() > MAX_VALUE_LEN ? format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str()) : value; replace_all(print_value, "\n", "\\n");
random
<|fim_prefix|> (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) { { int gridSize = 10; int xGridStep = mCalibData->imageSize.width / gridSize; int yGridStep = mCalibData->imageSize.height / gridSize; std::vector<int> pointsInCell(gridSize*gridSize); std::fill(pointsInCell.begin(), pointsInCell.end(), 0); for(size_t k = 0; k < mCalibData->imagePoints.size(); k++) if(k != excludedIndex) for(std::vector<cv::Point2f>::iterator pointIt = mCalibData->imagePoints[k].begin(); pointIt != mCalibData->imagePoints[k].end(); ++pointIt) { int i = (int)((*pointIt).x / xGridStep); int j = (int)((*pointIt).y / yGridStep); pointsInCell[i*gridSize + j]++; } for(size_t k = 0; k < mCalibData->allCharucoCorners.size(); k++) if(k != excludedIndex) for(int l = 0; l < mCalibData->allCharucoCorners[k].size[0]; l++) { int i = (int)(mCalibData->allCharucoCorners[k].at<float>(l, 0) / xGridStep); int j = (int)(mCalibData->allCharucoCorners[k].at<float>(l, 1) / yGridStep); pointsInCell[i*gridSize + j]++; } cv::Mat mean, stdDev; cv::meanStdDev(pointsInCell, mean, stdDev); <|fim_suffix|>} calib::calibDataController::calibDataController(cv::Ptr<calib::calibrationData> data, int maxFrames, double convParameter) : mCalibData(data), mParamsFileName("CamParams.xml") { mMaxFramesNum = maxFrames; mAlpha = convParameter; } calib::calibDataController::calibDataController() { } void calib::calibDataController::filterFrames() { size_t numberOfFrames = std::max(mCalibData->allCharucoIds.size(), mCalibData->imagePoints.size()); CV_Assert(numberOfFrames == mCalibData->perViewErrors.total()); if(numberOfFrames >= mMaxFramesNum) { double worstValue = -HUGE_VAL, maxQuality = estimateGridSubsetQuality(numberOfFrames); size_t worstElemIndex = 0; for(size_t i = 0; i < numberOfFrames; i++) { double gridQDelta = estimateGridSubsetQuality(i) - maxQuality; double currentValue = mCalibData->perViewErrors.at<double>((int)i)*mAlpha + gridQDelta*(1. - mAlpha); if(currentValue > worstValue) { worstValue = currentValue; worstElemIndex = i; } } showOverlayMessage(cv::format("Frame %zu is worst", worstElemIndex + 1)); if(mCalibData->allFrames.size()) mCalibData->allFrames.erase(mCalibData->allFrames.begin() + worstElemIndex); if(mCalibData->imagePoints.size()) { mCalibData->imagePoints.erase(mCalibData->imagePoints.begin() + worstElemIndex); mCalibData->objectPoints.erase(mCalibData->objectPoints.begin() + worstElemIndex); if (mCalibData->allCharucoCorners.size()) { mCalibData->allCharucoCorners.erase(mCalibData->allCharucoCorners.begin() + worstElemIndex); mCalibData->allCharucoIds.erase(mCalibData->allCharucoIds.begin() + worstElemIndex); } } cv::Mat newErrorsVec = cv::Mat((int)numberOfFrames - 1, 1, CV_64F); std::copy(mCalibData->perViewErrors.ptr<double>(0),<|fim_middle|> return mean.at<double>(0) / (stdDev.at<double>(0) + 1e-7); }
(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) { { int gridSize = 10; int xGridStep = mCalibData->imageSize.width / gridSize; int yGridStep = mCalibData->imageSize.height / gridSize; std::vector<int> pointsInCell(gridSize*gridSize); std::fill(pointsInCell.begin(), pointsInCell.end(), 0); for(size_t k = 0; k < mCalibData->imagePoints.size(); k++) if(k != excludedIndex) for(std::vector<cv::Point2f>::iterator pointIt = mCalibData->imagePoints[k].begin(); pointIt != mCalibData->imagePoints[k].end(); ++pointIt) { int i = (int)((*pointIt).x / xGridStep); int j = (int)((*pointIt).y / yGridStep); pointsInCell[i*gridSize + j]++; } for(size_t k = 0; k < mCalibData->allCharucoCorners.size(); k++) if(k != excludedIndex) for(int l = 0; l < mCalibData->allCharucoCorners[k].size[0]; l++) { int i = (int)(mCalibData->allCharucoCorners[k].at<float>(l, 0) / xGridStep); int j = (int)(mCalibData->allCharucoCorners[k].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::calibDataController::calibDataController(cv::Ptr<calib::calibrationData> data, int maxFrames, double convParameter) : mCalibData(data), mParamsFileName("CamParams.xml") { mMaxFramesNum = maxFrames; mAlpha = convParameter; } calib::calibDataController::calibDataController() { } void calib::calibDataController::filterFrames() { size_t numberOfFrames = std::max(mCalibData->allCharucoIds.size(), mCalibData->imagePoints.size()); CV_Assert(numberOfFrames == mCalibData->perViewErrors.total()); if(numberOfFrames >= mMaxFramesNum) { double worstValue = -HUGE_VAL, maxQuality = estimateGridSubsetQuality(numberOfFrames); size_t worstElemIndex = 0; for(size_t i = 0; i < numberOfFrames; i++) { double gridQDelta = estimateGridSubsetQuality(i) - maxQuality; double currentValue = mCalibData->perViewErrors.at<double>((int)i)*mAlpha + gridQDelta*(1. - mAlpha); if(currentValue > worstValue) { worstValue = currentValue; worstElemIndex = i; } } showOverlayMessage(cv::format("Frame %zu is worst", worstElemIndex + 1)); if(mCalibData->allFrames.size()) mCalibData->allFrames.erase(mCalibData->allFrames.begin() + worstElemIndex); if(mCalibData->imagePoints.size()) { mCalibData->imagePoints.erase(mCalibData->imagePoints.begin() + worstElemIndex); mCalibData->objectPoints.erase(mCalibData->objectPoints.begin() + worstElemIndex); if (mCalibData->allCharucoCorners.size()) { mCalibData->allCharucoCorners.erase(mCalibData->allCharucoCorners.begin() + worstElemIndex); mCalibData->allCharucoIds.erase(mCalibData->allCharucoIds.begin() + worstElemIndex); } } cv::Mat newErrorsVec = cv::Mat((int)numberOfFrames - 1, 1, CV_64F); std::copy(mCalibData->perViewErrors.ptr<double>(0),
random
<|fim_prefix|>/* Copyright 2021 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_CORE_ACTIVITY_WATCHER_ACTIVITY_H_ #define TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_ #include <atomic> #include <functional> #include <memory> #include <utility> #include "absl/container/flat_hash_map.h" #include "xla/tsl/platform/macros.h" #include "xla/tsl/platform/types.h" namespace tsl { class CoordinationServiceAgent; } namespace tensorflow { namespace activity_watcher { using ActivityId = tsl::uint64; constexpr ActivityId kActivityNotRecorded = 0; constexpr int kWatcherDisabled = 0; enum ActivityCategory { kCollective = 0, kRemoteFunction = 1, kMisc = 2, kDatasetOp = 3, kTpuOp = 4, kRendezvous = 5, }; static tsl::string ToString(ActivityCategory category) { switch (category) { case ActivityCategory::kCollective: return "Collective"; case ActivityCategory::kRemoteFunction: return "Remote Function"; case ActivityCategory::kMisc:<|fim_suffix|> } } // An activity to be recorded. struct Activity { using Attributes = absl::flat_hash_map<tsl::string, tsl::string>; // A human readable title of the activity. tsl::string title; // The category of the activity. ActivityCategory category = ActivityCategory::kMisc; // Key/value pairs that are attached to the activity. Attributes attributes; Activity() = default; Activity(tsl::string title, ActivityCategory category) : title(std::move(title)), category(category) {} Activity(tsl::string title, ActivityCategory category, Attributes attributes) : title(std::move(title)), category(category), attributes(std::move(attributes)) {} }; // Enable activity wathcer to send own workers activities to coordination // service and also fetch all workers' activities. void MaybeEnableMultiWorkersWatching(tsl::CoordinationServiceAgent* agent); namespace tfw_internal { #if defined(TF_ENABLE_ACTIVITY_WATCHER) // Records an activity start without checking whether the watcher is enabled. ActivityId RecordActivityStart(std::unique_ptr<Activity> activity); // Records an activity end without checking whether the activity_id is valid. void RecordActivityEnd(ActivityId activity_id); TF_EXPORT extern std::atomic<int> g_watcher_level; // Returns whether the activitity watcher is enabled. inline bool WatcherEnabled(int level = 1) { return g_watcher_level.load(std::memory_order_acquire) >= level; } #endif // NOTE: Borrowed from boost C++ libraries because std::is_invocable_r is not // available in Android NDK. template <typename R, typename F, typename... Args> struct is_invocable_r : std::is_constructible< std::function<R(Args...)>, std::reference_wrapper<typename std::remove_reference<F>::type>> {}; } // namespace tfw_internal template <typename F> constexpr bool is_activity_generator = tfw_internal::is_invocable_r<std::unique_ptr<Activity>, F>::value; <|fim_middle|> return "Miscellaneous"; case ActivityCategory::kDatasetOp: return "Dataset Op"; case ActivityCategory::kTpuOp: return "TPU Op"; case ActivityCategory::kRendezvous: return "Rendezvous";
/* Copyright 2021 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_CORE_ACTIVITY_WATCHER_ACTIVITY_H_ #define TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_ #include <atomic> #include <functional> #include <memory> #include <utility> #include "absl/container/flat_hash_map.h" #include "xla/tsl/platform/macros.h" #include "xla/tsl/platform/types.h" namespace tsl { class CoordinationServiceAgent; } namespace tensorflow { namespace activity_watcher { using ActivityId = tsl::uint64; constexpr ActivityId kActivityNotRecorded = 0; constexpr int kWatcherDisabled = 0; enum ActivityCategory { kCollective = 0, kRemoteFunction = 1, kMisc = 2, kDatasetOp = 3, kTpuOp = 4, kRendezvous = 5, }; static tsl::string ToString(ActivityCategory category) { switch (category) { case ActivityCategory::kCollective: return "Collective"; case ActivityCategory::kRemoteFunction: return "Remote Function"; case ActivityCategory::kMisc:
return "Miscellaneous"; case ActivityCategory::kDatasetOp: return "Dataset Op"; case ActivityCategory::kTpuOp: return "TPU Op"; case ActivityCategory::kRendezvous: return "Rendezvous";
} } // An activity to be recorded. struct Activity { using Attributes = absl::flat_hash_map<tsl::string, tsl::string>; // A human readable title of the activity. tsl::string title; // The category of the activity. ActivityCategory category = ActivityCategory::kMisc; // Key/value pairs that are attached to the activity. Attributes attributes; Activity() = default; Activity(tsl::string title, ActivityCategory category) : title(std::move(title)), category(category) {} Activity(tsl::string title, ActivityCategory category, Attributes attributes) : title(std::move(title)), category(category), attributes(std::move(attributes)) {} }; // Enable activity wathcer to send own workers activities to coordination // service and also fetch all workers' activities. void MaybeEnableMultiWorkersWatching(tsl::CoordinationServiceAgent* agent); namespace tfw_internal { #if defined(TF_ENABLE_ACTIVITY_WATCHER) // Records an activity start without checking whether the watcher is enabled. ActivityId RecordActivityStart(std::unique_ptr<Activity> activity); // Records an activity end without checking whether the activity_id is valid. void RecordActivityEnd(ActivityId activity_id); TF_EXPORT extern std::atomic<int> g_watcher_level; // Returns whether the activitity watcher is enabled. inline bool WatcherEnabled(int level = 1) { return g_watcher_level.load(std::memory_order_acquire) >= level; } #endif // NOTE: Borrowed from boost C++ libraries because std::is_invocable_r is not // available in Android NDK. template <typename R, typename F, typename... Args> struct is_invocable_r : std::is_constructible< std::function<R(Args...)>, std::reference_wrapper<typename std::remove_reference<F>::type>> {}; } // namespace tfw_internal template <typename F> constexpr bool is_activity_generator = tfw_internal::is_invocable_r<std::unique_ptr<Activity>, F>::value;
random
<|fim_prefix|> 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()) { host_str = &host_; } grpc_slice method_slice = SliceFromArray(method.name(), strlen(method.name())); grpc_slice host_slice; if (host_str != nullptr) { host_slice = grpc::SliceFromCopiedString(*host_str); } c_call = grpc_channel_create_call( c_channel_, context->propagate_from_call_, context->propagation_options_.c_bitmask(), cq->cq(), method_slice, host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(), nullptr); grpc_slice_unref(method_slice); if (host_str != nullptr) { grpc_slice_unref(host_slice); } } grpc_census_call_set_context(c_call, context->census_context()); // ClientRpcInfo should be set before call because set_call also checks // whether the call has been cancelled, and if the call was cancelled, we // should notify the interceptors too. auto* info = context->set_client_rpc_info( method.name(), method.suffix_for_stats(), method.method_type(), this, interceptor_creators_, interceptor_pos); context->set_call(c_call, shared_from_this()); return grpc::internal::Call(c_call, this, cq, info); } grpc::internal::Call Channel::CreateCall( const grpc::internal::RpcMethod& method, grpc::ClientContext* context, CompletionQueue* cq) { return CreateCallInternal(method, context, cq, 0); } void Channel::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,<|fim_suffix|> grpc_connectivity_state Channel::GetState(bool try_to_connect) { return grpc_channel_check_connectivity_state(c_channel_, try_to_connect); } namespace { class TagSaver final : public grpc::internal::CompletionQueueTag { public: explicit TagSaver(void* tag) : tag_(tag) {} ~TagSaver() override {} bool FinalizeResult(void** tag, bool* /*status*/) override { *tag = tag_; delete this; return true; } private: void* tag_; }; } // namespace void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline, grpc::CompletionQueue* cq, void* tag) { TagSaver* tag_saver = new TagSaver(tag); grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline, cq->cq(), tag_saver); } bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline) { grpc::CompletionQueue cq; bool ok = false; void* tag = nullptr; NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr); cq.Next(&tag, &ok); GRPC_CHECK_EQ(tag, nullptr); return ok; } namespace { class ShutdownCallback : public grpc_completion_queue_functor { public: ShutdownCallback() { functor_run = &ShutdownCallback::Run; // Set inlineable to true since this callback is trivial and thus does not // need to be run from the EventEngine (potentially triggering a thread // hop). This should only be used by internal callbacks like this and not by // user application code. inlineable = true; } // TakeCQ takes ownership of the cq into the shutdown callback // so that the shutdown callback will be responsible for destroying it void TakeCQ(grpc::CompletionQueue* cq) { cq_ = cq; } // The Run function will get invoked by the completion queue library // when the shutdown is actually complete<|fim_middle|> grpc::internal::Call* call) { ops->FillOps( call); // Make a copy of call. It's fine since Call just has pointers } void* Channel::RegisterMethod(const char* method) { return grpc_channel_register_call( c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr); }
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()) { host_str = &host_; } grpc_slice method_slice = SliceFromArray(method.name(), strlen(method.name())); grpc_slice host_slice; if (host_str != nullptr) { host_slice = grpc::SliceFromCopiedString(*host_str); } c_call = grpc_channel_create_call( c_channel_, context->propagate_from_call_, context->propagation_options_.c_bitmask(), cq->cq(), method_slice, host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(), nullptr); grpc_slice_unref(method_slice); if (host_str != nullptr) { grpc_slice_unref(host_slice); } } grpc_census_call_set_context(c_call, context->census_context()); // ClientRpcInfo should be set before call because set_call also checks // whether the call has been cancelled, and if the call was cancelled, we // should notify the interceptors too. auto* info = context->set_client_rpc_info( method.name(), method.suffix_for_stats(), method.method_type(), this, interceptor_creators_, interceptor_pos); context->set_call(c_call, shared_from_this()); return grpc::internal::Call(c_call, this, cq, info); } grpc::internal::Call Channel::CreateCall( const grpc::internal::RpcMethod& method, grpc::ClientContext* context, CompletionQueue* cq) { return CreateCallInternal(method, context, cq, 0); } void Channel::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
grpc::internal::Call* call) { ops->FillOps( call); // Make a copy of call. It's fine since Call just has pointers } void* Channel::RegisterMethod(const char* method) { return grpc_channel_register_call( c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr); }
grpc_connectivity_state Channel::GetState(bool try_to_connect) { return grpc_channel_check_connectivity_state(c_channel_, try_to_connect); } namespace { class TagSaver final : public grpc::internal::CompletionQueueTag { public: explicit TagSaver(void* tag) : tag_(tag) {} ~TagSaver() override {} bool FinalizeResult(void** tag, bool* /*status*/) override { *tag = tag_; delete this; return true; } private: void* tag_; }; } // namespace void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline, grpc::CompletionQueue* cq, void* tag) { TagSaver* tag_saver = new TagSaver(tag); grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline, cq->cq(), tag_saver); } bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline) { grpc::CompletionQueue cq; bool ok = false; void* tag = nullptr; NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr); cq.Next(&tag, &ok); GRPC_CHECK_EQ(tag, nullptr); return ok; } namespace { class ShutdownCallback : public grpc_completion_queue_functor { public: ShutdownCallback() { functor_run = &ShutdownCallback::Run; // Set inlineable to true since this callback is trivial and thus does not // need to be run from the EventEngine (potentially triggering a thread // hop). This should only be used by internal callbacks like this and not by // user application code. inlineable = true; } // TakeCQ takes ownership of the cq into the shutdown callback // so that the shutdown callback will be responsible for destroying it void TakeCQ(grpc::CompletionQueue* cq) { cq_ = cq; } // The Run function will get invoked by the completion queue library // when the shutdown is actually complete
random
<|fim_prefix|> int selected_track = 0; Vector<Rect2> view_rects; Ref<Texture2D> bezier_icon; Ref<Texture2D> bezier_handle_icon; Ref<Texture2D> selected_icon; RBMap<int, Rect2> subtracks; enum { REMOVE_ICON, LOCK_ICON, SOLO_ICON, VISIBILITY_ICON }; RBMap<int, RBMap<int, Rect2>> subtrack_icons; HashSet<int> locked_tracks; HashSet<int> hidden_tracks; int solo_track = -1; bool is_filtered = false; float track_v_scroll = 0; float track_v_scroll_max = 0; float timeline_v_scroll = 0; float timeline_v_zoom = 1; PopupMenu *menu = nullptr; void _zoom_changed(); void _update_locked_tracks_after(int p_track); void _update_hidden_tracks_after(int p_track); virtual void gui_input(const Ref<InputEvent> &p_event) override; void _menu_selected(int p_index); void _play_position_draw(); bool _is_track_displayed(int p_track_index); bool _is_track_curves_displayed(int p_track_index); Vector2 insert_at_pos; typedef Pair<int, int> IntPair; bool moving_selection_attempt = false; bool moving_inserted_key = false; 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) <|fim_suffix|> 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<|fim_middle|>{ int32_t hash = 23; hash = hash * 31 * hash_one_uint64(p_value.first);
int selected_track = 0; Vector<Rect2> view_rects; Ref<Texture2D> bezier_icon; Ref<Texture2D> bezier_handle_icon; Ref<Texture2D> selected_icon; RBMap<int, Rect2> subtracks; enum { REMOVE_ICON, LOCK_ICON, SOLO_ICON, VISIBILITY_ICON }; RBMap<int, RBMap<int, Rect2>> subtrack_icons; HashSet<int> locked_tracks; HashSet<int> hidden_tracks; int solo_track = -1; bool is_filtered = false; float track_v_scroll = 0; float track_v_scroll_max = 0; float timeline_v_scroll = 0; float timeline_v_zoom = 1; PopupMenu *menu = nullptr; void _zoom_changed(); void _update_locked_tracks_after(int p_track); void _update_hidden_tracks_after(int p_track); virtual void gui_input(const Ref<InputEvent> &p_event) override; void _menu_selected(int p_index); void _play_position_draw(); bool _is_track_displayed(int p_track_index); bool _is_track_curves_displayed(int p_track_index); Vector2 insert_at_pos; typedef Pair<int, int> IntPair; bool moving_selection_attempt = false; bool moving_inserted_key = false; 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
ast_based
<|fim_prefix|>ling_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); } animation->bezier_track_calculate_handles(offset_n, offset, height, offset_nn, height_nn, handle_mode, Animation::HANDLE_SET_MODE_AUTO, &in_handle, nullptr); } } } out_handle += Vector2(offset, height); in_handle += Vector2(offset_n, height_n); Vector2 start(offset, height); Vector2 end(offset_n, height_n); int from_x = (offset - timeline->get_value()) * scale + limit; int point_start = from_x; int to_x = (offset_n - timeline->get_value()) * scale + limit; int point_end = to_x; if (from_x > right_limit) { // Not visible. continue; } if (to_x < limit) { // Not visible. continue; } from_x = MAX(from_x, limit); to_x = MIN(to_x, right_limit); Vector<Vector2> lines; Vector2 prev_pos; for (<|fim_suffix|> j <= to_x; j++) { float t = (j - limit) / scale + timeline->get_value(); float h; if (j == point_end) { h = end.y; // Make sure it always connects. } else if (j == point_start) { h = start.y; // Make sure it always connects. } else { // Custom interpolation, used because it needs to show paths affected by moving the selection or handles. int iterations = 10; float low = 0; float high = 1; // Narrow high and low as much as possible. for (int k = 0; k < iterations; k++) { float middle = (low + high) / 2.0; Vector2 interp = start.bezier_interpolate(out_handle, in_handle, end, middle); if (interp.x < t) { low = middle; } else { high = middle; } } // Interpolate the result. Vector2 low_pos = start.bezier_interpolate(out_handle, in_handle, end, low); Vector2 high_pos = start.bezier_interpolate(out_handle, in_handle, end, high); float c = (t - low_pos.x) / (high_pos.x - low_pos.x); h = low_pos.lerp(high_pos, c).y; } h = _bezier_h_to_pixel(h); Vector2 pos(j, h); if (j > from_x) { lines.push_back(prev_pos); lines.push_back(pos); } prev_pos = pos; } if (lines.size() >= 2) { draw_multiline(lines, p_color, Math::round(EDSCALE), true); } } } void AnimationBezierTrackEdit::_draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right) { Vector2 from = p_from; Vector2 to = p_to; if (from.x == to.x && from.y == to.y) { return; } if (to.x < from.x) { SWAP(to, from); } if (to.x < p_clip_left) { return; } if (from.x > p_clip_right) { return; } if (to.x > p_clip_right) { float c = (p_clip_right - from.x) / (to.x - from.x); to = from.lerp(to, c); } if (from.x < p_clip_left) { 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:<|fim_middle|>int j = from_x;
ling_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); } animation->bezier_track_calculate_handles(offset_n, offset, height, offset_nn, height_nn, handle_mode, Animation::HANDLE_SET_MODE_AUTO, &in_handle, nullptr); } } } out_handle += Vector2(offset, height); in_handle += Vector2(offset_n, height_n); Vector2 start(offset, height); Vector2 end(offset_n, height_n); int from_x = (offset - timeline->get_value()) * scale + limit; int point_start = from_x; int to_x = (offset_n - timeline->get_value()) * scale + limit; int point_end = to_x; if (from_x > right_limit) { // Not visible. continue; } if (to_x < limit) { // Not visible. continue; } from_x = MAX(from_x, limit); to_x = MIN(to_x, right_limit); Vector<Vector2> lines; Vector2 prev_pos; for (
int j = from_x;
j <= to_x; j++) { float t = (j - limit) / scale + timeline->get_value(); float h; if (j == point_end) { h = end.y; // Make sure it always connects. } else if (j == point_start) { h = start.y; // Make sure it always connects. } else { // Custom interpolation, used because it needs to show paths affected by moving the selection or handles. int iterations = 10; float low = 0; float high = 1; // Narrow high and low as much as possible. for (int k = 0; k < iterations; k++) { float middle = (low + high) / 2.0; Vector2 interp = start.bezier_interpolate(out_handle, in_handle, end, middle); if (interp.x < t) { low = middle; } else { high = middle; } } // Interpolate the result. Vector2 low_pos = start.bezier_interpolate(out_handle, in_handle, end, low); Vector2 high_pos = start.bezier_interpolate(out_handle, in_handle, end, high); float c = (t - low_pos.x) / (high_pos.x - low_pos.x); h = low_pos.lerp(high_pos, c).y; } h = _bezier_h_to_pixel(h); Vector2 pos(j, h); if (j > from_x) { lines.push_back(prev_pos); lines.push_back(pos); } prev_pos = pos; } if (lines.size() >= 2) { draw_multiline(lines, p_color, Math::round(EDSCALE), true); } } } void AnimationBezierTrackEdit::_draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right) { Vector2 from = p_from; Vector2 to = p_to; if (from.x == to.x && from.y == to.y) { return; } if (to.x < from.x) { SWAP(to, from); } if (to.x < p_clip_left) { return; } if (from.x > p_clip_right) { return; } if (to.x > p_clip_right) { float c = (p_clip_right - from.x) / (to.x - from.x); to = from.lerp(to, c); } if (from.x < p_clip_left) { 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:
ast_based
<|fim_prefix|> } 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();<|fim_suffix|> 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) {<|fim_middle|> ERR_FAIL_COND(ae.is_null());
} 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); 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) {
random
<|fim_prefix|>/**************************************************************************/ /* engine.h */ /**************************************************************************/ /* 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. */ /* */<|fim_suffix|>/* 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; <|fim_middle|>/* 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, */
/**************************************************************************/ /* engine.h */ /**************************************************************************/ /* 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. */ /**************************************************************************/ #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;
random
<|fim_prefix|> handle_mode, handle_set_mode); } // 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) + moving_selection_offset.x; 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()) <|fim_suffix|> real_t newpos = oldpos + moving_selection_offset.x; 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(); } else if (select_single_attempt != IntPair(-1, -1)) { selection.clear(); set_animation_and_track(animation, select_single_attempt.first, read_only); _select_at_anim(animation, select_single_attempt.first, animation->track_get_key_time(select_single_attempt.first, select_single_attempt.second), true); } moving_selection = false; moving_selection_attempt = false; moving_inserted_key = false; moving_selection_mouse_begin = Point2(); queue_redraw(); } } if (scaling_selection && mb.is_valid() && !read_only && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) { if (std::abs(scaling_selection_scale.x - 1) > CMP_EPSILON || std::abs(scaling_selection_scale.y - 1) > CMP_EPSILON) { // Scale it. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Scale Bezier Points")); List<AnimMoveRestore> to_restore; List<Animation::HandleMode> to_restore_handle_modes; // 1 - Remove the keys. for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->get().first, E->get().second); } // 2 - Remove overlapped keys. for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t newtime = animation->track_get_key_time(E->get().first, E->get().second); newtime += -scaling_selection_offset.x + (newtime - scaling_selection_pivot.x<|fim_middle|>{ real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
handle_mode, handle_set_mode); } // 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) + moving_selection_offset.x; 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 = oldpos + moving_selection_offset.x; 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(); } else if (select_single_attempt != IntPair(-1, -1)) { selection.clear(); set_animation_and_track(animation, select_single_attempt.first, read_only); _select_at_anim(animation, select_single_attempt.first, animation->track_get_key_time(select_single_attempt.first, select_single_attempt.second), true); } moving_selection = false; moving_selection_attempt = false; moving_inserted_key = false; moving_selection_mouse_begin = Point2(); queue_redraw(); } } if (scaling_selection && mb.is_valid() && !read_only && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) { if (std::abs(scaling_selection_scale.x - 1) > CMP_EPSILON || std::abs(scaling_selection_scale.y - 1) > CMP_EPSILON) { // Scale it. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Scale Bezier Points")); List<AnimMoveRestore> to_restore; List<Animation::HandleMode> to_restore_handle_modes; // 1 - Remove the keys. for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->get().first, E->get().second); } // 2 - Remove overlapped keys. for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t newtime = animation->track_get_key_time(E->get().first, E->get().second); newtime += -scaling_selection_offset.x + (newtime - scaling_selection_pivot.x
ast_based
<|fim_prefix|> 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) <|fim_suffix|> } 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 = a<|fim_middle|>{ offset += moving_selection_offset.x; value += moving_selection_offset.y;
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_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 = a
ast_based
<|fim_prefix|> // 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()) <|fim_suffix|> auto it = adapter->gguf_kv.begin(); std::advance(it, i); return snprintf(buf, buf_size, "%s", it->first.c_str()); } int32_t llama_adapter_meta_val_str_by_index(const llama_adapter_lora * adapter, int32_t i, char * buf, size_t buf_size) { if (i < 0 || i >= (int)adapter->gguf_kv.size()) { if (buf_size > 0) { buf[0] = '\0'; } return -1; } auto it = adapter->gguf_kv.begin(); std::advance(it, i); return snprintf(buf, buf_size, "%s", it->second.c_str()); } void llama_adapter_lora_free(llama_adapter_lora * adapter) { delete adapter; } uint64_t llama_adapter_get_alora_n_invocation_tokens(const struct llama_adapter_lora * adapter) { if (!adapter) { return 0; } return adapter->alora_invocation_tokens.size(); } const llama_token * llama_adapter_get_alora_invocation_tokens(const llama_adapter_lora * adapter) { GGML_ASSERT(adapter); return adapter->alora_invocation_tokens.data(); } <|fim_middle|>{ if (buf_size > 0) { buf[0] = '\0'; } return -1; }
// 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'; } return -1; }
auto it = adapter->gguf_kv.begin(); std::advance(it, i); return snprintf(buf, buf_size, "%s", it->first.c_str()); } int32_t llama_adapter_meta_val_str_by_index(const llama_adapter_lora * adapter, int32_t i, char * buf, size_t buf_size) { if (i < 0 || i >= (int)adapter->gguf_kv.size()) { if (buf_size > 0) { buf[0] = '\0'; } return -1; } auto it = adapter->gguf_kv.begin(); std::advance(it, i); return snprintf(buf, buf_size, "%s", it->second.c_str()); } void llama_adapter_lora_free(llama_adapter_lora * adapter) { delete adapter; } uint64_t llama_adapter_get_alora_n_invocation_tokens(const struct llama_adapter_lora * adapter) { if (!adapter) { return 0; } return adapter->alora_invocation_tokens.size(); } const llama_token * llama_adapter_get_alora_invocation_tokens(const llama_adapter_lora * adapter) { GGML_ASSERT(adapter); return adapter->alora_invocation_tokens.data(); }
ast_based
<|fim_prefix|> } else if (p_delta.y < 0) { _wheel_button_click(event_buttons_mask, ev, MouseButton::WHEEL_DOWN, -p_delta.y); } if (p_delta.x > 0) { _wheel_button_click(event_buttons_mask, ev, MouseButton::WHEEL_RIGHT, p_delta.x); } else if (p_delta.x < 0) { _wheel_button_click(event_buttons_mask, ev, MouseButton::WHEEL_LEFT, -p_delta.x); } } break; } } void AndroidInputHandler::_wheel_button_click(BitField<MouseButtonMask> event_buttons_mask, const Ref<InputEventMouseButton> &ev, MouseButton wheel_button, float factor) { Ref<InputEventMouseButton> evd = ev->duplicate(); _set_key_modifier_state(evd, Key::NONE); evd->set_button_index(wheel_button); evd->set_button_mask(event_buttons_mask.get_different(mouse_button_to_mask(wheel_button))); evd->set_factor(factor); Input::get_singleton()->parse_input_event(evd); Ref<InputEventMouseButton> evdd = evd->duplicate(); evdd->set_pressed(false); evdd->set_button_mask(event_buttons_mask); Input::get_singleton()->parse_input_event(evdd); } void AndroidInputHandler::process_magnify(Point2 p_pos, float p_factor) { Ref<InputEventMagnifyGesture> magnify_event; magnify_event.instantiate(); _set_key_modifier_state(magnify_event, Key::NONE); magnify_event->set_position(p_pos); magnify_event->set_factor(p_factor); Input::get_singleton()->parse_input_event(magnify_event); } void AndroidInputHandler::process_pan(Point2 p_pos, Vector2 p_delta) { Ref<InputEventPanGesture> pan_event; pan_event.instantiate(); _set_key_modifier_state(pan_event, Key::NONE); pan_event->set_position(p_pos); pan_event->set_delta(p_delta); Input::get_singleton()->parse_input_event(pan_event); } MouseButton AndroidInputHandler::_button_index_from_mask(BitField<MouseButtonMask> button_mask) { switch (button_mask) { case MouseButtonMask::LEFT: return MouseButton::LEFT; case MouseButtonMask::RIGHT: return MouseButton::RIGHT; case MouseButtonMask::MIDDLE: return MouseButton::MIDDLE;<|fim_suffix|> return MouseButton::NONE; } } BitField<MouseButtonMask> AndroidInputHandler::_android_button_mask_to_godot_button_mask(int android_button_mask) { BitField<MouseButtonMask> godot_button_mask = MouseButtonMask::NONE; if (android_button_mask & AMOTION_EVENT_BUTTON_PRIMARY) { godot_button_mask.set_flag(MouseButtonMask::LEFT); } if (android_button_mask & AMOTION_EVENT_BUTTON_SECONDARY) { godot_button_mask.set_flag(MouseButtonMask::RIGHT); } if (android_button_mask & AMOTION_EVENT_BUTTON_TERTIARY) { godot_button_mask.set_flag(MouseButtonMask::MIDDLE); } if (android_button_mask & AMOTION_EVENT_BUTTON_BACK) { godot_button_mask.set_flag(MouseButtonMask::MB_XBUTTON1); } if (android_button_mask & AMOTION_EVENT_BUTTON_FORWARD) { godot_button_mask.set_flag(MouseButtonMask::MB_XBUTTON2); } return godot_button_mask; } <|fim_middle|> case MouseButtonMask::MB_XBUTTON1: return MouseButton::MB_XBUTTON1; case MouseButtonMask::MB_XBUTTON2: return MouseButton::MB_XBUTTON2; default:
} else if (p_delta.y < 0) { _wheel_button_click(event_buttons_mask, ev, MouseButton::WHEEL_DOWN, -p_delta.y); } if (p_delta.x > 0) { _wheel_button_click(event_buttons_mask, ev, MouseButton::WHEEL_RIGHT, p_delta.x); } else if (p_delta.x < 0) { _wheel_button_click(event_buttons_mask, ev, MouseButton::WHEEL_LEFT, -p_delta.x); } } break; } } void AndroidInputHandler::_wheel_button_click(BitField<MouseButtonMask> event_buttons_mask, const Ref<InputEventMouseButton> &ev, MouseButton wheel_button, float factor) { Ref<InputEventMouseButton> evd = ev->duplicate(); _set_key_modifier_state(evd, Key::NONE); evd->set_button_index(wheel_button); evd->set_button_mask(event_buttons_mask.get_different(mouse_button_to_mask(wheel_button))); evd->set_factor(factor); Input::get_singleton()->parse_input_event(evd); Ref<InputEventMouseButton> evdd = evd->duplicate(); evdd->set_pressed(false); evdd->set_button_mask(event_buttons_mask); Input::get_singleton()->parse_input_event(evdd); } void AndroidInputHandler::process_magnify(Point2 p_pos, float p_factor) { Ref<InputEventMagnifyGesture> magnify_event; magnify_event.instantiate(); _set_key_modifier_state(magnify_event, Key::NONE); magnify_event->set_position(p_pos); magnify_event->set_factor(p_factor); Input::get_singleton()->parse_input_event(magnify_event); } void AndroidInputHandler::process_pan(Point2 p_pos, Vector2 p_delta) { Ref<InputEventPanGesture> pan_event; pan_event.instantiate(); _set_key_modifier_state(pan_event, Key::NONE); pan_event->set_position(p_pos); pan_event->set_delta(p_delta); Input::get_singleton()->parse_input_event(pan_event); } MouseButton AndroidInputHandler::_button_index_from_mask(BitField<MouseButtonMask> button_mask) { switch (button_mask) { case MouseButtonMask::LEFT: return MouseButton::LEFT; case MouseButtonMask::RIGHT: return MouseButton::RIGHT; case MouseButtonMask::MIDDLE: return MouseButton::MIDDLE;
case MouseButtonMask::MB_XBUTTON1: return MouseButton::MB_XBUTTON1; case MouseButtonMask::MB_XBUTTON2: return MouseButton::MB_XBUTTON2; default:
return MouseButton::NONE; } } BitField<MouseButtonMask> AndroidInputHandler::_android_button_mask_to_godot_button_mask(int android_button_mask) { BitField<MouseButtonMask> godot_button_mask = MouseButtonMask::NONE; if (android_button_mask & AMOTION_EVENT_BUTTON_PRIMARY) { godot_button_mask.set_flag(MouseButtonMask::LEFT); } if (android_button_mask & AMOTION_EVENT_BUTTON_SECONDARY) { godot_button_mask.set_flag(MouseButtonMask::RIGHT); } if (android_button_mask & AMOTION_EVENT_BUTTON_TERTIARY) { godot_button_mask.set_flag(MouseButtonMask::MIDDLE); } if (android_button_mask & AMOTION_EVENT_BUTTON_BACK) { godot_button_mask.set_flag(MouseButtonMask::MB_XBUTTON1); } if (android_button_mask & AMOTION_EVENT_BUTTON_FORWARD) { godot_button_mask.set_flag(MouseButtonMask::MB_XBUTTON2); } return godot_button_mask; }
random
<|fim_prefix|> text_width = TS->shaped_text_get_size(p_shaped_text).x; text_height = MAX(text_height, TS->shaped_text_get_size(p_shaped_text).y); words = TS->shaped_text_get_word_breaks(p_shaped_text); run_count = TS->shaped_get_run_count(p_shaped_text); gl = TS->shaped_text_get_glyphs(p_shaped_text); gl_count = TS->shaped_text_get_glyph_count(p_shaped_text); full_range = TS->shaped_text_get_range(p_shaped_text); } accesskit_rect root_rect; root_rect.x0 = 0; root_rect.y0 = 0; root_rect.x1 = text_width; root_rect.y1 = MAX(p_min_height, text_height); accesskit_node_set_bounds(root_ae->node, root_rect); // 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); } <|fim_suffix|>; // 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, lang<|fim_middle|>accesskit_node_set_word_lengths(ae->node, word_lengths.size(), word_lengths.ptr())
text_width = TS->shaped_text_get_size(p_shaped_text).x; text_height = MAX(text_height, TS->shaped_text_get_size(p_shaped_text).y); words = TS->shaped_text_get_word_breaks(p_shaped_text); run_count = TS->shaped_get_run_count(p_shaped_text); gl = TS->shaped_text_get_glyphs(p_shaped_text); gl_count = TS->shaped_text_get_glyph_count(p_shaped_text); full_range = TS->shaped_text_get_range(p_shaped_text); } accesskit_rect root_rect; root_rect.x0 = 0; root_rect.y0 = 0; root_rect.x1 = text_width; root_rect.y1 = MAX(p_min_height, text_height); accesskit_node_set_bounds(root_ae->node, root_rect); // 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, lang
ast_based
<|fim_prefix|> */ /* 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/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") { <|fim_suffix|> 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://p<|fim_middle|>CHECK_FALSE(ProjectSettings::get_singleton()->has_setting("not_existing_setting")); Variant variant = ProjectSettings::get_singleton()->get_setting("not_existing_setting");
*/ /* 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/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://p
ast_based
<|fim_prefix|> 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();<|fim_suffix|> 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); <|fim_middle|>} _FORCE_INLINE_ void AccessibilityDriverAccessKit::_ensure_node(const RID &p_id, AccessibilityElement *p_ae) {
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); 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);
random
<|fim_prefix|>get_key_transition(track_idx, key_idx)); undo_redo->add_undo_method(this, "_select_at_anim", animation, track_idx, time, i == 0); i++; } i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) { undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, E->value().pos, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(); } } void AnimationBezierTrackEdit::paste_keys(real_t p_ofs, bool p_ofs_valid) { if (editor->is_key_clipboard_active() && animation.is_valid() && (selected_track >= 0 && selected_track < animation->get_track_count())) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Animation Paste Keys")); bool same_track = true; bool all_compatible = true; for (int i = 0; i < editor->key_clipboard.keys.size(); i++) { const AnimationTrackEditor::KeyClipboard::Key key = editor->key_clipboard.keys[i]; if (key.track != 0) { same_track = false; break; } if (!editor->_is_track_compatible(selected_track, key.value.get_type(), key.track_type)) { all_compatible = false; break; } } ERR_FAIL_COND_MSG(!all_compatible, "Paste failed: Not all animation keys were compatible with their target tracks"); if (!same_track) { WARN_PRINT("Pasted animation keys from multiple tracks into single Bezier track"); } List<Pair<int, float>> new_selection_values; for (int i = 0; i < editor->key_clipboard.keys.size(); i++) { const AnimationTrackEditor::KeyClipboard::Key key = editor->key_clipboard.keys[i]; float insert_pos = p_ofs_valid ? p_ofs : <|fim_suffix|>; if (p_ofs_valid) { if (editor->snap_keys->is_pressed() && editor->step->get_value() != 0) { insert_pos = editor->snap_time(insert_pos); } } float dst_time = key.time + insert_pos; int existing_idx = animation->track_find_key(selected_track, dst_time, Animation::FIND_MODE_APPROX); Variant value = key.value; if (key.track_type != Animation::TYPE_BEZIER) { value = animation->make_default_bezier_key(key.value); } undo_redo->add_do_method(animation.ptr(), "track_insert_key", selected_track, dst_time, value, key.transition); undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", selected_track, dst_time); Pair<int, float> p; p.first = selected_track; p.second = dst_time; new_selection_values.push_back(p); if (existing_idx != -1) { undo_redo->add_undo_method(animation.ptr(), "track_insert_key", selected_track, dst_time, animation->track_get_key_value(selected_track, existing_idx), animation->track_get_key_transition(selected_track, existing_idx)); } } undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); // Reselect pasted. int i = 0; for (const Pair<int, float> &E : new_selection_values) { undo_redo->add_do_method(this, "_select_at_anim", animation, E.first, E.second, i == 0); i++; } i = 0; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, animation->track_get_key_time(E->get().first, E->get().second), 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(<|fim_middle|>timeline->get_play_position()
get_key_transition(track_idx, key_idx)); undo_redo->add_undo_method(this, "_select_at_anim", animation, track_idx, time, i == 0); i++; } i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) { undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, E->value().pos, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(); } } void AnimationBezierTrackEdit::paste_keys(real_t p_ofs, bool p_ofs_valid) { if (editor->is_key_clipboard_active() && animation.is_valid() && (selected_track >= 0 && selected_track < animation->get_track_count())) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Animation Paste Keys")); bool same_track = true; bool all_compatible = true; for (int i = 0; i < editor->key_clipboard.keys.size(); i++) { const AnimationTrackEditor::KeyClipboard::Key key = editor->key_clipboard.keys[i]; if (key.track != 0) { same_track = false; break; } if (!editor->_is_track_compatible(selected_track, key.value.get_type(), key.track_type)) { all_compatible = false; break; } } ERR_FAIL_COND_MSG(!all_compatible, "Paste failed: Not all animation keys were compatible with their target tracks"); if (!same_track) { WARN_PRINT("Pasted animation keys from multiple tracks into single Bezier track"); } List<Pair<int, float>> new_selection_values; for (int i = 0; i < editor->key_clipboard.keys.size(); i++) { const AnimationTrackEditor::KeyClipboard::Key key = editor->key_clipboard.keys[i]; float insert_pos = p_ofs_valid ? p_ofs :
timeline->get_play_position()
; if (p_ofs_valid) { if (editor->snap_keys->is_pressed() && editor->step->get_value() != 0) { insert_pos = editor->snap_time(insert_pos); } } float dst_time = key.time + insert_pos; int existing_idx = animation->track_find_key(selected_track, dst_time, Animation::FIND_MODE_APPROX); Variant value = key.value; if (key.track_type != Animation::TYPE_BEZIER) { value = animation->make_default_bezier_key(key.value); } undo_redo->add_do_method(animation.ptr(), "track_insert_key", selected_track, dst_time, value, key.transition); undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", selected_track, dst_time); Pair<int, float> p; p.first = selected_track; p.second = dst_time; new_selection_values.push_back(p); if (existing_idx != -1) { undo_redo->add_undo_method(animation.ptr(), "track_insert_key", selected_track, dst_time, animation->track_get_key_value(selected_track, existing_idx), animation->track_get_key_transition(selected_track, existing_idx)); } } undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); // Reselect pasted. int i = 0; for (const Pair<int, float> &E : new_selection_values) { undo_redo->add_do_method(this, "_select_at_anim", animation, E.first, E.second, i == 0); i++; } i = 0; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, animation->track_get_key_time(E->get().first, E->get().second), 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(
ast_based
<|fim_prefix|>/* 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;<|fim_suffix|> 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]; <|fim_middle|> } // 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;
/* 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, 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];
random
<|fim_prefix|>: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]; <|fim_suffix|> 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_buttons_mask); ev->set_double_click(p_double_click); Input::get_singleton()->parse_input_event(ev); } void AndroidInputHandler::_release_mouse_event_info(bool p_source_mouse_relative) { _parse_mouse_event_info(Bit<|fim_middle|>touch.push_back(tp);
: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_buttons_mask); ev->set_double_click(p_double_click); Input::get_singleton()->parse_input_event(ev); } void AndroidInputHandler::_release_mouse_event_info(bool p_source_mouse_relative) { _parse_mouse_event_info(Bit
ast_based
<|fim_prefix|>ations; cv::Mat perViewErrors; std::vector<cv::Mat> rvecs; std::vector<cv::Mat> tvecs; double totalAvgErr; cv::Size imageSize; std::vector<cv::Mat> allFrames; std::vector<std::vector<cv::Point2f> > imagePoints; std::vector< std::vector<cv::Point3f> > objectPoints; std::vector<cv::Mat> allCharucoCorners; std::vector<cv::Mat> allCharucoIds; cv::Mat undistMap1, undistMap2; calibrationData() { imageSize = cv::Size(IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT); } }; struct cameraParameters { cv::Mat cameraMatrix; cv::Mat distCoeffs; cv::Mat stdDeviations; double avgError; cameraParameters(){} cameraParameters(cv::Mat& _cameraMatrix, cv::Mat& _distCoeffs, cv::Mat& _stdDeviations, double _avgError = 0) : cameraMatrix(_cameraMatrix), distCoeffs(_distCoeffs), stdDeviations(_stdDeviations), avgError(_avgError) {} }; struct captureParameters { InputType captureMethod; InputVideoSource source; TemplateType board; cv::Size inputBoardSize; cv::Size boardSizeInnerCorners; // board size in inner corners for chessboard cv::Size boardSizeUnits; // board size in squares, circles, etc. int charucoDictName; std::string charucoDictFile; int calibrationStep; float charucoSquareLength, charucoMarkerSize; float captureDelay; float squareSize; float templDst; std::string videoFileName; bool flipVertical; int camID; int camBackend; int fps; cv::Size cameraResolution; int maxFramesNum; int minFramesNum; bool saveFrames; float zoom; bool forceReopen; captureParameters() { calibrationStep = 1; captureDelay = 500.f; maxFramesNum = 30; <|fim_suffix|> fps = 30; cameraResolution = cv::Size(IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT); saveFrames = false; } }; struct internalParameters { double solverEps; int solverMaxIters; bool fastSolving; bool rationalModel; bool thinPrismModel; bool tiltedModel; double filterAlpha; internalParameters() { solverEps = 1e-7; solverMaxIters = 30; fastSolving = false; rationalModel = false; thinPrismModel = false; tiltedModel = false; filterAlpha = 0.1; } }; } #endif <|fim_middle|>minFramesNum = 10;
ations; cv::Mat perViewErrors; std::vector<cv::Mat> rvecs; std::vector<cv::Mat> tvecs; double totalAvgErr; cv::Size imageSize; std::vector<cv::Mat> allFrames; std::vector<std::vector<cv::Point2f> > imagePoints; std::vector< std::vector<cv::Point3f> > objectPoints; std::vector<cv::Mat> allCharucoCorners; std::vector<cv::Mat> allCharucoIds; cv::Mat undistMap1, undistMap2; calibrationData() { imageSize = cv::Size(IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT); } }; struct cameraParameters { cv::Mat cameraMatrix; cv::Mat distCoeffs; cv::Mat stdDeviations; double avgError; cameraParameters(){} cameraParameters(cv::Mat& _cameraMatrix, cv::Mat& _distCoeffs, cv::Mat& _stdDeviations, double _avgError = 0) : cameraMatrix(_cameraMatrix), distCoeffs(_distCoeffs), stdDeviations(_stdDeviations), avgError(_avgError) {} }; struct captureParameters { InputType captureMethod; InputVideoSource source; TemplateType board; cv::Size inputBoardSize; cv::Size boardSizeInnerCorners; // board size in inner corners for chessboard cv::Size boardSizeUnits; // board size in squares, circles, etc. int charucoDictName; std::string charucoDictFile; int calibrationStep; float charucoSquareLength, charucoMarkerSize; float captureDelay; float squareSize; float templDst; std::string videoFileName; bool flipVertical; int camID; int camBackend; int fps; cv::Size cameraResolution; int maxFramesNum; int minFramesNum; bool saveFrames; float zoom; bool forceReopen; captureParameters() { calibrationStep = 1; captureDelay = 500.f; maxFramesNum = 30;
minFramesNum = 10;
fps = 30; cameraResolution = cv::Size(IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT); saveFrames = false; } }; struct internalParameters { double solverEps; int solverMaxIters; bool fastSolving; bool rationalModel; bool thinPrismModel; bool tiltedModel; double filterAlpha; internalParameters() { solverEps = 1e-7; solverMaxIters = 30; fastSolving = false; rationalModel = false; thinPrismModel = false; tiltedModel = false; filterAlpha = 0.1; } }; } #endif
ast_based
<|fim_prefix|>_slice; if (host_str != nullptr) { host_slice = grpc::SliceFromCopiedString(*host_str); } c_call = grpc_channel_create_call( c_channel_, context->propagate_from_call_, context->propagation_options_.c_bitmask(), cq->cq(), method_slice, host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(), nullptr); grpc_slice_unref(method_slice); if (host_str != nullptr) { grpc_slice_unref(host_slice); } } grpc_census_call_set_context(c_call, context->census_context()); // ClientRpcInfo should be set before call because set_call also checks // whether the call has been cancelled, and if the call was cancelled, we // should notify the interceptors too. auto* info = context->set_client_rpc_info( method.name(), method.suffix_for_stats(), method.method_type(), this, interceptor_creators_, interceptor_pos); context->set_call(c_call, shared_from_this()); return grpc::internal::Call(c_call, this, cq, info); } grpc::internal::Call Channel::CreateCall( const grpc::internal::RpcMethod& method, grpc::ClientContext* context, CompletionQueue* cq) { return CreateCallInternal(method, context, cq, 0); } void Channel::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops, grpc::internal::Call* call) { ops->FillOps( call); // Make a copy of call. It's fine since Call just has pointers } void* Channel::RegisterMethod(const char* method) { return grpc_channel_register_call( c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr); } grpc_connectivity_state Channel::GetState(bool try_to_connect) { return grpc_channel_check_connectivity_state(c_channel_, try_to_connect); } namespace { class TagSaver final : public grpc::internal::CompletionQueueTag { public: explicit TagSaver(void* tag) : tag_(tag) {} ~TagSaver() override {} bool FinalizeResult(void** tag, bool* /*status*/) override { *tag = tag_; <|fim_suffix|> } private: void* tag_; }; } // namespace void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline, grpc::CompletionQueue* cq, void* tag) { TagSaver* tag_saver = new TagSaver(tag); grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline, cq->cq(), tag_saver); } bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline) { grpc::CompletionQueue cq; bool ok = false; void* tag = nullptr; NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr); cq.Next(&tag, &ok); GRPC_CHECK_EQ(tag, nullptr); return ok; } namespace { class ShutdownCallback : public grpc_completion_queue_functor { public: ShutdownCallback() { functor_run = &ShutdownCallback::Run; // Set inlineable to true since this callback is trivial and thus does not // need to be run from the EventEngine (potentially triggering a thread // hop). This should only be used by internal callbacks like this and not by // user application code. inlineable = true; } // TakeCQ takes ownership of the cq into the shutdown callback // so that the shutdown callback will be responsible for destroying it void TakeCQ(grpc::CompletionQueue* cq) { cq_ = cq; } // The Run function will get invoked by the completion queue library // when the shutdown is actually complete static void Run(grpc_completion_queue_functor* cb, int) { auto* callback = static_cast<ShutdownCallback*>(cb); delete callback->cq_; delete callback; } private: grpc::CompletionQueue* cq_ = nullptr; }; } // namespace ::grpc::CompletionQueue* Channel::CallbackCQ() { // TODO(vjpai): Consider using a single global CQ for the default CQ // if there is no explicit per-channel CQ registered CompletionQueue* callback_cq = callba<|fim_middle|>delete this; return true;
_slice; if (host_str != nullptr) { host_slice = grpc::SliceFromCopiedString(*host_str); } c_call = grpc_channel_create_call( c_channel_, context->propagate_from_call_, context->propagation_options_.c_bitmask(), cq->cq(), method_slice, host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(), nullptr); grpc_slice_unref(method_slice); if (host_str != nullptr) { grpc_slice_unref(host_slice); } } grpc_census_call_set_context(c_call, context->census_context()); // ClientRpcInfo should be set before call because set_call also checks // whether the call has been cancelled, and if the call was cancelled, we // should notify the interceptors too. auto* info = context->set_client_rpc_info( method.name(), method.suffix_for_stats(), method.method_type(), this, interceptor_creators_, interceptor_pos); context->set_call(c_call, shared_from_this()); return grpc::internal::Call(c_call, this, cq, info); } grpc::internal::Call Channel::CreateCall( const grpc::internal::RpcMethod& method, grpc::ClientContext* context, CompletionQueue* cq) { return CreateCallInternal(method, context, cq, 0); } void Channel::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops, grpc::internal::Call* call) { ops->FillOps( call); // Make a copy of call. It's fine since Call just has pointers } void* Channel::RegisterMethod(const char* method) { return grpc_channel_register_call( c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr); } grpc_connectivity_state Channel::GetState(bool try_to_connect) { return grpc_channel_check_connectivity_state(c_channel_, try_to_connect); } namespace { class TagSaver final : public grpc::internal::CompletionQueueTag { public: explicit TagSaver(void* tag) : tag_(tag) {} ~TagSaver() override {} bool FinalizeResult(void** tag, bool* /*status*/) override { *tag = tag_;
delete this; return true;
} private: void* tag_; }; } // namespace void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline, grpc::CompletionQueue* cq, void* tag) { TagSaver* tag_saver = new TagSaver(tag); grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline, cq->cq(), tag_saver); } bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline) { grpc::CompletionQueue cq; bool ok = false; void* tag = nullptr; NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr); cq.Next(&tag, &ok); GRPC_CHECK_EQ(tag, nullptr); return ok; } namespace { class ShutdownCallback : public grpc_completion_queue_functor { public: ShutdownCallback() { functor_run = &ShutdownCallback::Run; // Set inlineable to true since this callback is trivial and thus does not // need to be run from the EventEngine (potentially triggering a thread // hop). This should only be used by internal callbacks like this and not by // user application code. inlineable = true; } // TakeCQ takes ownership of the cq into the shutdown callback // so that the shutdown callback will be responsible for destroying it void TakeCQ(grpc::CompletionQueue* cq) { cq_ = cq; } // The Run function will get invoked by the completion queue library // when the shutdown is actually complete static void Run(grpc_completion_queue_functor* cb, int) { auto* callback = static_cast<ShutdownCallback*>(cb); delete callback->cq_; delete callback; } private: grpc::CompletionQueue* cq_ = nullptr; }; } // namespace ::grpc::CompletionQueue* Channel::CallbackCQ() { // TODO(vjpai): Consider using a single global CQ for the default CQ // if there is no explicit per-channel CQ registered CompletionQueue* callback_cq = callba
ast_based
<|fim_prefix|>gBox(level, raw_padding, &left, &top, &right, &bottom) && (!text_only || PTIsTextType(page_it->BlockType()))) { ++component_count; } } while (page_it->Next(level)); } else { // Get bounding box from binarized imaged. Note that this could be // differently scaled from the original image. do { if (page_it->BoundingBoxInternal(level, &left, &top, &right, &bottom) && (!text_only || PTIsTextType(page_it->BlockType()))) { ++component_count; } } while (page_it->Next(level)); } Boxa *boxa = boxaCreate(component_count); if (pixa != nullptr) { *pixa = pixaCreate(component_count); } if (blockids != nullptr) { *blockids = new int[component_count]; } if (paraids != nullptr) { *paraids = new int[component_count]; } int blockid = 0; int paraid = 0; int component_index = 0; page_it->Begin(); do { bool got_bounding_box; if (raw_image) { got_bounding_box = page_it->BoundingBox(level, raw_padding, &left, &top, &right, &bottom); } else { got_bounding_box = page_it->BoundingBoxInternal(level, &left, &top, &right, &bottom); } if (got_bounding_box && (!text_only || PTIsTextType(page_it->BlockType()))) { Box *lbox = boxCreate(left, top, right - left, bottom - top); boxaAddBox(boxa, lbox, L_INSERT); if (pixa != nullptr) { Pix *pix = nullptr; if (raw_image) { pix = page_it->GetImage(level, raw_padding, GetInputImage(), &left, &top); } else { pix = page_it->GetBinaryImage(level); } pixaAddPix(*pixa, pix, L_INSERT); pixaAddBox(*pixa, lbox, L_CLONE); } if (paraids != nullptr) { (*paraids)[component_index] = paraid; if (page_it->IsAtFinalElement(RIL_PARA, level)) { ++paraid; } } if (blockids != nullptr) { (*blockids)[component_index] = blockid; if (page_it->IsAtFinalElement(RIL_BLOCK, level)) <|fim_suffix|> } ++component_index; } } while (page_it->Next(level)); return boxa; } int TessBaseAPI::GetThresholdedImageScaleFactor() const { if (thresholder_ == nullptr) { return 0; } return thresholder_->GetScaleFactor(); } /** * Runs page layout analysis in the mode set by SetPageSegMode. * May optionally be called prior to Recognize to get access to just * the page layout results. Returns an iterator to the results. * If merge_similar_words is true, words are combined where suitable for use * with a line recognizer. Use if you want to use AnalyseLayout to find the * textlines, and then want to process textline fragments with an external * line recognizer. * Returns nullptr on error or an empty page. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ PageIterator *TessBaseAPI::AnalyseLayout() { return AnalyseLayout(false); } PageIterator *TessBaseAPI::AnalyseLayout(bool merge_similar_words) { if (FindLines() == 0) { if (block_list_->empty()) { return nullptr; // The page was empty. } page_res_ = new PAGE_RES(merge_similar_words, block_list_, nullptr); DetectParagraphs(false); return new PageIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } return nullptr; } /** * Recognize the tesseract global image and return the result as Tesseract * internal structures. */ int TessBaseAPI::Recognize(ETEXT_DESC *monitor) { if (tesseract_ == nullptr) { return -1; } if (FindLines() != 0) { return -1; } delete page_res_; if (block_list_->empty(<|fim_middle|>{ ++blockid; paraid = 0; }
gBox(level, raw_padding, &left, &top, &right, &bottom) && (!text_only || PTIsTextType(page_it->BlockType()))) { ++component_count; } } while (page_it->Next(level)); } else { // Get bounding box from binarized imaged. Note that this could be // differently scaled from the original image. do { if (page_it->BoundingBoxInternal(level, &left, &top, &right, &bottom) && (!text_only || PTIsTextType(page_it->BlockType()))) { ++component_count; } } while (page_it->Next(level)); } Boxa *boxa = boxaCreate(component_count); if (pixa != nullptr) { *pixa = pixaCreate(component_count); } if (blockids != nullptr) { *blockids = new int[component_count]; } if (paraids != nullptr) { *paraids = new int[component_count]; } int blockid = 0; int paraid = 0; int component_index = 0; page_it->Begin(); do { bool got_bounding_box; if (raw_image) { got_bounding_box = page_it->BoundingBox(level, raw_padding, &left, &top, &right, &bottom); } else { got_bounding_box = page_it->BoundingBoxInternal(level, &left, &top, &right, &bottom); } if (got_bounding_box && (!text_only || PTIsTextType(page_it->BlockType()))) { Box *lbox = boxCreate(left, top, right - left, bottom - top); boxaAddBox(boxa, lbox, L_INSERT); if (pixa != nullptr) { Pix *pix = nullptr; if (raw_image) { pix = page_it->GetImage(level, raw_padding, GetInputImage(), &left, &top); } else { pix = page_it->GetBinaryImage(level); } pixaAddPix(*pixa, pix, L_INSERT); pixaAddBox(*pixa, lbox, L_CLONE); } if (paraids != nullptr) { (*paraids)[component_index] = paraid; if (page_it->IsAtFinalElement(RIL_PARA, level)) { ++paraid; } } if (blockids != nullptr) { (*blockids)[component_index] = blockid; if (page_it->IsAtFinalElement(RIL_BLOCK, level))
{ ++blockid; paraid = 0; }
} ++component_index; } } while (page_it->Next(level)); return boxa; } int TessBaseAPI::GetThresholdedImageScaleFactor() const { if (thresholder_ == nullptr) { return 0; } return thresholder_->GetScaleFactor(); } /** * Runs page layout analysis in the mode set by SetPageSegMode. * May optionally be called prior to Recognize to get access to just * the page layout results. Returns an iterator to the results. * If merge_similar_words is true, words are combined where suitable for use * with a line recognizer. Use if you want to use AnalyseLayout to find the * textlines, and then want to process textline fragments with an external * line recognizer. * Returns nullptr on error or an empty page. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ PageIterator *TessBaseAPI::AnalyseLayout() { return AnalyseLayout(false); } PageIterator *TessBaseAPI::AnalyseLayout(bool merge_similar_words) { if (FindLines() == 0) { if (block_list_->empty()) { return nullptr; // The page was empty. } page_res_ = new PAGE_RES(merge_similar_words, block_list_, nullptr); DetectParagraphs(false); return new PageIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } return nullptr; } /** * Recognize the tesseract global image and return the result as Tesseract * internal structures. */ int TessBaseAPI::Recognize(ETEXT_DESC *monitor) { if (tesseract_ == nullptr) { return -1; } if (FindLines() != 0) { return -1; } delete page_res_; if (block_list_->empty(
ast_based
<|fim_prefix|>#pragma once #include "common.h" #include <set> #include <string> #include <vector> // // CLI argument parsing // struct common_arg { std::set<enum llama_example> examples = {LLAMA_EXAMPLE_COMMON}; std::set<enum llama_example> excludes = {}; std::vector<const char *> args; const char * value_hint = nullptr; // help text or example for arg value const char * value_hint_2 = nullptr; // for second arg value const char * env = nullptr; std::string help; bool is_sparam = false; // is current arg a sampling param? void (*handler_void) (common_params & params) = nullptr; void (*handler_string) (common_params & params, const std::string &) = nullptr; void (*handler_str_str)(common_params & params, const std::string &, const std::string &) = nullptr; void (*handler_int) (common_params & params, int) = nullptr; common_arg( const std::initializer_list<const char *> & args, const char * value_hint, <|fim_suffix|>, void (*handler)(common_params & params, const std::string &) ) : args(args), value_hint(value_hint), help(help), handler_string(handler) {} common_arg( const std::initializer_list<const char *> & args, const char * value_hint, const std::string & help, void (*handler)(common_params & params, int) ) : args(args), value_hint(value_hint), help(help), handler_int(handler) {} common_arg( const std::initializer_list<const char *> & args, const std::string & help, void (*handler)(common_params & params) ) : args(args), help(help), handler_void(handler) {} // support 2 values for arg common_arg( const std::initializer_list<const char *> & args, const char * value_hint, const char * value_hint_2, const std::string & help, void (*handler)(common_params & params, const std::string &, const std::string &) ) : args(args), value_hint(value_hint), value_hint_2(value_hint_2), help(help), handler_str_str(handler) {} common_arg & set_examples(std::initializer_list<enum llama_example> examples); common_arg & set_excludes(std::initializer_list<enum llama_example> excludes); common_arg & set_env(const char * env); common_arg & set_sparam(); bool in_example(enum llama_example ex); bool is_exclude(enum llama_example ex); bool get_value_from_env(std::string & output); bool has_value_from_env(); std::string to_string(); }; struct common_params_context { enum llama_example ex = LLAMA_EXAMPLE_COMMON; common_params & params; std::vector<common_arg> options; void(*print_usage)(int, char **) = nullptr; common_params_context(common_params & params) : params(params) {} }; // parse input arguments from CLI // if one argument has invalid value, it will automatically display usage of the specific argument (and not the full usage message) bool common_params_parse(int argc, char ** argv, common_params & pa<|fim_middle|>const std::string & help
#pragma once #include "common.h" #include <set> #include <string> #include <vector> // // CLI argument parsing // struct common_arg { std::set<enum llama_example> examples = {LLAMA_EXAMPLE_COMMON}; std::set<enum llama_example> excludes = {}; std::vector<const char *> args; const char * value_hint = nullptr; // help text or example for arg value const char * value_hint_2 = nullptr; // for second arg value const char * env = nullptr; std::string help; bool is_sparam = false; // is current arg a sampling param? void (*handler_void) (common_params & params) = nullptr; void (*handler_string) (common_params & params, const std::string &) = nullptr; void (*handler_str_str)(common_params & params, const std::string &, const std::string &) = nullptr; void (*handler_int) (common_params & params, int) = nullptr; common_arg( const std::initializer_list<const char *> & args, const char * value_hint,
const std::string & help
, void (*handler)(common_params & params, const std::string &) ) : args(args), value_hint(value_hint), help(help), handler_string(handler) {} common_arg( const std::initializer_list<const char *> & args, const char * value_hint, const std::string & help, void (*handler)(common_params & params, int) ) : args(args), value_hint(value_hint), help(help), handler_int(handler) {} common_arg( const std::initializer_list<const char *> & args, const std::string & help, void (*handler)(common_params & params) ) : args(args), help(help), handler_void(handler) {} // support 2 values for arg common_arg( const std::initializer_list<const char *> & args, const char * value_hint, const char * value_hint_2, const std::string & help, void (*handler)(common_params & params, const std::string &, const std::string &) ) : args(args), value_hint(value_hint), value_hint_2(value_hint_2), help(help), handler_str_str(handler) {} common_arg & set_examples(std::initializer_list<enum llama_example> examples); common_arg & set_excludes(std::initializer_list<enum llama_example> excludes); common_arg & set_env(const char * env); common_arg & set_sparam(); bool in_example(enum llama_example ex); bool is_exclude(enum llama_example ex); bool get_value_from_env(std::string & output); bool has_value_from_env(); std::string to_string(); }; struct common_params_context { enum llama_example ex = LLAMA_EXAMPLE_COMMON; common_params & params; std::vector<common_arg> options; void(*print_usage)(int, char **) = nullptr; common_params_context(common_params & params) : params(params) {} }; // parse input arguments from CLI // if one argument has invalid value, it will automatically display usage of the specific argument (and not the full usage message) bool common_params_parse(int argc, char ** argv, common_params & pa
ast_based
<|fim_prefix|>tyDriver { static AccessibilityDriverAccessKit *singleton; struct AccessibilityElement { HashMap<accesskit_action, Callable> actions; DisplayServer::WindowID window_id = DisplayServer::INVALID_WINDOW_ID; RID parent; LocalVector<RID> children; Vector3i run; Variant meta; String name; String name_extra_info; accesskit_role role = ACCESSKIT_ROLE_UNKNOWN; accesskit_node *node = nullptr; }; mutable 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(<|fim_suffix|>, 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<|fim_middle|>DisplayServer::WindowID p_window_id
tyDriver { static AccessibilityDriverAccessKit *singleton; struct AccessibilityElement { HashMap<accesskit_action, Callable> actions; DisplayServer::WindowID window_id = DisplayServer::INVALID_WINDOW_ID; RID parent; LocalVector<RID> children; Vector3i run; Variant meta; String name; String name_extra_info; accesskit_role role = ACCESSKIT_ROLE_UNKNOWN; accesskit_node *node = nullptr; }; mutable 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
ast_based
<|fim_prefix|> _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) { return; } <|fim_suffix|> frames->disconnect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); } stop(); frames = p_frames; if (frames.is_valid()) { frames->connect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); List<StringName> al; frames->get_animation_list(&al); if (al.is_empty()) { set_animation(StringName()); autoplay = String(); } else { if (!frames->has_animation(animation)) { set_animation(al.front()->get()); } if (!frames->has_animation(autoplay)) { autoplay = String(); } } } notify_property_list_changed(); queue_redraw(); update_configuration_warnings(); emit_signal("sprite_frames_changed"); } Ref<SpriteFrames> AnimatedSprite2D::get_sprite_frames() const { return frames; } void AnimatedSprite2D::set_frame(int p_frame) { set_frame_and_progress(p_frame, std::signbit(get_playing_speed()) ? 1.0 : 0.0); } int AnimatedSprite2D::get_frame() const { return frame; } void AnimatedSprite2D::set_frame_progress(real_t p_progress) { frame_progress = p_progress; } real_t AnimatedSprite2D::get_frame_progress() const { return frame_progress; } void AnimatedSprite2D::set_frame_and_progress(int p_frame, real_t p_progress) { if (frames.is_null()) { return; } bool has_animation = frames->has_animation(animation); int end_frame = has_animation ? MAX(0, frames->get_frame_count(animation) - 1) : 0; bool is_changed = frame != p_frame; if (p_frame < 0) { frame = 0; } else if (has_animation && p_frame > end_frame) { frame = end_frame; } else { frame = p_frame; } _calc_frame_speed_scale(); frame_progress = p_progress; if (!is_changed) { return; // No change, don't redraw. } queue_redraw(); emit_signal(SceneStringName(frame_changed)); } void AnimatedSprite2D::set_speed_scale(float p_speed_scale) { speed_scale = p_speed_scale; } float AnimatedSprite2D::get_speed_scale() const { return speed_scale; } float AnimatedSprite2D::get_playing_speed() const {<|fim_middle|> if (frames.is_valid()) {
_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) { return; }
if (frames.is_valid()) {
frames->disconnect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); } stop(); frames = p_frames; if (frames.is_valid()) { frames->connect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); List<StringName> al; frames->get_animation_list(&al); if (al.is_empty()) { set_animation(StringName()); autoplay = String(); } else { if (!frames->has_animation(animation)) { set_animation(al.front()->get()); } if (!frames->has_animation(autoplay)) { autoplay = String(); } } } notify_property_list_changed(); queue_redraw(); update_configuration_warnings(); emit_signal("sprite_frames_changed"); } Ref<SpriteFrames> AnimatedSprite2D::get_sprite_frames() const { return frames; } void AnimatedSprite2D::set_frame(int p_frame) { set_frame_and_progress(p_frame, std::signbit(get_playing_speed()) ? 1.0 : 0.0); } int AnimatedSprite2D::get_frame() const { return frame; } void AnimatedSprite2D::set_frame_progress(real_t p_progress) { frame_progress = p_progress; } real_t AnimatedSprite2D::get_frame_progress() const { return frame_progress; } void AnimatedSprite2D::set_frame_and_progress(int p_frame, real_t p_progress) { if (frames.is_null()) { return; } bool has_animation = frames->has_animation(animation); int end_frame = has_animation ? MAX(0, frames->get_frame_count(animation) - 1) : 0; bool is_changed = frame != p_frame; if (p_frame < 0) { frame = 0; } else if (has_animation && p_frame > end_frame) { frame = end_frame; } else { frame = p_frame; } _calc_frame_speed_scale(); frame_progress = p_progress; if (!is_changed) { return; // No change, don't redraw. } queue_redraw(); emit_signal(SceneStringName(frame_changed)); } void AnimatedSprite2D::set_speed_scale(float p_speed_scale) { speed_scale = p_speed_scale; } float AnimatedSprite2D::get_speed_scale() const { return speed_scale; } float AnimatedSprite2D::get_playing_speed() const {
random
<|fim_prefix|>#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) {<|fim_suffix|> //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; 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;<|fim_middle|> print_verbose("AccessKit loaded."); } else { return ERR_CANT_CREATE; } #endif #ifdef MACOS_ENABLED
#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; 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;
random
<|fim_prefix|>gml_format_name(layer.w2, TN_FFN_DOWN, i); gguf_add_tensor(ctx, layer.w2); ggml_format_name(layer.w3, TN_FFN_UP, i); gguf_add_tensor(ctx, layer.w3); ggml_format_name(layer.ffn_norm, TN_FFN_NORM, i); gguf_add_tensor(ctx, layer.ffn_norm); } gguf_write_to_file(ctx, filename, false); gguf_free(ctx); } static struct train_params get_default_train_params() { struct train_params params; params.fn_vocab_model = "models/7B/ggml-model-f16.gguf"; params.fn_llama2c_output_model = "ak_llama_model.bin"; params.fn_train_data = "shakespeare.txt"; params.fn_checkpoint_in = "checkpoint.bin"; params.fn_checkpoint_out = "checkpoint.bin"; params.fn_model_out = "ggml-checkpoint-f32.bin"; params.seed = -1; params.n_ctx = 128; params.n_embd = 256; params.n_mult = 256; params.n_head = 8; params.n_layer = 16; params.n_rotmax = 64; params.n_threads = 6; params.n_batch = 8; params.n_examples = 8; params.n_predict = 1024; params.print_info_interval = 1; params.print_details_interval = 2; params.samples_start_after_nl = false; params.use_adam = true; params.use_flash = false; params.use_scratch = true; // only adam params.warmup = 100; params.cos_decay_steps = 1000; params.cos_decay_restart = 1.1f; params.cos_decay_alpha = 0.0f; params.lbfgs_n_iter = 16; params.adam_n_iter = 16; params.adam_alpha = 1e-3f; params.adam_decay = 1e-3f; params.mem_model_gb = 2; params.mem_compute_gb = 24; params.mem_compute0_gb = 8; params.mem_compute1_gb = 2; return params; } static void print_usage(int /*argc*/, char ** argv, const struct train_params * params) { fprintf(stderr, "usage: %s [options]\n", argv[0]); <|fim_suffix|> fprintf(stderr, "options:\n"); fprintf(stderr, " -h, --help show this help message and exit\n"); fprintf(stderr, " --copy-vocab-from-model FNAME path of gguf llama model or llama2.c vocabulary from which to copy vocab (default '%s')\n", params->fn_vocab_model); fprintf(stderr, " --llama2c-model FNAME [REQUIRED] model path from which to load Karpathy's llama2.c model\n"); fprintf(stderr, " --llama2c-output-model FNAME model path to save the converted llama2.c model (default %s')\n", params->fn_llama2c_output_model); fprintf(stderr, "\n"); } static bool params_parse(int argc, char ** argv, struct train_params * params) { bool invalid_param = false; bool reqd_param_found = false; std::string arg; struct train_params default_params = get_default_train_params(); const std::string arg_prefix = "--"; for (int i = 1; i < argc; i++) { arg = argv[i]; if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) { std::replace(arg.begin(), arg.end(), '_', '-'); } if (arg == "--copy-vocab-from-model") { if (++i >= argc) { invalid_param = true; break; } params->fn_vocab_model = argv[i]; } else if (arg == "--llama2c-model") { if (++i >= argc) { invalid_param = true; break; } reqd_param_found = true; params->fn_llama2c_model = argv[i]; } else if (arg == "--llama2c-output-model") { if (++i >= argc) { invalid_param = true; break; } params->fn_llama2c_output_model = argv[i]; } else if (arg == "-h" || arg == "--help") { print_usage(argc, argv, &default_params); exit(0); } else { fprintf(stderr, "error: unknown argument: %s\n", arg.c_str()); print_usage(argc, argv<|fim_middle|>fprintf(stderr, "\n");
gml_format_name(layer.w2, TN_FFN_DOWN, i); gguf_add_tensor(ctx, layer.w2); ggml_format_name(layer.w3, TN_FFN_UP, i); gguf_add_tensor(ctx, layer.w3); ggml_format_name(layer.ffn_norm, TN_FFN_NORM, i); gguf_add_tensor(ctx, layer.ffn_norm); } gguf_write_to_file(ctx, filename, false); gguf_free(ctx); } static struct train_params get_default_train_params() { struct train_params params; params.fn_vocab_model = "models/7B/ggml-model-f16.gguf"; params.fn_llama2c_output_model = "ak_llama_model.bin"; params.fn_train_data = "shakespeare.txt"; params.fn_checkpoint_in = "checkpoint.bin"; params.fn_checkpoint_out = "checkpoint.bin"; params.fn_model_out = "ggml-checkpoint-f32.bin"; params.seed = -1; params.n_ctx = 128; params.n_embd = 256; params.n_mult = 256; params.n_head = 8; params.n_layer = 16; params.n_rotmax = 64; params.n_threads = 6; params.n_batch = 8; params.n_examples = 8; params.n_predict = 1024; params.print_info_interval = 1; params.print_details_interval = 2; params.samples_start_after_nl = false; params.use_adam = true; params.use_flash = false; params.use_scratch = true; // only adam params.warmup = 100; params.cos_decay_steps = 1000; params.cos_decay_restart = 1.1f; params.cos_decay_alpha = 0.0f; params.lbfgs_n_iter = 16; params.adam_n_iter = 16; params.adam_alpha = 1e-3f; params.adam_decay = 1e-3f; params.mem_model_gb = 2; params.mem_compute_gb = 24; params.mem_compute0_gb = 8; params.mem_compute1_gb = 2; return params; } static void print_usage(int /*argc*/, char ** argv, const struct train_params * params) { fprintf(stderr, "usage: %s [options]\n", argv[0]);
fprintf(stderr, "\n");
fprintf(stderr, "options:\n"); fprintf(stderr, " -h, --help show this help message and exit\n"); fprintf(stderr, " --copy-vocab-from-model FNAME path of gguf llama model or llama2.c vocabulary from which to copy vocab (default '%s')\n", params->fn_vocab_model); fprintf(stderr, " --llama2c-model FNAME [REQUIRED] model path from which to load Karpathy's llama2.c model\n"); fprintf(stderr, " --llama2c-output-model FNAME model path to save the converted llama2.c model (default %s')\n", params->fn_llama2c_output_model); fprintf(stderr, "\n"); } static bool params_parse(int argc, char ** argv, struct train_params * params) { bool invalid_param = false; bool reqd_param_found = false; std::string arg; struct train_params default_params = get_default_train_params(); const std::string arg_prefix = "--"; for (int i = 1; i < argc; i++) { arg = argv[i]; if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) { std::replace(arg.begin(), arg.end(), '_', '-'); } if (arg == "--copy-vocab-from-model") { if (++i >= argc) { invalid_param = true; break; } params->fn_vocab_model = argv[i]; } else if (arg == "--llama2c-model") { if (++i >= argc) { invalid_param = true; break; } reqd_param_found = true; params->fn_llama2c_model = argv[i]; } else if (arg == "--llama2c-output-model") { if (++i >= argc) { invalid_param = true; break; } params->fn_llama2c_output_model = argv[i]; } else if (arg == "-h" || arg == "--help") { print_usage(argc, argv, &default_params); exit(0); } else { fprintf(stderr, "error: unknown argument: %s\n", arg.c_str()); print_usage(argc, argv
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|>AccessibilityDriverAccessKit *AccessibilityDriverAccessKit::singleton = nullptr; _FORCE_INLINE_ accesskit_role AccessibilityDriverAccessKit::_accessibility_role(DisplayServer::AccessibilityRole p_role) const { if (role_map.has(p_role)) { return role_map[p_role]; } return ACCESSKIT_ROLE_UNKNOWN; } _FORCE_INLINE_ accesskit_action AccessibilityDriverAccessKit::_accessibility_action(DisplayServer::AccessibilityAction p_action) const { if (action_map.has(p_action)) { return action_map[p_action]; } return ACCESSKIT_ACTION_CLICK; } bool AccessibilityDriverAccessKit::window_create(DisplayServer::WindowID p_window_id, void *p_handle) { ERR_FAIL_COND_V(windows.has(p_window_id), false); WindowData &wd = windows[p_window_id]; AccessibilityElement *ae = memnew(AccessibilityElement); ae->role = ACCESSKIT_ROLE_WINDOW; ae->window_id = p_window_id; wd.root_id = rid_owner.make_rid(ae); #ifdef WINDOWS_ENABLED wd.adapter = accesskit_windows_subclassing_adapter_new(static_cast<HWND>(p_handle), &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef MACOS_ENABLED wd.adapter = accesskit_macos_subclassing_adapter_for_window(p_handle, &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef LINUXBSD_ENABLED wd.adapter = accesskit_unix_adapter_new(&_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id, &_accessibility_deactivation_callback, (void *)(size_t)p_window_id); #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); <|fim_middle|>#ifdef ACCESSKIT_ENABLED #include "accessibility_driver_accesskit.h" #include "core/config/project_settings.h" #include "core/version.h" #include "servers/text_server.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. */ /**************************************************************************/
#ifdef ACCESSKIT_ENABLED #include "accessibility_driver_accesskit.h" #include "core/config/project_settings.h" #include "core/version.h" #include "servers/text_server.h"
AccessibilityDriverAccessKit *AccessibilityDriverAccessKit::singleton = nullptr; _FORCE_INLINE_ accesskit_role AccessibilityDriverAccessKit::_accessibility_role(DisplayServer::AccessibilityRole p_role) const { if (role_map.has(p_role)) { return role_map[p_role]; } return ACCESSKIT_ROLE_UNKNOWN; } _FORCE_INLINE_ accesskit_action AccessibilityDriverAccessKit::_accessibility_action(DisplayServer::AccessibilityAction p_action) const { if (action_map.has(p_action)) { return action_map[p_action]; } return ACCESSKIT_ACTION_CLICK; } bool AccessibilityDriverAccessKit::window_create(DisplayServer::WindowID p_window_id, void *p_handle) { ERR_FAIL_COND_V(windows.has(p_window_id), false); WindowData &wd = windows[p_window_id]; AccessibilityElement *ae = memnew(AccessibilityElement); ae->role = ACCESSKIT_ROLE_WINDOW; ae->window_id = p_window_id; wd.root_id = rid_owner.make_rid(ae); #ifdef WINDOWS_ENABLED wd.adapter = accesskit_windows_subclassing_adapter_new(static_cast<HWND>(p_handle), &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef MACOS_ENABLED wd.adapter = accesskit_macos_subclassing_adapter_for_window(p_handle, &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef LINUXBSD_ENABLED wd.adapter = accesskit_unix_adapter_new(&_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id, &_accessibility_deactivation_callback, (void *)(size_t)p_window_id); #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);
random
<|fim_prefix|> 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'; } return -1; } auto it = adapter->gguf_kv.begin();<|fim_suffix|> if (i < 0 || i >= (int)adapter->gguf_kv.size()) { if (buf_size > 0) { buf[0] = '\0'; } return -1; } auto it = adapter->gguf_kv.begin(); std::advance(it, i); return snprintf(buf, buf_size, "%s", it->second.c_str()); } void llama_adapter_lora_free(llama_adapter_lora * adapter) { delete adapter; } uint64_t llama_adapter_get_alora_n_invocation_tokens(const struct llama_adapter_lora * adapter) { if (!adapter) { return 0; } return adapter->alora_invocation_tokens.size(); } const llama_token * llama_adapter_get_alora_invocation_tokens(const llama_adapter_lora * adapter) { GGML_ASSERT(adapter); return adapter->alora_invocation_tokens.data(); } <|fim_middle|> std::advance(it, i); return snprintf(buf, buf_size, "%s", it->first.c_str()); } int32_t llama_adapter_meta_val_str_by_index(const llama_adapter_lora * adapter, int32_t i, char * buf, size_t buf_size) {
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'; } return -1; } auto it = adapter->gguf_kv.begin();
std::advance(it, i); return snprintf(buf, buf_size, "%s", it->first.c_str()); } int32_t llama_adapter_meta_val_str_by_index(const llama_adapter_lora * adapter, int32_t i, char * buf, size_t buf_size) {
if (i < 0 || i >= (int)adapter->gguf_kv.size()) { if (buf_size > 0) { buf[0] = '\0'; } return -1; } auto it = adapter->gguf_kv.begin(); std::advance(it, i); return snprintf(buf, buf_size, "%s", it->second.c_str()); } void llama_adapter_lora_free(llama_adapter_lora * adapter) { delete adapter; } uint64_t llama_adapter_get_alora_n_invocation_tokens(const struct llama_adapter_lora * adapter) { if (!adapter) { return 0; } return adapter->alora_invocation_tokens.size(); } const llama_token * llama_adapter_get_alora_invocation_tokens(const llama_adapter_lora * adapter) { GGML_ASSERT(adapter); return adapter->alora_invocation_tokens.data(); }
random
<|fim_prefix|>#include "ggml.h" #include "gguf.h" #include "llama.h" #include "common.h" #include "log.h" #include <unordered_map> #include <vector> #include <cassert> #include <climits> #include <cstring> #include <cstdarg> #include <cinttypes> #include <ctime> #include <random> #include <stdexcept> #include <sstream> #include <algorithm> #include <string> // GGUF keys & tensor names. #define KV_GENERAL_ARCHITECTURE "general.architecture" #define KV_GENERAL_NAME "general.name" #define KV_TOKENIZER_MODEL "tokenizer.ggml.model"<|fim_suffix|>#define KV_TOKENIZER_TOKEN_TYPE "tokenizer.ggml.token_type" #define KV_TOKENIZER_SCORES "tokenizer.ggml.scores" #define KV_TOKENIZER_BOS_ID "tokenizer.ggml.bos_token_id" #define KV_TOKENIZER_EOS_ID "tokenizer.ggml.eos_token_id" #define KV_TOKENIZER_UNK_ID "tokenizer.ggml.unknown_token_id" #define KV_TOKENIZER_SEP_ID "tokenizer.ggml.seperator_token_id" #define KV_TOKENIZER_PAD_ID "tokenizer.ggml.padding_token_id" #define KV_TOKENIZER_HF_JSON "tokenizer.huggingface.json" #define KV_CONTEXT_LENGTH "llama.context_length" #define KV_EMBEDDING_LENGTH "llama.embedding_length" #define KV_BLOCK_COUNT "llama.block_count" #define KV_FEED_FORWARD_LENGTH "llama.feed_forward_length" #define KV_ATTENTION_HEAD_COUNT "llama.attention.head_count" #define KV_ATTENTION_HEAD_COUNT_KV "llama.attention.head_count_kv" #define KV_ATTENTION_LAYERNORM_RMS_EPS "llama.attention.layer_norm_rms_epsilon" #define KV_ROPE_DIMENSION_COUNT "llama.rope.dimension_count" #define TN_TOKEN_EMBD "token_embd.weight" #define TN_OUTPUT_NORM "output_norm.weight" #define TN_OUTPUT "output.weight" #define TN_ATTN_NORM "blk.%d.attn_norm.weight" #define TN_ATTN_Q "blk.%d.attn_q.weight" #define TN_ATTN_K "blk.%d.attn_k.weight" #define TN_ATTN_V "blk.%d.attn_v.weight" #define TN_ATTN_OUTPUT "blk.%d.attn_output.weight" #define TN_FFN_NORM "blk.%d.ffn_norm.weight" #define TN_FFN_GATE "blk.%d.ffn_gate.weight" #define TN_FFN_DOWN "blk.%d.ffn_down.weight" #define TN_FFN_UP "blk.%d.ffn_up.weight" #if defined(_MSC_VER) #pragma warning(disable: 4244 4267) // possible loss of data #endif #define LLAMA_FILE_MAGIC_GGJT 0x67676a74u // 'ggjt' #define LLAMA_FILE_VERSION_GGJT_V3 3 #define TOKENIZER_NAME "llama" #define UNKNOWN_TOKEN_ID 0 #define BOS_TOKEN_ID 1 #define EOS_TOKEN_ID 2 <|fim_middle|>#define KV_TOKENIZER_LIST "tokenizer.ggml.tokens"
#include "ggml.h" #include "gguf.h" #include "llama.h" #include "common.h" #include "log.h" #include <unordered_map> #include <vector> #include <cassert> #include <climits> #include <cstring> #include <cstdarg> #include <cinttypes> #include <ctime> #include <random> #include <stdexcept> #include <sstream> #include <algorithm> #include <string> // GGUF keys & tensor names. #define KV_GENERAL_ARCHITECTURE "general.architecture" #define KV_GENERAL_NAME "general.name" #define KV_TOKENIZER_MODEL "tokenizer.ggml.model"
#define KV_TOKENIZER_LIST "tokenizer.ggml.tokens"
#define KV_TOKENIZER_TOKEN_TYPE "tokenizer.ggml.token_type" #define KV_TOKENIZER_SCORES "tokenizer.ggml.scores" #define KV_TOKENIZER_BOS_ID "tokenizer.ggml.bos_token_id" #define KV_TOKENIZER_EOS_ID "tokenizer.ggml.eos_token_id" #define KV_TOKENIZER_UNK_ID "tokenizer.ggml.unknown_token_id" #define KV_TOKENIZER_SEP_ID "tokenizer.ggml.seperator_token_id" #define KV_TOKENIZER_PAD_ID "tokenizer.ggml.padding_token_id" #define KV_TOKENIZER_HF_JSON "tokenizer.huggingface.json" #define KV_CONTEXT_LENGTH "llama.context_length" #define KV_EMBEDDING_LENGTH "llama.embedding_length" #define KV_BLOCK_COUNT "llama.block_count" #define KV_FEED_FORWARD_LENGTH "llama.feed_forward_length" #define KV_ATTENTION_HEAD_COUNT "llama.attention.head_count" #define KV_ATTENTION_HEAD_COUNT_KV "llama.attention.head_count_kv" #define KV_ATTENTION_LAYERNORM_RMS_EPS "llama.attention.layer_norm_rms_epsilon" #define KV_ROPE_DIMENSION_COUNT "llama.rope.dimension_count" #define TN_TOKEN_EMBD "token_embd.weight" #define TN_OUTPUT_NORM "output_norm.weight" #define TN_OUTPUT "output.weight" #define TN_ATTN_NORM "blk.%d.attn_norm.weight" #define TN_ATTN_Q "blk.%d.attn_q.weight" #define TN_ATTN_K "blk.%d.attn_k.weight" #define TN_ATTN_V "blk.%d.attn_v.weight" #define TN_ATTN_OUTPUT "blk.%d.attn_output.weight" #define TN_FFN_NORM "blk.%d.ffn_norm.weight" #define TN_FFN_GATE "blk.%d.ffn_gate.weight" #define TN_FFN_DOWN "blk.%d.ffn_down.weight" #define TN_FFN_UP "blk.%d.ffn_up.weight" #if defined(_MSC_VER) #pragma warning(disable: 4244 4267) // possible loss of data #endif #define LLAMA_FILE_MAGIC_GGJT 0x67676a74u // 'ggjt' #define LLAMA_FILE_VERSION_GGJT_V3 3 #define TOKENIZER_NAME "llama" #define UNKNOWN_TOKEN_ID 0 #define BOS_TOKEN_ID 1 #define EOS_TOKEN_ID 2
random
<|fim_prefix|> /* 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;<|fim_suffix|> /* 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.unicharset->get_script_from_script_id(script_id); *script_name = script; } if (script_conf) { *script_conf = osr.best_result.sconfidence; } return true; } /** * The recognized text is returned as a char* which is coded * as UTF8 and must be freed with the delete [] operator. * page_number is a 0-based page index that will appear in the osd file. */ char *TessBaseAPI::GetOsdText(int page_number) { int orient_deg; float orient_conf; const char *script_name; float script_conf; if (!DetectOrientationScript(&orient_deg, &orient_conf, &script_name, &script_conf)) { return nullptr; } // clockwise rotation needed to make the page upright<|fim_middle|> last_char_was_tilde = true; } } } } } if (word->word->flag(W_EOL) && !last_char_was_newline) {
/* 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.unicharset->get_script_from_script_id(script_id); *script_name = script; } if (script_conf) { *script_conf = osr.best_result.sconfidence; } return true; } /** * The recognized text is returned as a char* which is coded * as UTF8 and must be freed with the delete [] operator. * page_number is a 0-based page index that will appear in the osd file. */ char *TessBaseAPI::GetOsdText(int page_number) { int orient_deg; float orient_conf; const char *script_name; float script_conf; if (!DetectOrientationScript(&orient_deg, &orient_conf, &script_name, &script_conf)) { return nullptr; } // clockwise rotation needed to make the page upright
random
<|fim_prefix|>/* 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. */ /**************************************************************************/ #ifdef ACCESSKIT_ENABLED #include "accessibility_driver_accesskit.h" #include "core/config/project_settings.h" #include "core/version.h" #include "servers/text_server.h" AccessibilityDriverAccessKit *AccessibilityDriverAccessKit::singleton = nullptr; _FORCE_INLINE_ accesskit_role AccessibilityDriverAccessKit::_accessibility_role(DisplayServer::AccessibilityRole p_role) const { if (role_map.has(p_role)) { return role_map[p_role]; } return ACCESSKIT_ROLE_UNKNOWN; } _FORCE_INLINE_ accesskit_action AccessibilityDriverAccessKit::_accessibility_action(DisplayServer::AccessibilityAction p_action) const { if (action_map.has(p_action)) { return action_map[p_action]; } return ACCESSKIT_ACTION_CLICK; } bool AccessibilityDriverAccessKit::window_create(DisplayServer::WindowID p_window_id, void *p_handle) { ERR_FAIL_COND_V(windows.has(p_window_id), false); WindowData &wd = windows[p_window_id]; AccessibilityElement *ae = memnew(AccessibilityElement); ae->role = ACCESSKIT_ROLE_WINDOW; ae->window_id = p_window_id; wd.root_id = rid_owner.make_rid(ae); #ifdef WINDOWS_ENABLED<|fim_suffix|>#endif #ifdef MACOS_ENABLED wd.adapter = accesskit_macos_subclassing_adapter_for_window(p_handle, &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef LINUXBSD_ENABLED wd.adapter = accesskit_unix_adapter_new(&_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id, &_accessibility_deactivation_callback, (void *)(size_t)p_window_id); #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; } <|fim_middle|> wd.adapter = accesskit_windows_subclassing_adapter_new(static_cast<HWND>(p_handle), &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id);
/* 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. */ /**************************************************************************/ #ifdef ACCESSKIT_ENABLED #include "accessibility_driver_accesskit.h" #include "core/config/project_settings.h" #include "core/version.h" #include "servers/text_server.h" AccessibilityDriverAccessKit *AccessibilityDriverAccessKit::singleton = nullptr; _FORCE_INLINE_ accesskit_role AccessibilityDriverAccessKit::_accessibility_role(DisplayServer::AccessibilityRole p_role) const { if (role_map.has(p_role)) { return role_map[p_role]; } return ACCESSKIT_ROLE_UNKNOWN; } _FORCE_INLINE_ accesskit_action AccessibilityDriverAccessKit::_accessibility_action(DisplayServer::AccessibilityAction p_action) const { if (action_map.has(p_action)) { return action_map[p_action]; } return ACCESSKIT_ACTION_CLICK; } bool AccessibilityDriverAccessKit::window_create(DisplayServer::WindowID p_window_id, void *p_handle) { ERR_FAIL_COND_V(windows.has(p_window_id), false); WindowData &wd = windows[p_window_id]; AccessibilityElement *ae = memnew(AccessibilityElement); ae->role = ACCESSKIT_ROLE_WINDOW; ae->window_id = p_window_id; wd.root_id = rid_owner.make_rid(ae); #ifdef WINDOWS_ENABLED
wd.adapter = accesskit_windows_subclassing_adapter_new(static_cast<HWND>(p_handle), &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id);
#endif #ifdef MACOS_ENABLED wd.adapter = accesskit_macos_subclassing_adapter_for_window(p_handle, &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef LINUXBSD_ENABLED wd.adapter = accesskit_unix_adapter_new(&_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id, &_accessibility_deactivation_callback, (void *)(size_t)p_window_id); #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; }
random
<|fim_prefix|>Type { 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 <|fim_suffix|> 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. if (size > values_.size()) { set_.GrowForInsertCount(size - values_.size(), KeyContext(&values_)); } values_.Reserve(size); } } // namespace Carbon #endif // CARBON_TOOLCHAIN_BASE_CANONICAL_VALUE_STORE_H_ <|fim_middle|>{ if (auto result = set_.Lookup(key, KeyContext(&values_))) { return result.key(); } return IdT::None; }
Type { 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. if (size > values_.size()) { set_.GrowForInsertCount(size - values_.size(), KeyContext(&values_)); } values_.Reserve(size); } } // namespace Carbon #endif // CARBON_TOOLCHAIN_BASE_CANONICAL_VALUE_STORE_H_
ast_based
<|fim_prefix|>imationBezierTrackEdit : public Control { GDCLASS(AnimationBezierTrackEdit, Control); enum { MENU_KEY_INSERT, MENU_KEY_DUPLICATE, MENU_KEY_CUT, MENU_KEY_COPY, MENU_KEY_PASTE, MENU_KEY_DELETE, MENU_KEY_SET_HANDLE_FREE, MENU_KEY_SET_HANDLE_LINEAR, MENU_KEY_SET_HANDLE_BALANCED, MENU_KEY_SET_HANDLE_MIRRORED, MENU_KEY_SET_HANDLE_AUTO_BALANCED, MENU_KEY_SET_HANDLE_AUTO_MIRRORED, }; AnimationTimelineEdit *timeline = nullptr; Node *root = nullptr; Control *play_position = nullptr; //separate control used to draw so updates for only position changed are much faster real_t play_position_pos = 0; Ref<Animation> animation; bool read_only = false; int selected_track = 0; Vector<Rect2> view_rects; Ref<Texture2D> bezier_icon; Ref<Texture2D> bezier_handle_icon; Ref<Texture2D> selected_icon; RBMap<int, Rect2> subtracks; enum { REMOVE_ICON, LOCK_ICON, SOLO_ICON, VISIBILITY_ICON }; RBMap<int, RBMap<int, Rect2>> subtrack_icons; HashSet<int> locked_tracks; HashSet<int> hidden_tracks; int solo_track = -1; bool is_filtered = false; float track_v_scroll = 0; float track_v_scroll_max = 0; float timeline_v_scroll = 0; float timeline_v_zoom = 1; PopupMenu *menu = nullptr; void _zoom_changed(); void _update_locked_tracks_after(int p_track); void _update_hidden_tracks_after(int p_track); virtual void gui_input(const Ref<InputEvent> &p_event) override; void _menu_selected(int p_index); void _play_position_draw(); bool _is_track_displayed(int p_track_index); bool _is_track_curves_displayed(int p_track_index); Vector2 insert_at_pos; typedef Pair<int, int> IntPair; bool moving_selection_attempt = false; bool moving_inserted_key = false; 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; <|fim_suffix|> 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, Re<|fim_middle|>bool box_selecting_add = false;
imationBezierTrackEdit : public Control { GDCLASS(AnimationBezierTrackEdit, Control); enum { MENU_KEY_INSERT, MENU_KEY_DUPLICATE, MENU_KEY_CUT, MENU_KEY_COPY, MENU_KEY_PASTE, MENU_KEY_DELETE, MENU_KEY_SET_HANDLE_FREE, MENU_KEY_SET_HANDLE_LINEAR, MENU_KEY_SET_HANDLE_BALANCED, MENU_KEY_SET_HANDLE_MIRRORED, MENU_KEY_SET_HANDLE_AUTO_BALANCED, MENU_KEY_SET_HANDLE_AUTO_MIRRORED, }; AnimationTimelineEdit *timeline = nullptr; Node *root = nullptr; Control *play_position = nullptr; //separate control used to draw so updates for only position changed are much faster real_t play_position_pos = 0; Ref<Animation> animation; bool read_only = false; int selected_track = 0; Vector<Rect2> view_rects; Ref<Texture2D> bezier_icon; Ref<Texture2D> bezier_handle_icon; Ref<Texture2D> selected_icon; RBMap<int, Rect2> subtracks; enum { REMOVE_ICON, LOCK_ICON, SOLO_ICON, VISIBILITY_ICON }; RBMap<int, RBMap<int, Rect2>> subtrack_icons; HashSet<int> locked_tracks; HashSet<int> hidden_tracks; int solo_track = -1; bool is_filtered = false; float track_v_scroll = 0; float track_v_scroll_max = 0; float timeline_v_scroll = 0; float timeline_v_zoom = 1; PopupMenu *menu = nullptr; void _zoom_changed(); void _update_locked_tracks_after(int p_track); void _update_hidden_tracks_after(int p_track); virtual void gui_input(const Ref<InputEvent> &p_event) override; void _menu_selected(int p_index); void _play_position_draw(); bool _is_track_displayed(int p_track_index); bool _is_track_curves_displayed(int p_track_index); Vector2 insert_at_pos; typedef Pair<int, int> IntPair; bool moving_selection_attempt = false; bool moving_inserted_key = false; 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, Re
ast_based
<|fim_prefix|>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. <|fim_suffix|> // 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( Rect2(bs_from, bs_to - bs_from), get_theme_color(SNAME("box_selection_stroke_color"), EditorStringName(Editor)), false, Math::round(EDSCALE)); } } break; } } // Check if a track is displayed in the bezier editor (track type = bezier and track not filtered). bool AnimationBezierTrackEdit::_is_track_displayed(int p_track_index) { if (animation->track_get_type(p_track_index) != Animation::TrackType::TYPE_BEZIER) { return false; } if (is_filtered) { String path = String(animation->track_get_path(p_track_index)); if (root && root->has_node(path)) { Node *node = root->get_node(path); if (!node) { return false; // No node, no filter. } if (!EditorNode::get_singleton()->get_editor_selection()->is_selected(node)) { return false; // Skip track due to not selected. } } } return true; } // Check if the curves for a track are displayed in th<|fim_middle|>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); }
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( Rect2(bs_from, bs_to - bs_from), get_theme_color(SNAME("box_selection_stroke_color"), EditorStringName(Editor)), false, Math::round(EDSCALE)); } } break; } } // Check if a track is displayed in the bezier editor (track type = bezier and track not filtered). bool AnimationBezierTrackEdit::_is_track_displayed(int p_track_index) { if (animation->track_get_type(p_track_index) != Animation::TrackType::TYPE_BEZIER) { return false; } if (is_filtered) { String path = String(animation->track_get_path(p_track_index)); if (root && root->has_node(path)) { Node *node = root->get_node(path); if (!node) { return false; // No node, no filter. } if (!EditorNode::get_singleton()->get_editor_selection()->is_selected(node)) { return false; // Skip track due to not selected. } } } return true; } // Check if the curves for a track are displayed in th
ast_based
<|fim_prefix|> 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); } animation->bezier_track_calculate_handles(offset_n, offset, height, offset_nn, height_nn, handle_mode, Animation::HANDLE_SET_MODE_AUTO, &in_handle, nullptr); } } } out_handle += Vector2(offset, height); in_handle += Vector2(offset_n, height_n); Vector2 start(offset, height); Vector2 end(offset_n, height_n); int from_x = (offset - timeline->get_value()) * scale + limit; int point_start = from_x; int to_x = (offset_n - timeline->get_value()) * scale + limit; int point_end = to_x; if (from_x > right_limit) { // Not visible. continue; } if (to_x < limit) { // Not visible. continue; } from_x = MAX(from_x, limit); to_x = MIN(to_x, right_limit); Vector<Vector2> lines; Vector2 prev_pos; for (int j = from_x; j <= to_x; j++) { float t = (j - limit) / scale + timeline->get_value(); float h; if (j == point_end) { h = end.y; // Make sure it always connects. } else if (j == point_start) { h = start.y; // Make sure it always connects. } else { // Custom interpolation, used because it needs to show paths affected by moving the selection or handles. int iterations = 10; float low = 0; float high = 1; // Narrow high and low as much as possible. for (int k = 0; k < iterations; k++) { float middle = (low + high) / 2.0; Vector2 interp = start.bezier_interpolate(out_handle, in_handle, end, middle); if (interp.x < t) { low = middle; } else { high = middle; } } // Interpolate the result. Vector2 low_pos = <|fim_suffix|>; Vector2 high_pos = start.bezier_interpolate(out_handle, in_handle, end, high); float c = (t - low_pos.x) / (high_pos.x - low_pos.x); h = low_pos.lerp(high_pos, c).y; } h = _bezier_h_to_pixel(h); Vector2 pos(j, h); if (j > from_x) { lines.push_back(prev_pos); lines.push_back(pos); } prev_pos = pos; } if (lines.size() >= 2) { draw_multiline(lines, p_color, Math::round(EDSCALE), true); } } } void AnimationBezierTrackEdit::_draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right) { Vector2 from = p_from; Vector2 to = p_to; if (from.x == to.x && from.y == to.y) { return; } if (to.x < from.x) { SWAP(to, from); } if (to.x < p_clip_left) { return; } if (from.x > p_clip_right) { return; } if (to.x > p_clip_right) { float c = (p_clip_right - from.x) / (to.x - from.x); to = from.lerp(to, c); } if (from.x < p_clip_left) { 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(<|fim_middle|>start.bezier_interpolate(out_handle, in_handle, end, low)
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); } animation->bezier_track_calculate_handles(offset_n, offset, height, offset_nn, height_nn, handle_mode, Animation::HANDLE_SET_MODE_AUTO, &in_handle, nullptr); } } } out_handle += Vector2(offset, height); in_handle += Vector2(offset_n, height_n); Vector2 start(offset, height); Vector2 end(offset_n, height_n); int from_x = (offset - timeline->get_value()) * scale + limit; int point_start = from_x; int to_x = (offset_n - timeline->get_value()) * scale + limit; int point_end = to_x; if (from_x > right_limit) { // Not visible. continue; } if (to_x < limit) { // Not visible. continue; } from_x = MAX(from_x, limit); to_x = MIN(to_x, right_limit); Vector<Vector2> lines; Vector2 prev_pos; for (int j = from_x; j <= to_x; j++) { float t = (j - limit) / scale + timeline->get_value(); float h; if (j == point_end) { h = end.y; // Make sure it always connects. } else if (j == point_start) { h = start.y; // Make sure it always connects. } else { // Custom interpolation, used because it needs to show paths affected by moving the selection or handles. int iterations = 10; float low = 0; float high = 1; // Narrow high and low as much as possible. for (int k = 0; k < iterations; k++) { float middle = (low + high) / 2.0; Vector2 interp = start.bezier_interpolate(out_handle, in_handle, end, middle); if (interp.x < t) { low = middle; } else { high = middle; } } // Interpolate the result. Vector2 low_pos =
start.bezier_interpolate(out_handle, in_handle, end, low)
; Vector2 high_pos = start.bezier_interpolate(out_handle, in_handle, end, high); float c = (t - low_pos.x) / (high_pos.x - low_pos.x); h = low_pos.lerp(high_pos, c).y; } h = _bezier_h_to_pixel(h); Vector2 pos(j, h); if (j > from_x) { lines.push_back(prev_pos); lines.push_back(pos); } prev_pos = pos; } if (lines.size() >= 2) { draw_multiline(lines, p_color, Math::round(EDSCALE), true); } } } void AnimationBezierTrackEdit::_draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right) { Vector2 from = p_from; Vector2 to = p_to; if (from.x == to.x && from.y == to.y) { return; } if (to.x < from.x) { SWAP(to, from); } if (to.x < p_clip_left) { return; } if (from.x > p_clip_right) { return; } if (to.x > p_clip_right) { float c = (p_clip_right - from.x) / (to.x - from.x); to = from.lerp(to, c); } if (from.x < p_clip_left) { 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(
ast_based
<|fim_prefix|>lama_get_state_size(struct llama_context * ctx), "use llama_state_get_size instead"); // Copies the state to the specified destination address. // Destination needs to have allocated enough memory. // Returns the number of bytes copied LLAMA_API size_t llama_state_get_data( struct llama_context * ctx, uint8_t * dst, size_t size); LLAMA_API DEPRECATED(size_t llama_copy_state_data( struct llama_context * ctx, uint8_t * dst), "use llama_state_get_data instead"); // Set the state reading from the specified address // Returns the number of bytes read LLAMA_API size_t llama_state_set_data( struct llama_context * ctx, const uint8_t * src, size_t size); LLAMA_API DEPRECATED(size_t llama_set_state_data( struct llama_context * ctx, const uint8_t * src), "use llama_state_set_data instead"); // Save/load session file LLAMA_API bool llama_state_load_file( 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( <|fim_suffix|>, 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 ll<|fim_middle|>struct llama_context * ctx
lama_get_state_size(struct llama_context * ctx), "use llama_state_get_size instead"); // Copies the state to the specified destination address. // Destination needs to have allocated enough memory. // Returns the number of bytes copied LLAMA_API size_t llama_state_get_data( struct llama_context * ctx, uint8_t * dst, size_t size); LLAMA_API DEPRECATED(size_t llama_copy_state_data( struct llama_context * ctx, uint8_t * dst), "use llama_state_get_data instead"); // Set the state reading from the specified address // Returns the number of bytes read LLAMA_API size_t llama_state_set_data( struct llama_context * ctx, const uint8_t * src, size_t size); LLAMA_API DEPRECATED(size_t llama_set_state_data( struct llama_context * ctx, const uint8_t * src), "use llama_state_set_data instead"); // Save/load session file LLAMA_API bool llama_state_load_file( 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 ll
ast_based
<|fim_prefix|>al_t> &E : new_selection_values) { undo_redo->add_do_method(this, "_select_at_anim", animation, E.first, E.second, i == 0); i++; } i = 0; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t time = animation->track_get_key_time(E->get().first, E->get().second); undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, time, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(); } void AnimationBezierTrackEdit::copy_selected_keys(bool p_cut) { if (selection.is_empty()) { return; } float top_time = 1e10; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { float t = animation->track_get_key_time(E->get().first, E->get().second); if (t < top_time) { top_time = t; } } RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo> keys; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { AnimationTrackEditor::SelectedKey sk; AnimationTrackEditor::KeyInfo ki; sk.track = E->get().first; sk.key = E->get().second; ki.pos = animation->track_get_key_time(E->get().first, E->get().second); keys.insert(sk, ki); } editor->_set_key_clipboard(selected_track, top_time, keys); if (p_cut) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Animation Cut Keys"), UndoRedo::MERGE_DISABLE, animation.ptr()); undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); int i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) { <|fim_suffix|> float time = E->value().pos; undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_time", track_idx, time); undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track_idx, time, animation->track_get_key_value(track_idx, key_idx), animation->track_get_key_transition(track_idx, key_idx)); undo_redo->add_undo_method(this, "_select_at_anim", animation, track_idx, time, i == 0); i++; } i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) { undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, E->value().pos, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(); } } void AnimationBezierTrackEdit::paste_keys(real_t p_ofs, bool p_ofs_valid) { if (editor->is_key_clipboard_active() && animation.is_valid() && (selected_track >= 0 && selected_track < animation->get_track_count())) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Animation Paste Keys")); bool same_track = true; bool all_compatible = true; for (int i = 0; i < editor->key_clipboard.keys.size(); i++) { const AnimationTrackEditor::KeyClipboard::Key key = editor->key_clipboard.keys[i]; if (key.track != 0) { same_track = false; break; } if (!editor->_is_track_compatible(selected_track, key.value.get_type(), key.track_type)) { all_compatible = false; break; } } ERR_FAIL_COND_MSG(!all_compatible, "Paste failed: Not all animation keys were compatible with their target tracks"); if (!same_track) { WARN_PRINT("Pasted animation keys from multiple track<|fim_middle|>int track_idx = E->key().track; int key_idx = E->key().key;
al_t> &E : new_selection_values) { undo_redo->add_do_method(this, "_select_at_anim", animation, E.first, E.second, i == 0); i++; } i = 0; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t time = animation->track_get_key_time(E->get().first, E->get().second); undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, time, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(); } void AnimationBezierTrackEdit::copy_selected_keys(bool p_cut) { if (selection.is_empty()) { return; } float top_time = 1e10; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { float t = animation->track_get_key_time(E->get().first, E->get().second); if (t < top_time) { top_time = t; } } RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo> keys; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { AnimationTrackEditor::SelectedKey sk; AnimationTrackEditor::KeyInfo ki; sk.track = E->get().first; sk.key = E->get().second; ki.pos = animation->track_get_key_time(E->get().first, E->get().second); keys.insert(sk, ki); } editor->_set_key_clipboard(selected_track, top_time, keys); if (p_cut) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Animation Cut Keys"), UndoRedo::MERGE_DISABLE, animation.ptr()); undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); int i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) {
int track_idx = E->key().track; int key_idx = E->key().key;
float time = E->value().pos; undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_time", track_idx, time); undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track_idx, time, animation->track_get_key_value(track_idx, key_idx), animation->track_get_key_transition(track_idx, key_idx)); undo_redo->add_undo_method(this, "_select_at_anim", animation, track_idx, time, i == 0); i++; } i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) { undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, E->value().pos, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(); } } void AnimationBezierTrackEdit::paste_keys(real_t p_ofs, bool p_ofs_valid) { if (editor->is_key_clipboard_active() && animation.is_valid() && (selected_track >= 0 && selected_track < animation->get_track_count())) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Animation Paste Keys")); bool same_track = true; bool all_compatible = true; for (int i = 0; i < editor->key_clipboard.keys.size(); i++) { const AnimationTrackEditor::KeyClipboard::Key key = editor->key_clipboard.keys[i]; if (key.track != 0) { same_track = false; break; } if (!editor->_is_track_compatible(selected_track, key.value.get_type(), key.track_type)) { all_compatible = false; break; } } ERR_FAIL_COND_MSG(!all_compatible, "Paste failed: Not all animation keys were compatible with their target tracks"); if (!same_track) { WARN_PRINT("Pasted animation keys from multiple track
ast_based
<|fim_prefix|>// File: altorenderer.cpp // Description: ALTO rendering interface // Author: Jake Sebright // (C) Copyright 2018 // 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. #include "errcode.h" // for ASSERT_HOST #include "helpers.h" // for copy_string #include "tprintf.h" // for tprintf #include <tesseract/baseapi.h> #include <tesseract/renderer.h> #include <memory> #include <sstream> // for std::stringstream namespace tesseract { /// Add coordinates to specified TextBlock, TextLine or String bounding box. /// Add word confidence if adding to a String bounding box. /// static void AddBoxToAlto(const ResultIterator *it, PageIteratorLevel level, std::stringstream &alto_str) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); int hpos = left; int vpos = top; int height = bottom - top; int width = right - left; alto_str << " HPOS=\"" << hpos << "\""; alto_str << " VPOS=\"" << vpos << "\""; alto_str << " WIDTH=\"" << width << "\""; alto_str << " HEIGHT=\"" << height << "\""; if (level == RIL_WORD) { int wc = it->Confidence(RIL_WORD);<|fim_suffix|> static std::string GetID(const char *prefix, int page_number, int counter) { std::stringstream idstr; // IDs will only have the counter for the first page to keep them consistent // with the IDs assigned before this change was made. // From the second page on, IDs will also contain the page number to make them unique. if (page_number == 0) { idstr << prefix << "_" << counter; } else { idstr << prefix << "_" << page_number << "_" << counter; } return idstr.str(); } /// /// Append the ALTO XML for the beginning of the document /// bool TessAltoRenderer::BeginDocumentHandler() { // Delay the XML output because we need the name of the image file. begin_document = true; return true; } /// /// Append the ALTO XML for the layout of the image /// bool TessAltoRenderer::AddImageHandler(TessBaseAPI *api) { if (begin_document) { AppendString( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<alto xmlns=\"http://www.loc.gov/standards/alto/ns-v3#\" " "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " "xsi:schemaLocation=\"http://www.loc.gov/standards/alto/ns-v3# " "http://www.loc.gov/alto/v3/alto-3-0.xsd\">\n" "\t<Description>\n" "\t\t<MeasurementUnit>pixel</MeasurementUnit>\n" "\t\t<sourceImageInformation>\n" "\t\t\t<fileName>"); AppendString(api->GetInputName()); AppendString( "</fileName>\n" "\t\t</sourceImageInformation>\n" "\t\t<OCRProcessing ID=\"OCR_0\">\n" "\t\t\t<ocrProcessingStep>\n" "\t\t\t\t<processingSoftware>\n" "\t\t\t\t\t<softwareName>Tesseract</softwareName>\n" "\t\t\t\t\t<softwareVersion>"); AppendString(TessBaseAPI::Version()); AppendString( "</softwareVersion>\n" "\t\t\t\t</processingSoftware>\n" "\t\t\t</ocrProcessingStep>\n" "\t\t</OCRProcessing>\n" "\t</Description>\n" "\t<Layout>\n"); begin_document = false; } <|fim_middle|> alto_str << " WC=\"0." << wc << "\""; } else { alto_str << ">"; } }
// File: altorenderer.cpp // Description: ALTO rendering interface // Author: Jake Sebright // (C) Copyright 2018 // 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. #include "errcode.h" // for ASSERT_HOST #include "helpers.h" // for copy_string #include "tprintf.h" // for tprintf #include <tesseract/baseapi.h> #include <tesseract/renderer.h> #include <memory> #include <sstream> // for std::stringstream namespace tesseract { /// Add coordinates to specified TextBlock, TextLine or String bounding box. /// Add word confidence if adding to a String bounding box. /// static void AddBoxToAlto(const ResultIterator *it, PageIteratorLevel level, std::stringstream &alto_str) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); int hpos = left; int vpos = top; int height = bottom - top; int width = right - left; alto_str << " HPOS=\"" << hpos << "\""; alto_str << " VPOS=\"" << vpos << "\""; alto_str << " WIDTH=\"" << width << "\""; alto_str << " HEIGHT=\"" << height << "\""; if (level == RIL_WORD) { int wc = it->Confidence(RIL_WORD);
alto_str << " WC=\"0." << wc << "\""; } else { alto_str << ">"; } }
static std::string GetID(const char *prefix, int page_number, int counter) { std::stringstream idstr; // IDs will only have the counter for the first page to keep them consistent // with the IDs assigned before this change was made. // From the second page on, IDs will also contain the page number to make them unique. if (page_number == 0) { idstr << prefix << "_" << counter; } else { idstr << prefix << "_" << page_number << "_" << counter; } return idstr.str(); } /// /// Append the ALTO XML for the beginning of the document /// bool TessAltoRenderer::BeginDocumentHandler() { // Delay the XML output because we need the name of the image file. begin_document = true; return true; } /// /// Append the ALTO XML for the layout of the image /// bool TessAltoRenderer::AddImageHandler(TessBaseAPI *api) { if (begin_document) { AppendString( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<alto xmlns=\"http://www.loc.gov/standards/alto/ns-v3#\" " "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " "xsi:schemaLocation=\"http://www.loc.gov/standards/alto/ns-v3# " "http://www.loc.gov/alto/v3/alto-3-0.xsd\">\n" "\t<Description>\n" "\t\t<MeasurementUnit>pixel</MeasurementUnit>\n" "\t\t<sourceImageInformation>\n" "\t\t\t<fileName>"); AppendString(api->GetInputName()); AppendString( "</fileName>\n" "\t\t</sourceImageInformation>\n" "\t\t<OCRProcessing ID=\"OCR_0\">\n" "\t\t\t<ocrProcessingStep>\n" "\t\t\t\t<processingSoftware>\n" "\t\t\t\t\t<softwareName>Tesseract</softwareName>\n" "\t\t\t\t\t<softwareVersion>"); AppendString(TessBaseAPI::Version()); AppendString( "</softwareVersion>\n" "\t\t\t\t</processingSoftware>\n" "\t\t\t</ocrProcessingStep>\n" "\t\t</OCRProcessing>\n" "\t</Description>\n" "\t<Layout>\n"); begin_document = false; }
random
<|fim_prefix|>{ 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; } } <|fim_middle|> tex->SetStatus(ImTextureStatus_OK);
{ 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; } }
random
<|fim_prefix|> } } 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) { return; } if (frames.is_valid()) { frames->disconnect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); } stop(); frames = p_frames; if (frames.is_valid()) { frames->connect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); List<StringName> al; frames->get_animation_list(&al); if (al.is_empty()) { set_animation(StringName()); autoplay = String(); } else { if (!frames->has_animation(animation)) { set_animation(al.front()->get()); } if (!frames->has_animation(autoplay)) { autoplay = String(); } } } notify_property_list_changed();<|fim_suffix|>} void AnimatedSprite2D::set_frame(int p_frame) { set_frame_and_progress(p_frame, std::signbit(get_playing_speed()) ? 1.0 : 0.0); } int AnimatedSprite2D::get_frame() const { return frame; } void AnimatedSprite2D::set_frame_progress(real_t p_progress) { frame_progress = p_progress; } real_t AnimatedSprite2D::get_frame_progress() const { return frame_progress; } void AnimatedSprite2D::set_frame_and_progress(int p_frame, real_t p_progress) { if (frames.is_null()) { return; } bool has_animation = frames->has_animation(animation); int end_frame = has_animation ? MAX(0, frames->get_frame_count(animation) - 1) : 0; bool is_changed = frame != p_frame; if (p_frame < 0) { frame = 0; } else if (has_animation && p_frame > end_frame) { frame = end_frame; } else { frame = p_frame; } _calc_frame_speed_scale(); frame_progress = p_progress; if (!is_changed) { return; // No change, don't redraw. } queue_redraw(); emit_signal(SceneStringName(frame_changed)); } void AnimatedSprite2D::set_speed_scale(float p_speed_scale) { speed_scale = p_speed_scale; } float AnimatedSprite2D::get_speed_scale() const { return speed_scale; } float AnimatedSprite2D::get_playing_speed() const { if (!playing) { return 0; } return speed_scale * custom_speed_scale; } void AnimatedSprite2D::set_centered(bool p_center) { if (centered == p_center) { return; } centered = p_center; queue_redraw(); item_rect_changed(); } bool AnimatedSprite2D::is_centered() const { return centered; } void AnimatedSprite2D::set_offset(const Point2 &p_offset) { if (offset == p_offset) { return; } offset = p_offset; queue_redraw(); item_rect_changed(); } Point2 AnimatedSprite2D::get_offset() const { return offset; } void AnimatedSprite2D::set_flip_h(bool p_flip) { if (hflip == p_flip) { return; } hflip = p_flip; queue_redraw(); } bool AnimatedSprite2D::is_flipped_h() const { return hflip; } void AnimatedSprite2D::set_flip_v(bool p_flip) {<|fim_middle|> queue_redraw(); update_configuration_warnings(); emit_signal("sprite_frames_changed"); } Ref<SpriteFrames> AnimatedSprite2D::get_sprite_frames() const { return frames;
} } 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) { return; } if (frames.is_valid()) { frames->disconnect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); } stop(); frames = p_frames; if (frames.is_valid()) { frames->connect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); List<StringName> al; frames->get_animation_list(&al); if (al.is_empty()) { set_animation(StringName()); autoplay = String(); } else { if (!frames->has_animation(animation)) { set_animation(al.front()->get()); } if (!frames->has_animation(autoplay)) { autoplay = String(); } } } notify_property_list_changed();
queue_redraw(); update_configuration_warnings(); emit_signal("sprite_frames_changed"); } Ref<SpriteFrames> AnimatedSprite2D::get_sprite_frames() const { return frames;
} void AnimatedSprite2D::set_frame(int p_frame) { set_frame_and_progress(p_frame, std::signbit(get_playing_speed()) ? 1.0 : 0.0); } int AnimatedSprite2D::get_frame() const { return frame; } void AnimatedSprite2D::set_frame_progress(real_t p_progress) { frame_progress = p_progress; } real_t AnimatedSprite2D::get_frame_progress() const { return frame_progress; } void AnimatedSprite2D::set_frame_and_progress(int p_frame, real_t p_progress) { if (frames.is_null()) { return; } bool has_animation = frames->has_animation(animation); int end_frame = has_animation ? MAX(0, frames->get_frame_count(animation) - 1) : 0; bool is_changed = frame != p_frame; if (p_frame < 0) { frame = 0; } else if (has_animation && p_frame > end_frame) { frame = end_frame; } else { frame = p_frame; } _calc_frame_speed_scale(); frame_progress = p_progress; if (!is_changed) { return; // No change, don't redraw. } queue_redraw(); emit_signal(SceneStringName(frame_changed)); } void AnimatedSprite2D::set_speed_scale(float p_speed_scale) { speed_scale = p_speed_scale; } float AnimatedSprite2D::get_speed_scale() const { return speed_scale; } float AnimatedSprite2D::get_playing_speed() const { if (!playing) { return 0; } return speed_scale * custom_speed_scale; } void AnimatedSprite2D::set_centered(bool p_center) { if (centered == p_center) { return; } centered = p_center; queue_redraw(); item_rect_changed(); } bool AnimatedSprite2D::is_centered() const { return centered; } void AnimatedSprite2D::set_offset(const Point2 &p_offset) { if (offset == p_offset) { return; } offset = p_offset; queue_redraw(); item_rect_changed(); } Point2 AnimatedSprite2D::get_offset() const { return offset; } void AnimatedSprite2D::set_flip_h(bool p_flip) { if (hflip == p_flip) { return; } hflip = p_flip; queue_redraw(); } bool AnimatedSprite2D::is_flipped_h() const { return hflip; } void AnimatedSprite2D::set_flip_v(bool p_flip) {
random
<|fim_prefix|>in_top, size_t margin_right, size_t margin_bottom, size_t ksize, int border_type) { CAROTENE_NS::Size2D sz(width, height); CAROTENE_NS::BORDER_MODE border = borderCV2Carotene(border_type); CAROTENE_NS::Margin mg(margin_left, margin_right, margin_top, margin_bottom); if (ksize == 3) { if ((depth != CV_8U) || (cn != 1)) return CV_HAL_ERROR_NOT_IMPLEMENTED; if (CAROTENE_NS::isGaussianBlur3x3MarginSupported(sz, border, mg)) { CAROTENE_NS::gaussianBlur3x3Margin(sz, src_data, src_step, dst_data, dst_step, border, 0, mg); return CV_HAL_ERROR_OK; } } else if (ksize == 5) { if (!CAROTENE_NS::isGaussianBlur5x5Supported(sz, cn, border)) return CV_HAL_ERROR_NOT_IMPLEMENTED; if (depth == CV_8U) { CAROTENE_NS::gaussianBlur5x5(sz, cn, (uint8_t*)src_data, src_step, (uint8_t*)dst_data, dst_step, border, 0, mg); return CV_HAL_ERROR_OK; } else if (depth == CV_16U) { CAROTENE_NS::gaussianBlur5x5(sz, cn, (uint16_t*)src_data, src_step, (uint16_t*)dst_data, dst_step, border, 0, mg); return CV_HAL_ERROR_OK; } else if (depth == CV_16S) { 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, <|fim_suffix|>, 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 <|fim_middle|>size_t prev_data_step
in_top, size_t margin_right, size_t margin_bottom, size_t ksize, int border_type) { CAROTENE_NS::Size2D sz(width, height); CAROTENE_NS::BORDER_MODE border = borderCV2Carotene(border_type); CAROTENE_NS::Margin mg(margin_left, margin_right, margin_top, margin_bottom); if (ksize == 3) { if ((depth != CV_8U) || (cn != 1)) return CV_HAL_ERROR_NOT_IMPLEMENTED; if (CAROTENE_NS::isGaussianBlur3x3MarginSupported(sz, border, mg)) { CAROTENE_NS::gaussianBlur3x3Margin(sz, src_data, src_step, dst_data, dst_step, border, 0, mg); return CV_HAL_ERROR_OK; } } else if (ksize == 5) { if (!CAROTENE_NS::isGaussianBlur5x5Supported(sz, cn, border)) return CV_HAL_ERROR_NOT_IMPLEMENTED; if (depth == CV_8U) { CAROTENE_NS::gaussianBlur5x5(sz, cn, (uint8_t*)src_data, src_step, (uint8_t*)dst_data, dst_step, border, 0, mg); return CV_HAL_ERROR_OK; } else if (depth == CV_16U) { CAROTENE_NS::gaussianBlur5x5(sz, cn, (uint16_t*)src_data, src_step, (uint16_t*)dst_data, dst_step, border, 0, mg); return CV_HAL_ERROR_OK; } else if (depth == CV_16S) { 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 (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) { WARN_PRINT("Setting autoplay after the node has been added to the scene has no effect."); } autoplay = p_name; } String AnimatedSprite2D::get_autoplay() const { return autoplay; } void AnimatedSprite2D::play(const StringName &p_name, float p_custom_scale, bool p_from_end) { StringName name = p_name; if (name == StringName()) { name = animation; } ERR_FAIL_COND_MSG(frames.is_null(), vformat("There is no animation with name '%s'.", name)); ERR_FAIL_COND_MSG(!frames->get_animation_names().has(name), vformat("There is no animation with name '%s'.", name)); if (frames->get_frame_count(name) == 0) { return; } playing = true; custom_speed_scale = p_custom_scale; if (name != animation) { animation = name; int end_frame = MAX(0, frames->get_frame_count(animation) - 1); 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); }<|fim_suffix|>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<|fim_middle|> double AnimatedSprite2D::_get_frame_duration() { if (frames.is_valid() && frames->has_animation(animation)) { return frames->get_frame_duration(animation, frame); } return 1.0; }
if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) { WARN_PRINT("Setting autoplay after the node has been added to the scene has no effect."); } autoplay = p_name; } String AnimatedSprite2D::get_autoplay() const { return autoplay; } void AnimatedSprite2D::play(const StringName &p_name, float p_custom_scale, bool p_from_end) { StringName name = p_name; if (name == StringName()) { name = animation; } ERR_FAIL_COND_MSG(frames.is_null(), vformat("There is no animation with name '%s'.", name)); ERR_FAIL_COND_MSG(!frames->get_animation_names().has(name), vformat("There is no animation with name '%s'.", name)); if (frames->get_frame_count(name) == 0) { return; } playing = true; custom_speed_scale = p_custom_scale; if (name != animation) { animation = name; int end_frame = MAX(0, frames->get_frame_count(animation) - 1); 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
random
<|fim_prefix|>id 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"]); } 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, <|fim_suffix|>) { 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 <|fim_middle|>int info_count
id 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"]); } 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
ast_based
<|fim_prefix|> 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"); } curlcode = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } std::string cookiefile = curl_cookiefile; if (!cookiefile.empty()) { curlcode = curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiefile.c_str()); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_USERAGENT, "Tesseract OCR"); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_perform(curl); if (curlcode != CURLE_OK) { return error("curl_easy_perform"); } curl_easy_cleanup(curl); data = reinterpret_cast<const l_uint8 *>(buf.data()); } #else fprintf(stderr, "Error, this tesseract has no URL support\n"); return false; #endif } else { // Check whether the input file can be read. if (FILE *file = fopen(filename, "rb")) { fclose(file); } else {<|fim_suffix|> (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,<|fim_middle|> fprintf(stderr, "Error, cannot read input file %s: %s\n", filename, strerror(errno)); return false; } } // Here is our autodetection int format; int r =
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"); } curlcode = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } std::string cookiefile = curl_cookiefile; if (!cookiefile.empty()) { curlcode = curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiefile.c_str()); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_USERAGENT, "Tesseract OCR"); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_perform(curl); if (curlcode != CURLE_OK) { return error("curl_easy_perform"); } curl_easy_cleanup(curl); data = reinterpret_cast<const l_uint8 *>(buf.data()); } #else fprintf(stderr, "Error, this tesseract has no URL support\n"); return false; #endif } else { // Check whether the input file can be read. if (FILE *file = fopen(filename, "rb")) { 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,
random
<|fim_prefix|>ocus(1, win_id); accesskit_tree_update_set_tree(tree_update, accesskit_tree_new(win_id)); accesskit_tree_update_push_node(tree_update, win_id, win_node); return tree_update; } RID AccessibilityDriverAccessKit::accessibility_create_element(DisplayServer::WindowID p_window_id, DisplayServer::AccessibilityRole p_role) { AccessibilityElement *ae = memnew(AccessibilityElement); ae->role = _accessibility_role(p_role); ae->window_id = p_window_id; RID rid = rid_owner.make_rid(ae); return rid; } RID AccessibilityDriverAccessKit::accessibility_create_sub_element(const RID &p_parent_rid, DisplayServer::AccessibilityRole p_role, int p_insert_pos) { AccessibilityElement *parent_ae = rid_owner.get_or_null(p_parent_rid); ERR_FAIL_NULL_V(parent_ae, RID()); WindowData *wd = windows.getptr(parent_ae->window_id); ERR_FAIL_NULL_V(wd, RID()); AccessibilityElement *ae = memnew(AccessibilityElement); ae->role = _accessibility_role(p_role); ae->window_id = parent_ae->window_id; ae->parent = p_parent_rid; ae->node = accesskit_node_new(ae->role); RID rid = rid_owner.make_rid(ae); if (p_insert_pos == -1) { parent_ae->children.push_back(rid); } else { parent_ae->children.insert(p_insert_pos, rid); } wd->update.insert(rid); return rid; } RID AccessibilityDriverAccessKit::accessibility_create_sub_text_edit_elements(const RID &p_parent_rid, const RID &p_shaped_text, float p_min_height, int p_insert_pos) { AccessibilityElement *parent_ae = rid_owner.get_or_null(p_parent_rid); ERR_FAIL_NULL_V(parent_ae, RID()); WindowData *wd = windows.getptr(parent_ae->window_id); ERR_FAIL_NULL_V(wd, RID()); AccessibilityElement *root_ae = memnew(AccessibilityElement); root_ae->role = ACCESSKIT_ROLE_GENERIC_CONTAINER; root_ae->window_id = parent_ae->window_id; root_ae->parent = p_parent_rid; root_ae->node = accesskit_node_new(root_ae->role); RID root_rid = rid_owner.make_rid(root_ae); if (p_insert_pos == -1) { parent_ae->children.push_back(root_rid); } else { <|fim_suffix|> } wd->update.insert(root_rid); float text_width = 0; float text_height = p_min_height; Vector<int32_t> words; int64_t run_count = 0; // Note: runs in visual order. const Glyph *gl = nullptr; int64_t gl_count = 0; int64_t gl_index = 0; float run_off_x = 0.0; Vector2i full_range; if (p_shaped_text.is_valid()) { text_width = TS->shaped_text_get_size(p_shaped_text).x; text_height = MAX(text_height, TS->shaped_text_get_size(p_shaped_text).y); words = TS->shaped_text_get_word_breaks(p_shaped_text); run_count = TS->shaped_get_run_count(p_shaped_text); gl = TS->shaped_text_get_glyphs(p_shaped_text); gl_count = TS->shaped_text_get_glyph_count(p_shaped_text); full_range = TS->shaped_text_get_range(p_shaped_text); } accesskit_rect root_rect; root_rect.x0 = 0; root_rect.y0 = 0; root_rect.x1 = text_width; root_rect.y1 = MAX(p_min_height, text_height); accesskit_node_set_bounds(root_ae->node, root_rect); // 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) { <|fim_middle|>parent_ae->children.insert(p_insert_pos, root_rid);
ocus(1, win_id); accesskit_tree_update_set_tree(tree_update, accesskit_tree_new(win_id)); accesskit_tree_update_push_node(tree_update, win_id, win_node); return tree_update; } RID AccessibilityDriverAccessKit::accessibility_create_element(DisplayServer::WindowID p_window_id, DisplayServer::AccessibilityRole p_role) { AccessibilityElement *ae = memnew(AccessibilityElement); ae->role = _accessibility_role(p_role); ae->window_id = p_window_id; RID rid = rid_owner.make_rid(ae); return rid; } RID AccessibilityDriverAccessKit::accessibility_create_sub_element(const RID &p_parent_rid, DisplayServer::AccessibilityRole p_role, int p_insert_pos) { AccessibilityElement *parent_ae = rid_owner.get_or_null(p_parent_rid); ERR_FAIL_NULL_V(parent_ae, RID()); WindowData *wd = windows.getptr(parent_ae->window_id); ERR_FAIL_NULL_V(wd, RID()); AccessibilityElement *ae = memnew(AccessibilityElement); ae->role = _accessibility_role(p_role); ae->window_id = parent_ae->window_id; ae->parent = p_parent_rid; ae->node = accesskit_node_new(ae->role); RID rid = rid_owner.make_rid(ae); if (p_insert_pos == -1) { parent_ae->children.push_back(rid); } else { parent_ae->children.insert(p_insert_pos, rid); } wd->update.insert(rid); return rid; } RID AccessibilityDriverAccessKit::accessibility_create_sub_text_edit_elements(const RID &p_parent_rid, const RID &p_shaped_text, float p_min_height, int p_insert_pos) { AccessibilityElement *parent_ae = rid_owner.get_or_null(p_parent_rid); ERR_FAIL_NULL_V(parent_ae, RID()); WindowData *wd = windows.getptr(parent_ae->window_id); ERR_FAIL_NULL_V(wd, RID()); AccessibilityElement *root_ae = memnew(AccessibilityElement); root_ae->role = ACCESSKIT_ROLE_GENERIC_CONTAINER; root_ae->window_id = parent_ae->window_id; root_ae->parent = p_parent_rid; root_ae->node = accesskit_node_new(root_ae->role); RID root_rid = rid_owner.make_rid(root_ae); if (p_insert_pos == -1) { parent_ae->children.push_back(root_rid); } else {
parent_ae->children.insert(p_insert_pos, root_rid);
} wd->update.insert(root_rid); float text_width = 0; float text_height = p_min_height; Vector<int32_t> words; int64_t run_count = 0; // Note: runs in visual order. const Glyph *gl = nullptr; int64_t gl_count = 0; int64_t gl_index = 0; float run_off_x = 0.0; Vector2i full_range; if (p_shaped_text.is_valid()) { text_width = TS->shaped_text_get_size(p_shaped_text).x; text_height = MAX(text_height, TS->shaped_text_get_size(p_shaped_text).y); words = TS->shaped_text_get_word_breaks(p_shaped_text); run_count = TS->shaped_get_run_count(p_shaped_text); gl = TS->shaped_text_get_glyphs(p_shaped_text); gl_count = TS->shaped_text_get_glyph_count(p_shaped_text); full_range = TS->shaped_text_get_range(p_shaped_text); } accesskit_rect root_rect; root_rect.x0 = 0; root_rect.y0 = 0; root_rect.x1 = text_width; root_rect.y1 = MAX(p_min_height, text_height); accesskit_node_set_bounds(root_ae->node, root_rect); // 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) {
ast_based
<|fim_prefix|> 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); } } <|fim_suffix|> 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)) {<|fim_middle|>void AccessibilityDriverAccessKit::accessibility_update_set_color_value(const RID &p_id, const Color &p_color) {
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 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)) {
random
<|fim_prefix|> 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 (box_selecting_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) { if (box_selecting) { // Do actual select. if (!box_selecting_add) { _clear_selection(); } Vector2 bs_from = box_selection_from;<|fim_suffix|> bool track_set = false; int j = 0; for (int i = 0; i < edit_points.size(); i++) { if (edit_points[i].point_rect.intersects(rect)) { _select_at_anim(animation, edit_points[i].track, animation->track_get_key_time(edit_points[i].track, edit_points[i].key), j == 0 && !box_selecting_add); if (!track_set) { track_set = true; set_animation_and_track(animation, edit_points[i].track, read_only); } j++; } } } else { _clear_selection(); // Clicked and nothing happened, so clear the selection. // Select by clicking on curve. int track_count = animation->get_track_count(); real_t animation_length = animation->get_length(); animation->set_length(real_t(INT_MAX)); // bezier_track_interpolate doesn't find keys if they exist beyond anim length. real_t time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value(); for (int i = 0; i < track_count; ++i) { if (animation->track_get_type(i) != Animation::TrackType::TYPE_BEZIER || hidden_tracks.has(i) || locked_tracks.has(i)) { continue; } float track_h = animation->bezier_track_interpolate(i, time); float track_height = _bezier_h_to_pixel(track_h); if (std::abs(mb->get_position().y - track_height) < 10) { set_animation_and_track(animation, i, read_only); break; } } animation->set_length(animation_length); } box_selecting_attempt = false; box_selecting = false; queue_redraw(); } if (moving_selection_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) { if (!read_only) { if (moving_selection && (std::abs(moving_selection_offset.x) > CMP_EPSILON || std::abs(moving_selection_offset.y) > CMP_EPSILON)) { // Commit it. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Move Bezier Points")); List<AnimMoveRestore> to_restore;<|fim_middle|> 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); } Rect2 rect(bs_from, bs_to - bs_from);
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 (box_selecting_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) { if (box_selecting) { // Do actual select. if (!box_selecting_add) { _clear_selection(); } 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); } Rect2 rect(bs_from, bs_to - bs_from);
bool track_set = false; int j = 0; for (int i = 0; i < edit_points.size(); i++) { if (edit_points[i].point_rect.intersects(rect)) { _select_at_anim(animation, edit_points[i].track, animation->track_get_key_time(edit_points[i].track, edit_points[i].key), j == 0 && !box_selecting_add); if (!track_set) { track_set = true; set_animation_and_track(animation, edit_points[i].track, read_only); } j++; } } } else { _clear_selection(); // Clicked and nothing happened, so clear the selection. // Select by clicking on curve. int track_count = animation->get_track_count(); real_t animation_length = animation->get_length(); animation->set_length(real_t(INT_MAX)); // bezier_track_interpolate doesn't find keys if they exist beyond anim length. real_t time = ((mb->get_position().x - limit) / timeline->get_zoom_scale()) + timeline->get_value(); for (int i = 0; i < track_count; ++i) { if (animation->track_get_type(i) != Animation::TrackType::TYPE_BEZIER || hidden_tracks.has(i) || locked_tracks.has(i)) { continue; } float track_h = animation->bezier_track_interpolate(i, time); float track_height = _bezier_h_to_pixel(track_h); if (std::abs(mb->get_position().y - track_height) < 10) { set_animation_and_track(animation, i, read_only); break; } } animation->set_length(animation_length); } box_selecting_attempt = false; box_selecting = false; queue_redraw(); } if (moving_selection_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) { if (!read_only) { if (moving_selection && (std::abs(moving_selection_offset.x) > CMP_EPSILON || std::abs(moving_selection_offset.y) > CMP_EPSILON)) { // Commit it. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Move Bezier Points")); List<AnimMoveRestore> to_restore;
random
<|fim_prefix|> ERR_FAIL_COND_V_MSG(!E, nullptr, vformat("Failed to retrieve non-existent singleton '%s'.", p_name)); #ifdef TOOLS_ENABLED if (!is_editor_hint() && is_singleton_editor_only(p_name)) { ERR_FAIL_V_MSG(nullptr, vformat("Can't retrieve singleton '%s' outside of editor.", p_name)); } #endif return E->value; } bool Engine::is_singleton_user_created(const StringName &p_name) const { ERR_FAIL_COND_V(!singleton_ptrs.has(p_name), false); for (const Singleton &E : singletons) { if (E.name == p_name && E.user_created) { return true; } } return false; } bool Engine::is_singleton_editor_only(const StringName &p_name) const { ERR_FAIL_COND_V(!singleton_ptrs.has(p_name), false); for (const Singleton &E : singletons) { if (E.name == p_name && E.editor_only) { return true; } } return false; } void Engine::remove_singleton(const StringName &p_name) { ERR_FAIL_COND(!singleton_ptrs.has(p_name)); for (List<Singleton>::Element *E = singletons.front(); E; E = E->next()) { if (E->get().name == p_name) { singletons.erase(E); singleton_ptrs.erase(p_name); return; } } } bool Engine::has_singleton(const StringName &p_name) const { return singleton_ptrs.has(p_name); } void Engine::get_singletons(List<Singleton> *p_singletons) { for (const Singleton &E : singletons) { #ifdef TOOLS_ENABLED if (!is_editor_hint() && E.editor_only) { continue; } #endif p_singletons->push_back(E); } } String Engine::get_write_movie_path() const { return write_movie_path; } void Engine::set_write_movie_path(const String &p_path) { write_movie_path = p_path; } void Engine::set_shader_cache_path(const String &p_path) { shader_cache_path = p_path; } String Engine::get_shader_cache_path() const { return shader_cache_path; } Engine *Engine::get_singleton() { return singleton; } bool Engine::notify_frame_server_synced() { frame_server_synced = true; return server_syncs > SERVER_SYNC_FRAME_COUNT_WARNING; }<|fim_suffix|>void Engine::set_embedded_in_editor(bool p_enabled) { embedded_in_editor = p_enabled; } bool Engine::is_embedded_in_editor() const { return embedded_in_editor; } Engine::Engine() { singleton = this; } Engine::~Engine() { if (singleton == this) { singleton = nullptr; } } Engine::Singleton::Singleton(const StringName &p_name, Object *p_ptr, const StringName &p_class_name) : name(p_name), ptr(p_ptr), class_name(p_class_name) { #ifdef DEBUG_ENABLED RefCounted *rc = Object::cast_to<RefCounted>(p_ptr); if (rc && !rc->is_referenced()) { WARN_PRINT("You must use Ref<> to ensure the lifetime of a RefCounted object intended to be used as a singleton."); } #endif } <|fim_middle|> void Engine::set_freeze_time_scale(bool p_frozen) { freeze_time_scale = p_frozen; }
ERR_FAIL_COND_V_MSG(!E, nullptr, vformat("Failed to retrieve non-existent singleton '%s'.", p_name)); #ifdef TOOLS_ENABLED if (!is_editor_hint() && is_singleton_editor_only(p_name)) { ERR_FAIL_V_MSG(nullptr, vformat("Can't retrieve singleton '%s' outside of editor.", p_name)); } #endif return E->value; } bool Engine::is_singleton_user_created(const StringName &p_name) const { ERR_FAIL_COND_V(!singleton_ptrs.has(p_name), false); for (const Singleton &E : singletons) { if (E.name == p_name && E.user_created) { return true; } } return false; } bool Engine::is_singleton_editor_only(const StringName &p_name) const { ERR_FAIL_COND_V(!singleton_ptrs.has(p_name), false); for (const Singleton &E : singletons) { if (E.name == p_name && E.editor_only) { return true; } } return false; } void Engine::remove_singleton(const StringName &p_name) { ERR_FAIL_COND(!singleton_ptrs.has(p_name)); for (List<Singleton>::Element *E = singletons.front(); E; E = E->next()) { if (E->get().name == p_name) { singletons.erase(E); singleton_ptrs.erase(p_name); return; } } } bool Engine::has_singleton(const StringName &p_name) const { return singleton_ptrs.has(p_name); } void Engine::get_singletons(List<Singleton> *p_singletons) { for (const Singleton &E : singletons) { #ifdef TOOLS_ENABLED if (!is_editor_hint() && E.editor_only) { continue; } #endif p_singletons->push_back(E); } } String Engine::get_write_movie_path() const { return write_movie_path; } void Engine::set_write_movie_path(const String &p_path) { write_movie_path = p_path; } void Engine::set_shader_cache_path(const String &p_path) { shader_cache_path = p_path; } String Engine::get_shader_cache_path() const { return shader_cache_path; } Engine *Engine::get_singleton() { return singleton; } bool Engine::notify_frame_server_synced() { frame_server_synced = true; return server_syncs > SERVER_SYNC_FRAME_COUNT_WARNING; }
void Engine::set_freeze_time_scale(bool p_frozen) { freeze_time_scale = p_frozen; }
void Engine::set_embedded_in_editor(bool p_enabled) { embedded_in_editor = p_enabled; } bool Engine::is_embedded_in_editor() const { return embedded_in_editor; } Engine::Engine() { singleton = this; } Engine::~Engine() { if (singleton == this) { singleton = nullptr; } } Engine::Singleton::Singleton(const StringName &p_name, Object *p_ptr, const StringName &p_class_name) : name(p_name), ptr(p_ptr), class_name(p_class_name) { #ifdef DEBUG_ENABLED RefCounted *rc = Object::cast_to<RefCounted>(p_ptr); if (rc && !rc->is_referenced()) { WARN_PRINT("You must use Ref<> to ensure the lifetime of a RefCounted object intended to be used as a singleton."); } #endif }
random
<|fim_prefix|> } showOverlayMessage(cv::format("Frame %zu is worst", worstElemIndex + 1)); if(mCalibData->allFrames.size()) mCalibData->allFrames.erase(mCalibData->allFrames.begin() + worstElemIndex); if(mCalibData->imagePoints.size()) { mCalibData->imagePoints.erase(mCalibData->imagePoints.begin() + worstElemIndex); mCalibData->objectPoints.erase(mCalibData->objectPoints.begin() + worstElemIndex); if (mCalibData->allCharucoCorners.size()) { mCalibData->allCharucoCorners.erase(mCalibData->allCharucoCorners.begin() + worstElemIndex); mCalibData->allCharucoIds.erase(mCalibData->allCharucoIds.begin() + worstElemIndex); } } cv::Mat newErrorsVec = cv::Mat((int)numberOfFrames - 1, 1, CV_64F); std::copy(mCalibData->perViewErrors.ptr<double>(0), mCalibData->perViewErrors.ptr<double>((int)worstElemIndex), newErrorsVec.ptr<double>(0)); if((int)worstElemIndex < (int)numberOfFrames-1) { std::copy(mCalibData->perViewErrors.ptr<double>((int)worstElemIndex + 1), mCalibData->perViewErrors.ptr<double>((int)numberOfFrames), newErrorsVec.ptr<double>((int)worstElemIndex)); } mCalibData->perViewErrors = 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;<|fim_suffix|> 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;<|fim_middle|> mCalibData->distCoeffs = (mParamsStack.top()).distCoeffs;
} showOverlayMessage(cv::format("Frame %zu is worst", worstElemIndex + 1)); if(mCalibData->allFrames.size()) mCalibData->allFrames.erase(mCalibData->allFrames.begin() + worstElemIndex); if(mCalibData->imagePoints.size()) { mCalibData->imagePoints.erase(mCalibData->imagePoints.begin() + worstElemIndex); mCalibData->objectPoints.erase(mCalibData->objectPoints.begin() + worstElemIndex); if (mCalibData->allCharucoCorners.size()) { mCalibData->allCharucoCorners.erase(mCalibData->allCharucoCorners.begin() + worstElemIndex); mCalibData->allCharucoIds.erase(mCalibData->allCharucoIds.begin() + worstElemIndex); } } cv::Mat newErrorsVec = cv::Mat((int)numberOfFrames - 1, 1, CV_64F); std::copy(mCalibData->perViewErrors.ptr<double>(0), mCalibData->perViewErrors.ptr<double>((int)worstElemIndex), newErrorsVec.ptr<double>(0)); if((int)worstElemIndex < (int)numberOfFrames-1) { std::copy(mCalibData->perViewErrors.ptr<double>((int)worstElemIndex + 1), mCalibData->perViewErrors.ptr<double>((int)numberOfFrames), newErrorsVec.ptr<double>((int)worstElemIndex)); } mCalibData->perViewErrors = 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;
random
<|fim_prefix|> 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 = <|fim_suffix|>; } 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) { return; } if (frames.is_valid()) { frames->disconnect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); } stop(); frames = p_frames; if (frames.is_valid()) { frames->connect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); List<StringName> al; frames->get_animation_list(&al); if (al.is_empty()) { set_animation(StringName()); autoplay = String(); } else { if (!frames->has_animation(animation)) { set_animation(al.front()->get()); } if (!frames->has_animation(autoplay)) { autoplay = String(); } } } notify_property_list_changed(); queue_redraw(); update_configuration_warnings(); emit_signal("sprite_frames_changed"); } Ref<SpriteFrames> AnimatedSprite2D::get_sprite_frames() const { return frames; } void AnimatedSprite2D::set_frame(int p_frame) { set_frame_and_progress(p_frame, std::signbit(get_playing_speed()) ? 1.0 : 0.0); } int AnimatedSprite2D::get_frame() const { return frame; } void AnimatedSprite2D::set_frame_progress(real_t p_progress) { frame_progress = p_progress; } real_t AnimatedSprite2D::get_frame_progress() const { return frame_progress; } void AnimatedSprite2D::set_frame_and_progress(int p_frame, real_t p_progress) { if (frames.is_null()) { return; } bool has_animation = frames->has_animation(animation); int end_frame = has_animation ? MAX(0, frames->get_frame_count(animation) - 1) : 0; bool is_changed = frame != p_frame; if (p_frame < 0) { frame = 0; } else if (has_animation && p_frame > end_frame) { frame = end_frame; } else { frame = p<|fim_middle|>(ofs + Point2(0.5, 0.5)).floor()
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) { return; } if (frames.is_valid()) { frames->disconnect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); } stop(); frames = p_frames; if (frames.is_valid()) { frames->connect(CoreStringName(changed), callable_mp(this, &AnimatedSprite2D::_res_changed)); List<StringName> al; frames->get_animation_list(&al); if (al.is_empty()) { set_animation(StringName()); autoplay = String(); } else { if (!frames->has_animation(animation)) { set_animation(al.front()->get()); } if (!frames->has_animation(autoplay)) { autoplay = String(); } } } notify_property_list_changed(); queue_redraw(); update_configuration_warnings(); emit_signal("sprite_frames_changed"); } Ref<SpriteFrames> AnimatedSprite2D::get_sprite_frames() const { return frames; } void AnimatedSprite2D::set_frame(int p_frame) { set_frame_and_progress(p_frame, std::signbit(get_playing_speed()) ? 1.0 : 0.0); } int AnimatedSprite2D::get_frame() const { return frame; } void AnimatedSprite2D::set_frame_progress(real_t p_progress) { frame_progress = p_progress; } real_t AnimatedSprite2D::get_frame_progress() const { return frame_progress; } void AnimatedSprite2D::set_frame_and_progress(int p_frame, real_t p_progress) { if (frames.is_null()) { return; } bool has_animation = frames->has_animation(animation); int end_frame = has_animation ? MAX(0, frames->get_frame_count(animation) - 1) : 0; bool is_changed = frame != p_frame; if (p_frame < 0) { frame = 0; } else if (has_animation && p_frame > end_frame) { frame = end_frame; } else { frame = p
ast_based
<|fim_prefix|>/**************************************************************************/ /* engine.h */ /**************************************************************************/ /* 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 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;<|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 */
/**************************************************************************/ /* engine.h */ /**************************************************************************/ /* 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. */ /**************************************************************************/ #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;
random
<|fim_prefix|>} else { // Now run the main recognition. bool wait_for_text = true; GetBoolVariable("paragraph_text_based", &wait_for_text); if (!wait_for_text) { DetectParagraphs(false); } if (tesseract_->recog_all_words(page_res_, monitor, nullptr, nullptr, 0)) { if (wait_for_text) { DetectParagraphs(true); } } else { result = -1; } } return result; } // Takes ownership of the input pix. void TessBaseAPI::SetInputImage(Pix *pix) { tesseract_->set_pix_original(pix); } Pix *TessBaseAPI::GetInputImage() { return tesseract_->pix_original(); } const char *TessBaseAPI::GetInputName() { if (!input_file_.empty()) { return input_file_.c_str(); } return nullptr; } const char *TessBaseAPI::GetDatapath() { return tesseract_->datadir.c_str(); } int TessBaseAPI::GetSourceYResolution() { if (thresholder_ == nullptr) return -1; return thresholder_->GetSourceYResolution(); } // If flist exists, get data from there. Otherwise get data from buf. // Seems convoluted, but is the easiest way I know of to meet multiple // goals. Support streaming from stdin, and also work on platforms // lacking fmemopen. // TODO: check different logic for flist/buf and simplify. bool TessBaseAPI::ProcessPagesFileList(FILE *flist, std::string *buf, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer, int tessedit_page_number) { if (!flist && !buf) { return false; } unsigned page = (tessedit_page_number >= 0) ? tessedit_page_number : 0; char pagename[MAX_PATH]; std::vector<std::string> lines; if (!flist) { std::string line; for (const auto ch : *buf) { if (ch == '\n') { lines.push_back(line); line.clear(); } else { line.push_back(ch); } } if (!line.empty()) { // Add last line without terminating LF. lines.push_back(line); } if (<|fim_suffix|>) { 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, <|fim_middle|>lines.empty()
} else { // Now run the main recognition. bool wait_for_text = true; GetBoolVariable("paragraph_text_based", &wait_for_text); if (!wait_for_text) { DetectParagraphs(false); } if (tesseract_->recog_all_words(page_res_, monitor, nullptr, nullptr, 0)) { if (wait_for_text) { DetectParagraphs(true); } } else { result = -1; } } return result; } // Takes ownership of the input pix. void TessBaseAPI::SetInputImage(Pix *pix) { tesseract_->set_pix_original(pix); } Pix *TessBaseAPI::GetInputImage() { return tesseract_->pix_original(); } const char *TessBaseAPI::GetInputName() { if (!input_file_.empty()) { return input_file_.c_str(); } return nullptr; } const char *TessBaseAPI::GetDatapath() { return tesseract_->datadir.c_str(); } int TessBaseAPI::GetSourceYResolution() { if (thresholder_ == nullptr) return -1; return thresholder_->GetSourceYResolution(); } // If flist exists, get data from there. Otherwise get data from buf. // Seems convoluted, but is the easiest way I know of to meet multiple // goals. Support streaming from stdin, and also work on platforms // lacking fmemopen. // TODO: check different logic for flist/buf and simplify. bool TessBaseAPI::ProcessPagesFileList(FILE *flist, std::string *buf, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer, int tessedit_page_number) { if (!flist && !buf) { return false; } unsigned page = (tessedit_page_number >= 0) ? tessedit_page_number : 0; char pagename[MAX_PATH]; std::vector<std::string> lines; if (!flist) { std::string line; for (const auto ch : *buf) { if (ch == '\n') { lines.push_back(line); line.clear(); } else { line.push_back(ch); } } if (!line.empty()) { // 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,
ast_based
<|fim_prefix|>ceAgent* agent); namespace tfw_internal { #if defined(TF_ENABLE_ACTIVITY_WATCHER) // Records an activity start without checking whether the watcher is enabled. ActivityId RecordActivityStart(std::unique_ptr<Activity> activity); // Records an activity end without checking whether the activity_id is valid. void RecordActivityEnd(ActivityId activity_id); TF_EXPORT extern std::atomic<int> g_watcher_level; // Returns whether the activitity watcher is enabled. inline bool WatcherEnabled(int level = 1) { return g_watcher_level.load(std::memory_order_acquire) >= level; } #endif // NOTE: Borrowed from boost C++ libraries because std::is_invocable_r is not // available in Android NDK. template <typename R, typename F, typename... Args> struct is_invocable_r : std::is_constructible< std::function<R(Args...)>, std::reference_wrapper<typename std::remove_reference<F>::type>> {}; } // namespace tfw_internal template <typename F> constexpr bool is_activity_generator = tfw_internal::is_invocable_r<std::unique_ptr<Activity>, F>::value; // Records an activity explicitly. Useful when the start and end of an activity // happen in different threads. Generates the Activity only if activity // watching is enabled, useful for avoiding expensive operations when activity // watching is disabled. // Example Usage: // auto aid = ActivityStart([&]() { // return std::make_unique<Activity>( // op_name, category, // Activity::Attributes{{"key1", value1}, {"key2", value2}}); // }, /*level=*/2); // DoSomething(); // ActivityEnd(aid); template < typename ActivityGenerator, std::enable_if_t<is_activity_generator<ActivityGenerator>, bool> = true> inline ActivityId ActivityStart(ActivityGenerator&& gen, int level = 1) { #if defined(TF_ENABLE_ACTIVITY_WATCHER) if (TF_PREDICT_FALSE(tfw_internal::WatcherEnabled(level))) { return tfw_internal::RecordActivityStart( std::forward<ActivityGenerator>(gen)()); } #endif <|fim_suffix|> } inline void ActivityEnd(ActivityId id) { #if defined(TF_ENABLE_ACTIVITY_WATCHER) if (TF_PREDICT_FALSE(id != kActivityNotRecorded)) { tfw_internal::RecordActivityEnd(id); } #endif } // ActivityScope marks a scope as an activity and record it with a global // ActivityRecorder. // Example Usage: // { // ActivityScope activity_scope([&]() { // return std::make_unique<Activity>( // op_name, ActivityCategory::kMisc, // Activity::Attributes{{"key1", value1}, {"key2", value2}}); // }, /*level=*/2); // DoSomething(); // } class ActivityScope { public: template < typename ActivityGenerator, std::enable_if_t<is_activity_generator<ActivityGenerator>, bool> = true> explicit ActivityScope(ActivityGenerator&& gen, int level = 1) { activity_id_ = ActivityStart(std::forward<ActivityGenerator>(gen), level); } ActivityScope(ActivityScope&& activity) { activity_id_ = activity.activity_id_; activity.activity_id_ = kActivityNotRecorded; } ~ActivityScope() { ActivityEnd(activity_id_); } private: ActivityId activity_id_; ActivityScope(const ActivityScope&) = delete; void operator=(const ActivityScope&) = delete; }; } // namespace activity_watcher } // namespace tensorflow #endif // TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_ <|fim_middle|>return kActivityNotRecorded;
ceAgent* agent); namespace tfw_internal { #if defined(TF_ENABLE_ACTIVITY_WATCHER) // Records an activity start without checking whether the watcher is enabled. ActivityId RecordActivityStart(std::unique_ptr<Activity> activity); // Records an activity end without checking whether the activity_id is valid. void RecordActivityEnd(ActivityId activity_id); TF_EXPORT extern std::atomic<int> g_watcher_level; // Returns whether the activitity watcher is enabled. inline bool WatcherEnabled(int level = 1) { return g_watcher_level.load(std::memory_order_acquire) >= level; } #endif // NOTE: Borrowed from boost C++ libraries because std::is_invocable_r is not // available in Android NDK. template <typename R, typename F, typename... Args> struct is_invocable_r : std::is_constructible< std::function<R(Args...)>, std::reference_wrapper<typename std::remove_reference<F>::type>> {}; } // namespace tfw_internal template <typename F> constexpr bool is_activity_generator = tfw_internal::is_invocable_r<std::unique_ptr<Activity>, F>::value; // Records an activity explicitly. Useful when the start and end of an activity // happen in different threads. Generates the Activity only if activity // watching is enabled, useful for avoiding expensive operations when activity // watching is disabled. // Example Usage: // auto aid = ActivityStart([&]() { // return std::make_unique<Activity>( // op_name, category, // Activity::Attributes{{"key1", value1}, {"key2", value2}}); // }, /*level=*/2); // DoSomething(); // ActivityEnd(aid); template < typename ActivityGenerator, std::enable_if_t<is_activity_generator<ActivityGenerator>, bool> = true> inline ActivityId ActivityStart(ActivityGenerator&& gen, int level = 1) { #if defined(TF_ENABLE_ACTIVITY_WATCHER) if (TF_PREDICT_FALSE(tfw_internal::WatcherEnabled(level))) { return tfw_internal::RecordActivityStart( std::forward<ActivityGenerator>(gen)()); } #endif
return kActivityNotRecorded;
} inline void ActivityEnd(ActivityId id) { #if defined(TF_ENABLE_ACTIVITY_WATCHER) if (TF_PREDICT_FALSE(id != kActivityNotRecorded)) { tfw_internal::RecordActivityEnd(id); } #endif } // ActivityScope marks a scope as an activity and record it with a global // ActivityRecorder. // Example Usage: // { // ActivityScope activity_scope([&]() { // return std::make_unique<Activity>( // op_name, ActivityCategory::kMisc, // Activity::Attributes{{"key1", value1}, {"key2", value2}}); // }, /*level=*/2); // DoSomething(); // } class ActivityScope { public: template < typename ActivityGenerator, std::enable_if_t<is_activity_generator<ActivityGenerator>, bool> = true> explicit ActivityScope(ActivityGenerator&& gen, int level = 1) { activity_id_ = ActivityStart(std::forward<ActivityGenerator>(gen), level); } ActivityScope(ActivityScope&& activity) { activity_id_ = activity.activity_id_; activity.activity_id_ = kActivityNotRecorded; } ~ActivityScope() { ActivityEnd(activity_id_); } private: ActivityId activity_id_; ActivityScope(const ActivityScope&) = delete; void operator=(const ActivityScope&) = delete; }; } // namespace activity_watcher } // namespace tensorflow #endif // TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_
ast_based
<|fim_prefix|>me = t + (insert_pos - top_time); int existing_idx = animation->track_find_key(E->get().first, dst_time, Animation::FIND_MODE_APPROX); undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->get().first, dst_time, animation->track_get_key_value(E->get().first, E->get().second), animation->track_get_key_transition(E->get().first, E->get().second)); undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, dst_time); Pair<int, real_t> p; p.first = E->get().first; p.second = dst_time; new_selection_values.push_back(p); if (existing_idx != -1) { undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->get().first, dst_time, animation->track_get_key_value(E->get().first, existing_idx), animation->track_get_key_transition(E->get().first, existing_idx)); } } undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); // Reselect duplicated. int i = 0; for (const Pair<int, real_t> &E : new_selection_values) { undo_redo->add_do_method(this, "_select_at_anim", animation, E.first, E.second, i == 0); i++; } i = 0; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t time = animation->track_get_key_time(E->get().first, E->get().second); undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, time, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(); } void AnimationBezierTrackEdit::copy_selected_keys(bool p_cut) { if (selection.is_empty()) { return; } float top_time = 1e10; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { <|fim_suffix|> } RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo> keys; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { AnimationTrackEditor::SelectedKey sk; AnimationTrackEditor::KeyInfo ki; sk.track = E->get().first; sk.key = E->get().second; ki.pos = animation->track_get_key_time(E->get().first, E->get().second); keys.insert(sk, ki); } editor->_set_key_clipboard(selected_track, top_time, keys); if (p_cut) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Animation Cut Keys"), UndoRedo::MERGE_DISABLE, animation.ptr()); undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); int i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) { int track_idx = E->key().track; int key_idx = E->key().key; float time = E->value().pos; undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_time", track_idx, time); undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track_idx, time, animation->track_get_key_value(track_idx, key_idx), animation->track_get_key_transition(track_idx, key_idx)); undo_redo->add_undo_method(this, "_select_at_anim", animation, track_idx, time, i == 0); i++; } i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) { undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, E->value().pos, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_<|fim_middle|>float t = animation->track_get_key_time(E->get().first, E->get().second); if (t < top_time) { top_time = t; }
me = t + (insert_pos - top_time); int existing_idx = animation->track_find_key(E->get().first, dst_time, Animation::FIND_MODE_APPROX); undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->get().first, dst_time, animation->track_get_key_value(E->get().first, E->get().second), animation->track_get_key_transition(E->get().first, E->get().second)); undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, dst_time); Pair<int, real_t> p; p.first = E->get().first; p.second = dst_time; new_selection_values.push_back(p); if (existing_idx != -1) { undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->get().first, dst_time, animation->track_get_key_value(E->get().first, existing_idx), animation->track_get_key_transition(E->get().first, existing_idx)); } } undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); // Reselect duplicated. int i = 0; for (const Pair<int, real_t> &E : new_selection_values) { undo_redo->add_do_method(this, "_select_at_anim", animation, E.first, E.second, i == 0); i++; } i = 0; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { real_t time = animation->track_get_key_time(E->get().first, E->get().second); undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, time, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_redo->commit_action(); } void AnimationBezierTrackEdit::copy_selected_keys(bool p_cut) { if (selection.is_empty()) { return; } float top_time = 1e10; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
float t = animation->track_get_key_time(E->get().first, E->get().second); if (t < top_time) { top_time = t; }
} RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo> keys; for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { AnimationTrackEditor::SelectedKey sk; AnimationTrackEditor::KeyInfo ki; sk.track = E->get().first; sk.key = E->get().second; ki.pos = animation->track_get_key_time(E->get().first, E->get().second); keys.insert(sk, ki); } editor->_set_key_clipboard(selected_track, top_time, keys); if (p_cut) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Animation Cut Keys"), UndoRedo::MERGE_DISABLE, animation.ptr()); undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); int i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) { int track_idx = E->key().track; int key_idx = E->key().key; float time = E->value().pos; undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_time", track_idx, time); undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track_idx, time, animation->track_get_key_value(track_idx, key_idx), animation->track_get_key_transition(track_idx, key_idx)); undo_redo->add_undo_method(this, "_select_at_anim", animation, track_idx, time, i == 0); i++; } i = 0; for (RBMap<AnimationTrackEditor::SelectedKey, AnimationTrackEditor::KeyInfo>::Element *E = keys.back(); E; E = E->prev()) { undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, E->value().pos, 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->add_do_method(this, "queue_redraw"); undo_redo->add_undo_method(this, "queue_redraw"); undo_
ast_based
<|fim_prefix|>CV_HAL_ERROR_OK; } else { return CV_HAL_ERROR_UNKNOWN; } } #define TEGRA_SEPFILTERIMPL(context, src_data, src_step, dst_data, dst_step, width, height, full_width, full_height, offset_x, offset_y) \ ( \ context && CAROTENE_NS::isSeparableFilter3x3Supported(CAROTENE_NS::Size2D(width, height), ((SepFilterCtx*)context)->border, 3, 3, \ CAROTENE_NS::Margin(offset_x, full_width - width - offset_x, offset_y, full_height - height - offset_y)) ? \ CAROTENE_NS::SeparableFilter3x3(CAROTENE_NS::Size2D(width, height), \ src_data, src_step, \ (CAROTENE_NS::s16*)dst_data, dst_step, \ 3, 3, ((SepFilterCtx*)context)->kernelx_data, ((SepFilterCtx*)context)->kernely_data, \ ((SepFilterCtx*)context)->border, 0, \ CAROTENE_NS::Margin(offset_x, full_width - width - offset_x, offset_y, full_height - height - offset_y)), \ CV_HAL_ERROR_OK \ : CV_HAL_ERROR_NOT_IMPLEMENTED \ ) #undef cv_hal_sepFilterInit #define cv_hal_sepFilterInit TEGRA_SEPFILTERINIT #undef cv_hal_sepFilter #define cv_hal_sepFilter TEGRA_SEPFILTERIMPL #undef cv_hal_sepFilterFree #define cv_hal_sepFilterFree TEGRA_SEPFILTERFREE struct MorphCtx { int operation; int channels; CAROTENE_NS::Size2D ksize; int anchor_x, anchor_y; CAROTENE_NS::BORDER_MODE border; uchar borderValues[4]; }; inline int TEGRA_MORPHINIT(cvhalFilter2D **context, int operation, int src_type, int dst_type, int width, int height, int kernel_type, uchar *kernel_data, size_t kernel_step, int kernel_width, int kernel_height, int anchor_x, int anchor_y, int borderType, const double borderValue[4], int iterations, bool allowSubmatrix, bool allowInplace) { if(!context || !kernel_data || src_type != dst_type || <|fim_suffix|> != CV_8U || src_type < 0 || (src_type >> CV_CN_SHIFT) > 3 || width < kernel_width || height < kernel_height || allowSubmatrix || allowInplace || iterations != 1 || !CAROTENE_NS::isSupportedConfiguration()) return CV_HAL_ERROR_NOT_IMPLEMENTED; switch(CV_MAT_DEPTH(kernel_type)) { case CV_8U: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_16U: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (uint16_t*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_32S: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (int32_t*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_32F: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (float*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_64F: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (double*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; default: return CV_HAL_ERROR_NOT_IMPLEMENTED; } MorphCtx* ctx = new MorphCtx; if(!ctx) return CV_HAL_ERROR_UNKNOWN; ctx->channels = (src_type >> CV_CN_SHIFT) + 1; ctx->ksize.width = kernel_width; ctx->ksize.height = kernel_height; ctx->anchor_x = anchor_x; ctx->anchor_y = anchor_y; switch(operation) { case CV_HAL_MORPH_ERODE: case CV_HAL_MORPH_DILATE: ctx->operation = operation; break; default: delete ctx; <|fim_middle|>CV_MAT_DEPTH(src_type)
CV_HAL_ERROR_OK; } else { return CV_HAL_ERROR_UNKNOWN; } } #define TEGRA_SEPFILTERIMPL(context, src_data, src_step, dst_data, dst_step, width, height, full_width, full_height, offset_x, offset_y) \ ( \ context && CAROTENE_NS::isSeparableFilter3x3Supported(CAROTENE_NS::Size2D(width, height), ((SepFilterCtx*)context)->border, 3, 3, \ CAROTENE_NS::Margin(offset_x, full_width - width - offset_x, offset_y, full_height - height - offset_y)) ? \ CAROTENE_NS::SeparableFilter3x3(CAROTENE_NS::Size2D(width, height), \ src_data, src_step, \ (CAROTENE_NS::s16*)dst_data, dst_step, \ 3, 3, ((SepFilterCtx*)context)->kernelx_data, ((SepFilterCtx*)context)->kernely_data, \ ((SepFilterCtx*)context)->border, 0, \ CAROTENE_NS::Margin(offset_x, full_width - width - offset_x, offset_y, full_height - height - offset_y)), \ CV_HAL_ERROR_OK \ : CV_HAL_ERROR_NOT_IMPLEMENTED \ ) #undef cv_hal_sepFilterInit #define cv_hal_sepFilterInit TEGRA_SEPFILTERINIT #undef cv_hal_sepFilter #define cv_hal_sepFilter TEGRA_SEPFILTERIMPL #undef cv_hal_sepFilterFree #define cv_hal_sepFilterFree TEGRA_SEPFILTERFREE struct MorphCtx { int operation; int channels; CAROTENE_NS::Size2D ksize; int anchor_x, anchor_y; CAROTENE_NS::BORDER_MODE border; uchar borderValues[4]; }; inline int TEGRA_MORPHINIT(cvhalFilter2D **context, int operation, int src_type, int dst_type, int width, int height, int kernel_type, uchar *kernel_data, size_t kernel_step, int kernel_width, int kernel_height, int anchor_x, int anchor_y, int borderType, const double borderValue[4], int iterations, bool allowSubmatrix, bool allowInplace) { if(!context || !kernel_data || src_type != dst_type ||
CV_MAT_DEPTH(src_type)
!= CV_8U || src_type < 0 || (src_type >> CV_CN_SHIFT) > 3 || width < kernel_width || height < kernel_height || allowSubmatrix || allowInplace || iterations != 1 || !CAROTENE_NS::isSupportedConfiguration()) return CV_HAL_ERROR_NOT_IMPLEMENTED; switch(CV_MAT_DEPTH(kernel_type)) { case CV_8U: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_16U: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (uint16_t*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_32S: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (int32_t*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_32F: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (float*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_64F: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (double*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; default: return CV_HAL_ERROR_NOT_IMPLEMENTED; } MorphCtx* ctx = new MorphCtx; if(!ctx) return CV_HAL_ERROR_UNKNOWN; ctx->channels = (src_type >> CV_CN_SHIFT) + 1; ctx->ksize.width = kernel_width; ctx->ksize.height = kernel_height; ctx->anchor_x = anchor_x; ctx->anchor_y = anchor_y; switch(operation) { case CV_HAL_MORPH_ERODE: case CV_HAL_MORPH_DILATE: ctx->operation = operation; break; default: delete ctx;
ast_based
<|fim_prefix|> must call SetImage or TesseractRect before doing * any Recognize or Get* operation. */ void TessBaseAPI::Clear() { if (thresholder_ != nullptr) { thresholder_->Clear(); } ClearResults(); if (tesseract_ != nullptr) { SetInputImage(nullptr); } } /** * Close down tesseract and free up all memory. End() is equivalent to * destructing and reconstructing your TessBaseAPI. * Once End() has been used, none of the other API functions may be used * other than Init and anything declared above it in the class definition. */ void TessBaseAPI::End() { Clear(); delete thresholder_; thresholder_ = nullptr; delete page_res_; page_res_ = nullptr; delete block_list_; block_list_ = nullptr; if (paragraph_models_ != nullptr) { for (auto model : *paragraph_models_) { delete model; } delete paragraph_models_; paragraph_models_ = nullptr; } #ifndef DISABLED_LEGACY_ENGINE if (osd_tesseract_ == tesseract_) { osd_tesseract_ = nullptr; } delete osd_tesseract_; osd_tesseract_ = nullptr; delete equ_detect_; equ_detect_ = nullptr; #endif // ndef DISABLED_LEGACY_ENGINE delete tesseract_; tesseract_ = nullptr; input_file_.clear(); output_file_.clear(); datapath_.clear(); language_.clear(); } // Clear any library-level memory caches. // There are a variety of expensive-to-load constant data structures (mostly // language dictionaries) that are cached globally -- surviving the Init() // and End() of individual TessBaseAPI's. This function allows the clearing // of these caches. void TessBaseAPI::ClearPersistentCache() { Dict::GlobalDawgCache()->DeleteUnusedDawgs(); } /** * Check whether a word is valid according to Tesseract's language model * returns 0 if the word is invalid, non-zero if valid */ int TessBaseAPI::IsValidWord(const char *word) const { return tesseract_->getDict().valid_word(word); } // Returns true if utf8_character is defined in the UniCharset. bool TessBaseAPI::IsValidCharacter(<|fim_suffix|>) const { return tesseract_->unicharset.contains_unichar(utf8_character); } // TODO(rays) Obsolete this function and replace with a more aptly named // function that returns image coordinates rather than tesseract coordinates. bool TessBaseAPI::GetTextDirection(int *out_offset, float *out_slope) { const std::unique_ptr<const PageIterator> it(AnalyseLayout()); if (it == nullptr) { return false; } int x1, x2, y1, y2; it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2); // Calculate offset and slope (NOTE: Kind of ugly) if (x2 <= x1) { x2 = x1 + 1; } // Convert the point pair to slope/offset of the baseline (in image coords.) *out_slope = static_cast<float>(y2 - y1) / (x2 - x1); *out_offset = static_cast<int>(y1 - *out_slope * x1); // Get the y-coord of the baseline at the left and right edges of the // textline's bounding box. int left, top, right, bottom; if (!it->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom)) { return false; } int left_y = IntCastRounded(*out_slope * left + *out_offset); int right_y = IntCastRounded(*out_slope * right + *out_offset); // Shift the baseline down so it passes through the nearest bottom-corner // of the textline's bounding box. This is the difference between the y // at the lowest (max) edge of the box and the actual box bottom. *out_offset += bottom - std::max(left_y, right_y); // Switch back to bottom-up tesseract coordinates. Requires negation of // the slope and height - offset for the offset. *out_slope = -*out_slope; *out_offset = rect_height_ - *out_offset; return true; } /** Sets Dict::letter_is_okay_ function to point to the given function. */ void TessBaseAPI::SetDictFunc(DictFunc f) { if (tesseract_ != nullptr) { tesseract_->getDict().letter_is_okay_ = f; } } /** * Sets Dict::probability_in_context_ function to point to the given * function. * * @param f A single function that returns the probability of the current * "character" (in gene<|fim_middle|>const char *utf8_character
must call SetImage or TesseractRect before doing * any Recognize or Get* operation. */ void TessBaseAPI::Clear() { if (thresholder_ != nullptr) { thresholder_->Clear(); } ClearResults(); if (tesseract_ != nullptr) { SetInputImage(nullptr); } } /** * Close down tesseract and free up all memory. End() is equivalent to * destructing and reconstructing your TessBaseAPI. * Once End() has been used, none of the other API functions may be used * other than Init and anything declared above it in the class definition. */ void TessBaseAPI::End() { Clear(); delete thresholder_; thresholder_ = nullptr; delete page_res_; page_res_ = nullptr; delete block_list_; block_list_ = nullptr; if (paragraph_models_ != nullptr) { for (auto model : *paragraph_models_) { delete model; } delete paragraph_models_; paragraph_models_ = nullptr; } #ifndef DISABLED_LEGACY_ENGINE if (osd_tesseract_ == tesseract_) { osd_tesseract_ = nullptr; } delete osd_tesseract_; osd_tesseract_ = nullptr; delete equ_detect_; equ_detect_ = nullptr; #endif // ndef DISABLED_LEGACY_ENGINE delete tesseract_; tesseract_ = nullptr; input_file_.clear(); output_file_.clear(); datapath_.clear(); language_.clear(); } // Clear any library-level memory caches. // There are a variety of expensive-to-load constant data structures (mostly // language dictionaries) that are cached globally -- surviving the Init() // and End() of individual TessBaseAPI's. This function allows the clearing // of these caches. void TessBaseAPI::ClearPersistentCache() { Dict::GlobalDawgCache()->DeleteUnusedDawgs(); } /** * Check whether a word is valid according to Tesseract's language model * returns 0 if the word is invalid, non-zero if valid */ int TessBaseAPI::IsValidWord(const char *word) const { return tesseract_->getDict().valid_word(word); } // Returns true if utf8_character is defined in the UniCharset. bool TessBaseAPI::IsValidCharacter(
const char *utf8_character
) const { return tesseract_->unicharset.contains_unichar(utf8_character); } // TODO(rays) Obsolete this function and replace with a more aptly named // function that returns image coordinates rather than tesseract coordinates. bool TessBaseAPI::GetTextDirection(int *out_offset, float *out_slope) { const std::unique_ptr<const PageIterator> it(AnalyseLayout()); if (it == nullptr) { return false; } int x1, x2, y1, y2; it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2); // Calculate offset and slope (NOTE: Kind of ugly) if (x2 <= x1) { x2 = x1 + 1; } // Convert the point pair to slope/offset of the baseline (in image coords.) *out_slope = static_cast<float>(y2 - y1) / (x2 - x1); *out_offset = static_cast<int>(y1 - *out_slope * x1); // Get the y-coord of the baseline at the left and right edges of the // textline's bounding box. int left, top, right, bottom; if (!it->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom)) { return false; } int left_y = IntCastRounded(*out_slope * left + *out_offset); int right_y = IntCastRounded(*out_slope * right + *out_offset); // Shift the baseline down so it passes through the nearest bottom-corner // of the textline's bounding box. This is the difference between the y // at the lowest (max) edge of the box and the actual box bottom. *out_offset += bottom - std::max(left_y, right_y); // Switch back to bottom-up tesseract coordinates. Requires negation of // the slope and height - offset for the offset. *out_slope = -*out_slope; *out_offset = rect_height_ - *out_offset; return true; } /** Sets Dict::letter_is_okay_ function to point to the given function. */ void TessBaseAPI::SetDictFunc(DictFunc f) { if (tesseract_ != nullptr) { tesseract_->getDict().letter_is_okay_ = f; } } /** * Sets Dict::probability_in_context_ function to point to the given * function. * * @param f A single function that returns the probability of the current * "character" (in gene
ast_based
<|fim_prefix|>en_tracks.insert(updated_hidden_tracks[i]); } } } String AnimationBezierTrackEdit::get_tooltip(const Point2 &p_pos) const { return Control::get_tooltip(p_pos); } void AnimationBezierTrackEdit::_clear_selection() { selection.clear(); emit_signal(SNAME("clear_selection")); queue_redraw(); } void AnimationBezierTrackEdit::_change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Update Selected Key Handles"), UndoRedo::MERGE_DISABLE, animation.ptr()); for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { const IntPair track_key_pair = E->get(); undo_redo->add_undo_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_handle_mode(track_key_pair.first, track_key_pair.second), Animation::HANDLE_SET_MODE_NONE); undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_in_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_in_handle(track_key_pair.first, track_key_pair.second)); undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_out_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_out_handle(track_key_pair.first, track_key_pair.second)); undo_redo->add_do_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, p_mode, p_auto ? Animation::HANDLE_SET_MODE_AUTO : Animation::HANDLE_SET_MODE_RESET); } 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(); } void AnimationBezierTrackEdit::_clear_selection_for_anim(const Ref<Animation> &p_anim) { if (!(animation == p_anim) || !is_visible()) <|fim_suffix|> _clear_selection(); } void AnimationBezierTrackEdit::_select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single) { if (!(animation == p_anim) || !is_visible()) { return; } int idx = animation->track_find_key(p_track, p_pos, Animation::FIND_MODE_APPROX); ERR_FAIL_COND(idx < 0); selection.insert(IntPair(p_track, idx)); emit_signal(SNAME("select_key"), idx, p_single, p_track); queue_redraw(); } void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (panner->gui_input(p_event)) { accept_event(); return; } if (p_event->is_pressed()) { if (ED_IS_SHORTCUT("animation_editor/duplicate_selected_keys", p_event)) { if (!read_only) { duplicate_selected_keys(-1.0, false); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/cut_selected_keys", p_event)) { if (!read_only) { copy_selected_keys(true); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/copy_selected_keys", p_event)) { if (!read_only) { copy_selected_keys(false); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/paste_keys", p_event)) { if (!read_only) { paste_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<|fim_middle|>{ return; }
en_tracks.insert(updated_hidden_tracks[i]); } } } String AnimationBezierTrackEdit::get_tooltip(const Point2 &p_pos) const { return Control::get_tooltip(p_pos); } void AnimationBezierTrackEdit::_clear_selection() { selection.clear(); emit_signal(SNAME("clear_selection")); queue_redraw(); } void AnimationBezierTrackEdit::_change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Update Selected Key Handles"), UndoRedo::MERGE_DISABLE, animation.ptr()); for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { const IntPair track_key_pair = E->get(); undo_redo->add_undo_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_handle_mode(track_key_pair.first, track_key_pair.second), Animation::HANDLE_SET_MODE_NONE); undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_in_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_in_handle(track_key_pair.first, track_key_pair.second)); undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_out_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_out_handle(track_key_pair.first, track_key_pair.second)); undo_redo->add_do_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, p_mode, p_auto ? Animation::HANDLE_SET_MODE_AUTO : Animation::HANDLE_SET_MODE_RESET); } 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(); } void AnimationBezierTrackEdit::_clear_selection_for_anim(const Ref<Animation> &p_anim) { if (!(animation == p_anim) || !is_visible())
{ return; }
_clear_selection(); } void AnimationBezierTrackEdit::_select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single) { if (!(animation == p_anim) || !is_visible()) { return; } int idx = animation->track_find_key(p_track, p_pos, Animation::FIND_MODE_APPROX); ERR_FAIL_COND(idx < 0); selection.insert(IntPair(p_track, idx)); emit_signal(SNAME("select_key"), idx, p_single, p_track); queue_redraw(); } void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (panner->gui_input(p_event)) { accept_event(); return; } if (p_event->is_pressed()) { if (ED_IS_SHORTCUT("animation_editor/duplicate_selected_keys", p_event)) { if (!read_only) { duplicate_selected_keys(-1.0, false); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/cut_selected_keys", p_event)) { if (!read_only) { copy_selected_keys(true); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/copy_selected_keys", p_event)) { if (!read_only) { copy_selected_keys(false); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/paste_keys", p_event)) { if (!read_only) { paste_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
ast_based
<|fim_prefix|>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; <|fim_suffix|> 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"; #elif defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC) return "arm64"; #elif defined(__arm__) || defined(_M_ARM) return "arm32"; #elif defined(__riscv) return "rv64"; #elif defined(__powerpc64__) return "ppc64"; #elif defined(__loongarch64) return "loongarch64"; #elif defined(__wasm64__) return "wasm64"; #elif defined(__wasm32__) return "wasm32"; #endif } bool Engine::is_abort_on_gpu_errors_enabled() const { return abort_on_gpu_errors; } int32_t Engine::get_gpu_index() const { return gpu_idx; } bool Engine::is_validation_layers_enabled() const { return use_validation_layers; } bool Engine::is_generate_spirv_debug_info_enabled() const { return generate_spirv_debug_info; } bool Engine::is_extra_gpu_memory_tracking_enabled() const { r<|fim_middle|>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); }
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"; #elif defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC) return "arm64"; #elif defined(__arm__) || defined(_M_ARM) return "arm32"; #elif defined(__riscv) return "rv64"; #elif defined(__powerpc64__) return "ppc64"; #elif defined(__loongarch64) return "loongarch64"; #elif defined(__wasm64__) return "wasm64"; #elif defined(__wasm32__) return "wasm32"; #endif } bool Engine::is_abort_on_gpu_errors_enabled() const { return abort_on_gpu_errors; } int32_t Engine::get_gpu_index() const { return gpu_idx; } bool Engine::is_validation_layers_enabled() const { return use_validation_layers; } bool Engine::is_generate_spirv_debug_info_enabled() const { return generate_spirv_debug_info; } bool Engine::is_extra_gpu_memory_tracking_enabled() const { r
ast_based
<|fim_prefix|>eys_handle_mode(Animation::HandleMode p_mode, bool p_auto) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Update Selected Key Handles"), UndoRedo::MERGE_DISABLE, animation.ptr()); for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { const IntPair track_key_pair = E->get(); undo_redo->add_undo_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_handle_mode(track_key_pair.first, track_key_pair.second), Animation::HANDLE_SET_MODE_NONE); undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_in_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_in_handle(track_key_pair.first, track_key_pair.second)); undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_out_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_out_handle(track_key_pair.first, track_key_pair.second)); undo_redo->add_do_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, p_mode, p_auto ? Animation::HANDLE_SET_MODE_AUTO : Animation::HANDLE_SET_MODE_RESET); } 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(); } void AnimationBezierTrackEdit::_clear_selection_for_anim(const Ref<Animation> &p_anim) { if (!(animation == p_anim) || !is_visible()) { return; } _clear_selection(); } void AnimationBezierTrackEdit::_select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single) { if (!(animation == p_anim) || !is_visible()) { return; } int idx = animation->track_find_key(p_track, p_pos, Animation::FIND_MODE_APPROX); ERR_FAIL_COND(idx < 0); selection.insert(<|fim_suffix|>); emit_signal(SNAME("select_key"), idx, p_single, p_track); queue_redraw(); } void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (panner->gui_input(p_event)) { accept_event(); return; } if (p_event->is_pressed()) { if (ED_IS_SHORTCUT("animation_editor/duplicate_selected_keys", p_event)) { if (!read_only) { duplicate_selected_keys(-1.0, false); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/cut_selected_keys", p_event)) { if (!read_only) { copy_selected_keys(true); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/copy_selected_keys", p_event)) { if (!read_only) { copy_selected_keys(false); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/paste_keys", p_event)) { if (!read_only) { paste_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_<|fim_middle|>IntPair(p_track, idx)
eys_handle_mode(Animation::HandleMode p_mode, bool p_auto) { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); undo_redo->create_action(TTR("Update Selected Key Handles"), UndoRedo::MERGE_DISABLE, animation.ptr()); for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) { const IntPair track_key_pair = E->get(); undo_redo->add_undo_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_handle_mode(track_key_pair.first, track_key_pair.second), Animation::HANDLE_SET_MODE_NONE); undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_in_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_in_handle(track_key_pair.first, track_key_pair.second)); undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_out_handle", track_key_pair.first, track_key_pair.second, animation->bezier_track_get_key_out_handle(track_key_pair.first, track_key_pair.second)); undo_redo->add_do_method(editor, "_bezier_track_set_key_handle_mode", animation.ptr(), track_key_pair.first, track_key_pair.second, p_mode, p_auto ? Animation::HANDLE_SET_MODE_AUTO : Animation::HANDLE_SET_MODE_RESET); } 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(); } void AnimationBezierTrackEdit::_clear_selection_for_anim(const Ref<Animation> &p_anim) { if (!(animation == p_anim) || !is_visible()) { return; } _clear_selection(); } void AnimationBezierTrackEdit::_select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single) { if (!(animation == p_anim) || !is_visible()) { return; } int idx = animation->track_find_key(p_track, p_pos, Animation::FIND_MODE_APPROX); ERR_FAIL_COND(idx < 0); selection.insert(
IntPair(p_track, idx)
); emit_signal(SNAME("select_key"), idx, p_single, p_track); queue_redraw(); } void AnimationBezierTrackEdit::gui_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (panner->gui_input(p_event)) { accept_event(); return; } if (p_event->is_pressed()) { if (ED_IS_SHORTCUT("animation_editor/duplicate_selected_keys", p_event)) { if (!read_only) { duplicate_selected_keys(-1.0, false); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/cut_selected_keys", p_event)) { if (!read_only) { copy_selected_keys(true); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/copy_selected_keys", p_event)) { if (!read_only) { copy_selected_keys(false); } accept_event(); } if (ED_IS_SHORTCUT("animation_editor/paste_keys", p_event)) { if (!read_only) { paste_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_
ast_based
<|fim_prefix|>// // // Copyright 2015 gRPC authors. // // 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. // //<|fim_suffix|> #include <grpc/grpc.h> #include <grpcpp/completion_queue.h> #include <grpcpp/impl/call.h> #include <grpcpp/impl/channel_interface.h> #include <grpcpp/impl/grpc_library.h> #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:<|fim_middle|> #ifndef GRPCPP_CHANNEL_H #define GRPCPP_CHANNEL_H
// // // Copyright 2015 gRPC authors. // // 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 GRPCPP_CHANNEL_H #define GRPCPP_CHANNEL_H
#include <grpc/grpc.h> #include <grpcpp/completion_queue.h> #include <grpcpp/impl/call.h> #include <grpcpp/impl/channel_interface.h> #include <grpcpp/impl/grpc_library.h> #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:
random
<|fim_prefix|>, context->raw_deadline(), nullptr); } else { const ::std::string* host_str = nullptr; if (!context->authority_.empty()) { host_str = &context->authority_; } else if (!host_.empty()) { host_str = &host_; } grpc_slice method_slice = SliceFromArray(method.name(), strlen(method.name())); grpc_slice host_slice; if (host_str != nullptr) { host_slice = grpc::SliceFromCopiedString(*host_str); } c_call = grpc_channel_create_call( c_channel_, context->propagate_from_call_, context->propagation_options_.c_bitmask(), cq->cq(), method_slice, host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(), nullptr); grpc_slice_unref(method_slice); if (host_str != nullptr) { grpc_slice_unref(host_slice); } } grpc_census_call_set_context(c_call, context->census_context()); // ClientRpcInfo should be set before call because set_call also checks // whether the call has been cancelled, and if the call was cancelled, we // should notify the interceptors too. auto* info = context->set_client_rpc_info( method.name(), method.suffix_for_stats(), method.method_type(), this, interceptor_creators_, interceptor_pos); context->set_call(c_call, shared_from_this()); return grpc::internal::Call(c_call, this, cq, info); } grpc::internal::Call Channel::CreateCall( const grpc::internal::RpcMethod& method, grpc::ClientContext* context, CompletionQueue* cq) { return CreateCallInternal(method, context, cq, 0); } void Channel::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops, grpc::internal::Call* call) { ops->FillOps( call); // Make a copy of call. It's fine since Call just has pointers } void* Channel::RegisterMethod(const char* method) { return grpc_channel_register_call( c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr); } grpc_connectivity_state Channel::GetState(<|fim_suffix|>) { return grpc_channel_check_connectivity_state(c_channel_, try_to_connect); } namespace { class TagSaver final : public grpc::internal::CompletionQueueTag { public: explicit TagSaver(void* tag) : tag_(tag) {} ~TagSaver() override {} bool FinalizeResult(void** tag, bool* /*status*/) override { *tag = tag_; delete this; return true; } private: void* tag_; }; } // namespace void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline, grpc::CompletionQueue* cq, void* tag) { TagSaver* tag_saver = new TagSaver(tag); grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline, cq->cq(), tag_saver); } bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline) { grpc::CompletionQueue cq; bool ok = false; void* tag = nullptr; NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr); cq.Next(&tag, &ok); GRPC_CHECK_EQ(tag, nullptr); return ok; } namespace { class ShutdownCallback : public grpc_completion_queue_functor { public: ShutdownCallback() { functor_run = &ShutdownCallback::Run; // Set inlineable to true since this callback is trivial and thus does not // need to be run from the EventEngine (potentially triggering a thread // hop). This should only be used by internal callbacks like this and not by // user application code. inlineable = true; } // TakeCQ takes ownership of the cq into the shutdown callback // so that the shutdown callback will be responsible for destroying it void TakeCQ(grpc::CompletionQueue* cq) { cq_ = cq; } // The Run function will get invoked by the completion queue library // when the shutdown is actually complete static void Run(grpc_completion_queue_functor* cb, int) { auto* callback = static_cast<Shu<|fim_middle|>bool try_to_connect
, context->raw_deadline(), nullptr); } else { const ::std::string* host_str = nullptr; if (!context->authority_.empty()) { host_str = &context->authority_; } else if (!host_.empty()) { host_str = &host_; } grpc_slice method_slice = SliceFromArray(method.name(), strlen(method.name())); grpc_slice host_slice; if (host_str != nullptr) { host_slice = grpc::SliceFromCopiedString(*host_str); } c_call = grpc_channel_create_call( c_channel_, context->propagate_from_call_, context->propagation_options_.c_bitmask(), cq->cq(), method_slice, host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(), nullptr); grpc_slice_unref(method_slice); if (host_str != nullptr) { grpc_slice_unref(host_slice); } } grpc_census_call_set_context(c_call, context->census_context()); // ClientRpcInfo should be set before call because set_call also checks // whether the call has been cancelled, and if the call was cancelled, we // should notify the interceptors too. auto* info = context->set_client_rpc_info( method.name(), method.suffix_for_stats(), method.method_type(), this, interceptor_creators_, interceptor_pos); context->set_call(c_call, shared_from_this()); return grpc::internal::Call(c_call, this, cq, info); } grpc::internal::Call Channel::CreateCall( const grpc::internal::RpcMethod& method, grpc::ClientContext* context, CompletionQueue* cq) { return CreateCallInternal(method, context, cq, 0); } void Channel::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops, grpc::internal::Call* call) { ops->FillOps( call); // Make a copy of call. It's fine since Call just has pointers } void* Channel::RegisterMethod(const char* method) { return grpc_channel_register_call( c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr); } grpc_connectivity_state Channel::GetState(
bool try_to_connect
) { return grpc_channel_check_connectivity_state(c_channel_, try_to_connect); } namespace { class TagSaver final : public grpc::internal::CompletionQueueTag { public: explicit TagSaver(void* tag) : tag_(tag) {} ~TagSaver() override {} bool FinalizeResult(void** tag, bool* /*status*/) override { *tag = tag_; delete this; return true; } private: void* tag_; }; } // namespace void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline, grpc::CompletionQueue* cq, void* tag) { TagSaver* tag_saver = new TagSaver(tag); grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline, cq->cq(), tag_saver); } bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline) { grpc::CompletionQueue cq; bool ok = false; void* tag = nullptr; NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr); cq.Next(&tag, &ok); GRPC_CHECK_EQ(tag, nullptr); return ok; } namespace { class ShutdownCallback : public grpc_completion_queue_functor { public: ShutdownCallback() { functor_run = &ShutdownCallback::Run; // Set inlineable to true since this callback is trivial and thus does not // need to be run from the EventEngine (potentially triggering a thread // hop). This should only be used by internal callbacks like this and not by // user application code. inlineable = true; } // TakeCQ takes ownership of the cq into the shutdown callback // so that the shutdown callback will be responsible for destroying it void TakeCQ(grpc::CompletionQueue* cq) { cq_ = cq; } // The Run function will get invoked by the completion queue library // when the shutdown is actually complete static void Run(grpc_completion_queue_functor* cb, int) { auto* callback = static_cast<Shu
ast_based
<|fim_prefix|>den_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) { <|fim_suffix|> } } } 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_hand<|fim_middle|>if (!locked_tracks.has(i) && animation->track_get_type(i) == Animation::TrackType::TYPE_BEZIER) { set_animation_and_track(animation, i, read_only); break; }
den_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::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_hand
ast_based
<|fim_prefix|> 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<RunCompare>(); for (AccessibilityElement *text_element : text_elements) { RID rid = rid_owner.make_rid(text_element); root_ae->children.push_back(rid); wd->update.insert(rid); } return root_rid; } bool AccessibilityDriverAccessKit::accessibility_has_element(const RID &p_id) const { return rid_owner.owns(p_id); } void AccessibilityDriverAccessKit::_free_recursive(WindowData *p_wd, const RID &p_id) { if (p_wd && p_wd->update.has(p_id)) { p_wd->update.erase(p_id); } AccessibilityElement *ae = rid_owner.get_or_null(p_id); for (const RID &rid : ae->children) { _free_recursive(p_wd, rid); } if (ae->node) { accesskit_node_free(ae->node); } memdelete(ae); rid_owner.free(p_id); } void AccessibilityDriverAccessKit::accessibility_free_element(const RID &p_id) { ERR_FAIL_COND_MSG(in_accessibility_update, "Element can't be removed inside NOTIFICATION_ACCESSIBILITY_UPDATE notification."); AccessibilityElement *ae = rid_owner.get_or_null(p_id); if (ae) {<|fim_suffix|> _free_recursive(wd, p_id); } } void AccessibilityDriverAccessKit::accessibility_element_set_meta(const RID &p_id, const Variant &p_meta) { 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(); } <|fim_middle|> WindowData *wd = windows.getptr(ae->window_id); AccessibilityElement *parent_ae = rid_owner.get_or_null(ae->parent); if (parent_ae) { parent_ae->children.erase(p_id); }
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<RunCompare>(); for (AccessibilityElement *text_element : text_elements) { RID rid = rid_owner.make_rid(text_element); root_ae->children.push_back(rid); wd->update.insert(rid); } return root_rid; } bool AccessibilityDriverAccessKit::accessibility_has_element(const RID &p_id) const { return rid_owner.owns(p_id); } void AccessibilityDriverAccessKit::_free_recursive(WindowData *p_wd, const RID &p_id) { if (p_wd && p_wd->update.has(p_id)) { p_wd->update.erase(p_id); } AccessibilityElement *ae = rid_owner.get_or_null(p_id); for (const RID &rid : ae->children) { _free_recursive(p_wd, rid); } if (ae->node) { accesskit_node_free(ae->node); } memdelete(ae); rid_owner.free(p_id); } void AccessibilityDriverAccessKit::accessibility_free_element(const RID &p_id) { ERR_FAIL_COND_MSG(in_accessibility_update, "Element can't be removed inside NOTIFICATION_ACCESSIBILITY_UPDATE notification."); AccessibilityElement *ae = rid_owner.get_or_null(p_id); if (ae) {
WindowData *wd = windows.getptr(ae->window_id); AccessibilityElement *parent_ae = rid_owner.get_or_null(ae->parent); if (parent_ae) { parent_ae->children.erase(p_id); }
_free_recursive(wd, p_id); } } void AccessibilityDriverAccessKit::accessibility_element_set_meta(const RID &p_id, const Variant &p_meta) { 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(); }
random
<|fim_prefix|>in() + worstElemIndex); if(mCalibData->imagePoints.size()) { mCalibData->imagePoints.erase(mCalibData->imagePoints.begin() + worstElemIndex); mCalibData->objectPoints.erase(mCalibData->objectPoints.begin() + worstElemIndex); if (mCalibData->allCharucoCorners.size()) { mCalibData->allCharucoCorners.erase(mCalibData->allCharucoCorners.begin() + worstElemIndex); mCalibData->allCharucoIds.erase(mCalibData->allCharucoIds.begin() + worstElemIndex); } } cv::Mat newErrorsVec = cv::Mat((int)numberOfFrames - 1, 1, CV_64F); std::copy(mCalibData->perViewErrors.ptr<double>(0), mCalibData->perViewErrors.ptr<double>((int)worstElemIndex), newErrorsVec.ptr<double>(0)); if((int)worstElemIndex < (int)numberOfFrames-1) { std::copy(mCalibData->perViewErrors.ptr<double>((int)worstElemIndex + 1), mCalibData->perViewErrors.ptr<double>((int)numberOfFrames), newErrorsVec.ptr<double>((int)worstElemIndex)); } mCalibData->perViewErrors = 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; <|fim_suffix|>; } } 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_coef<|fim_middle|>mParamsStack.pop()
in() + worstElemIndex); if(mCalibData->imagePoints.size()) { mCalibData->imagePoints.erase(mCalibData->imagePoints.begin() + worstElemIndex); mCalibData->objectPoints.erase(mCalibData->objectPoints.begin() + worstElemIndex); if (mCalibData->allCharucoCorners.size()) { mCalibData->allCharucoCorners.erase(mCalibData->allCharucoCorners.begin() + worstElemIndex); mCalibData->allCharucoIds.erase(mCalibData->allCharucoIds.begin() + worstElemIndex); } } cv::Mat newErrorsVec = cv::Mat((int)numberOfFrames - 1, 1, CV_64F); std::copy(mCalibData->perViewErrors.ptr<double>(0), mCalibData->perViewErrors.ptr<double>((int)worstElemIndex), newErrorsVec.ptr<double>(0)); if((int)worstElemIndex < (int)numberOfFrames-1) { std::copy(mCalibData->perViewErrors.ptr<double>((int)worstElemIndex + 1), mCalibData->perViewErrors.ptr<double>((int)numberOfFrames), newErrorsVec.ptr<double>((int)worstElemIndex)); } mCalibData->perViewErrors = 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_coef
ast_based
<|fim_prefix|>ge_height_ - bottom, right, image_height_ - top, page_number); output_length += strlen(result + output_length); // Just in case... if (output_length + kMaxBytesPerLine > total_length) { break; } } } while (it->Next(RIL_SYMBOL)); delete it; return result; } /** * Conversion table for non-latin characters. * Maps characters out of the latin set into the latin set. * TODO(rays) incorporate this translation into unicharset. */ const int kUniChs[] = {0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0}; /** Latin chars corresponding to the unicode chars above. */ const int kLatinChs[] = {0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0}; /** * The recognized text is returned as a char* which is coded * as UNLV format Latin-1 with specific reject and suspect codes. * Returned string must be freed with the delete [] operator. */ char *TessBaseAPI::GetUNLVText() { if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) { return nullptr; } bool tilde_crunch_written = false; bool last_char_was_newline = true; bool last_char_was_tilde = false; int total_length = TextLength(nullptr); PAGE_RES_IT page_res_it(page_res_); 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++ = ' '; <|fim_suffix|> } 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_c<|fim_middle|>last_char_was_tilde = false;
ge_height_ - bottom, right, image_height_ - top, page_number); output_length += strlen(result + output_length); // Just in case... if (output_length + kMaxBytesPerLine > total_length) { break; } } } while (it->Next(RIL_SYMBOL)); delete it; return result; } /** * Conversion table for non-latin characters. * Maps characters out of the latin set into the latin set. * TODO(rays) incorporate this translation into unicharset. */ const int kUniChs[] = {0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0}; /** Latin chars corresponding to the unicode chars above. */ const int kLatinChs[] = {0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0}; /** * The recognized text is returned as a char* which is coded * as UNLV format Latin-1 with specific reject and suspect codes. * Returned string must be freed with the delete [] operator. */ char *TessBaseAPI::GetUNLVText() { if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) { return nullptr; } bool tilde_crunch_written = false; bool last_char_was_newline = true; bool last_char_was_tilde = false; int total_length = TextLength(nullptr); PAGE_RES_IT page_res_it(page_res_); 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_c
ast_based
<|fim_prefix|>s 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)) { LogWarning("banlist.dat ignored because it can only be read by " CLIENT_NAME " version 22.x. Remove %s to silence this warning.", fs::quoted(fs::PathToString(m_banlist_dat))); } // If the JSON banlist does not exist, then recreate it if (!fs::exists(m_banlist_json)) { return false; } std::map<std::string, common::SettingsValue> settings; std::vector<std::string> errors; if (!common::ReadSettings(m_banlist_json, settings, errors)) { for (const auto& err : errors) { LogWarning("Cannot load banlist %s: %s", fs::PathToString(m_banlist_json), err); } return false; } try { BanMapFromJson(settings[JSON_KEY], banSet); } catch (const std::runtime_error& e) { LogWarning("Cannot parse banlist %s: %s", <|fim_suffix|>, e.what()); return false; } return true; } bool DumpPeerAddresses(const ArgsManager& args, const AddrMan& addr) { const auto pathAddr = args.GetDataDirNet() / "peers.dat"; return SerializeFileDB("peers", pathAddr, addr); } void ReadFromStream(AddrMan& addr, DataStream& ssPeers) { DeserializeDB(ssPeers, addr, false); } util::Result<std::unique_ptr<AddrMan>> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args) { auto check_addrman = std::clamp<int32_t>(args.GetIntArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000); bool deterministic = HasTestOption(args, "addrman"); // use a deterministic addrman only for tests auto addrman{std::make_unique<AddrMan>(netgroupman, deterministic, /*consistency_check_ratio=*/check_addrman)}; const auto start{SteadyClock::now()}; const auto path_addr{args.GetDataDirNet() / "peers.dat"}; try { DeserializeFileDB(path_addr, *addrman); LogInfo("Loaded %i addresses from peers.dat %dms", addrman->Size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start)); } catch (const DbNotFoundError&) { // Addrman can be in an inconsistent state after failure, reset it addrman = std::make_unique<AddrMan>(netgroupman, deterministic, /*consistency_check_ratio=*/check_addrman); LogInfo("Creating peers.dat because the file was not found (%s)", fs::quoted(fs::PathToString(path_addr))); DumpPeerAddresses(args, *addrman); } catch (const InvalidAddrManVersionError&) { if (!RenameOver(path_addr, (fs::path)path_addr + ".bak")) { return util::Error{strprintf(_("Failed to rename invalid peers.dat file. Please move or delete it and try again."))}; } // Addrman can be in an inconsistent state after failure, reset it addrman = std::make_unique<AddrMan>(netgroupman, deterministic, /*consistency_check_ratio=*/check_addrman); LogWarning("Creating new peers.dat be<|fim_middle|>fs::PathToString(m_banlist_json)
s 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)) { LogWarning("banlist.dat ignored because it can only be read by " CLIENT_NAME " version 22.x. Remove %s to silence this warning.", fs::quoted(fs::PathToString(m_banlist_dat))); } // If the JSON banlist does not exist, then recreate it if (!fs::exists(m_banlist_json)) { return false; } std::map<std::string, common::SettingsValue> settings; std::vector<std::string> errors; if (!common::ReadSettings(m_banlist_json, settings, errors)) { for (const auto& err : errors) { LogWarning("Cannot load banlist %s: %s", fs::PathToString(m_banlist_json), err); } return false; } try { BanMapFromJson(settings[JSON_KEY], banSet); } catch (const std::runtime_error& e) { LogWarning("Cannot parse banlist %s: %s",
fs::PathToString(m_banlist_json)
, e.what()); return false; } return true; } bool DumpPeerAddresses(const ArgsManager& args, const AddrMan& addr) { const auto pathAddr = args.GetDataDirNet() / "peers.dat"; return SerializeFileDB("peers", pathAddr, addr); } void ReadFromStream(AddrMan& addr, DataStream& ssPeers) { DeserializeDB(ssPeers, addr, false); } util::Result<std::unique_ptr<AddrMan>> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args) { auto check_addrman = std::clamp<int32_t>(args.GetIntArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000); bool deterministic = HasTestOption(args, "addrman"); // use a deterministic addrman only for tests auto addrman{std::make_unique<AddrMan>(netgroupman, deterministic, /*consistency_check_ratio=*/check_addrman)}; const auto start{SteadyClock::now()}; const auto path_addr{args.GetDataDirNet() / "peers.dat"}; try { DeserializeFileDB(path_addr, *addrman); LogInfo("Loaded %i addresses from peers.dat %dms", addrman->Size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start)); } catch (const DbNotFoundError&) { // Addrman can be in an inconsistent state after failure, reset it addrman = std::make_unique<AddrMan>(netgroupman, deterministic, /*consistency_check_ratio=*/check_addrman); LogInfo("Creating peers.dat because the file was not found (%s)", fs::quoted(fs::PathToString(path_addr))); DumpPeerAddresses(args, *addrman); } catch (const InvalidAddrManVersionError&) { if (!RenameOver(path_addr, (fs::path)path_addr + ".bak")) { return util::Error{strprintf(_("Failed to rename invalid peers.dat file. Please move or delete it and try again."))}; } // Addrman can be in an inconsistent state after failure, reset it addrman = std::make_unique<AddrMan>(netgroupman, deterministic, /*consistency_check_ratio=*/check_addrman); LogWarning("Creating new peers.dat be
ast_based
<|fim_prefix|>ual 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, int dimensionality = -1, size_t *tokenCount = nullptr, bool doMean = true, bool atlas = false, EmbedCancelCallback *cancelCb = nullptr); // automatic prefix virtual void embed(const std::vector<std::string> &texts, float *embeddings, bool isRetrieval, int dimensionality = -1, size_t *tokenCount = nullptr, bool doMean = true, bool atlas = false); virtual void setThreadCount(int32_t n_threads) { (void)n_threads; } virtual int32_t threadCount() const { return 1; } const Implementation &implementation() const { return *m_implementation; } virtual std::vector<GPUDevice> availableGPUDevices(size_t memoryRequired) const { (void)memoryRequired; return {}; } virtual bool initializeGPUDevice(size_t memoryRequired, const std::string &name) const { (void)memoryRequired; (void)name; <|fim_suffix|> } virtual bool initializeGPUDevice(int device, std::string *unavail_reason = nullptr) const { (void)device; if (unavail_reason) { *unavail_reason = "model has no GPU support"; } return false; } virtual bool usingGPUDevice() const { return false; } virtual const char *backendName() const { return "cpu"; } virtual const char *gpuDeviceName() const { return nullptr; } void setProgressCallback(ProgressCallback callback) { m_progressCallback = callback; } virtual int32_t contextLength() const = 0; virtual auto specialTokens() -> std::unordered_map<std::string, std::string> const = 0; protected: // These are pure virtual because subclasses need to implement as the default implementation of // 'prompt' above calls these functions virtual std::vector<Token> tokenize(std::string_view str) const = 0; virtual bool isSpecialToken(Token id) const = 0; virtual std::string tokenToString(Token id) const = 0; virtual void initSampler(const PromptContext &ctx) = 0; virtual Token sampleToken() const = 0; virtual bool evalTokens(int32_t nPast, std::span<const Token> tokens) const = 0; virtual void shiftContext(const PromptContext &promptCtx, int32_t *nPast) = 0; virtual int32_t inputLength() const = 0; virtual int32_t computeModelInputPosition(std::span<const Token> input) const = 0; virtual void setModelInputPosition(int32_t pos) = 0; virtual void appendInputToken(Token tok) = 0; virtual std::span<const Token> inputTokens() const = 0; virtual const std::vector<Token> &endTokens() const = 0; virtual bool shouldAddBOS() const = 0; virtual int32_t maxContextLength(std::string const &modelPath) const { (void)modelPath; return -1; } virtual int32_t layerCount(std::string const &modelPath) const { (void)modelPath; return -1; } virtual auto chatTemplate(const char *modelPath) const <|fim_middle|>return false;
ual 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, int dimensionality = -1, size_t *tokenCount = nullptr, bool doMean = true, bool atlas = false, EmbedCancelCallback *cancelCb = nullptr); // automatic prefix virtual void embed(const std::vector<std::string> &texts, float *embeddings, bool isRetrieval, int dimensionality = -1, size_t *tokenCount = nullptr, bool doMean = true, bool atlas = false); virtual void setThreadCount(int32_t n_threads) { (void)n_threads; } virtual int32_t threadCount() const { return 1; } const Implementation &implementation() const { return *m_implementation; } virtual std::vector<GPUDevice> availableGPUDevices(size_t memoryRequired) const { (void)memoryRequired; return {}; } virtual bool initializeGPUDevice(size_t memoryRequired, const std::string &name) const { (void)memoryRequired; (void)name;
return false;
} virtual bool initializeGPUDevice(int device, std::string *unavail_reason = nullptr) const { (void)device; if (unavail_reason) { *unavail_reason = "model has no GPU support"; } return false; } virtual bool usingGPUDevice() const { return false; } virtual const char *backendName() const { return "cpu"; } virtual const char *gpuDeviceName() const { return nullptr; } void setProgressCallback(ProgressCallback callback) { m_progressCallback = callback; } virtual int32_t contextLength() const = 0; virtual auto specialTokens() -> std::unordered_map<std::string, std::string> const = 0; protected: // These are pure virtual because subclasses need to implement as the default implementation of // 'prompt' above calls these functions virtual std::vector<Token> tokenize(std::string_view str) const = 0; virtual bool isSpecialToken(Token id) const = 0; virtual std::string tokenToString(Token id) const = 0; virtual void initSampler(const PromptContext &ctx) = 0; virtual Token sampleToken() const = 0; virtual bool evalTokens(int32_t nPast, std::span<const Token> tokens) const = 0; virtual void shiftContext(const PromptContext &promptCtx, int32_t *nPast) = 0; virtual int32_t inputLength() const = 0; virtual int32_t computeModelInputPosition(std::span<const Token> input) const = 0; virtual void setModelInputPosition(int32_t pos) = 0; virtual void appendInputToken(Token tok) = 0; virtual std::span<const Token> inputTokens() const = 0; virtual const std::vector<Token> &endTokens() const = 0; virtual bool shouldAddBOS() const = 0; virtual int32_t maxContextLength(std::string const &modelPath) const { (void)modelPath; return -1; } virtual int32_t layerCount(std::string const &modelPath) const { (void)modelPath; return -1; } virtual auto chatTemplate(const char *modelPath) const
ast_based
<|fim_prefix|>* ctx, std::vector<llama_token> & tokens) { llama_memory_clear(llama_get_memory(ctx), true); if (llama_decode(ctx, llama_batch_get_one(tokens.data(), tokens.size()))) { fprintf(stderr, "%s : failed to eval\n", __func__); return false; } return true; } static void export_gguf(const std::vector<struct ggml_tensor *> & v_ctrl, const std::string fname, const std::string model_hint) { struct gguf_context * ctx = gguf_init_empty(); const std::string arch = "controlvector"; gguf_set_val_str(ctx, "general.architecture", arch.c_str()); gguf_set_val_str(ctx, (arch + ".model_hint").c_str(), model_hint.c_str()); gguf_set_val_i32(ctx, (arch + ".layer_count").c_str(), v_ctrl.size()); for (size_t i = 0; i < v_ctrl.size(); ++i) { gguf_add_tensor(ctx, v_ctrl[i]); print_debug_tensor(v_ctrl[i]); printf("Added tensor: %s\n", v_ctrl[i]->name); } printf("%s: writing file...\n", __func__); gguf_write_to_file(ctx, fname.c_str(), false); printf("%s: wrote file '%s'\n", __func__, fname.c_str()); gguf_free(ctx); } /** * Load prompt files and completion file. * Then format each pair of prompt + completion to make an entry. */ static int prepare_entries(common_params & params, train_context & ctx_train) { // load prompts std::vector<std::string> positive_prompts = ctrlvec_load_prompt_file(params.cvector_positive_file, true); std::vector<std::string> negative_prompts = ctrlvec_load_prompt_file(params.cvector_negative_file, true); if (positive_prompts.size() != negative_prompts.size()) { fprintf(stderr, "number of positive and negative prompts must be equal\n"); return 1; } if (positive_prompts.empty()) { fprintf(stderr, "must provide at least one prompt pair\n"); return 1; } ctx_train.positive_entries = positive_prompts; ctx_train.negative_entries = negative_prompts; return 0; } int main(int argc, char ** argv) { <|fim_suffix|> params.out_file = "control_vector.gguf"; if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_CVECTOR_GENERATOR, print_usage)) { return 1; } if (params.n_pca_iterations % params.n_pca_batch != 0) { fprintf(stderr, "PCA iterations must by multiply of PCA batch size\n"); return 1; } callback_data cb_data; // pass the callback to the backend scheduler // it will be executed for each node during the graph computation params.cb_eval = cb_eval; params.cb_eval_user_data = &cb_data; params.warmup = false; print_build_info(); llama_backend_init(); llama_numa_init(params.numa); // load the model to get hparams common_init_result llama_init = common_init_from_params(params); llama_model * model = llama_init.model.get(); llama_context * ctx = llama_init.context.get(); // int n_ctx = llama_n_ctx(ctx); int n_layers = llama_model_n_layer(model); int n_embd = llama_model_n_embd(model); // get model hint param (a.k.a model arch name) char model_hint[128]; llama_model_meta_val_str(model, "general.architecture", model_hint, 128); // init train_context train_context ctx_train(n_embd, n_layers); // 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 = tokeni<|fim_middle|>common_params params;
* ctx, std::vector<llama_token> & tokens) { llama_memory_clear(llama_get_memory(ctx), true); if (llama_decode(ctx, llama_batch_get_one(tokens.data(), tokens.size()))) { fprintf(stderr, "%s : failed to eval\n", __func__); return false; } return true; } static void export_gguf(const std::vector<struct ggml_tensor *> & v_ctrl, const std::string fname, const std::string model_hint) { struct gguf_context * ctx = gguf_init_empty(); const std::string arch = "controlvector"; gguf_set_val_str(ctx, "general.architecture", arch.c_str()); gguf_set_val_str(ctx, (arch + ".model_hint").c_str(), model_hint.c_str()); gguf_set_val_i32(ctx, (arch + ".layer_count").c_str(), v_ctrl.size()); for (size_t i = 0; i < v_ctrl.size(); ++i) { gguf_add_tensor(ctx, v_ctrl[i]); print_debug_tensor(v_ctrl[i]); printf("Added tensor: %s\n", v_ctrl[i]->name); } printf("%s: writing file...\n", __func__); gguf_write_to_file(ctx, fname.c_str(), false); printf("%s: wrote file '%s'\n", __func__, fname.c_str()); gguf_free(ctx); } /** * Load prompt files and completion file. * Then format each pair of prompt + completion to make an entry. */ static int prepare_entries(common_params & params, train_context & ctx_train) { // load prompts std::vector<std::string> positive_prompts = ctrlvec_load_prompt_file(params.cvector_positive_file, true); std::vector<std::string> negative_prompts = ctrlvec_load_prompt_file(params.cvector_negative_file, true); if (positive_prompts.size() != negative_prompts.size()) { fprintf(stderr, "number of positive and negative prompts must be equal\n"); return 1; } if (positive_prompts.empty()) { fprintf(stderr, "must provide at least one prompt pair\n"); return 1; } ctx_train.positive_entries = positive_prompts; ctx_train.negative_entries = negative_prompts; return 0; } int main(int argc, char ** argv) {
common_params params;
params.out_file = "control_vector.gguf"; if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_CVECTOR_GENERATOR, print_usage)) { return 1; } if (params.n_pca_iterations % params.n_pca_batch != 0) { fprintf(stderr, "PCA iterations must by multiply of PCA batch size\n"); return 1; } callback_data cb_data; // pass the callback to the backend scheduler // it will be executed for each node during the graph computation params.cb_eval = cb_eval; params.cb_eval_user_data = &cb_data; params.warmup = false; print_build_info(); llama_backend_init(); llama_numa_init(params.numa); // load the model to get hparams common_init_result llama_init = common_init_from_params(params); llama_model * model = llama_init.model.get(); llama_context * ctx = llama_init.context.get(); // int n_ctx = llama_n_ctx(ctx); int n_layers = llama_model_n_layer(model); int n_embd = llama_model_n_embd(model); // get model hint param (a.k.a model arch name) char model_hint[128]; llama_model_meta_val_str(model, "general.architecture", model_hint, 128); // init train_context train_context ctx_train(n_embd, n_layers); // 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 = tokeni
ast_based
<|fim_prefix|> src_data, src_step, \ (CAROTENE_NS::s16*)dst_data, dst_step, \ 3, 3, ((SepFilterCtx*)context)->kernelx_data, ((SepFilterCtx*)context)->kernely_data, \ ((SepFilterCtx*)context)->border, 0, \ CAROTENE_NS::Margin(offset_x, full_width - width - offset_x, offset_y, full_height - height - offset_y)), \ CV_HAL_ERROR_OK \ : CV_HAL_ERROR_NOT_IMPLEMENTED \ ) #undef cv_hal_sepFilterInit #define cv_hal_sepFilterInit TEGRA_SEPFILTERINIT #undef cv_hal_sepFilter #define cv_hal_sepFilter TEGRA_SEPFILTERIMPL #undef cv_hal_sepFilterFree #define cv_hal_sepFilterFree TEGRA_SEPFILTERFREE struct MorphCtx { int operation; int channels; CAROTENE_NS::Size2D ksize; int anchor_x, anchor_y; CAROTENE_NS::BORDER_MODE border; uchar borderValues[4]; }; inline int TEGRA_MORPHINIT(cvhalFilter2D **context, int operation, int src_type, int dst_type, int width, int height, int kernel_type, uchar *kernel_data, size_t kernel_step, int kernel_width, int kernel_height, int anchor_x, int anchor_y, int borderType, const double borderValue[4], int iterations, bool allowSubmatrix, bool allowInplace) { if(!context || !kernel_data || src_type != dst_type || CV_MAT_DEPTH(src_type) != CV_8U || src_type < 0 || (src_type >> CV_CN_SHIFT) > 3 || width < kernel_width || height < kernel_height || allowSubmatrix || allowInplace || iterations != 1 || !CAROTENE_NS::isSupportedConfiguration()) return CV_HAL_ERROR_NOT_IMPLEMENTED; switch(CV_MAT_DEPTH(kernel_type)) { case CV_8U: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_16U: <|fim_suffix|> break; case CV_32S: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (int32_t*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_32F: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (float*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_64F: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (double*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; default: return CV_HAL_ERROR_NOT_IMPLEMENTED; } MorphCtx* ctx = new MorphCtx; if(!ctx) return CV_HAL_ERROR_UNKNOWN; ctx->channels = (src_type >> CV_CN_SHIFT) + 1; ctx->ksize.width = kernel_width; ctx->ksize.height = kernel_height; ctx->anchor_x = anchor_x; ctx->anchor_y = anchor_y; switch(operation) { case CV_HAL_MORPH_ERODE: case CV_HAL_MORPH_DILATE: ctx->operation = operation; break; default: delete ctx; return CV_HAL_ERROR_NOT_IMPLEMENTED; } switch(borderType) { case CV_HAL_BORDER_CONSTANT: ctx->border = CAROTENE_NS::BORDER_MODE_CONSTANT; if( borderValue[0] == DBL_MAX && borderValue[1] == DBL_MAX && borderValue[2] == DBL_MAX && borderValue[3] == DBL_MAX ) { if( operation == CV_HAL_MORPH_ERODE ) for(int i = 0; i < ctx->channels; ++i) ctx->borderValues[i] = (CAROTENE_NS::u8)UCHAR_MAX; else for(int i = 0; i < ctx->channels; ++i) ctx->borderValues[i] = 0; } else { for(int i = 0; i < ctx->channels; ++i) ctx->borderValues[i] = (CAROTENE_NS::u8)cv::saturate_cast<uchar>(bor<|fim_middle|>if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (uint16_t*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED;
src_data, src_step, \ (CAROTENE_NS::s16*)dst_data, dst_step, \ 3, 3, ((SepFilterCtx*)context)->kernelx_data, ((SepFilterCtx*)context)->kernely_data, \ ((SepFilterCtx*)context)->border, 0, \ CAROTENE_NS::Margin(offset_x, full_width - width - offset_x, offset_y, full_height - height - offset_y)), \ CV_HAL_ERROR_OK \ : CV_HAL_ERROR_NOT_IMPLEMENTED \ ) #undef cv_hal_sepFilterInit #define cv_hal_sepFilterInit TEGRA_SEPFILTERINIT #undef cv_hal_sepFilter #define cv_hal_sepFilter TEGRA_SEPFILTERIMPL #undef cv_hal_sepFilterFree #define cv_hal_sepFilterFree TEGRA_SEPFILTERFREE struct MorphCtx { int operation; int channels; CAROTENE_NS::Size2D ksize; int anchor_x, anchor_y; CAROTENE_NS::BORDER_MODE border; uchar borderValues[4]; }; inline int TEGRA_MORPHINIT(cvhalFilter2D **context, int operation, int src_type, int dst_type, int width, int height, int kernel_type, uchar *kernel_data, size_t kernel_step, int kernel_width, int kernel_height, int anchor_x, int anchor_y, int borderType, const double borderValue[4], int iterations, bool allowSubmatrix, bool allowInplace) { if(!context || !kernel_data || src_type != dst_type || CV_MAT_DEPTH(src_type) != CV_8U || src_type < 0 || (src_type >> CV_CN_SHIFT) > 3 || width < kernel_width || height < kernel_height || allowSubmatrix || allowInplace || iterations != 1 || !CAROTENE_NS::isSupportedConfiguration()) return CV_HAL_ERROR_NOT_IMPLEMENTED; switch(CV_MAT_DEPTH(kernel_type)) { case CV_8U: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_16U:
if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (uint16_t*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED;
break; case CV_32S: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (int32_t*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_32F: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (float*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; case CV_64F: if(CAROTENE_NS::countNonZero(CAROTENE_NS::Size2D(kernel_width, kernel_height), (double*)kernel_data, kernel_step) != kernel_width * kernel_height) return CV_HAL_ERROR_NOT_IMPLEMENTED; break; default: return CV_HAL_ERROR_NOT_IMPLEMENTED; } MorphCtx* ctx = new MorphCtx; if(!ctx) return CV_HAL_ERROR_UNKNOWN; ctx->channels = (src_type >> CV_CN_SHIFT) + 1; ctx->ksize.width = kernel_width; ctx->ksize.height = kernel_height; ctx->anchor_x = anchor_x; ctx->anchor_y = anchor_y; switch(operation) { case CV_HAL_MORPH_ERODE: case CV_HAL_MORPH_DILATE: ctx->operation = operation; break; default: delete ctx; return CV_HAL_ERROR_NOT_IMPLEMENTED; } switch(borderType) { case CV_HAL_BORDER_CONSTANT: ctx->border = CAROTENE_NS::BORDER_MODE_CONSTANT; if( borderValue[0] == DBL_MAX && borderValue[1] == DBL_MAX && borderValue[2] == DBL_MAX && borderValue[3] == DBL_MAX ) { if( operation == CV_HAL_MORPH_ERODE ) for(int i = 0; i < ctx->channels; ++i) ctx->borderValues[i] = (CAROTENE_NS::u8)UCHAR_MAX; else for(int i = 0; i < ctx->channels; ++i) ctx->borderValues[i] = 0; } else { for(int i = 0; i < ctx->channels; ++i) ctx->borderValues[i] = (CAROTENE_NS::u8)cv::saturate_cast<uchar>(bor
ast_based
<|fim_prefix|> gguf_set_val_u32(ctx, KV_TOKENIZER_EOS_ID, EOS_TOKEN_ID); gguf_set_val_u32(ctx, KV_TOKENIZER_SEP_ID, LLAMA_TOKEN_NULL); gguf_set_val_u32(ctx, KV_TOKENIZER_PAD_ID, LLAMA_TOKEN_NULL); gguf_set_val_u32(ctx, KV_CONTEXT_LENGTH, model->hparams.n_ctx); gguf_set_val_u32(ctx, KV_EMBEDDING_LENGTH, model->hparams.n_embd); gguf_set_val_u32(ctx, KV_FEED_FORWARD_LENGTH, model->hparams.n_ff); gguf_set_val_u32(ctx, KV_ATTENTION_HEAD_COUNT, model->hparams.n_head); gguf_set_val_u32(ctx, KV_ATTENTION_HEAD_COUNT, model->hparams.n_head); gguf_set_val_u32(ctx, KV_ATTENTION_HEAD_COUNT_KV, model->hparams.n_head_kv); gguf_set_val_u32(ctx, KV_BLOCK_COUNT, model->hparams.n_layer); gguf_set_val_u32(ctx, KV_ROPE_DIMENSION_COUNT, model->hparams.n_rot); gguf_set_val_f32(ctx, KV_ATTENTION_LAYERNORM_RMS_EPS, 1e-5f); // write tensors ggml_set_name(model->tok_embeddings, TN_TOKEN_EMBD); gguf_add_tensor(ctx, model->tok_embeddings); ggml_set_name(model->norm, TN_OUTPUT_NORM); gguf_add_tensor(ctx, model->norm); ggml_set_name(model->output, TN_OUTPUT); gguf_add_tensor(ctx, model->output); for (uint32_t i = 0; i < model->hparams.n_layer; ++i) { auto & layer = model->layers[i]; ggml_format_name(layer.wq, TN_ATTN_Q, i); gguf_add_tensor(ctx, layer.wq); ggml_format_name(layer.wk, TN_ATTN_K, i); gguf_add_tensor(ctx, layer.wk); ggml_format_name(layer.wv, TN_ATTN_V, i); gguf_add_tensor(ctx, layer.wv); ggml_format_name(layer.wo, TN_ATTN_OUTPUT, i); gguf_add_tensor(ctx, layer.wo); ggml_format_name(layer.attention_norm, TN_ATTN_NORM, i); gguf_add_tensor(ctx, layer.attention_norm); ggml_format_name(layer.w1, TN_FFN_GATE, i); gguf_add_tensor(ctx, layer.w1); ggml_format_name(layer.w2, TN_FFN_DOWN, i); gguf_add_tensor(ctx, layer.w2); ggml_format_name(layer.w3, TN_FFN_UP, i);<|fim_suffix|> static struct train_params get_default_train_params() { struct train_params params; params.fn_vocab_model = "models/7B/ggml-model-f16.gguf"; params.fn_llama2c_output_model = "ak_llama_model.bin"; params.fn_train_data = "shakespeare.txt"; params.fn_checkpoint_in = "checkpoint.bin"; params.fn_checkpoint_out = "checkpoint.bin"; params.fn_model_out = "ggml-checkpoint-f32.bin"; params.seed = -1; params.n_ctx = 128; params.n_embd = 256; params.n_mult = 256; params.n_head = 8; params.n_layer = 16; params.n_rotmax = 64; params.n_threads = 6; params.n_batch = 8; params.n_examples = 8; params.n_predict = 1024; params.print_info_interval = 1; params.print_details_interval = 2; params.samples_start_after_nl = false; params.use_adam = true; params.use_flash = false; params.use_scratch = true; // only adam params.warmup = 100; params.cos_decay_steps = 1000; params.cos_decay_restart = 1.1f; params.cos_decay_alpha = 0.0f; params.lbfgs_n_iter = 16; params.adam_n_iter = 16; params.adam_alpha = 1e-3f; params.adam_decay = 1e-3f; params.mem_model_gb = 2; params.mem_compute_gb = 24; params.mem_compute0_gb = 8; params.mem_compute1_gb = 2; return params; } static void print_usage(int /*argc*/, char ** argv, const struct train_params * params) { fprintf(stderr, "usage: %s [options]\n", argv[0]); fprintf(stderr, "\n"); fprintf(stderr, "options:\n"); fprintf(stderr, " -h, --help show this help message and exit\n"); fprintf(stderr, " --copy-vocab-from-model FNAME path of gguf llama model or llama2.c vocabulary from which to copy vocab (default '%s')\n", params->fn_vocab_model);<|fim_middle|> gguf_add_tensor(ctx, layer.w3); ggml_format_name(layer.ffn_norm, TN_FFN_NORM, i); gguf_add_tensor(ctx, layer.ffn_norm); } gguf_write_to_file(ctx, filename, false); gguf_free(ctx); }
gguf_set_val_u32(ctx, KV_TOKENIZER_EOS_ID, EOS_TOKEN_ID); gguf_set_val_u32(ctx, KV_TOKENIZER_SEP_ID, LLAMA_TOKEN_NULL); gguf_set_val_u32(ctx, KV_TOKENIZER_PAD_ID, LLAMA_TOKEN_NULL); gguf_set_val_u32(ctx, KV_CONTEXT_LENGTH, model->hparams.n_ctx); gguf_set_val_u32(ctx, KV_EMBEDDING_LENGTH, model->hparams.n_embd); gguf_set_val_u32(ctx, KV_FEED_FORWARD_LENGTH, model->hparams.n_ff); gguf_set_val_u32(ctx, KV_ATTENTION_HEAD_COUNT, model->hparams.n_head); gguf_set_val_u32(ctx, KV_ATTENTION_HEAD_COUNT, model->hparams.n_head); gguf_set_val_u32(ctx, KV_ATTENTION_HEAD_COUNT_KV, model->hparams.n_head_kv); gguf_set_val_u32(ctx, KV_BLOCK_COUNT, model->hparams.n_layer); gguf_set_val_u32(ctx, KV_ROPE_DIMENSION_COUNT, model->hparams.n_rot); gguf_set_val_f32(ctx, KV_ATTENTION_LAYERNORM_RMS_EPS, 1e-5f); // write tensors ggml_set_name(model->tok_embeddings, TN_TOKEN_EMBD); gguf_add_tensor(ctx, model->tok_embeddings); ggml_set_name(model->norm, TN_OUTPUT_NORM); gguf_add_tensor(ctx, model->norm); ggml_set_name(model->output, TN_OUTPUT); gguf_add_tensor(ctx, model->output); for (uint32_t i = 0; i < model->hparams.n_layer; ++i) { auto & layer = model->layers[i]; ggml_format_name(layer.wq, TN_ATTN_Q, i); gguf_add_tensor(ctx, layer.wq); ggml_format_name(layer.wk, TN_ATTN_K, i); gguf_add_tensor(ctx, layer.wk); ggml_format_name(layer.wv, TN_ATTN_V, i); gguf_add_tensor(ctx, layer.wv); ggml_format_name(layer.wo, TN_ATTN_OUTPUT, i); gguf_add_tensor(ctx, layer.wo); ggml_format_name(layer.attention_norm, TN_ATTN_NORM, i); gguf_add_tensor(ctx, layer.attention_norm); ggml_format_name(layer.w1, TN_FFN_GATE, i); gguf_add_tensor(ctx, layer.w1); ggml_format_name(layer.w2, TN_FFN_DOWN, i); gguf_add_tensor(ctx, layer.w2); ggml_format_name(layer.w3, TN_FFN_UP, i);
gguf_add_tensor(ctx, layer.w3); ggml_format_name(layer.ffn_norm, TN_FFN_NORM, i); gguf_add_tensor(ctx, layer.ffn_norm); } gguf_write_to_file(ctx, filename, false); gguf_free(ctx); }
static struct train_params get_default_train_params() { struct train_params params; params.fn_vocab_model = "models/7B/ggml-model-f16.gguf"; params.fn_llama2c_output_model = "ak_llama_model.bin"; params.fn_train_data = "shakespeare.txt"; params.fn_checkpoint_in = "checkpoint.bin"; params.fn_checkpoint_out = "checkpoint.bin"; params.fn_model_out = "ggml-checkpoint-f32.bin"; params.seed = -1; params.n_ctx = 128; params.n_embd = 256; params.n_mult = 256; params.n_head = 8; params.n_layer = 16; params.n_rotmax = 64; params.n_threads = 6; params.n_batch = 8; params.n_examples = 8; params.n_predict = 1024; params.print_info_interval = 1; params.print_details_interval = 2; params.samples_start_after_nl = false; params.use_adam = true; params.use_flash = false; params.use_scratch = true; // only adam params.warmup = 100; params.cos_decay_steps = 1000; params.cos_decay_restart = 1.1f; params.cos_decay_alpha = 0.0f; params.lbfgs_n_iter = 16; params.adam_n_iter = 16; params.adam_alpha = 1e-3f; params.adam_decay = 1e-3f; params.mem_model_gb = 2; params.mem_compute_gb = 24; params.mem_compute0_gb = 8; params.mem_compute1_gb = 2; return params; } static void print_usage(int /*argc*/, char ** argv, const struct train_params * params) { fprintf(stderr, "usage: %s [options]\n", argv[0]); fprintf(stderr, "\n"); fprintf(stderr, "options:\n"); fprintf(stderr, " -h, --help show this help message and exit\n"); fprintf(stderr, " --copy-vocab-from-model FNAME path of gguf llama model or llama2.c vocabulary from which to copy vocab (default '%s')\n", params->fn_vocab_model);
random
<|fim_prefix|> /// Both "model" and "custom_template" are optional, but at least one is required. "custom_template" has higher precedence than "model" /// NOTE: This function does not use a jinja parser. It only support a pre-defined list of template. See more: https://github.com/ggml-org/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template /// @param tmpl A Jinja template to use for this chat. If this is nullptr, the model’s default chat template will be used instead. /// @param chat Pointer to a list of multiple llama_chat_message /// @param n_msg Number of llama_chat_message in this chat /// @param add_ass Whether to end the prompt with the token(s) that indicate the start of an assistant message. /// @param buf A buffer to hold the output formatted prompt. The recommended alloc size is 2 * (total number of characters of all messages) /// @param length The size of the allocated buffer /// @return The total number of bytes of the formatted prompt. If is it larger than the size of buffer, you may need to re-alloc it and then re-apply the template. LLAMA_API int32_t llama_chat_apply_template( const char * tmpl, const struct llama_chat_message * chat, size_t n_msg, bool add_ass, char * buf, int32_t length); // Get list of built-in chat templates LLAMA_API int32_t llama_chat_builtin_templates(const char ** output, size_t len); // // Sampling API // // Sample usage: // // // prepare the sampling chain at the start // auto sparams = llama_sampler_chain_default_params(); // // llama_sampler * smpl = llama_sampler_chain_init(sparams); // // llama_sampler_chain_add(smpl, llama_sampler_init_top_k(50)); // llama_sampler_chain_add(smpl, llama_sampler_init_top_p(0.9, 1));<|fim_suffix|> // // // typically, the chain should end with a sampler such as "greedy", "dist" or "mirostat" // // this sampler will be responsible to select the actual token // llama_sampler_chain_add(smpl, llama_sampler_init_dist(seed)); // // ... // // // decoding loop: // while (...) { // ... // // llama_decode(ctx, batch); // // // sample from the logits of the last token in the batch // const llama_token id = llama_sampler_sample(smpl, ctx, -1); // // // accepting the token updates the internal state of certain samplers (e.g. grammar, repetition, etc.) // llama_sampler_accept(smpl, id); // ... // } // // llama_sampler_free(smpl); // // TODO: In the future, llama_sampler will be utilized to offload the sampling to the backends (e.g. GPU). // typedef void * llama_sampler_context_t; // user code can implement the interface below in order to create custom llama_sampler struct llama_sampler_i { const char * (*name) (const struct llama_sampler * smpl); // can be NULL void (*accept)( struct llama_sampler * smpl, llama_token token); // can be NULL void (*apply) ( struct llama_sampler * smpl, llama_token_data_array * cur_p); // required void (*reset) ( struct llama_sampler * smpl); // can be NULL struct llama_sampler * (*clone) (const struct llama_sampler * smpl); // can be NULL if ctx is NULL void (*free) ( struct llama_sampler * smpl); // can be NULL if ctx is NULL // TODO: API for internal libllama usage for appending the sampling to an existing ggml_cgraph<|fim_middle|> // llama_sampler_chain_add(smpl, llama_sampler_init_temp (0.8));
/// Both "model" and "custom_template" are optional, but at least one is required. "custom_template" has higher precedence than "model" /// NOTE: This function does not use a jinja parser. It only support a pre-defined list of template. See more: https://github.com/ggml-org/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template /// @param tmpl A Jinja template to use for this chat. If this is nullptr, the model’s default chat template will be used instead. /// @param chat Pointer to a list of multiple llama_chat_message /// @param n_msg Number of llama_chat_message in this chat /// @param add_ass Whether to end the prompt with the token(s) that indicate the start of an assistant message. /// @param buf A buffer to hold the output formatted prompt. The recommended alloc size is 2 * (total number of characters of all messages) /// @param length The size of the allocated buffer /// @return The total number of bytes of the formatted prompt. If is it larger than the size of buffer, you may need to re-alloc it and then re-apply the template. LLAMA_API int32_t llama_chat_apply_template( const char * tmpl, const struct llama_chat_message * chat, size_t n_msg, bool add_ass, char * buf, int32_t length); // Get list of built-in chat templates LLAMA_API int32_t llama_chat_builtin_templates(const char ** output, size_t len); // // Sampling API // // Sample usage: // // // prepare the sampling chain at the start // auto sparams = llama_sampler_chain_default_params(); // // llama_sampler * smpl = llama_sampler_chain_init(sparams); // // llama_sampler_chain_add(smpl, llama_sampler_init_top_k(50)); // llama_sampler_chain_add(smpl, llama_sampler_init_top_p(0.9, 1));
// llama_sampler_chain_add(smpl, llama_sampler_init_temp (0.8));
// // // typically, the chain should end with a sampler such as "greedy", "dist" or "mirostat" // // this sampler will be responsible to select the actual token // llama_sampler_chain_add(smpl, llama_sampler_init_dist(seed)); // // ... // // // decoding loop: // while (...) { // ... // // llama_decode(ctx, batch); // // // sample from the logits of the last token in the batch // const llama_token id = llama_sampler_sample(smpl, ctx, -1); // // // accepting the token updates the internal state of certain samplers (e.g. grammar, repetition, etc.) // llama_sampler_accept(smpl, id); // ... // } // // llama_sampler_free(smpl); // // TODO: In the future, llama_sampler will be utilized to offload the sampling to the backends (e.g. GPU). // typedef void * llama_sampler_context_t; // user code can implement the interface below in order to create custom llama_sampler struct llama_sampler_i { const char * (*name) (const struct llama_sampler * smpl); // can be NULL void (*accept)( struct llama_sampler * smpl, llama_token token); // can be NULL void (*apply) ( struct llama_sampler * smpl, llama_token_data_array * cur_p); // required void (*reset) ( struct llama_sampler * smpl); // can be NULL struct llama_sampler * (*clone) (const struct llama_sampler * smpl); // can be NULL if ctx is NULL void (*free) ( struct llama_sampler * smpl); // can be NULL if ctx is NULL // TODO: API for internal libllama usage for appending the sampling to an existing ggml_cgraph
random
<|fim_prefix|> 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="}, };<|fim_suffix|> 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, "decoded: {} encoded: '{}' original: {}", decoded, encoded, original); } TEST_SUCCESS(); }; TEST_SEQUENCE("EncodeDecodeLEB128") { TEST_ASSERT(hex::crypt::encodeUleb128(0) == (std::vector<u8>{ 0 })); TEST_ASSERT(hex::crypt::encodeUleb128(0x7F) == (std::vector<u8>{ 0x7F })); TEST_ASSERT(hex::crypt::encodeUleb128(0xFF) == (std::vector<u8>{ 0xFF, 0x01 })); TEST_ASSERT(hex::crypt::encodeUleb128(0xF0F0) == (std::vector<u8>{ 0xF0, 0xE1, 0x03 })); TEST_ASSERT(hex::crypt::encodeSleb128(0) == (std::vector<u8>{ 0 })); TEST_ASSERT(hex::crypt::encodeSleb128(0x7F) == (std::vector<u8>{ 0xFF, 0x00 })); TEST_ASSERT(hex::crypt::encodeSleb128(0xFF) == (std::vector<u8>{ 0xFF, 0x01 })); TEST_ASSERT(hex::crypt::encodeSleb128(0xF0F0) == (std::vector<u8>{ 0xF0, 0xE1, 0x03 })); TEST_ASSERT(hex::crypt::encodeSleb128(-1) == (std::vector<u8>{ 0x7F })); TEST_ASSERT(hex::crypt::encodeSleb128(-128) == (std::vector<u8>{ 0x80, 0x7F })); TEST_ASSERT(hex::crypt::decodeUleb128({}) == 0); TEST_ASSERT(hex::crypt::decodeUleb128({ 1 }) == 0x01); TEST_ASSERT(hex::crypt::decodeUleb128({ 0x7F }) == 0x7F);<|fim_middle|> 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, "decoded: {} encoded: '{}' original: {}", decoded, encoded, original); } TEST_SUCCESS(); }; TEST_SEQUENCE("EncodeDecodeLEB128") { TEST_ASSERT(hex::crypt::encodeUleb128(0) == (std::vector<u8>{ 0 })); TEST_ASSERT(hex::crypt::encodeUleb128(0x7F) == (std::vector<u8>{ 0x7F })); TEST_ASSERT(hex::crypt::encodeUleb128(0xFF) == (std::vector<u8>{ 0xFF, 0x01 })); TEST_ASSERT(hex::crypt::encodeUleb128(0xF0F0) == (std::vector<u8>{ 0xF0, 0xE1, 0x03 })); TEST_ASSERT(hex::crypt::encodeSleb128(0) == (std::vector<u8>{ 0 })); TEST_ASSERT(hex::crypt::encodeSleb128(0x7F) == (std::vector<u8>{ 0xFF, 0x00 })); TEST_ASSERT(hex::crypt::encodeSleb128(0xFF) == (std::vector<u8>{ 0xFF, 0x01 })); TEST_ASSERT(hex::crypt::encodeSleb128(0xF0F0) == (std::vector<u8>{ 0xF0, 0xE1, 0x03 })); TEST_ASSERT(hex::crypt::encodeSleb128(-1) == (std::vector<u8>{ 0x7F })); TEST_ASSERT(hex::crypt::encodeSleb128(-128) == (std::vector<u8>{ 0x80, 0x7F })); TEST_ASSERT(hex::crypt::decodeUleb128({}) == 0); TEST_ASSERT(hex::crypt::decodeUleb128({ 1 }) == 0x01); TEST_ASSERT(hex::crypt::decodeUleb128({ 0x7F }) == 0x7F);
random
<|fim_prefix|> ClassDB::bind_method(D_METHOD("set_offset", "offset"), &AnimatedSprite2D::set_offset); ClassDB::bind_method(D_METHOD("get_offset"), &AnimatedSprite2D::get_offset); ClassDB::bind_method(D_METHOD("set_flip_h", "flip_h"), &AnimatedSprite2D::set_flip_h); ClassDB::bind_method(D_METHOD("is_flipped_h"), &AnimatedSprite2D::is_flipped_h); ClassDB::bind_method(D_METHOD("set_flip_v", "flip_v"), &AnimatedSprite2D::set_flip_v); ClassDB::bind_method(D_METHOD("is_flipped_v"), &AnimatedSprite2D::is_flipped_v); ClassDB::bind_method(D_METHOD("set_frame", "frame"), &AnimatedSprite2D::set_frame); ClassDB::bind_method(D_METHOD("get_frame"), &AnimatedSprite2D::get_frame); ClassDB::bind_method(D_METHOD("set_frame_progress", "progress"), &AnimatedSprite2D::set_frame_progress); ClassDB::bind_method(D_METHOD("get_frame_progress"), &AnimatedSprite2D::get_frame_progress); ClassDB::bind_method(D_METHOD("set_frame_and_progress", "frame", "progress"), &AnimatedSprite2D::set_frame_and_progress); ClassDB::bind_method(D_METHOD("set_speed_scale", "speed_scale"), &AnimatedSprite2D::set_speed_scale); ClassDB::bind_method(D_METHOD("get_speed_scale"), &AnimatedSprite2D::get_speed_scale); ClassDB::bind_method(D_METHOD("get_playing_speed"), &AnimatedSprite2D::get_playing_speed); ADD_SIGNAL(MethodInfo("sprite_frames_changed")); ADD_SIGNAL(MethodInfo("animation_changed")); ADD_SIGNAL(MethodInfo("frame_changed")); ADD_SIGNAL(MethodInfo("animation_looped")); ADD_SIGNAL(MethodInfo("animation_finished")); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "sprite_frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames"); ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "animation", PROPERTY_HINT_ENUM, ""), "set_animation", "get_animation"); ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "autoplay", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_autoplay", "get_autoplay");<|fim_suffix|> ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "speed_scale"), "set_speed_scale", "get_speed_scale"); ADD_GROUP("Offset", ""); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset", PROPERTY_HINT_NONE, "suffix:px"), "set_offset", "get_offset"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v"); } AnimatedSprite2D::AnimatedSprite2D() { } <|fim_middle|> ADD_PROPERTY(PropertyInfo(Variant::INT, "frame"), "set_frame", "get_frame"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "frame_progress", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_frame_progress", "get_frame_progress");
ClassDB::bind_method(D_METHOD("set_offset", "offset"), &AnimatedSprite2D::set_offset); ClassDB::bind_method(D_METHOD("get_offset"), &AnimatedSprite2D::get_offset); ClassDB::bind_method(D_METHOD("set_flip_h", "flip_h"), &AnimatedSprite2D::set_flip_h); ClassDB::bind_method(D_METHOD("is_flipped_h"), &AnimatedSprite2D::is_flipped_h); ClassDB::bind_method(D_METHOD("set_flip_v", "flip_v"), &AnimatedSprite2D::set_flip_v); ClassDB::bind_method(D_METHOD("is_flipped_v"), &AnimatedSprite2D::is_flipped_v); ClassDB::bind_method(D_METHOD("set_frame", "frame"), &AnimatedSprite2D::set_frame); ClassDB::bind_method(D_METHOD("get_frame"), &AnimatedSprite2D::get_frame); ClassDB::bind_method(D_METHOD("set_frame_progress", "progress"), &AnimatedSprite2D::set_frame_progress); ClassDB::bind_method(D_METHOD("get_frame_progress"), &AnimatedSprite2D::get_frame_progress); ClassDB::bind_method(D_METHOD("set_frame_and_progress", "frame", "progress"), &AnimatedSprite2D::set_frame_and_progress); ClassDB::bind_method(D_METHOD("set_speed_scale", "speed_scale"), &AnimatedSprite2D::set_speed_scale); ClassDB::bind_method(D_METHOD("get_speed_scale"), &AnimatedSprite2D::get_speed_scale); ClassDB::bind_method(D_METHOD("get_playing_speed"), &AnimatedSprite2D::get_playing_speed); ADD_SIGNAL(MethodInfo("sprite_frames_changed")); ADD_SIGNAL(MethodInfo("animation_changed")); ADD_SIGNAL(MethodInfo("frame_changed")); ADD_SIGNAL(MethodInfo("animation_looped")); ADD_SIGNAL(MethodInfo("animation_finished")); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "sprite_frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames"); ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "animation", PROPERTY_HINT_ENUM, ""), "set_animation", "get_animation"); ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "autoplay", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_autoplay", "get_autoplay");
ADD_PROPERTY(PropertyInfo(Variant::INT, "frame"), "set_frame", "get_frame"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "frame_progress", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_frame_progress", "get_frame_progress");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "speed_scale"), "set_speed_scale", "get_speed_scale"); ADD_GROUP("Offset", ""); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset", PROPERTY_HINT_NONE, "suffix:px"), "set_offset", "get_offset"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v"); } AnimatedSprite2D::AnimatedSprite2D() { }
random
<|fim_prefix|>W; ae->window_id = p_window_id; wd.root_id = rid_owner.make_rid(ae); #ifdef WINDOWS_ENABLED wd.adapter = accesskit_windows_subclassing_adapter_new(static_cast<HWND>(p_handle), &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef MACOS_ENABLED wd.adapter = accesskit_macos_subclassing_adapter_for_window(p_handle, &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef LINUXBSD_ENABLED wd.adapter = accesskit_unix_adapter_new(&_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id, &_accessibility_deactivation_callback, (void *)(size_t)p_window_id); #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; <|fim_suffix|> 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-<|fim_middle|>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; }
W; ae->window_id = p_window_id; wd.root_id = rid_owner.make_rid(ae); #ifdef WINDOWS_ENABLED wd.adapter = accesskit_windows_subclassing_adapter_new(static_cast<HWND>(p_handle), &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef MACOS_ENABLED wd.adapter = accesskit_macos_subclassing_adapter_for_window(p_handle, &_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id); #endif #ifdef LINUXBSD_ENABLED wd.adapter = accesskit_unix_adapter_new(&_accessibility_initial_tree_update_callback, (void *)(size_t)p_window_id, &_accessibility_action_callback, (void *)(size_t)p_window_id, &_accessibility_deactivation_callback, (void *)(size_t)p_window_id); #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-
ast_based
<|fim_prefix|>/* 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;<|fim_suffix|> 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(); Key physical_keycode = godot_code_from_android_code(p_physical_keycode); Key keycode; if (unicode == '\b') { // 0x08 keycode = Key::BACKSPACE; } else if (unicode == '\t') { // 0x09 keycode = Key::TAB; } else if (unicode == '\n') { // 0x0A keycode = Key::ENTER; } else if (unicode == 0x1B) { keycode = Key::ESCAPE; } else if (unicode == 0x1F) { keycode = Key::KEY_DELETE; } else { keycode = fix_keycode(unicode, physical_keycode); } switch (physical_keycode) { case Key::SHIFT: { shift_mem = p_pressed; } break; case Key::ALT: { alt_mem = p_pressed; } break; case Key::CTRL: { control_mem = p_pressed; } break; case Key::META: { meta_mem = p_pressed; } break; default: break; } ev->set_keycode(keycode); ev->set_physical_keycode(physical_keycode); ev->set_key_label(fix_key_label(p_key_label, keycode)); ev->set_unicode(fix_unicode(unicode)); ev->set_location(godot_location_from_android_code(p_physical_keycode)); ev->set_pressed(p_pressed); ev->set_echo(p_echo); _set_key_modifier_state(ev, keycode); <|fim_middle|> } } void AndroidInputHandler::_set_key_modifier_state(Ref<InputEventWithModifiers> ev, Key p_keycode) { if (p_keycode != Key::SHIFT) { ev->set_shift_pressed(shift_mem); }
/* 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(); Key physical_keycode = godot_code_from_android_code(p_physical_keycode); Key keycode; if (unicode == '\b') { // 0x08 keycode = Key::BACKSPACE; } else if (unicode == '\t') { // 0x09 keycode = Key::TAB; } else if (unicode == '\n') { // 0x0A keycode = Key::ENTER; } else if (unicode == 0x1B) { keycode = Key::ESCAPE; } else if (unicode == 0x1F) { keycode = Key::KEY_DELETE; } else { keycode = fix_keycode(unicode, physical_keycode); } switch (physical_keycode) { case Key::SHIFT: { shift_mem = p_pressed; } break; case Key::ALT: { alt_mem = p_pressed; } break; case Key::CTRL: { control_mem = p_pressed; } break; case Key::META: { meta_mem = p_pressed; } break; default: break; } ev->set_keycode(keycode); ev->set_physical_keycode(physical_keycode); ev->set_key_label(fix_key_label(p_key_label, keycode)); ev->set_unicode(fix_unicode(unicode)); ev->set_location(godot_location_from_android_code(p_physical_keycode)); ev->set_pressed(p_pressed); ev->set_echo(p_echo); _set_key_modifier_state(ev, keycode);
random
<|fim_prefix|>()); } 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 = <|fim_suffix|>.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; 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::Accessibilit<|fim_middle|>OS::get_singleton()->get_executable_path().get_base_dir().path_join("../Frameworks")
()); } 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; 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::Accessibilit
ast_based
<|fim_prefix|> float(i*squareSize), 0)); } static bool run3Calibration(vector<vector<Point2f> > imagePoints1, vector<vector<Point2f> > imagePoints2, vector<vector<Point2f> > imagePoints3, Size imageSize, Size boardSize, float squareSize, float aspectRatio, int flags, Mat& cameraMatrix1, Mat& distCoeffs1, Mat& cameraMatrix2, Mat& distCoeffs2, Mat& cameraMatrix3, Mat& distCoeffs3, Mat& R12, Mat& T12, Mat& R13, Mat& T13) { int c, i; // step 1: calibrate each camera individually vector<vector<Point3f> > objpt(1); vector<vector<Point2f> > imgpt; calcChessboardCorners(boardSize, squareSize, objpt[0]); vector<Mat> rvecs, tvecs; for( c = 1; c <= 3; c++ ) { const vector<vector<Point2f> >& imgpt0 = c == 1 ? imagePoints1 : c == 2 ? imagePoints2 : imagePoints3; imgpt.clear(); int N = 0; for( i = 0; i < (int)imgpt0.size(); i++ ) if( !imgpt0[i].empty() ) { imgpt.push_back(imgpt0[i]); N += (int)imgpt0[i].size(); } if( imgpt.size() < 3 ) { printf("Error: not enough views for camera %d\n", c); return false; } objpt.resize(imgpt.size(),objpt[0]); Mat cameraMatrix = Mat::eye(3, 3, CV_64F); if( flags & CALIB_FIX_ASPECT_RATIO ) cameraMatrix.at<double>(0,0) = aspectRatio; Mat distCoeffs = Mat::zeros(5, 1, CV_64F); double err = calibrateCamera(objpt, imgpt, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags|CALIB_FIX_K3/*|CALIB_FIX_K4|CALIB_FIX_K5|CALIB_FIX_K6*/); bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs); if(!ok) <|fim_suffix|> printf("Camera %d calibration reprojection error = %g\n", c, sqrt(err/N)); if( c == 1 ) cameraMatrix1 = cameraMatrix, distCoeffs1 = distCoeffs; else if( c == 2 ) cameraMatrix2 = cameraMatrix, distCoeffs2 = distCoeffs; else cameraMatrix3 = cameraMatrix, distCoeffs3 = distCoeffs; } vector<vector<Point2f> > imgpt_right; // step 2: calibrate (1,2) and (3,2) pairs for( c = 2; c <= 3; c++ ) { const vector<vector<Point2f> >& imgpt0 = c == 2 ? imagePoints2 : imagePoints3; imgpt.clear(); imgpt_right.clear(); int N = 0; for( i = 0; i < (int)std::min(imagePoints1.size(), imgpt0.size()); i++ ) if( !imagePoints1.empty() && !imgpt0[i].empty() ) { imgpt.push_back(imagePoints1[i]); imgpt_right.push_back(imgpt0[i]); N += (int)imgpt0[i].size(); } if( imgpt.size() < 3 ) { printf("Error: not enough shared views for cameras 1 and %d\n", c); return false; } objpt.resize(imgpt.size(),objpt[0]); Mat cameraMatrix = c == 2 ? cameraMatrix2 : cameraMatrix3; Mat distCoeffs = c == 2 ? distCoeffs2 : distCoeffs3; Mat R, T, E, F; double err = stereoCalibrate(objpt, imgpt, imgpt_right, cameraMatrix1, distCoeffs1, cameraMatrix, distCoeffs, imageSize, R, T, E, F, CALIB_FIX_INTRINSIC, TermCriteria(TermCriteria::COUNT, 30, 0)); printf("Pair (1,%d) calibration reprojection error = %g\n", c, sqrt(err/(N*2))); if( c == 2 ) { cameraMatrix2 = cameraMatrix; distCoeffs2 = distCoeffs; R12 = R; T12 = T; } else { R13 = R; T13 = T; } } return true; } stat<|fim_middle|>{ printf("Error: camera %d was not calibrated\n", c); return false; }
float(i*squareSize), 0)); } static bool run3Calibration(vector<vector<Point2f> > imagePoints1, vector<vector<Point2f> > imagePoints2, vector<vector<Point2f> > imagePoints3, Size imageSize, Size boardSize, float squareSize, float aspectRatio, int flags, Mat& cameraMatrix1, Mat& distCoeffs1, Mat& cameraMatrix2, Mat& distCoeffs2, Mat& cameraMatrix3, Mat& distCoeffs3, Mat& R12, Mat& T12, Mat& R13, Mat& T13) { int c, i; // step 1: calibrate each camera individually vector<vector<Point3f> > objpt(1); vector<vector<Point2f> > imgpt; calcChessboardCorners(boardSize, squareSize, objpt[0]); vector<Mat> rvecs, tvecs; for( c = 1; c <= 3; c++ ) { const vector<vector<Point2f> >& imgpt0 = c == 1 ? imagePoints1 : c == 2 ? imagePoints2 : imagePoints3; imgpt.clear(); int N = 0; for( i = 0; i < (int)imgpt0.size(); i++ ) if( !imgpt0[i].empty() ) { imgpt.push_back(imgpt0[i]); N += (int)imgpt0[i].size(); } if( imgpt.size() < 3 ) { printf("Error: not enough views for camera %d\n", c); return false; } objpt.resize(imgpt.size(),objpt[0]); Mat cameraMatrix = Mat::eye(3, 3, CV_64F); if( flags & CALIB_FIX_ASPECT_RATIO ) cameraMatrix.at<double>(0,0) = aspectRatio; Mat distCoeffs = Mat::zeros(5, 1, CV_64F); double err = calibrateCamera(objpt, imgpt, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags|CALIB_FIX_K3/*|CALIB_FIX_K4|CALIB_FIX_K5|CALIB_FIX_K6*/); bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs); if(!ok)
{ printf("Error: camera %d was not calibrated\n", c); return false; }
printf("Camera %d calibration reprojection error = %g\n", c, sqrt(err/N)); if( c == 1 ) cameraMatrix1 = cameraMatrix, distCoeffs1 = distCoeffs; else if( c == 2 ) cameraMatrix2 = cameraMatrix, distCoeffs2 = distCoeffs; else cameraMatrix3 = cameraMatrix, distCoeffs3 = distCoeffs; } vector<vector<Point2f> > imgpt_right; // step 2: calibrate (1,2) and (3,2) pairs for( c = 2; c <= 3; c++ ) { const vector<vector<Point2f> >& imgpt0 = c == 2 ? imagePoints2 : imagePoints3; imgpt.clear(); imgpt_right.clear(); int N = 0; for( i = 0; i < (int)std::min(imagePoints1.size(), imgpt0.size()); i++ ) if( !imagePoints1.empty() && !imgpt0[i].empty() ) { imgpt.push_back(imagePoints1[i]); imgpt_right.push_back(imgpt0[i]); N += (int)imgpt0[i].size(); } if( imgpt.size() < 3 ) { printf("Error: not enough shared views for cameras 1 and %d\n", c); return false; } objpt.resize(imgpt.size(),objpt[0]); Mat cameraMatrix = c == 2 ? cameraMatrix2 : cameraMatrix3; Mat distCoeffs = c == 2 ? distCoeffs2 : distCoeffs3; Mat R, T, E, F; double err = stereoCalibrate(objpt, imgpt, imgpt_right, cameraMatrix1, distCoeffs1, cameraMatrix, distCoeffs, imageSize, R, T, E, F, CALIB_FIX_INTRINSIC, TermCriteria(TermCriteria::COUNT, 30, 0)); printf("Pair (1,%d) calibration reprojection error = %g\n", c, sqrt(err/(N*2))); if( c == 2 ) { cameraMatrix2 = cameraMatrix; distCoeffs2 = distCoeffs; R12 = R; T12 = T; } else { R13 = R; T13 = T; } } return true; } stat
ast_based
<|fim_prefix|> _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, "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);<|fim_suffix|> 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_described_by(ae->node, (accesskit_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);<|fim_middle|> accesskit_node_push_detail(ae->node, (accesskit_node_id)p_related_id.get_id()); } void AccessibilityDriverAccessKit::accessibility_update_add_related_described_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);
_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, "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_detail(ae->node, (accesskit_node_id)p_related_id.get_id()); } void AccessibilityDriverAccessKit::accessibility_update_add_related_described_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_described_by(ae->node, (accesskit_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);
random
<|fim_prefix|>andles. 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 = <|fim_suffix|>; 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; mo<|fim_middle|>Point2(time, h)
andles. 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_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; mo
ast_based
<|fim_prefix|> } 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( Rect2(bs_from, bs_to - bs_from), get_theme_color(SNAME("box_selection_stroke_color"), EditorStringName(Editor)), false, Math::round(EDSCALE)); } } break; } } // Check if a track is displayed in the bezier editor (track type = bezier and track not filtered). bool AnimationBezierTrackEdit::_is_track_displayed(int p_track_index) { if (animation->track_get_type(p_track_index) != Animation::TrackType::TYPE_BEZIER) { return false; } if (is_filtered) { String path = String(animation->track_get_path(p_track_index)); if (root && root->has_node(path)) { Node *node = root->get_node(path); if (!node) { return false; // No node, no filter. } if (!EditorNode::get_singleton()->get_editor_selection()->is_selected(node)) { 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 {<|fim_suffix|> } } } // 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() {<|fim_middle|> // 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();
} 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( Rect2(bs_from, bs_to - bs_from), get_theme_color(SNAME("box_selection_stroke_color"), EditorStringName(Editor)), false, Math::round(EDSCALE)); } } break; } } // Check if a track is displayed in the bezier editor (track type = bezier and track not filtered). bool AnimationBezierTrackEdit::_is_track_displayed(int p_track_index) { if (animation->track_get_type(p_track_index) != Animation::TrackType::TYPE_BEZIER) { return false; } if (is_filtered) { String path = String(animation->track_get_path(p_track_index)); if (root && root->has_node(path)) { Node *node = root->get_node(path); if (!node) { return false; // No node, no filter. } if (!EditorNode::get_singleton()->get_editor_selection()->is_selected(node)) { 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() {
random
<|fim_prefix|>_log"; // Attribute used to record the name of the eager operation triggered the // DTensor rewrites. static constexpr char kEagerOperationName[] = "dtensor.eager_operation_name"; // The number of TPU cores in a donut. static constexpr int kTpuDonutSize = 8; // An attribute used to cache the computation of device seeds, so that we don't // constantly recompute device seeds in a cluster for a given layout. static constexpr char kDeviceSeedForMeshDims[] = "dtensor.device_seed_for_mesh_dims"; // Attribute that determines whether to skip XlA compilation. There are some ops // that run on a TPU mesh but are not expected to be compiled by XLA, e.g. // VarHandleOp, DestroyResourceOp, etc. For such an case, set this attribute // to true on the StatefulPartitionedCallOp generated by MLIR lowering. static constexpr char kSkipXlaCompilation[] = "_skip_xla_compilation"; // An attribute which stores the cache_key for the graph in the module. Used // to uniquely name functions. static constexpr char kCacheKey[] = "dtensor.cache_key"; // An attribute on Const nodes to record which argument it was originally // from. static constexpr char kFromArgIndex[] = "dtensor.from_arg_index"; // To record the target layout of a DTensorSend, which is computed after // layout propagation. static constexpr char kTargetLayoutAttr[] = "target_layout"; // To record the source layout of a DTensorRecv, which is computed after // layout propagation. static constexpr char kSourceLayoutAttr[] = "source_layout"; // An attribute that determines whether a tensor is a sparse tensor. If this // attribute exists in a tensor, then this tensor is a sparse tensor. static constexpr char kSparseValue[] = "tf._sparse"; // Attribute which stores the layouts to be applied to the elements returned by // calling IteratorGetNextOp on a tf.data iterator. static constexpr char kIteratorElementLayouts[] = "tf._element_layouts"; // Attribute used in tf.data ops which stores the shapes of the output elements. <|fim_suffix|> // The number of list of regular tensors used to represent sparse tensors. static constexpr int kSparseTensorNum = 3; // Attribute which stores the environment variable value for all_reduce // optimization group size: DTENSOR_ALLREDUCE_COMBINE_OPTIMIZATION_GROUP_SIZE. // This represents the maximum number of AllReduce ops to merge into one op. It // is a determining factor used during dtensor_allreduce_combine_optimization. static constexpr char kAllReduceNumOpsInGroup[] = "dtensor.all_reduce_combiner.num_ops_in_group"; // Attribute which stores the environment variable value for whether // multi-device expansion is enabled: DTENSOR_ENABLE_MULTI_DEVICE_EXPANSION. static constexpr char kEnableMultiDeviceMode[] = "dtensor.enable_multi_device_mode"; // Attribute which stores the environment variable value for all_reduce // optimization group size: DTENSOR_ALLREDUCE_COMBINE_OPTIMIZATION_GROUP_SIZE. // This represents the maximum distance between two AllReduce on the compute // graph in terms of topological level. It is a determining factor used during // dtensor_allreduce_combine_optimization. static constexpr char kAllReduceTopologicalDistance[] = "dtensor.all_reduce_combiner.topological_distance"; } // namespace dtensor } // namespace tensorflow #endif // TENSORFLOW_DTENSOR_CC_CONSTANTS_H_ <|fim_middle|>static constexpr char kIteratorOutputShapes[] = "output_shapes";
_log"; // Attribute used to record the name of the eager operation triggered the // DTensor rewrites. static constexpr char kEagerOperationName[] = "dtensor.eager_operation_name"; // The number of TPU cores in a donut. static constexpr int kTpuDonutSize = 8; // An attribute used to cache the computation of device seeds, so that we don't // constantly recompute device seeds in a cluster for a given layout. static constexpr char kDeviceSeedForMeshDims[] = "dtensor.device_seed_for_mesh_dims"; // Attribute that determines whether to skip XlA compilation. There are some ops // that run on a TPU mesh but are not expected to be compiled by XLA, e.g. // VarHandleOp, DestroyResourceOp, etc. For such an case, set this attribute // to true on the StatefulPartitionedCallOp generated by MLIR lowering. static constexpr char kSkipXlaCompilation[] = "_skip_xla_compilation"; // An attribute which stores the cache_key for the graph in the module. Used // to uniquely name functions. static constexpr char kCacheKey[] = "dtensor.cache_key"; // An attribute on Const nodes to record which argument it was originally // from. static constexpr char kFromArgIndex[] = "dtensor.from_arg_index"; // To record the target layout of a DTensorSend, which is computed after // layout propagation. static constexpr char kTargetLayoutAttr[] = "target_layout"; // To record the source layout of a DTensorRecv, which is computed after // layout propagation. static constexpr char kSourceLayoutAttr[] = "source_layout"; // An attribute that determines whether a tensor is a sparse tensor. If this // attribute exists in a tensor, then this tensor is a sparse tensor. static constexpr char kSparseValue[] = "tf._sparse"; // Attribute which stores the layouts to be applied to the elements returned by // calling IteratorGetNextOp on a tf.data iterator. static constexpr char kIteratorElementLayouts[] = "tf._element_layouts"; // Attribute used in tf.data ops which stores the shapes of the output elements.
static constexpr char kIteratorOutputShapes[] = "output_shapes";
// The number of list of regular tensors used to represent sparse tensors. static constexpr int kSparseTensorNum = 3; // Attribute which stores the environment variable value for all_reduce // optimization group size: DTENSOR_ALLREDUCE_COMBINE_OPTIMIZATION_GROUP_SIZE. // This represents the maximum number of AllReduce ops to merge into one op. It // is a determining factor used during dtensor_allreduce_combine_optimization. static constexpr char kAllReduceNumOpsInGroup[] = "dtensor.all_reduce_combiner.num_ops_in_group"; // Attribute which stores the environment variable value for whether // multi-device expansion is enabled: DTENSOR_ENABLE_MULTI_DEVICE_EXPANSION. static constexpr char kEnableMultiDeviceMode[] = "dtensor.enable_multi_device_mode"; // Attribute which stores the environment variable value for all_reduce // optimization group size: DTENSOR_ALLREDUCE_COMBINE_OPTIMIZATION_GROUP_SIZE. // This represents the maximum distance between two AllReduce on the compute // graph in terms of topological level. It is a determining factor used during // dtensor_allreduce_combine_optimization. static constexpr char kAllReduceTopologicalDistance[] = "dtensor.all_reduce_combiner.topological_distance"; } // namespace dtensor } // namespace tensorflow #endif // TENSORFLOW_DTENSOR_CC_CONSTANTS_H_
ast_based
<|fim_prefix|>_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"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:/testroot/path/something/../filename"), "C:/testroot/path/filename"); CHECK_EQ(<|fim_suffix|>->localize_path("C:/testroot/path/./filename"), "C:/testroot/path/filename"); 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"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:\\testroot\\path\\something\\..\\filename"), "C:/testroot/path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:\\testroot\\path\\.\\filename"), "C:/testroot/path/filename"); #endif CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path + "/filename"), "res://filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path + "/path/filename"), "res://path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path + "/path/something/../filename"), "res://path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path + "/path/./filename"), "res://path/filename"); #ifdef WINDOWS_ENABLED CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path_win + "\\filename"), "res://filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path_win + "\\path\\filename"), "res://path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path_win + "\\path\\something\\..\\filename"), "res://path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path_win + "\\path\\.\\filename"), "res://path/filename"); #endif TestProjectSettingsInternalsAccessor::resource_path() = old_resource_path; } } // namespace TestProjectSettings <|fim_middle|>ProjectSettings::get_singleton()
_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"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:/testroot/path/something/../filename"), "C:/testroot/path/filename"); CHECK_EQ(
ProjectSettings::get_singleton()
->localize_path("C:/testroot/path/./filename"), "C:/testroot/path/filename"); 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"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:\\testroot\\path\\something\\..\\filename"), "C:/testroot/path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path("C:\\testroot\\path\\.\\filename"), "C:/testroot/path/filename"); #endif CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path + "/filename"), "res://filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path + "/path/filename"), "res://path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path + "/path/something/../filename"), "res://path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path + "/path/./filename"), "res://path/filename"); #ifdef WINDOWS_ENABLED CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path_win + "\\filename"), "res://filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path_win + "\\path\\filename"), "res://path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path_win + "\\path\\something\\..\\filename"), "res://path/filename"); CHECK_EQ(ProjectSettings::get_singleton()->localize_path(root_path_win + "\\path\\.\\filename"), "res://path/filename"); #endif TestProjectSettingsInternalsAccessor::resource_path() = old_resource_path; } } // namespace TestProjectSettings
ast_based
<|fim_prefix|>ating [%d] x [%d] x [%d] = [%d] float space for w->w1\n",__func__,p->n_layers, p->hidden_dim, p->dim, p->n_layers * p->hidden_dim * p->dim); w->w2.resize(p->n_layers * p->hidden_dim * p->dim); LOG_INF("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->w2\n",__func__,p->n_layers, p->dim, p->hidden_dim, p->n_layers * p->hidden_dim * p->dim); w->w3.resize(p->n_layers * p->hidden_dim * p->dim); LOG_INF("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->w3\n",__func__,p->n_layers, p->hidden_dim, p->dim, p->n_layers * p->hidden_dim * p->dim); w->rms_final_weight.resize(p->dim); LOG_INF("%s: Allocating [%d] float space for w->rms_final_weight\n",__func__,p->dim); if (shared_weights) { w->wcls = {}; } else { w->wcls.resize(p->vocab_size * p->dim); LOG_INF("%s: Allocating [%d] x [%d] = [%d] float space for w->wcls\n",__func__,p->vocab_size , p->dim, p->vocab_size * p->dim); } } catch (std::length_error &) { die("Invalid configuration. Failed to allocate memory for weights"); } } static int checkpoint_init_weights(TransformerWeights * w, const Config * p, FILE * f, bool shared_weights) { if (fread(w->token_embedding_table.data(), sizeof(float), w->token_embedding_table.size(), f) != w->token_embedding_table.size()) return 1; if (fread(w->rms_att_weight.data(), sizeof(float), w->rms_att_weight.size(), f) != w->rms_att_weight.size()) return 1; if (fread(w->wq.data(), sizeof(float), w->wq.size(), f) != w->wq.size()) return 1; if (fread(w->wk.data(), sizeof(float), w->wk.size(), f) != w->wk.size()) return 1; if (fread(w->wv.data(), sizeof(float), w->wv.size(), f) != w->wv.size()) return 1; if (fread(w->wo.data(), sizeof(float), w->wo.size(), f) != w->wo.size()) return 1; if (fread(w->rms_ffn_weight.data(), sizeof(float), w->rms_ffn_weight.size(), f) != w->rms_ffn_weight.size()) return 1; if (fread(<|fim_suffix|>, sizeof(float), w->w1.size(), f) != w->w1.size()) return 1; if (fread(w->w2.data(), sizeof(float), w->w2.size(), f) != w->w2.size()) return 1; if (fread(w->w3.data(), sizeof(float), w->w3.size(), f) != w->w3.size()) return 1; if (fread(w->rms_final_weight.data(), sizeof(float), w->rms_final_weight.size(), f) != w->rms_final_weight.size()) return 1; // Skip freq_cis_real & freq_cis_imag int head_size = p->dim / p->n_heads; fseek(f, p->seq_len * head_size * sizeof(float), SEEK_CUR); if (!shared_weights && fread(w->wcls.data(), sizeof(float), w->wcls.size(), f) != w->wcls.size()) return 1; // Check we didn't forget to read anything auto curr = ftell(f); fseek(f, 0, SEEK_END); auto end = ftell(f); if (curr != end) { LOG_ERR("%s: Error: failed to read the checkpoint file to the end (curr = %ld, end = %ld)\n", __func__, curr, end); return 1; } return 0; } static void print_sample_weights(TransformerWeights *w){ LOG_INF("----- Quick print of first of the weight vales of all the variables\n"); LOG_INF("%f\n", w->token_embedding_table[0]); LOG_INF("%f\n", w->rms_att_weight[0]); LOG_INF("%f\n", w->rms_ffn_weight[0]); LOG_INF("%f\n", w->wq[0]); LOG_INF("%f\n", w->wk[0]); LOG_INF("%f\n", w->wv[0]); LOG_INF("%f\n", w->wo[0]); LOG_INF("%f\n", w->w1[0]); LOG_INF("%f\n", w->w2[0]); LOG_INF("%f\n", w->w3[0]); LOG_INF("%f\n", w->rms_att_weight[0]); if (!w->wcls.empty()) LOG_INF("%f\n", w->wcls[0]); } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////// ggml structs and functions required to load models, configs and save the model. struct my_llama_vocab { using id = int32_t; using token = std::string; using ttype = llama_token_type; struct token_data { token text; float score; ttype type; }; std::unordered<|fim_middle|>w->w1.data()
ating [%d] x [%d] x [%d] = [%d] float space for w->w1\n",__func__,p->n_layers, p->hidden_dim, p->dim, p->n_layers * p->hidden_dim * p->dim); w->w2.resize(p->n_layers * p->hidden_dim * p->dim); LOG_INF("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->w2\n",__func__,p->n_layers, p->dim, p->hidden_dim, p->n_layers * p->hidden_dim * p->dim); w->w3.resize(p->n_layers * p->hidden_dim * p->dim); LOG_INF("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->w3\n",__func__,p->n_layers, p->hidden_dim, p->dim, p->n_layers * p->hidden_dim * p->dim); w->rms_final_weight.resize(p->dim); LOG_INF("%s: Allocating [%d] float space for w->rms_final_weight\n",__func__,p->dim); if (shared_weights) { w->wcls = {}; } else { w->wcls.resize(p->vocab_size * p->dim); LOG_INF("%s: Allocating [%d] x [%d] = [%d] float space for w->wcls\n",__func__,p->vocab_size , p->dim, p->vocab_size * p->dim); } } catch (std::length_error &) { die("Invalid configuration. Failed to allocate memory for weights"); } } static int checkpoint_init_weights(TransformerWeights * w, const Config * p, FILE * f, bool shared_weights) { if (fread(w->token_embedding_table.data(), sizeof(float), w->token_embedding_table.size(), f) != w->token_embedding_table.size()) return 1; if (fread(w->rms_att_weight.data(), sizeof(float), w->rms_att_weight.size(), f) != w->rms_att_weight.size()) return 1; if (fread(w->wq.data(), sizeof(float), w->wq.size(), f) != w->wq.size()) return 1; if (fread(w->wk.data(), sizeof(float), w->wk.size(), f) != w->wk.size()) return 1; if (fread(w->wv.data(), sizeof(float), w->wv.size(), f) != w->wv.size()) return 1; if (fread(w->wo.data(), sizeof(float), w->wo.size(), f) != w->wo.size()) return 1; if (fread(w->rms_ffn_weight.data(), sizeof(float), w->rms_ffn_weight.size(), f) != w->rms_ffn_weight.size()) return 1; if (fread(
w->w1.data()
, sizeof(float), w->w1.size(), f) != w->w1.size()) return 1; if (fread(w->w2.data(), sizeof(float), w->w2.size(), f) != w->w2.size()) return 1; if (fread(w->w3.data(), sizeof(float), w->w3.size(), f) != w->w3.size()) return 1; if (fread(w->rms_final_weight.data(), sizeof(float), w->rms_final_weight.size(), f) != w->rms_final_weight.size()) return 1; // Skip freq_cis_real & freq_cis_imag int head_size = p->dim / p->n_heads; fseek(f, p->seq_len * head_size * sizeof(float), SEEK_CUR); if (!shared_weights && fread(w->wcls.data(), sizeof(float), w->wcls.size(), f) != w->wcls.size()) return 1; // Check we didn't forget to read anything auto curr = ftell(f); fseek(f, 0, SEEK_END); auto end = ftell(f); if (curr != end) { LOG_ERR("%s: Error: failed to read the checkpoint file to the end (curr = %ld, end = %ld)\n", __func__, curr, end); return 1; } return 0; } static void print_sample_weights(TransformerWeights *w){ LOG_INF("----- Quick print of first of the weight vales of all the variables\n"); LOG_INF("%f\n", w->token_embedding_table[0]); LOG_INF("%f\n", w->rms_att_weight[0]); LOG_INF("%f\n", w->rms_ffn_weight[0]); LOG_INF("%f\n", w->wq[0]); LOG_INF("%f\n", w->wk[0]); LOG_INF("%f\n", w->wv[0]); LOG_INF("%f\n", w->wo[0]); LOG_INF("%f\n", w->w1[0]); LOG_INF("%f\n", w->w2[0]); LOG_INF("%f\n", w->w3[0]); LOG_INF("%f\n", w->rms_att_weight[0]); if (!w->wcls.empty()) LOG_INF("%f\n", w->wcls[0]); } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////// ggml structs and functions required to load models, configs and save the model. struct my_llama_vocab { using id = int32_t; using token = std::string; using ttype = llama_token_type; struct token_data { token text; float score; ttype type; }; std::unordered
ast_based
<|fim_prefix|>// (C) Copyright 2017, Google Inc. // 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. #include <allheaders.h> #include <tesseract/baseapi.h> #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); <|fim_suffix|> 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(tess<|fim_middle|>api_.SetImage(src_pix_); api_.SetVariable("tessedit_make_boxes_from_boxes", "1"); api_.SetInputName(TestDataNameToPath(filename).c_str());
// (C) Copyright 2017, Google Inc. // 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. #include <allheaders.h> #include <tesseract/baseapi.h> #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(tess
ast_based
<|fim_prefix|>M_KV_ADAPTER_ALORA_INVOCATION_TOKENS); const int kid = gguf_find_key(ctx_gguf.get(), key.c_str()); if (kid >= 0) { if (gguf_get_kv_type(ctx_gguf.get(), kid) != GGUF_TYPE_ARRAY) { throw std::runtime_error("invalid gguf type for " + key); } const auto arr_type = gguf_get_arr_type(ctx_gguf.get(), kid); if (arr_type != GGUF_TYPE_UINT32) { throw std::runtime_error("invalid gguf element type for " + key); } const size_t seq_len = gguf_get_arr_n(ctx_gguf.get(), kid); const void * data = gguf_get_arr_data(ctx_gguf.get(), kid); adapter.alora_invocation_tokens.resize(seq_len); std::copy( (const llama_token *)data, (const llama_token *)data + seq_len, adapter.alora_invocation_tokens.begin()); } } int n_tensors = gguf_get_n_tensors(ctx_gguf.get()); // contexts 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()) { // add a new context ggml_init_params params = { /*.mem_size =*/ n_tensors*ggml_tensor_overhead(), /*.mem_buffer =*/ NULL, /*.no_alloc =*/ true, }; ggml_context * buft_ctx = ggml_init(params); if (!buft_ctx) { return nullptr; } ctx_map[buft] = buft_ctx; adapter.ctxs.emplace_back(buft_ctx); return buft_ctx; }; return it->second; }; // bundle lora_a and lora_b into pairs std::map<std::string, llama_adapter_lora_weight> ab_map; auto str_endswith = [](const std::string & str, const std::string & suffix) { return str.size() >= suffix.size() && str.compare(<|fim_suffix|>-suffix.size(), suffix.size(), suffix) == 0; }; for (ggml_tensor * cur = ggml_get_first_tensor(ctx.get()); cur; cur = ggml_get_next_tensor(ctx.get(), cur)) { std::string name(cur->name); if (str_endswith(name, ".lora_a")) { replace_all(name, ".lora_a", ""); if (ab_map.find(name) == ab_map.end()) { ab_map[name] = llama_adapter_lora_weight(cur, nullptr); } else { ab_map[name].a = cur; } } else if (str_endswith(name, ".lora_b")) { replace_all(name, ".lora_b", ""); if (ab_map.find(name) == ab_map.end()) { ab_map[name] = llama_adapter_lora_weight(nullptr, cur); } else { ab_map[name].b = cur; } } else if (str_endswith(name, "_norm.weight")) { // TODO: add support for norm vector // for now, we don't really care because most adapters still work fine without it continue; } else { throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix"); } } // get extra buffer types of the CPU // TODO: a more general solution for non-CPU extra buft should be imlpemented in the future // ref: https://github.com/ggml-org/llama.cpp/pull/12593#pullrequestreview-2718659948 std::vector<ggml_backend_buffer_type_t> buft_extra; { 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__)); } auto * cpu_reg = ggml_backend_dev_backend_reg(cpu_dev); auto ggml_backend_dev_get_extra_bufts_fn = (ggml_backend_dev_get_extra_bufts_t) ggml_backend_reg_get_proc_address(cpu_reg, "ggml_backend_dev_get_extra_bufts"); if (ggml_backend_dev_get_extra_bufts_fn) { ggml_backend_buffer_type_t * extra_bufts = ggml_backend_dev_ge<|fim_middle|>str.size()
M_KV_ADAPTER_ALORA_INVOCATION_TOKENS); const int kid = gguf_find_key(ctx_gguf.get(), key.c_str()); if (kid >= 0) { if (gguf_get_kv_type(ctx_gguf.get(), kid) != GGUF_TYPE_ARRAY) { throw std::runtime_error("invalid gguf type for " + key); } const auto arr_type = gguf_get_arr_type(ctx_gguf.get(), kid); if (arr_type != GGUF_TYPE_UINT32) { throw std::runtime_error("invalid gguf element type for " + key); } const size_t seq_len = gguf_get_arr_n(ctx_gguf.get(), kid); const void * data = gguf_get_arr_data(ctx_gguf.get(), kid); adapter.alora_invocation_tokens.resize(seq_len); std::copy( (const llama_token *)data, (const llama_token *)data + seq_len, adapter.alora_invocation_tokens.begin()); } } int n_tensors = gguf_get_n_tensors(ctx_gguf.get()); // contexts 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()) { // add a new context ggml_init_params params = { /*.mem_size =*/ n_tensors*ggml_tensor_overhead(), /*.mem_buffer =*/ NULL, /*.no_alloc =*/ true, }; ggml_context * buft_ctx = ggml_init(params); if (!buft_ctx) { return nullptr; } ctx_map[buft] = buft_ctx; adapter.ctxs.emplace_back(buft_ctx); return buft_ctx; }; return it->second; }; // bundle lora_a and lora_b into pairs std::map<std::string, llama_adapter_lora_weight> ab_map; auto str_endswith = [](const std::string & str, const std::string & suffix) { return str.size() >= suffix.size() && str.compare(
str.size()
-suffix.size(), suffix.size(), suffix) == 0; }; for (ggml_tensor * cur = ggml_get_first_tensor(ctx.get()); cur; cur = ggml_get_next_tensor(ctx.get(), cur)) { std::string name(cur->name); if (str_endswith(name, ".lora_a")) { replace_all(name, ".lora_a", ""); if (ab_map.find(name) == ab_map.end()) { ab_map[name] = llama_adapter_lora_weight(cur, nullptr); } else { ab_map[name].a = cur; } } else if (str_endswith(name, ".lora_b")) { replace_all(name, ".lora_b", ""); if (ab_map.find(name) == ab_map.end()) { ab_map[name] = llama_adapter_lora_weight(nullptr, cur); } else { ab_map[name].b = cur; } } else if (str_endswith(name, "_norm.weight")) { // TODO: add support for norm vector // for now, we don't really care because most adapters still work fine without it continue; } else { throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix"); } } // get extra buffer types of the CPU // TODO: a more general solution for non-CPU extra buft should be imlpemented in the future // ref: https://github.com/ggml-org/llama.cpp/pull/12593#pullrequestreview-2718659948 std::vector<ggml_backend_buffer_type_t> buft_extra; { 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__)); } auto * cpu_reg = ggml_backend_dev_backend_reg(cpu_dev); auto ggml_backend_dev_get_extra_bufts_fn = (ggml_backend_dev_get_extra_bufts_t) ggml_backend_reg_get_proc_address(cpu_reg, "ggml_backend_dev_get_extra_bufts"); if (ggml_backend_dev_get_extra_bufts_fn) { ggml_backend_buffer_type_t * extra_bufts = ggml_backend_dev_ge
ast_based
<|fim_prefix|>num_graph_nodes_ TF_GUARDED_BY(mu_) = 0; }; ClientSession::ClientSession(const Scope& scope, const string& target) : ClientSession(scope, Impl::MakeDefaultSessionOptions(target)) {} ClientSession::ClientSession(const Scope& scope) : ClientSession(scope, "") {} ClientSession::ClientSession(const Scope& scope, const SessionOptions& session_options) { Session* new_session; absl::Status status = NewSession(session_options, &new_session); TF_CHECK_OK(status) << status; impl_.reset(new Impl(new_session, scope.graph_as_shared_ptr())); CHECK_NOTNULL(impl()->session_.get()); } // Define destructor here so we can forward declare `Impl` in client_session.h. // If we define a dtor in the header file or use the default dtor, // unique_ptr<Impl> needs the complete type. ClientSession::~ClientSession() {} SessionOptions ClientSession::Impl::MakeDefaultSessionOptions( const string& target) { SessionOptions options; options.env = Env::Default(); options.target = target; return options; } absl::Status ClientSession::Run(const std::vector<Output>& fetch_outputs, std::vector<Tensor>* outputs) const { return Run(FeedType{}, fetch_outputs, {}, outputs); } absl::Status ClientSession::Run(const FeedType& inputs, const std::vector<Output>& fetch_outputs, std::vector<Tensor>* outputs) const { return Run(inputs, fetch_outputs, {}, outputs); } absl::Status ClientSession::Run(const FeedType& inputs, const std::vector<Output>& fetch_outputs, const std::vector<Operation>& run_outputs, std::vector<Tensor>* outputs) const { return Run(RunOptions(), inputs, fetch_outputs, run_outputs, outputs, nullptr); } absl::Status ClientSession::Impl::MaybeExtendGraph() const { mutex_lock l(mu_); int num_nodes = graph_->num_node_ids(); <|fim_suffix|> } absl::Status ClientSession::Run(const RunOptions& run_options, const FeedType& inputs, const std::vector<Output>& fetch_outputs, const std::vector<Operation>& run_outputs, std::vector<Tensor>* outputs, RunMetadata* run_metadata) const { std::vector<std::pair<string, Tensor>> feeds; feeds.reserve(inputs.size()); for (auto const& feed : inputs) { TF_RETURN_IF_ERROR(feed.second.status); feeds.emplace_back(std::piecewise_construct, std::forward_as_tuple(feed.first.name()), std::forward_as_tuple(feed.second.tensor)); } std::vector<string> output_tensor_names; output_tensor_names.reserve(fetch_outputs.size()); for (auto const& output : fetch_outputs) { output_tensor_names.push_back(output.name()); } std::vector<string> target_node_names; target_node_names.reserve(run_outputs.size()); for (auto const& output : run_outputs) { target_node_names.push_back(output.node()->name()); } TF_RETURN_IF_ERROR(impl()->MaybeExtendGraph()); return impl()->session_->Run(run_options, feeds, output_tensor_names, target_node_names, outputs, run_metadata); } absl::Status ClientSession::Run( const RunOptions& run_options, const FeedType& inputs, const std::vector<Output>& fetch_outputs, const std::vector<Operation>& run_outputs, std::vector<Tensor>* outputs, RunMetadata* run_metadata, const thread::ThreadPoolOptions& threadpool_options) const { std::vector<std::pair<string, Tensor>> feeds; for (auto const& feed : inputs) { TF_RETURN_IF_ERROR(feed.second.status); feeds.emplace_back(feed.first.name(), feed.second.tensor); } std::vector<string> output_tensor_names; output_tensor_names.reserve(fetch_outputs.size()); for (auto const& output : fetch_outputs) { output_tensor_n<|fim_middle|>if (num_nodes > last_num_graph_nodes_) { GraphDef graph_def; graph_->ToGraphDefSubRange(&graph_def, last_num_graph_nodes_); last_num_graph_nodes_ = num_nodes; return session_->Extend(graph_def); } return absl::OkStatus();
num_graph_nodes_ TF_GUARDED_BY(mu_) = 0; }; ClientSession::ClientSession(const Scope& scope, const string& target) : ClientSession(scope, Impl::MakeDefaultSessionOptions(target)) {} ClientSession::ClientSession(const Scope& scope) : ClientSession(scope, "") {} ClientSession::ClientSession(const Scope& scope, const SessionOptions& session_options) { Session* new_session; absl::Status status = NewSession(session_options, &new_session); TF_CHECK_OK(status) << status; impl_.reset(new Impl(new_session, scope.graph_as_shared_ptr())); CHECK_NOTNULL(impl()->session_.get()); } // Define destructor here so we can forward declare `Impl` in client_session.h. // If we define a dtor in the header file or use the default dtor, // unique_ptr<Impl> needs the complete type. ClientSession::~ClientSession() {} SessionOptions ClientSession::Impl::MakeDefaultSessionOptions( const string& target) { SessionOptions options; options.env = Env::Default(); options.target = target; return options; } absl::Status ClientSession::Run(const std::vector<Output>& fetch_outputs, std::vector<Tensor>* outputs) const { return Run(FeedType{}, fetch_outputs, {}, outputs); } absl::Status ClientSession::Run(const FeedType& inputs, const std::vector<Output>& fetch_outputs, std::vector<Tensor>* outputs) const { return Run(inputs, fetch_outputs, {}, outputs); } absl::Status ClientSession::Run(const FeedType& inputs, const std::vector<Output>& fetch_outputs, const std::vector<Operation>& run_outputs, std::vector<Tensor>* outputs) const { return Run(RunOptions(), inputs, fetch_outputs, run_outputs, outputs, nullptr); } absl::Status ClientSession::Impl::MaybeExtendGraph() const { mutex_lock l(mu_); int num_nodes = graph_->num_node_ids();
if (num_nodes > last_num_graph_nodes_) { GraphDef graph_def; graph_->ToGraphDefSubRange(&graph_def, last_num_graph_nodes_); last_num_graph_nodes_ = num_nodes; return session_->Extend(graph_def); } return absl::OkStatus();
} absl::Status ClientSession::Run(const RunOptions& run_options, const FeedType& inputs, const std::vector<Output>& fetch_outputs, const std::vector<Operation>& run_outputs, std::vector<Tensor>* outputs, RunMetadata* run_metadata) const { std::vector<std::pair<string, Tensor>> feeds; feeds.reserve(inputs.size()); for (auto const& feed : inputs) { TF_RETURN_IF_ERROR(feed.second.status); feeds.emplace_back(std::piecewise_construct, std::forward_as_tuple(feed.first.name()), std::forward_as_tuple(feed.second.tensor)); } std::vector<string> output_tensor_names; output_tensor_names.reserve(fetch_outputs.size()); for (auto const& output : fetch_outputs) { output_tensor_names.push_back(output.name()); } std::vector<string> target_node_names; target_node_names.reserve(run_outputs.size()); for (auto const& output : run_outputs) { target_node_names.push_back(output.node()->name()); } TF_RETURN_IF_ERROR(impl()->MaybeExtendGraph()); return impl()->session_->Run(run_options, feeds, output_tensor_names, target_node_names, outputs, run_metadata); } absl::Status ClientSession::Run( const RunOptions& run_options, const FeedType& inputs, const std::vector<Output>& fetch_outputs, const std::vector<Operation>& run_outputs, std::vector<Tensor>* outputs, RunMetadata* run_metadata, const thread::ThreadPoolOptions& threadpool_options) const { std::vector<std::pair<string, Tensor>> feeds; for (auto const& feed : inputs) { TF_RETURN_IF_ERROR(feed.second.status); feeds.emplace_back(feed.first.name(), feed.second.tensor); } std::vector<string> output_tensor_names; output_tensor_names.reserve(fetch_outputs.size()); for (auto const& output : fetch_outputs) { output_tensor_n
ast_based
<|fim_prefix|> "\n", argv[0] ); } static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point3f>& corners) { corners.resize(0); for( int i = 0; i < boardSize.height; i++ ) for( int j = 0; j < boardSize.width; j++ ) corners.push_back(Point3f(float(j*squareSize), float(i*squareSize), 0)); } static bool run3Calibration(vector<vector<Point2f> > imagePoints1, vector<vector<Point2f> > imagePoints2, vector<vector<Point2f> > imagePoints3, Size imageSize, Size boardSize, float squareSize, float aspectRatio, int flags, Mat& cameraMatrix1, Mat& distCoeffs1, Mat& cameraMatrix2, Mat& distCoeffs2, Mat& cameraMatrix3, Mat& distCoeffs3, Mat& R12, Mat& T12, Mat& R13, Mat& T13) { int c, i; // step 1: calibrate each camera individually vector<vector<Point3f> > objpt(1); vector<vector<Point2f> > imgpt; calcChessboardCorners(boardSize, squareSize, objpt[0]); vector<Mat> rvecs, tvecs; for( c = 1; c <= 3; c++ ) { const vector<vector<Point2f> >& imgpt0 = c == 1 ? imagePoints1 : c == 2 ? imagePoints2 : imagePoints3; imgpt.clear(); int N = 0; for( i = 0; i < (int)imgpt0.size(); i++ ) if( !imgpt0[i].empty() ) { imgpt.push_back(imgpt0[i]); N += (int)imgpt0[i].size(); } if( imgpt.size() < 3 ) { printf("Error: not enough views for camera %d\n", c); return false; } objpt.resize(imgpt.size(),objpt[0]); Mat cameraMatrix = Mat::eye(3, 3, CV_64F); if( flags & CALIB_FIX_ASPECT_RATIO ) cameraMatrix.at<double>(0,0) = aspectRatio; Mat distCoeffs = <|fim_suffix|>; double err = calibrateCamera(objpt, imgpt, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags|CALIB_FIX_K3/*|CALIB_FIX_K4|CALIB_FIX_K5|CALIB_FIX_K6*/); bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs); if(!ok) { printf("Error: camera %d was not calibrated\n", c); return false; } printf("Camera %d calibration reprojection error = %g\n", c, sqrt(err/N)); if( c == 1 ) cameraMatrix1 = cameraMatrix, distCoeffs1 = distCoeffs; else if( c == 2 ) cameraMatrix2 = cameraMatrix, distCoeffs2 = distCoeffs; else cameraMatrix3 = cameraMatrix, distCoeffs3 = distCoeffs; } vector<vector<Point2f> > imgpt_right; // step 2: calibrate (1,2) and (3,2) pairs for( c = 2; c <= 3; c++ ) { const vector<vector<Point2f> >& imgpt0 = c == 2 ? imagePoints2 : imagePoints3; imgpt.clear(); imgpt_right.clear(); int N = 0; for( i = 0; i < (int)std::min(imagePoints1.size(), imgpt0.size()); i++ ) if( !imagePoints1.empty() && !imgpt0[i].empty() ) { imgpt.push_back(imagePoints1[i]); imgpt_right.push_back(imgpt0[i]); N += (int)imgpt0[i].size(); } if( imgpt.size() < 3 ) { printf("Error: not enough shared views for cameras 1 and %d\n", c); return false; } objpt.resize(imgpt.size(),objpt[0]); Mat cameraMatrix = c == 2 ? cameraMatrix2 : cameraMatrix3; Mat distCoeffs = c == 2 ? distCoeffs2 : distCoeffs3; Mat R, T, E, F; double err = stereoCalibrate(objpt, imgpt, imgpt_right, cameraMatrix1, distCoeffs1, cameraMatrix, distCoeffs, imageSize, R, T, E, F, CALIB_FIX_INTRINSIC, <|fim_middle|>Mat::zeros(5, 1, CV_64F)
"\n", argv[0] ); } static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point3f>& corners) { corners.resize(0); for( int i = 0; i < boardSize.height; i++ ) for( int j = 0; j < boardSize.width; j++ ) corners.push_back(Point3f(float(j*squareSize), float(i*squareSize), 0)); } static bool run3Calibration(vector<vector<Point2f> > imagePoints1, vector<vector<Point2f> > imagePoints2, vector<vector<Point2f> > imagePoints3, Size imageSize, Size boardSize, float squareSize, float aspectRatio, int flags, Mat& cameraMatrix1, Mat& distCoeffs1, Mat& cameraMatrix2, Mat& distCoeffs2, Mat& cameraMatrix3, Mat& distCoeffs3, Mat& R12, Mat& T12, Mat& R13, Mat& T13) { int c, i; // step 1: calibrate each camera individually vector<vector<Point3f> > objpt(1); vector<vector<Point2f> > imgpt; calcChessboardCorners(boardSize, squareSize, objpt[0]); vector<Mat> rvecs, tvecs; for( c = 1; c <= 3; c++ ) { const vector<vector<Point2f> >& imgpt0 = c == 1 ? imagePoints1 : c == 2 ? imagePoints2 : imagePoints3; imgpt.clear(); int N = 0; for( i = 0; i < (int)imgpt0.size(); i++ ) if( !imgpt0[i].empty() ) { imgpt.push_back(imgpt0[i]); N += (int)imgpt0[i].size(); } if( imgpt.size() < 3 ) { printf("Error: not enough views for camera %d\n", c); return false; } objpt.resize(imgpt.size(),objpt[0]); Mat cameraMatrix = Mat::eye(3, 3, CV_64F); if( flags & CALIB_FIX_ASPECT_RATIO ) cameraMatrix.at<double>(0,0) = aspectRatio; Mat distCoeffs =
Mat::zeros(5, 1, CV_64F)
; double err = calibrateCamera(objpt, imgpt, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags|CALIB_FIX_K3/*|CALIB_FIX_K4|CALIB_FIX_K5|CALIB_FIX_K6*/); bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs); if(!ok) { printf("Error: camera %d was not calibrated\n", c); return false; } printf("Camera %d calibration reprojection error = %g\n", c, sqrt(err/N)); if( c == 1 ) cameraMatrix1 = cameraMatrix, distCoeffs1 = distCoeffs; else if( c == 2 ) cameraMatrix2 = cameraMatrix, distCoeffs2 = distCoeffs; else cameraMatrix3 = cameraMatrix, distCoeffs3 = distCoeffs; } vector<vector<Point2f> > imgpt_right; // step 2: calibrate (1,2) and (3,2) pairs for( c = 2; c <= 3; c++ ) { const vector<vector<Point2f> >& imgpt0 = c == 2 ? imagePoints2 : imagePoints3; imgpt.clear(); imgpt_right.clear(); int N = 0; for( i = 0; i < (int)std::min(imagePoints1.size(), imgpt0.size()); i++ ) if( !imagePoints1.empty() && !imgpt0[i].empty() ) { imgpt.push_back(imagePoints1[i]); imgpt_right.push_back(imgpt0[i]); N += (int)imgpt0[i].size(); } if( imgpt.size() < 3 ) { printf("Error: not enough shared views for cameras 1 and %d\n", c); return false; } objpt.resize(imgpt.size(),objpt[0]); Mat cameraMatrix = c == 2 ? cameraMatrix2 : cameraMatrix3; Mat distCoeffs = c == 2 ? distCoeffs2 : distCoeffs3; Mat R, T, E, F; double err = stereoCalibrate(objpt, imgpt, imgpt_right, cameraMatrix1, distCoeffs1, cameraMatrix, distCoeffs, imageSize, R, T, E, F, CALIB_FIX_INTRINSIC,
ast_based
<|fim_prefix|> set_only_non_debug_params, nullptr); } // In-memory version reads the traineddata file directly from the given // data[data_size] array. Also implements the version with a datapath in data, // flagged by data_size = 0. int TessBaseAPI::Init(const char *data, int data_size, const char *language, OcrEngineMode oem, char **configs, int configs_size, const std::vector<std::string> *vars_vec, const std::vector<std::string> *vars_values, bool set_only_non_debug_params, FileReader reader) { if (language == nullptr) { language = ""; } if (data == nullptr) { data = ""; } std::string datapath = data_size == 0 ? data : language; // If the datapath, OcrEngineMode or the language have changed - start again. // Note that the language_ field stores the last requested language that was // initialized successfully, while tesseract_->lang stores the language // actually used. They differ only if the requested language was nullptr, in // which case tesseract_->lang is set to the Tesseract default ("eng"). if (tesseract_ != nullptr && (datapath_.empty() || language_.empty() || datapath_ != datapath || last_oem_requested_ != oem || (language_ != language && tesseract_->lang != language))) { delete tesseract_; tesseract_ = nullptr; } bool reset_classifier = true; if (tesseract_ == nullptr) { reset_classifier = false; tesseract_ = new Tesseract; if (reader != nullptr) { reader_ = reader; } TessdataManager mgr(reader_); if (data_size != 0) { mgr.LoadMemBuffer(language, data, data_size); } if (tesseract_->init_tesseract(datapath, output_file_, language, oem, configs, configs_size, vars_vec, vars_values, set_only_non_debug_params, &mgr) != 0) { return -1;<|fim_suffix|> // Update datapath and language requested for the last valid initialization. datapath_ = std::move(datapath); if (datapath_.empty() && !tesseract_->datadir.empty()) { datapath_ = tesseract_->datadir; } language_ = language; last_oem_requested_ = oem; #ifndef DISABLED_LEGACY_ENGINE // For same language and datapath, just reset the adaptive classifier. if (reset_classifier) { tesseract_->ResetAdaptiveClassifier(); } #endif // ndef DISABLED_LEGACY_ENGINE return 0; } /** * Returns the languages string used in the last valid initialization. * If the last initialization specified "deu+hin" then that will be * returned. If hin loaded eng automatically as well, then that will * not be included in this list. To find the languages actually * loaded use GetLoadedLanguagesAsVector. * The returned string should NOT be deleted. */ const char *TessBaseAPI::GetInitLanguagesAsString() const { return language_.c_str(); } /** * Returns the loaded languages in the vector of std::string. * Includes all languages loaded by the last Init, including those loaded * as dependencies of other loaded languages. */ void TessBaseAPI::GetLoadedLanguagesAsVector(std::vector<std::string> *langs) const { langs->clear(); if (tesseract_ != nullptr) { langs->push_back(tesseract_->lang); int num_subs = tesseract_->num_sub_langs(); for (int i = 0; i < num_subs; ++i) { langs->push_back(tesseract_->get_sub_lang(i)->lang); } } } /** * Returns the available languages in the sorted vector of std::string. */ void TessBaseAPI::GetAvailableLanguagesAsVector(std::vector<std::string> *langs) const { langs->clear(); if (tesseract_ != nullptr) { addAvailableLanguages(tesseract_->datadir, langs); std::sort(langs->begin(), langs->end()); } } /** * Init only for page layout analysis. Use only for calls to SetImage and * AnalysePage. Calls that attempt recognition will generate an error. */<|fim_middle|> } }
set_only_non_debug_params, nullptr); } // In-memory version reads the traineddata file directly from the given // data[data_size] array. Also implements the version with a datapath in data, // flagged by data_size = 0. int TessBaseAPI::Init(const char *data, int data_size, const char *language, OcrEngineMode oem, char **configs, int configs_size, const std::vector<std::string> *vars_vec, const std::vector<std::string> *vars_values, bool set_only_non_debug_params, FileReader reader) { if (language == nullptr) { language = ""; } if (data == nullptr) { data = ""; } std::string datapath = data_size == 0 ? data : language; // If the datapath, OcrEngineMode or the language have changed - start again. // Note that the language_ field stores the last requested language that was // initialized successfully, while tesseract_->lang stores the language // actually used. They differ only if the requested language was nullptr, in // which case tesseract_->lang is set to the Tesseract default ("eng"). if (tesseract_ != nullptr && (datapath_.empty() || language_.empty() || datapath_ != datapath || last_oem_requested_ != oem || (language_ != language && tesseract_->lang != language))) { delete tesseract_; tesseract_ = nullptr; } bool reset_classifier = true; if (tesseract_ == nullptr) { reset_classifier = false; tesseract_ = new Tesseract; if (reader != nullptr) { reader_ = reader; } TessdataManager mgr(reader_); if (data_size != 0) { mgr.LoadMemBuffer(language, data, data_size); } if (tesseract_->init_tesseract(datapath, output_file_, language, oem, configs, configs_size, vars_vec, vars_values, set_only_non_debug_params, &mgr) != 0) { return -1;
} }
// Update datapath and language requested for the last valid initialization. datapath_ = std::move(datapath); if (datapath_.empty() && !tesseract_->datadir.empty()) { datapath_ = tesseract_->datadir; } language_ = language; last_oem_requested_ = oem; #ifndef DISABLED_LEGACY_ENGINE // For same language and datapath, just reset the adaptive classifier. if (reset_classifier) { tesseract_->ResetAdaptiveClassifier(); } #endif // ndef DISABLED_LEGACY_ENGINE return 0; } /** * Returns the languages string used in the last valid initialization. * If the last initialization specified "deu+hin" then that will be * returned. If hin loaded eng automatically as well, then that will * not be included in this list. To find the languages actually * loaded use GetLoadedLanguagesAsVector. * The returned string should NOT be deleted. */ const char *TessBaseAPI::GetInitLanguagesAsString() const { return language_.c_str(); } /** * Returns the loaded languages in the vector of std::string. * Includes all languages loaded by the last Init, including those loaded * as dependencies of other loaded languages. */ void TessBaseAPI::GetLoadedLanguagesAsVector(std::vector<std::string> *langs) const { langs->clear(); if (tesseract_ != nullptr) { langs->push_back(tesseract_->lang); int num_subs = tesseract_->num_sub_langs(); for (int i = 0; i < num_subs; ++i) { langs->push_back(tesseract_->get_sub_lang(i)->lang); } } } /** * Returns the available languages in the sorted vector of std::string. */ void TessBaseAPI::GetAvailableLanguagesAsVector(std::vector<std::string> *langs) const { langs->clear(); if (tesseract_ != nullptr) { addAvailableLanguages(tesseract_->datadir, langs); std::sort(langs->begin(), langs->end()); } } /** * Init only for page layout analysis. Use only for calls to SetImage and * AnalysePage. Calls that attempt recognition will generate an error. */
random